From 452095f3d2482ebc76321d2bf831e7edc9a0f5f7 Mon Sep 17 00:00:00 2001 From: georgepisaltu Date: Fri, 15 Dec 2023 14:38:40 +0200 Subject: [PATCH] Revert "Bring `TransactionExtension` branch up-to-date (#2717)" This reverts commit 443d0e9d68302c79591a9b945244cdb35d357023. --- .cargo/config.toml | 38 +- .config/lychee.toml | 56 +- .config/taplo.toml | 33 - .config/zepter.yaml | 5 +- .github/pr-custom-review.yml | 63 + .github/review-bot.yml | 59 +- .github/runtime_specs/rococo.json | 17 - .github/runtime_specs/westend.json | 17 - .github/scripts/check-runtime.py | 124 -- .github/scripts/common/lib.sh | 49 +- .../build-and-attach-release-runtimes.yml | 14 +- .github/workflows/check-licenses.yml | 2 +- .github/workflows/check-prdoc.yml | 36 +- .github/workflows/check-publish.yml | 2 +- .github/workflows/check-runtimes.yml | 94 - .github/workflows/claim-crates.yml | 2 +- .github/workflows/fmt-check.yml | 2 +- .github/workflows/gitspiegel-trigger.yml | 11 - .github/workflows/merge-queue.yml | 2 +- .github/workflows/notif-burnin-label.yml | 24 - .github/workflows/pr-custom-review.yml | 46 + .../workflows/release-10_rc-automation.yml | 113 - .../workflows/release-50_publish-docker.yml | 5 +- .../workflows/release-99_notif-published.yml | 61 - .github/workflows/review-bot.yml | 2 +- .gitignore | 1 - .gitlab-ci.yml | 44 +- .gitlab/pipeline/build.yml | 2 +- .gitlab/pipeline/check.yml | 21 +- .gitlab/pipeline/short-benchmarks.yml | 30 + .gitlab/pipeline/test.yml | 12 +- .gitlab/pipeline/zombienet.yml | 2 +- .gitlab/pipeline/zombienet/polkadot.yml | 24 - .gitlab/rust-features.sh | 87 - .gitlab/spellcheck.toml | 18 +- .prdoc.toml | 7 - Cargo.lock | 1349 ++++++------ Cargo.toml | 75 +- README.md | 6 +- bridges/bin/runtime-common/Cargo.toml | 9 +- .../src/messages_xcm_extension.rs | 131 +- bridges/bin/runtime-common/src/mock.rs | 4 +- bridges/modules/grandpa/Cargo.toml | 5 +- bridges/modules/grandpa/src/call_ext.rs | 29 +- bridges/modules/grandpa/src/mock.rs | 4 +- bridges/modules/messages/Cargo.toml | 5 +- bridges/modules/messages/src/weights_ext.rs | 3 +- bridges/modules/parachains/Cargo.toml | 5 +- bridges/modules/parachains/src/mock.rs | 8 +- bridges/modules/relayers/Cargo.toml | 5 +- .../modules/xcm-bridge-hub-router/Cargo.toml | 5 +- .../xcm-bridge-hub-router/src/benchmarking.rs | 12 +- .../modules/xcm-bridge-hub-router/src/lib.rs | 96 +- .../modules/xcm-bridge-hub-router/src/mock.rs | 20 +- bridges/modules/xcm-bridge-hub/Cargo.toml | 77 - .../modules/xcm-bridge-hub/src/exporter.rs | 209 -- bridges/modules/xcm-bridge-hub/src/lib.rs | 118 -- bridges/modules/xcm-bridge-hub/src/mock.rs | 334 --- .../chain-asset-hub-rococo/Cargo.toml | 5 +- .../chain-asset-hub-westend/Cargo.toml | 5 +- .../chain-bridge-hub-cumulus/Cargo.toml | 5 +- .../chain-bridge-hub-kusama/Cargo.toml | 5 +- .../chain-bridge-hub-polkadot/Cargo.toml | 5 +- .../chain-bridge-hub-rococo/Cargo.toml | 5 +- .../chain-bridge-hub-rococo/src/lib.rs | 2 - .../chain-bridge-hub-westend/Cargo.toml | 5 +- bridges/primitives/chain-kusama/Cargo.toml | 5 +- bridges/primitives/chain-kusama/src/lib.rs | 4 +- .../chain-polkadot-bulletin/Cargo.toml | 5 +- .../chain-polkadot-bulletin/src/lib.rs | 8 +- bridges/primitives/chain-polkadot/Cargo.toml | 5 +- bridges/primitives/chain-polkadot/src/lib.rs | 4 +- bridges/primitives/chain-rococo/Cargo.toml | 5 +- bridges/primitives/chain-rococo/src/lib.rs | 4 +- bridges/primitives/chain-westend/Cargo.toml | 5 +- bridges/primitives/chain-westend/src/lib.rs | 4 +- bridges/primitives/header-chain/Cargo.toml | 5 +- .../header-chain/src/justification/mod.rs | 4 +- bridges/primitives/header-chain/src/lib.rs | 93 +- bridges/primitives/messages/Cargo.toml | 7 +- bridges/primitives/parachains/Cargo.toml | 5 +- bridges/primitives/polkadot-core/Cargo.toml | 5 +- bridges/primitives/polkadot-core/src/lib.rs | 18 +- bridges/primitives/relayers/Cargo.toml | 7 +- bridges/primitives/runtime/Cargo.toml | 5 +- bridges/primitives/test-utils/Cargo.toml | 11 +- .../xcm-bridge-hub-router/Cargo.toml | 9 +- bridges/primitives/xcm-bridge-hub/Cargo.toml | 19 - bridges/primitives/xcm-bridge-hub/src/lib.rs | 24 - .../native-assets-balance-increased.js | 20 - bridges/zombienet/run-tests.sh | 22 +- ...set-transfer-works-rococo-to-westend.zndsl | 18 +- ...set-transfer-works-westend-to-rococo.zndsl | 16 +- cumulus/README.md | 21 +- cumulus/client/cli/Cargo.toml | 6 +- cumulus/client/cli/src/lib.rs | 85 +- cumulus/client/collator/Cargo.toml | 5 +- cumulus/client/consensus/aura/Cargo.toml | 5 +- cumulus/client/consensus/common/Cargo.toml | 5 +- cumulus/client/consensus/proposer/Cargo.toml | 3 - .../client/consensus/relay-chain/Cargo.toml | 3 - cumulus/client/network/Cargo.toml | 5 +- cumulus/client/pov-recovery/Cargo.toml | 5 +- cumulus/client/pov-recovery/src/lib.rs | 17 +- .../Cargo.toml | 5 +- .../src/lib.rs | 3 +- .../client/relay-chain-interface/Cargo.toml | 3 - .../relay-chain-minimal-node/Cargo.toml | 5 +- .../src/blockchain_rpc_client.rs | 14 +- .../src/collator_overseer.rs | 15 +- .../relay-chain-minimal-node/src/lib.rs | 14 +- .../relay-chain-minimal-node/src/network.rs | 25 +- .../relay-chain-rpc-interface/Cargo.toml | 6 +- .../src/rpc_client.rs | 15 +- cumulus/client/service/Cargo.toml | 5 +- cumulus/client/service/src/lib.rs | 2 - cumulus/pallets/aura-ext/Cargo.toml | 21 +- cumulus/pallets/collator-selection/Cargo.toml | 23 +- .../pallets/collator-selection/src/mock.rs | 3 +- cumulus/pallets/dmp-queue/Cargo.toml | 7 +- cumulus/pallets/parachain-system/Cargo.toml | 36 +- .../parachain-system/proc-macro/Cargo.toml | 9 +- .../src/validate_block/mod.rs | 4 - .../src/validate_block/trie_recorder.rs | 286 --- .../pallets/session-benchmarking/Cargo.toml | 17 +- cumulus/pallets/solo-to-para/Cargo.toml | 19 +- cumulus/pallets/xcm/Cargo.toml | 17 +- cumulus/pallets/xcmp-queue/Cargo.toml | 21 +- cumulus/pallets/xcmp-queue/src/lib.rs | 38 +- cumulus/pallets/xcmp-queue/src/migration.rs | 381 +--- cumulus/pallets/xcmp-queue/src/mock.rs | 8 +- cumulus/pallets/xcmp-queue/src/tests.rs | 55 +- cumulus/parachain-template/node/Cargo.toml | 10 +- cumulus/parachain-template/node/src/cli.rs | 7 +- .../parachain-template/node/src/command.rs | 4 +- cumulus/parachain-template/node/src/rpc.rs | 2 + .../pallets/template/Cargo.toml | 19 +- .../pallets/template/src/mock.rs | 3 +- cumulus/parachain-template/runtime/Cargo.toml | 75 +- cumulus/parachain-template/runtime/src/lib.rs | 37 +- .../runtime/src/xcm_config.rs | 13 +- .../chain-specs/asset-hub-kusama.json | 5 +- .../chain-specs/asset-hub-polkadot.json | 5 +- .../chain-specs/asset-hub-westend.json | 5 +- .../chain-specs/bridge-hub-kusama.json | 5 +- .../chain-specs/bridge-hub-polkadot.json | 5 +- .../chain-specs/bridge-hub-westend.json | 5 +- .../chain-specs/collectives-polkadot.json | 5 +- .../chain-specs/collectives-westend.json | 5 +- cumulus/parachains/common/Cargo.toml | 23 +- cumulus/parachains/common/src/impls.rs | 3 +- cumulus/parachains/common/src/polkadot.rs | 2 - cumulus/parachains/common/src/westend.rs | 31 +- cumulus/parachains/common/src/xcm_config.rs | 57 +- .../assets/asset-hub-kusama/0_xcm/0_init.yml | 145 ++ .../assets/asset-hub-kusama/0_xcm/1_dmp.yml | 263 +++ .../assets/asset-hub-kusama/0_xcm/2_ump.yml | 191 ++ .../0_xcm/3_force_hrmp-open-channels.yml | 122 ++ .../assets/asset-hub-kusama/0_xcm/4_hrmp.yml | 388 ++++ .../e2e/assets/asset-hub-kusama/config.toml | 71 + .../asset-hub-polkadot/0_xcm/0_init.yml | 145 ++ .../assets/asset-hub-polkadot/0_xcm/1_dmp.yml | 263 +++ .../assets/asset-hub-polkadot/0_xcm/2_ump.yml | 194 ++ .../0_xcm/3_force_hrmp-open-channels.yml | 120 ++ .../asset-hub-polkadot/0_xcm/4_hrmp.yml | 388 ++++ .../e2e/assets/asset-hub-polkadot/config.toml | 72 + .../e2e/collectives/README.md | 26 + .../collectives-polkadot/0_xcm/0_init.yml | 166 ++ .../collectives-polkadot/0_xcm/1_teleport.yml | 168 ++ .../collectives-polkadot/0_xcm/2_reserve.yml | 53 + .../0_xcm/3_hrmp-open-channels.yml | 69 + .../1_alliance/0_join_alliance_fails.yml | 29 + .../1_alliance/1_init_alliance.yml | 256 +++ .../1_alliance/2_join_alliance_fails.yml | 30 + .../1_alliance/3_kick_member.yml | 175 ++ .../2_opengov/0_assethub.yml | 149 ++ .../3_fellowship/0_init.yml | 209 ++ .../3_fellowship/1_whitelist_call.yml | 146 ++ .../3_fellowship/2_assethub.yml | 126 ++ .../collectives-polkadot/config.toml | 42 + .../assets/asset-hub-rococo/Cargo.toml | 3 - .../assets/asset-hub-rococo/src/lib.rs | 7 +- .../assets/asset-hub-westend/Cargo.toml | 3 - .../assets/asset-hub-westend/src/lib.rs | 7 +- .../bridges/bridge-hub-rococo/Cargo.toml | 3 - .../bridges/bridge-hub-rococo/src/lib.rs | 5 +- .../bridges/bridge-hub-westend/Cargo.toml | 3 - .../bridges/bridge-hub-westend/src/lib.rs | 5 +- .../collectives-westend/Cargo.toml | 28 - .../collectives-westend/src/genesis.rs | 67 - .../collectives-westend/src/lib.rs | 51 - .../parachains/testing/penpal/Cargo.toml | 4 - .../parachains/testing/penpal/src/lib.rs | 8 +- .../emulated/chains/relays/rococo/Cargo.toml | 3 - .../chains/relays/rococo/src/genesis.rs | 4 + .../emulated/chains/relays/rococo/src/lib.rs | 2 +- .../emulated/chains/relays/westend/Cargo.toml | 3 - .../chains/relays/westend/src/genesis.rs | 4 + .../emulated/chains/relays/westend/src/lib.rs | 2 +- .../emulated/common/Cargo.toml | 31 +- .../emulated/common/src/impls.rs | 67 +- .../emulated/common/src/lib.rs | 2 + .../emulated/common/src/macros.rs | 99 - .../emulated/common/src/xcm_helpers.rs | 14 - .../networks/rococo-system/Cargo.toml | 3 - .../networks/rococo-westend-system/Cargo.toml | 3 - .../networks/westend-system/Cargo.toml | 4 - .../networks/westend-system/src/lib.rs | 4 - .../tests/assets/asset-hub-rococo/Cargo.toml | 22 +- .../assets/asset-hub-rococo/src/tests/mod.rs | 8 - .../src/tests/reserve_transfer.rs | 71 +- .../assets/asset-hub-rococo/src/tests/swap.rs | 163 +- .../asset-hub-rococo/src/tests/teleport.rs | 337 --- .../tests/assets/asset-hub-westend/Cargo.toml | 32 +- .../tests/assets/asset-hub-westend/src/lib.rs | 37 +- .../src/tests/fellowship_treasury.rs | 131 -- .../assets/asset-hub-westend/src/tests/mod.rs | 9 - .../src/tests/reserve_transfer.rs | 341 +-- .../asset-hub-westend/src/tests/send.rs | 12 +- .../asset-hub-westend/src/tests/swap.rs | 156 +- .../asset-hub-westend/src/tests/teleport.rs | 382 +--- .../bridges/bridge-hub-rococo/Cargo.toml | 20 +- .../bridges/bridge-hub-rococo/src/lib.rs | 4 +- .../src/tests/asset_transfers.rs | 70 +- .../bridge-hub-rococo/src/tests/mod.rs | 96 - .../bridge-hub-rococo/src/tests/send_xcm.rs | 145 +- .../bridges/bridge-hub-westend/Cargo.toml | 20 +- .../bridges/bridge-hub-westend/src/lib.rs | 4 +- .../src/tests/asset_transfers.rs | 70 +- .../bridge-hub-westend/src/tests/mod.rs | 96 - .../bridge-hub-westend/src/tests/send_xcm.rs | 145 +- .../pallets/collective-content/Cargo.toml | 5 +- .../pallets/collective-content/src/mock.rs | 3 +- .../pallets/parachain-info/Cargo.toml | 13 +- cumulus/parachains/pallets/ping/Cargo.toml | 15 +- .../assets/asset-hub-kusama/Cargo.toml | 236 +++ .../runtimes/assets/asset-hub-kusama/build.rs | 26 +- .../assets/asset-hub-kusama/src/lib.rs | 1549 ++++++++++++++ .../src/weights/block_weights.rs | 53 + .../src/weights/cumulus_pallet_dmp_queue.rs | 131 ++ .../cumulus_pallet_parachain_system.rs | 80 + .../src/weights/cumulus_pallet_xcmp_queue.rs | 148 ++ .../src/weights/extrinsic_weights.rs | 53 + .../src/weights/frame_system.rs | 154 ++ .../asset-hub-kusama/src/weights/mod.rs | 45 + .../src/weights/pallet_asset_conversion.rs | 154 ++ .../src/weights/pallet_assets_foreign.rs | 533 +++++ .../src/weights/pallet_assets_local.rs | 530 +++++ .../src/weights/pallet_assets_pool.rs | 530 +++++ .../src/weights/pallet_balances.rs | 152 ++ .../src/weights/pallet_collator_selection.rs | 248 +++ .../src/weights/pallet_message_queue.rs | 179 ++ .../src/weights/pallet_multisig.rs | 164 ++ .../weights/pallet_nft_fractionalization.rs | 114 + .../src/weights/pallet_nfts.rs | 772 +++++++ .../src/weights/pallet_proxy.rs | 225 ++ .../src/weights/pallet_session.rs | 80 + .../src/weights/pallet_timestamp.rs | 74 + .../src/weights/pallet_uniques.rs | 466 ++++ .../src/weights/pallet_utility.rs | 101 + .../src/weights/pallet_xcm.rs | 324 +++ .../src/weights/paritydb_weights.rs | 63 + .../src/weights/rocksdb_weights.rs | 63 + .../asset-hub-kusama/src/weights/xcm/mod.rs | 244 +++ .../xcm/pallet_xcm_benchmarks_fungible.rs | 187 ++ .../xcm/pallet_xcm_benchmarks_generic.rs | 328 +++ .../assets/asset-hub-kusama/src/xcm_config.rs | 634 ++++++ .../assets/asset-hub-kusama/tests/tests.rs | 658 ++++++ .../assets/asset-hub-polkadot/Cargo.toml | 215 ++ .../assets/asset-hub-polkadot/build.rs | 25 +- .../assets/asset-hub-polkadot/src/lib.rs | 1383 ++++++++++++ .../src/weights/block_weights.rs | 53 + .../src/weights/cumulus_pallet_dmp_queue.rs | 131 ++ .../cumulus_pallet_parachain_system.rs | 80 + .../src/weights/cumulus_pallet_xcmp_queue.rs | 148 ++ .../src/weights/extrinsic_weights.rs | 53 + .../src/weights/frame_system.rs | 154 ++ .../asset-hub-polkadot/src/weights/mod.rs | 42 + .../src/weights/pallet_assets_foreign.rs | 532 +++++ .../src/weights/pallet_assets_local.rs | 528 +++++ .../src/weights/pallet_balances.rs | 152 ++ .../src/weights/pallet_collator_selection.rs | 246 +++ .../src/weights/pallet_message_queue.rs | 179 ++ .../src/weights/pallet_multisig.rs | 164 ++ .../src/weights/pallet_nfts.rs | 772 +++++++ .../src/weights/pallet_proxy.rs | 225 ++ .../src/weights/pallet_session.rs | 80 + .../src/weights/pallet_timestamp.rs | 74 + .../src/weights/pallet_uniques.rs | 466 ++++ .../src/weights/pallet_utility.rs | 101 + .../src/weights/pallet_xcm.rs | 324 +++ .../src/weights/paritydb_weights.rs | 63 + .../src/weights/rocksdb_weights.rs | 63 + .../asset-hub-polkadot/src/weights/xcm/mod.rs | 244 +++ .../xcm/pallet_xcm_benchmarks_fungible.rs | 187 ++ .../xcm/pallet_xcm_benchmarks_generic.rs | 328 +++ .../asset-hub-polkadot/src/xcm_config.rs | 546 +++++ .../assets/asset-hub-polkadot/tests/tests.rs | 683 ++++++ .../assets/asset-hub-rococo/Cargo.toml | 34 +- .../assets/asset-hub-rococo/src/lib.rs | 103 +- .../src/weights/pallet_xcm.rs | 154 +- .../weights/pallet_xcm_bridge_hub_router.rs | 32 +- .../assets/asset-hub-rococo/src/xcm_config.rs | 51 +- .../assets/asset-hub-rococo/tests/tests.rs | 9 +- .../assets/asset-hub-westend/Cargo.toml | 107 +- .../assets/asset-hub-westend/src/lib.rs | 99 +- .../src/weights/cumulus_pallet_dmp_queue.rs | 131 ++ .../asset-hub-westend/src/weights/mod.rs | 1 + .../src/weights/pallet_xcm.rs | 154 +- .../weights/pallet_xcm_bridge_hub_router.rs | 46 +- .../asset-hub-westend/src/xcm_config.rs | 60 +- .../assets/asset-hub-westend/tests/tests.rs | 12 +- .../runtimes/assets/common/Cargo.toml | 21 +- .../runtimes/assets/test-utils/Cargo.toml | 27 +- .../bridge-hubs/bridge-hub-kusama/Cargo.toml | 192 ++ .../bridge-hubs/bridge-hub-kusama/build.rs | 26 + .../bridge-hubs/bridge-hub-kusama/src/lib.rs | 872 ++++++++ .../src/weights/block_weights.rs | 53 + .../src/weights/cumulus_pallet_dmp_queue.rs | 131 ++ .../cumulus_pallet_parachain_system.rs | 80 + .../src/weights/cumulus_pallet_xcmp_queue.rs | 148 ++ .../src/weights/extrinsic_weights.rs | 53 + .../src/weights/frame_system.rs | 154 ++ .../bridge-hub-kusama/src/weights/mod.rs | 41 + .../src/weights/pallet_balances.rs | 152 ++ .../src/weights/pallet_collator_selection.rs | 248 +++ .../src/weights/pallet_message_queue.rs | 179 ++ .../src/weights/pallet_multisig.rs | 164 ++ .../src/weights/pallet_session.rs | 80 + .../src/weights/pallet_timestamp.rs | 74 + .../src/weights/pallet_utility.rs | 101 + .../src/weights/pallet_xcm.rs | 323 +++ .../src/weights/paritydb_weights.rs | 63 + .../src/weights/rocksdb_weights.rs | 63 + .../bridge-hub-kusama/src/weights/xcm/mod.rs | 244 +++ .../xcm/pallet_xcm_benchmarks_fungible.rs | 187 ++ .../xcm/pallet_xcm_benchmarks_generic.rs | 328 +++ .../bridge-hub-kusama/src/xcm_config.rs | 280 +++ .../bridge-hub-kusama/tests/tests.rs | 51 + .../bridge-hub-polkadot/Cargo.toml | 192 ++ .../bridge-hubs/bridge-hub-polkadot/build.rs | 26 + .../bridge-hub-polkadot/src/lib.rs | 873 ++++++++ .../src/weights/block_weights.rs | 53 + .../src/weights/cumulus_pallet_dmp_queue.rs | 131 ++ .../cumulus_pallet_parachain_system.rs | 80 + .../src/weights/cumulus_pallet_xcmp_queue.rs | 148 ++ .../src/weights/extrinsic_weights.rs | 53 + .../src/weights/frame_system.rs | 154 ++ .../bridge-hub-polkadot/src/weights/mod.rs | 41 + .../src/weights/pallet_balances.rs | 152 ++ .../src/weights/pallet_collator_selection.rs | 248 +++ .../src/weights/pallet_message_queue.rs | 179 ++ .../src/weights/pallet_multisig.rs | 164 ++ .../src/weights/pallet_session.rs | 80 + .../src/weights/pallet_timestamp.rs | 74 + .../src/weights/pallet_utility.rs | 101 + .../src/weights/pallet_xcm.rs | 323 +++ .../src/weights/paritydb_weights.rs | 63 + .../src/weights/rocksdb_weights.rs | 63 + .../src/weights/xcm/mod.rs | 244 +++ .../xcm/pallet_xcm_benchmarks_fungible.rs | 187 ++ .../xcm/pallet_xcm_benchmarks_generic.rs | 328 +++ .../bridge-hub-polkadot/src/xcm_config.rs | 284 +++ .../bridge-hub-polkadot/tests/tests.rs | 51 + .../bridge-hubs/bridge-hub-rococo/Cargo.toml | 19 +- .../src/bridge_common_config.rs | 39 +- .../src/bridge_to_bulletin_config.rs | 292 --- .../src/bridge_to_westend_config.rs | 87 +- .../bridge-hubs/bridge-hub-rococo/src/lib.rs | 200 +- .../bridge-hub-rococo/src/weights/mod.rs | 24 +- .../src/weights/pallet_bridge_grandpa.rs | 16 +- ...o_westend.rs => pallet_bridge_messages.rs} | 71 +- ...idge_messages_rococo_to_rococo_bulletin.rs | 221 -- .../src/weights/pallet_bridge_parachains.rs | 20 +- .../src/weights/pallet_bridge_relayers.rs | 34 +- .../src/weights/pallet_xcm.rs | 191 +- .../xcm/pallet_xcm_benchmarks_generic.rs | 132 +- .../bridge-hub-rococo/src/xcm_config.rs | 57 +- .../bridge-hub-rococo/tests/tests.rs | 333 +-- .../bridge-hubs/bridge-hub-westend/Cargo.toml | 101 +- .../src/bridge_to_rococo_config.rs | 64 +- .../bridge-hubs/bridge-hub-westend/src/lib.rs | 74 +- .../src/weights/cumulus_pallet_dmp_queue.rs | 131 ++ .../bridge-hub-westend/src/weights/mod.rs | 1 + .../src/weights/pallet_bridge_grandpa.rs | 28 +- .../src/weights/pallet_bridge_messages.rs | 187 +- .../src/weights/pallet_bridge_parachains.rs | 78 +- .../src/weights/pallet_bridge_relayers.rs | 30 +- .../src/weights/pallet_xcm.rs | 220 +- .../xcm/pallet_xcm_benchmarks_generic.rs | 190 +- .../bridge-hub-westend/src/xcm_config.rs | 40 +- .../bridge-hub-westend/tests/tests.rs | 47 +- .../bridge-hubs/test-utils/Cargo.toml | 36 +- .../bridge-hubs/test-utils/src/lib.rs | 2 - .../bridge-hubs/test-utils/src/test_cases.rs | 1564 ++++++++++++++ .../src/test_cases/from_grandpa_chain.rs | 442 ---- .../src/test_cases/from_parachain.rs | 544 ----- .../test-utils/src/test_cases/helpers.rs | 340 --- .../test-utils/src/test_cases/mod.rs | 485 ----- .../src/test_data/from_grandpa_chain.rs | 244 --- .../src/test_data/from_parachain.rs | 326 --- .../test-utils/src/test_data/mod.rs | 144 -- .../collectives-polkadot/Cargo.toml | 226 ++ .../collectives/collectives-polkadot/build.rs | 26 + .../src/ambassador/mod.rs | 255 +++ .../src/ambassador/origins.rs | 135 ++ .../src/ambassador/tracks.rs | 282 +++ .../src/fellowship/migration.rs | 261 +++ .../src/fellowship/mod.rs | 239 +++ .../src/fellowship/origins.rs | 247 +++ .../src/fellowship/tracks.rs | 532 +++++ .../collectives-polkadot/src/impls.rs | 229 ++ .../collectives-polkadot/src/lib.rs | 1031 +++++++++ .../src/weights/block_weights.rs | 53 + .../src/weights/cumulus_pallet_dmp_queue.rs | 131 ++ .../cumulus_pallet_parachain_system.rs | 80 + .../src/weights/cumulus_pallet_xcmp_queue.rs | 148 ++ .../src/weights/extrinsic_weights.rs | 53 + .../src/weights/frame_system.rs | 154 ++ .../collectives-polkadot/src/weights/mod.rs | 50 + .../src/weights/pallet_alliance.rs | 494 +++++ .../src/weights/pallet_balances.rs | 152 ++ .../src/weights/pallet_collator_selection.rs | 246 +++ .../src/weights/pallet_collective.rs | 304 +++ .../src/weights/pallet_collective_content.rs | 93 + .../pallet_core_fellowship_ambassador_core.rs | 223 ++ .../pallet_core_fellowship_fellowship_core.rs | 222 ++ .../src/weights/pallet_message_queue.rs | 179 ++ .../src/weights/pallet_multisig.rs | 164 ++ .../src/weights/pallet_preimage.rs | 232 ++ .../src/weights/pallet_proxy.rs | 225 ++ ...ranked_collective_ambassador_collective.rs | 177 ++ ...ranked_collective_fellowship_collective.rs | 176 ++ .../pallet_referenda_ambassador_referenda.rs | 536 +++++ .../pallet_referenda_fellowship_referenda.rs | 535 +++++ .../pallet_salary_ambassador_salary.rs | 190 ++ .../pallet_salary_fellowship_salary.rs | 189 ++ .../src/weights/pallet_scheduler.rs | 206 ++ .../src/weights/pallet_session.rs | 80 + .../src/weights/pallet_timestamp.rs | 74 + .../src/weights/pallet_utility.rs | 101 + .../src/weights/pallet_xcm.rs | 323 +++ .../src/weights/paritydb_weights.rs | 63 + .../src/weights/rocksdb_weights.rs | 63 + .../collectives-polkadot/src/xcm_config.rs | 331 +++ .../collectives-westend/Cargo.toml | 37 +- .../collectives-westend/src/fellowship/mod.rs | 128 +- .../collectives-westend/src/lib.rs | 74 +- .../src/weights/cumulus_pallet_dmp_queue.rs | 131 ++ .../collectives-westend/src/weights/mod.rs | 3 +- .../src/weights/pallet_asset_rate.rs | 85 - .../src/weights/pallet_treasury.rs | 214 -- .../src/weights/pallet_xcm.rs | 117 +- .../collectives-westend/src/xcm_config.rs | 54 +- .../contracts/contracts-rococo/Cargo.toml | 75 +- .../contracts/contracts-rococo/src/lib.rs | 44 +- .../contracts-rococo/src/xcm_config.rs | 47 +- .../glutton/glutton-kusama/Cargo.toml | 138 ++ .../runtimes/glutton/glutton-kusama/build.rs | 18 +- .../glutton/glutton-kusama/src/lib.rs | 528 +++++ .../cumulus_pallet_parachain_system.rs | 80 + .../src/weights/frame_system.rs | 154 ++ .../glutton/glutton-kusama/src/weights/mod.rs | 19 + .../src/weights/pallet_glutton.rs | 179 ++ .../src/weights/pallet_message_queue.rs | 179 ++ .../src/weights/pallet_timestamp.rs | 75 + .../glutton/glutton-kusama/src/xcm_config.rs | 92 + .../glutton/glutton-westend/Cargo.toml | 59 +- .../glutton/glutton-westend/src/lib.rs | 19 +- .../runtimes/starters/seedling/Cargo.toml | 41 +- .../runtimes/starters/seedling/src/lib.rs | 6 +- .../runtimes/starters/shell/Cargo.toml | 43 +- .../runtimes/starters/shell/src/lib.rs | 3 +- .../parachains/runtimes/test-utils/Cargo.toml | 37 +- .../parachains/runtimes/test-utils/src/lib.rs | 57 +- .../runtimes/testing/penpal/Cargo.toml | 83 +- .../runtimes/testing/penpal/src/lib.rs | 5 +- .../runtimes/testing/penpal/src/xcm_config.rs | 61 +- .../testing/rococo-parachain/Cargo.toml | 65 +- .../testing/rococo-parachain/src/lib.rs | 16 +- cumulus/parachains/testnets-common/Cargo.toml | 44 + cumulus/parachains/testnets-common/src/lib.rs | 30 + .../parachains/testnets-common/src/rococo.rs | 119 ++ .../parachains/testnets-common/src/westend.rs | 140 ++ .../parachains/testnets-common/src/wococo.rs | 9 +- cumulus/polkadot-parachain/Cargo.toml | 31 +- .../src/chain_spec/asset_hubs.rs | 357 +++- .../src/chain_spec/bridge_hubs.rs | 246 ++- .../src/chain_spec/collectives.rs | 134 ++ .../src/chain_spec/glutton.rs | 56 + cumulus/polkadot-parachain/src/cli.rs | 3 +- cumulus/polkadot-parachain/src/command.rs | 62 +- cumulus/polkadot-parachain/src/service.rs | 90 + .../tests/benchmark_storage_works.rs | 2 +- cumulus/primitives/aura/Cargo.toml | 19 +- cumulus/primitives/core/Cargo.toml | 23 +- .../primitives/parachain-inherent/Cargo.toml | 25 +- .../proof-size-hostfunction/Cargo.toml | 24 - .../proof-size-hostfunction/src/lib.rs | 107 - cumulus/primitives/timestamp/Cargo.toml | 13 +- cumulus/primitives/utility/Cargo.toml | 19 +- cumulus/scripts/benchmarks.sh | 9 + cumulus/scripts/bridges_common.sh | 14 +- cumulus/scripts/bridges_rococo_westend.sh | 33 - .../scripts/create_bridge_hub_kusama_spec.sh | 108 + .../create_bridge_hub_polkadot_spec.sh | 108 + cumulus/scripts/create_glutton_spec.sh | 2 +- .../generate_hex_encoded_call/index.js | 10 +- .../scripts/parachains_integration_tests.sh | 32 + cumulus/test/client/Cargo.toml | 6 +- cumulus/test/client/src/lib.rs | 3 +- cumulus/test/relay-sproof-builder/Cargo.toml | 17 +- cumulus/test/runtime/Cargo.toml | 49 +- cumulus/test/runtime/src/lib.rs | 17 +- cumulus/test/service/Cargo.toml | 13 +- cumulus/test/service/benches/block_import.rs | 92 +- .../service/benches/block_import_glutton.rs | 37 +- .../test/service/benches/validate_block.rs | 15 +- cumulus/test/service/src/bench_utils.rs | 7 +- cumulus/test/service/src/cli.rs | 37 +- cumulus/test/service/src/genesis.rs | 43 +- cumulus/test/service/src/lib.rs | 76 +- cumulus/test/service/src/main.rs | 47 +- cumulus/xcm/xcm-emulator/Cargo.toml | 3 - .../bridge_hub_kusama_local_network.toml | 67 + .../bridge_hub_polkadot_local_network.toml | 67 + cumulus/zombienet/examples/small_network.toml | 2 +- ...ml => statemine_kusama_local_network.toml} | 18 +- .../zombienet/tests/0002-pov_recovery.toml | 5 +- .../zombienet/tests/0002-pov_recovery.zndsl | 3 +- docs/{contributor => }/CODE_OF_CONDUCT.md | 0 docs/{contributor => }/CONTRIBUTING.md | 24 +- .../DEPRECATION_CHECKLIST.md | 8 +- .../DOCUMENTATION_GUIDELINES.md | 6 +- .../PULL_REQUEST_TEMPLATE.md | 2 +- docs/{contributor => }/SECURITY.md | 0 docs/{contributor => }/STYLE_GUIDE.md | 34 +- docs/{contributor => }/container.md | 0 docs/contributor/prdoc.md | 71 - docs/{contributor => }/docker.md | 0 docs/{contributor => }/markdown_linting.md | 0 docs/mermaid/IA.mmd | 14 - docs/mermaid/extrinsics.mmd | 5 - docs/mermaid/polkadot_sdk_parachain.mmd | 11 - docs/mermaid/polkadot_sdk_polkadot.mmd | 10 - docs/mermaid/polkadot_sdk_substrate.mmd | 8 - docs/mermaid/state.mmd | 16 - docs/mermaid/stf.mmd | 21 - docs/mermaid/stf_simple.mmd | 4 - docs/mermaid/substrate_client_runtime.mmd | 8 +- docs/mermaid/substrate_dev.mmd | 2 - docs/mermaid/substrate_simple.mmd | 2 +- docs/mermaid/substrate_with_frame.mmd | 6 +- docs/sdk/Cargo.toml | 69 - docs/sdk/headers/toc.html | 54 - docs/sdk/src/guides/changing_consensus.rs | 1 - .../src/guides/cumulus_enabled_parachain.rs | 1 - docs/sdk/src/guides/mod.rs | 25 - docs/sdk/src/guides/xcm_enabled_parachain.rs | 1 - docs/sdk/src/guides/your_first_node.rs | 1 - docs/sdk/src/guides/your_first_pallet/mod.rs | 754 ------- .../guides/your_first_pallet/with_event.rs | 101 - docs/sdk/src/guides/your_first_runtime.rs | 1 - docs/sdk/src/lib.rs | 43 - docs/sdk/src/meta_contributing.rs | 146 -- docs/sdk/src/polkadot_sdk/cumulus.rs | 130 -- docs/sdk/src/polkadot_sdk/frame_runtime.rs | 179 -- docs/sdk/src/polkadot_sdk/mod.rs | 134 -- docs/sdk/src/polkadot_sdk/polkadot.rs | 87 - docs/sdk/src/polkadot_sdk/smart_contracts.rs | 9 - docs/sdk/src/polkadot_sdk/substrate.rs | 151 -- docs/sdk/src/polkadot_sdk/templates.rs | 45 - docs/sdk/src/polkadot_sdk/xcm.rs | 5 - .../reference_docs/blockchain_scalibility.rs | 0 .../blockchain_state_machines.rs | 29 - .../src/reference_docs/chain_spec_genesis.rs | 4 - docs/sdk/src/reference_docs/cli.rs | 7 - .../src/reference_docs/consensus_swapping.rs | 6 - .../src/reference_docs/extrinsic_encoding.rs | 294 --- .../src/reference_docs/fee_less_runtime.rs | 12 - .../frame_benchmarking_weight.rs | 23 - .../reference_docs/frame_composite_enums.rs | 1 - docs/sdk/src/reference_docs/frame_currency.rs | 8 - docs/sdk/src/reference_docs/frame_origin.rs | 14 - .../reference_docs/frame_runtime_migration.rs | 9 - .../reference_docs/frame_system_accounts.rs | 8 - docs/sdk/src/reference_docs/glossary.rs | 120 -- docs/sdk/src/reference_docs/light_nodes.rs | 7 - docs/sdk/src/reference_docs/metadata.rs | 1 - docs/sdk/src/reference_docs/mod.rs | 99 - .../runtime_vs_smart_contract.rs | 6 - .../safe_defensive_programming.rs | 1 - .../reference_docs/trait_based_programming.rs | 229 -- .../reference_docs/transaction_extensions.rs | 57 - docs/sdk/src/reference_docs/wasm_memory.rs | 7 - .../src/reference_docs/wasm_meta_protocol.rs | 113 - polkadot/Cargo.toml | 28 +- polkadot/README.md | 7 +- polkadot/cli/Cargo.toml | 26 +- polkadot/cli/src/cli.rs | 20 +- polkadot/cli/src/command.rs | 11 +- polkadot/core-primitives/Cargo.toml | 7 +- polkadot/doc/testing.md | 91 +- polkadot/erasure-coding/Cargo.toml | 5 +- polkadot/erasure-coding/fuzzer/Cargo.toml | 3 - polkadot/node/collation-generation/Cargo.toml | 5 +- polkadot/node/core/approval-voting/Cargo.toml | 6 +- .../approval-voting/src/approval_checking.rs | 212 +- .../approval_db/common/migration_helpers.rs | 39 - .../src/approval_db/common/mod.rs | 293 --- .../approval-voting/src/approval_db/mod.rs | 2 - .../src/approval_db/v1/tests.rs | 4 + .../src/approval_db/v2/migration_helpers.rs | 70 +- .../approval-voting/src/approval_db/v2/mod.rs | 251 ++- .../src/approval_db/v2/tests.rs | 68 +- .../src/approval_db/v3/migration_helpers.rs | 237 --- .../approval-voting/src/approval_db/v3/mod.rs | 137 -- .../src/approval_db/v3/tests.rs | 575 ----- .../node/core/approval-voting/src/backend.rs | 18 +- .../node/core/approval-voting/src/criteria.rs | 22 +- .../node/core/approval-voting/src/import.rs | 363 ++-- polkadot/node/core/approval-voting/src/lib.rs | 856 ++------ polkadot/node/core/approval-voting/src/ops.rs | 2 +- .../approval-voting/src/persisted_entries.rs | 292 +-- .../node/core/approval-voting/src/tests.rs | 607 +----- .../node/core/approval-voting/src/time.rs | 165 +- polkadot/node/core/av-store/Cargo.toml | 3 - polkadot/node/core/backing/Cargo.toml | 3 - .../node/core/bitfield-signing/Cargo.toml | 3 - .../node/core/candidate-validation/Cargo.toml | 3 - .../node/core/candidate-validation/src/lib.rs | 11 +- polkadot/node/core/chain-api/Cargo.toml | 3 - polkadot/node/core/chain-selection/Cargo.toml | 3 - .../node/core/dispute-coordinator/Cargo.toml | 3 - .../core/dispute-coordinator/src/import.rs | 38 +- .../dispute-coordinator/src/initialized.rs | 4 +- .../node/core/dispute-coordinator/src/lib.rs | 2 +- .../core/dispute-coordinator/src/tests.rs | 54 +- .../node/core/parachains-inherent/Cargo.toml | 3 - .../core/prospective-parachains/Cargo.toml | 3 - .../core/prospective-parachains/src/tests.rs | 8 +- polkadot/node/core/provisioner/Cargo.toml | 5 +- .../src/disputes/prioritized_selection/mod.rs | 2 +- polkadot/node/core/pvf-checker/Cargo.toml | 3 - polkadot/node/core/pvf/Cargo.toml | 8 +- polkadot/node/core/pvf/README.md | 47 - .../benches/host_prepare_rococo_runtime.rs | 6 +- polkadot/node/core/pvf/common/Cargo.toml | 3 - ...executor_interface.rs => executor_intf.rs} | 6 +- polkadot/node/core/pvf/common/src/lib.rs | 14 +- .../node/core/pvf/common/src/worker/mod.rs | 234 +- .../common/src/worker/security/change_root.rs | 173 -- .../common/src/worker/security/landlock.rs | 65 +- .../pvf/common/src/worker/security/mod.rs | 130 +- .../pvf/common/src/worker/security/seccomp.rs | 32 +- .../node/core/pvf/execute-worker/Cargo.toml | 5 +- .../node/core/pvf/execute-worker/src/lib.rs | 15 +- .../node/core/pvf/prepare-worker/Cargo.toml | 5 +- .../benches/prepare_rococo_runtime.rs | 2 +- .../node/core/pvf/prepare-worker/src/lib.rs | 8 +- polkadot/node/core/pvf/src/artifacts.rs | 102 +- polkadot/node/core/pvf/src/execute/mod.rs | 2 +- polkadot/node/core/pvf/src/execute/queue.rs | 8 +- .../{worker_interface.rs => worker_intf.rs} | 13 +- polkadot/node/core/pvf/src/host.rs | 19 +- polkadot/node/core/pvf/src/lib.rs | 4 +- polkadot/node/core/pvf/src/prepare/mod.rs | 2 +- polkadot/node/core/pvf/src/prepare/pool.rs | 8 +- .../{worker_interface.rs => worker_intf.rs} | 2 +- polkadot/node/core/pvf/src/security.rs | 197 +- polkadot/node/core/pvf/src/testing.rs | 4 +- .../{worker_interface.rs => worker_intf.rs} | 151 +- polkadot/node/core/pvf/tests/README.md | 9 + polkadot/node/core/pvf/tests/it/main.rs | 43 +- .../node/core/pvf/tests/it/worker_common.rs | 12 +- polkadot/node/core/runtime-api/Cargo.toml | 5 +- polkadot/node/core/runtime-api/src/cache.rs | 31 +- polkadot/node/core/runtime-api/src/lib.rs | 13 - polkadot/node/core/runtime-api/src/tests.rs | 22 +- polkadot/node/gum/Cargo.toml | 3 - polkadot/node/gum/proc-macro/Cargo.toml | 7 +- polkadot/node/jaeger/Cargo.toml | 3 - polkadot/node/malus/Cargo.toml | 9 +- polkadot/node/malus/src/malus.rs | 46 - polkadot/node/malus/src/variants/common.rs | 4 +- .../variants/dispute_finalized_candidates.rs | 265 --- polkadot/node/malus/src/variants/mod.rs | 2 - .../src/variants/suggest_garbage_candidate.rs | 2 +- polkadot/node/metrics/Cargo.toml | 9 +- .../network/approval-distribution/Cargo.toml | 6 +- .../network/approval-distribution/src/lib.rs | 734 +++---- .../approval-distribution/src/metrics.rs | 148 -- .../approval-distribution/src/tests.rs | 754 ++----- .../availability-distribution/Cargo.toml | 3 - .../src/pov_requester/mod.rs | 10 +- .../src/requester/tests.rs | 8 +- .../src/tests/state.rs | 7 +- .../network/availability-recovery/Cargo.toml | 7 - .../network/availability-recovery/src/lib.rs | 13 +- .../availability-recovery/src/metrics.rs | 17 +- .../network/availability-recovery/src/task.rs | 3 +- .../availability-recovery/src/tests.rs | 29 +- .../network/bitfield-distribution/Cargo.toml | 3 - .../network/bitfield-distribution/src/lib.rs | 18 +- polkadot/node/network/bridge/Cargo.toml | 3 - polkadot/node/network/bridge/src/lib.rs | 1 - polkadot/node/network/bridge/src/network.rs | 108 +- polkadot/node/network/bridge/src/rx/mod.rs | 963 ++++----- polkadot/node/network/bridge/src/rx/tests.rs | 349 +-- polkadot/node/network/bridge/src/tx/mod.rs | 52 +- polkadot/node/network/bridge/src/tx/tests.rs | 130 +- .../network/bridge/src/validator_discovery.rs | 13 +- .../node/network/collator-protocol/Cargo.toml | 3 - .../src/collator_side/mod.rs | 6 +- .../src/collator_side/tests/mod.rs | 12 +- .../src/validator_side/mod.rs | 6 +- .../network/dispute-distribution/Cargo.toml | 3 - .../dispute-distribution/src/tests/mod.rs | 22 +- .../node/network/gossip-support/Cargo.toml | 4 - .../node/network/gossip-support/src/lib.rs | 16 +- .../node/network/gossip-support/src/tests.rs | 22 - polkadot/node/network/protocol/Cargo.toml | 6 +- .../network/protocol/src/grid_topology.rs | 21 +- polkadot/node/network/protocol/src/lib.rs | 61 +- .../node/network/protocol/src/peer_set.rs | 132 +- .../protocol/src/request_response/mod.rs | 4 +- .../network/statement-distribution/Cargo.toml | 4 +- .../src/legacy_v1/mod.rs | 30 +- .../src/legacy_v1/tests.rs | 57 +- .../network/statement-distribution/src/lib.rs | 10 +- .../statement-distribution/src/v2/mod.rs | 90 +- .../src/v2/tests/grid.rs | 602 ++---- .../src/v2/tests/mod.rs | 150 -- polkadot/node/overseer/Cargo.toml | 17 +- polkadot/node/overseer/src/lib.rs | 2 - polkadot/node/primitives/Cargo.toml | 5 +- polkadot/node/primitives/src/approval.rs | 77 +- .../node/primitives/src/disputes/message.rs | 2 +- polkadot/node/primitives/src/disputes/mod.rs | 23 +- polkadot/node/primitives/src/lib.rs | 4 +- polkadot/node/service/Cargo.toml | 22 +- polkadot/node/service/chain-specs/kusama.json | 4 +- .../node/service/chain-specs/polkadot.json | 4 +- .../node/service/chain-specs/westend.json | 4 +- polkadot/node/service/src/chain_spec.rs | 64 +- polkadot/node/service/src/fake_runtime_api.rs | 2 +- polkadot/node/service/src/grandpa_support.rs | 178 ++ polkadot/node/service/src/lib.rs | 104 +- polkadot/node/service/src/overseer.rs | 14 +- .../node/service/src/parachains_db/upgrade.rs | 99 +- polkadot/node/subsystem-bench/Cargo.toml | 61 - polkadot/node/subsystem-bench/README.md | 216 -- .../examples/availability_read.yaml | 57 - .../grafana/availability-read.json | 1874 ----------------- .../grafana/task-cpu-usage.json | 755 ------- .../subsystem-bench/src/availability/cli.rs | 37 - .../subsystem-bench/src/availability/mod.rs | 339 --- polkadot/node/subsystem-bench/src/cli.rs | 60 - .../subsystem-bench/src/core/configuration.rs | 262 --- .../node/subsystem-bench/src/core/display.rs | 191 -- .../subsystem-bench/src/core/environment.rs | 333 --- .../node/subsystem-bench/src/core/keyring.rs | 40 - .../subsystem-bench/src/core/mock/av_store.rs | 137 -- .../subsystem-bench/src/core/mock/dummy.rs | 98 - .../node/subsystem-bench/src/core/mock/mod.rs | 77 - .../src/core/mock/network_bridge.rs | 323 --- .../src/core/mock/runtime_api.rs | 110 - polkadot/node/subsystem-bench/src/core/mod.rs | 24 - .../node/subsystem-bench/src/core/network.rs | 485 ----- .../subsystem-bench/src/subsystem-bench.rs | 186 -- .../node/subsystem-test-helpers/Cargo.toml | 6 - .../node/subsystem-test-helpers/src/lib.rs | 31 - .../node/subsystem-test-helpers/src/mock.rs | 7 +- polkadot/node/subsystem-types/Cargo.toml | 5 +- polkadot/node/subsystem-types/src/messages.rs | 35 +- .../subsystem-types/src/runtime_client.rs | 33 +- polkadot/node/subsystem-util/Cargo.toml | 7 +- .../node/subsystem-util/src/runtime/mod.rs | 27 +- polkadot/node/subsystem/Cargo.toml | 3 - polkadot/node/test/client/Cargo.toml | 5 +- polkadot/node/test/service/Cargo.toml | 7 +- polkadot/node/test/service/src/lib.rs | 3 +- polkadot/node/tracking-allocator/Cargo.toml | 3 - .../node/zombienet-backchannel/Cargo.toml | 3 - polkadot/parachain/Cargo.toml | 11 +- polkadot/parachain/src/lib.rs | 2 + polkadot/parachain/test-parachains/Cargo.toml | 7 +- .../test-parachains/adder/Cargo.toml | 13 +- .../test-parachains/adder/collator/Cargo.toml | 5 +- .../test-parachains/adder/collator/src/cli.rs | 6 +- .../adder/collator/src/main.rs | 3 +- .../parachain/test-parachains/halt/Cargo.toml | 5 +- .../test-parachains/undying/Cargo.toml | 11 +- .../undying/collator/Cargo.toml | 8 +- .../undying/collator/src/cli.rs | 6 +- .../undying/collator/src/main.rs | 3 +- polkadot/primitives/Cargo.toml | 7 +- polkadot/primitives/src/runtime_api.rs | 50 +- polkadot/primitives/src/v6/mod.rs | 70 +- polkadot/primitives/src/vstaging/mod.rs | 48 - polkadot/primitives/test-helpers/Cargo.toml | 3 - polkadot/roadmap/implementers-guide/README.md | 2 +- polkadot/roadmap/implementers-guide/book.toml | 2 +- .../implementers-guide/src/glossary.md | 9 +- .../src/node/approval/approval-voting.md | 47 +- .../src/node/utility/candidate-validation.md | 25 - .../src/node/utility/pvf-host-and-workers.md | 93 +- .../src/node/utility/pvf-prechecker.md | 6 +- .../src/protocol-approval.md | 12 - polkadot/roadmap/phase-1.toml | 14 +- polkadot/rpc/Cargo.toml | 3 - polkadot/runtime/common/Cargo.toml | 15 +- .../common/slot_range_helper/Cargo.toml | 7 +- .../runtime/common/src/assigned_slots/mod.rs | 4 +- polkadot/runtime/common/src/auctions.rs | 5 +- polkadot/runtime/common/src/claims.rs | 5 +- polkadot/runtime/common/src/crowdloan/mod.rs | 3 +- polkadot/runtime/common/src/impls.rs | 23 +- .../runtime/common/src/integration_tests.rs | 3 +- .../runtime/common/src/paras_registrar/mod.rs | 3 +- polkadot/runtime/common/src/purchase.rs | 5 +- polkadot/runtime/common/src/slots/mod.rs | 4 +- polkadot/runtime/metrics/Cargo.toml | 9 +- polkadot/runtime/parachains/Cargo.toml | 15 +- polkadot/runtime/parachains/src/builder.rs | 2 +- .../runtime/parachains/src/configuration.rs | 29 +- .../parachains/src/configuration/migration.rs | 1 - .../src/configuration/migration/v10.rs | 110 +- .../src/configuration/migration/v11.rs | 329 --- .../src/configuration/migration/v8.rs | 2 +- .../parachains/src/configuration/tests.rs | 1 - polkadot/runtime/parachains/src/disputes.rs | 34 +- .../runtime/parachains/src/disputes/tests.rs | 126 +- polkadot/runtime/parachains/src/mock.rs | 3 +- .../src/runtime_api_impl/vstaging.rs | 11 +- polkadot/runtime/parachains/src/ump_tests.rs | 8 +- polkadot/runtime/rococo/Cargo.toml | 17 +- polkadot/runtime/rococo/constants/Cargo.toml | 7 +- polkadot/runtime/rococo/constants/src/lib.rs | 12 +- polkadot/runtime/rococo/src/impls.rs | 24 +- polkadot/runtime/rococo/src/lib.rs | 227 +- .../runtime/rococo/src/weights/pallet_xcm.rs | 4 - polkadot/runtime/rococo/src/xcm_config.rs | 14 +- polkadot/runtime/test-runtime/Cargo.toml | 7 +- .../runtime/test-runtime/constants/Cargo.toml | 5 +- polkadot/runtime/test-runtime/src/lib.rs | 20 +- polkadot/runtime/westend/Cargo.toml | 15 +- polkadot/runtime/westend/constants/Cargo.toml | 7 +- polkadot/runtime/westend/constants/src/lib.rs | 11 +- polkadot/runtime/westend/src/impls.rs | 24 +- polkadot/runtime/westend/src/lib.rs | 236 +-- .../src/weights/pallet_nomination_pools.rs | 276 ++- .../westend/src/weights/pallet_staking.rs | 214 +- .../runtime/westend/src/weights/pallet_xcm.rs | 4 - polkadot/runtime/westend/src/xcm_config.rs | 26 +- polkadot/statement-table/Cargo.toml | 3 - polkadot/utils/generate-bags/Cargo.toml | 5 +- .../remote-ext-tests/bags-list/Cargo.toml | 5 +- polkadot/xcm/Cargo.toml | 15 +- polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml | 17 +- .../src/fungible/mock.rs | 3 - .../pallet-xcm-benchmarks/src/generic/mock.rs | 1 - polkadot/xcm/pallet-xcm/Cargo.toml | 19 +- polkadot/xcm/pallet-xcm/src/benchmarking.rs | 71 +- polkadot/xcm/pallet-xcm/src/lib.rs | 576 ++--- polkadot/xcm/pallet-xcm/src/mock.rs | 78 +- .../pallet-xcm/src/tests/assets_transfer.rs | 1356 ++---------- polkadot/xcm/pallet-xcm/src/tests/mod.rs | 75 +- polkadot/xcm/procedural/Cargo.toml | 5 +- polkadot/xcm/src/double_encoded.rs | 1 - polkadot/xcm/src/lib.rs | 20 +- polkadot/xcm/src/v2/mod.rs | 1 - polkadot/xcm/src/v3/junction.rs | 6 - polkadot/xcm/src/v3/junctions.rs | 1 - polkadot/xcm/src/v3/mod.rs | 10 - polkadot/xcm/src/v3/multiasset.rs | 8 - polkadot/xcm/src/v3/multilocation.rs | 1 - polkadot/xcm/src/v3/traits.rs | 1 - polkadot/xcm/xcm-builder/Cargo.toml | 5 +- .../xcm/xcm-builder/src/currency_adapter.rs | 3 - .../xcm/xcm-builder/src/fungible_adapter.rs | 317 --- polkadot/xcm/xcm-builder/src/lib.rs | 4 - .../src/tests/bridging/local_para_para.rs | 9 +- .../src/tests/bridging/local_relay_relay.rs | 9 +- .../xcm/xcm-builder/src/tests/bridging/mod.rs | 1 - .../tests/bridging/paid_remote_relay_relay.rs | 3 +- .../src/tests/bridging/remote_para_para.rs | 3 +- .../bridging/remote_para_para_via_relay.rs | 3 +- .../src/tests/bridging/remote_relay_relay.rs | 3 +- .../xcm/xcm-builder/src/universal_exports.rs | 68 +- polkadot/xcm/xcm-builder/tests/mock/mod.rs | 12 +- polkadot/xcm/xcm-executor/Cargo.toml | 5 +- .../xcm-executor/integration-tests/Cargo.toml | 7 +- polkadot/xcm/xcm-simulator/Cargo.toml | 3 - polkadot/xcm/xcm-simulator/example/Cargo.toml | 3 - .../xcm-simulator/example/src/parachain.rs | 12 +- .../xcm-simulator/example/src/relay_chain.rs | 11 +- polkadot/xcm/xcm-simulator/fuzzer/Cargo.toml | 3 - .../xcm/xcm-simulator/fuzzer/src/parachain.rs | 13 +- .../xcm-simulator/fuzzer/src/relay_chain.rs | 12 +- .../functional/0001-parachains-pvf.zndsl | 2 - .../functional/0002-parachains-disputes.toml | 4 - .../0007-dispute-freshly-finalized.toml | 40 - .../0007-dispute-freshly-finalized.zndsl | 29 - .../0008-dispute-old-finalized.toml | 40 - .../0008-dispute-old-finalized.zndsl | 21 - .../0009-approval-voting-coalescing.toml | 115 - .../0009-approval-voting-coalescing.zndsl | 32 - .../zombienet_tests/misc/0002-update-cmd.sh | 11 - .../misc/0002-upgrade-node.zndsl | 5 - prdoc/.template.prdoc | 11 - prdoc/1.3.0/pr_1255.prdoc | 21 - prdoc/1.3.0/readme.md | 2 - prdoc/1.4.0/readme.md | 2 - prdoc/1.5.0/pr_1370_special.prdoc | 9 - prdoc/1.5.0/pr_1497_special.prdoc | 9 - prdoc/1.5.0/pr_1918_special.prdoc | 9 - prdoc/1.5.0/pr_1946_prdoc_new_schema.prdoc | 17 - prdoc/1.5.0/pr_1985_special.prdoc | 9 - prdoc/1.5.0/pr_2001_special.prdoc | 9 - prdoc/1.5.0/pr_2058_special.prdoc | 9 - prdoc/1.5.0/pr_2142.prdoc | 17 - prdoc/1.5.0/pr_2167_special.prdoc | 9 - prdoc/1.5.0/pr_2174_special.prdoc | 9 - prdoc/1.5.0/pr_2182_special.prdoc | 9 - prdoc/1.5.0/pr_2184_special.prdoc | 9 - prdoc/1.5.0/pr_2221_special.prdoc | 9 - prdoc/1.5.0/pr_2250_special.prdoc | 9 - prdoc/1.5.0/pr_2265_special.prdoc | 9 - prdoc/1.5.0/pr_2300_special.prdoc | 9 - prdoc/1.5.0/pr_2351_special.prdoc | 9 - prdoc/1.5.0/pr_2354_special.prdoc | 9 - prdoc/1.5.0/pr_2361_special.prdoc | 9 - prdoc/1.5.0/pr_2368_special.prdoc | 9 - prdoc/1.5.0/pr_2369_special.prdoc | 9 - prdoc/1.5.0/pr_2377_special.prdoc | 9 - prdoc/1.5.0/pr_2378_special.prdoc | 9 - prdoc/1.5.0/pr_2380_special.prdoc | 9 - prdoc/1.5.0/pr_2381_special.prdoc | 9 - prdoc/1.5.0/pr_2385_special.prdoc | 9 - prdoc/1.5.0/pr_2388.prdoc | 30 - prdoc/1.5.0/pr_2397_special.prdoc | 9 - prdoc/1.5.0/pr_2406_special.prdoc | 9 - prdoc/1.5.0/pr_2411_special.prdoc | 9 - prdoc/1.5.0/pr_2413_special.prdoc | 9 - prdoc/1.5.0/pr_2426_special.prdoc | 9 - prdoc/1.5.0/pr_2435_special.prdoc | 9 - prdoc/1.5.0/pr_2442_special.prdoc | 9 - prdoc/1.5.0/pr_2446_special.prdoc | 9 - prdoc/1.5.0/pr_2450_special.prdoc | 9 - prdoc/1.5.0/pr_2455_special.prdoc | 9 - prdoc/1.5.0/pr_2457_special.prdoc | 9 - prdoc/1.5.0/pr_2459_special.prdoc | 9 - prdoc/1.5.0/pr_2461_special.prdoc | 9 - prdoc/1.5.0/pr_2462_special.prdoc | 9 - prdoc/1.5.0/pr_2463_special.prdoc | 9 - prdoc/1.5.0/pr_2474_special.prdoc | 9 - prdoc/1.5.0/pr_2483_special.prdoc | 9 - prdoc/1.5.0/pr_2486.prdoc | 25 - prdoc/1.5.0/pr_2487_special.prdoc | 9 - prdoc/1.5.0/pr_2501_special.prdoc | 9 - prdoc/1.5.0/pr_2509_special.prdoc | 9 - prdoc/1.5.0/pr_2515_special.prdoc | 9 - prdoc/1.5.0/pr_2516_special.prdoc | 9 - prdoc/1.5.0/pr_2521_special.prdoc | 10 - prdoc/1.5.0/pr_2526_special.prdoc | 10 - prdoc/1.5.0/pr_2552_special.prdoc | 10 - prdoc/1.5.0/pr_2555_special.prdoc | 10 - prdoc/1.5.0/pr_2572_special.prdoc | 10 - prdoc/1.5.0/pr_2579_special.prdoc | 10 - prdoc/1.5.0/pr_2581_special.prdoc | 10 - prdoc/1.5.0/pr_2591.prdoc | 12 - prdoc/1.5.0/pr_2602_special.prdoc | 10 - prdoc/1.5.0/pr_2625_special.prdoc | 10 - prdoc/1.5.0/readme.md | 2 - prdoc/{1.4.0 => }/pr_1178.prdoc | 5 +- prdoc/pr_1191.prdoc | 21 - prdoc/pr_1226.prdoc | 15 +- prdoc/{1.3.0 => }/pr_1234.prdoc | 11 +- prdoc/{1.4.0 => }/pr_1246.prdoc | 6 +- prdoc/pr_1255.prdoc | 22 + prdoc/{1.4.0 => }/pr_1256.prdoc | 0 prdoc/pr_1289.prdoc | 15 +- prdoc/pr_1343.prdoc | 29 - .../pr_1408_prodc-introduction.prdoc | 14 +- prdoc/pr_1454.prdoc | 10 - prdoc/{1.4.0 => }/pr_1805.prdoc | 6 +- prdoc/{1.3.0 => }/pr_1818.prdoc | 11 +- prdoc/{1.3.0 => }/pr_1873.prdoc | 12 +- prdoc/{1.3.0 => }/pr_1913.prdoc | 7 + prdoc/{1.3.0 => }/pr_1921.prdoc | 11 +- prdoc/{1.4.0 => }/pr_1926.prdoc | 22 +- prdoc/{1.4.0 => }/pr_2086.prdoc | 11 +- prdoc/{1.4.0 => }/pr_2107.prdoc | 4 +- prdoc/{1.4.0 => }/pr_2165.prdoc | 5 +- prdoc/{1.5.0 => }/pr_2253.prdoc | 5 +- prdoc/pr_2331.prdoc | 17 - prdoc/pr_2403.prdoc | 9 - prdoc/pr_2481.prdoc | 13 - prdoc/pr_2532.prdoc | 11 - prdoc/pr_2597.prdoc | 17 - prdoc/pr_2656.prdoc | 10 - ...-could-not-create-temporary-drectory.prdoc | 17 - prdoc/pr_2684.prdoc | 14 - prdoc/pr_2687.prdoc | 18 - prdoc/schema_user.json | 222 -- scripts/release/build-changelogs.sh | 54 - scripts/release/templates/audience.md.tera | 13 - scripts/release/templates/changelog.md.tera | 7 - substrate/Cargo.toml | 30 + substrate/README.md | 10 +- substrate/bin/minimal/node/Cargo.toml | 13 +- substrate/bin/minimal/runtime/Cargo.toml | 11 +- substrate/bin/node-template/node/Cargo.toml | 11 +- .../bin/node-template/node/src/service.rs | 37 +- .../node-template/pallets/template/Cargo.toml | 13 +- .../pallets/template/src/mock.rs | 6 +- .../bin/node-template/runtime/Cargo.toml | 49 +- .../bin/node-template/runtime/src/lib.rs | 36 +- .../bin/node-template/rust-toolchain.toml | 4 +- substrate/bin/node/bench/Cargo.toml | 11 +- substrate/bin/node/cli/Cargo.toml | 77 +- substrate/bin/node/cli/src/command.rs | 3 +- substrate/bin/node/cli/src/service.rs | 59 +- .../bin/node/cli/tests/websocket_server.rs | 3 +- substrate/bin/node/executor/Cargo.toml | 57 + .../executor.rs => executor/benches/bench.rs} | 119 +- substrate/bin/node/executor/src/lib.rs | 40 + .../bin/node/{cli => executor}/tests/basic.rs | 69 +- .../node/{cli => executor}/tests/common.rs | 18 +- .../bin/node/{cli => executor}/tests/fees.rs | 14 +- .../tests/res/default_genesis_config.json | 0 .../tests/submit_transaction.rs | 0 substrate/bin/node/inspect/Cargo.toml | 15 +- substrate/bin/node/inspect/src/command.rs | 10 +- substrate/bin/node/primitives/Cargo.toml | 11 +- substrate/bin/node/rpc/Cargo.toml | 3 - substrate/bin/node/runtime/Cargo.toml | 205 +- substrate/bin/node/runtime/src/lib.rs | 31 +- substrate/bin/node/testing/Cargo.toml | 13 +- substrate/bin/node/testing/src/bench.rs | 14 +- substrate/bin/node/testing/src/client.rs | 19 +- .../bin/utils/chain-spec-builder/Cargo.toml | 5 +- substrate/bin/utils/subkey/Cargo.toml | 5 +- substrate/client/allocator/Cargo.toml | 3 - substrate/client/allocator/src/lib.rs | 2 +- substrate/client/api/Cargo.toml | 7 +- .../client/api/src/execution_extensions.rs | 5 +- .../client/authority-discovery/Cargo.toml | 15 +- .../client/authority-discovery/src/worker.rs | 2 +- substrate/client/basic-authorship/Cargo.toml | 3 - substrate/client/block-builder/Cargo.toml | 4 - substrate/client/block-builder/src/lib.rs | 5 - substrate/client/chain-spec/Cargo.toml | 7 +- substrate/client/chain-spec/derive/Cargo.toml | 7 +- substrate/client/chain-spec/src/extension.rs | 2 +- .../chain-spec/src/genesis_config_builder.rs | 1 + substrate/client/cli/Cargo.toml | 21 +- substrate/client/consensus/aura/Cargo.toml | 3 - substrate/client/consensus/babe/Cargo.toml | 5 +- .../client/consensus/babe/rpc/Cargo.toml | 7 +- .../client/consensus/babe/src/authorship.rs | 2 +- substrate/client/consensus/babe/src/tests.rs | 8 +- .../client/consensus/babe/src/verification.rs | 2 +- substrate/client/consensus/beefy/Cargo.toml | 5 +- .../client/consensus/beefy/rpc/Cargo.toml | 9 +- .../consensus/beefy/src/communication/mod.rs | 12 +- substrate/client/consensus/beefy/src/lib.rs | 6 +- substrate/client/consensus/beefy/src/tests.rs | 41 +- .../client/consensus/beefy/src/worker.rs | 4 - substrate/client/consensus/common/Cargo.toml | 5 +- substrate/client/consensus/epochs/Cargo.toml | 3 - substrate/client/consensus/grandpa/Cargo.toml | 5 +- .../client/consensus/grandpa/rpc/Cargo.toml | 9 +- .../grandpa/src/communication/mod.rs | 4 +- .../grandpa/src/communication/tests.rs | 242 +-- substrate/client/consensus/grandpa/src/lib.rs | 22 +- .../client/consensus/grandpa/src/observer.rs | 23 +- .../client/consensus/grandpa/src/tests.rs | 82 +- .../client/consensus/manual-seal/Cargo.toml | 7 +- substrate/client/consensus/pow/Cargo.toml | 3 - substrate/client/consensus/slots/Cargo.toml | 3 - substrate/client/db/Cargo.toml | 7 +- substrate/client/executor/Cargo.toml | 5 +- substrate/client/executor/common/Cargo.toml | 3 - .../client/executor/runtime-test/Cargo.toml | 15 +- substrate/client/executor/src/executor.rs | 23 +- substrate/client/executor/src/lib.rs | 2 +- substrate/client/executor/wasmtime/Cargo.toml | 7 +- .../client/executor/wasmtime/src/tests.rs | 8 +- substrate/client/informant/Cargo.toml | 3 - substrate/client/keystore/Cargo.toml | 3 - substrate/client/keystore/src/local.rs | 22 +- .../client/merkle-mountain-range/Cargo.toml | 3 - .../merkle-mountain-range/rpc/Cargo.toml | 7 +- substrate/client/mixnet/Cargo.toml | 4 - .../client/mixnet/src/packet_dispatcher.rs | 36 +- substrate/client/mixnet/src/protocol.rs | 25 +- substrate/client/mixnet/src/run.rs | 60 +- .../client/mixnet/src/sync_with_runtime.rs | 1 - substrate/client/network-gossip/Cargo.toml | 5 - substrate/client/network-gossip/src/bridge.rs | 276 +-- .../network-gossip/src/state_machine.rs | 176 +- substrate/client/network/Cargo.toml | 11 +- substrate/client/network/bitswap/Cargo.toml | 5 +- substrate/client/network/common/Cargo.toml | 3 - substrate/client/network/common/src/role.rs | 14 +- substrate/client/network/light/Cargo.toml | 5 +- substrate/client/network/src/behaviour.rs | 57 +- substrate/client/network/src/config.rs | 90 +- substrate/client/network/src/error.rs | 9 - substrate/client/network/src/event.rs | 49 +- substrate/client/network/src/lib.rs | 22 +- substrate/client/network/src/mock.rs | 9 - substrate/client/network/src/peer_store.rs | 41 +- substrate/client/network/src/protocol.rs | 448 ++-- .../client/network/src/protocol/message.rs | 5 +- .../network/src/protocol/notifications.rs | 4 - .../src/protocol/notifications/behaviour.rs | 992 ++------- .../src/protocol/notifications/handler.rs | 73 +- .../protocol/notifications/service/metrics.rs | 130 -- .../src/protocol/notifications/service/mod.rs | 634 ------ .../protocol/notifications/service/tests.rs | 839 -------- .../src/protocol/notifications/tests.rs | 31 +- .../src/protocol/notifications/upgrade.rs | 8 +- .../client/network/src/protocol_controller.rs | 3 - substrate/client/network/src/service.rs | 235 ++- .../client/network/src/service/metrics.rs | 28 + .../client/network/src/service/signature.rs | 2 - .../client/network/src/service/traits.rs | 228 +- substrate/client/network/statement/Cargo.toml | 3 - substrate/client/network/statement/src/lib.rs | 123 +- substrate/client/network/sync/Cargo.toml | 5 +- substrate/client/network/sync/src/engine.rs | 386 ++-- .../client/network/sync/src/service/mock.rs | 7 +- substrate/client/network/test/Cargo.toml | 5 +- substrate/client/network/test/src/lib.rs | 97 +- substrate/client/network/test/src/service.rs | 337 +-- substrate/client/network/test/src/sync.rs | 86 +- .../client/network/transactions/Cargo.toml | 3 - .../client/network/transactions/src/lib.rs | 156 +- substrate/client/offchain/Cargo.toml | 7 +- substrate/client/offchain/src/api.rs | 15 +- substrate/client/offchain/src/lib.rs | 16 +- substrate/client/proposer-metrics/Cargo.toml | 3 - substrate/client/rpc-api/Cargo.toml | 7 +- substrate/client/rpc-servers/Cargo.toml | 3 - substrate/client/rpc-spec-v2/Cargo.toml | 7 +- .../rpc-spec-v2/src/chain_head/chain_head.rs | 8 +- .../rpc-spec-v2/src/chain_head/error.rs | 64 +- .../rpc-spec-v2/src/chain_head/tests.rs | 24 +- substrate/client/rpc/Cargo.toml | 3 - substrate/client/service/Cargo.toml | 13 +- substrate/client/service/src/builder.rs | 59 +- substrate/client/service/src/client/client.rs | 15 +- substrate/client/service/src/lib.rs | 7 +- substrate/client/service/test/Cargo.toml | 7 +- substrate/client/state-db/Cargo.toml | 3 - substrate/client/state-db/src/lib.rs | 6 +- substrate/client/state-db/src/pruning.rs | 6 +- substrate/client/statement-store/Cargo.toml | 5 +- substrate/client/storage-monitor/Cargo.toml | 9 +- substrate/client/sync-state-rpc/Cargo.toml | 7 +- substrate/client/sysinfo/Cargo.toml | 5 +- substrate/client/telemetry/Cargo.toml | 5 +- substrate/client/tracing/Cargo.toml | 5 +- .../client/tracing/proc-macro/Cargo.toml | 7 +- substrate/client/transaction-pool/Cargo.toml | 5 +- .../client/transaction-pool/api/Cargo.toml | 9 +- .../client/transaction-pool/src/graph/mod.rs | 5 +- substrate/client/utils/Cargo.toml | 7 +- substrate/docs/STYLE_GUIDE.md | 2 +- substrate/frame/Cargo.toml | 13 +- substrate/frame/alliance/Cargo.toml | 19 +- substrate/frame/asset-conversion/Cargo.toml | 23 +- substrate/frame/asset-conversion/src/mock.rs | 3 +- substrate/frame/asset-rate/Cargo.toml | 19 +- substrate/frame/asset-rate/src/mock.rs | 6 +- substrate/frame/assets/Cargo.toml | 15 +- substrate/frame/assets/src/benchmarking.rs | 2 +- substrate/frame/assets/src/lib.rs | 2 +- substrate/frame/assets/src/mock.rs | 3 +- substrate/frame/atomic-swap/Cargo.toml | 17 +- substrate/frame/atomic-swap/src/tests.rs | 6 +- substrate/frame/aura/Cargo.toml | 21 +- substrate/frame/aura/src/mock.rs | 3 +- .../frame/authority-discovery/Cargo.toml | 19 +- .../frame/authority-discovery/src/lib.rs | 3 +- substrate/frame/authorship/Cargo.toml | 13 +- substrate/frame/babe/Cargo.toml | 23 +- substrate/frame/babe/src/lib.rs | 6 +- substrate/frame/babe/src/mock.rs | 1 - substrate/frame/bags-list/Cargo.toml | 5 +- substrate/frame/bags-list/fuzzer/Cargo.toml | 9 +- .../frame/bags-list/remote-tests/Cargo.toml | 5 +- substrate/frame/balances/Cargo.toml | 15 +- substrate/frame/balances/src/lib.rs | 48 +- substrate/frame/balances/src/tests/mod.rs | 4 +- substrate/frame/beefy-mmr/Cargo.toml | 33 +- substrate/frame/beefy/Cargo.toml | 21 +- substrate/frame/beefy/src/mock.rs | 1 - substrate/frame/benchmarking/Cargo.toml | 29 +- substrate/frame/benchmarking/pov/Cargo.toml | 17 +- .../benchmarking/pov/src/benchmarking.rs | 2 - substrate/frame/benchmarking/pov/src/tests.rs | 2 - substrate/frame/benchmarking/src/baseline.rs | 2 - substrate/frame/benchmarking/src/tests.rs | 3 +- .../frame/benchmarking/src/tests_instance.rs | 3 +- substrate/frame/bounties/Cargo.toml | 21 +- substrate/frame/bounties/src/migrations/v4.rs | 4 +- substrate/frame/bounties/src/tests.rs | 3 +- substrate/frame/broker/Cargo.toml | 21 +- substrate/frame/broker/src/lib.rs | 20 +- substrate/frame/broker/src/mock.rs | 32 +- substrate/frame/child-bounties/Cargo.toml | 23 +- substrate/frame/child-bounties/src/tests.rs | 3 +- substrate/frame/collective/Cargo.toml | 19 +- .../frame/collective/src/migrations/v4.rs | 4 +- substrate/frame/collective/src/tests.rs | 4 +- substrate/frame/contracts/Cargo.toml | 37 +- substrate/frame/contracts/build.rs | 1 + substrate/frame/contracts/fixtures/Cargo.toml | 19 +- substrate/frame/contracts/fixtures/build.rs | 277 --- .../contracts/fixtures/contracts/call.rs | 48 - .../fixtures/contracts/common/Cargo.toml | 11 - .../data/account_reentrance_count_call.wat | 2 +- .../data/add_remove_delegate_dependency.wat | 16 +- .../frame/contracts/fixtures/data/balance.wat | 2 +- .../frame/contracts/fixtures/data/call.wat | 39 + .../fixtures/data/call_runtime_and_call.wat | 2 +- .../fixtures/data/caller_contract.wat | 66 +- .../fixtures/data/chain_extension.wat | 2 +- .../data/chain_extension_temp_storage.wat | 2 +- .../fixtures/data/create_storage_and_call.wat | 2 +- .../data/create_storage_and_instantiate.wat | 2 +- .../contracts/fixtures/data/crypto_hashes.wat | 6 +- .../data/debug_message_invalid_utf8.wat | 2 +- .../data/debug_message_logging_disabled.wat | 2 +- .../fixtures/data/debug_message_works.wat | 2 +- .../contracts/fixtures/data/delegate_call.wat | 6 +- .../fixtures/data/delegate_call_lib.wat | 2 +- .../fixtures/data/delegate_call_simple.wat | 2 +- .../fixtures/data/destroy_and_transfer.wat | 2 +- .../frame/contracts/fixtures/data/drain.wat | 2 +- .../frame/contracts/fixtures/data/dummy.wat | 6 + .../contracts/fixtures/data/ecdsa_recover.wat | 2 +- .../contracts/fixtures/data/event_size.wat | 2 +- .../contracts/fixtures/data/multi_store.wat | 2 +- .../fixtures/data/reentrance_count_call.wat | 10 +- .../data/reentrance_count_delegated_call.wat | 12 +- .../contracts/fixtures/data/self_destruct.wat | 2 +- .../data/self_destructing_constructor.wat | 2 +- .../contracts/fixtures/data/set_code_hash.wat | 6 +- .../contracts/fixtures/data/storage_size.wat | 2 +- .../contracts/fixtures/data/store_call.wat | 2 +- .../contracts/fixtures/data/store_deploy.wat | 2 +- .../contracts/fixtures/data/xcm_execute.wat | 2 +- .../contracts/fixtures/data/xcm_send.wat | 2 +- substrate/frame/contracts/fixtures/src/lib.rs | 40 +- .../frame/contracts/mock-network/Cargo.toml | 40 +- .../contracts/mock-network/src/parachain.rs | 13 +- .../contracts/mock-network/src/relay_chain.rs | 12 +- .../frame/contracts/mock-network/src/tests.rs | 3 +- .../frame/contracts/primitives/Cargo.toml | 11 +- .../frame/contracts/primitives/README.md | 3 + .../primitives.rs => primitives/src/lib.rs} | 15 +- .../frame/contracts/proc-macro/Cargo.toml | 5 +- .../frame/contracts/proc-macro/src/lib.rs | 14 +- .../frame/contracts/src/benchmarking/mod.rs | 2 +- .../frame/contracts/src/chain_extension.rs | 2 +- substrate/frame/contracts/src/debug.rs | 6 +- substrate/frame/contracts/src/exec.rs | 4 +- substrate/frame/contracts/src/lib.rs | 8 +- substrate/frame/contracts/src/tests.rs | 7 +- .../frame/contracts/src/tests/test_debug.rs | 2 +- substrate/frame/contracts/src/wasm/mod.rs | 77 +- substrate/frame/contracts/src/wasm/runtime.rs | 908 +++++++- substrate/frame/contracts/uapi/Cargo.toml | 25 - substrate/frame/contracts/uapi/src/flags.rs | 73 - substrate/frame/contracts/uapi/src/host.rs | 793 ------- .../frame/contracts/uapi/src/host/wasm32.rs | 811 ------- substrate/frame/contracts/uapi/src/lib.rs | 139 -- substrate/frame/conviction-voting/Cargo.toml | 19 +- .../frame/conviction-voting/src/tests.rs | 3 +- substrate/frame/core-fellowship/Cargo.toml | 21 +- substrate/frame/core-fellowship/src/tests.rs | 4 +- substrate/frame/democracy/Cargo.toml | 21 +- substrate/frame/democracy/src/tests.rs | 4 +- .../election-provider-multi-phase/Cargo.toml | 29 +- .../election-provider-multi-phase/src/lib.rs | 3 - .../election-provider-multi-phase/src/mock.rs | 18 +- .../src/signed.rs | 34 - .../test-staking-e2e/Cargo.toml | 5 +- .../test-staking-e2e/src/mock.rs | 1 - .../election-provider-support/Cargo.toml | 21 +- .../benchmarking/Cargo.toml | 17 +- .../solution-type/Cargo.toml | 7 +- .../solution-type/fuzzer/Cargo.toml | 9 +- .../election-provider-support/src/onchain.rs | 3 +- substrate/frame/elections-phragmen/Cargo.toml | 23 +- substrate/frame/elections-phragmen/src/lib.rs | 3 +- .../elections-phragmen/src/migrations/v4.rs | 4 +- .../elections-phragmen/src/migrations/v5.rs | 2 +- substrate/frame/examples/Cargo.toml | 20 +- substrate/frame/examples/basic/Cargo.toml | 21 +- substrate/frame/examples/basic/src/tests.rs | 3 +- .../frame/examples/default-config/Cargo.toml | 15 +- .../frame/examples/default-config/src/lib.rs | 5 - substrate/frame/examples/dev-mode/Cargo.toml | 19 +- .../frame/examples/dev-mode/src/tests.rs | 3 +- .../frame/examples/frame-crate/Cargo.toml | 9 +- .../frame/examples/kitchensink/Cargo.toml | 22 +- .../frame/examples/kitchensink/src/lib.rs | 5 +- .../frame/examples/offchain-worker/Cargo.toml | 19 +- .../examples/offchain-worker/src/tests.rs | 3 +- substrate/frame/examples/split/Cargo.toml | 19 +- substrate/frame/examples/src/lib.rs | 2 - substrate/frame/examples/tasks/Cargo.toml | 55 - .../frame/examples/tasks/src/benchmarking.rs | 42 - substrate/frame/examples/tasks/src/lib.rs | 78 - substrate/frame/examples/tasks/src/mock.rs | 43 - substrate/frame/examples/tasks/src/tests.rs | 127 -- substrate/frame/examples/tasks/src/weights.rs | 84 - substrate/frame/executive/Cargo.toml | 21 +- substrate/frame/executive/README.md | 6 +- substrate/frame/executive/src/lib.rs | 16 +- substrate/frame/fast-unstake/Cargo.toml | 23 +- substrate/frame/fast-unstake/src/mock.rs | 1 - substrate/frame/fast-unstake/src/types.rs | 1 - substrate/frame/glutton/Cargo.toml | 19 +- substrate/frame/glutton/src/mock.rs | 3 +- substrate/frame/grandpa/Cargo.toml | 21 +- substrate/frame/grandpa/src/migrations/v4.rs | 4 +- substrate/frame/grandpa/src/mock.rs | 4 +- substrate/frame/identity/Cargo.toml | 17 +- substrate/frame/identity/src/tests.rs | 3 +- substrate/frame/im-online/Cargo.toml | 17 +- substrate/frame/im-online/src/mock.rs | 3 +- substrate/frame/indices/Cargo.toml | 21 +- substrate/frame/indices/src/mock.rs | 6 +- .../Cargo.toml | 13 +- .../src/lib.rs | 3 +- substrate/frame/lottery/Cargo.toml | 15 +- substrate/frame/lottery/src/mock.rs | 3 +- substrate/frame/membership/Cargo.toml | 15 +- substrate/frame/membership/src/lib.rs | 3 +- .../frame/membership/src/migrations/v4.rs | 4 +- .../frame/merkle-mountain-range/Cargo.toml | 21 +- substrate/frame/message-queue/Cargo.toml | 27 +- .../frame/message-queue/src/benchmarking.rs | 7 +- .../message-queue/src/integration_test.rs | 85 +- substrate/frame/message-queue/src/lib.rs | 227 +- substrate/frame/message-queue/src/mock.rs | 34 +- .../frame/message-queue/src/mock_helpers.rs | 4 - substrate/frame/message-queue/src/tests.rs | 185 +- substrate/frame/mixnet/Cargo.toml | 7 +- substrate/frame/multisig/Cargo.toml | 17 +- .../frame/nft-fractionalization/Cargo.toml | 19 +- .../frame/nft-fractionalization/src/mock.rs | 4 +- substrate/frame/nfts/Cargo.toml | 19 +- substrate/frame/nfts/runtime-api/Cargo.toml | 7 +- .../src/features/create_delete_collection.rs | 6 - substrate/frame/nfts/src/mock.rs | 3 +- substrate/frame/nfts/src/tests.rs | 28 +- substrate/frame/nicks/Cargo.toml | 15 +- substrate/frame/nicks/src/lib.rs | 3 +- substrate/frame/nis/Cargo.toml | 19 +- substrate/frame/nis/src/mock.rs | 3 +- substrate/frame/node-authorization/Cargo.toml | 17 +- .../frame/node-authorization/src/mock.rs | 3 +- substrate/frame/nomination-pools/Cargo.toml | 21 +- .../nomination-pools/benchmarking/Cargo.toml | 29 +- .../nomination-pools/benchmarking/src/lib.rs | 41 +- .../nomination-pools/benchmarking/src/mock.rs | 4 +- .../frame/nomination-pools/fuzzer/Cargo.toml | 3 - .../nomination-pools/runtime-api/Cargo.toml | 13 +- substrate/frame/nomination-pools/src/lib.rs | 60 +- .../frame/nomination-pools/src/migration.rs | 77 - substrate/frame/nomination-pools/src/mock.rs | 3 +- substrate/frame/nomination-pools/src/tests.rs | 211 +- .../frame/nomination-pools/src/weights.rs | 523 +++-- .../nomination-pools/test-staking/Cargo.toml | 3 - .../nomination-pools/test-staking/src/mock.rs | 4 +- substrate/frame/offences/Cargo.toml | 19 +- .../frame/offences/benchmarking/Cargo.toml | 33 +- .../frame/offences/benchmarking/src/lib.rs | 235 ++- .../frame/offences/benchmarking/src/mock.rs | 4 +- substrate/frame/offences/src/mock.rs | 3 +- substrate/frame/paged-list/Cargo.toml | 21 +- substrate/frame/paged-list/fuzzer/Cargo.toml | 9 +- substrate/frame/paged-list/src/mock.rs | 6 +- substrate/frame/preimage/Cargo.toml | 21 +- substrate/frame/preimage/src/mock.rs | 3 +- substrate/frame/proxy/Cargo.toml | 17 +- substrate/frame/ranked-collective/Cargo.toml | 21 +- substrate/frame/ranked-collective/src/lib.rs | 25 +- .../frame/ranked-collective/src/tests.rs | 60 +- substrate/frame/recovery/Cargo.toml | 19 +- substrate/frame/recovery/src/mock.rs | 3 +- substrate/frame/referenda/Cargo.toml | 21 +- substrate/frame/referenda/src/mock.rs | 3 +- substrate/frame/remark/Cargo.toml | 23 +- substrate/frame/remark/src/mock.rs | 6 +- substrate/frame/root-offences/Cargo.toml | 19 +- substrate/frame/root-offences/src/mock.rs | 4 +- substrate/frame/root-testing/Cargo.toml | 17 +- substrate/frame/safe-mode/Cargo.toml | 21 +- substrate/frame/safe-mode/src/mock.rs | 3 +- substrate/frame/salary/Cargo.toml | 21 +- substrate/frame/salary/src/tests.rs | 4 +- substrate/frame/sassafras/Cargo.toml | 62 - substrate/frame/sassafras/README.md | 8 - substrate/frame/sassafras/src/benchmarking.rs | 272 --- .../src/data/25_tickets_100_auths.bin | Bin 24728 -> 0 bytes .../sassafras/src/data/benchmark-results.md | 99 - .../frame/sassafras/src/data/tickets-sort.md | 274 --- .../frame/sassafras/src/data/tickets-sort.png | Bin 33919 -> 0 bytes substrate/frame/sassafras/src/lib.rs | 1081 ---------- substrate/frame/sassafras/src/mock.rs | 343 --- substrate/frame/sassafras/src/tests.rs | 874 -------- substrate/frame/sassafras/src/weights.rs | 425 ---- substrate/frame/scheduler/Cargo.toml | 21 +- substrate/frame/scheduler/src/mock.rs | 4 +- substrate/frame/scored-pool/Cargo.toml | 15 +- substrate/frame/scored-pool/src/mock.rs | 3 +- substrate/frame/session/Cargo.toml | 23 +- .../frame/session/benchmarking/Cargo.toml | 21 +- .../frame/session/benchmarking/src/mock.rs | 4 +- .../frame/session/src/historical/offchain.rs | 10 +- substrate/frame/session/src/mock.rs | 3 +- substrate/frame/society/Cargo.toml | 19 +- substrate/frame/society/src/mock.rs | 3 +- substrate/frame/src/lib.rs | 36 +- substrate/frame/staking/Cargo.toml | 21 +- .../frame/staking/reward-curve/Cargo.toml | 7 +- substrate/frame/staking/reward-fn/Cargo.toml | 9 +- .../frame/staking/runtime-api/Cargo.toml | 7 +- substrate/frame/staking/src/benchmarking.rs | 36 +- substrate/frame/staking/src/mock.rs | 5 +- substrate/frame/staking/src/pallet/mod.rs | 69 +- substrate/frame/staking/src/tests.rs | 179 +- substrate/frame/staking/src/weights.rs | 419 ++-- .../frame/state-trie-migration/Cargo.toml | 25 +- .../frame/state-trie-migration/src/lib.rs | 3 +- substrate/frame/statement/Cargo.toml | 23 +- substrate/frame/statement/src/mock.rs | 3 +- substrate/frame/sudo/Cargo.toml | 17 +- substrate/frame/sudo/src/mock.rs | 6 +- substrate/frame/support/Cargo.toml | 43 +- substrate/frame/support/procedural/Cargo.toml | 10 +- .../src/construct_runtime/expand/mod.rs | 2 - .../src/construct_runtime/expand/task.rs | 131 -- .../procedural/src/construct_runtime/mod.rs | 59 +- .../procedural/src/construct_runtime/parse.rs | 8 +- .../support/procedural/src/derive_impl.rs | 48 +- substrate/frame/support/procedural/src/lib.rs | 104 +- .../procedural/src/pallet/expand/call.rs | 22 +- .../procedural/src/pallet/expand/error.rs | 37 +- .../procedural/src/pallet/expand/mod.rs | 3 - .../procedural/src/pallet/expand/tasks.rs | 267 --- .../src/pallet/expand/tt_default_parts.rs | 4 +- .../procedural/src/pallet/parse/call.rs | 41 +- .../procedural/src/pallet/parse/composite.rs | 9 +- .../procedural/src/pallet/parse/error.rs | 26 +- .../procedural/src/pallet/parse/mod.rs | 159 +- .../procedural/src/pallet/parse/tasks.rs | 968 --------- .../procedural/src/pallet/parse/tests/mod.rs | 264 --- .../src/pallet/parse/tests/tasks.rs | 240 --- .../frame/support/procedural/tools/Cargo.toml | 7 +- .../procedural/tools/derive/Cargo.toml | 5 +- substrate/frame/support/src/dispatch.rs | 5 +- substrate/frame/support/src/lib.rs | 209 +- substrate/frame/support/src/migrations.rs | 3 +- substrate/frame/support/src/storage/child.rs | 6 +- .../support/src/storage/generator/mod.rs | 2 - substrate/frame/support/src/storage/mod.rs | 6 +- substrate/frame/support/src/tests/mod.rs | 57 +- substrate/frame/support/src/tests/tasks.rs | 62 - substrate/frame/support/src/traits.rs | 3 - .../frame/support/src/traits/messages.rs | 2 - substrate/frame/support/src/traits/tasks.rs | 87 - .../src/traits/tokens/fungible/regular.rs | 44 - .../src/traits/tokens/fungibles/regular.rs | 63 - substrate/frame/support/test/Cargo.toml | 39 +- .../support/test/compile_pass/Cargo.toml | 15 +- .../support/test/compile_pass/src/lib.rs | 3 +- .../frame/support/test/pallet/Cargo.toml | 13 +- substrate/frame/support/test/src/lib.rs | 2 - .../support/test/stg_frame_crate/Cargo.toml | 9 +- .../deprecated_where_block.stderr | 9 +- .../generics_in_invalid_module.stderr | 2 +- .../invalid_module_details_keyword.stderr | 2 +- .../invalid_module_entry.stderr | 2 +- .../number_of_pallets_exceeds_tuple_size.rs | 3 +- ...umber_of_pallets_exceeds_tuple_size.stderr | 62 +- .../pallet_error_too_large.rs | 3 +- .../pallet_error_too_large.stderr | 18 +- .../undefined_call_part.rs | 3 +- .../undefined_call_part.stderr | 14 +- .../undefined_event_part.rs | 3 +- .../undefined_event_part.stderr | 30 +- .../undefined_genesis_config_part.rs | 3 +- .../undefined_genesis_config_part.stderr | 30 +- .../undefined_inherent_part.rs | 3 +- .../undefined_inherent_part.stderr | 94 +- .../undefined_origin_part.rs | 3 +- .../undefined_origin_part.stderr | 30 +- .../undefined_validate_unsigned_part.rs | 3 +- .../undefined_validate_unsigned_part.stderr | 58 +- .../frame/support/test/tests/derive_impl.rs | 52 - ...e_type_fails_when_type_not_in_scope.stderr | 6 +- .../inject_runtime_type_invalid.stderr | 2 +- substrate/frame/support/test/tests/pallet.rs | 184 +- .../support/test/tests/pallet_instance.rs | 2 - .../test/tests/pallet_outer_enums_explicit.rs | 2 - .../test/tests/pallet_outer_enums_implicit.rs | 2 - .../call_argument_invalid_bound.stderr | 1 - .../call_argument_invalid_bound_2.stderr | 7 +- .../call_argument_invalid_bound_3.stderr | 1 - .../pallet_ui/call_invalid_origin_type.stderr | 2 +- .../tests/pallet_ui/call_missing_index.stderr | 1 - .../call_weight_argument_has_suffix.stderr | 1 - .../call_weight_const_warning.stderr | 1 - .../call_weight_const_warning_twice.stderr | 1 - .../call_weight_inherited_invalid3.stderr | 1 - .../call_weight_unchecked_warning.stderr | 1 - ...mposite_enum_unsupported_identifier.stderr | 2 +- .../pallet_ui/deprecated_store_attr.stderr | 1 - .../dev_mode_without_arg_call_index.stderr | 1 - ...ev_mode_without_arg_max_encoded_len.stderr | 12 +- .../error_does_not_derive_pallet_error.stderr | 7 +- .../tests/pallet_ui/pass/dev_mode_valid.rs | 3 +- .../pallet_ui/pass/no_std_genesis_config.rs | 3 +- .../test/tests/pallet_ui/pass/task_valid.rs | 43 - ...age_ensure_span_are_ok_on_wrong_gen.stderr | 84 +- ...re_span_are_ok_on_wrong_gen_unnamed.stderr | 84 +- .../pallet_ui/storage_info_unsatisfied.stderr | 11 +- .../storage_info_unsatisfied_nmap.stderr | 11 +- .../pallet_ui/store_trait_leak_private.stderr | 1 - .../task_can_only_be_attached_to_impl.stderr | 5 - .../pallet_ui/task_condition_invalid_arg.rs | 42 - .../task_condition_invalid_arg.stderr | 23 - .../tests/pallet_ui/task_invalid_condition.rs | 42 - .../pallet_ui/task_invalid_condition.stderr | 28 - .../tests/pallet_ui/task_invalid_index.rs | 39 - .../tests/pallet_ui/task_invalid_index.stderr | 5 - .../test/tests/pallet_ui/task_invalid_list.rs | 42 - .../tests/pallet_ui/task_invalid_list.stderr | 20 - .../tests/pallet_ui/task_invalid_weight.rs | 42 - .../pallet_ui/task_invalid_weight.stderr | 28 - .../tests/pallet_ui/task_missing_condition.rs | 39 - .../pallet_ui/task_missing_condition.stderr | 5 - .../tests/pallet_ui/task_missing_index.rs | 38 - .../tests/pallet_ui/task_missing_index.stderr | 5 - .../test/tests/pallet_ui/task_missing_list.rs | 40 - .../tests/pallet_ui/task_missing_list.stderr | 5 - .../tests/pallet_ui/task_missing_weight.rs | 41 - .../pallet_ui/task_missing_weight.stderr | 5 - .../support/test/tests/runtime_metadata.rs | 3 +- .../support/test/tests/storage_layers.rs | 5 +- substrate/frame/system/Cargo.toml | 18 +- substrate/frame/system/benches/bench.rs | 7 +- .../frame/system/benchmarking/Cargo.toml | 17 +- .../frame/system/benchmarking/src/mock.rs | 2 - .../frame/system/rpc/runtime-api/Cargo.toml | 9 +- substrate/frame/system/src/lib.rs | 133 +- substrate/frame/system/src/mock.rs | 3 +- substrate/frame/timestamp/Cargo.toml | 23 +- substrate/frame/timestamp/src/mock.rs | 3 +- substrate/frame/tips/Cargo.toml | 23 +- substrate/frame/tips/src/migrations/v4.rs | 4 +- substrate/frame/tips/src/tests.rs | 4 +- .../frame/transaction-payment/Cargo.toml | 19 +- .../asset-conversion-tx-payment/Cargo.toml | 23 +- .../asset-conversion-tx-payment/src/mock.rs | 2 - .../asset-tx-payment/Cargo.toml | 23 +- .../asset-tx-payment/src/mock.rs | 2 - .../frame/transaction-payment/rpc/Cargo.toml | 5 +- .../rpc/runtime-api/Cargo.toml | 13 +- .../skip-feeless-payment/Cargo.toml | 13 +- .../frame/transaction-payment/src/mock.rs | 2 - .../frame/transaction-storage/Cargo.toml | 29 +- substrate/frame/treasury/Cargo.toml | 21 +- substrate/frame/treasury/src/benchmarking.rs | 10 +- substrate/frame/treasury/src/tests.rs | 3 +- substrate/frame/try-runtime/Cargo.toml | 17 +- substrate/frame/tx-pause/Cargo.toml | 19 +- substrate/frame/tx-pause/src/mock.rs | 3 +- substrate/frame/uniques/Cargo.toml | 15 +- substrate/frame/uniques/src/migration.rs | 65 +- substrate/frame/uniques/src/mock.rs | 3 +- substrate/frame/utility/Cargo.toml | 19 +- substrate/frame/utility/src/tests.rs | 3 +- substrate/frame/vesting/Cargo.toml | 17 +- substrate/frame/vesting/src/benchmarking.rs | 8 +- substrate/frame/vesting/src/lib.rs | 13 +- substrate/frame/vesting/src/mock.rs | 4 +- substrate/frame/whitelist/Cargo.toml | 17 +- substrate/frame/whitelist/src/mock.rs | 3 +- substrate/primitives/api/Cargo.toml | 11 +- .../primitives/api/proc-macro/Cargo.toml | 11 +- .../api/proc-macro/src/decl_runtime_apis.rs | 2 +- .../api/proc-macro/src/impl_runtime_apis.rs | 9 +- substrate/primitives/api/src/lib.rs | 16 +- substrate/primitives/api/test/Cargo.toml | 3 - .../ui/impl_incorrect_method_signature.stderr | 18 - ...reference_in_impl_runtime_apis_call.stderr | 18 - .../primitives/application-crypto/Cargo.toml | 17 +- .../application-crypto/test/Cargo.toml | 7 +- substrate/primitives/arithmetic/Cargo.toml | 15 +- .../primitives/arithmetic/fuzzer/Cargo.toml | 3 - .../primitives/authority-discovery/Cargo.toml | 13 +- substrate/primitives/block-builder/Cargo.toml | 15 +- substrate/primitives/blockchain/Cargo.toml | 3 - .../primitives/consensus/aura/Cargo.toml | 19 +- .../primitives/consensus/babe/Cargo.toml | 23 +- .../primitives/consensus/babe/src/lib.rs | 2 +- .../primitives/consensus/beefy/Cargo.toml | 7 +- .../primitives/consensus/common/Cargo.toml | 3 - .../primitives/consensus/grandpa/Cargo.toml | 19 +- substrate/primitives/consensus/pow/Cargo.toml | 13 +- .../primitives/consensus/sassafras/Cargo.toml | 19 +- .../primitives/consensus/sassafras/README.md | 12 +- .../consensus/sassafras/src/digests.rs | 6 +- .../primitives/consensus/sassafras/src/lib.rs | 38 +- .../consensus/sassafras/src/ticket.rs | 43 +- .../primitives/consensus/sassafras/src/vrf.rs | 32 +- .../primitives/consensus/slots/Cargo.toml | 13 +- substrate/primitives/core/Cargo.toml | 31 +- substrate/primitives/core/fuzz/Cargo.toml | 3 - substrate/primitives/core/hashing/Cargo.toml | 5 +- .../core/hashing/proc-macro/Cargo.toml | 7 +- substrate/primitives/core/src/bandersnatch.rs | 406 ++-- .../primitives/core/src/const_hex2array.rs | 162 -- substrate/primitives/core/src/crypto.rs | 8 +- substrate/primitives/core/src/lib.rs | 1 - substrate/primitives/core/src/sr25519.rs | 52 +- substrate/primitives/core/src/traits.rs | 1 + .../primitives/crypto/ec-utils/Cargo.toml | 17 +- substrate/primitives/database/Cargo.toml | 3 - substrate/primitives/debug-derive/Cargo.toml | 6 +- substrate/primitives/externalities/Cargo.toml | 11 +- .../primitives/genesis-builder/Cargo.toml | 13 +- substrate/primitives/inherents/Cargo.toml | 9 +- substrate/primitives/io/Cargo.toml | 31 +- substrate/primitives/keyring/Cargo.toml | 6 +- .../primitives/keyring/src/bandersnatch.rs | 69 +- substrate/primitives/keyring/src/ed25519.rs | 78 +- substrate/primitives/keyring/src/sr25519.rs | 76 +- substrate/primitives/keystore/Cargo.toml | 17 +- substrate/primitives/keystore/src/lib.rs | 24 +- substrate/primitives/keystore/src/testing.rs | 31 +- .../maybe-compressed-blob/Cargo.toml | 3 - .../merkle-mountain-range/Cargo.toml | 19 +- substrate/primitives/metadata-ir/Cargo.toml | 9 +- substrate/primitives/mixnet/Cargo.toml | 5 +- .../primitives/npos-elections/Cargo.toml | 15 +- .../npos-elections/fuzzer/Cargo.toml | 7 +- .../primitives/npos-elections/src/lib.rs | 5 +- substrate/primitives/offchain/Cargo.toml | 13 +- substrate/primitives/panic-handler/Cargo.toml | 3 - substrate/primitives/rpc/Cargo.toml | 5 +- .../primitives/runtime-interface/Cargo.toml | 13 +- .../runtime-interface/proc-macro/Cargo.toml | 8 +- .../proc-macro/src/runtime_interface/mod.rs | 6 - .../runtime-interface/src/pass_by.rs | 2 +- .../test-wasm-deprecated/Cargo.toml | 11 +- .../runtime-interface/test-wasm/Cargo.toml | 13 +- .../runtime-interface/test/Cargo.toml | 5 +- substrate/primitives/runtime/Cargo.toml | 22 +- .../runtime/src/generic/checked_extrinsic.rs | 8 +- .../src/generic/unchecked_extrinsic.rs | 25 +- .../runtime/src/offchain/storage_lock.rs | 2 +- substrate/primitives/session/Cargo.toml | 15 +- substrate/primitives/staking/Cargo.toml | 15 +- substrate/primitives/state-machine/Cargo.toml | 15 +- substrate/primitives/state-machine/src/lib.rs | 6 +- .../src/overlayed_changes/changeset.rs | 2 +- .../src/overlayed_changes/mod.rs | 10 +- .../state-machine/src/trie_backend.rs | 150 +- .../state-machine/src/trie_backend_essence.rs | 154 +- .../primitives/statement-store/Cargo.toml | 21 +- substrate/primitives/std/Cargo.toml | 5 +- substrate/primitives/storage/Cargo.toml | 13 +- .../primitives/test-primitives/Cargo.toml | 15 +- substrate/primitives/timestamp/Cargo.toml | 11 +- substrate/primitives/tracing/Cargo.toml | 11 +- .../primitives/transaction-pool/Cargo.toml | 11 +- .../transaction-storage-proof/Cargo.toml | 15 +- substrate/primitives/trie/Cargo.toml | 13 +- .../primitives/trie/src/cache/shared_cache.rs | 26 +- substrate/primitives/trie/src/lib.rs | 26 - .../trie/src/proof_size_extension.rs | 39 - substrate/primitives/trie/src/recorder.rs | 48 +- substrate/primitives/version/Cargo.toml | 15 +- .../primitives/version/proc-macro/Cargo.toml | 7 +- .../primitives/wasm-interface/Cargo.toml | 11 +- substrate/primitives/weights/Cargo.toml | 26 +- substrate/primitives/weights/src/lib.rs | 6 +- substrate/primitives/weights/src/weight_v2.rs | 1 - substrate/scripts/ci/deny.toml | 134 +- .../ci/node-template-release/Cargo.toml | 5 +- substrate/src/lib.rs | 242 +++ substrate/test-utils/Cargo.toml | 5 +- substrate/test-utils/cli/Cargo.toml | 5 +- substrate/test-utils/client/Cargo.toml | 9 +- substrate/test-utils/client/src/lib.rs | 3 +- substrate/test-utils/runtime/Cargo.toml | 57 +- .../test-utils/runtime/client/Cargo.toml | 3 - substrate/test-utils/runtime/src/lib.rs | 3 +- .../runtime/transaction-pool/Cargo.toml | 3 - substrate/utils/binary-merkle-tree/Cargo.toml | 9 +- substrate/utils/build-script-utils/Cargo.toml | 3 - substrate/utils/fork-tree/Cargo.toml | 3 - .../utils/frame/benchmarking-cli/Cargo.toml | 19 +- .../frame/frame-utilities-cli/Cargo.toml | 5 +- .../utils/frame/generate-bags/Cargo.toml | 3 - .../generate-bags/node-runtime/Cargo.toml | 5 +- .../frame/remote-externalities/Cargo.toml | 5 +- .../frame/remote-externalities/src/lib.rs | 193 +- substrate/utils/frame/rpc/client/Cargo.toml | 3 - .../rpc/state-trie-migration-rpc/Cargo.toml | 5 +- substrate/utils/frame/rpc/support/Cargo.toml | 5 +- substrate/utils/frame/rpc/support/src/lib.rs | 4 +- substrate/utils/frame/rpc/system/Cargo.toml | 5 +- .../utils/frame/try-runtime/cli/Cargo.toml | 11 +- substrate/utils/prometheus/Cargo.toml | 3 - substrate/utils/wasm-builder/Cargo.toml | 6 +- substrate/utils/wasm-builder/README.md | 86 + substrate/utils/wasm-builder/src/lib.rs | 35 - .../utils/wasm-builder/src/prerequisites.rs | 192 +- substrate/utils/wasm-builder/src/version.rs | 17 - .../utils/wasm-builder/src/wasm_project.rs | 20 - 1733 files changed, 61137 insertions(+), 56609 deletions(-) delete mode 100644 .config/taplo.toml create mode 100644 .github/pr-custom-review.yml delete mode 100644 .github/runtime_specs/rococo.json delete mode 100644 .github/runtime_specs/westend.json delete mode 100755 .github/scripts/check-runtime.py delete mode 100644 .github/workflows/check-runtimes.yml delete mode 100644 .github/workflows/notif-burnin-label.yml create mode 100644 .github/workflows/pr-custom-review.yml delete mode 100644 .github/workflows/release-10_rc-automation.yml delete mode 100644 .github/workflows/release-99_notif-published.yml delete mode 100755 .gitlab/rust-features.sh delete mode 100644 .prdoc.toml delete mode 100644 bridges/modules/xcm-bridge-hub/Cargo.toml delete mode 100644 bridges/modules/xcm-bridge-hub/src/exporter.rs delete mode 100644 bridges/modules/xcm-bridge-hub/src/lib.rs delete mode 100644 bridges/modules/xcm-bridge-hub/src/mock.rs delete mode 100644 bridges/primitives/xcm-bridge-hub/Cargo.toml delete mode 100644 bridges/primitives/xcm-bridge-hub/src/lib.rs delete mode 100644 bridges/zombienet/helpers/native-assets-balance-increased.js delete mode 100644 cumulus/pallets/parachain-system/src/validate_block/trie_recorder.rs create mode 100644 cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/0_init.yml create mode 100644 cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/1_dmp.yml create mode 100644 cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/2_ump.yml create mode 100644 cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/3_force_hrmp-open-channels.yml create mode 100644 cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/4_hrmp.yml create mode 100644 cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/config.toml create mode 100644 cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/0_init.yml create mode 100644 cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/1_dmp.yml create mode 100644 cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/2_ump.yml create mode 100644 cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/3_force_hrmp-open-channels.yml create mode 100644 cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/4_hrmp.yml create mode 100644 cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/config.toml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/README.md create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/0_init.yml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/1_teleport.yml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/2_reserve.yml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/3_hrmp-open-channels.yml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/0_join_alliance_fails.yml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/1_init_alliance.yml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/2_join_alliance_fails.yml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/3_kick_member.yml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/2_opengov/0_assethub.yml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/3_fellowship/0_init.yml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/3_fellowship/1_whitelist_call.yml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/3_fellowship/2_assethub.yml create mode 100644 cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/config.toml delete mode 100644 cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/Cargo.toml delete mode 100644 cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/src/genesis.rs delete mode 100644 cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/src/lib.rs delete mode 100644 cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/fellowship_treasury.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/Cargo.toml rename substrate/frame/support/test/tests/pallet_ui/task_can_only_be_attached_to_impl.rs => cumulus/parachains/runtimes/assets/asset-hub-kusama/build.rs (63%) create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/lib.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/block_weights.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_dmp_queue.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_parachain_system.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_xcmp_queue.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/extrinsic_weights.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/frame_system.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/mod.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_asset_conversion.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_assets_foreign.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_assets_local.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_assets_pool.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_balances.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_collator_selection.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_message_queue.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_multisig.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_nft_fractionalization.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_nfts.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_proxy.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_session.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_timestamp.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_uniques.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_utility.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_xcm.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/paritydb_weights.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/rocksdb_weights.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/mod.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_generic.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/src/xcm_config.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-kusama/tests/tests.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/Cargo.toml rename substrate/frame/contracts/fixtures/contracts/common/src/lib.rs => cumulus/parachains/runtimes/assets/asset-hub-polkadot/build.rs (60%) create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/lib.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/block_weights.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_dmp_queue.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_parachain_system.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/extrinsic_weights.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/frame_system.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/mod.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_assets_foreign.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_assets_local.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_balances.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_collator_selection.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_message_queue.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_multisig.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_nfts.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_proxy.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_session.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_timestamp.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_uniques.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_utility.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_xcm.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/paritydb_weights.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/rocksdb_weights.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/mod.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_generic.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/xcm_config.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-polkadot/tests/tests.rs create mode 100644 cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/cumulus_pallet_dmp_queue.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/Cargo.toml create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/build.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/lib.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/block_weights.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_dmp_queue.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_parachain_system.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_xcmp_queue.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/extrinsic_weights.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/frame_system.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/mod.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_balances.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_collator_selection.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_message_queue.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_multisig.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_session.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_timestamp.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_utility.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_xcm.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/paritydb_weights.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/rocksdb_weights.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/mod.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_generic.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/xcm_config.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/tests/tests.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/Cargo.toml create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/build.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/lib.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/block_weights.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_dmp_queue.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_parachain_system.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/extrinsic_weights.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/frame_system.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/mod.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_balances.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_collator_selection.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_message_queue.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_multisig.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_session.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_timestamp.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_utility.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_xcm.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/paritydb_weights.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/rocksdb_weights.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/mod.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_generic.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/xcm_config.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/tests/tests.rs delete mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs rename cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/{pallet_bridge_messages_rococo_to_westend.rs => pallet_bridge_messages.rs} (90%) delete mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_messages_rococo_to_rococo_bulletin.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/cumulus_pallet_dmp_queue.rs create mode 100644 cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases.rs delete mode 100644 cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_grandpa_chain.rs delete mode 100644 cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_parachain.rs delete mode 100644 cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs delete mode 100644 cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/mod.rs delete mode 100644 cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_grandpa_chain.rs delete mode 100644 cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_parachain.rs delete mode 100644 cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/mod.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/Cargo.toml create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/build.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/mod.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/origins.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/tracks.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/migration.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/mod.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/origins.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/tracks.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/impls.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/lib.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/block_weights.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_dmp_queue.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_parachain_system.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/extrinsic_weights.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/frame_system.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/mod.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_alliance.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_balances.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_collator_selection.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_collective.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_collective_content.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_core_fellowship_ambassador_core.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_core_fellowship_fellowship_core.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_message_queue.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_multisig.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_preimage.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_proxy.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_ranked_collective_ambassador_collective.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_ranked_collective_fellowship_collective.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_referenda_ambassador_referenda.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_referenda_fellowship_referenda.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_salary_ambassador_salary.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_salary_fellowship_salary.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_scheduler.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_session.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_timestamp.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_utility.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_xcm.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/paritydb_weights.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/rocksdb_weights.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-polkadot/src/xcm_config.rs create mode 100644 cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/cumulus_pallet_dmp_queue.rs delete mode 100644 cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_asset_rate.rs delete mode 100644 cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_treasury.rs create mode 100644 cumulus/parachains/runtimes/glutton/glutton-kusama/Cargo.toml rename substrate/frame/contracts/fixtures/contracts/dummy.rs => cumulus/parachains/runtimes/glutton/glutton-kusama/build.rs (79%) create mode 100644 cumulus/parachains/runtimes/glutton/glutton-kusama/src/lib.rs create mode 100644 cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/cumulus_pallet_parachain_system.rs create mode 100644 cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/frame_system.rs create mode 100644 cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/mod.rs create mode 100644 cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/pallet_glutton.rs create mode 100644 cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/pallet_message_queue.rs create mode 100644 cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/pallet_timestamp.rs create mode 100644 cumulus/parachains/runtimes/glutton/glutton-kusama/src/xcm_config.rs create mode 100644 cumulus/parachains/testnets-common/Cargo.toml create mode 100644 cumulus/parachains/testnets-common/src/lib.rs create mode 100644 cumulus/parachains/testnets-common/src/rococo.rs create mode 100644 cumulus/parachains/testnets-common/src/westend.rs rename substrate/frame/contracts/uapi/src/host/riscv32.rs => cumulus/parachains/testnets-common/src/wococo.rs (77%) delete mode 100644 cumulus/primitives/proof-size-hostfunction/Cargo.toml delete mode 100644 cumulus/primitives/proof-size-hostfunction/src/lib.rs create mode 100755 cumulus/scripts/create_bridge_hub_kusama_spec.sh create mode 100755 cumulus/scripts/create_bridge_hub_polkadot_spec.sh create mode 100755 cumulus/scripts/parachains_integration_tests.sh create mode 100644 cumulus/zombienet/examples/bridge_hub_kusama_local_network.toml create mode 100644 cumulus/zombienet/examples/bridge_hub_polkadot_local_network.toml rename cumulus/zombienet/examples/{asset_hub_westend_local_network.toml => statemine_kusama_local_network.toml} (71%) rename docs/{contributor => }/CODE_OF_CONDUCT.md (100%) rename docs/{contributor => }/CONTRIBUTING.md (90%) rename docs/{contributor => }/DEPRECATION_CHECKLIST.md (90%) rename docs/{contributor => }/DOCUMENTATION_GUIDELINES.md (99%) rename docs/{contributor => }/PULL_REQUEST_TEMPLATE.md (96%) rename docs/{contributor => }/SECURITY.md (100%) rename docs/{contributor => }/STYLE_GUIDE.md (83%) rename docs/{contributor => }/container.md (100%) delete mode 100644 docs/contributor/prdoc.md rename docs/{contributor => }/docker.md (100%) rename docs/{contributor => }/markdown_linting.md (100%) delete mode 100644 docs/mermaid/IA.mmd delete mode 100644 docs/mermaid/extrinsics.mmd delete mode 100644 docs/mermaid/polkadot_sdk_parachain.mmd delete mode 100644 docs/mermaid/polkadot_sdk_polkadot.mmd delete mode 100644 docs/mermaid/polkadot_sdk_substrate.mmd delete mode 100644 docs/mermaid/state.mmd delete mode 100644 docs/mermaid/stf.mmd delete mode 100644 docs/mermaid/stf_simple.mmd delete mode 100644 docs/mermaid/substrate_dev.mmd delete mode 100644 docs/sdk/Cargo.toml delete mode 100644 docs/sdk/headers/toc.html delete mode 100644 docs/sdk/src/guides/changing_consensus.rs delete mode 100644 docs/sdk/src/guides/cumulus_enabled_parachain.rs delete mode 100644 docs/sdk/src/guides/mod.rs delete mode 100644 docs/sdk/src/guides/xcm_enabled_parachain.rs delete mode 100644 docs/sdk/src/guides/your_first_node.rs delete mode 100644 docs/sdk/src/guides/your_first_pallet/mod.rs delete mode 100644 docs/sdk/src/guides/your_first_pallet/with_event.rs delete mode 100644 docs/sdk/src/guides/your_first_runtime.rs delete mode 100644 docs/sdk/src/lib.rs delete mode 100644 docs/sdk/src/meta_contributing.rs delete mode 100644 docs/sdk/src/polkadot_sdk/cumulus.rs delete mode 100644 docs/sdk/src/polkadot_sdk/frame_runtime.rs delete mode 100644 docs/sdk/src/polkadot_sdk/mod.rs delete mode 100644 docs/sdk/src/polkadot_sdk/polkadot.rs delete mode 100644 docs/sdk/src/polkadot_sdk/smart_contracts.rs delete mode 100644 docs/sdk/src/polkadot_sdk/substrate.rs delete mode 100644 docs/sdk/src/polkadot_sdk/templates.rs delete mode 100644 docs/sdk/src/polkadot_sdk/xcm.rs delete mode 100644 docs/sdk/src/reference_docs/blockchain_scalibility.rs delete mode 100644 docs/sdk/src/reference_docs/blockchain_state_machines.rs delete mode 100644 docs/sdk/src/reference_docs/chain_spec_genesis.rs delete mode 100644 docs/sdk/src/reference_docs/cli.rs delete mode 100644 docs/sdk/src/reference_docs/consensus_swapping.rs delete mode 100644 docs/sdk/src/reference_docs/extrinsic_encoding.rs delete mode 100644 docs/sdk/src/reference_docs/fee_less_runtime.rs delete mode 100644 docs/sdk/src/reference_docs/frame_benchmarking_weight.rs delete mode 100644 docs/sdk/src/reference_docs/frame_composite_enums.rs delete mode 100644 docs/sdk/src/reference_docs/frame_currency.rs delete mode 100644 docs/sdk/src/reference_docs/frame_origin.rs delete mode 100644 docs/sdk/src/reference_docs/frame_runtime_migration.rs delete mode 100644 docs/sdk/src/reference_docs/frame_system_accounts.rs delete mode 100644 docs/sdk/src/reference_docs/glossary.rs delete mode 100644 docs/sdk/src/reference_docs/light_nodes.rs delete mode 100644 docs/sdk/src/reference_docs/metadata.rs delete mode 100644 docs/sdk/src/reference_docs/mod.rs delete mode 100644 docs/sdk/src/reference_docs/runtime_vs_smart_contract.rs delete mode 100644 docs/sdk/src/reference_docs/safe_defensive_programming.rs delete mode 100644 docs/sdk/src/reference_docs/trait_based_programming.rs delete mode 100644 docs/sdk/src/reference_docs/transaction_extensions.rs delete mode 100644 docs/sdk/src/reference_docs/wasm_memory.rs delete mode 100644 docs/sdk/src/reference_docs/wasm_meta_protocol.rs delete mode 100644 polkadot/node/core/approval-voting/src/approval_db/common/migration_helpers.rs delete mode 100644 polkadot/node/core/approval-voting/src/approval_db/common/mod.rs delete mode 100644 polkadot/node/core/approval-voting/src/approval_db/v3/migration_helpers.rs delete mode 100644 polkadot/node/core/approval-voting/src/approval_db/v3/mod.rs delete mode 100644 polkadot/node/core/approval-voting/src/approval_db/v3/tests.rs delete mode 100644 polkadot/node/core/pvf/README.md rename polkadot/node/core/pvf/common/src/{executor_interface.rs => executor_intf.rs} (98%) delete mode 100644 polkadot/node/core/pvf/common/src/worker/security/change_root.rs rename polkadot/node/core/pvf/src/execute/{worker_interface.rs => worker_intf.rs} (96%) rename polkadot/node/core/pvf/src/prepare/{worker_interface.rs => worker_intf.rs} (99%) rename polkadot/node/core/pvf/src/{worker_interface.rs => worker_intf.rs} (82%) create mode 100644 polkadot/node/core/pvf/tests/README.md delete mode 100644 polkadot/node/malus/src/variants/dispute_finalized_candidates.rs delete mode 100644 polkadot/node/subsystem-bench/Cargo.toml delete mode 100644 polkadot/node/subsystem-bench/README.md delete mode 100644 polkadot/node/subsystem-bench/examples/availability_read.yaml delete mode 100644 polkadot/node/subsystem-bench/grafana/availability-read.json delete mode 100644 polkadot/node/subsystem-bench/grafana/task-cpu-usage.json delete mode 100644 polkadot/node/subsystem-bench/src/availability/cli.rs delete mode 100644 polkadot/node/subsystem-bench/src/availability/mod.rs delete mode 100644 polkadot/node/subsystem-bench/src/cli.rs delete mode 100644 polkadot/node/subsystem-bench/src/core/configuration.rs delete mode 100644 polkadot/node/subsystem-bench/src/core/display.rs delete mode 100644 polkadot/node/subsystem-bench/src/core/environment.rs delete mode 100644 polkadot/node/subsystem-bench/src/core/keyring.rs delete mode 100644 polkadot/node/subsystem-bench/src/core/mock/av_store.rs delete mode 100644 polkadot/node/subsystem-bench/src/core/mock/dummy.rs delete mode 100644 polkadot/node/subsystem-bench/src/core/mock/mod.rs delete mode 100644 polkadot/node/subsystem-bench/src/core/mock/network_bridge.rs delete mode 100644 polkadot/node/subsystem-bench/src/core/mock/runtime_api.rs delete mode 100644 polkadot/node/subsystem-bench/src/core/mod.rs delete mode 100644 polkadot/node/subsystem-bench/src/core/network.rs delete mode 100644 polkadot/node/subsystem-bench/src/subsystem-bench.rs delete mode 100644 polkadot/runtime/parachains/src/configuration/migration/v11.rs delete mode 100644 polkadot/xcm/xcm-builder/src/fungible_adapter.rs delete mode 100644 polkadot/zombienet_tests/functional/0007-dispute-freshly-finalized.toml delete mode 100644 polkadot/zombienet_tests/functional/0007-dispute-freshly-finalized.zndsl delete mode 100644 polkadot/zombienet_tests/functional/0008-dispute-old-finalized.toml delete mode 100644 polkadot/zombienet_tests/functional/0008-dispute-old-finalized.zndsl delete mode 100644 polkadot/zombienet_tests/functional/0009-approval-voting-coalescing.toml delete mode 100644 polkadot/zombienet_tests/functional/0009-approval-voting-coalescing.zndsl delete mode 100755 polkadot/zombienet_tests/misc/0002-update-cmd.sh delete mode 100644 prdoc/.template.prdoc delete mode 100644 prdoc/1.3.0/pr_1255.prdoc delete mode 100644 prdoc/1.3.0/readme.md delete mode 100644 prdoc/1.4.0/readme.md delete mode 100644 prdoc/1.5.0/pr_1370_special.prdoc delete mode 100644 prdoc/1.5.0/pr_1497_special.prdoc delete mode 100644 prdoc/1.5.0/pr_1918_special.prdoc delete mode 100644 prdoc/1.5.0/pr_1946_prdoc_new_schema.prdoc delete mode 100644 prdoc/1.5.0/pr_1985_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2001_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2058_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2142.prdoc delete mode 100644 prdoc/1.5.0/pr_2167_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2174_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2182_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2184_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2221_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2250_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2265_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2300_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2351_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2354_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2361_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2368_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2369_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2377_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2378_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2380_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2381_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2385_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2388.prdoc delete mode 100644 prdoc/1.5.0/pr_2397_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2406_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2411_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2413_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2426_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2435_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2442_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2446_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2450_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2455_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2457_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2459_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2461_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2462_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2463_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2474_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2483_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2486.prdoc delete mode 100644 prdoc/1.5.0/pr_2487_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2501_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2509_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2515_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2516_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2521_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2526_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2552_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2555_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2572_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2579_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2581_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2591.prdoc delete mode 100644 prdoc/1.5.0/pr_2602_special.prdoc delete mode 100644 prdoc/1.5.0/pr_2625_special.prdoc delete mode 100644 prdoc/1.5.0/readme.md rename prdoc/{1.4.0 => }/pr_1178.prdoc (96%) delete mode 100644 prdoc/pr_1191.prdoc rename prdoc/{1.3.0 => }/pr_1234.prdoc (83%) rename prdoc/{1.4.0 => }/pr_1246.prdoc (87%) create mode 100644 prdoc/pr_1255.prdoc rename prdoc/{1.4.0 => }/pr_1256.prdoc (100%) delete mode 100644 prdoc/pr_1343.prdoc rename prdoc/{1.5.0 => }/pr_1408_prodc-introduction.prdoc (76%) delete mode 100644 prdoc/pr_1454.prdoc rename prdoc/{1.4.0 => }/pr_1805.prdoc (87%) rename prdoc/{1.3.0 => }/pr_1818.prdoc (63%) rename prdoc/{1.3.0 => }/pr_1873.prdoc (66%) rename prdoc/{1.3.0 => }/pr_1913.prdoc (87%) rename prdoc/{1.3.0 => }/pr_1921.prdoc (67%) rename prdoc/{1.4.0 => }/pr_1926.prdoc (59%) rename prdoc/{1.4.0 => }/pr_2086.prdoc (70%) rename prdoc/{1.4.0 => }/pr_2107.prdoc (91%) rename prdoc/{1.4.0 => }/pr_2165.prdoc (80%) rename prdoc/{1.5.0 => }/pr_2253.prdoc (92%) delete mode 100644 prdoc/pr_2331.prdoc delete mode 100644 prdoc/pr_2403.prdoc delete mode 100644 prdoc/pr_2481.prdoc delete mode 100644 prdoc/pr_2532.prdoc delete mode 100644 prdoc/pr_2597.prdoc delete mode 100644 prdoc/pr_2656.prdoc delete mode 100644 prdoc/pr_2663-fix-could-not-create-temporary-drectory.prdoc delete mode 100644 prdoc/pr_2684.prdoc delete mode 100644 prdoc/pr_2687.prdoc delete mode 100644 prdoc/schema_user.json delete mode 100755 scripts/release/build-changelogs.sh delete mode 100644 scripts/release/templates/audience.md.tera delete mode 100644 scripts/release/templates/changelog.md.tera create mode 100644 substrate/Cargo.toml create mode 100644 substrate/bin/node/executor/Cargo.toml rename substrate/bin/node/{cli/benches/executor.rs => executor/benches/bench.rs} (69%) create mode 100644 substrate/bin/node/executor/src/lib.rs rename substrate/bin/node/{cli => executor}/tests/basic.rs (94%) rename substrate/bin/node/{cli => executor}/tests/common.rs (91%) rename substrate/bin/node/{cli => executor}/tests/fees.rs (95%) rename substrate/bin/node/{cli => executor}/tests/res/default_genesis_config.json (100%) rename substrate/bin/node/{cli => executor}/tests/submit_transaction.rs (100%) delete mode 100644 substrate/client/network/src/protocol/notifications/service/metrics.rs delete mode 100644 substrate/client/network/src/protocol/notifications/service/mod.rs delete mode 100644 substrate/client/network/src/protocol/notifications/service/tests.rs delete mode 100644 substrate/frame/contracts/fixtures/build.rs delete mode 100644 substrate/frame/contracts/fixtures/contracts/call.rs delete mode 100644 substrate/frame/contracts/fixtures/contracts/common/Cargo.toml create mode 100644 substrate/frame/contracts/fixtures/data/call.wat create mode 100644 substrate/frame/contracts/fixtures/data/dummy.wat create mode 100644 substrate/frame/contracts/primitives/README.md rename substrate/frame/contracts/{src/primitives.rs => primitives/src/lib.rs} (96%) delete mode 100644 substrate/frame/contracts/uapi/Cargo.toml delete mode 100644 substrate/frame/contracts/uapi/src/flags.rs delete mode 100644 substrate/frame/contracts/uapi/src/host.rs delete mode 100644 substrate/frame/contracts/uapi/src/host/wasm32.rs delete mode 100644 substrate/frame/contracts/uapi/src/lib.rs delete mode 100644 substrate/frame/examples/tasks/Cargo.toml delete mode 100644 substrate/frame/examples/tasks/src/benchmarking.rs delete mode 100644 substrate/frame/examples/tasks/src/lib.rs delete mode 100644 substrate/frame/examples/tasks/src/mock.rs delete mode 100644 substrate/frame/examples/tasks/src/tests.rs delete mode 100644 substrate/frame/examples/tasks/src/weights.rs delete mode 100644 substrate/frame/sassafras/Cargo.toml delete mode 100644 substrate/frame/sassafras/README.md delete mode 100644 substrate/frame/sassafras/src/benchmarking.rs delete mode 100644 substrate/frame/sassafras/src/data/25_tickets_100_auths.bin delete mode 100644 substrate/frame/sassafras/src/data/benchmark-results.md delete mode 100644 substrate/frame/sassafras/src/data/tickets-sort.md delete mode 100644 substrate/frame/sassafras/src/data/tickets-sort.png delete mode 100644 substrate/frame/sassafras/src/lib.rs delete mode 100644 substrate/frame/sassafras/src/mock.rs delete mode 100644 substrate/frame/sassafras/src/tests.rs delete mode 100644 substrate/frame/sassafras/src/weights.rs delete mode 100644 substrate/frame/support/procedural/src/construct_runtime/expand/task.rs delete mode 100644 substrate/frame/support/procedural/src/pallet/expand/tasks.rs delete mode 100644 substrate/frame/support/procedural/src/pallet/parse/tasks.rs delete mode 100644 substrate/frame/support/procedural/src/pallet/parse/tests/mod.rs delete mode 100644 substrate/frame/support/procedural/src/pallet/parse/tests/tasks.rs delete mode 100644 substrate/frame/support/src/tests/tasks.rs delete mode 100644 substrate/frame/support/src/traits/tasks.rs delete mode 100644 substrate/frame/support/test/tests/derive_impl.rs delete mode 100644 substrate/frame/support/test/tests/pallet_ui/pass/task_valid.rs delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_can_only_be_attached_to_impl.stderr delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_condition_invalid_arg.rs delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_condition_invalid_arg.stderr delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_invalid_condition.rs delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_invalid_condition.stderr delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_invalid_index.rs delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_invalid_index.stderr delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_invalid_list.rs delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_invalid_list.stderr delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_invalid_weight.rs delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_invalid_weight.stderr delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_missing_condition.rs delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_missing_condition.stderr delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_missing_index.rs delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_missing_index.stderr delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_missing_list.rs delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_missing_list.stderr delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_missing_weight.rs delete mode 100644 substrate/frame/support/test/tests/pallet_ui/task_missing_weight.stderr delete mode 100644 substrate/primitives/core/src/const_hex2array.rs delete mode 100644 substrate/primitives/trie/src/proof_size_extension.rs create mode 100644 substrate/src/lib.rs create mode 100644 substrate/utils/wasm-builder/README.md diff --git a/.cargo/config.toml b/.cargo/config.toml index f113e9114ac..bd46659f799 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,7 +1,41 @@ [build] rustdocflags = [ - "-Dwarnings", - "-Arustdoc::redundant_explicit_links", # stylistic + "-Dwarnings", + "-Arustdoc::redundant_explicit_links", # stylistic +] + +# An auto defined `clippy` feature was introduced, +# but it was found to clash with user defined features, +# so was renamed to `cargo-clippy`. +# +# If you want standard clippy run: +# RUSTFLAGS= cargo clippy +[target.'cfg(feature = "cargo-clippy")'] +rustflags = [ + "-Aclippy::all", + "-Dclippy::correctness", + "-Aclippy::if-same-then-else", + "-Asuspicious_double_ref_op", + "-Dclippy::complexity", + "-Aclippy::zero-prefixed-literal", # 00_1000_000 + "-Aclippy::type_complexity", # raison d'etre + "-Aclippy::nonminimal-bool", # maybe + "-Aclippy::borrowed-box", # Reasonable to fix this one + "-Aclippy::too-many-arguments", # (Turning this on would lead to) + "-Aclippy::unnecessary_cast", # Types may change + "-Aclippy::identity-op", # One case where we do 0 + + "-Aclippy::useless_conversion", # Types may change + "-Aclippy::unit_arg", # styalistic. + "-Aclippy::option-map-unit-fn", # styalistic + "-Aclippy::bind_instead_of_map", # styalistic + "-Aclippy::erasing_op", # E.g. 0 * DOLLARS + "-Aclippy::eq_op", # In tests we test equality. + "-Aclippy::while_immutable_condition", # false positives + "-Aclippy::needless_option_as_deref", # false positives + "-Aclippy::derivable_impls", # false positives + "-Aclippy::stable_sort_primitive", # prefer stable sort + "-Aclippy::extra-unused-type-parameters", # stylistic + "-Aclippy::default_constructed_unit_structs", # stylistic ] [env] diff --git a/.config/lychee.toml b/.config/lychee.toml index 72c1e66a4df..9b2ae069931 100644 --- a/.config/lychee.toml +++ b/.config/lychee.toml @@ -15,36 +15,36 @@ accept = [ 200, # Rate limited - GitHub likes to throw this. - 429, + 429 ] -exclude_path = ["./target"] +exclude_path = [ "./target" ] exclude = [ - # Place holders (no need to fix these): - "http://visitme/", - "https://visitme/", - - # TODO - "https://docs.substrate.io/main-docs/build/custom-rpc/#public-rpcs", - "https://docs.substrate.io/rustdocs/latest/sp_api/macro.decl_runtime_apis.html", - "https://github.com/ipfs/js-ipfs-bitswap/blob/", - "https://github.com/paritytech/polkadot-sdk/substrate/frame/timestamp", - "https://github.com/paritytech/substrate/frame/fast-unstake", - "https://github.com/zkcrypto/bls12_381/blob/e224ad4ea1babfc582ccd751c2bf128611d10936/src/test-data/mod.rs", - "https://polkadot.network/the-path-of-a-parachain-block/", - "https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results", - "https://research.web3.foundation/en/latest/polkadot/NPoS/3.%20Balancing.html", - "https://research.web3.foundation/en/latest/polkadot/Token%20Economics.html#inflation-model", - "https://research.web3.foundation/en/latest/polkadot/block-production/Babe.html", - "https://research.web3.foundation/en/latest/polkadot/block-production/Babe.html#-6.-practical-results", - "https://research.web3.foundation/en/latest/polkadot/networking/3-avail-valid.html#topology", - "https://research.web3.foundation/en/latest/polkadot/overview/2-token-economics.html", - "https://research.web3.foundation/en/latest/polkadot/overview/2-token-economics.html#inflation-model", - "https://research.web3.foundation/en/latest/polkadot/slashing/npos.html", - "https://rpc.polkadot.io/", - "https://w3f.github.io/parachain-implementers-guide/node/approval/approval-distribution.html", - "https://w3f.github.io/parachain-implementers-guide/node/index.html", - "https://w3f.github.io/parachain-implementers-guide/protocol-chain-selection.html", - "https://w3f.github.io/parachain-implementers-guide/runtime/session_info.html", + # Place holders (no need to fix these): + "http://visitme/", + "https://visitme/", + + # TODO + "https://docs.substrate.io/main-docs/build/custom-rpc/#public-rpcs", + "https://docs.substrate.io/rustdocs/latest/sp_api/macro.decl_runtime_apis.html", + "https://github.com/ipfs/js-ipfs-bitswap/blob/", + "https://github.com/paritytech/polkadot-sdk/substrate/frame/timestamp", + "https://github.com/paritytech/substrate/frame/fast-unstake", + "https://github.com/zkcrypto/bls12_381/blob/e224ad4ea1babfc582ccd751c2bf128611d10936/src/test-data/mod.rs", + "https://polkadot.network/the-path-of-a-parachain-block/", + "https://research.web3.foundation/en/latest/polkadot/BABE/Babe/#6-practical-results", + "https://research.web3.foundation/en/latest/polkadot/block-production/Babe.html", + "https://research.web3.foundation/en/latest/polkadot/block-production/Babe.html#-6.-practical-results", + "https://research.web3.foundation/en/latest/polkadot/networking/3-avail-valid.html#topology", + "https://research.web3.foundation/en/latest/polkadot/NPoS/3.%20Balancing.html", + "https://research.web3.foundation/en/latest/polkadot/overview/2-token-economics.html", + "https://research.web3.foundation/en/latest/polkadot/overview/2-token-economics.html#inflation-model", + "https://research.web3.foundation/en/latest/polkadot/slashing/npos.html", + "https://research.web3.foundation/en/latest/polkadot/Token%20Economics.html#inflation-model", + "https://rpc.polkadot.io/", + "https://w3f.github.io/parachain-implementers-guide/node/approval/approval-distribution.html", + "https://w3f.github.io/parachain-implementers-guide/node/index.html", + "https://w3f.github.io/parachain-implementers-guide/protocol-chain-selection.html", + "https://w3f.github.io/parachain-implementers-guide/runtime/session_info.html", ] diff --git a/.config/taplo.toml b/.config/taplo.toml deleted file mode 100644 index f5d0b7021ba..00000000000 --- a/.config/taplo.toml +++ /dev/null @@ -1,33 +0,0 @@ -# all options https://taplo.tamasfe.dev/configuration/formatter-options.html - -# ignore zombienet as they do some deliberate custom toml stuff -exclude = [ - "cumulus/zombienet/**", - "polkadot/node/malus/integrationtests/**", - "polkadot/zombienet_tests/**", - "substrate/zombienet/**", -] - -# global rules -[formatting] -reorder_arrays = true -inline_table_expand = false -array_auto_expand = false -array_auto_collapse = false -indent_string = " " # tab - -# don't re-order order-dependent deb package metadata -[[rule]] -include = ["polkadot/Cargo.toml"] -keys = ["package.metadata.deb"] - -[rule.formatting] -reorder_arrays = false - -# don't re-order order-dependent rustflags -[[rule]] -include = [".cargo/config.toml"] -keys = ["build"] - -[rule.formatting] -reorder_arrays = false diff --git a/.config/zepter.yaml b/.config/zepter.yaml index f701392d16b..33bf3a044cf 100644 --- a/.config/zepter.yaml +++ b/.config/zepter.yaml @@ -19,15 +19,18 @@ workflows: '--left-side-outside-workspace=ignore', # Some features imply that they activate a specific dependency as non-optional. Otherwise the default behaviour with a `?` is used. '--feature-enables-dep=try-runtime:frame-try-runtime,runtime-benchmarks:frame-benchmarking', - # Auxillary flags: + # Actually modify the files and not just report the issues: '--offline', '--locked', '--show-path', '--quiet', ] + # Format the features into canonical format: + - ['format', 'features', '--offline', '--locked', '--quiet'] # Same as `check`, but with the `--fix` flag. default: - [ $check.0, '--fix' ] + - [ $check.1, '--fix' ] # Will be displayed when any workflow fails: help: diff --git a/.github/pr-custom-review.yml b/.github/pr-custom-review.yml new file mode 100644 index 00000000000..ac13d862a4a --- /dev/null +++ b/.github/pr-custom-review.yml @@ -0,0 +1,63 @@ +# 🔒 PROTECTED: Changes to locks-review-team should be approved by the current locks-review-team +locks-review-team: locks-review +team-leads-team: polkadot-review +action-review-team: ci + +rules: + - name: CI files + check_type: changed_files + condition: + include: ^\.gitlab-ci\.yml|^docker/.*|^\.github/.*|^\.gitlab/.*|^\.config/nextest.toml|^\.cargo/.* + exclude: ^\.gitlab/pipeline/zombienet.* + min_approvals: 2 + teams: + - ci + - release-engineering + + - name: Core developers + check_type: changed_files + condition: + include: .* + # excluding files from 'Runtime files' and 'CI files' rules + exclude: ^polkadot/runtime/(kusama|polkadot)/src/[^/]+\.rs$|^cumulus/parachains/runtimes/assets/(asset-hub-kusama|asset-hub-polkadot)/src/[^/]+\.rs$|^cumulus/parachains/runtimes/bridge-hubs/(bridge-hub-kusama|bridge-hub-polkadot)/src/[^/]+\.rs$|^cumulus/parachains/runtimes/collectives/collectives-polkadot/src/[^/]+\.rs$|^cumulus/parachains/common/src/[^/]+\.rs$|^substrate/frame/(?!.*(nfts/.*|uniques/.*|babe/.*|grandpa/.*|beefy|merkle-mountain-range/.*|contracts/.*|election|nomination-pools/.*|staking/.*|aura/.*))|^polkadot/runtime/(kusama|polkadot)/src/[^/]+\.rs$|^\.gitlab-ci\.yml|^docker/.*|^\.github/.*|^\.gitlab/.*|^\.config/nextest.toml|^\.cargo/.* + min_approvals: 2 + teams: + - core-devs + + # cumulus + - name: Runtime files cumulus + check_type: changed_files + condition: ^cumulus/parachains/runtimes/assets/(asset-hub-kusama|asset-hub-polkadot)/src/[^/]+\.rs$|^cumulus/parachains/runtimes/bridge-hubs/(bridge-hub-kusama|bridge-hub-polkadot)/src/[^/]+\.rs$|^cumulus/parachains/runtimes/collectives/collectives-polkadot/src/[^/]+\.rs$|^cumulus/parachains/common/src/[^/]+\.rs$ + all_distinct: + - min_approvals: 1 + teams: + - locks-review + - min_approvals: 1 + teams: + - polkadot-review + + # if there are any changes in the bridges subtree (in case of backport changes back to bridges repo) + - name: Bridges subtree files + check_type: changed_files + condition: ^bridges/.* + min_approvals: 1 + teams: + - bridges-core + + # substrate + + - name: FRAME coders substrate + check_type: changed_files + condition: + include: ^substrate/frame/(?!.*(nfts/.*|uniques/.*|babe/.*|grandpa/.*|beefy|merkle-mountain-range/.*|contracts/.*|election|nomination-pools/.*|staking/.*|aura/.*)) + all: + - min_approvals: 2 + teams: + - core-devs + - min_approvals: 1 + teams: + - frame-coders + +prevent-review-request: + teams: + - core-devs diff --git a/.github/review-bot.yml b/.github/review-bot.yml index aa4ab8a69e0..c522988f02e 100644 --- a/.github/review-bot.yml +++ b/.github/review-bot.yml @@ -1,34 +1,31 @@ rules: - name: CI files - countAuthor: true condition: - include: + include: - ^\.gitlab-ci\.yml - ^docker/.* - ^\.github/.* - ^\.gitlab/.* - ^\.config/nextest.toml - ^\.cargo/.* - exclude: + exclude: - ^\.gitlab/pipeline/zombienet.* - type: "or" - reviewers: - - minApprovals: 2 - teams: - - ci - - minApprovals: 2 - teams: - - core-devs + minApprovals: 2 + type: basic + teams: + - ci + - release-engineering - name: Audit rules type: basic condition: - include: - - ^polkadot/runtime/common/.* + include: + - ^polkadot/runtime\/(kusama|polkadot|common)\/.* - ^polkadot/primitives/src\/.+\.rs$ - ^substrate/primitives/.* - ^substrate/frame/.* - exclude: + exclude: + - ^polkadot/runtime\/(kusama|polkadot)\/src\/weights\/.+\.rs$ - ^substrate\/frame\/.+\.md$ minApprovals: 1 allowedToSkipRule: @@ -44,8 +41,13 @@ rules: - .* # excluding files from 'Runtime files' and 'CI files' rules exclude: + - ^polkadot/runtime/(kusama|polkadot)/src/[^/]+\.rs$ + - ^cumulus/parachains/runtimes/assets/(asset-hub-kusama|asset-hub-polkadot)/src/[^/]+\.rs$ + - ^cumulus/parachains/runtimes/bridge-hubs/(bridge-hub-kusama|bridge-hub-polkadot)/src/[^/]+\.rs$ + - ^cumulus/parachains/runtimes/collectives/collectives-polkadot/src/[^/]+\.rs$ - ^cumulus/parachains/common/src/[^/]+\.rs$ - ^substrate/frame/(?!.*(nfts/.*|uniques/.*|babe/.*|grandpa/.*|beefy|merkle-mountain-range/.*|contracts/.*|election|nomination-pools/.*|staking/.*|aura/.*)) + - ^polkadot/runtime/(kusama|polkadot)/src/[^/]+\.rs$ - ^\.gitlab-ci\.yml - ^docker/.* - ^\.github/.* @@ -57,10 +59,28 @@ rules: teams: - core-devs + # cumulus + - name: Runtime files cumulus + countAuthor: true + condition: + include: + - ^cumulus/parachains/runtimes/assets/(asset-hub-kusama|asset-hub-polkadot)/src/[^/]+\.rs$ + - ^cumulus/parachains/runtimes/bridge-hubs/(bridge-hub-kusama|bridge-hub-polkadot)/src/[^/]+\.rs$ + - ^cumulus/parachains/runtimes/collectives/collectives-polkadot/src/[^/]+\.rs$ + - ^cumulus/parachains/common/src/[^/]+\.rs$ + type: and-distinct + reviewers: + - minApprovals: 1 + teams: + - locks-review + - minApprovals: 1 + teams: + - polkadot-review + # if there are any changes in the bridges subtree (in case of backport changes back to bridges repo) - name: Bridges subtree files type: basic - condition: + condition: include: - ^bridges/.* minApprovals: 1 @@ -68,9 +88,10 @@ rules: - bridges-core # substrate + - name: FRAME coders substrate condition: - include: + include: - ^substrate/frame/(?!.*(nfts/.*|uniques/.*|babe/.*|grandpa/.*|beefy|merkle-mountain-range/.*|contracts/.*|election|nomination-pools/.*|staking/.*|aura/.*)) type: "and" reviewers: @@ -83,9 +104,8 @@ rules: # Protection of THIS file - name: Review Bot - countAuthor: true condition: - include: + include: - review-bot\.yml type: "and" reviewers: @@ -95,6 +115,9 @@ rules: - minApprovals: 1 teams: - locks-review + - minApprovals: 1 + teams: + - ci preventReviewRequests: teams: diff --git a/.github/runtime_specs/rococo.json b/.github/runtime_specs/rococo.json deleted file mode 100644 index 6568b06400c..00000000000 --- a/.github/runtime_specs/rococo.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "pallets": { - "1": { - "constants": { - "EpochDuration": { - "value": [ 88, 2, 0, 0, 0, 0, 0, 0 ]} - } - }, - - "2": { - "constants": { - "MinimumPeriod": { - "value": [ 184, 11, 0, 0, 0, 0, 0, 0 ]} - } - } - } - } diff --git a/.github/runtime_specs/westend.json b/.github/runtime_specs/westend.json deleted file mode 100644 index 6568b06400c..00000000000 --- a/.github/runtime_specs/westend.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "pallets": { - "1": { - "constants": { - "EpochDuration": { - "value": [ 88, 2, 0, 0, 0, 0, 0, 0 ]} - } - }, - - "2": { - "constants": { - "MinimumPeriod": { - "value": [ 184, 11, 0, 0, 0, 0, 0, 0 ]} - } - } - } - } diff --git a/.github/scripts/check-runtime.py b/.github/scripts/check-runtime.py deleted file mode 100755 index 9f3d047e01f..00000000000 --- a/.github/scripts/check-runtime.py +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/env python3 - -import json -import sys -import logging -import os - - -def check_constant(spec_pallet_id, spec_pallet_value, meta_constant): - """ - Check a single constant - - :param spec_pallet_id: - :param spec_pallet_value: - :param meta_constant: - :return: - """ - if meta_constant['name'] == list(spec_pallet_value.keys())[0]: - constant = meta_constant['name'] - res = list(spec_pallet_value.values())[0]["value"] == meta_constant["value"] - - logging.debug(f" Checking pallet:{spec_pallet_id}/constants/{constant}") - logging.debug(f" spec_pallet_value: {spec_pallet_value}") - logging.debug(f" meta_constant: {meta_constant}") - logging.info(f"pallet:{spec_pallet_id}/constants/{constant} -> {res}") - return res - else: - # logging.warning(f" Skipping pallet:{spec_pallet_id}/constants/{meta_constant['name']}") - pass - - -def check_pallet(metadata, spec_pallet): - """ - Check one pallet - - :param metadata: - :param spec_pallet_id: - :param spec_pallet_value: - :return: - """ - - spec_pallet_id, spec_pallet_value = spec_pallet - logging.debug(f"Pallet: {spec_pallet_id}") - - metadata_pallets = metadata["pallets"] - metadata_pallet = metadata_pallets[spec_pallet_id] - - res = map(lambda meta_constant_value: check_constant( - spec_pallet_id, spec_pallet_value["constants"], meta_constant_value), - metadata_pallet["constants"].values()) - res = list(filter(lambda item: item is not None, res)) - return all(res) - - -def check_pallets(metadata, specs): - """ - CHeck all pallets - - :param metadata: - :param specs: - :return: - """ - - res = list(map(lambda spec_pallet: check_pallet(metadata, spec_pallet), - specs['pallets'].items())) - res = list(filter(lambda item: item is not None, res)) - return all(res) - - -def check_metadata(metadata, specs): - """ - Check metadata (json) against a list of expectations - - :param metadata: Metadata in JSON format - :param expectation: Expectations - :return: Bool - """ - - res = check_pallets(metadata, specs) - return res - - -def help(): - """ Show some simple help """ - - print(f"You must pass 2 args, you passed {len(sys.argv) - 1}") - print("Sample call:") - print("check-runtime.py ") - - -def load_json(file): - """ Load json from a file """ - - f = open(file) - return json.load(f) - - -def main(): - LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper() - logging.basicConfig(level=LOGLEVEL) - - if len(sys.argv) != 3: - help() - exit(1) - - metadata_file = sys.argv[1] - specs_file = sys.argv[2] - print(f"Checking metadata from: {metadata_file} with specs from: {specs_file}") - - metadata = load_json(metadata_file) - specs = load_json(specs_file) - - res = check_metadata(metadata, specs) - - if res: - logging.info(f"OK") - exit(0) - else: - print("") - logging.info(f"Some errors were found, run again with LOGLEVEL=debug") - exit(1) - -if __name__ == "__main__": - main() diff --git a/.github/scripts/common/lib.sh b/.github/scripts/common/lib.sh index e499dfabd64..b0f9cb32063 100755 --- a/.github/scripts/common/lib.sh +++ b/.github/scripts/common/lib.sh @@ -202,26 +202,21 @@ fetch_release_artifacts() { echo "Release ID : $RELEASE_ID" echo "Repo : $REPO" echo "Binary : $BINARY" - OUTPUT_DIR=${OUTPUT_DIR:-"./release-artifacts/${BINARY}"} - echo "OUTPUT_DIR : $OUTPUT_DIR" - echo "Fetching release info..." curl -L -s \ -H "Accept: application/vnd.github+json" \ -H "Authorization: Bearer ${GITHUB_TOKEN}" \ -H "X-GitHub-Api-Version: 2022-11-28" \ https://api.github.com/repos/${REPO}/releases/${RELEASE_ID} > release.json - echo "Extract asset ids..." + # Get Asset ids ids=($(jq -r '.assets[].id' < release.json )) - echo "Extract asset count..." count=$(jq '.assets|length' < release.json ) # Fetch artifacts - mkdir -p "$OUTPUT_DIR" - pushd "$OUTPUT_DIR" > /dev/null + mkdir -p "./release-artifacts/${BINARY}" + pushd "./release-artifacts/${BINARY}" > /dev/null - echo "Fetching assets..." iter=1 for id in "${ids[@]}" do @@ -269,41 +264,3 @@ function check_gpg() { echo "Checking GPG Signature for $1" gpg --no-tty --verify -q $1.asc $1 } - -# GITHUB_REF will typically be like: -# - refs/heads/release-v1.2.3 -# - refs/heads/release-polkadot-v1.2.3-rc2 -# This function extracts the version -function get_version_from_ghref() { - GITHUB_REF=$1 - stripped=${GITHUB_REF#refs/heads/release-} - re="v([0-9]+\.[0-9]+\.[0-9]+)" - if [[ $stripped =~ $re ]]; then - echo ${BASH_REMATCH[0]}; - return 0 - else - return 1 - fi -} - -# Get latest rc tag based on the release version and product -function get_latest_rc_tag() { - version=$1 - product=$2 - - if [[ "$product" == "polkadot" ]]; then - last_rc=$(git tag -l "$version-rc*" | sort -V | tail -n 1) - elif [[ "$product" == "polkadot-parachain" ]]; then - last_rc=$(git tag -l "polkadot-parachains-$version-rc*" | sort -V | tail -n 1) - fi - echo "${last_rc}" -} - -# Increment rc tag number based on the value of a suffix of the current rc tag -function increment_rc_tag() { - last_rc=$1 - - suffix=$(echo "$last_rc" | grep -Eo '[0-9]+$') - ((suffix++)) - echo $suffix -} diff --git a/.github/workflows/build-and-attach-release-runtimes.yml b/.github/workflows/build-and-attach-release-runtimes.yml index f7003379cf0..db0175c6855 100644 --- a/.github/workflows/build-and-attach-release-runtimes.yml +++ b/.github/workflows/build-and-attach-release-runtimes.yml @@ -3,7 +3,7 @@ name: Build and Attach Runtimes to Releases/RC on: release: types: - - published + - created env: PROFILE: production @@ -23,7 +23,7 @@ jobs: - { name: glutton-westend, package: glutton-westend-runtime, path: cumulus/parachains/runtimes/glutton/glutton-westend } build_config: # Release build has logging disabled and no dev features - - { type: on-chain-release, opts: --features on-chain-release-build } + - { type: on-chain-release, opts: --features on-chain-release-build } # Debug build has logging enabled and developer features - { type: dev-debug-build, opts: --features try-runtime } @@ -31,11 +31,11 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + uses: actions/checkout@v4 - name: Build ${{ matrix.runtime.name }} ${{ matrix.build_config.type }} id: srtool_build - uses: chevdor/srtool-actions@v0.9.1 + uses: chevdor/srtool-actions@v0.9.0 env: BUILD_OPTS: ${{ matrix.build_config.opts }} with: @@ -44,6 +44,12 @@ jobs: runtime_dir: ${{ matrix.runtime.path }} profile: ${{ env.PROFILE }} + - name: Build Summary + run: | + echo "${{ steps.srtool_build.outputs.json }}" | jq . > ${{ matrix.runtime.name }}-srtool-digest.json + cat ${{ matrix.runtime.name }}-srtool-digest.json + echo "Runtime location: ${{ steps.srtool_build.outputs.wasm }}" + - name: Set up paths and runtime names id: setup run: | diff --git a/.github/workflows/check-licenses.yml b/.github/workflows/check-licenses.yml index a5d7ba6ec27..a66e3a53998 100644 --- a/.github/workflows/check-licenses.yml +++ b/.github/workflows/check-licenses.yml @@ -9,7 +9,7 @@ permissions: jobs: check-licenses: - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 env: LICENSES: "'Apache-2.0' 'GPL-3.0-only' 'GPL-3.0-or-later WITH Classpath-exception-2.0'" NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/check-prdoc.yml b/.github/workflows/check-prdoc.yml index f47404744a4..54e4d2b9680 100644 --- a/.github/workflows/check-prdoc.yml +++ b/.github/workflows/check-prdoc.yml @@ -6,27 +6,26 @@ on: merge_group: env: - IMAGE: docker.io/paritytech/prdoc:v0.0.7 + IMAGE: paritytech/prdoc:v0.0.5 API_BASE: https://api.github.com/repos REPO: ${{ github.repository }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_PR: ${{ github.event.pull_request.number }} + MOUNT: /prdoc ENGINE: docker - PRDOC_DOC: https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/prdoc.md jobs: check-prdoc: runs-on: ubuntu-latest steps: - # we cannot show the version in this step (ie before checking out the repo) - # due to https://github.com/paritytech/prdoc/issues/15 - name: Skip merge queue if: ${{ contains(github.ref, 'gh-readonly-queue') }} run: exit 0 - name: Pull image run: | echo "Pulling $IMAGE" - $ENGINE pull $IMAGE + docker pull $IMAGE + docker run --rm $IMAGE --version - name: Check if PRdoc is required id: get-labels @@ -37,29 +36,18 @@ jobs: echo "Labels: ${labels}" echo "labels=${labels}" >> "$GITHUB_OUTPUT" - - name: Checkout repo - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 - - - name: Check PRDoc version - run: | - $ENGINE run --rm -v $PWD:/repo $IMAGE --version - - - name: Early exit if PR is silent + - name: No PRdoc required if: ${{ contains(steps.get-labels.outputs.labels, 'R0') }} run: | - hits=$(find prdoc -name "pr_$GITHUB_PR*.prdoc" | wc -l) - if (( hits > 0 )); then - echo "PR detected as silent, but a PRDoc was found, checking it as information" - $ENGINE run --rm -v $PWD:/repo $IMAGE check -n ${GITHUB_PR} || echo "Ignoring failure" - else - echo "PR detected as silent, no PRDoc found, exiting..." - fi - echo "If you want to add a PRDoc, please refer to $PRDOC_DOC" + echo "PR detected as silent, no PRdoc is required, exiting..." exit 0 + - name: Checkout repo + if: ${{ !contains(steps.get-labels.outputs.labels, 'R0') }} + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 + - name: PRdoc check for PR#${{ github.event.pull_request.number }} if: ${{ !contains(steps.get-labels.outputs.labels, 'R0') }} run: | - echo "Checking for PR#${GITHUB_PR}" - echo "You can find more information about PRDoc at $PRDOC_DOC" - $ENGINE run --rm -v $PWD:/repo $IMAGE check -n ${GITHUB_PR} + echo "Checking for PR#${GITHUB_PR} in $MOUNT" + $ENGINE run --rm -v $PWD/prdoc:/doc $IMAGE check -n ${GITHUB_PR} || true diff --git a/.github/workflows/check-publish.yml b/.github/workflows/check-publish.yml index 1941bd98167..db0863888b8 100644 --- a/.github/workflows/check-publish.yml +++ b/.github/workflows/check-publish.yml @@ -12,7 +12,7 @@ jobs: check-publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0 - name: Rust Cache uses: Swatinem/rust-cache@3cf7f8cc28d1b4e7d01e3783be10a97d55d483c8 # v2.7.1 diff --git a/.github/workflows/check-runtimes.yml b/.github/workflows/check-runtimes.yml deleted file mode 100644 index 0e5ad104766..00000000000 --- a/.github/workflows/check-runtimes.yml +++ /dev/null @@ -1,94 +0,0 @@ -name: Check Runtimes Specs -# This GH Workflow fetches the runtimes available in a release. -# It then compares their metadata with reference specs located under -# .github/runtime_specs. - -on: - workflow_dispatch: - inputs: - release_id: - description: | - Release ID. - You can find it using the command: - curl -s \ - -H "Authorization: Bearer ${GITHUB_TOKEN}" https://api.github.com/repos/paritytech/polkadot-sdk/releases | \ - jq '.[] | { name: .name, id: .id }' - required: true - type: string - - # This trigger unfortunately does not work as expected. - # https://github.com/orgs/community/discussions/47794 - # release: - # types: [edited] - -env: - RUNTIME_SPECS_DIR: .github/runtime_specs - DATA_DIR: runtimes - RELEASE_ID: ${{ inputs.release_id }} - REPO: ${{ github.repository }} - -jobs: - find-specs: - name: Fetch runtime specs - outputs: - specs: ${{ steps.get-list.outputs.specs }} - runs-on: ubuntu-latest - steps: - - name: Checkout the repo - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 - - - name: Get list - id: get-list - run: | - lst=$(ls $RUNTIME_SPECS_DIR/*.json | xargs -I{} basename "{}" .json | jq -R .| jq -sc .) - echo "Found: $lst" - echo "specs=$lst" >> $GITHUB_OUTPUT - - check-runtimes: - name: Check runtime specs - runs-on: ubuntu-latest - needs: - - find-specs - - strategy: - matrix: - specs: ${{ fromJSON(needs.find-specs.outputs.specs) }} - - steps: - - name: Checkout the repo - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 - - - name: Fetch release artifacts based on release id - env: - OUTPUT_DIR: ${{ env.DATA_DIR }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - . ./.github/scripts/common/lib.sh - fetch_release_artifacts - - - name: Install tooling - env: - SUBWASM_VERSION: v0.20.0 - DL_BASE_URL: https://github.com/chevdor/subwasm/releases/download - run: | - wget $DL_BASE_URL/$SUBWASM_VERSION/subwasm_linux_amd64_$SUBWASM_VERSION.deb \ - -O subwasm.deb - sudo dpkg -i subwasm.deb - subwasm --version - - - name: Extract metadata JSON for ${{ matrix.specs }} - env: - RUNTIME: ${{ matrix.specs }} - run: | - WASM=$(ls ${DATA_DIR}/${RUNTIME}*.wasm) - echo "WASM=$WASM" - subwasm show --json "$WASM" > "${DATA_DIR}/${RUNTIME}.json" - - - name: Check specs for ${{ matrix.specs }} - id: build - env: - RUNTIME: ${{ matrix.specs }} - LOGLEVEL: info - run: | - python --version - .github/scripts/check-runtime.py "${DATA_DIR}/${RUNTIME}.json" "${RUNTIME_SPECS_DIR}/${RUNTIME}.json" diff --git a/.github/workflows/claim-crates.yml b/.github/workflows/claim-crates.yml index 9e272266201..0bd5593b54f 100644 --- a/.github/workflows/claim-crates.yml +++ b/.github/workflows/claim-crates.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest environment: master steps: - - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0 - name: Rust Cache uses: Swatinem/rust-cache@3cf7f8cc28d1b4e7d01e3783be10a97d55d483c8 # v2.7.1 diff --git a/.github/workflows/fmt-check.yml b/.github/workflows/fmt-check.yml index 99ac5120097..e4d39acabfd 100644 --- a/.github/workflows/fmt-check.yml +++ b/.github/workflows/fmt-check.yml @@ -15,7 +15,7 @@ jobs: os: ["ubuntu-latest"] runs-on: ${{ matrix.os }} container: - image: paritytech/ci-unified:bullseye-1.74.0-2023-11-01-v20231204 + image: paritytech/ci-unified:bullseye-1.73.0-2023-11-01-v20231025 steps: - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 diff --git a/.github/workflows/gitspiegel-trigger.yml b/.github/workflows/gitspiegel-trigger.yml index b338f7a3f62..59347fad6d6 100644 --- a/.github/workflows/gitspiegel-trigger.yml +++ b/.github/workflows/gitspiegel-trigger.yml @@ -13,19 +13,8 @@ on: - unlocked - ready_for_review - reopened - # the job doesn't check out any code, so it is relatively safe to run it on any event - pull_request_target: - types: - - opened - - synchronize - - unlocked - - ready_for_review - - reopened merge_group: -# drop all permissions for GITHUB_TOKEN -permissions: {} - jobs: sync: runs-on: ubuntu-latest diff --git a/.github/workflows/merge-queue.yml b/.github/workflows/merge-queue.yml index cce326f4493..f3fb7765ca6 100644 --- a/.github/workflows/merge-queue.yml +++ b/.github/workflows/merge-queue.yml @@ -6,7 +6,7 @@ on: jobs: trigger-merge-queue-action: runs-on: ubuntu-latest - environment: merge-queues + environment: master steps: - name: Generate token id: app_token diff --git a/.github/workflows/notif-burnin-label.yml b/.github/workflows/notif-burnin-label.yml deleted file mode 100644 index b630cd07440..00000000000 --- a/.github/workflows/notif-burnin-label.yml +++ /dev/null @@ -1,24 +0,0 @@ -name: Notify DevOps when burn-in label applied -on: - pull_request: - types: [labeled] - -jobs: - notify-devops: - runs-on: ubuntu-latest - strategy: - matrix: - channel: - - name: 'Team: DevOps' - room: '!lUslSijLMgNcEKcAiE:parity.io' - - steps: - - name: Send Matrix message to ${{ matrix.channel.name }} - if: startsWith(github.event.label.name, 'A0-') - uses: s3krit/matrix-message-action@70ad3fb812ee0e45ff8999d6af11cafad11a6ecf # v0.0.3 - with: - room_id: ${{ matrix.channel.room }} - access_token: ${{ secrets.RELEASENOTES_MATRIX_V2_ACCESS_TOKEN }} - server: m.parity.io - message: | - @room Burn-in request received for [${{ github.event.pull_request.title }}](${{ github.event.pull_request.html_url }}) diff --git a/.github/workflows/pr-custom-review.yml b/.github/workflows/pr-custom-review.yml new file mode 100644 index 00000000000..4e0809cbfdc --- /dev/null +++ b/.github/workflows/pr-custom-review.yml @@ -0,0 +1,46 @@ +name: Assign reviewers + +on: + pull_request: + branches: + - master + - main + types: + - opened + - reopened + - synchronize + - review_requested + - review_request_removed + - ready_for_review + - converted_to_draft + pull_request_review: + merge_group: + +jobs: + pr-custom-review: + runs-on: ubuntu-latest + steps: + - name: Skip merge queue + if: ${{ contains(github.ref, 'gh-readonly-queue') }} + run: exit 0 + - name: Skip if pull request is in Draft + # `if: github.event.pull_request.draft == true` should be kept here, at + # the step level, rather than at the job level. The latter is not + # recommended because when the PR is moved from "Draft" to "Ready to + # review" the workflow will immediately be passing (since it was skipped), + # even though it hasn't actually ran, since it takes a few seconds for + # the workflow to start. This is also disclosed in: + # https://github.community/t/dont-run-actions-on-draft-pull-requests/16817/17 + # That scenario would open an opportunity for the check to be bypassed: + # 1. Get your PR approved + # 2. Move it to Draft + # 3. Push whatever commits you want + # 4. Move it to "Ready for review"; now the workflow is passing (it was + # skipped) and "Check reviews" is also passing (it won't be updated + # until the workflow is finished) + if: github.event.pull_request.draft == true + run: exit 1 + - name: pr-custom-review + uses: paritytech/pr-custom-review@master + with: + checks-reviews-api: http://pcr.parity-prod.parity.io/api/v1/check_reviews diff --git a/.github/workflows/release-10_rc-automation.yml b/.github/workflows/release-10_rc-automation.yml deleted file mode 100644 index 7231a8b7588..00000000000 --- a/.github/workflows/release-10_rc-automation.yml +++ /dev/null @@ -1,113 +0,0 @@ -name: Release - RC automation -on: - push: - branches: - # Catches release-polkadot-v1.2.3, release-v1.2.3-rc1, etc - - release-v[0-9]+.[0-9]+.[0-9]+* - - release-cumulus-v[0-9]+* - - release-polkadot-v[0-9]+* - - workflow_dispatch: - -jobs: - tag_rc: - runs-on: ubuntu-latest - strategy: - matrix: - channel: - - name: "RelEng: Polkadot Release Coordination" - room: '!cqAmzdIcbOFwrdrubV:parity.io' - environment: release - - steps: - - name: Checkout sources - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 - with: - fetch-depth: 0 - - - name: Get release product - id: get_rel_product - shell: bash - run: | - current_branch=$(git branch --show-current) - echo "Current branch: $current_branch" - if [[ "$current_branch" =~ "release-polkadot" ]]; then - echo "product=polkadot" >> $GITHUB_OUTPUT - elif [[ "$current_branch" =~ "release-cumulus" ]]; then - echo "product=polkadot-parachain" >> $GITHUB_OUTPUT - fi - - - - name: Compute next rc tag for polkadot - if: ${{ steps.get_rel_product.outputs.product == 'polkadot' }} - id: compute_tag_polkadot - shell: bash - run: | - . ./.github/scripts/common/lib.sh - - # Get last rc tag if exists, else set it to {version}-rc1 - version=$(get_version_from_ghref ${GITHUB_REF}) - echo "$version" - echo "version=$version" >> $GITHUB_OUTPUT - - last_rc=$(get_latest_rc_tag $version polkadot) - - if [ -n "$last_rc" ]; then - suffix=$(increment_rc_tag $last_rc) - echo "new_tag=$version-rc$suffix" >> $GITHUB_OUTPUT - echo "first_rc=false" >> $GITHUB_OUTPUT - else - echo "new_tag=$version-rc1" >> $GITHUB_OUTPUT - echo "first_rc=true" >> $GITHUB_OUTPUT - fi - - - name: Compute next rc tag for polkadot-parachain - if: ${{ steps.get_rel_product.outputs.product == 'polkadot-parachain' }} - id: compute_tag_cumulus - shell: bash - run: | - . ./.github/scripts/common/lib.sh - - # Get last rc tag if exists, else set it to polkadot-parachains-{version}-rc1 - version=$(get_version_from_ghref ${GITHUB_REF}) - echo "$version" - echo "version=$version" >> $GITHUB_OUTPUT - - last_rc=$(get_latest_rc_tag $version polkadot-parachain) - if [ -n "$last_rc" ]; then - suffix=$(increment_rc_tag $last_rc) - echo "new_tag=polkadot-parachains-$version-rc$suffix" >> $GITHUB_OUTPUT - echo "first_rc=false" >> $GITHUB_OUTPUT - else - echo "new_tag=polkadot-parachain-$version-rc1" >> $GITHUB_OUTPUT - echo "first_rc=true" >> $GITHUB_OUTPUT - fi - - - name: Apply new tag - uses: tvdias/github-tagger@ed7350546e3e503b5e942dffd65bc8751a95e49d # v0.0.2 - with: - # We can't use the normal GITHUB_TOKEN for the following reason: - # https://docs.github.com/en/actions/reference/events-that-trigger-workflows#triggering-new-workflows-using-a-personal-access-token - # RELEASE_BRANCH_TOKEN requires public_repo OAuth scope - repo-token: "${{ secrets.RELEASE_BRANCH_TOKEN }}" - tag: ${{ steps.compute_tag_polkadot.outputs.new_tag || steps.compute_tag_cumulus.outputs.new_tag }} - - # - id: create-issue - # uses: JasonEtco/create-an-issue@e27dddc79c92bc6e4562f268fffa5ed752639abd # v2.9.1 - # # Only create the issue if it's the first release candidate - # if: steps.compute_tag.outputs.first_rc == 'true' - # env: - # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # VERSION: ${{ steps.compute_tag.outputs.version }} - # with: - # filename: .github/ISSUE_TEMPLATE/release.md - - - name: Send Matrix message to ${{ matrix.channel.name }} - uses: s3krit/matrix-message-action@70ad3fb812ee0e45ff8999d6af11cafad11a6ecf # v0.0.3 - # if: steps.create-issue.outputs.url != '' - with: - room_id: ${{ matrix.channel.room }} - access_token: ${{ secrets.RELEASENOTES_MATRIX_V2_ACCESS_TOKEN }} - server: m.parity.io - message: | - Release process for polkadot ${{ steps.compute_tag_polkadot.outputs.new_tag || steps.compute_tag_cumulus.outputs.new_tag }} has been started.
diff --git a/.github/workflows/release-50_publish-docker.yml b/.github/workflows/release-50_publish-docker.yml index f74fb6a0ad1..567e996b8fd 100644 --- a/.github/workflows/release-50_publish-docker.yml +++ b/.github/workflows/release-50_publish-docker.yml @@ -220,7 +220,6 @@ jobs: runs-on: ubuntu-latest outputs: polkadot_apt_version: ${{ steps.fetch-latest-apt.outputs.polkadot_apt_version }} - polkadot_container_tag: ${{ steps.fetch-latest-apt.outputs.polkadot_container_tag }} container: image: paritytech/parity-keyring options: --user root @@ -231,9 +230,7 @@ jobs: apt update apt show polkadot version=$(apt show polkadot 2>/dev/null | grep "Version:" | awk '{print $2}') - tag=$(echo $version | sed 's/-.*//') echo "polkadot_apt_version=v$version" >> $GITHUB_OUTPUT - echo "polkadot_container_tag=v$tag" >> $GITHUB_OUTPUT echo "You passed ${{ inputs.version }} but this is ignored" echo "We use the version from the Debian Package: $version" @@ -279,7 +276,7 @@ jobs: # TODO: It would be good to get rid of this GHA that we don't really need. tags: | parity/polkadot:latest - parity/polkadot:${{ needs.fetch-latest-debian-package-version.outputs.polkadot_container_tag }} + parity/polkadot:${{ needs.fetch-latest-debian-package-version.outputs.polkadot_apt_version }} build-args: | VCS_REF=${{ github.ref }} POLKADOT_VERSION=${{ needs.fetch-latest-debian-package-version.outputs.polkadot_apt_version }} diff --git a/.github/workflows/release-99_notif-published.yml b/.github/workflows/release-99_notif-published.yml deleted file mode 100644 index b35120ca4e1..00000000000 --- a/.github/workflows/release-99_notif-published.yml +++ /dev/null @@ -1,61 +0,0 @@ -name: Release - Announce release to Matrix rooms -on: - release: - types: - - published - - prereleased - -jobs: - ping_matrix: - runs-on: ubuntu-latest - strategy: - matrix: - channel: - # Internal - - name: 'RelEng: Cumulus Release Coordination' - room: '!NAEMyPAHWOiOQHsvus:parity.io' - pre-releases: true - - name: "RelEng: Polkadot Release Coordination" - room: '!cqAmzdIcbOFwrdrubV:parity.io' - pre-release: true - - name: 'General: Rust, Polkadot, Substrate' - room: '!aJymqQYtCjjqImFLSb:parity.io' - pre-release: false - - name: 'Team: DevOps' - room: '!lUslSijLMgNcEKcAiE:parity.io' - pre-release: true - - # External - - name: 'Ledger <> Polkadot Coordination' - room: '!EoIhaKfGPmFOBrNSHT:web3.foundation' - pre-release: true - - # Public - # - name: '#KusamaValidatorLounge:polkadot.builders' - # room: '!LhjZccBOqFNYKLdmbb:polkadot.builders' - # pre-releases: false - # - name: '#kusama-announcements:matrix.parity.io' - # room: '!FMwxpQnYhRCNDRsYGI:matrix.parity.io' - # pre-release: false - # - name: '#polkadotvalidatorlounge:web3.foundation' - # room: '!NZrbtteFeqYKCUGQtr:matrix.parity.io' - # pre-release: false - # - name: '#polkadot-announcements:matrix.parity.io' - # room: '!UqHPWiCBGZWxrmYBkF:matrix.parity.io' - # pre-release: false - - steps: - - name: Matrix notification to ${{ matrix.channel.name }} - if: github.event.release.prerelease == false || matrix.channel.pre-release - uses: s3krit/matrix-message-action@70ad3fb812ee0e45ff8999d6af11cafad11a6ecf # v0.0.3 - with: - room_id: ${{ matrix.channel.room }} - access_token: ${{ secrets.RELEASENOTES_MATRIX_V2_ACCESS_TOKEN }} - server: m.parity.io - message: | - A (pre)release has been ${{github.event.action}} in **${{github.event.repository.full_name}}:**
- Release version: [${{github.event.release.tag_name}}](${{github.event.release.html_url}}) - - ----- - - ${{github.event.release.body}} diff --git a/.github/workflows/review-bot.yml b/.github/workflows/review-bot.yml index 0a7e80f007c..5970989cde0 100644 --- a/.github/workflows/review-bot.yml +++ b/.github/workflows/review-bot.yml @@ -23,7 +23,7 @@ jobs: app_id: ${{ secrets.REVIEW_APP_ID }} private_key: ${{ secrets.REVIEW_APP_KEY }} - name: "Evaluates PR reviews and assigns reviewers" - uses: paritytech/review-bot@v2.3.0 + uses: paritytech/review-bot@v2.2.0 with: repo-token: ${{ steps.app_token.outputs.token }} team-token: ${{ steps.app_token.outputs.token }} diff --git a/.gitignore b/.gitignore index 2f1631fb4b9..581c417cb85 100644 --- a/.gitignore +++ b/.gitignore @@ -29,7 +29,6 @@ bin/node-template/Cargo.lock nohup.out polkadot_argument_parsing polkadot.* -!docs/sdk/src/polkadot_sdk/polkadot.rs pwasm-alloc/Cargo.lock pwasm-libc/Cargo.lock release-artifacts diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index dc4b3cf162e..f7e54961fa9 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -69,6 +69,7 @@ default: .common-before-script: before_script: - !reference [.job-switcher, before_script] + - !reference [.timestamp, before_script] - !reference [.pipeline-stopper-vars, script] .job-switcher: @@ -106,37 +107,27 @@ default: .docker-env: image: "${CI_IMAGE}" - variables: - FL_FORKLIFT_VERSION: !reference [.forklift, variables, FL_FORKLIFT_VERSION] before_script: - !reference [.common-before-script, before_script] - !reference [.prepare-env, before_script] - !reference [.rust-info-script, script] - - !reference [.forklift-cache, before_script] + - !reference [.rusty-cachier, before_script] tags: - linux-docker -# -.forklift-cache: +# rusty-cachier's hidden job. Parts of this job are used to instrument the pipeline's other real jobs with rusty-cachier +# rusty-cachier's commands are described here: https://gitlab.parity.io/parity/infrastructure/ci_cd/rusty-cachier/client#description +.rusty-cachier: before_script: - - 'curl --header "PRIVATE-TOKEN: $FL_CI_GROUP_TOKEN" -o forklift -L "${CI_API_V4_URL}/projects/676/packages/generic/forklift/${FL_FORKLIFT_VERSION}/forklift_${FL_FORKLIFT_VERSION}_linux_amd64"' - - chmod +x forklift - - mkdir .forklift - - cp $FL_FORKLIFT_CONFIG .forklift/config.toml - - export FORKLIFT_PACKAGE_SUFFIX=${CI_JOB_NAME/ [0-9 \/]*} - - shopt -s expand_aliases - - export PATH=$PATH:$(pwd) - - | - if [ "$FORKLIFT_BYPASS" != "true" ]; then - echo "FORKLIFT_BYPASS not set, creating alias cargo='forklift cargo'" - alias cargo="forklift cargo" - fi - - ls -al - - rm -f forklift.sock - - forklift clean - # - - echo "FL_FORKLIFT_VERSION ${FL_FORKLIFT_VERSION}" - - echo "FORKLIFT_PACKAGE_SUFFIX $FORKLIFT_PACKAGE_SUFFIX" + # - curl -s https://gitlab-ci-token:${CI_JOB_TOKEN}@gitlab.parity.io/parity/infrastructure/ci_cd/rusty-cachier/client/-/raw/release/util/install.sh | bash + # - mkdir -p cargo_home cargo_target_dir + # - export CARGO_HOME=$CI_PROJECT_DIR/cargo_home + # - export CARGO_TARGET_DIR=$CI_PROJECT_DIR/cargo_target_dir + # - find . \( -path ./cargo_target_dir -o -path ./cargo_home \) -prune -o -type f -exec touch -t 202005260100 {} + + # - git restore-mtime + # - rusty-cachier --version + # - rusty-cachier project touch-changed + - echo tbd .common-refs: rules: @@ -220,13 +211,14 @@ include: - .gitlab/pipeline/publish.yml # zombienet jobs - .gitlab/pipeline/zombienet.yml + # timestamp handler + - project: parity/infrastructure/ci_cd/shared + ref: v0.2 + file: /common/timestamp.yml # ci image - project: parity/infrastructure/ci_cd/shared ref: main file: /common/ci-unified.yml - - project: parity/infrastructure/ci_cd/shared - ref: main - file: /common/forklift.yml # This job cancels the whole pipeline if any of provided jobs fail. # In a DAG, every jobs chain is executed independently of others. The `fail_fast` principle suggests # to fail the pipeline as soon as possible to shorten the feedback loop. diff --git a/.gitlab/pipeline/build.yml b/.gitlab/pipeline/build.yml index 377236193cc..5c13045706c 100644 --- a/.gitlab/pipeline/build.yml +++ b/.gitlab/pipeline/build.yml @@ -125,7 +125,7 @@ build-rustdoc: find "$path" -name '*.html' | xargs -I {} -P "$(nproc)" bash -c 'process_file "$@"' _ {} } inject_simple_analytics "./crate-docs" - - echo "" > ./crate-docs/index.html + - echo "" > ./crate-docs/index.html build-implementers-guide: stage: build diff --git a/.gitlab/pipeline/check.yml b/.gitlab/pipeline/check.yml index 3b14034a110..b2f2efc5e66 100644 --- a/.gitlab/pipeline/check.yml +++ b/.gitlab/pipeline/check.yml @@ -4,10 +4,8 @@ cargo-clippy: - .docker-env - .common-refs - .pipeline-stopper-artifacts - variables: - RUSTFLAGS: "-D warnings" script: - - SKIP_WASM_BUILD=1 cargo clippy --all-targets --locked --workspace + - SKIP_WASM_BUILD=1 env -u RUSTFLAGS cargo clippy --all-targets --locked --workspace check-try-runtime: stage: check @@ -67,7 +65,11 @@ test-rust-features: - .kubernetes-env - .test-refs-no-trigger-prs-only script: - - bash .gitlab/rust-features.sh . + - git clone + --depth=1 + --branch="master" + https://github.com/paritytech/pipeline-scripts + - bash ./pipeline-scripts/rust-features.sh . job-starter: stage: check @@ -85,17 +87,9 @@ check-rust-feature-propagation: - .kubernetes-env - .common-refs script: + - cargo install --locked --version 0.13.3 -q -f zepter && zepter --version - zepter run check -check-toml-format: - stage: check - extends: - - .kubernetes-env - - .common-refs - script: - - taplo format --check --config .config/taplo.toml - - echo "Please run `taplo format --config .config/taplo.toml` to fix any toml formatting issues" - # More info can be found here: https://github.com/paritytech/polkadot/pull/5865 .check-runtime-migration: stage: check @@ -117,7 +111,6 @@ check-toml-format: time ./try-runtime ${COMMAND_EXTRA_ARGS} \ --runtime ./target/release/wbuild/"$PACKAGE"/"$WASM" \ on-runtime-upgrade --disable-spec-version-check --checks=all ${SUBCOMMAND_EXTRA_ARGS} live --uri ${URI} - sleep 5 # Check runtime migrations for Parity managed relay chains check-runtime-migration-westend: diff --git a/.gitlab/pipeline/short-benchmarks.yml b/.gitlab/pipeline/short-benchmarks.yml index 97bce479927..0218d3fdac0 100644 --- a/.gitlab/pipeline/short-benchmarks.yml +++ b/.gitlab/pipeline/short-benchmarks.yml @@ -49,6 +49,16 @@ short-benchmark-westend: &short-bench script: - ./artifacts/polkadot-parachain benchmark pallet --chain $RUNTIME_CHAIN --pallet "*" --extrinsic "*" --steps 2 --repeat 1 +short-benchmark-asset-hub-polkadot: + <<: *short-bench-cumulus + variables: + RUNTIME_CHAIN: asset-hub-polkadot-dev + +short-benchmark-asset-hub-kusama: + <<: *short-bench-cumulus + variables: + RUNTIME_CHAIN: asset-hub-kusama-dev + short-benchmark-asset-hub-rococo: <<: *short-bench-cumulus variables: @@ -59,6 +69,16 @@ short-benchmark-asset-hub-westend: variables: RUNTIME_CHAIN: asset-hub-westend-dev +short-benchmark-bridge-hub-polkadot: + <<: *short-bench-cumulus + variables: + RUNTIME_CHAIN: bridge-hub-polkadot-dev + +short-benchmark-bridge-hub-kusama: + <<: *short-bench-cumulus + variables: + RUNTIME_CHAIN: bridge-hub-kusama-dev + short-benchmark-bridge-hub-rococo: <<: *short-bench-cumulus variables: @@ -69,11 +89,21 @@ short-benchmark-bridge-hub-westend: variables: RUNTIME_CHAIN: bridge-hub-westend-dev +short-benchmark-collectives-polkadot: + <<: *short-bench-cumulus + variables: + RUNTIME_CHAIN: collectives-polkadot-dev + short-benchmark-collectives-westend: <<: *short-bench-cumulus variables: RUNTIME_CHAIN: collectives-westend-dev +short-benchmark-glutton-kusama: + <<: *short-bench-cumulus + variables: + RUNTIME_CHAIN: glutton-kusama-dev-1300 + short-benchmark-glutton-westend: <<: *short-bench-cumulus variables: diff --git a/.gitlab/pipeline/test.yml b/.gitlab/pipeline/test.yml index 0e7d96f3dba..9c3fa7701c8 100644 --- a/.gitlab/pipeline/test.yml +++ b/.gitlab/pipeline/test.yml @@ -270,7 +270,7 @@ cargo-check-benches: SKIP_WASM_BUILD=1 time cargo check --locked --benches --all; cargo run --locked --release -p node-bench -- ::trie::read::small --json | tee ./artifacts/benches/$CI_COMMIT_REF_NAME-$CI_COMMIT_SHORT_SHA/::trie::read::small.json; - echo "___Cache could be uploaded___"; + echo "___Uploading cache for rusty-cachier___"; ;; 2) cargo run --locked --release -p node-bench -- ::node::import::sr25519::transfer_keep_alive::paritydb::small --json @@ -313,7 +313,7 @@ node-bench-regression-guard: after_script: [""] # if this fails run `bot update-ui` in the Pull Request or "./scripts/update-ui-tests.sh" locally -# see ./docs/contributor/CONTRIBUTING.md#ui-tests +# see ./docs/CONTRIBUTING.md#ui-tests test-frame-ui: stage: test extends: @@ -395,6 +395,7 @@ test-linux-stable-int: RUN_UI_TESTS: 1 script: - WASM_BUILD_NO_COLOR=1 + RUST_LOG=sync=trace,consensus=trace,client=trace,state-db=trace,db=trace,forks=trace,state_db=trace,storage_cache=trace time cargo test -p staging-node-cli --release --locked -- --ignored # more information about this job can be found here: @@ -438,8 +439,7 @@ cargo-check-each-crate: - .run-immediately # - .collect-artifacts variables: - RUSTFLAGS: "-D warnings" - # $CI_JOB_NAME is set manually so that cache could be shared for all jobs + # $CI_JOB_NAME is set manually so that rusty-cachier can share the cache for all # "cargo-check-each-crate I/N" jobs CI_JOB_NAME: cargo-check-each-crate timeout: 2h @@ -462,10 +462,10 @@ cargo-check-each-crate-macos: variables: SKIP_WASM_BUILD: 1 script: + # TODO: enable rusty-cachier once it supports Mac # TODO: use parallel jobs, as per cargo-check-each-crate, once more Mac runners are available # - time ./scripts/ci/gitlab/check-each-crate.py 1 1 - time cargo check --workspace --locked - timeout: 2h tags: - osx @@ -488,7 +488,7 @@ cargo-hfuzz: # use git version of honggfuzz-rs until v0.5.56 is out, we need a few recent changes: # https://github.com/rust-fuzz/honggfuzz-rs/pull/75 to avoid breakage on debian # https://github.com/rust-fuzz/honggfuzz-rs/pull/81 fix to the above pr - # https://github.com/rust-fuzz/honggfuzz-rs/pull/82 fix for handling absolute CARGO_TARGET_DIR + # https://github.com/rust-fuzz/honggfuzz-rs/pull/82 fix for handling rusty-cachier's absolute CARGO_TARGET_DIR HFUZZ_BUILD_ARGS: > --config=patch.crates-io.honggfuzz.git="https://github.com/altaua/honggfuzz-rs" --config=patch.crates-io.honggfuzz.rev="205f7c8c059a0d98fe1cb912cdac84f324cb6981" diff --git a/.gitlab/pipeline/zombienet.yml b/.gitlab/pipeline/zombienet.yml index d5845611c60..558cc549cb0 100644 --- a/.gitlab/pipeline/zombienet.yml +++ b/.gitlab/pipeline/zombienet.yml @@ -1,7 +1,7 @@ .zombienet-refs: extends: .build-refs variables: - ZOMBIENET_IMAGE: "docker.io/paritytech/zombienet:v1.3.86" + ZOMBIENET_IMAGE: "docker.io/paritytech/zombienet:v1.3.83" include: # substrate tests diff --git a/.gitlab/pipeline/zombienet/polkadot.yml b/.gitlab/pipeline/zombienet/polkadot.yml index 356abaa93cd..995dd982532 100644 --- a/.gitlab/pipeline/zombienet/polkadot.yml +++ b/.gitlab/pipeline/zombienet/polkadot.yml @@ -115,30 +115,6 @@ zombienet-polkadot-functional-0006-parachains-max-tranche0: --local-dir="${LOCAL_DIR}/functional" --test="0006-parachains-max-tranche0.zndsl" -zombienet-polkadot-functional-0007-dispute-freshly-finalized: - extends: - - .zombienet-polkadot-common - script: - - /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh - --local-dir="${LOCAL_DIR}/functional" - --test="0007-dispute-freshly-finalized.zndsl" - -zombienet-polkadot-functional-0008-dispute-old-finalized: - extends: - - .zombienet-polkadot-common - script: - - /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh - --local-dir="${LOCAL_DIR}/functional" - --test="0008-dispute-old-finalized.zndsl" - -zombienet-polkadot-functional-0009-approval-voting-coalescing: - extends: - - .zombienet-polkadot-common - script: - - /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh - --local-dir="${LOCAL_DIR}/functional" - --test="0009-approval-voting-coalescing.zndsl" - zombienet-polkadot-smoke-0001-parachains-smoke-test: extends: - .zombienet-polkadot-common diff --git a/.gitlab/rust-features.sh b/.gitlab/rust-features.sh deleted file mode 100755 index c0ac192a6ec..00000000000 --- a/.gitlab/rust-features.sh +++ /dev/null @@ -1,87 +0,0 @@ -#!/usr/bin/env bash - -############################################################################## -# -# This script checks that crates to not carelessly enable features that -# should stay disabled. It's important to check that since features -# are used to gate specific functionality which should only be enabled -# when the feature is explicitly enabled. -# -# Invocation scheme: -# ./rust-features.sh -# -# Example: -# ./rust-features.sh path/to/substrate -# -# The steps of this script: -# 1. Check that all required dependencies are installed. -# 2. Check that all rules are fullfilled for the whole workspace. If not: -# 4. Check all crates to find the offending ones. -# 5. Print all offending crates and exit with code 1. -# -############################################################################## - -set -eu - -# Check that cargo and grep are installed - otherwise abort. -command -v cargo >/dev/null 2>&1 || { echo >&2 "cargo is required but not installed. Aborting."; exit 1; } -command -v grep >/dev/null 2>&1 || { echo >&2 "grep is required but not installed. Aborting."; exit 1; } - -# Enter the workspace root folder. -cd "$1" -echo "Workspace root is $PWD" - -function main() { - feature_does_not_imply 'default' 'runtime-benchmarks' - feature_does_not_imply 'std' 'runtime-benchmarks' - feature_does_not_imply 'default' 'try-runtime' - feature_does_not_imply 'std' 'try-runtime' -} - -# Accepts two feature names as arguments. -# Checks that the first feature does not imply the second one. -function feature_does_not_imply() { - ENABLED=$1 - STAYS_DISABLED=$2 - echo "📏 Checking that $ENABLED does not imply $STAYS_DISABLED ..." - - # Check if the forbidden feature is enabled anywhere in the workspace. - # But only check "normal" dependencies, so no "dev" or "build" dependencies. - if cargo tree --no-default-features --locked --workspace -e features,normal --features "$ENABLED" | grep -qF "feature \"$STAYS_DISABLED\""; then - echo "❌ $ENABLED implies $STAYS_DISABLED in the workspace" - else - echo "✅ $ENABLED does not imply $STAYS_DISABLED in the workspace" - return - fi - - # Find all Cargo.toml files but exclude the root one since we already know that it is broken. - CARGOS=`find . -name Cargo.toml -not -path ./Cargo.toml` - NUM_CRATES=`echo "$CARGOS" | wc -l` - FAILED=0 - PASSED=0 - echo "🔍 Checking all $NUM_CRATES crates - this takes some time." - - for CARGO in $CARGOS; do - OUTPUT=$(cargo tree --no-default-features --locked --offline -e features,normal --features $ENABLED --manifest-path $CARGO 2>&1 || true) - - if echo "$OUTPUT" | grep -qF "not supported for packages in this workspace"; then - # This case just means that the pallet does not support the - # requested feature which is fine. - PASSED=$((PASSED+1)) - elif echo "$OUTPUT" | grep -qF "feature \"$STAYS_DISABLED\""; then - echo "❌ Violation in $CARGO by dependency:" - # Best effort hint for which dependency needs to be fixed. - echo "$OUTPUT" | grep -wF "feature \"$STAYS_DISABLED\"" | head -n 1 - FAILED=$((FAILED+1)) - else - PASSED=$((PASSED+1)) - fi - done - - echo "Checked $NUM_CRATES crates in total of which $FAILED failed and $PASSED passed." - echo "Exiting with code 1" - exit 1 -} - -main "$@" - diff --git a/.gitlab/spellcheck.toml b/.gitlab/spellcheck.toml index 8c60bf6915d..025c7a0a461 100644 --- a/.gitlab/spellcheck.toml +++ b/.gitlab/spellcheck.toml @@ -8,20 +8,20 @@ use_builtin = true [hunspell.quirks] # He tagged it as 'TheGreatestOfAllTimes' transform_regex = [ - # `Type`'s +# `Type`'s "^'([^\\s])'$", - # 5x - # 10.7% +# 5x +# 10.7% "^[0-9_]+(?:\\.[0-9]*)?(x|%)$", - # Transforms' +# Transforms' "^(.*)'$", - # backslashes - "^[0-9]*+k|MB|Mb|ms|Mbit|nd|th|rd$", +# backslashes "^\\+$", - # single char `=` `>` `%` .. + "^[0-9]*+k|MB|Mb|ms|Mbit|nd|th|rd$", +# single char `=` `>` `%` .. "^=|>|<|%$", - # 22_100 - "^(?:[0-9]+_)+[0-9]+$", +# 22_100 + "^(?:[0-9]+_)+[0-9]+$" ] allow_concatenation = true allow_dashes = true diff --git a/.prdoc.toml b/.prdoc.toml deleted file mode 100644 index 01e2eebe54b..00000000000 --- a/.prdoc.toml +++ /dev/null @@ -1,7 +0,0 @@ -# Config file for prdoc, see https://github.com/paritytech/prdoc - -version = 1 -schema = "prdoc/schema_user.json" -output_dir = "prdoc" -prdoc_folders = ["prdoc"] -template = "prdoc/.template.prdoc" diff --git a/Cargo.lock b/Cargo.lock index 2058c207063..90adee46b85 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -541,24 +541,10 @@ dependencies = [ "scale-info", ] -[[package]] -name = "ark-scale" -version = "0.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f69c00b3b529be29528a6f2fd5fa7b1790f8bed81b9cdca17e326538545a179" -dependencies = [ - "ark-ec", - "ark-ff", - "ark-serialize", - "ark-std", - "parity-scale-codec", - "scale-info", -] - [[package]] name = "ark-secret-scalar" version = "0.0.2" -source = "git+https://github.com/w3f/ring-vrf?rev=e9782f9#e9782f938629c90f3adb3fff2358bc8d1386af3e" +source = "git+https://github.com/w3f/ring-vrf?rev=3ddc205#3ddc2051066c4b3f0eadd0ba5700df12500d9754" dependencies = [ "ark-ec", "ark-ff", @@ -566,7 +552,7 @@ dependencies = [ "ark-std", "ark-transcript", "digest 0.10.7", - "getrandom_or_panic", + "rand_core 0.6.4", "zeroize", ] @@ -607,7 +593,7 @@ dependencies = [ [[package]] name = "ark-transcript" version = "0.0.2" -source = "git+https://github.com/w3f/ring-vrf?rev=e9782f9#e9782f938629c90f3adb3fff2358bc8d1386af3e" +source = "git+https://github.com/w3f/ring-vrf?rev=3ddc205#3ddc2051066c4b3f0eadd0ba5700df12500d9754" dependencies = [ "ark-ff", "ark-serialize", @@ -744,6 +730,150 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9" +[[package]] +name = "asset-hub-kusama-runtime" +version = "0.9.420" +dependencies = [ + "asset-test-utils", + "assets-common", + "cumulus-pallet-aura-ext", + "cumulus-pallet-dmp-queue", + "cumulus-pallet-parachain-system", + "cumulus-pallet-session-benchmarking", + "cumulus-pallet-xcm", + "cumulus-pallet-xcmp-queue", + "cumulus-primitives-core", + "cumulus-primitives-utility", + "frame-benchmarking", + "frame-executive", + "frame-support", + "frame-system", + "frame-system-benchmarking", + "frame-system-rpc-runtime-api", + "frame-try-runtime", + "hex-literal", + "log", + "pallet-asset-conversion", + "pallet-asset-conversion-tx-payment", + "pallet-assets", + "pallet-aura", + "pallet-authorship", + "pallet-balances", + "pallet-collator-selection", + "pallet-message-queue", + "pallet-multisig", + "pallet-nft-fractionalization", + "pallet-nfts", + "pallet-nfts-runtime-api", + "pallet-proxy", + "pallet-session", + "pallet-state-trie-migration", + "pallet-timestamp", + "pallet-transaction-payment", + "pallet-transaction-payment-rpc-runtime-api", + "pallet-uniques", + "pallet-utility", + "pallet-xcm", + "pallet-xcm-benchmarks", + "parachains-common", + "parity-scale-codec", + "polkadot-core-primitives", + "polkadot-parachain-primitives", + "polkadot-runtime-common", + "primitive-types", + "scale-info", + "smallvec", + "sp-api", + "sp-block-builder", + "sp-consensus-aura", + "sp-core", + "sp-genesis-builder", + "sp-inherents", + "sp-offchain", + "sp-runtime", + "sp-session", + "sp-std 8.0.0", + "sp-storage 13.0.0", + "sp-transaction-pool", + "sp-version", + "sp-weights", + "staging-parachain-info", + "staging-xcm", + "staging-xcm-builder", + "staging-xcm-executor", + "substrate-wasm-builder", +] + +[[package]] +name = "asset-hub-polkadot-runtime" +version = "0.9.420" +dependencies = [ + "asset-test-utils", + "assets-common", + "cumulus-pallet-aura-ext", + "cumulus-pallet-dmp-queue", + "cumulus-pallet-parachain-system", + "cumulus-pallet-session-benchmarking", + "cumulus-pallet-xcm", + "cumulus-pallet-xcmp-queue", + "cumulus-primitives-core", + "cumulus-primitives-utility", + "frame-benchmarking", + "frame-executive", + "frame-support", + "frame-system", + "frame-system-benchmarking", + "frame-system-rpc-runtime-api", + "frame-try-runtime", + "hex-literal", + "log", + "pallet-asset-tx-payment", + "pallet-assets", + "pallet-aura", + "pallet-authorship", + "pallet-balances", + "pallet-collator-selection", + "pallet-message-queue", + "pallet-multisig", + "pallet-nfts", + "pallet-nfts-runtime-api", + "pallet-proxy", + "pallet-session", + "pallet-timestamp", + "pallet-transaction-payment", + "pallet-transaction-payment-rpc-runtime-api", + "pallet-uniques", + "pallet-utility", + "pallet-xcm", + "pallet-xcm-benchmarks", + "parachains-common", + "parity-scale-codec", + "polkadot-core-primitives", + "polkadot-parachain-primitives", + "polkadot-runtime-common", + "scale-info", + "smallvec", + "sp-api", + "sp-block-builder", + "sp-consensus-aura", + "sp-core", + "sp-genesis-builder", + "sp-inherents", + "sp-offchain", + "sp-runtime", + "sp-session", + "sp-std 8.0.0", + "sp-storage 13.0.0", + "sp-transaction-pool", + "sp-version", + "sp-weights", + "staging-parachain-info", + "staging-xcm", + "staging-xcm-builder", + "staging-xcm-executor", + "substrate-wasm-builder", +] + [[package]] name = "asset-hub-rococo-emulated-chain" version = "0.0.0" @@ -775,6 +905,7 @@ dependencies = [ "pallet-xcm", "parachains-common", "parity-scale-codec", + "penpal-runtime", "rococo-runtime", "rococo-system-emulated-network", "sp-runtime", @@ -885,7 +1016,6 @@ dependencies = [ "asset-test-utils", "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", - "cumulus-pallet-xcmp-queue", "emulated-integration-tests-common", "frame-support", "frame-system", @@ -919,6 +1049,7 @@ dependencies = [ "bp-bridge-hub-rococo", "bp-bridge-hub-westend", "cumulus-pallet-aura-ext", + "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", "cumulus-pallet-session-benchmarking", "cumulus-pallet-xcm", @@ -1158,7 +1289,7 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -1175,7 +1306,7 @@ checksum = "bc00ceb34980c03614e35a3a4e218276a0a824e911d07651cd0d858a51e8c0f0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -1238,7 +1369,7 @@ dependencies = [ [[package]] name = "bandersnatch_vrfs" version = "0.0.4" -source = "git+https://github.com/w3f/ring-vrf?rev=e9782f9#e9782f938629c90f3adb3fff2358bc8d1386af3e" +source = "git+https://github.com/w3f/ring-vrf?rev=3ddc205#3ddc2051066c4b3f0eadd0ba5700df12500d9754" dependencies = [ "ark-bls12-381", "ark-ec", @@ -1351,7 +1482,7 @@ dependencies = [ "regex", "rustc-hash", "shlex", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -1361,8 +1492,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93f2635620bf0b9d4576eb7bb9a38a55df78bd1205d26fa994b25911a69f212f" dependencies = [ "bitcoin_hashes", - "rand 0.7.3", - "rand_core 0.5.1", + "rand 0.8.5", + "rand_core 0.6.4", "serde", "unicode-normalization", ] @@ -1536,14 +1667,13 @@ dependencies = [ [[package]] name = "bounded-collections" -version = "0.1.9" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca548b6163b872067dc5eb82fd130c56881435e30367d2073594a3d9744120dd" +checksum = "eb5b05133427c07c4776906f673ccf36c21b102c9829c641a5b56bd151d44fd6" dependencies = [ "log", "parity-scale-codec", "scale-info", - "schemars", "serde", ] @@ -1834,20 +1964,141 @@ dependencies = [ ] [[package]] -name = "bp-xcm-bridge-hub" +name = "bp-xcm-bridge-hub-router" +version = "0.1.0" +dependencies = [ + "parity-scale-codec", + "scale-info", + "sp-core", + "sp-runtime", +] + +[[package]] +name = "bridge-hub-kusama-runtime" version = "0.1.0" dependencies = [ + "bridge-hub-test-utils", + "cumulus-pallet-aura-ext", + "cumulus-pallet-dmp-queue", + "cumulus-pallet-parachain-system", + "cumulus-pallet-session-benchmarking", + "cumulus-pallet-xcm", + "cumulus-pallet-xcmp-queue", + "cumulus-primitives-core", + "cumulus-primitives-utility", + "frame-benchmarking", + "frame-executive", + "frame-support", + "frame-system", + "frame-system-benchmarking", + "frame-system-rpc-runtime-api", + "frame-try-runtime", + "hex-literal", + "log", + "pallet-aura", + "pallet-authorship", + "pallet-balances", + "pallet-collator-selection", + "pallet-message-queue", + "pallet-multisig", + "pallet-session", + "pallet-timestamp", + "pallet-transaction-payment", + "pallet-transaction-payment-rpc-runtime-api", + "pallet-utility", + "pallet-xcm", + "pallet-xcm-benchmarks", + "parachains-common", + "parity-scale-codec", + "polkadot-core-primitives", + "polkadot-parachain-primitives", + "polkadot-runtime-common", + "scale-info", + "serde", + "smallvec", + "sp-api", + "sp-block-builder", + "sp-consensus-aura", + "sp-core", + "sp-genesis-builder", + "sp-inherents", + "sp-io", + "sp-offchain", + "sp-runtime", + "sp-session", "sp-std 8.0.0", + "sp-storage 13.0.0", + "sp-transaction-pool", + "sp-version", + "staging-parachain-info", + "staging-xcm", + "staging-xcm-builder", + "staging-xcm-executor", + "substrate-wasm-builder", ] [[package]] -name = "bp-xcm-bridge-hub-router" +name = "bridge-hub-polkadot-runtime" version = "0.1.0" dependencies = [ + "bridge-hub-test-utils", + "cumulus-pallet-aura-ext", + "cumulus-pallet-dmp-queue", + "cumulus-pallet-parachain-system", + "cumulus-pallet-session-benchmarking", + "cumulus-pallet-xcm", + "cumulus-pallet-xcmp-queue", + "cumulus-primitives-core", + "cumulus-primitives-utility", + "frame-benchmarking", + "frame-executive", + "frame-support", + "frame-system", + "frame-system-benchmarking", + "frame-system-rpc-runtime-api", + "frame-try-runtime", + "hex-literal", + "log", + "pallet-aura", + "pallet-authorship", + "pallet-balances", + "pallet-collator-selection", + "pallet-message-queue", + "pallet-multisig", + "pallet-session", + "pallet-timestamp", + "pallet-transaction-payment", + "pallet-transaction-payment-rpc-runtime-api", + "pallet-utility", + "pallet-xcm", + "pallet-xcm-benchmarks", + "parachains-common", "parity-scale-codec", + "polkadot-core-primitives", + "polkadot-parachain-primitives", + "polkadot-runtime-common", "scale-info", + "serde", + "smallvec", + "sp-api", + "sp-block-builder", + "sp-consensus-aura", "sp-core", + "sp-genesis-builder", + "sp-inherents", + "sp-io", + "sp-offchain", "sp-runtime", + "sp-session", + "sp-std 8.0.0", + "sp-storage 13.0.0", + "sp-transaction-pool", + "sp-version", + "staging-parachain-info", + "staging-xcm", + "staging-xcm-builder", + "staging-xcm-executor", + "substrate-wasm-builder", ] [[package]] @@ -1883,7 +2134,6 @@ dependencies = [ "parachains-common", "parity-scale-codec", "rococo-westend-system-emulated-network", - "sp-runtime", "staging-xcm", "staging-xcm-executor", ] @@ -1894,13 +2144,11 @@ version = "0.1.0" dependencies = [ "bp-asset-hub-rococo", "bp-asset-hub-westend", - "bp-bridge-hub-polkadot", "bp-bridge-hub-rococo", "bp-bridge-hub-westend", "bp-header-chain", "bp-messages", "bp-parachains", - "bp-polkadot-bulletin", "bp-polkadot-core", "bp-relayers", "bp-rococo", @@ -1941,7 +2189,6 @@ dependencies = [ "pallet-utility", "pallet-xcm", "pallet-xcm-benchmarks", - "pallet-xcm-bridge-hub", "parachains-common", "parity-scale-codec", "polkadot-core-primitives", @@ -1993,7 +2240,6 @@ dependencies = [ "frame-executive", "frame-support", "frame-system", - "impl-trait-for-tuples", "log", "pallet-balances", "pallet-bridge-grandpa", @@ -2012,7 +2258,6 @@ dependencies = [ "sp-io", "sp-keyring", "sp-runtime", - "sp-std 8.0.0", "sp-tracing 10.0.0", "staging-parachain-info", "staging-xcm", @@ -2053,7 +2298,6 @@ dependencies = [ "parachains-common", "parity-scale-codec", "rococo-westend-system-emulated-network", - "sp-runtime", "staging-xcm", "staging-xcm-executor", ] @@ -2062,7 +2306,6 @@ dependencies = [ name = "bridge-hub-westend-runtime" version = "0.1.0" dependencies = [ - "bp-asset-hub-rococo", "bp-asset-hub-westend", "bp-bridge-hub-rococo", "bp-bridge-hub-westend", @@ -2077,6 +2320,7 @@ dependencies = [ "bridge-hub-test-utils", "bridge-runtime-common", "cumulus-pallet-aura-ext", + "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", "cumulus-pallet-session-benchmarking", "cumulus-pallet-xcm", @@ -2109,7 +2353,6 @@ dependencies = [ "pallet-utility", "pallet-xcm", "pallet-xcm-benchmarks", - "pallet-xcm-bridge-hub", "parachains-common", "parity-scale-codec", "polkadot-core-primitives", @@ -2153,7 +2396,6 @@ dependencies = [ "bp-relayers", "bp-runtime", "bp-test-utils", - "bp-xcm-bridge-hub", "bp-xcm-bridge-hub-router", "frame-support", "frame-system", @@ -2456,7 +2698,7 @@ checksum = "b9b68e3193982cd54187d71afdb2a271ad4cf8af157858e9cb911b91321de143" dependencies = [ "core2", "multibase", - "multihash 0.17.0", + "multihash", "serde", "unsigned-varint", ] @@ -2528,32 +2770,23 @@ dependencies = [ [[package]] name = "clap" -version = "4.4.11" +version = "4.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfaff671f6b22ca62406885ece523383b9b64022e341e53e009a62ebc47a45f2" +checksum = "d04704f56c2cde07f43e8e2c154b43f216dc5c92fc98ada720177362f953b956" dependencies = [ "clap_builder", - "clap_derive 4.4.7", -] - -[[package]] -name = "clap-num" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488557e97528174edaa2ee268b23a809e0c598213a4bbcb4f34575a46fda147e" -dependencies = [ - "num-traits", + "clap_derive 4.4.2", ] [[package]] name = "clap_builder" -version = "4.4.11" +version = "4.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a216b506622bb1d316cd51328dce24e07bdff4a6128a47c7e7fad11878d5adbb" +checksum = "0e231faeaca65ebd1ea3c737966bf858971cd38c3849107aa3ea7de90a804e45" dependencies = [ "anstream", "anstyle", - "clap_lex 0.6.0", + "clap_lex 0.5.1", "strsim", "terminal_size", ] @@ -2564,7 +2797,7 @@ version = "4.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "586a385f7ef2f8b4d86bddaa0c094794e7ccbfe5ffef1f434fe928143fc783a5" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", ] [[package]] @@ -2582,14 +2815,14 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.4.7" +version = "4.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf9804afaaf59a91e75b022a30fb7229a7901f60c755489cc61c9b423b836442" +checksum = "0862016ff20d69b84ef8247369fabf5c008a7417002411897d40ee1f4532b873" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -2603,9 +2836,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.6.0" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1" +checksum = "cd7cc57abe963c6d3b9d8be5b06ba7c8957a930305ca90304f24ef040aa6f961" [[package]] name = "coarsetime" @@ -2630,18 +2863,75 @@ dependencies = [ ] [[package]] -name = "collectives-westend-emulated-chain" -version = "0.0.0" +name = "collectives-polkadot-runtime" +version = "1.0.0" dependencies = [ - "collectives-westend-runtime", + "cumulus-pallet-aura-ext", + "cumulus-pallet-dmp-queue", + "cumulus-pallet-parachain-system", + "cumulus-pallet-session-benchmarking", + "cumulus-pallet-xcm", + "cumulus-pallet-xcmp-queue", "cumulus-primitives-core", - "emulated-integration-tests-common", + "cumulus-primitives-utility", + "frame-benchmarking", + "frame-executive", "frame-support", + "frame-system", + "frame-system-benchmarking", + "frame-system-rpc-runtime-api", + "frame-try-runtime", + "hex-literal", + "log", + "pallet-alliance", + "pallet-aura", + "pallet-authorship", + "pallet-balances", + "pallet-collator-selection", + "pallet-collective", + "pallet-collective-content", + "pallet-core-fellowship", + "pallet-message-queue", + "pallet-multisig", + "pallet-preimage", + "pallet-proxy", + "pallet-ranked-collective", + "pallet-referenda", + "pallet-salary", + "pallet-scheduler", + "pallet-session", + "pallet-timestamp", + "pallet-transaction-payment", + "pallet-transaction-payment-rpc-runtime-api", + "pallet-utility", + "pallet-xcm", "parachains-common", - "serde_json", + "parity-scale-codec", + "polkadot-core-primitives", + "polkadot-parachain-primitives", + "polkadot-runtime-common", + "scale-info", + "smallvec", + "sp-api", + "sp-arithmetic", + "sp-block-builder", + "sp-consensus-aura", "sp-core", + "sp-genesis-builder", + "sp-inherents", + "sp-io", + "sp-offchain", "sp-runtime", - "westend-emulated-chain", + "sp-session", + "sp-std 8.0.0", + "sp-storage 13.0.0", + "sp-transaction-pool", + "sp-version", + "staging-parachain-info", + "staging-xcm", + "staging-xcm-builder", + "staging-xcm-executor", + "substrate-wasm-builder", ] [[package]] @@ -2649,6 +2939,7 @@ name = "collectives-westend-runtime" version = "1.0.0" dependencies = [ "cumulus-pallet-aura-ext", + "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", "cumulus-pallet-session-benchmarking", "cumulus-pallet-xcm", @@ -2665,7 +2956,6 @@ dependencies = [ "hex-literal", "log", "pallet-alliance", - "pallet-asset-rate", "pallet-aura", "pallet-authorship", "pallet-balances", @@ -2685,7 +2975,6 @@ dependencies = [ "pallet-timestamp", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", - "pallet-treasury", "pallet-utility", "pallet-xcm", "parachains-common", @@ -2715,6 +3004,7 @@ dependencies = [ "staging-xcm-builder", "staging-xcm-executor", "substrate-wasm-builder", + "testnets-common", "westend-runtime-constants", ] @@ -2758,17 +3048,6 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" -[[package]] -name = "colored" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2674ec482fbc38012cf31e6c42ba0177b431a0cb6f15fe40efa5aab1bda516f6" -dependencies = [ - "is-terminal", - "lazy_static", - "windows-sys 0.48.0", -] - [[package]] name = "comfy-table" version = "7.0.1" @@ -2783,7 +3062,7 @@ dependencies = [ [[package]] name = "common" version = "0.1.0" -source = "git+https://github.com/w3f/ring-proof#b273d33f9981e2bb3375ab45faeb537f7ee35224" +source = "git+https://github.com/burdges/ring-proof?branch=patch-1#05a756076cb20f981a52afea3a620168de49f95f" dependencies = [ "ark-ec", "ark-ff", @@ -2791,7 +3070,6 @@ dependencies = [ "ark-serialize", "ark-std", "fflonk", - "getrandom_or_panic", "merlin 3.0.0", "rand_chacha 0.3.1", ] @@ -2902,6 +3180,7 @@ dependencies = [ "pallet-balances", "pallet-collator-selection", "pallet-contracts", + "pallet-contracts-primitives", "pallet-insecure-randomness-collective-flip", "pallet-message-queue", "pallet-multisig", @@ -3167,7 +3446,7 @@ dependencies = [ "anes", "cast", "ciborium", - "clap 4.4.11", + "clap 4.4.6", "criterion-plot", "futures", "is-terminal", @@ -3342,13 +3621,12 @@ dependencies = [ name = "cumulus-client-cli" version = "0.1.0" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "parity-scale-codec", "sc-chain-spec", "sc-cli", "sc-client-api", "sc-service", - "sp-blockchain", "sp-core", "sp-runtime", "url", @@ -3564,7 +3842,6 @@ dependencies = [ "cumulus-client-network", "cumulus-client-pov-recovery", "cumulus-primitives-core", - "cumulus-primitives-proof-size-hostfunction", "cumulus-relay-chain-inprocess-interface", "cumulus-relay-chain-interface", "cumulus-relay-chain-minimal-node", @@ -3634,7 +3911,6 @@ dependencies = [ "cumulus-pallet-parachain-system-proc-macro", "cumulus-primitives-core", "cumulus-primitives-parachain-inherent", - "cumulus-primitives-proof-size-hostfunction", "cumulus-test-client", "cumulus-test-relay-sproof-builder", "environmental", @@ -3666,17 +3942,16 @@ dependencies = [ "sp-version", "staging-xcm", "trie-db", - "trie-standardmap", ] [[package]] name = "cumulus-pallet-parachain-system-proc-macro" version = "0.1.0" dependencies = [ - "proc-macro-crate 2.0.1", + "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -3815,18 +4090,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "cumulus-primitives-proof-size-hostfunction" -version = "0.1.0" -dependencies = [ - "sp-core", - "sp-externalities 0.19.0", - "sp-io", - "sp-runtime-interface 17.0.0", - "sp-state-machine", - "sp-trie", -] - [[package]] name = "cumulus-primitives-timestamp" version = "0.1.0" @@ -3913,7 +4176,6 @@ dependencies = [ "cumulus-relay-chain-interface", "cumulus-relay-chain-rpc-interface", "futures", - "parking_lot 0.12.1", "polkadot-availability-recovery", "polkadot-collator-protocol", "polkadot-core-primitives", @@ -3987,7 +4249,6 @@ version = "0.1.0" dependencies = [ "cumulus-primitives-core", "cumulus-primitives-parachain-inherent", - "cumulus-primitives-proof-size-hostfunction", "cumulus-test-relay-sproof-builder", "cumulus-test-runtime", "cumulus-test-service", @@ -4064,7 +4325,7 @@ name = "cumulus-test-service" version = "0.1.0" dependencies = [ "async-trait", - "clap 4.4.11", + "clap 4.4.6", "criterion 0.5.1", "cumulus-client-cli", "cumulus-client-consensus-common", @@ -4187,7 +4448,7 @@ checksum = "83fdaf97f4804dcebfa5862639bc9ce4121e82140bec2a987ac5140294865b5b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -4227,7 +4488,7 @@ dependencies = [ "proc-macro2", "quote", "scratch", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -4244,7 +4505,7 @@ checksum = "50c49547d73ba8dcfd4ad7325d64c6d5391ff4224d498fc39a6f3f49825a530d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -4543,7 +4804,7 @@ checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -4555,16 +4816,17 @@ checksum = "86e3bdc80eee6e16b2b6b0f87fbc98c04bee3455e35174c0de1a125d0688c632" [[package]] name = "dleq_vrf" version = "0.0.2" -source = "git+https://github.com/w3f/ring-vrf?rev=e9782f9#e9782f938629c90f3adb3fff2358bc8d1386af3e" +source = "git+https://github.com/w3f/ring-vrf?rev=3ddc205#3ddc2051066c4b3f0eadd0ba5700df12500d9754" dependencies = [ "ark-ec", "ark-ff", - "ark-scale 0.0.12", + "ark-scale", "ark-secret-scalar", "ark-serialize", "ark-std", "ark-transcript", "arrayvec 0.7.4", + "rand_core 0.6.4", "zeroize", ] @@ -4604,9 +4866,9 @@ dependencies = [ "proc-macro2", "quote", "regex", - "syn 2.0.40", + "syn 2.0.38", "termcolor", - "toml 0.7.8", + "toml 0.7.6", "walkdir", ] @@ -4693,16 +4955,15 @@ dependencies = [ [[package]] name = "ed25519-dalek" -version = "2.1.0" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f628eaec48bfd21b865dc2950cfa014450c01d2fa2b69a86c2fd5844ec523c0" +checksum = "7277392b266383ef8396db7fdeb1e77b6c52fed775f5df15bb24f35b72156980" dependencies = [ "curve25519-dalek 4.0.0", "ed25519", "rand_core 0.6.4", "serde", "sha2 0.10.7", - "subtle 2.4.1", "zeroize", ] @@ -4860,7 +5121,7 @@ checksum = "5e9a1f9f7d83e59740248a6e14ecf93929ade55027844dfcea78beafccc15745" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -4871,17 +5132,7 @@ checksum = "c2ad8cef1d801a4686bfd8919f0b30eac4c8e48968c437a6405ded4fb5272d2b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", -] - -[[package]] -name = "env_logger" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3" -dependencies = [ - "log", - "regex", + "syn 2.0.38", ] [[package]] @@ -4899,9 +5150,9 @@ dependencies = [ [[package]] name = "env_logger" -version = "0.10.1" +version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95b3f3e67048839cb0d0781f445682a35113da7121f7c949db0e2be96a4fbece" +checksum = "85cdab6a89accf66733ad5a1693a4dcced6aeff64602b634530dd73c1f3ee9f0" dependencies = [ "humantime", "is-terminal", @@ -5026,7 +5277,7 @@ dependencies = [ "fs-err", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -5084,7 +5335,7 @@ checksum = "f5aa1e3ae159e592ad222dc90c5acbad632b527779ba88486abe92782ab268bd" dependencies = [ "expander 0.0.4", "indexmap 1.9.3", - "proc-macro-crate 1.3.1", + "proc-macro-crate", "proc-macro2", "quote", "syn 1.0.109", @@ -5140,7 +5391,7 @@ dependencies = [ [[package]] name = "fflonk" version = "0.1.0" -source = "git+https://github.com/w3f/fflonk#1e854f35e9a65d08b11a86291405cdc95baa0a35" +source = "git+https://github.com/w3f/fflonk#1beb0585e1c8488956fac7f05da061f9b41e8948" dependencies = [ "ark-ec", "ark-ff", @@ -5162,7 +5413,7 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84f2e425d9790201ba4af4630191feac6dcc98765b118d4d18e91d23c2353866" dependencies = [ - "env_logger 0.10.1", + "env_logger 0.10.0", "log", ] @@ -5296,7 +5547,7 @@ dependencies = [ "pallet-examples", "parity-scale-codec", "scale-info", - "simple-mermaid 0.1.0 (git+https://github.com/kianenigma/simple-mermaid.git?rev=e48b187bcfd5cc75111acd9d241f1bd36604344b)", + "simple-mermaid", "sp-api", "sp-arithmetic", "sp-block-builder", @@ -5347,7 +5598,7 @@ dependencies = [ "Inflector", "array-bytes 6.1.0", "chrono", - "clap 4.4.11", + "clap 4.4.6", "comfy-table", "frame-benchmarking", "frame-support", @@ -5408,12 +5659,12 @@ dependencies = [ "frame-election-provider-support", "frame-support", "parity-scale-codec", - "proc-macro-crate 2.0.1", + "proc-macro-crate", "proc-macro2", "quote", "scale-info", "sp-arithmetic", - "syn 2.0.40", + "syn 2.0.38", "trybuild", ] @@ -5439,7 +5690,7 @@ dependencies = [ name = "frame-election-solution-type-fuzzer" version = "2.0.0-alpha.5" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "frame-election-provider-solution-type", "frame-election-provider-support", "frame-support", @@ -5564,9 +5815,8 @@ dependencies = [ "proc-macro-warning", "proc-macro2", "quote", - "regex", "sp-core-hashing", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -5574,10 +5824,10 @@ name = "frame-support-procedural-tools" version = "4.0.0-dev" dependencies = [ "frame-support-procedural-tools-derive", - "proc-macro-crate 2.0.1", + "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -5586,7 +5836,7 @@ version = "3.0.0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -5727,9 +5977,9 @@ dependencies = [ [[package]] name = "fs4" -version = "0.7.0" +version = "0.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29f9df8a11882c4e3335eb2d18a0137c505d9ca927470b0cac9c6f0ae07d28f7" +checksum = "2eeb4ed9e12f43b7fa0baae3f9cdda28352770132ef2e09a23760c29cae8bd47" dependencies = [ "rustix 0.38.21", "windows-sys 0.48.0", @@ -5819,7 +6069,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -5943,16 +6193,6 @@ dependencies = [ "wasi 0.11.0+wasi-snapshot-preview1", ] -[[package]] -name = "getrandom_or_panic" -version = "0.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea1015b5a70616b688dc230cfe50c8af89d972cb132d5a622814d29773b10b9" -dependencies = [ - "rand 0.8.5", - "rand_core 0.6.4", -] - [[package]] name = "ghash" version = "0.4.4" @@ -6009,6 +6249,51 @@ dependencies = [ "regex", ] +[[package]] +name = "glutton-runtime" +version = "1.0.0" +dependencies = [ + "cumulus-pallet-aura-ext", + "cumulus-pallet-parachain-system", + "cumulus-pallet-xcm", + "cumulus-primitives-aura", + "cumulus-primitives-core", + "cumulus-primitives-timestamp", + "frame-benchmarking", + "frame-executive", + "frame-support", + "frame-system", + "frame-system-benchmarking", + "frame-system-rpc-runtime-api", + "frame-try-runtime", + "pallet-aura", + "pallet-glutton", + "pallet-message-queue", + "pallet-sudo", + "pallet-timestamp", + "parachains-common", + "parity-scale-codec", + "scale-info", + "sp-api", + "sp-block-builder", + "sp-consensus-aura", + "sp-core", + "sp-genesis-builder", + "sp-inherents", + "sp-offchain", + "sp-runtime", + "sp-session", + "sp-std 8.0.0", + "sp-storage 13.0.0", + "sp-transaction-pool", + "sp-version", + "staging-parachain-info", + "staging-xcm", + "staging-xcm-builder", + "staging-xcm-executor", + "substrate-wasm-builder", +] + [[package]] name = "glutton-westend-runtime" version = "1.0.0" @@ -6809,7 +7094,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "44e8ab85614a08792b9bff6c8feee23be78c98d0182d4c622c05256ab553892a" dependencies = [ "heck", - "proc-macro-crate 1.3.1", + "proc-macro-crate", "proc-macro2", "quote", "syn 1.0.109", @@ -6933,13 +7218,13 @@ dependencies = [ "pallet-child-bounties", "pallet-collective", "pallet-contracts", + "pallet-contracts-primitives", "pallet-conviction-voting", "pallet-core-fellowship", "pallet-democracy", "pallet-election-provider-multi-phase", "pallet-election-provider-support-benchmarking", "pallet-elections-phragmen", - "pallet-example-tasks", "pallet-fast-unstake", "pallet-glutton", "pallet-grandpa", @@ -7225,7 +7510,7 @@ dependencies = [ "libp2p-identity", "log", "multiaddr", - "multihash 0.17.0", + "multihash", "multistream-select", "once_cell", "parking_lot 0.12.1", @@ -7285,7 +7570,7 @@ dependencies = [ "ed25519-dalek", "log", "multiaddr", - "multihash 0.17.0", + "multihash", "quick-protobuf", "rand 0.8.5", "sha2 0.10.7", @@ -7532,7 +7817,7 @@ dependencies = [ "libp2p-identity", "libp2p-noise", "log", - "multihash 0.17.0", + "multihash", "quick-protobuf", "quick-protobuf-codec", "rand 0.8.5", @@ -7824,7 +8109,7 @@ dependencies = [ "macro_magic_core", "macro_magic_macros", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -7838,7 +8123,7 @@ dependencies = [ "macro_magic_core_macros", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -7849,7 +8134,7 @@ checksum = "9ea73aa640dc01d62a590d48c0c3521ed739d53b27f919b25c3551e233481654" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -7860,7 +8145,7 @@ checksum = "ef9d79ae96aaba821963320eb2b6e34d17df1e5a83d8a1985c29cc5be59577b3" dependencies = [ "macro_magic_core", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -8029,7 +8314,7 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" name = "minimal-node" version = "4.0.0-dev" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "frame", "futures", "futures-timer", @@ -8199,7 +8484,7 @@ dependencies = [ "data-encoding", "log", "multibase", - "multihash 0.17.0", + "multihash", "percent-encoding", "serde", "static_assertions", @@ -8229,87 +8514,19 @@ dependencies = [ "blake3", "core2", "digest 0.10.7", - "multihash-derive 0.8.0", + "multihash-derive", "sha2 0.10.7", "sha3", "unsigned-varint", ] -[[package]] -name = "multihash" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfd8a792c1694c6da4f68db0a9d707c72bd260994da179e6030a5dcee00bb815" -dependencies = [ - "core2", - "digest 0.10.7", - "multihash-derive 0.8.0", - "sha2 0.10.7", - "unsigned-varint", -] - -[[package]] -name = "multihash" -version = "0.19.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "076d548d76a0e2a0d4ab471d0b1c36c577786dfc4471242035d97a12a735c492" -dependencies = [ - "core2", - "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.7", - "sha3", - "strobe-rs", -] - [[package]] name = "multihash-derive" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc076939022111618a5026d3be019fd8b366e76314538ff9a1b59ffbcbf98bcd" dependencies = [ - "proc-macro-crate 1.3.1", - "proc-macro-error", - "proc-macro2", - "quote", - "syn 1.0.109", - "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-crate", "proc-macro-error", "proc-macro2", "quote", @@ -8364,6 +8581,15 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "names" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7d66043b25d4a6cccb23619d10c19c25304b355a7dccd4a8e11423dd2382146" +dependencies = [ + "rand 0.8.5", +] + [[package]] name = "names" version = "0.14.0" @@ -8494,7 +8720,7 @@ name = "node-bench" version = "0.9.0-dev" dependencies = [ "array-bytes 6.1.0", - "clap 4.4.11", + "clap 4.4.6", "derive_more", "fs_extra", "futures", @@ -8569,7 +8795,7 @@ dependencies = [ name = "node-runtime-generate-bags" version = "3.0.0" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "generate-bags", "kitchensink-runtime", ] @@ -8578,7 +8804,7 @@ dependencies = [ name = "node-template" version = "4.0.0-dev" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "frame-benchmarking", "frame-benchmarking-cli", "frame-system", @@ -8622,14 +8848,14 @@ dependencies = [ name = "node-template-release" version = "3.0.0" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "flate2", "fs_extra", "glob", "itertools 0.10.5", "tar", "tempfile", - "toml_edit 0.19.15", + "toml_edit", ] [[package]] @@ -8703,7 +8929,7 @@ dependencies = [ "sp-keyring", "sp-runtime", "sp-timestamp", - "staging-node-cli", + "staging-node-executor", "substrate-test-client", "tempfile", ] @@ -8815,9 +9041,9 @@ dependencies = [ [[package]] name = "num-traits" -version = "0.2.17" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c" +checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" dependencies = [ "autocfg", "libm", @@ -8944,7 +9170,7 @@ dependencies = [ "itertools 0.11.0", "layout-rs", "petgraph", - "proc-macro-crate 1.3.1", + "proc-macro-crate", "proc-macro2", "quote", "syn 1.0.109", @@ -9544,8 +9770,8 @@ dependencies = [ "pallet-assets", "pallet-balances", "pallet-contracts-fixtures", + "pallet-contracts-primitives", "pallet-contracts-proc-macro", - "pallet-contracts-uapi", "pallet-insecure-randomness-collective-flip", "pallet-message-queue", "pallet-proxy", @@ -9576,21 +9802,11 @@ dependencies = [ name = "pallet-contracts-fixtures" version = "1.0.0" dependencies = [ - "anyhow", - "cfg-if", "frame-system", - "parity-wasm", "sp-runtime", - "tempfile", - "toml 0.8.2", - "twox-hash", "wat", ] -[[package]] -name = "pallet-contracts-fixtures-common" -version = "1.0.0" - [[package]] name = "pallet-contracts-mock-network" version = "1.0.0" @@ -9602,8 +9818,8 @@ dependencies = [ "pallet-balances", "pallet-contracts", "pallet-contracts-fixtures", + "pallet-contracts-primitives", "pallet-contracts-proc-macro", - "pallet-contracts-uapi", "pallet-insecure-randomness-collective-flip", "pallet-message-queue", "pallet-proxy", @@ -9630,22 +9846,24 @@ dependencies = [ ] [[package]] -name = "pallet-contracts-proc-macro" -version = "4.0.0-dev" +name = "pallet-contracts-primitives" +version = "24.0.0" dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.40", + "bitflags 1.3.2", + "parity-scale-codec", + "scale-info", + "sp-runtime", + "sp-std 8.0.0", + "sp-weights", ] [[package]] -name = "pallet-contracts-uapi" +name = "pallet-contracts-proc-macro" version = "4.0.0-dev" dependencies = [ - "bitflags 1.3.2", - "parity-scale-codec", - "paste", - "scale-info", + "proc-macro2", + "quote", + "syn 2.0.38", ] [[package]] @@ -9894,22 +10112,6 @@ dependencies = [ "sp-std 8.0.0", ] -[[package]] -name = "pallet-example-tasks" -version = "1.0.0-dev" -dependencies = [ - "frame-benchmarking", - "frame-support", - "frame-system", - "log", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std 8.0.0", -] - [[package]] name = "pallet-examples" version = "4.0.0-dev" @@ -9921,7 +10123,6 @@ dependencies = [ "pallet-example-kitchensink", "pallet-example-offchain-worker", "pallet-example-split", - "pallet-example-tasks", ] [[package]] @@ -10103,7 +10304,6 @@ dependencies = [ name = "pallet-message-queue" version = "7.0.0-dev" dependencies = [ - "environmental", "frame-benchmarking", "frame-support", "frame-system", @@ -10628,24 +10828,6 @@ dependencies = [ "sp-std 8.0.0", ] -[[package]] -name = "pallet-sassafras" -version = "0.3.5-dev" -dependencies = [ - "array-bytes 6.1.0", - "frame-benchmarking", - "frame-support", - "frame-system", - "log", - "parity-scale-codec", - "scale-info", - "sp-consensus-sassafras", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std 8.0.0", -] - [[package]] name = "pallet-scheduler" version = "4.0.0-dev" @@ -10791,11 +10973,11 @@ dependencies = [ name = "pallet-staking-reward-curve" version = "4.0.0-dev" dependencies = [ - "proc-macro-crate 2.0.1", + "proc-macro-crate", "proc-macro2", "quote", "sp-runtime", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -11153,31 +11335,6 @@ dependencies = [ "staging-xcm-executor", ] -[[package]] -name = "pallet-xcm-bridge-hub" -version = "0.1.0" -dependencies = [ - "bp-header-chain", - "bp-messages", - "bp-runtime", - "bp-xcm-bridge-hub", - "bridge-runtime-common", - "frame-support", - "frame-system", - "log", - "pallet-balances", - "pallet-bridge-messages", - "parity-scale-codec", - "scale-info", - "sp-core", - "sp-io", - "sp-runtime", - "sp-std 8.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", -] - [[package]] name = "pallet-xcm-bridge-hub-router" version = "0.1.0" @@ -11201,7 +11358,7 @@ dependencies = [ name = "parachain-template-node" version = "0.1.0" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "color-print", "cumulus-client-cli", "cumulus-client-collator", @@ -11382,9 +11539,9 @@ dependencies = [ [[package]] name = "parity-db" -version = "0.4.12" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59e9ab494af9e6e813c72170f0d3c1de1500990d62c97cc05cc7576f91aa402f" +checksum = "78f19d20a0d2cc52327a88d131fa1c4ea81ea4a04714aedcfeca2dd410049cf8" dependencies = [ "blake2 0.10.6", "crc32fast", @@ -11402,9 +11559,9 @@ dependencies = [ [[package]] name = "parity-scale-codec" -version = "3.6.5" +version = "3.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dec8a8073036902368c2cdc0387e85ff9a37054d7e7c98e592145e0c92cd4fb" +checksum = "dd8e946cc0cc711189c0b0249fb8b599cbeeab9784d83c415719368bb8d4ac64" dependencies = [ "arrayvec 0.7.4", "bitvec", @@ -11417,11 +11574,11 @@ dependencies = [ [[package]] name = "parity-scale-codec-derive" -version = "3.6.5" +version = "3.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "312270ee71e1cd70289dacf597cab7b207aa107d2f28191c2ae45b2ece18a260" +checksum = "2a296c3079b5fefbc499e1de58dc26c09b1b9a5952d26694ee89f04a43ebbb3e" dependencies = [ - "proc-macro-crate 1.3.1", + "proc-macro-crate", "proc-macro2", "quote", "syn 1.0.109", @@ -11589,7 +11746,6 @@ dependencies = [ "serde_json", "sp-core", "sp-runtime", - "westend-emulated-chain", ] [[package]] @@ -11689,7 +11845,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -11730,7 +11886,7 @@ checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -11813,7 +11969,7 @@ dependencies = [ [[package]] name = "polkadot" -version = "1.5.0" +version = "1.1.0" dependencies = [ "assert_cmd", "color-eyre", @@ -11944,7 +12100,6 @@ dependencies = [ "sp-core", "sp-keyring", "thiserror", - "tokio", "tracing-gum", ] @@ -11952,8 +12107,7 @@ dependencies = [ name = "polkadot-cli" version = "1.1.0" dependencies = [ - "cfg-if", - "clap 4.4.11", + "clap 4.4.6", "frame-benchmarking-cli", "futures", "log", @@ -12079,7 +12233,6 @@ dependencies = [ "polkadot-node-subsystem-test-helpers", "polkadot-node-subsystem-util", "polkadot-primitives", - "quickcheck", "rand 0.8.5", "rand_chacha 0.3.1", "sc-network", @@ -12453,7 +12606,6 @@ dependencies = [ "tempfile", "test-parachain-adder", "test-parachain-halt", - "thiserror", "tokio", "tracing-gum", ] @@ -12674,8 +12826,6 @@ dependencies = [ "async-trait", "futures", "parking_lot 0.12.1", - "polkadot-erasure-coding", - "polkadot-node-primitives", "polkadot-node-subsystem", "polkadot-node-subsystem-util", "polkadot-primitives", @@ -12786,15 +12936,20 @@ dependencies = [ [[package]] name = "polkadot-parachain-bin" -version = "1.5.0" +version = "1.1.0" dependencies = [ "assert_cmd", + "asset-hub-kusama-runtime", + "asset-hub-polkadot-runtime", "asset-hub-rococo-runtime", "asset-hub-westend-runtime", "async-trait", + "bridge-hub-kusama-runtime", + "bridge-hub-polkadot-runtime", "bridge-hub-rococo-runtime", "bridge-hub-westend-runtime", - "clap 4.4.11", + "clap 4.4.6", + "collectives-polkadot-runtime", "collectives-westend-runtime", "color-print", "contracts-rococo-runtime", @@ -12815,6 +12970,7 @@ dependencies = [ "frame-system-rpc-runtime-api", "frame-try-runtime", "futures", + "glutton-runtime", "glutton-westend-runtime", "hex-literal", "jsonrpsee", @@ -13073,54 +13229,15 @@ dependencies = [ "sp-io", "sp-keyring", "sp-keystore", - "sp-runtime", - "sp-session", - "sp-staking", - "sp-std 8.0.0", - "sp-tracing 10.0.0", - "staging-xcm", - "staging-xcm-executor", - "static_assertions", - "thousands", -] - -[[package]] -name = "polkadot-sdk-docs" -version = "0.0.1" -dependencies = [ - "cumulus-pallet-aura-ext", - "cumulus-pallet-parachain-system", - "docify", - "frame", - "kitchensink-runtime", - "pallet-aura", - "pallet-default-config-example", - "pallet-examples", - "pallet-timestamp", - "parity-scale-codec", - "sc-cli", - "sc-client-db", - "sc-consensus-aura", - "sc-consensus-babe", - "sc-consensus-beefy", - "sc-consensus-grandpa", - "sc-consensus-manual-seal", - "sc-consensus-pow", - "sc-network", - "sc-rpc", - "sc-rpc-api", - "scale-info", - "simple-mermaid 0.1.0 (git+https://github.com/kianenigma/simple-mermaid.git?branch=main)", - "sp-api", - "sp-core", - "sp-io", - "sp-keyring", - "sp-runtime", - "staging-chain-spec-builder", - "staging-node-cli", - "staging-parachain-info", - "subkey", - "substrate-wasm-builder", + "sp-runtime", + "sp-session", + "sp-staking", + "sp-std 8.0.0", + "sp-tracing 10.0.0", + "staging-xcm", + "staging-xcm-executor", + "static_assertions", + "thousands", ] [[package]] @@ -13149,7 +13266,6 @@ dependencies = [ "pallet-transaction-payment-rpc-runtime-api", "parity-db", "parity-scale-codec", - "parking_lot 0.12.1", "polkadot-approval-distribution", "polkadot-availability-bitfield-distribution", "polkadot-availability-distribution", @@ -13265,6 +13381,7 @@ dependencies = [ "polkadot-node-primitives", "polkadot-node-subsystem", "polkadot-node-subsystem-test-helpers", + "polkadot-node-subsystem-types", "polkadot-node-subsystem-util", "polkadot-primitives", "polkadot-primitives-test-helpers", @@ -13291,52 +13408,6 @@ dependencies = [ "sp-core", ] -[[package]] -name = "polkadot-subsystem-bench" -version = "1.0.0" -dependencies = [ - "assert_matches", - "async-trait", - "clap 4.4.11", - "clap-num", - "color-eyre", - "colored", - "env_logger 0.9.3", - "futures", - "futures-timer", - "itertools 0.11.0", - "log", - "orchestra", - "parity-scale-codec", - "paste", - "polkadot-availability-recovery", - "polkadot-erasure-coding", - "polkadot-node-metrics", - "polkadot-node-network-protocol", - "polkadot-node-primitives", - "polkadot-node-subsystem", - "polkadot-node-subsystem-test-helpers", - "polkadot-node-subsystem-types", - "polkadot-node-subsystem-util", - "polkadot-overseer", - "polkadot-primitives", - "polkadot-primitives-test-helpers", - "prometheus", - "rand 0.8.5", - "sc-keystore", - "sc-network", - "sc-service", - "serde", - "serde_yaml", - "sp-application-crypto", - "sp-core", - "sp-keyring", - "sp-keystore", - "substrate-prometheus-endpoint", - "tokio", - "tracing-gum", -] - [[package]] name = "polkadot-test-client" version = "1.0.0" @@ -13372,7 +13443,7 @@ version = "1.0.0" dependencies = [ "assert_matches", "async-trait", - "clap 4.4.11", + "clap 4.4.6", "color-eyre", "futures", "futures-timer", @@ -13519,7 +13590,7 @@ dependencies = [ name = "polkadot-voter-bags" version = "1.0.0" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "generate-bags", "sp-io", "westend-runtime", @@ -13697,7 +13768,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c64d9ba0963cdcea2e1b2230fbae2bab30eb25a174be395c41e764bfb65dd62" dependencies = [ "proc-macro2", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -13738,17 +13809,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" dependencies = [ "once_cell", - "toml_edit 0.19.15", -] - -[[package]] -name = "proc-macro-crate" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97dc5fea232fc28d2f597b37c4876b348a40e33f3b02cc975c8d006d78d94b1a" -dependencies = [ - "toml_datetime", - "toml_edit 0.20.2", + "toml_edit", ] [[package]] @@ -13789,7 +13850,7 @@ checksum = "9b698b0b09d40e9b7c1a47b132d66a8b54bcd20583d9b6d06e4535e383b4405c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -13861,7 +13922,7 @@ checksum = "440f724eba9f6996b75d63681b0a92b06947f1457076d503a4d2e2c8f56442b8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -13949,7 +14010,7 @@ dependencies = [ "libc", "libflate", "log", - "names", + "names 0.14.0", "prost", "reqwest", "thiserror", @@ -14003,8 +14064,6 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "588f6378e4dd99458b60ec275b4477add41ce4fa9f64dcba6f15adccb19b50d6" dependencies = [ - "env_logger 0.8.4", - "log", "rand 0.8.5", ] @@ -14213,15 +14272,6 @@ dependencies = [ "bitflags 1.3.2", ] -[[package]] -name = "redox_syscall" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" -dependencies = [ - "bitflags 1.3.2", -] - [[package]] name = "redox_users" version = "0.4.3" @@ -14263,7 +14313,7 @@ checksum = "7f7473c2cfcf90008193dd0e3e16599455cb601a9fce322b5bb55de799664925" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -14332,7 +14382,7 @@ checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" name = "remote-ext-tests-bags-list" version = "1.0.0" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "frame-system", "log", "pallet-bags-list-remote-tests", @@ -14416,7 +14466,7 @@ dependencies = [ [[package]] name = "ring" version = "0.1.0" -source = "git+https://github.com/w3f/ring-proof#b273d33f9981e2bb3375ab45faeb537f7ee35224" +source = "git+https://github.com/burdges/ring-proof?branch=patch-1#05a756076cb20f981a52afea3a620168de49f95f" dependencies = [ "ark-ec", "ark-ff", @@ -14444,15 +14494,6 @@ dependencies = [ "winapi", ] -[[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" @@ -14664,7 +14705,6 @@ dependencies = [ "sp-runtime", "sp-weights", "staging-xcm", - "staging-xcm-builder", ] [[package]] @@ -15009,8 +15049,7 @@ dependencies = [ "ip_network", "libp2p", "log", - "multihash 0.18.1", - "multihash-codetable", + "multihash", "parity-scale-codec", "prost", "prost-build", @@ -15067,7 +15106,6 @@ dependencies = [ "sp-inherents", "sp-runtime", "sp-state-machine", - "sp-trie", "substrate-test-runtime-client", ] @@ -15103,10 +15141,10 @@ dependencies = [ name = "sc-chain-spec-derive" version = "4.0.0-dev" dependencies = [ - "proc-macro-crate 2.0.1", + "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -15116,14 +15154,14 @@ dependencies = [ "array-bytes 6.1.0", "bip39", "chrono", - "clap 4.4.11", + "clap 4.4.6", "fdlimit", "futures", "futures-timer", "itertools 0.10.5", "libp2p-identity", "log", - "names", + "names 0.13.0", "parity-scale-codec", "rand 0.8.5", "regex", @@ -15688,7 +15726,6 @@ dependencies = [ "array-bytes 4.2.0", "arrayvec 0.7.4", "blake2 0.10.6", - "bytes", "futures", "futures-timer", "libp2p-identity", @@ -15754,7 +15791,6 @@ dependencies = [ "tempfile", "thiserror", "tokio", - "tokio-stream", "tokio-test", "tokio-util", "unsigned-varint", @@ -15810,12 +15846,10 @@ name = "sc-network-gossip" version = "0.10.0-dev" dependencies = [ "ahash 0.8.3", - "async-trait", "futures", "futures-timer", "libp2p", "log", - "parity-scale-codec", "quickcheck", "sc-network", "sc-network-common", @@ -16260,7 +16294,7 @@ dependencies = [ name = "sc-storage-monitor" version = "0.1.0" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "fs4", "log", "sc-client-db", @@ -16359,10 +16393,10 @@ dependencies = [ name = "sc-tracing-proc-macro" version = "4.0.0-dev" dependencies = [ - "proc-macro-crate 2.0.1", + "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -16449,7 +16483,7 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abf2c68b89cafb3b8d918dd07b42be0da66ff202cf1155c5739a4e0c1ea0dc19" dependencies = [ - "proc-macro-crate 1.3.1", + "proc-macro-crate", "proc-macro2", "quote", "syn 1.0.109", @@ -16464,30 +16498,6 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "schemars" -version = "0.8.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "763f8cd0d4c71ed8389c90cb8100cba87e763bd01a8e614d4f0af97bcd50a161" -dependencies = [ - "dyn-clone", - "schemars_derive", - "serde", - "serde_json", -] - -[[package]] -name = "schemars_derive" -version = "0.8.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0f696e21e10fa546b7ffb1c9672c6de8fbc7a81acf59524386d8639bf12737" -dependencies = [ - "proc-macro2", - "quote", - "serde_derive_internals", - "syn 1.0.109", -] - [[package]] name = "schnellru" version = "0.2.1" @@ -16740,33 +16750,22 @@ checksum = "f97841a747eef040fcd2e7b3b9a220a7205926e60488e673d9e4926d27772ce5" [[package]] name = "serde" -version = "1.0.193" +version = "1.0.188" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25dd9975e68d0cb5aa1120c288333fc98731bd1dd12f561e468ea4728c042b89" +checksum = "cf9e0fcba69a370eed61bcf2b728575f726b50b55cba78064753d708ddc7549e" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.193" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43576ca501357b9b071ac53cdc7da8ef0cbd9493d8df094cd821777ea6e894d3" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.40", -] - -[[package]] -name = "serde_derive_internals" -version = "0.26.0" +version = "1.0.188" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85bf8229e7920a9f636479437026331ce11aa132b4dde37d121944a44d6e5f3c" +checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2" dependencies = [ "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.38", ] [[package]] @@ -16791,9 +16790,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "0.6.4" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12022b835073e5b11e90a14f86838ceb1c8fb0325b72416845c487ac0fa95e80" +checksum = "96426c9936fd7a0124915f9185ea1d20aa9445cc9821142f0a73bc9207a2e186" dependencies = [ "serde", ] @@ -16810,19 +16809,6 @@ dependencies = [ "serde", ] -[[package]] -name = "serde_yaml" -version = "0.9.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cc7a1570e38322cfe4154732e5110f887ea57e22b76f4bfd32b5bdd3368666c" -dependencies = [ - "indexmap 2.0.0", - "itoa", - "ryu", - "serde", - "unsafe-libyaml", -] - [[package]] name = "serial_test" version = "2.0.0" @@ -16845,7 +16831,7 @@ checksum = "91d129178576168c589c9ec973feedf7d3126c01ac2bf08795109aa35b69fb8f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -17033,11 +17019,6 @@ dependencies = [ "wide", ] -[[package]] -name = "simple-mermaid" -version = "0.1.0" -source = "git+https://github.com/kianenigma/simple-mermaid.git?branch=main#e48b187bcfd5cc75111acd9d241f1bd36604344b" - [[package]] name = "simple-mermaid" version = "0.1.0" @@ -17286,10 +17267,10 @@ dependencies = [ "assert_matches", "blake2 0.10.6", "expander 2.0.0", - "proc-macro-crate 2.0.1", + "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -17624,7 +17605,7 @@ version = "9.0.0" dependencies = [ "quote", "sp-core-hashing", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -17642,7 +17623,7 @@ dependencies = [ "ark-ed-on-bls12-377-ext", "ark-ed-on-bls12-381-bandersnatch", "ark-ed-on-bls12-381-bandersnatch-ext", - "ark-scale 0.0.12", + "ark-scale", "sp-runtime-interface 17.0.0", "sp-std 8.0.0", ] @@ -17663,7 +17644,7 @@ dependencies = [ "ark-ed-on-bls12-377-ext", "ark-ed-on-bls12-381-bandersnatch", "ark-ed-on-bls12-381-bandersnatch-ext", - "ark-scale 0.0.11", + "ark-scale", "sp-runtime-interface 17.0.0 (git+https://github.com/paritytech/polkadot-sdk)", "sp-std 8.0.0 (git+https://github.com/paritytech/polkadot-sdk)", ] @@ -17682,7 +17663,7 @@ version = "8.0.0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -17692,7 +17673,7 @@ source = "git+https://github.com/paritytech/polkadot-sdk#82912acb33a9030c0ef3bf5 dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -17767,6 +17748,7 @@ dependencies = [ name = "sp-keyring" version = "24.0.0" dependencies = [ + "lazy_static", "sp-core", "sp-runtime", "strum", @@ -17778,7 +17760,7 @@ version = "0.27.0" dependencies = [ "parity-scale-codec", "parking_lot 0.12.1", - "rand 0.8.5", + "rand 0.7.3", "rand_chacha 0.2.2", "sp-core", "sp-externalities 0.19.0", @@ -17851,7 +17833,7 @@ dependencies = [ name = "sp-npos-elections-fuzzer" version = "2.0.0-alpha.5" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "honggfuzz", "rand 0.8.5", "sp-npos-elections", @@ -17890,7 +17872,6 @@ dependencies = [ name = "sp-runtime" version = "24.0.0" dependencies = [ - "docify", "either", "hash256-std-hasher", "impl-trait-for-tuples", @@ -17901,7 +17882,6 @@ dependencies = [ "scale-info", "serde", "serde_json", - "simple-mermaid 0.1.0 (git+https://github.com/kianenigma/simple-mermaid.git?branch=main)", "sp-api", "sp-application-crypto", "sp-arithmetic", @@ -17962,11 +17942,10 @@ name = "sp-runtime-interface-proc-macro" version = "11.0.0" dependencies = [ "Inflector", - "expander 2.0.0", - "proc-macro-crate 2.0.1", + "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -17975,10 +17954,10 @@ version = "11.0.0" source = "git+https://github.com/paritytech/polkadot-sdk#82912acb33a9030c0ef3bf590a34fca09b72dc5f" dependencies = [ "Inflector", - "proc-macro-crate 1.3.1", + "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -18205,6 +18184,7 @@ dependencies = [ "array-bytes 6.1.0", "criterion 0.4.0", "hash-db", + "hashbrown 0.13.2", "lazy_static", "memory-db", "nohash-hasher", @@ -18214,7 +18194,6 @@ dependencies = [ "scale-info", "schnellru", "sp-core", - "sp-externalities 0.19.0", "sp-runtime", "sp-std 8.0.0", "thiserror", @@ -18249,7 +18228,7 @@ dependencies = [ "proc-macro2", "quote", "sp-version", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -18281,13 +18260,12 @@ dependencies = [ name = "sp-weights" version = "20.0.0" dependencies = [ - "bounded-collections", "parity-scale-codec", "scale-info", - "schemars", "serde", "smallvec", "sp-arithmetic", + "sp-core", "sp-debug-derive 8.0.0", "sp-std 8.0.0", ] @@ -18360,7 +18338,7 @@ checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" name = "staging-chain-spec-builder" version = "2.0.0" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "log", "sc-chain-spec", "serde_json", @@ -18373,12 +18351,10 @@ version = "3.0.0-dev" dependencies = [ "array-bytes 6.1.0", "assert_cmd", - "clap 4.4.11", + "clap 4.4.6", "clap_complete", "criterion 0.4.0", - "frame-benchmarking", "frame-benchmarking-cli", - "frame-support", "frame-system", "frame-system-rpc-runtime-api", "futures", @@ -18388,20 +18364,13 @@ dependencies = [ "nix 0.26.2", "node-primitives", "node-rpc", - "node-testing", "pallet-asset-conversion-tx-payment", "pallet-asset-tx-payment", "pallet-assets", "pallet-balances", - "pallet-contracts", - "pallet-glutton", "pallet-im-online", - "pallet-root-testing", "pallet-skip-feeless-payment", - "pallet-sudo", "pallet-timestamp", - "pallet-transaction-payment", - "pallet-treasury", "parity-scale-codec", "platforms", "rand 0.8.5", @@ -18436,31 +18405,27 @@ dependencies = [ "sc-telemetry", "sc-transaction-pool", "sc-transaction-pool-api", - "scale-info", "serde", "serde_json", "soketto", "sp-api", - "sp-application-crypto", "sp-authority-discovery", "sp-blockchain", "sp-consensus", "sp-consensus-babe", "sp-consensus-grandpa", "sp-core", - "sp-externalities 0.19.0", "sp-inherents", "sp-io", "sp-keyring", "sp-keystore", "sp-mixnet", "sp-runtime", - "sp-state-machine", "sp-statement-store", "sp-timestamp", "sp-tracing 10.0.0", "sp-transaction-storage-proof", - "sp-trie", + "staging-node-executor", "staging-node-inspect", "substrate-build-script-utils", "substrate-cli-test-utils", @@ -18471,6 +18436,44 @@ dependencies = [ "tokio-util", "try-runtime-cli", "wait-timeout", +] + +[[package]] +name = "staging-node-executor" +version = "3.0.0-dev" +dependencies = [ + "criterion 0.4.0", + "frame-benchmarking", + "frame-support", + "frame-system", + "futures", + "kitchensink-runtime", + "node-primitives", + "node-testing", + "pallet-balances", + "pallet-contracts", + "pallet-glutton", + "pallet-im-online", + "pallet-root-testing", + "pallet-sudo", + "pallet-timestamp", + "pallet-transaction-payment", + "pallet-treasury", + "parity-scale-codec", + "sc-executor", + "scale-info", + "serde_json", + "sp-application-crypto", + "sp-consensus-babe", + "sp-core", + "sp-externalities 0.19.0", + "sp-keyring", + "sp-keystore", + "sp-runtime", + "sp-state-machine", + "sp-statement-store", + "sp-tracing 10.0.0", + "sp-trie", "wat", ] @@ -18478,16 +18481,14 @@ dependencies = [ name = "staging-node-inspect" version = "0.9.0-dev" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "parity-scale-codec", "sc-cli", "sc-client-api", "sc-service", "sp-blockchain", "sp-core", - "sp-io", "sp-runtime", - "sp-statement-store", "thiserror", ] @@ -18521,7 +18522,6 @@ dependencies = [ "log", "parity-scale-codec", "scale-info", - "schemars", "serde", "sp-io", "sp-weights", @@ -18637,19 +18637,6 @@ dependencies = [ "syn 1.0.109", ] -[[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.4.1", - "zeroize", -] - [[package]] name = "strsim" version = "0.10.0" @@ -18701,8 +18688,28 @@ dependencies = [ name = "subkey" version = "3.0.0" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", + "sc-cli", +] + +[[package]] +name = "substrate" +version = "1.0.0" +dependencies = [ + "frame-support", + "sc-chain-spec", "sc-cli", + "sc-consensus-aura", + "sc-consensus-babe", + "sc-consensus-beefy", + "sc-consensus-grandpa", + "sc-consensus-manual-seal", + "sc-consensus-pow", + "sc-service", + "simple-mermaid", + "sp-runtime", + "staging-chain-spec-builder", + "subkey", ] [[package]] @@ -18743,7 +18750,7 @@ dependencies = [ name = "substrate-frame-cli" version = "4.0.0-dev" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "frame-support", "frame-system", "sc-cli", @@ -18962,7 +18969,7 @@ dependencies = [ "sp-maybe-compressed-blob", "strum", "tempfile", - "toml 0.8.2", + "toml 0.7.6", "walkdir", "wasm-opt", ] @@ -19098,9 +19105,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.40" +version = "2.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13fa70a4ee923979ffb522cacce59d34421ebdea5625e1073c4326ef9d2dd42e" +checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b" dependencies = [ "proc-macro2", "quote", @@ -19165,13 +19172,13 @@ checksum = "9d0e916b1148c8e263850e1ebcbd046f333e0683c724876bb0da63ea4373dc8a" [[package]] name = "tempfile" -version = "3.8.1" +version = "3.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ef1adac450ad7f4b3c28589471ade84f25f731a7a0fe30d71dfa9f60fd808e5" +checksum = "cb94d2f3cc536af71caac6b6fcebf65860b347e7ce0cc9ebe8f70d3e521054ef" dependencies = [ "cfg-if", "fastrand 2.0.0", - "redox_syscall 0.4.1", + "redox_syscall 0.3.5", "rustix 0.38.21", "windows-sys 0.48.0", ] @@ -19218,7 +19225,7 @@ dependencies = [ name = "test-parachain-adder-collator" version = "1.0.0" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "futures", "futures-timer", "log", @@ -19266,7 +19273,7 @@ dependencies = [ name = "test-parachain-undying-collator" version = "1.0.0" dependencies = [ - "clap 4.4.11", + "clap 4.4.6", "futures", "futures-timer", "log", @@ -19312,6 +19319,19 @@ dependencies = [ "sp-weights", ] +[[package]] +name = "testnets-common" +version = "1.0.0" +dependencies = [ + "frame-support", + "polkadot-core-primitives", + "rococo-runtime-constants", + "smallvec", + "sp-runtime", + "substrate-wasm-builder", + "westend-runtime-constants", +] + [[package]] name = "textwrap" version = "0.16.0" @@ -19355,7 +19375,7 @@ checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -19502,9 +19522,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.33.0" +version = "1.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f38200e3ef7995e5ef13baec2f432a6da0aa9ac495b2c0e8f3b7eec2c92d653" +checksum = "17ed6077ed6cd6c74735e21f37eb16dc3935f96878b1fe961074089cc80893f9" dependencies = [ "backtrace", "bytes", @@ -19527,7 +19547,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -19614,26 +19634,14 @@ dependencies = [ [[package]] name = "toml" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd79e69d3b627db300ff956027cc6c3798cef26d22526befdfcd12feeb6d2257" -dependencies = [ - "serde", - "serde_spanned", - "toml_datetime", - "toml_edit 0.19.15", -] - -[[package]] -name = "toml" -version = "0.8.2" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" +checksum = "c17e963a819c331dcacd7ab957d80bc2b9a9c1e71c804826d2f283dd65306542" dependencies = [ "serde", "serde_spanned", "toml_datetime", - "toml_edit 0.20.2", + "toml_edit", ] [[package]] @@ -19647,22 +19655,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.19.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" -dependencies = [ - "indexmap 2.0.0", - "serde", - "serde_spanned", - "toml_datetime", - "winnow", -] - -[[package]] -name = "toml_edit" -version = "0.20.2" +version = "0.19.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" +checksum = "f8123f27e969974a3dfba720fdb560be359f57b44302d280ba72e76a74480e8a" dependencies = [ "indexmap 2.0.0", "serde", @@ -19733,14 +19728,14 @@ checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] name = "tracing-core" -version = "0.1.32" +version = "0.1.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" +checksum = "0955b8137a1df6f1a2e9a37d8a6656291ff0297c1a97c24e0d8425fe2312f79a" dependencies = [ "once_cell", "valuable", @@ -19772,10 +19767,10 @@ version = "1.0.0" dependencies = [ "assert_matches", "expander 2.0.0", - "proc-macro-crate 2.0.1", + "proc-macro-crate", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] @@ -19928,7 +19923,7 @@ version = "0.10.0-dev" dependencies = [ "assert_cmd", "async-trait", - "clap 4.4.11", + "clap 4.4.6", "frame-remote-externalities", "frame-try-runtime", "hex", @@ -20037,7 +20032,7 @@ checksum = "97fee6b57c6a41524a810daee9286c02d7752c4253064d0b05472833a438f675" dependencies = [ "cfg-if", "digest 0.10.7", - "rand 0.7.3", + "rand 0.8.5", "static_assertions", ] @@ -20118,12 +20113,6 @@ dependencies = [ "subtle 2.4.1", ] -[[package]] -name = "unsafe-libyaml" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f28467d3e1d3c6586d8f25fa243f544f5800fec42d97032474e17222c2b75cfa" - [[package]] name = "unsigned-varint" version = "0.7.1" @@ -20342,7 +20331,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", "wasm-bindgen-shared", ] @@ -20376,7 +20365,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -21140,7 +21129,6 @@ dependencies = [ "sp-runtime", "sp-weights", "staging-xcm", - "staging-xcm-builder", ] [[package]] @@ -21149,7 +21137,6 @@ version = "0.0.0" dependencies = [ "asset-hub-westend-emulated-chain", "bridge-hub-westend-emulated-chain", - "collectives-westend-emulated-chain", "emulated-integration-tests-common", "penpal-emulated-chain", "westend-emulated-chain", @@ -21556,7 +21543,7 @@ dependencies = [ "proc-macro2", "quote", "staging-xcm", - "syn 2.0.40", + "syn 2.0.38", "trybuild", ] @@ -21676,7 +21663,7 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2", "quote", - "syn 2.0.40", + "syn 2.0.38", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index e3b6e3aadfe..6af3ea4c3cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,6 @@ members = [ "bridges/modules/messages", "bridges/modules/parachains", "bridges/modules/relayers", - "bridges/modules/xcm-bridge-hub", "bridges/modules/xcm-bridge-hub-router", "bridges/primitives/chain-asset-hub-rococo", "bridges/primitives/chain-asset-hub-westend", @@ -23,8 +22,8 @@ members = [ "bridges/primitives/chain-bridge-hub-rococo", "bridges/primitives/chain-bridge-hub-westend", "bridges/primitives/chain-kusama", - "bridges/primitives/chain-polkadot", "bridges/primitives/chain-polkadot-bulletin", + "bridges/primitives/chain-polkadot", "bridges/primitives/chain-rococo", "bridges/primitives/chain-westend", "bridges/primitives/header-chain", @@ -34,7 +33,6 @@ members = [ "bridges/primitives/relayers", "bridges/primitives/runtime", "bridges/primitives/test-utils", - "bridges/primitives/xcm-bridge-hub", "bridges/primitives/xcm-bridge-hub-router", "cumulus/client/cli", "cumulus/client/collator", @@ -66,13 +64,11 @@ members = [ "cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend", "cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo", "cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend", - "cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend", "cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal", "cumulus/parachains/integration-tests/emulated/chains/relays/rococo", "cumulus/parachains/integration-tests/emulated/chains/relays/westend", "cumulus/parachains/integration-tests/emulated/common", "cumulus/parachains/integration-tests/emulated/networks/rococo-system", - "cumulus/parachains/integration-tests/emulated/networks/rococo-westend-system", "cumulus/parachains/integration-tests/emulated/networks/westend-system", "cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo", "cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend", @@ -81,26 +77,32 @@ members = [ "cumulus/parachains/pallets/collective-content", "cumulus/parachains/pallets/parachain-info", "cumulus/parachains/pallets/ping", + "cumulus/parachains/runtimes/assets/asset-hub-kusama", + "cumulus/parachains/runtimes/assets/asset-hub-polkadot", "cumulus/parachains/runtimes/assets/asset-hub-rococo", "cumulus/parachains/runtimes/assets/asset-hub-westend", "cumulus/parachains/runtimes/assets/common", "cumulus/parachains/runtimes/assets/test-utils", + "cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama", + "cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot", "cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo", "cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend", "cumulus/parachains/runtimes/bridge-hubs/test-utils", + "cumulus/parachains/runtimes/collectives/collectives-polkadot", "cumulus/parachains/runtimes/collectives/collectives-westend", "cumulus/parachains/runtimes/contracts/contracts-rococo", + "cumulus/parachains/runtimes/glutton/glutton-kusama", "cumulus/parachains/runtimes/glutton/glutton-westend", "cumulus/parachains/runtimes/starters/seedling", "cumulus/parachains/runtimes/starters/shell", "cumulus/parachains/runtimes/test-utils", "cumulus/parachains/runtimes/testing/penpal", "cumulus/parachains/runtimes/testing/rococo-parachain", + "cumulus/parachains/testnets-common", "cumulus/polkadot-parachain", "cumulus/primitives/aura", "cumulus/primitives/core", "cumulus/primitives/parachain-inherent", - "cumulus/primitives/proof-size-hostfunction", "cumulus/primitives/timestamp", "cumulus/primitives/utility", "cumulus/test/client", @@ -108,7 +110,6 @@ members = [ "cumulus/test/runtime", "cumulus/test/service", "cumulus/xcm/xcm-emulator", - "docs/sdk", "polkadot", "polkadot/cli", "polkadot/core-primitives", @@ -126,8 +127,8 @@ members = [ "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", "polkadot/node/core/pvf/common", "polkadot/node/core/pvf/execute-worker", "polkadot/node/core/pvf/prepare-worker", @@ -150,11 +151,10 @@ members = [ "polkadot/node/overseer", "polkadot/node/primitives", "polkadot/node/service", - "polkadot/node/subsystem", - "polkadot/node/subsystem-bench", "polkadot/node/subsystem-test-helpers", "polkadot/node/subsystem-types", "polkadot/node/subsystem-util", + "polkadot/node/subsystem", "polkadot/node/test/client", "polkadot/node/test/service", "polkadot/node/tracking-allocator", @@ -183,8 +183,8 @@ members = [ "polkadot/utils/generate-bags", "polkadot/utils/remote-ext-tests/bags-list", "polkadot/xcm", - "polkadot/xcm/pallet-xcm", "polkadot/xcm/pallet-xcm-benchmarks", + "polkadot/xcm/pallet-xcm", "polkadot/xcm/procedural", "polkadot/xcm/xcm-builder", "polkadot/xcm/xcm-executor", @@ -192,6 +192,7 @@ members = [ "polkadot/xcm/xcm-simulator", "polkadot/xcm/xcm-simulator/example", "polkadot/xcm/xcm-simulator/fuzzer", + "substrate", "substrate/bin/minimal/node", "substrate/bin/minimal/runtime", "substrate/bin/node-template/node", @@ -199,6 +200,7 @@ members = [ "substrate/bin/node-template/runtime", "substrate/bin/node/bench", "substrate/bin/node/cli", + "substrate/bin/node/executor", "substrate/bin/node/inspect", "substrate/bin/node/primitives", "substrate/bin/node/rpc", @@ -236,8 +238,8 @@ members = [ "substrate/client/merkle-mountain-range", "substrate/client/merkle-mountain-range/rpc", "substrate/client/mixnet", - "substrate/client/network", "substrate/client/network-gossip", + "substrate/client/network", "substrate/client/network/bitswap", "substrate/client/network/common", "substrate/client/network/light", @@ -247,10 +249,10 @@ members = [ "substrate/client/network/transactions", "substrate/client/offchain", "substrate/client/proposer-metrics", - "substrate/client/rpc", "substrate/client/rpc-api", "substrate/client/rpc-servers", "substrate/client/rpc-spec-v2", + "substrate/client/rpc", "substrate/client/service", "substrate/client/service/test", "substrate/client/state-db", @@ -278,8 +280,8 @@ members = [ "substrate/frame/bags-list/fuzzer", "substrate/frame/bags-list/remote-tests", "substrate/frame/balances", - "substrate/frame/beefy", "substrate/frame/beefy-mmr", + "substrate/frame/beefy", "substrate/frame/benchmarking", "substrate/frame/benchmarking/pov", "substrate/frame/bounties", @@ -288,10 +290,9 @@ members = [ "substrate/frame/collective", "substrate/frame/contracts", "substrate/frame/contracts/fixtures", - "substrate/frame/contracts/fixtures/contracts/common", "substrate/frame/contracts/mock-network", + "substrate/frame/contracts/primitives", "substrate/frame/contracts/proc-macro", - "substrate/frame/contracts/uapi", "substrate/frame/conviction-voting", "substrate/frame/core-fellowship", "substrate/frame/democracy", @@ -310,7 +311,6 @@ members = [ "substrate/frame/examples/kitchensink", "substrate/frame/examples/offchain-worker", "substrate/frame/examples/split", - "substrate/frame/examples/tasks", "substrate/frame/executive", "substrate/frame/fast-unstake", "substrate/frame/glutton", @@ -350,7 +350,6 @@ members = [ "substrate/frame/root-testing", "substrate/frame/safe-mode", "substrate/frame/salary", - "substrate/frame/sassafras", "substrate/frame/scheduler", "substrate/frame/scored-pool", "substrate/frame/session", @@ -430,12 +429,12 @@ members = [ "substrate/primitives/offchain", "substrate/primitives/panic-handler", "substrate/primitives/rpc", - "substrate/primitives/runtime", "substrate/primitives/runtime-interface", "substrate/primitives/runtime-interface/proc-macro", - "substrate/primitives/runtime-interface/test", - "substrate/primitives/runtime-interface/test-wasm", "substrate/primitives/runtime-interface/test-wasm-deprecated", + "substrate/primitives/runtime-interface/test-wasm", + "substrate/primitives/runtime-interface/test", + "substrate/primitives/runtime", "substrate/primitives/session", "substrate/primitives/staking", "substrate/primitives/state-machine", @@ -474,43 +473,17 @@ members = [ "substrate/utils/frame/try-runtime/cli", "substrate/utils/prometheus", "substrate/utils/wasm-builder", + "cumulus/parachains/integration-tests/emulated/networks/rococo-westend-system", ] -default-members = ["polkadot", "substrate/bin/node/cli"] - -[workspace.lints.rust] -suspicious_double_ref_op = { level = "allow", priority = 2 } - -[workspace.lints.clippy] -all = { level = "allow", priority = 0 } -correctness = { level = "deny", priority = 1 } -if-same-then-else = { level = "allow", priority = 2 } -complexity = { level = "deny", priority = 1 } -zero-prefixed-literal = { level = "allow", priority = 2 } # 00_1000_000 -type_complexity = { level = "allow", priority = 2 } # raison d'etre -nonminimal-bool = { level = "allow", priority = 2 } # maybe -borrowed-box = { level = "allow", priority = 2 } # Reasonable to fix this one -too-many-arguments = { level = "allow", priority = 2 } # (Turning this on would lead to) -unnecessary_cast = { level = "allow", priority = 2 } # Types may change -identity-op = { level = "allow", priority = 2 } # One case where we do 0 + -useless_conversion = { level = "allow", priority = 2 } # Types may change -unit_arg = { level = "allow", priority = 2 } # styalistic. -option-map-unit-fn = { level = "allow", priority = 2 } # styalistic -bind_instead_of_map = { level = "allow", priority = 2 } # styalistic -erasing_op = { level = "allow", priority = 2 } # E.g. 0 * DOLLARS -eq_op = { level = "allow", priority = 2 } # In tests we test equality. -while_immutable_condition = { level = "allow", priority = 2 } # false positives -needless_option_as_deref = { level = "allow", priority = 2 } # false positives -derivable_impls = { level = "allow", priority = 2 } # false positives -stable_sort_primitive = { level = "allow", priority = 2 } # prefer stable sort -extra-unused-type-parameters = { level = "allow", priority = 2 } # stylistic -default_constructed_unit_structs = { level = "allow", priority = 2 } # stylistic +default-members = [ "polkadot", "substrate/bin/node/cli" ] [profile.release] # Polkadot runtime requires unwinding. panic = "unwind" opt-level = 3 -# make sure dev builds with backtrace do not slow us down +# make sure dev builds with backtrace do +# not slow us down [profile.dev.package.backtrace] inherits = "release" diff --git a/README.md b/README.md index 1f255823b5b..56b3481bafc 100644 --- a/README.md +++ b/README.md @@ -46,12 +46,12 @@ Below are the primary upstream dependencies utilized in this project: ## Security -The security policy and procedures can be found in [docs/contributor/SECURITY.md](./docs/contributor/SECURITY.md). +The security policy and procedures can be found in [docs/SECURITY.md](./docs/SECURITY.md). ## Contributing & Code of Conduct -Ensure you follow our [contribution guidelines](./docs/contributor/CONTRIBUTING.md). In every interaction and -contribution, this project adheres to the [Contributor Covenant Code of Conduct](./docs/contributor/CODE_OF_CONDUCT.md). +Ensure you follow our [contribution guidelines](./docs/CONTRIBUTING.md). In every interaction and contribution, this +project adheres to the [Contributor Covenant Code of Conduct](./docs/CODE_OF_CONDUCT.md). ## Additional Resources diff --git a/bridges/bin/runtime-common/Cargo.toml b/bridges/bin/runtime-common/Cargo.toml index 8c3e8c989db..0ccf30987e8 100644 --- a/bridges/bin/runtime-common/Cargo.toml +++ b/bridges/bin/runtime-common/Cargo.toml @@ -7,9 +7,6 @@ edition.workspace = true repository.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive"] } hash-db = { version = "0.16.0", default-features = false } @@ -25,7 +22,6 @@ 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 } @@ -54,7 +50,7 @@ bp-test-utils = { path = "../../primitives/test-utils" } pallet-balances = { path = "../../../substrate/frame/balances" } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-header-chain/std", "bp-messages/std", @@ -63,7 +59,6 @@ std = [ "bp-relayers/std", "bp-runtime/std", "bp-xcm-bridge-hub-router/std", - "bp-xcm-bridge-hub/std", "codec/std", "frame-support/std", "frame-system/std", @@ -97,4 +92,4 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", ] -integrity-test = ["static_assertions"] +integrity-test = [ "static_assertions" ] diff --git a/bridges/bin/runtime-common/src/messages_xcm_extension.rs b/bridges/bin/runtime-common/src/messages_xcm_extension.rs index 53c0579c4cd..77c23db3b2b 100644 --- a/bridges/bin/runtime-common/src/messages_xcm_extension.rs +++ b/bridges/bin/runtime-common/src/messages_xcm_extension.rs @@ -22,23 +22,26 @@ //! `XcmRouter` <- `MessageDispatch` <- `InboundMessageQueue` use bp_messages::{ - source_chain::OnMessagesDelivered, + source_chain::{MessagesBridge, OnMessagesDelivered}, target_chain::{DispatchMessage, MessageDispatch}, LaneId, MessageNonce, }; use bp_runtime::messages::MessageDispatchResult; -pub use bp_xcm_bridge_hub::XcmAsPlainPayload; use bp_xcm_bridge_hub_router::XcmChannelStatusProvider; use codec::{Decode, Encode}; use frame_support::{traits::Get, weights::Weight, CloneNoBound, EqNoBound, PartialEqNoBound}; use pallet_bridge_messages::{ - Config as MessagesConfig, OutboundLanesCongestedSignals, WeightInfoExt as MessagesPalletWeights, + Config as MessagesConfig, OutboundLanesCongestedSignals, Pallet as MessagesPallet, + WeightInfoExt as MessagesPalletWeights, }; use scale_info::TypeInfo; use sp_runtime::SaturatedConversion; use sp_std::{fmt::Debug, marker::PhantomData}; use xcm::prelude::*; -use xcm_builder::{DispatchBlob, DispatchBlobError}; +use xcm_builder::{DispatchBlob, DispatchBlobError, HaulBlob, HaulBlobError}; + +/// Plain "XCM" payload, which we transfer through bridge +pub type XcmAsPlainPayload = sp_std::prelude::Vec; /// Message dispatch result type for single message #[derive(CloneNoBound, EqNoBound, PartialEqNoBound, Encode, Decode, Debug, TypeInfo)] @@ -120,7 +123,6 @@ impl< /// A pair of sending chain location and message lane, used by this chain to send messages /// over the bridge. -#[cfg_attr(feature = "std", derive(Debug, Eq, PartialEq))] pub struct SenderAndLane { /// Sending chain relative location. pub location: MultiLocation, @@ -142,6 +144,8 @@ pub trait XcmBlobHauler { type Runtime: MessagesConfig; /// Instance of the messages pallet that is used to send messages. type MessagesInstance: 'static; + /// Returns lane used by this hauler. + type SenderAndLane: Get; /// Actual XCM message sender (`HRMP` or `UMP`) to the source chain /// location (`Self::SenderAndLane::get().location`). @@ -162,25 +166,54 @@ pub trait XcmBlobHauler { /// makes sure that XCM blob is sent to the outbound lane to be relayed. /// /// It needs to be used at the source bridge hub. -pub struct XcmBlobHaulerAdapter( - sp_std::marker::PhantomData<(XcmBlobHauler, Lanes)>, -); +pub struct XcmBlobHaulerAdapter(sp_std::marker::PhantomData); -impl< - H: XcmBlobHauler, - Lanes: Get>, - > OnMessagesDelivered for XcmBlobHaulerAdapter +impl HaulBlob for XcmBlobHaulerAdapter +where + H::Runtime: MessagesConfig, { + fn haul_blob(blob: sp_std::prelude::Vec) -> Result<(), HaulBlobError> { + let sender_and_lane = H::SenderAndLane::get(); + MessagesPallet::::send_message(sender_and_lane.lane, blob) + .map(|artifacts| { + log::info!( + target: crate::LOG_TARGET_BRIDGE_DISPATCH, + "haul_blob result - ok: {:?} on lane: {:?}. Enqueued messages: {}", + artifacts.nonce, + sender_and_lane.lane, + artifacts.enqueued_messages, + ); + + // notify XCM queue manager about updated lane state + LocalXcmQueueManager::::on_bridge_message_enqueued( + &sender_and_lane, + artifacts.enqueued_messages, + ); + }) + .map_err(|error| { + log::error!( + target: crate::LOG_TARGET_BRIDGE_DISPATCH, + "haul_blob result - error: {:?} on lane: {:?}", + error, + sender_and_lane.lane, + ); + HaulBlobError::Transport("MessageSenderError") + }) + } +} + +impl OnMessagesDelivered for XcmBlobHaulerAdapter { fn on_messages_delivered(lane: LaneId, enqueued_messages: MessageNonce) { - if let Some(sender_and_lane) = - Lanes::get().iter().find(|link| link.0.lane == lane).map(|link| &link.0) - { - // notify XCM queue manager about updated lane state - LocalXcmQueueManager::::on_bridge_messages_delivered( - sender_and_lane, - enqueued_messages, - ); + let sender_and_lane = H::SenderAndLane::get(); + if sender_and_lane.lane != lane { + return } + + // notify XCM queue manager about updated lane state + LocalXcmQueueManager::::on_bridge_messages_delivered( + &sender_and_lane, + enqueued_messages, + ); } } @@ -309,28 +342,6 @@ impl LocalXcmQueueManager { } } -/// Adapter for the implementation of `GetVersion`, which attempts to find the minimal -/// configured XCM version between the destination `dest` and the bridge hub location provided as -/// `Get`. -pub struct XcmVersionOfDestAndRemoteBridge( - sp_std::marker::PhantomData<(Version, RemoteBridge)>, -); -impl> GetVersion - for XcmVersionOfDestAndRemoteBridge -{ - fn get_version_for(dest: &MultiLocation) -> Option { - let dest_version = Version::get_version_for(dest); - let bridge_hub_version = Version::get_version_for(&RemoteBridge::get()); - - match (dest_version, bridge_hub_version) { - (Some(dv), Some(bhv)) => Some(sp_std::cmp::min(dv, bhv)), - (Some(dv), None) => Some(dv), - (None, Some(bhv)) => Some(bhv), - (None, None) => None, - } - } -} - #[cfg(test)] mod tests { use super::*; @@ -345,9 +356,6 @@ mod tests { location: MultiLocation::new(1, X1(Parachain(1000))), lane: TEST_LANE_ID, }; - pub TestLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorMultiLocation))> = sp_std::vec![ - (TestSenderAndLane::get(), (NetworkId::ByGenesis([0; 32]), InteriorMultiLocation::Here)) - ]; pub DummyXcmMessage: Xcm<()> = Xcm::new(); } @@ -381,44 +389,37 @@ mod tests { impl XcmBlobHauler for TestBlobHauler { type Runtime = TestRuntime; type MessagesInstance = (); + type SenderAndLane = TestSenderAndLane; type ToSourceChainSender = DummySendXcm; type CongestedMessage = DummyXcmMessage; type UncongestedMessage = DummyXcmMessage; } - type TestBlobHaulerAdapter = XcmBlobHaulerAdapter; + type TestBlobHaulerAdapter = XcmBlobHaulerAdapter; - fn fill_up_lane_to_congestion() -> MessageNonce { - let latest_generated_nonce = OUTBOUND_LANE_CONGESTED_THRESHOLD; + fn fill_up_lane_to_congestion() { OutboundLanes::::insert( TEST_LANE_ID, OutboundLaneData { oldest_unpruned_nonce: 0, latest_received_nonce: 0, - latest_generated_nonce, + latest_generated_nonce: OUTBOUND_LANE_CONGESTED_THRESHOLD, }, ); - latest_generated_nonce } #[test] fn congested_signal_is_not_sent_twice() { run_test(|| { - let enqueued = fill_up_lane_to_congestion(); + fill_up_lane_to_congestion(); // next sent message leads to congested signal - LocalXcmQueueManager::::on_bridge_message_enqueued( - &TestSenderAndLane::get(), - enqueued + 1, - ); + TestBlobHaulerAdapter::haul_blob(vec![42]).unwrap(); assert_eq!(DummySendXcm::messages_sent(), 1); // next sent message => we don't sent another congested signal - LocalXcmQueueManager::::on_bridge_message_enqueued( - &TestSenderAndLane::get(), - enqueued, - ); + TestBlobHaulerAdapter::haul_blob(vec![42]).unwrap(); assert_eq!(DummySendXcm::messages_sent(), 1); }); } @@ -426,10 +427,7 @@ mod tests { #[test] fn congested_signal_is_not_sent_when_outbound_lane_is_not_congested() { run_test(|| { - LocalXcmQueueManager::::on_bridge_message_enqueued( - &TestSenderAndLane::get(), - 1, - ); + TestBlobHaulerAdapter::haul_blob(vec![42]).unwrap(); assert_eq!(DummySendXcm::messages_sent(), 0); }); } @@ -437,13 +435,10 @@ mod tests { #[test] fn congested_signal_is_sent_when_outbound_lane_is_congested() { run_test(|| { - let enqueued = fill_up_lane_to_congestion(); + fill_up_lane_to_congestion(); // next sent message leads to congested signal - LocalXcmQueueManager::::on_bridge_message_enqueued( - &TestSenderAndLane::get(), - enqueued + 1, - ); + TestBlobHaulerAdapter::haul_blob(vec![42]).unwrap(); assert_eq!(DummySendXcm::messages_sent(), 1); assert!(LocalXcmQueueManager::::is_congested_signal_sent(TEST_LANE_ID)); }); diff --git a/bridges/bin/runtime-common/src/mock.rs b/bridges/bin/runtime-common/src/mock.rs index bd47d37fc07..ffabf7f6e2f 100644 --- a/bridges/bin/runtime-common/src/mock.rs +++ b/bridges/bin/runtime-common/src/mock.rs @@ -376,8 +376,8 @@ impl ChainWithGrandpa for BridgedUnderlyingChain { const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = ""; const MAX_AUTHORITIES_COUNT: u32 = 16; const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = 8; - const MAX_MANDATORY_HEADER_SIZE: u32 = 256; - const AVERAGE_HEADER_SIZE: u32 = 64; + const MAX_HEADER_SIZE: u32 = 256; + const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = 64; } impl Chain for BridgedUnderlyingParachain { diff --git a/bridges/modules/grandpa/Cargo.toml b/bridges/modules/grandpa/Cargo.toml index e346f2061e2..dbbe18febc6 100644 --- a/bridges/modules/grandpa/Cargo.toml +++ b/bridges/modules/grandpa/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] @@ -40,7 +37,7 @@ sp-core = { path = "../../../substrate/primitives/core" } sp-io = { path = "../../../substrate/primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-header-chain/std", "bp-runtime/std", diff --git a/bridges/modules/grandpa/src/call_ext.rs b/bridges/modules/grandpa/src/call_ext.rs index c1585020be1..f238064f92b 100644 --- a/bridges/modules/grandpa/src/call_ext.rs +++ b/bridges/modules/grandpa/src/call_ext.rs @@ -15,10 +15,7 @@ // along with Parity Bridges Common. If not, see . use crate::{weights::WeightInfo, BridgedBlockNumber, BridgedHeader, Config, Error, Pallet}; -use bp_header_chain::{ - justification::GrandpaJustification, max_expected_submit_finality_proof_arguments_size, - ChainWithGrandpa, GrandpaConsensusLogReader, -}; +use bp_header_chain::{justification::GrandpaJustification, ChainWithGrandpa}; use bp_runtime::{BlockNumberOf, OwnedBridgeModule}; use codec::Encode; use frame_support::{dispatch::CallableCallFor, traits::IsSubType, weights::Weight}; @@ -172,28 +169,28 @@ pub(crate) fn submit_finality_proof_info_from_args, I: 'static>( Weight::zero() }; - // check if the `finality_target` is a mandatory header. If so, we are ready to refund larger - // size - let is_mandatory_finality_target = - GrandpaConsensusLogReader::>::find_scheduled_change( - finality_target.digest(), - ) - .is_some(); - // we can estimate extra call size easily, without any additional significant overhead let actual_call_size: u32 = finality_target .encoded_size() .saturating_add(justification.encoded_size()) .saturated_into(); - let max_expected_call_size = max_expected_submit_finality_proof_arguments_size::( - is_mandatory_finality_target, - required_precommits, - ); + let max_expected_call_size = max_expected_call_size::(required_precommits); let extra_size = actual_call_size.saturating_sub(max_expected_call_size); SubmitFinalityProofInfo { block_number, extra_weight, extra_size } } +/// Returns maximal expected size of `submit_finality_proof` call arguments. +fn max_expected_call_size, I: 'static>(required_precommits: u32) -> u32 { + let max_expected_justification_size = + GrandpaJustification::>::max_reasonable_size::( + required_precommits, + ); + + // call arguments are header and justification + T::BridgedChain::MAX_HEADER_SIZE.saturating_add(max_expected_justification_size) +} + #[cfg(test)] mod tests { use crate::{ diff --git a/bridges/modules/grandpa/src/mock.rs b/bridges/modules/grandpa/src/mock.rs index a54f56c4a62..7efa84971fe 100644 --- a/bridges/modules/grandpa/src/mock.rs +++ b/bridges/modules/grandpa/src/mock.rs @@ -86,8 +86,8 @@ impl ChainWithGrandpa for TestBridgedChain { const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = ""; const MAX_AUTHORITIES_COUNT: u32 = MAX_BRIDGED_AUTHORITIES; const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = 8; - const MAX_MANDATORY_HEADER_SIZE: u32 = 256; - const AVERAGE_HEADER_SIZE: u32 = 64; + const MAX_HEADER_SIZE: u32 = 256; + const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = 64; } /// Return test externalities to use in tests. diff --git a/bridges/modules/messages/Cargo.toml b/bridges/modules/messages/Cargo.toml index 4d9371448df..a5c86693309 100644 --- a/bridges/modules/messages/Cargo.toml +++ b/bridges/modules/messages/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false } log = { version = "0.4.20", default-features = false } @@ -34,7 +31,7 @@ pallet-balances = { path = "../../../substrate/frame/balances" } sp-io = { path = "../../../substrate/primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-messages/std", "bp-runtime/std", diff --git a/bridges/modules/messages/src/weights_ext.rs b/bridges/modules/messages/src/weights_ext.rs index c12e04f692b..aeb3a581a69 100644 --- a/bridges/modules/messages/src/weights_ext.rs +++ b/bridges/modules/messages/src/weights_ext.rs @@ -60,8 +60,7 @@ pub fn ensure_weights_are_correct() { // W::receive_messages_delivery_proof_messages_overhead(1).ref_time() may be zero because: // there's no code that iterates over confirmed messages in confirmation transaction assert_eq!(W::receive_messages_delivery_proof_messages_overhead(1).proof_size(), 0); - // W::receive_messages_delivery_proof_relayers_overhead(1).ref_time() may be zero because: - // runtime **can** choose not to pay any rewards to relayers + assert_ne!(W::receive_messages_delivery_proof_relayers_overhead(1).ref_time(), 0); // W::receive_messages_delivery_proof_relayers_overhead(1).proof_size() is an exception // it may or may not cause additional db reads, so proof size may vary assert_ne!(W::storage_proof_size_overhead(1).ref_time(), 0); diff --git a/bridges/modules/parachains/Cargo.toml b/bridges/modules/parachains/Cargo.toml index 77a5366c78d..0d1b61ddea8 100644 --- a/bridges/modules/parachains/Cargo.toml +++ b/bridges/modules/parachains/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false } log = { version = "0.4.20", default-features = false } @@ -38,7 +35,7 @@ sp-core = { path = "../../../substrate/primitives/core" } sp-io = { path = "../../../substrate/primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-header-chain/std", "bp-parachains/std", diff --git a/bridges/modules/parachains/src/mock.rs b/bridges/modules/parachains/src/mock.rs index 1c7851364d1..d95e76f3108 100644 --- a/bridges/modules/parachains/src/mock.rs +++ b/bridges/modules/parachains/src/mock.rs @@ -252,8 +252,8 @@ impl ChainWithGrandpa for TestBridgedChain { const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = ""; const MAX_AUTHORITIES_COUNT: u32 = 16; const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = 8; - const MAX_MANDATORY_HEADER_SIZE: u32 = 256; - const AVERAGE_HEADER_SIZE: u32 = 64; + const MAX_HEADER_SIZE: u32 = 256; + const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = 64; } #[derive(Debug)] @@ -283,8 +283,8 @@ impl ChainWithGrandpa for OtherBridgedChain { const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = ""; const MAX_AUTHORITIES_COUNT: u32 = 16; const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = 8; - const MAX_MANDATORY_HEADER_SIZE: u32 = 256; - const AVERAGE_HEADER_SIZE: u32 = 64; + const MAX_HEADER_SIZE: u32 = 256; + const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = 64; } /// Return test externalities to use in tests. diff --git a/bridges/modules/relayers/Cargo.toml b/bridges/modules/relayers/Cargo.toml index 8c8305ef64c..6ec1971e3f6 100644 --- a/bridges/modules/relayers/Cargo.toml +++ b/bridges/modules/relayers/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false } log = { version = "0.4.20", default-features = false } @@ -37,7 +34,7 @@ sp-io = { path = "../../../substrate/primitives/io" } sp-runtime = { path = "../../../substrate/primitives/runtime" } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-messages/std", "bp-relayers/std", diff --git a/bridges/modules/xcm-bridge-hub-router/Cargo.toml b/bridges/modules/xcm-bridge-hub-router/Cargo.toml index 1d84f723ee9..56b9139d7d5 100644 --- a/bridges/modules/xcm-bridge-hub-router/Cargo.toml +++ b/bridges/modules/xcm-bridge-hub-router/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false } log = { version = "0.4.20", default-features = false } @@ -37,7 +34,7 @@ sp-io = { path = "../../../substrate/primitives/io" } sp-std = { path = "../../../substrate/primitives/std" } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-xcm-bridge-hub-router/std", "codec/std", diff --git a/bridges/modules/xcm-bridge-hub-router/src/benchmarking.rs b/bridges/modules/xcm-bridge-hub-router/src/benchmarking.rs index 922e4bf94ba..c4d1e3971e7 100644 --- a/bridges/modules/xcm-bridge-hub-router/src/benchmarking.rs +++ b/bridges/modules/xcm-bridge-hub-router/src/benchmarking.rs @@ -21,7 +21,7 @@ use crate::{Bridge, Call}; use bp_xcm_bridge_hub_router::{BridgeState, MINIMAL_DELIVERY_FEE_FACTOR}; -use frame_benchmarking::{benchmarks_instance_pallet, BenchmarkError}; +use frame_benchmarking::benchmarks_instance_pallet; use frame_support::traits::{EnsureOrigin, Get, Hooks, UnfilteredDispatchable}; use sp_runtime::traits::Zero; use xcm::prelude::*; @@ -37,11 +37,11 @@ pub trait Config: crate::Config { /// Returns destination which is valid for this router instance. /// (Needs to pass `T::Bridges`) /// Make sure that `SendXcm` will pass. - fn ensure_bridged_target_destination() -> Result { - Ok(MultiLocation::new( + fn ensure_bridged_target_destination() -> MultiLocation { + MultiLocation::new( Self::UniversalLocation::get().len() as u8, X1(GlobalConsensus(Self::BridgedNetworkId::get().unwrap())), - )) + ) } } @@ -61,7 +61,7 @@ benchmarks_instance_pallet! { delivery_fee_factor: MINIMAL_DELIVERY_FEE_FACTOR + MINIMAL_DELIVERY_FEE_FACTOR, }); - let _ = T::ensure_bridged_target_destination()?; + let _ = T::ensure_bridged_target_destination(); T::make_congested(); }: { crate::Pallet::::on_initialize(Zero::zero()) @@ -81,7 +81,7 @@ benchmarks_instance_pallet! { } send_message { - let dest = T::ensure_bridged_target_destination()?; + let dest = T::ensure_bridged_target_destination(); let xcm = sp_std::vec![].into(); // make local queue congested, because it means additional db write diff --git a/bridges/modules/xcm-bridge-hub-router/src/lib.rs b/bridges/modules/xcm-bridge-hub-router/src/lib.rs index 229628aedcb..cf51ef82412 100644 --- a/bridges/modules/xcm-bridge-hub-router/src/lib.rs +++ b/bridges/modules/xcm-bridge-hub-router/src/lib.rs @@ -89,8 +89,6 @@ pub mod pallet { /// **possible fee**. Allows to externalize better control over allowed **bridged /// networks/locations**. type Bridges: ExporterFor; - /// Checks the XCM version for the destination. - type DestinationVersion: GetVersion; /// Origin of the sibling bridge hub that is allowed to report bridge status. type BridgeHubOrigin: EnsureOrigin; @@ -321,13 +319,12 @@ impl, I: 'static> SendXcm for Pallet { dest: &mut Option, xcm: &mut Option>, ) -> SendResult { - // `dest` and `xcm` are required here - let dest_ref = dest.as_ref().ok_or(SendError::MissingArgument)?; - let xcm_ref = xcm.as_ref().ok_or(SendError::MissingArgument)?; - - // we won't have an access to `dest` and `xcm` in the `deliver` method, so precompute + // we won't have an access to `dest` and `xcm` in the `delvier` method, so precompute // everything required here - let message_size = xcm_ref.encoded_size() as _; + let message_size = xcm + .as_ref() + .map(|xcm| xcm.encoded_size() as _) + .ok_or(SendError::MissingArgument)?; // bridge doesn't support oversized/overweight messages now. So it is better to drop such // messages here than at the bridge hub. Let's check the message size. @@ -335,18 +332,6 @@ impl, I: 'static> SendXcm for Pallet { return Err(SendError::ExceedsMaxMessageSize) } - // We need to ensure that the known `dest`'s XCM version can comprehend the current `xcm` - // program. This may seem like an additional, unnecessary check, but it is not. A similar - // check is probably performed by the `ViaBridgeHubExporter`, which attempts to send a - // versioned message to the sibling bridge hub. However, the local bridge hub may have a - // higher XCM version than the remote `dest`. Once again, it is better to discard such - // messages here than at the bridge hub (e.g., to avoid losing funds). - let destination_version = T::DestinationVersion::get_version_for(dest_ref) - .ok_or(SendError::DestinationUnsupported)?; - let _ = VersionedXcm::from(xcm_ref.clone()) - .into_version(destination_version) - .map_err(|()| SendError::DestinationUnsupported)?; - // just use exporter to validate destination and insert instructions to pay message fee // at the sibling/child bridge hub // @@ -373,7 +358,6 @@ impl, I: 'static> SendXcm for Pallet { #[cfg(test)] mod tests { use super::*; - use frame_support::assert_ok; use mock::*; use frame_support::traits::Hooks; @@ -467,19 +451,6 @@ mod tests { }); } - #[test] - fn destination_unsupported_if_wrap_version_fails() { - run_test(|| { - assert_eq!( - send_xcm::( - UnknownXcmVersionLocation::get(), - vec![ClearOrigin].into(), - ), - Err(SendError::DestinationUnsupported), - ); - }); - } - #[test] fn returns_proper_delivery_price() { run_test(|| { @@ -517,14 +488,17 @@ mod tests { fn sent_message_doesnt_increase_factor_if_xcm_channel_is_uncongested() { run_test(|| { let old_bridge = XcmBridgeHubRouter::bridge(); - assert_ok!(send_xcm::( - MultiLocation::new( - 2, - X2(GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)) - ), - vec![ClearOrigin].into(), - ) - .map(drop)); + assert_eq!( + send_xcm::( + MultiLocation::new( + 2, + X2(GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)) + ), + vec![ClearOrigin].into(), + ) + .map(drop), + Ok(()), + ); assert!(TestToBridgeHubSender::is_message_sent()); assert_eq!(old_bridge, XcmBridgeHubRouter::bridge()); @@ -537,14 +511,17 @@ mod tests { TestWithBridgeHubChannel::make_congested(); let old_bridge = XcmBridgeHubRouter::bridge(); - assert_ok!(send_xcm::( - MultiLocation::new( - 2, - X2(GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)) - ), - vec![ClearOrigin].into(), - ) - .map(drop)); + assert_eq!( + send_xcm::( + MultiLocation::new( + 2, + X2(GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)) + ), + vec![ClearOrigin].into(), + ) + .map(drop), + Ok(()), + ); assert!(TestToBridgeHubSender::is_message_sent()); assert!( @@ -559,14 +536,17 @@ mod tests { Bridge::::put(congested_bridge(MINIMAL_DELIVERY_FEE_FACTOR)); let old_bridge = XcmBridgeHubRouter::bridge(); - assert_ok!(send_xcm::( - MultiLocation::new( - 2, - X2(GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)) - ), - vec![ClearOrigin].into(), - ) - .map(drop)); + assert_eq!( + send_xcm::( + MultiLocation::new( + 2, + X2(GlobalConsensus(BridgedNetworkId::get()), Parachain(1000)) + ), + vec![ClearOrigin].into(), + ) + .map(drop), + Ok(()), + ); assert!(TestToBridgeHubSender::is_message_sent()); assert!( diff --git a/bridges/modules/xcm-bridge-hub-router/src/mock.rs b/bridges/modules/xcm-bridge-hub-router/src/mock.rs index 9079f4b9c4c..2d173ebc045 100644 --- a/bridges/modules/xcm-bridge-hub-router/src/mock.rs +++ b/bridges/modules/xcm-bridge-hub-router/src/mock.rs @@ -19,10 +19,7 @@ use crate as pallet_xcm_bridge_hub_router; use bp_xcm_bridge_hub_router::XcmChannelStatusProvider; -use frame_support::{ - construct_runtime, derive_impl, parameter_types, - traits::{Contains, Equals}, -}; +use frame_support::{construct_runtime, derive_impl, parameter_types}; use frame_system::EnsureRoot; use sp_runtime::{traits::ConstU128, BuildStorage}; use xcm::prelude::*; @@ -61,7 +58,6 @@ parameter_types! { Some((BridgeFeeAsset::get(), BASE_FEE).into()) ) ]; - pub UnknownXcmVersionLocation: MultiLocation = MultiLocation::new(2, X2(GlobalConsensus(BridgedNetworkId::get()), Parachain(9999))); } #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] @@ -75,8 +71,6 @@ impl pallet_xcm_bridge_hub_router::Config<()> for TestRuntime { type UniversalLocation = UniversalLocation; type BridgedNetworkId = BridgedNetworkId; type Bridges = NetworkExportTable; - type DestinationVersion = - LatestOrNoneForLocationVersionChecker>; type BridgeHubOrigin = EnsureRoot; type ToBridgeHubSender = TestToBridgeHubSender; @@ -86,18 +80,6 @@ impl pallet_xcm_bridge_hub_router::Config<()> for TestRuntime { type FeeAsset = BridgeFeeAsset; } -pub struct LatestOrNoneForLocationVersionChecker(sp_std::marker::PhantomData); -impl> GetVersion - for LatestOrNoneForLocationVersionChecker -{ - fn get_version_for(dest: &MultiLocation) -> Option { - if Location::contains(dest) { - return None - } - Some(XCM_VERSION) - } -} - pub struct TestToBridgeHubSender; impl TestToBridgeHubSender { diff --git a/bridges/modules/xcm-bridge-hub/Cargo.toml b/bridges/modules/xcm-bridge-hub/Cargo.toml deleted file mode 100644 index 061d4b7ced8..00000000000 --- a/bridges/modules/xcm-bridge-hub/Cargo.toml +++ /dev/null @@ -1,77 +0,0 @@ -[package] -name = "pallet-xcm-bridge-hub" -description = "Module that adds dynamic bridges/lanes support to XCM infrastucture at the bridge hub." -version = "0.1.0" -authors.workspace = true -edition.workspace = true -license = "GPL-3.0-or-later WITH Classpath-exception-2.0" - -[lints] -workspace = true - -[dependencies] -codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false } -log = { version = "0.4.20", default-features = false } -scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } - -# 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 } - -# 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 } - -# 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 } - -[dev-dependencies] -bp-header-chain = { path = "../../primitives/header-chain" } -pallet-balances = { path = "../../../substrate/frame/balances" } -sp-io = { path = "../../../substrate/primitives/io" } - -[features] -default = ["std"] -std = [ - "bp-messages/std", - "bp-runtime/std", - "bp-xcm-bridge-hub/std", - "bridge-runtime-common/std", - "codec/std", - "frame-support/std", - "frame-system/std", - "log/std", - "pallet-bridge-messages/std", - "scale-info/std", - "sp-core/std", - "sp-runtime/std", - "sp-std/std", - "xcm-builder/std", - "xcm-executor/std", - "xcm/std", -] -runtime-benchmarks = [ - "bridge-runtime-common/runtime-benchmarks", - "frame-support/runtime-benchmarks", - "frame-system/runtime-benchmarks", - "pallet-balances/runtime-benchmarks", - "pallet-bridge-messages/runtime-benchmarks", - "sp-runtime/runtime-benchmarks", - "xcm-builder/runtime-benchmarks", - "xcm-executor/runtime-benchmarks", -] -try-runtime = [ - "frame-support/try-runtime", - "frame-system/try-runtime", - "pallet-balances/try-runtime", - "pallet-bridge-messages/try-runtime", - "sp-runtime/try-runtime", -] diff --git a/bridges/modules/xcm-bridge-hub/src/exporter.rs b/bridges/modules/xcm-bridge-hub/src/exporter.rs deleted file mode 100644 index 5318b222c54..00000000000 --- a/bridges/modules/xcm-bridge-hub/src/exporter.rs +++ /dev/null @@ -1,209 +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 . - -//! The code that allows to use the pallet (`pallet-xcm-bridge-hub`) as XCM message -//! exporter at the sending bridge hub. Internally, it just enqueues outbound blob -//! in the messages pallet queue. -//! -//! This code is executed at the source bridge hub. - -use crate::{Config, Pallet, LOG_TARGET}; - -use bp_messages::source_chain::MessagesBridge; -use bp_xcm_bridge_hub::XcmAsPlainPayload; -use bridge_runtime_common::messages_xcm_extension::{LocalXcmQueueManager, SenderAndLane}; -use pallet_bridge_messages::{Config as BridgeMessagesConfig, Pallet as BridgeMessagesPallet}; -use xcm::prelude::*; -use xcm_builder::{HaulBlob, HaulBlobError, HaulBlobExporter}; -use xcm_executor::traits::ExportXcm; - -/// An easy way to access `HaulBlobExporter`. -pub type PalletAsHaulBlobExporter = HaulBlobExporter< - DummyHaulBlob, - >::BridgedNetwork, - >::DestinationVersion, - >::MessageExportPrice, ->; -/// An easy way to access associated messages pallet. -type MessagesPallet = BridgeMessagesPallet>::BridgeMessagesPalletInstance>; - -impl, I: 'static> ExportXcm for Pallet -where - T: BridgeMessagesConfig< - >::BridgeMessagesPalletInstance, - OutboundPayload = XcmAsPlainPayload, - >, -{ - type Ticket = (SenderAndLane, XcmAsPlainPayload, XcmHash); - - fn validate( - network: NetworkId, - channel: u32, - universal_source: &mut Option, - destination: &mut Option, - message: &mut Option>, - ) -> Result<(Self::Ticket, MultiAssets), SendError> { - // Find supported lane_id. - let sender_and_lane = Self::lane_for( - universal_source.as_ref().ok_or(SendError::MissingArgument)?, - (&network, destination.as_ref().ok_or(SendError::MissingArgument)?), - ) - .ok_or(SendError::NotApplicable)?; - - // check if we are able to route the message. We use existing `HaulBlobExporter` for that. - // It will make all required changes and will encode message properly, so that the - // `DispatchBlob` at the bridged bridge hub will be able to decode it - let ((blob, id), price) = PalletAsHaulBlobExporter::::validate( - network, - channel, - universal_source, - destination, - message, - )?; - - Ok(((sender_and_lane, blob, id), price)) - } - - fn deliver( - (sender_and_lane, blob, id): (SenderAndLane, XcmAsPlainPayload, XcmHash), - ) -> Result { - let lane_id = sender_and_lane.lane; - let send_result = MessagesPallet::::send_message(lane_id, blob); - - match send_result { - Ok(artifacts) => { - log::info!( - target: LOG_TARGET, - "XCM message {:?} has been enqueued at bridge {:?} with nonce {}", - id, - lane_id, - artifacts.nonce, - ); - - // notify XCM queue manager about updated lane state - LocalXcmQueueManager::::on_bridge_message_enqueued( - &sender_and_lane, - artifacts.enqueued_messages, - ); - }, - Err(error) => { - log::debug!( - target: LOG_TARGET, - "XCM message {:?} has been dropped because of bridge error {:?} on bridge {:?}", - id, - error, - lane_id, - ); - return Err(SendError::Transport("BridgeSendError")) - }, - } - - Ok(id) - } -} - -/// Dummy implementation of the `HaulBlob` trait that is never called. -/// -/// We are using `HaulBlobExporter`, which requires `HaulBlob` implementation. It assumes that -/// there's a single channel between two bridge hubs - `HaulBlob` only accepts the blob and nothing -/// else. But bridge messages pallet may have a dedicated channel (lane) for every pair of bridged -/// chains. So we are using our own `ExportXcm` implementation, but to utilize `HaulBlobExporter` we -/// still need this `DummyHaulBlob`. -pub struct DummyHaulBlob; - -impl HaulBlob for DummyHaulBlob { - fn haul_blob(_blob: XcmAsPlainPayload) -> Result<(), HaulBlobError> { - Err(HaulBlobError::Transport("DummyHaulBlob")) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::mock::*; - use frame_support::assert_ok; - use xcm_executor::traits::export_xcm; - - fn universal_source() -> InteriorMultiLocation { - X2(GlobalConsensus(RelayNetwork::get()), Parachain(SIBLING_ASSET_HUB_ID)) - } - - fn universal_destination() -> InteriorMultiLocation { - BridgedDestination::get() - } - - #[test] - fn export_works() { - run_test(|| { - assert_ok!(export_xcm::( - BridgedRelayNetwork::get(), - 0, - universal_source(), - universal_destination(), - vec![Instruction::ClearOrigin].into(), - )); - }) - } - - #[test] - fn export_fails_if_argument_is_missing() { - run_test(|| { - assert_eq!( - XcmOverBridge::validate( - BridgedRelayNetwork::get(), - 0, - &mut None, - &mut Some(universal_destination()), - &mut Some(Vec::new().into()), - ), - Err(SendError::MissingArgument), - ); - - assert_eq!( - XcmOverBridge::validate( - BridgedRelayNetwork::get(), - 0, - &mut Some(universal_source()), - &mut None, - &mut Some(Vec::new().into()), - ), - Err(SendError::MissingArgument), - ); - }) - } - - #[test] - fn exporter_computes_correct_lane_id() { - run_test(|| { - let expected_lane_id = TEST_LANE_ID; - - assert_eq!( - XcmOverBridge::validate( - BridgedRelayNetwork::get(), - 0, - &mut Some(universal_source()), - &mut Some(universal_destination()), - &mut Some(Vec::new().into()), - ) - .unwrap() - .0 - .0 - .lane, - expected_lane_id, - ); - }) - } -} diff --git a/bridges/modules/xcm-bridge-hub/src/lib.rs b/bridges/modules/xcm-bridge-hub/src/lib.rs deleted file mode 100644 index 44f6903b018..00000000000 --- a/bridges/modules/xcm-bridge-hub/src/lib.rs +++ /dev/null @@ -1,118 +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 . - -//! Module that adds XCM support to bridge pallets. - -#![warn(missing_docs)] -#![cfg_attr(not(feature = "std"), no_std)] - -use bridge_runtime_common::messages_xcm_extension::XcmBlobHauler; -use pallet_bridge_messages::Config as BridgeMessagesConfig; -use xcm::prelude::*; - -pub use exporter::PalletAsHaulBlobExporter; -pub use pallet::*; - -mod exporter; -mod mock; - -/// The target that will be used when publishing logs related to this pallet. -pub const LOG_TARGET: &str = "runtime::bridge-xcm"; - -#[frame_support::pallet] -pub mod pallet { - use super::*; - use bridge_runtime_common::messages_xcm_extension::SenderAndLane; - use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::BlockNumberFor; - - #[pallet::config] - #[pallet::disable_frame_system_supertrait_check] - pub trait Config: - BridgeMessagesConfig - { - /// Runtime's universal location. - type UniversalLocation: Get; - // TODO: https://github.com/paritytech/parity-bridges-common/issues/1666 remove `ChainId` and - // replace it with the `NetworkId` - then we'll be able to use - // `T as pallet_bridge_messages::Config::BridgedChain::NetworkId` - /// Bridged network as relative location of bridged `GlobalConsensus`. - #[pallet::constant] - type BridgedNetwork: Get; - /// Associated messages pallet instance that bridges us with the - /// `BridgedNetworkId` consensus. - type BridgeMessagesPalletInstance: 'static; - - /// Price of single message export to the bridged consensus (`Self::BridgedNetworkId`). - type MessageExportPrice: Get; - /// Checks the XCM version for the destination. - type DestinationVersion: GetVersion; - - /// Get point-to-point links with bridged consensus (`Self::BridgedNetworkId`). - /// (this will be replaced with dynamic on-chain bridges - `Bridges V2`) - type Lanes: Get>; - /// Support for point-to-point links - /// (this will be replaced with dynamic on-chain bridges - `Bridges V2`) - type LanesSupport: XcmBlobHauler; - } - - #[pallet::pallet] - pub struct Pallet(PhantomData<(T, I)>); - - #[pallet::hooks] - impl, I: 'static> Hooks> for Pallet { - fn integrity_test() { - assert!( - Self::bridged_network_id().is_some(), - "Configured `T::BridgedNetwork`: {:?} does not contain `GlobalConsensus` junction with `NetworkId`", - T::BridgedNetwork::get() - ) - } - } - - impl, I: 'static> Pallet { - /// Returns dedicated/configured lane identifier. - pub(crate) fn lane_for( - source: &InteriorMultiLocation, - dest: (&NetworkId, &InteriorMultiLocation), - ) -> Option { - let source = source.relative_to(&T::UniversalLocation::get()); - - // Check that we have configured a point-to-point lane for 'source' and `dest`. - T::Lanes::get() - .into_iter() - .find_map(|(lane_source, (lane_dest_network, lane_dest))| { - if lane_source.location == source && - &lane_dest_network == dest.0 && - Self::bridged_network_id().as_ref() == Some(dest.0) && - &lane_dest == dest.1 - { - Some(lane_source) - } else { - None - } - }) - } - - /// Returns some `NetworkId` if contains `GlobalConsensus` junction. - fn bridged_network_id() -> Option { - match T::BridgedNetwork::get().take_first_interior() { - Some(GlobalConsensus(network)) => Some(network), - _ => None, - } - } - } -} diff --git a/bridges/modules/xcm-bridge-hub/src/mock.rs b/bridges/modules/xcm-bridge-hub/src/mock.rs deleted file mode 100644 index 8edd4b1f7aa..00000000000 --- a/bridges/modules/xcm-bridge-hub/src/mock.rs +++ /dev/null @@ -1,334 +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 . - -#![cfg(test)] - -use crate as pallet_xcm_bridge_hub; - -use bp_messages::{ - source_chain::LaneMessageVerifier, - target_chain::{DispatchMessage, MessageDispatch}, - LaneId, OutboundLaneData, VerificationError, -}; -use bp_runtime::{messages::MessageDispatchResult, Chain, UnderlyingChainProvider}; -use bridge_runtime_common::{ - messages::{ - source::TargetHeaderChainAdapter, target::SourceHeaderChainAdapter, - BridgedChainWithMessages, HashOf, MessageBridge, ThisChainWithMessages, - }, - messages_xcm_extension::{SenderAndLane, XcmBlobHauler}, -}; -use codec::Encode; -use frame_support::{derive_impl, parameter_types, traits::ConstU32, weights::RuntimeDbWeight}; -use sp_core::H256; -use sp_runtime::{ - testing::Header as SubstrateHeader, - traits::{BlakeTwo256, IdentityLookup}, - AccountId32, BuildStorage, -}; -use xcm::prelude::*; - -pub type AccountId = AccountId32; -pub type Balance = u64; - -type Block = frame_system::mocking::MockBlock; - -pub const SIBLING_ASSET_HUB_ID: u32 = 2001; -pub const THIS_BRIDGE_HUB_ID: u32 = 2002; -pub const BRIDGED_ASSET_HUB_ID: u32 = 1001; -pub const TEST_LANE_ID: LaneId = LaneId([0, 0, 0, 1]); - -frame_support::construct_runtime! { - pub enum TestRuntime { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - Balances: pallet_balances::{Pallet, Event}, - Messages: pallet_bridge_messages::{Pallet, Call, Event}, - XcmOverBridge: pallet_xcm_bridge_hub::{Pallet}, - } -} - -parameter_types! { - pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 1, write: 2 }; - pub const ExistentialDeposit: Balance = 1; -} - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] -impl frame_system::Config for TestRuntime { - type AccountId = AccountId; - type AccountData = pallet_balances::AccountData; - type Block = Block; - type Lookup = IdentityLookup; -} - -#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)] -impl pallet_balances::Config for TestRuntime { - type AccountStore = System; -} - -/// Lane message verifier that is used in tests. -#[derive(Debug, Default)] -pub struct TestLaneMessageVerifier; - -impl LaneMessageVerifier> for TestLaneMessageVerifier { - fn verify_message( - _lane: &LaneId, - _lane_outbound_data: &OutboundLaneData, - _payload: &Vec, - ) -> Result<(), VerificationError> { - Ok(()) - } -} - -parameter_types! { - pub const ActiveOutboundLanes: &'static [LaneId] = &[TEST_LANE_ID]; -} - -impl pallet_bridge_messages::Config for TestRuntime { - type RuntimeEvent = RuntimeEvent; - type WeightInfo = TestMessagesWeights; - - type BridgedChainId = (); - type ActiveOutboundLanes = ActiveOutboundLanes; - type MaxUnrewardedRelayerEntriesAtInboundLane = (); - type MaxUnconfirmedMessagesAtInboundLane = (); - type MaximalOutboundPayloadSize = ConstU32<2048>; - type OutboundPayload = Vec; - type InboundPayload = Vec; - type InboundRelayer = (); - type DeliveryPayments = (); - type TargetHeaderChain = TargetHeaderChainAdapter; - type LaneMessageVerifier = TestLaneMessageVerifier; - type DeliveryConfirmationPayments = (); - type OnMessagesDelivered = (); - type SourceHeaderChain = SourceHeaderChainAdapter; - type MessageDispatch = TestMessageDispatch; -} - -pub struct TestMessagesWeights; - -impl pallet_bridge_messages::WeightInfo for TestMessagesWeights { - fn receive_single_message_proof() -> Weight { - Weight::zero() - } - fn receive_single_message_proof_with_outbound_lane_state() -> Weight { - Weight::zero() - } - fn receive_delivery_proof_for_single_message() -> Weight { - Weight::zero() - } - fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { - Weight::zero() - } - fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { - Weight::zero() - } - - fn receive_two_messages_proof() -> Weight { - Weight::zero() - } - - fn receive_single_message_proof_1_kb() -> Weight { - Weight::zero() - } - - fn receive_single_message_proof_16_kb() -> Weight { - Weight::zero() - } - - fn receive_single_message_proof_with_dispatch(_: u32) -> Weight { - Weight::from_parts(1, 0) - } -} - -impl pallet_bridge_messages::WeightInfoExt for TestMessagesWeights { - fn expected_extra_storage_proof_size() -> u32 { - 0 - } - - fn receive_messages_proof_overhead_from_runtime() -> Weight { - Weight::zero() - } - - fn receive_messages_delivery_proof_overhead_from_runtime() -> Weight { - Weight::zero() - } -} - -parameter_types! { - pub const RelayNetwork: NetworkId = NetworkId::Kusama; - pub const BridgedRelayNetwork: NetworkId = NetworkId::Polkadot; - pub const BridgedRelayNetworkLocation: MultiLocation = MultiLocation { - parents: 1, - interior: X1(GlobalConsensus(BridgedRelayNetwork::get())) - }; - pub const NonBridgedRelayNetwork: NetworkId = NetworkId::Rococo; - pub const BridgeReserve: Balance = 100_000; - pub UniversalLocation: InteriorMultiLocation = X2( - GlobalConsensus(RelayNetwork::get()), - Parachain(THIS_BRIDGE_HUB_ID), - ); - pub const Penalty: Balance = 1_000; -} - -impl pallet_xcm_bridge_hub::Config for TestRuntime { - type UniversalLocation = UniversalLocation; - type BridgedNetwork = BridgedRelayNetworkLocation; - type BridgeMessagesPalletInstance = (); - - type MessageExportPrice = (); - type DestinationVersion = AlwaysLatest; - - type Lanes = TestLanes; - type LanesSupport = TestXcmBlobHauler; -} - -parameter_types! { - pub TestSenderAndLane: SenderAndLane = SenderAndLane { - location: MultiLocation::new(1, X1(Parachain(SIBLING_ASSET_HUB_ID))), - lane: TEST_LANE_ID, - }; - pub const BridgedDestination: InteriorMultiLocation = X1( - Parachain(BRIDGED_ASSET_HUB_ID) - ); - pub TestLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorMultiLocation))> = sp_std::vec![ - (TestSenderAndLane::get(), (BridgedRelayNetwork::get(), BridgedDestination::get())) - ]; -} - -pub struct TestXcmBlobHauler; -impl XcmBlobHauler for TestXcmBlobHauler { - type Runtime = TestRuntime; - type MessagesInstance = (); - type ToSourceChainSender = (); - type CongestedMessage = (); - type UncongestedMessage = (); -} - -pub struct ThisChain; - -impl Chain for ThisChain { - type BlockNumber = u64; - type Hash = H256; - type Hasher = BlakeTwo256; - type Header = SubstrateHeader; - type AccountId = AccountId; - type Balance = Balance; - type Nonce = u64; - type Signature = sp_runtime::MultiSignature; - - fn max_extrinsic_size() -> u32 { - u32::MAX - } - - fn max_extrinsic_weight() -> Weight { - Weight::MAX - } -} - -pub struct BridgedChain; -pub type BridgedHeaderHash = H256; -pub type BridgedChainHeader = SubstrateHeader; - -impl Chain for BridgedChain { - type BlockNumber = u64; - type Hash = BridgedHeaderHash; - type Hasher = BlakeTwo256; - type Header = BridgedChainHeader; - type AccountId = AccountId; - type Balance = Balance; - type Nonce = u64; - type Signature = sp_runtime::MultiSignature; - - fn max_extrinsic_size() -> u32 { - 4096 - } - - fn max_extrinsic_weight() -> Weight { - Weight::MAX - } -} - -/// Test message dispatcher. -pub struct TestMessageDispatch; - -impl TestMessageDispatch { - pub fn deactivate(lane: LaneId) { - frame_support::storage::unhashed::put(&(b"inactive", lane).encode()[..], &false); - } -} - -impl MessageDispatch for TestMessageDispatch { - type DispatchPayload = Vec; - type DispatchLevelResult = (); - - fn is_active() -> bool { - frame_support::storage::unhashed::take::(&(b"inactive").encode()[..]) != Some(false) - } - - fn dispatch_weight(_message: &mut DispatchMessage) -> Weight { - Weight::zero() - } - - fn dispatch( - _: DispatchMessage, - ) -> MessageDispatchResult { - MessageDispatchResult { unspent_weight: Weight::zero(), dispatch_level_result: () } - } -} - -pub struct WrappedThisChain; -impl UnderlyingChainProvider for WrappedThisChain { - type Chain = ThisChain; -} -impl ThisChainWithMessages for WrappedThisChain { - type RuntimeOrigin = RuntimeOrigin; -} - -pub struct WrappedBridgedChain; -impl UnderlyingChainProvider for WrappedBridgedChain { - type Chain = BridgedChain; -} -impl BridgedChainWithMessages for WrappedBridgedChain {} - -pub struct BridgedHeaderChain; -impl bp_header_chain::HeaderChain for BridgedHeaderChain { - fn finalized_header_state_root( - _hash: HashOf, - ) -> Option> { - unreachable!() - } -} - -/// Bridge that is deployed on `ThisChain` and allows sending/receiving messages to/from -/// `BridgedChain`. -#[derive(Debug, PartialEq, Eq)] -pub struct OnThisChainBridge; - -impl MessageBridge for OnThisChainBridge { - const BRIDGED_MESSAGES_PALLET_NAME: &'static str = ""; - - type ThisChain = WrappedThisChain; - type BridgedChain = WrappedBridgedChain; - type BridgedHeaderChain = BridgedHeaderChain; -} - -/// Run pallet test. -pub fn run_test(test: impl FnOnce() -> T) -> T { - sp_io::TestExternalities::new( - frame_system::GenesisConfig::::default().build_storage().unwrap(), - ) - .execute_with(test) -} diff --git a/bridges/primitives/chain-asset-hub-rococo/Cargo.toml b/bridges/primitives/chain-asset-hub-rococo/Cargo.toml index d5f724e581f..088510adcec 100644 --- a/bridges/primitives/chain-asset-hub-rococo/Cargo.toml +++ b/bridges/primitives/chain-asset-hub-rococo/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } @@ -20,7 +17,7 @@ frame-support = { path = "../../../substrate/frame/support", default-features = bp-xcm-bridge-hub-router = { path = "../xcm-bridge-hub-router", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-xcm-bridge-hub-router/std", "codec/std", diff --git a/bridges/primitives/chain-asset-hub-westend/Cargo.toml b/bridges/primitives/chain-asset-hub-westend/Cargo.toml index d309e50bfbf..c880f159ac1 100644 --- a/bridges/primitives/chain-asset-hub-westend/Cargo.toml +++ b/bridges/primitives/chain-asset-hub-westend/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } @@ -20,7 +17,7 @@ frame-support = { path = "../../../substrate/frame/support", default-features = bp-xcm-bridge-hub-router = { path = "../xcm-bridge-hub-router", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-xcm-bridge-hub-router/std", "codec/std", diff --git a/bridges/primitives/chain-bridge-hub-cumulus/Cargo.toml b/bridges/primitives/chain-bridge-hub-cumulus/Cargo.toml index 73aaa53269f..46697913674 100644 --- a/bridges/primitives/chain-bridge-hub-cumulus/Cargo.toml +++ b/bridges/primitives/chain-bridge-hub-cumulus/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] # Bridge Dependencies @@ -27,7 +24,7 @@ sp-std = { path = "../../../substrate/primitives/std", default-features = false polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-messages/std", "bp-polkadot-core/std", diff --git a/bridges/primitives/chain-bridge-hub-kusama/Cargo.toml b/bridges/primitives/chain-bridge-hub-kusama/Cargo.toml index ea09712ae30..c4cd229ef43 100644 --- a/bridges/primitives/chain-bridge-hub-kusama/Cargo.toml +++ b/bridges/primitives/chain-bridge-hub-kusama/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] # Bridge Dependencies @@ -24,7 +21,7 @@ sp-runtime = { path = "../../../substrate/primitives/runtime", default-features sp-std = { path = "../../../substrate/primitives/std", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-bridge-hub-cumulus/std", "bp-messages/std", diff --git a/bridges/primitives/chain-bridge-hub-polkadot/Cargo.toml b/bridges/primitives/chain-bridge-hub-polkadot/Cargo.toml index de208895fb4..4913d87e5fb 100644 --- a/bridges/primitives/chain-bridge-hub-polkadot/Cargo.toml +++ b/bridges/primitives/chain-bridge-hub-polkadot/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] # Bridge Dependencies @@ -25,7 +22,7 @@ sp-runtime = { path = "../../../substrate/primitives/runtime", default-features sp-std = { path = "../../../substrate/primitives/std", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-bridge-hub-cumulus/std", "bp-messages/std", diff --git a/bridges/primitives/chain-bridge-hub-rococo/Cargo.toml b/bridges/primitives/chain-bridge-hub-rococo/Cargo.toml index 281e1f74261..05b8163e9fc 100644 --- a/bridges/primitives/chain-bridge-hub-rococo/Cargo.toml +++ b/bridges/primitives/chain-bridge-hub-rococo/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] # Bridge Dependencies @@ -24,7 +21,7 @@ sp-runtime = { path = "../../../substrate/primitives/runtime", default-features sp-std = { path = "../../../substrate/primitives/std", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-bridge-hub-cumulus/std", "bp-messages/std", diff --git a/bridges/primitives/chain-bridge-hub-rococo/src/lib.rs b/bridges/primitives/chain-bridge-hub-rococo/src/lib.rs index 1fe44597c3d..59d293edf1c 100644 --- a/bridges/primitives/chain-bridge-hub-rococo/src/lib.rs +++ b/bridges/primitives/chain-bridge-hub-rococo/src/lib.rs @@ -76,8 +76,6 @@ pub const WITH_BRIDGE_HUB_ROCOCO_RELAYERS_PALLET_NAME: &str = "BridgeRelayers"; /// Pallet index of `BridgeWestendMessages: pallet_bridge_messages::`. pub const WITH_BRIDGE_ROCOCO_TO_WESTEND_MESSAGES_PALLET_INDEX: u8 = 51; -/// Pallet index of `BridgePolkadotBulletinMessages: pallet_bridge_messages::`. -pub const WITH_BRIDGE_ROCOCO_TO_BULLETIN_MESSAGES_PALLET_INDEX: u8 = 61; decl_bridge_finality_runtime_apis!(bridge_hub_rococo); decl_bridge_messages_runtime_apis!(bridge_hub_rococo); diff --git a/bridges/primitives/chain-bridge-hub-westend/Cargo.toml b/bridges/primitives/chain-bridge-hub-westend/Cargo.toml index beebfa8f1a0..22daf280868 100644 --- a/bridges/primitives/chain-bridge-hub-westend/Cargo.toml +++ b/bridges/primitives/chain-bridge-hub-westend/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] # Bridge Dependencies @@ -25,7 +22,7 @@ sp-runtime = { path = "../../../substrate/primitives/runtime", default-features sp-std = { path = "../../../substrate/primitives/std", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-bridge-hub-cumulus/std", "bp-messages/std", diff --git a/bridges/primitives/chain-kusama/Cargo.toml b/bridges/primitives/chain-kusama/Cargo.toml index 6ca4f051f1c..2d63c3f374f 100644 --- a/bridges/primitives/chain-kusama/Cargo.toml +++ b/bridges/primitives/chain-kusama/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] # Bridge Dependencies @@ -24,7 +21,7 @@ sp-api = { path = "../../../substrate/primitives/api", default-features = false sp-std = { path = "../../../substrate/primitives/std", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-header-chain/std", "bp-polkadot-core/std", diff --git a/bridges/primitives/chain-kusama/src/lib.rs b/bridges/primitives/chain-kusama/src/lib.rs index 781c2fbfaf3..e1e15807fc6 100644 --- a/bridges/primitives/chain-kusama/src/lib.rs +++ b/bridges/primitives/chain-kusama/src/lib.rs @@ -52,8 +52,8 @@ impl ChainWithGrandpa for Kusama { const MAX_AUTHORITIES_COUNT: u32 = MAX_AUTHORITIES_COUNT; const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY; - const MAX_MANDATORY_HEADER_SIZE: u32 = MAX_MANDATORY_HEADER_SIZE; - const AVERAGE_HEADER_SIZE: u32 = AVERAGE_HEADER_SIZE; + const MAX_HEADER_SIZE: u32 = MAX_HEADER_SIZE; + const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = AVERAGE_HEADER_SIZE_IN_JUSTIFICATION; } // The TransactionExtension used by Kusama. diff --git a/bridges/primitives/chain-polkadot-bulletin/Cargo.toml b/bridges/primitives/chain-polkadot-bulletin/Cargo.toml index 98633847462..1dd45ba95fd 100644 --- a/bridges/primitives/chain-polkadot-bulletin/Cargo.toml +++ b/bridges/primitives/chain-polkadot-bulletin/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } @@ -29,7 +26,7 @@ sp-runtime = { path = "../../../substrate/primitives/runtime", default-features sp-std = { path = "../../../substrate/primitives/std", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-header-chain/std", "bp-messages/std", diff --git a/bridges/primitives/chain-polkadot-bulletin/src/lib.rs b/bridges/primitives/chain-polkadot-bulletin/src/lib.rs index 3b849f3c9a9..0f633655b21 100644 --- a/bridges/primitives/chain-polkadot-bulletin/src/lib.rs +++ b/bridges/primitives/chain-polkadot-bulletin/src/lib.rs @@ -47,8 +47,8 @@ use sp_runtime::{ // This chain reuses most of Polkadot primitives. pub use bp_polkadot_core::{ AccountAddress, AccountId, Balance, Block, BlockNumber, Hash, Hasher, Header, Nonce, Signature, - SignedBlock, UncheckedExtrinsic, AVERAGE_HEADER_SIZE, EXTRA_STORAGE_PROOF_SIZE, - MAX_MANDATORY_HEADER_SIZE, REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY, + SignedBlock, UncheckedExtrinsic, AVERAGE_HEADER_SIZE_IN_JUSTIFICATION, + EXTRA_STORAGE_PROOF_SIZE, MAX_HEADER_SIZE, REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY, }; /// Maximal number of GRANDPA authorities at Polkadot Bulletin chain. @@ -208,8 +208,8 @@ impl ChainWithGrandpa for PolkadotBulletin { const MAX_AUTHORITIES_COUNT: u32 = MAX_AUTHORITIES_COUNT; const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY; - const MAX_MANDATORY_HEADER_SIZE: u32 = MAX_MANDATORY_HEADER_SIZE; - const AVERAGE_HEADER_SIZE: u32 = AVERAGE_HEADER_SIZE; + const MAX_HEADER_SIZE: u32 = MAX_HEADER_SIZE; + const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = AVERAGE_HEADER_SIZE_IN_JUSTIFICATION; } decl_bridge_finality_runtime_apis!(polkadot_bulletin, grandpa); diff --git a/bridges/primitives/chain-polkadot/Cargo.toml b/bridges/primitives/chain-polkadot/Cargo.toml index 361901b7ae0..539b10ef9c6 100644 --- a/bridges/primitives/chain-polkadot/Cargo.toml +++ b/bridges/primitives/chain-polkadot/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] # Bridge Dependencies @@ -24,7 +21,7 @@ sp-api = { path = "../../../substrate/primitives/api", default-features = false sp-std = { path = "../../../substrate/primitives/std", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-header-chain/std", "bp-polkadot-core/std", diff --git a/bridges/primitives/chain-polkadot/src/lib.rs b/bridges/primitives/chain-polkadot/src/lib.rs index fef7813be69..d66edb44ce9 100644 --- a/bridges/primitives/chain-polkadot/src/lib.rs +++ b/bridges/primitives/chain-polkadot/src/lib.rs @@ -52,8 +52,8 @@ impl ChainWithGrandpa for Polkadot { const MAX_AUTHORITIES_COUNT: u32 = MAX_AUTHORITIES_COUNT; const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY; - const MAX_MANDATORY_HEADER_SIZE: u32 = MAX_MANDATORY_HEADER_SIZE; - const AVERAGE_HEADER_SIZE: u32 = AVERAGE_HEADER_SIZE; + const MAX_HEADER_SIZE: u32 = MAX_HEADER_SIZE; + const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = AVERAGE_HEADER_SIZE_IN_JUSTIFICATION; } /// The TransactionExtension used by Polkadot. diff --git a/bridges/primitives/chain-rococo/Cargo.toml b/bridges/primitives/chain-rococo/Cargo.toml index d59a00cfd14..469be1dbd33 100644 --- a/bridges/primitives/chain-rococo/Cargo.toml +++ b/bridges/primitives/chain-rococo/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] # Bridge Dependencies @@ -24,7 +21,7 @@ sp-api = { path = "../../../substrate/primitives/api", default-features = false sp-std = { path = "../../../substrate/primitives/std", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-header-chain/std", "bp-polkadot-core/std", diff --git a/bridges/primitives/chain-rococo/src/lib.rs b/bridges/primitives/chain-rococo/src/lib.rs index dc1aa59a3ae..2ec0e558077 100644 --- a/bridges/primitives/chain-rococo/src/lib.rs +++ b/bridges/primitives/chain-rococo/src/lib.rs @@ -52,8 +52,8 @@ impl ChainWithGrandpa for Rococo { const MAX_AUTHORITIES_COUNT: u32 = MAX_AUTHORITIES_COUNT; const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY; - const MAX_MANDATORY_HEADER_SIZE: u32 = MAX_MANDATORY_HEADER_SIZE; - const AVERAGE_HEADER_SIZE: u32 = AVERAGE_HEADER_SIZE; + const MAX_HEADER_SIZE: u32 = MAX_HEADER_SIZE; + const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = AVERAGE_HEADER_SIZE_IN_JUSTIFICATION; } parameter_types! { diff --git a/bridges/primitives/chain-westend/Cargo.toml b/bridges/primitives/chain-westend/Cargo.toml index 6b6d2748aff..797621bbce2 100644 --- a/bridges/primitives/chain-westend/Cargo.toml +++ b/bridges/primitives/chain-westend/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] # Bridge Dependencies @@ -24,7 +21,7 @@ sp-api = { path = "../../../substrate/primitives/api", default-features = false sp-std = { path = "../../../substrate/primitives/std", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-header-chain/std", "bp-polkadot-core/std", diff --git a/bridges/primitives/chain-westend/src/lib.rs b/bridges/primitives/chain-westend/src/lib.rs index 4e505a514ae..f4413a1631b 100644 --- a/bridges/primitives/chain-westend/src/lib.rs +++ b/bridges/primitives/chain-westend/src/lib.rs @@ -52,8 +52,8 @@ impl ChainWithGrandpa for Westend { const MAX_AUTHORITIES_COUNT: u32 = MAX_AUTHORITIES_COUNT; const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY; - const MAX_MANDATORY_HEADER_SIZE: u32 = MAX_MANDATORY_HEADER_SIZE; - const AVERAGE_HEADER_SIZE: u32 = AVERAGE_HEADER_SIZE; + const MAX_HEADER_SIZE: u32 = MAX_HEADER_SIZE; + const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = AVERAGE_HEADER_SIZE_IN_JUSTIFICATION; } parameter_types! { diff --git a/bridges/primitives/header-chain/Cargo.toml b/bridges/primitives/header-chain/Cargo.toml index 7338996d69f..19b2819bddc 100644 --- a/bridges/primitives/header-chain/Cargo.toml +++ b/bridges/primitives/header-chain/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false } finality-grandpa = { version = "0.16.2", default-features = false } @@ -33,7 +30,7 @@ hex = "0.4" hex-literal = "0.4" [features] -default = ["std"] +default = [ "std" ] std = [ "bp-runtime/std", "codec/std", diff --git a/bridges/primitives/header-chain/src/justification/mod.rs b/bridges/primitives/header-chain/src/justification/mod.rs index b32d8bdb5f1..72a5f68918d 100644 --- a/bridges/primitives/header-chain/src/justification/mod.rs +++ b/bridges/primitives/header-chain/src/justification/mod.rs @@ -82,8 +82,8 @@ impl GrandpaJustification { .saturating_add(BlockNumberOf::::max_encoded_len().saturated_into()) .saturating_add(HashOf::::max_encoded_len().saturated_into()); - let max_expected_votes_ancestries_size = - C::REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY.saturating_mul(C::AVERAGE_HEADER_SIZE); + let max_expected_votes_ancestries_size = C::REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY + .saturating_mul(C::AVERAGE_HEADER_SIZE_IN_JUSTIFICATION); // justification is round number (u64=8b), a signed GRANDPA commit and the // `votes_ancestries` vector diff --git a/bridges/primitives/header-chain/src/lib.rs b/bridges/primitives/header-chain/src/lib.rs index 1459b1c1994..d2c7ec0759e 100644 --- a/bridges/primitives/header-chain/src/lib.rs +++ b/bridges/primitives/header-chain/src/lib.rs @@ -266,28 +266,23 @@ pub trait ChainWithGrandpa: Chain { /// to submitter. const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32; - /// Maximal size of the mandatory chain header. Mandatory header is the header that enacts new - /// GRANDPA authorities set (so it has large digest inside). + /// Maximal size of the chain header. The header may be the header that enacts new GRANDPA + /// authorities set (so it has large digest inside). /// /// This isn't a strict limit. The relay may submit larger headers and the pallet will accept /// the call. The limit is only used to compute maximal refund amount and doing calls which /// exceed the limit, may be costly to submitter. - const MAX_MANDATORY_HEADER_SIZE: u32; + const MAX_HEADER_SIZE: u32; - /// Average size of the chain header. We don't expect to see there headers that change GRANDPA - /// authorities set (GRANDPA will probably be able to finalize at least one additional header - /// per session on non test chains), so this is average size of headers that aren't changing the - /// set. + /// Average size of the chain header from justification ancestry. We don't expect to see there + /// headers that change GRANDPA authorities set (GRANDPA will probably be able to finalize at + /// least one additional header per session on non test chains), so this is average size of + /// headers that aren't changing the set. /// - /// This isn't a strict limit. The relay may submit justifications with larger headers and the - /// pallet will accept the call. However, if the total size of all `submit_finality_proof` - /// arguments exceeds the maximal size, computed using this average size, relayer will only get - /// partial refund. - /// - /// We expect some headers on production chains that are above this size. But they are rare and - /// if rellayer cares about its profitability, we expect it'll select other headers for - /// submission. - const AVERAGE_HEADER_SIZE: u32; + /// This isn't a strict limit. The relay may submit justifications with larger headers in its + /// ancestry and the pallet will accept the call. The limit is only used to compute maximal + /// refund amount and doing calls which exceed the limit, may be costly to submitter. + const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32; } impl ChainWithGrandpa for T @@ -300,67 +295,7 @@ where const MAX_AUTHORITIES_COUNT: u32 = ::MAX_AUTHORITIES_COUNT; const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = ::REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY; - const MAX_MANDATORY_HEADER_SIZE: u32 = - ::MAX_MANDATORY_HEADER_SIZE; - const AVERAGE_HEADER_SIZE: u32 = ::AVERAGE_HEADER_SIZE; -} - -/// Returns maximal expected size of `submit_finality_proof` call arguments. -pub fn max_expected_submit_finality_proof_arguments_size( - is_mandatory_finality_target: bool, - precommits: u32, -) -> u32 { - let max_expected_justification_size = - GrandpaJustification::>::max_reasonable_size::(precommits); - - // call arguments are header and justification - let max_expected_finality_target_size = if is_mandatory_finality_target { - C::MAX_MANDATORY_HEADER_SIZE - } else { - C::AVERAGE_HEADER_SIZE - }; - max_expected_finality_target_size.saturating_add(max_expected_justification_size) -} - -#[cfg(test)] -mod tests { - use super::*; - use frame_support::weights::Weight; - use sp_runtime::{testing::H256, traits::BlakeTwo256, MultiSignature}; - - struct TestChain; - - impl Chain for TestChain { - type BlockNumber = u32; - type Hash = H256; - type Hasher = BlakeTwo256; - type Header = sp_runtime::generic::Header; - type AccountId = u64; - type Balance = u64; - type Nonce = u64; - type Signature = MultiSignature; - - fn max_extrinsic_size() -> u32 { - 0 - } - fn max_extrinsic_weight() -> Weight { - Weight::zero() - } - } - - impl ChainWithGrandpa for TestChain { - const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = "Test"; - const MAX_AUTHORITIES_COUNT: u32 = 128; - const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = 2; - const MAX_MANDATORY_HEADER_SIZE: u32 = 100_000; - const AVERAGE_HEADER_SIZE: u32 = 1_024; - } - - #[test] - fn max_expected_submit_finality_proof_arguments_size_respects_mandatory_argument() { - assert!( - max_expected_submit_finality_proof_arguments_size::(true, 100) > - max_expected_submit_finality_proof_arguments_size::(false, 100), - ); - } + const MAX_HEADER_SIZE: u32 = ::MAX_HEADER_SIZE; + const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = + ::AVERAGE_HEADER_SIZE_IN_JUSTIFICATION; } diff --git a/bridges/primitives/messages/Cargo.toml b/bridges/primitives/messages/Cargo.toml index 6333000a71a..7a61643a0bc 100644 --- a/bridges/primitives/messages/Cargo.toml +++ b/bridges/primitives/messages/Cargo.toml @@ -6,11 +6,8 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["bit-vec", "derive"] } +codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive", "bit-vec"] } scale-info = { version = "2.10.0", default-features = false, features = ["bit-vec", "derive"] } serde = { version = "1.0", default-features = false, features = ["alloc", "derive"] } @@ -30,7 +27,7 @@ hex = "0.4" hex-literal = "0.4" [features] -default = ["std"] +default = [ "std" ] std = [ "bp-header-chain/std", "bp-runtime/std", diff --git a/bridges/primitives/parachains/Cargo.toml b/bridges/primitives/parachains/Cargo.toml index 99b447f6c0a..11e9336f66a 100644 --- a/bridges/primitives/parachains/Cargo.toml +++ b/bridges/primitives/parachains/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive"] } impl-trait-for-tuples = "0.2" @@ -28,7 +25,7 @@ sp-runtime = { path = "../../../substrate/primitives/runtime", default-features sp-std = { path = "../../../substrate/primitives/std", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-header-chain/std", "bp-polkadot-core/std", diff --git a/bridges/primitives/polkadot-core/Cargo.toml b/bridges/primitives/polkadot-core/Cargo.toml index 80382b3289f..e2bd4c29522 100644 --- a/bridges/primitives/polkadot-core/Cargo.toml +++ b/bridges/primitives/polkadot-core/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive"] } parity-util-mem = { version = "0.12.0", optional = true } @@ -32,7 +29,7 @@ sp-std = { path = "../../../substrate/primitives/std", default-features = false hex = "0.4" [features] -default = ["std"] +default = [ "std" ] std = [ "bp-messages/std", "bp-runtime/std", diff --git a/bridges/primitives/polkadot-core/src/lib.rs b/bridges/primitives/polkadot-core/src/lib.rs index 8af0afc314e..0d593445ce7 100644 --- a/bridges/primitives/polkadot-core/src/lib.rs +++ b/bridges/primitives/polkadot-core/src/lib.rs @@ -64,28 +64,30 @@ pub const MAX_AUTHORITIES_COUNT: u32 = 1_256; /// /// See [`bp-header-chain::ChainWithGrandpa`] for more details. /// -/// This value comes from recent (December, 2023) Kusama and Polkadot headers. There are no +/// This value comes from recent (February, 2023) Kusama and Polkadot headers. There are no /// justifications with any additional headers in votes ancestry, so reasonable headers may /// be set to zero. But we assume that there may be small GRANDPA lags, so we're leaving some /// reserve here. pub const REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY: u32 = 2; -/// Average header size in `votes_ancestries` field of justification on Polkadot-like +/// Approximate average header size in `votes_ancestries` field of justification on Polkadot-like /// chains. /// /// See [`bp-header-chain::ChainWithGrandpa`] for more details. /// -/// This value comes from recent (December, 2023) Kusama headers. Most of headers are `327` bytes -/// there, but let's have some reserve and make it 1024. -pub const AVERAGE_HEADER_SIZE: u32 = 1024; +/// This value comes from recent (February, 2023) Kusama headers. Average is `336` there, but some +/// non-mandatory headers has size `40kb` (they contain the BABE epoch descriptor with all +/// authorities - just like our mandatory header). Since we assume `2` headers in justification +/// votes ancestry, let's set average header to `40kb / 2`. +pub const AVERAGE_HEADER_SIZE_IN_JUSTIFICATION: u32 = 20 * 1024; /// Approximate maximal header size on Polkadot-like chains. /// /// See [`bp-header-chain::ChainWithGrandpa`] for more details. /// -/// This value comes from recent (December, 2023) Kusama headers. Maximal header is a mandatory -/// header. In its SCALE-encoded form it is `113407` bytes. Let's have some reserve here. -pub const MAX_MANDATORY_HEADER_SIZE: u32 = 120 * 1024; +/// This value comes from recent (February, 2023) Kusama headers. Maximal header is a mandatory +/// header. In its SCALE-encoded form it is `80348` bytes. Let's have some reserve here. +pub const MAX_HEADER_SIZE: u32 = 90_000; /// Number of extra bytes (excluding size of storage value itself) of storage proof, built at /// Polkadot-like chain. This mostly depends on number of entries in the storage trie. diff --git a/bridges/primitives/relayers/Cargo.toml b/bridges/primitives/relayers/Cargo.toml index 563d27c91c9..ffed2debbe6 100644 --- a/bridges/primitives/relayers/Cargo.toml +++ b/bridges/primitives/relayers/Cargo.toml @@ -6,11 +6,8 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["bit-vec", "derive"] } +codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive", "bit-vec"] } scale-info = { version = "2.10.0", default-features = false, features = ["bit-vec", "derive"] } # Bridge Dependencies @@ -29,7 +26,7 @@ hex = "0.4" hex-literal = "0.4" [features] -default = ["std"] +default = [ "std" ] std = [ "bp-messages/std", "bp-runtime/std", diff --git a/bridges/primitives/runtime/Cargo.toml b/bridges/primitives/runtime/Cargo.toml index 779030b5278..48f6722c982 100644 --- a/bridges/primitives/runtime/Cargo.toml +++ b/bridges/primitives/runtime/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false } hash-db = { version = "0.16.0", default-features = false } @@ -34,7 +31,7 @@ trie-db = { version = "0.28.0", default-features = false } hex-literal = "0.4" [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/bridges/primitives/test-utils/Cargo.toml b/bridges/primitives/test-utils/Cargo.toml index 3ccec9d9033..9836c1877f0 100644 --- a/bridges/primitives/test-utils/Cargo.toml +++ b/bridges/primitives/test-utils/Cargo.toml @@ -6,16 +6,13 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] -bp-header-chain = { path = "../header-chain", default-features = false } +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-polkadot-core = { path = "../polkadot-core", default-features = false } bp-runtime = { path = "../runtime", default-features = false } codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false } -ed25519-dalek = { version = "2.1", default-features = false } +ed25519-dalek = { version = "2.0", 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 } @@ -25,7 +22,7 @@ sp-std = { path = "../../../substrate/primitives/std", default-features = false sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-header-chain/std", "bp-parachains/std", diff --git a/bridges/primitives/xcm-bridge-hub-router/Cargo.toml b/bridges/primitives/xcm-bridge-hub-router/Cargo.toml index fa537bda960..fb079b48e42 100644 --- a/bridges/primitives/xcm-bridge-hub-router/Cargo.toml +++ b/bridges/primitives/xcm-bridge-hub-router/Cargo.toml @@ -6,11 +6,8 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["bit-vec", "derive"] } +codec = { package = "parity-scale-codec", version = "3.1.5", default-features = false, features = ["derive", "bit-vec"] } scale-info = { version = "2.10.0", default-features = false, features = ["bit-vec", "derive"] } # Substrate Dependencies @@ -18,5 +15,5 @@ sp-runtime = { path = "../../../substrate/primitives/runtime", default-features sp-core = { path = "../../../substrate/primitives/core", default-features = false } [features] -default = ["std"] -std = ["codec/std", "scale-info/std", "sp-core/std", "sp-runtime/std"] +default = [ "std" ] +std = [ "codec/std", "scale-info/std", "sp-core/std", "sp-runtime/std" ] diff --git a/bridges/primitives/xcm-bridge-hub/Cargo.toml b/bridges/primitives/xcm-bridge-hub/Cargo.toml deleted file mode 100644 index f9f44fd0f8d..00000000000 --- a/bridges/primitives/xcm-bridge-hub/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "bp-xcm-bridge-hub" -description = "Primitives of the xcm-bridge-hub pallet." -version = "0.1.0" -authors.workspace = true -edition.workspace = true -license = "GPL-3.0-or-later WITH Classpath-exception-2.0" - -[lints] -workspace = true - -[dependencies] - -# Substrate Dependencies -sp-std = { path = "../../../substrate/primitives/std", default-features = false } - -[features] -default = ["std"] -std = ["sp-std/std"] diff --git a/bridges/primitives/xcm-bridge-hub/src/lib.rs b/bridges/primitives/xcm-bridge-hub/src/lib.rs deleted file mode 100644 index 9745011c902..00000000000 --- a/bridges/primitives/xcm-bridge-hub/src/lib.rs +++ /dev/null @@ -1,24 +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 . - -//! Primitives of the xcm-bridge-hub pallet. - -#![warn(missing_docs)] -#![cfg_attr(not(feature = "std"), no_std)] - -/// Encoded XCM blob. We expect the bridge messages pallet to use this blob type for both inbound -/// and outbound payloads. -pub type XcmAsPlainPayload = sp_std::vec::Vec; diff --git a/bridges/zombienet/helpers/native-assets-balance-increased.js b/bridges/zombienet/helpers/native-assets-balance-increased.js deleted file mode 100644 index 9ee1a769e9f..00000000000 --- a/bridges/zombienet/helpers/native-assets-balance-increased.js +++ /dev/null @@ -1,20 +0,0 @@ -async function run(nodeName, networkInfo, args) { - const {wsUri, userDefinedTypes} = networkInfo.nodesByName[nodeName]; - const api = await zombie.connect(wsUri, userDefinedTypes); - - const accountAddress = args[0]; - const initialAccountData = await api.query.system.account(accountAddress); - const initialAccountBalance = initialAccountData.data['free']; - while (true) { - const accountData = await api.query.system.account(accountAddress); - const accountBalance = accountData.data['free']; - if (accountBalance > initialAccountBalance) { - return accountBalance; - } - - // else sleep and retry - await new Promise((resolve) => setTimeout(resolve, 12000)); - } -} - -module.exports = { run } diff --git a/bridges/zombienet/run-tests.sh b/bridges/zombienet/run-tests.sh index 4f80e06650e..22fefd09360 100755 --- a/bridges/zombienet/run-tests.sh +++ b/bridges/zombienet/run-tests.sh @@ -14,9 +14,6 @@ export POLKADOT_PARACHAIN_BINARY_PATH_FOR_ASSET_HUB_ROCOCO=$POLKADOT_PARACHAIN_B export POLKADOT_PARACHAIN_BINARY_PATH_FOR_ASSET_HUB_WESTEND=$POLKADOT_PARACHAIN_BINARY_PATH export ZOMBIENET_BINARY_PATH=~/local_bridge_testing/bin/zombienet-linux -# check if `wait` supports -p flag -if [ `printf "$BASH_VERSION\n5.1" | sort -V | head -n 1` = "5.1" ]; then IS_BASH_5_1=1; else IS_BASH_5_1=0; fi - # bridge configuration export LANE_ID="00000002" @@ -69,19 +66,12 @@ do # wait until all tests are completed relay_exited=0 for n in `seq 1 $TEST_COPROCS_COUNT`; do - if [ "$IS_BASH_5_1" -eq 1 ]; then - wait -n -p COPROC_PID - exit_code=$? - coproc_name=${TEST_COPROCS[$COPROC_PID, 0]} - coproc_log=${TEST_COPROCS[$COPROC_PID, 1]} - coproc_stdout=$(cat $coproc_log) - relay_exited=$(expr "${coproc_name}" == "relay") - else - wait -n - exit_code=$? - coproc_name="" - coproc_stdout="" - fi + wait -n -p COPROC_PID + exit_code=$? + coproc_name=${TEST_COPROCS[$COPROC_PID, 0]} + coproc_log=${TEST_COPROCS[$COPROC_PID, 1]} + coproc_stdout=$(cat $coproc_log) + relay_exited=$(expr "${coproc_name}" == "relay") echo "Process $coproc_name has finished with exit code: $exit_code" # if exit code is not zero, exit diff --git a/bridges/zombienet/tests/0001-asset-transfer-works-rococo-to-westend.zndsl b/bridges/zombienet/tests/0001-asset-transfer-works-rococo-to-westend.zndsl index a61f1e039f4..f68d658cdac 100644 --- a/bridges/zombienet/tests/0001-asset-transfer-works-rococo-to-westend.zndsl +++ b/bridges/zombienet/tests/0001-asset-transfer-works-rococo-to-westend.zndsl @@ -1,8 +1,8 @@ -Description: User is able to transfer ROC from Rococo Asset Hub to Westend Asset Hub and back +Description: User is able to transfer ROC from Rococo Asset Hub to Westend Asset Hub Network: ../../../cumulus/zombienet/bridge-hubs/bridge_hub_westend_local_network.toml Creds: config -# step 1: initialize Westend AH +# step 1: initialize Westend asset hub asset-hub-westend-collator1: run ../scripts/invoke-script.sh with "init-asset-hub-westend-local" within 240 seconds asset-hub-westend-collator1: js-script ../helpers/wait-hrmp-channel-opened.js with "1002" within 400 seconds @@ -12,23 +12,15 @@ bridge-hub-westend-collator1: run ../scripts/invoke-script.sh with "init-bridge- # step 3: relay is started elsewhere - let's wait until with-Rococo GRANPDA pallet is initialized at Westend bridge-hub-westend-collator1: js-script ../helpers/best-finalized-header-at-bridged-chain.js with "Rococo,0" within 400 seconds -# step 4: send WND to //Alice on Rococo AH -# (that's a required part of a sibling 0001-asset-transfer-works-westend-to-rococo.zndsl test) +# step 2: send WOC to Rococo asset-hub-westend-collator1: run ../scripts/invoke-script.sh with "reserve-transfer-assets-from-asset-hub-westend-local" within 60 seconds -# step 5: elsewhere Rococo has sent ROC to //Alice - let's wait for it +# step 3: elsewhere Rococo has sent ROC to //Alice - let's wait for it asset-hub-westend-collator1: js-script ../helpers/wrapped-assets-balance.js with "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY,0,Rococo" within 600 seconds -# step 6: check that the relayer //Charlie is rewarded by both our AH and target AH +# step 4: check that the relayer //Charlie is rewarded by both our AH and target AH bridge-hub-westend-collator1: js-script ../helpers/relayer-rewards.js with "5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y,0x00000002,0x6268726f,BridgedChain,0" within 300 seconds bridge-hub-westend-collator1: js-script ../helpers/relayer-rewards.js with "5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y,0x00000002,0x6268726F,ThisChain,0" within 300 seconds -# step 7: send wROC back to Alice at Rococo AH -asset-hub-westend-collator1: run ../scripts/invoke-script.sh with "withdraw-reserve-assets-from-asset-hub-westend-local" within 60 seconds - -# step 8: elsewhere Rococo has sent wWND to //Alice - let's wait for it -# (we wait until //Alice account increases here - there are no other transactionc that may increase it) -asset-hub-westend-collator1: js-script ../helpers/native-assets-balance-increased.js with "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" within 600 seconds - # wait until other network test has completed OR exit with an error too asset-hub-westend-collator1: run ../scripts/sync-exit.sh within 600 seconds diff --git a/bridges/zombienet/tests/0001-asset-transfer-works-westend-to-rococo.zndsl b/bridges/zombienet/tests/0001-asset-transfer-works-westend-to-rococo.zndsl index 2da5b7a772a..c862fa6d176 100644 --- a/bridges/zombienet/tests/0001-asset-transfer-works-westend-to-rococo.zndsl +++ b/bridges/zombienet/tests/0001-asset-transfer-works-westend-to-rococo.zndsl @@ -1,8 +1,8 @@ -Description: User is able to transfer WND from Westend Asset Hub to Rococo Asset Hub and back +Description: User is able to transfer WOC from Westend Asset Hub to Rococo Asset Hub Network: ../../../cumulus/zombienet/bridge-hubs/bridge_hub_rococo_local_network.toml Creds: config -# step 1: initialize Rococo AH +# step 1: initialize Rococo asset hub asset-hub-rococo-collator1: run ../scripts/invoke-script.sh with "init-asset-hub-rococo-local" within 240 seconds asset-hub-rococo-collator1: js-script ../helpers/wait-hrmp-channel-opened.js with "1013" within 400 seconds @@ -12,23 +12,15 @@ bridge-hub-rococo-collator1: run ../scripts/invoke-script.sh with "init-bridge-h # step 3: relay is started elsewhere - let's wait until with-Westend GRANPDA pallet is initialized at Rococo bridge-hub-rococo-collator1: js-script ../helpers/best-finalized-header-at-bridged-chain.js with "Westend,0" within 400 seconds -# step 4: send ROC to //Alice on Westend AH -# (that's a required part of a sibling 0001-asset-transfer-works-rococo-to-westend.zndsl test) +# step 4: send ROC to Westend asset-hub-rococo-collator1: run ../scripts/invoke-script.sh with "reserve-transfer-assets-from-asset-hub-rococo-local" within 60 seconds -# step 5: elsewhere Westend has sent WND to //Alice - let's wait for it +# step 5: elsewhere Westend has sent WOC to //Alice - let's wait for it asset-hub-rococo-collator1: js-script ../helpers/wrapped-assets-balance.js with "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY,0,Westend" within 600 seconds # step 6: check that the relayer //Charlie is rewarded by both our AH and target AH bridge-hub-rococo-collator1: js-script ../helpers/relayer-rewards.js with "5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y,0x00000002,0x62687764,BridgedChain,0" within 300 seconds bridge-hub-rococo-collator1: js-script ../helpers/relayer-rewards.js with "5FLSigC9HGRKVhB9FiEo4Y3koPsNmBmLJbpXg2mp1hXcS59Y,0x00000002,0x62687764,ThisChain,0" within 300 seconds -# step 7: send wWND back to Alice at Westend AH -asset-hub-rococo-collator1: run ../scripts/invoke-script.sh with "withdraw-reserve-assets-from-asset-hub-rococo-local" within 60 seconds - -# step 8: elsewhere Westend has sent wROC to //Alice - let's wait for it -# (we wait until //Alice account increases here - there are no other transactionc that may increase it) -asset-hub-rococo-collator1: js-script ../helpers/native-assets-balance-increased.js with "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" within 600 seconds - # wait until other network test has completed OR exit with an error too asset-hub-rococo-collator1: run ../scripts/sync-exit.sh within 600 seconds diff --git a/cumulus/README.md b/cumulus/README.md index 7e145ad7b4a..19f9f3f113d 100644 --- a/cumulus/README.md +++ b/cumulus/README.md @@ -4,7 +4,7 @@ This repository contains both the Cumulus SDK and also specific chains implemented on top of this SDK. -If you only want to run a **Polkadot Parachain Node**, check out our [container section](./docs/contributor/container.md). +If you only want to run a **Polkadot Parachain Node**, check out our [container section](./docs/container.md). ## Cumulus SDK @@ -34,7 +34,7 @@ A Polkadot [collator](https://wiki.polkadot.network/docs/en/learn-collator) for `polkadot-parachain` binary (previously called `polkadot-collator`). You may run `polkadot-parachain` locally after building it or using one of the container option described -[here](./docs/contributor/container.md). +[here](./docs/container.md). ### Relay Chain Interaction To operate a parachain node, a connection to the corresponding relay chain is necessary. This can be achieved in one of @@ -142,8 +142,8 @@ zombienet --provider native spawn ./zombienet/examples/small_network.toml # Clone git clone https://github.com/paritytech/polkadot-sdk -# Compile Polkadot's required binaries -cargo build --release -p polkadot +# Compile Polkadot +cargo build --release --bin polkadot # Generate a raw chain spec ./target/release/polkadot build-spec --chain rococo-local --disable-default-bootnode --raw > rococo-local-cfde.json @@ -158,8 +158,11 @@ cargo build --release -p polkadot #### Launch the Parachain ```bash +# Clone +git clone https://github.com/paritytech/polkadot-sdk + # Compile -cargo build --release -p polkadot-parachain-bin +cargo build --release --bin polkadot-parachain # Export genesis state ./target/release/polkadot-parachain export-genesis-state > genesis-state @@ -169,15 +172,15 @@ cargo build --release -p polkadot-parachain-bin # Collator1 ./target/release/polkadot-parachain --collator --alice --force-authoring \ - --tmp --port 40335 --rpc-port 9946 -- --chain rococo-local-cfde.json --port 30335 + --tmp --port 40335 --rpc-port 9946 -- --chain ../polkadot/rococo-local-cfde.json --port 30335 # Collator2 ./target/release/polkadot-parachain --collator --bob --force-authoring \ - --tmp --port 40336 --rpc-port 9947 -- --chain rococo-local-cfde.json --port 30336 + --tmp --port 40336 --rpc-port 9947 -- --chain ../polkadot/rococo-local-cfde.json --port 30336 # Parachain Full Node 1 ./target/release/polkadot-parachain --tmp --port 40337 --rpc-port 9948 -- \ - --chain rococo-local-cfde.json --port 30337 + --chain ../polkadot/rococo-local-cfde.json --port 30337 ``` #### Register the parachain @@ -242,7 +245,7 @@ Once the executable is built, launch collators for each parachain (repeat once e ./target/release/polkadot-parachain --chain $CHAIN --validator ``` -You can also build [using a container](./docs/contributor/container.md). +You can also build [using a container](./docs/container.md). ### Parachains diff --git a/cumulus/client/cli/Cargo.toml b/cumulus/client/cli/Cargo.toml index e57e7a44a56..0f942feb595 100644 --- a/cumulus/client/cli/Cargo.toml +++ b/cumulus/client/cli/Cargo.toml @@ -6,11 +6,8 @@ edition.workspace = true description = "Parachain node CLI utilities." license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.0.0" } url = "2.4.0" @@ -21,4 +18,3 @@ 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" } diff --git a/cumulus/client/cli/src/lib.rs b/cumulus/client/cli/src/lib.rs index 1cebecb0043..7e78afe6efb 100644 --- a/cumulus/client/cli/src/lib.rs +++ b/cumulus/client/cli/src/lib.rs @@ -23,18 +23,20 @@ use std::{ io::{self, Write}, net::SocketAddr, path::PathBuf, - sync::Arc, }; use codec::Encode; use sc_chain_spec::ChainSpec; -use sc_client_api::HeaderBackend; +use sc_client_api::ExecutorProvider; use sc_service::{ config::{PrometheusConfig, TelemetryEndpoints}, BasePath, TransactionPoolOptions, }; use sp_core::hexdisplay::HexDisplay; -use sp_runtime::traits::{Block as BlockT, Zero}; +use sp_runtime::{ + traits::{Block as BlockT, Hash as HashT, Header as HeaderT, Zero}, + StateVersion, +}; use url::Url; /// The `purge-chain` command used to remove the whole chain: the parachain and the relay chain. @@ -127,9 +129,9 @@ impl sc_cli::CliConfiguration for PurgeChainCmd { } } -/// Command for exporting the genesis head data of the parachain +/// Command for exporting the genesis state of the parachain #[derive(Debug, clap::Parser)] -pub struct ExportGenesisHeadCommand { +pub struct ExportGenesisStateCommand { /// Output file name or stdout if unspecified. #[arg()] pub output: Option, @@ -143,29 +145,24 @@ pub struct ExportGenesisHeadCommand { pub shared_params: sc_cli::SharedParams, } -impl ExportGenesisHeadCommand { - /// Run the export-genesis-head command - pub fn run(&self, client: Arc) -> sc_cli::Result<()> - where - B: BlockT, - C: HeaderBackend + 'static, - { - let genesis_hash = client.hash(Zero::zero())?.ok_or(sc_cli::Error::Client( - sp_blockchain::Error::Backend( - "Failed to lookup genesis block hash when exporting genesis head data.".into(), - ), - ))?; - let genesis_header = client.header(genesis_hash)?.ok_or(sc_cli::Error::Client( - sp_blockchain::Error::Backend( - "Failed to lookup genesis header by hash when exporting genesis head data.".into(), - ), - ))?; - - let raw_header = genesis_header.encode(); +impl ExportGenesisStateCommand { + /// Run the export-genesis-state command + pub fn run( + &self, + chain_spec: &dyn ChainSpec, + client: &impl ExecutorProvider, + ) -> sc_cli::Result<()> { + let state_version = sc_chain_spec::resolve_state_version_from_wasm( + &chain_spec.build_storage()?, + client.executor(), + )?; + + let block: Block = generate_genesis_block(chain_spec, state_version)?; + let raw_header = block.header().encode(); let output_buf = if self.raw { raw_header } else { - format!("0x{:?}", HexDisplay::from(&genesis_header.encode())).into_bytes() + format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes() }; if let Some(output) = &self.output { @@ -178,7 +175,43 @@ impl ExportGenesisHeadCommand { } } -impl sc_cli::CliConfiguration for ExportGenesisHeadCommand { +/// Generate the genesis block from a given ChainSpec. +pub fn generate_genesis_block( + chain_spec: &dyn ChainSpec, + genesis_state_version: StateVersion, +) -> Result { + let storage = chain_spec.build_storage()?; + + let child_roots = storage.children_default.iter().map(|(sk, child_content)| { + let state_root = <<::Header as HeaderT>::Hashing as HashT>::trie_root( + child_content.data.clone().into_iter().collect(), + genesis_state_version, + ); + (sk.clone(), state_root.encode()) + }); + let state_root = <<::Header as HeaderT>::Hashing as HashT>::trie_root( + storage.top.clone().into_iter().chain(child_roots).collect(), + genesis_state_version, + ); + + let extrinsics_root = <<::Header as HeaderT>::Hashing as HashT>::trie_root( + Vec::new(), + genesis_state_version, + ); + + Ok(Block::new( + <::Header as HeaderT>::new( + Zero::zero(), + extrinsics_root, + state_root, + Default::default(), + Default::default(), + ), + Default::default(), + )) +} + +impl sc_cli::CliConfiguration for ExportGenesisStateCommand { fn shared_params(&self) -> &sc_cli::SharedParams { &self.shared_params } diff --git a/cumulus/client/collator/Cargo.toml b/cumulus/client/collator/Cargo.toml index 7392934f4c9..ad9f01ed083 100644 --- a/cumulus/client/collator/Cargo.toml +++ b/cumulus/client/collator/Cargo.toml @@ -6,12 +6,9 @@ edition.workspace = true description = "Common node-side functionality and glue code to collate parachain blocks." license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] parking_lot = "0.12.1" -codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", features = [ "derive" ] } futures = "0.3.21" tracing = "0.1.25" diff --git a/cumulus/client/consensus/aura/Cargo.toml b/cumulus/client/consensus/aura/Cargo.toml index cd77504a2a2..f440270c982 100644 --- a/cumulus/client/consensus/aura/Cargo.toml +++ b/cumulus/client/consensus/aura/Cargo.toml @@ -6,12 +6,9 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] async-trait = "0.1.73" -codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", features = [ "derive" ] } futures = "0.3.28" tracing = "0.1.37" schnellru = "0.2.1" diff --git a/cumulus/client/consensus/common/Cargo.toml b/cumulus/client/consensus/common/Cargo.toml index 770e5c01e8b..9dfd14b1cf5 100644 --- a/cumulus/client/consensus/common/Cargo.toml +++ b/cumulus/client/consensus/common/Cargo.toml @@ -6,12 +6,9 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] async-trait = "0.1.73" -codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", features = [ "derive" ] } dyn-clone = "1.0.12" futures = "0.3.28" log = "0.4.20" diff --git a/cumulus/client/consensus/proposer/Cargo.toml b/cumulus/client/consensus/proposer/Cargo.toml index 2006eac5bf1..4cfba66cec3 100644 --- a/cumulus/client/consensus/proposer/Cargo.toml +++ b/cumulus/client/consensus/proposer/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] anyhow = "1.0" async-trait = "0.1.73" diff --git a/cumulus/client/consensus/relay-chain/Cargo.toml b/cumulus/client/consensus/relay-chain/Cargo.toml index 76b1c9a422f..de280e6e9a8 100644 --- a/cumulus/client/consensus/relay-chain/Cargo.toml +++ b/cumulus/client/consensus/relay-chain/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] async-trait = "0.1.73" futures = "0.3.28" diff --git a/cumulus/client/network/Cargo.toml b/cumulus/client/network/Cargo.toml index 5e0d478f5ac..08956f9f6c6 100644 --- a/cumulus/client/network/Cargo.toml +++ b/cumulus/client/network/Cargo.toml @@ -6,12 +6,9 @@ description = "Cumulus-specific networking protocol" edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] async-trait = "0.1.73" -codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", features = [ "derive" ] } futures = "0.3.28" futures-timer = "3.0.2" parking_lot = "0.12.1" diff --git a/cumulus/client/pov-recovery/Cargo.toml b/cumulus/client/pov-recovery/Cargo.toml index 93d65016530..e407b33e0e2 100644 --- a/cumulus/client/pov-recovery/Cargo.toml +++ b/cumulus/client/pov-recovery/Cargo.toml @@ -6,11 +6,8 @@ description = "Cumulus-specific networking protocol" edition.workspace = true license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", features = [ "derive" ] } futures = "0.3.28" futures-timer = "3.0.2" rand = "0.8.5" diff --git a/cumulus/client/pov-recovery/src/lib.rs b/cumulus/client/pov-recovery/src/lib.rs index 32aba6c8993..b9a140f55c6 100644 --- a/cumulus/client/pov-recovery/src/lib.rs +++ b/cumulus/client/pov-recovery/src/lib.rs @@ -410,7 +410,6 @@ where ?block_hash, parent_hash = ?parent, parent_scheduled_for_recovery, - waiting_blocks = self.waiting_for_parent.len(), "Waiting for recovery of parent.", ); @@ -443,13 +442,13 @@ where _ => (), } - self.import_block(block); + self.import_block(block).await; } /// Import the given `block`. /// /// This will also recursivley drain `waiting_for_parent` and import them as well. - fn import_block(&mut self, block: Block) { + async fn import_block(&mut self, block: Block) { let mut blocks = VecDeque::new(); tracing::debug!(target: LOG_TARGET, block_hash = ?block.hash(), "Importing block retrieved using pov_recovery"); @@ -552,6 +551,7 @@ where }; futures::pin_mut!(pending_candidates); + loop { select! { pending_candidate = pending_candidates.next() => { @@ -573,17 +573,6 @@ where imported = imported_blocks.next() => { if let Some(imported) = imported { self.clear_waiting_recovery(&imported.hash); - - // We need to double check that no blocks are waiting for this block. - // Can happen when a waiting child block is queued to wait for parent while the parent block is still - // in the import queue. - if let Some(waiting_blocks) = self.waiting_for_parent.remove(&imported.hash) { - for block in waiting_blocks { - tracing::debug!(target: LOG_TARGET, block_hash = ?block.hash(), resolved_parent = ?imported.hash, "Found new waiting child block during import, queuing."); - self.import_block(block); - } - }; - } else { tracing::debug!(target: LOG_TARGET, "Imported blocks stream ended"); return; diff --git a/cumulus/client/relay-chain-inprocess-interface/Cargo.toml b/cumulus/client/relay-chain-inprocess-interface/Cargo.toml index 15063d09bca..87f0eabd9b5 100644 --- a/cumulus/client/relay-chain-inprocess-interface/Cargo.toml +++ b/cumulus/client/relay-chain-inprocess-interface/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true description = "Implementation of the RelayChainInterface trait for Polkadot full-nodes." license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] async-trait = "0.1.73" futures = "0.3.28" @@ -42,7 +39,7 @@ sp-keyring = { path = "../../../substrate/primitives/keyring" } # Polkadot polkadot-primitives = { path = "../../../polkadot/primitives" } polkadot-test-client = { path = "../../../polkadot/node/test/client" } -metered = { package = "prioritized-metered-channel", version = "0.5.1", default-features = false, features = ["futures_channel"] } +metered = { package = "prioritized-metered-channel", version = "0.5.1", default-features = false, features=["futures_channel"] } # Cumulus cumulus-test-service = { path = "../../test/service" } diff --git a/cumulus/client/relay-chain-inprocess-interface/src/lib.rs b/cumulus/client/relay-chain-inprocess-interface/src/lib.rs index d384c9d9bd2..42a56b649f0 100644 --- a/cumulus/client/relay-chain-inprocess-interface/src/lib.rs +++ b/cumulus/client/relay-chain-inprocess-interface/src/lib.rs @@ -283,15 +283,14 @@ fn build_polkadot_full_node( config, polkadot_service::NewFullParams { is_parachain_node, + grandpa_pause: None, // Disable BEEFY. It should not be required by the internal relay chain node. enable_beefy: false, - force_authoring_backoff: false, jaeger_agent: None, telemetry_worker_handle, // Cumulus doesn't spawn PVF workers, so we can disable version checks. node_version: None, - secure_validator_mode: false, workers_path: None, workers_names: None, diff --git a/cumulus/client/relay-chain-interface/Cargo.toml b/cumulus/client/relay-chain-interface/Cargo.toml index 98893a398fb..c9d50afe8fa 100644 --- a/cumulus/client/relay-chain-interface/Cargo.toml +++ b/cumulus/client/relay-chain-interface/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true description = "Common interface for different relay chain datasources." license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] polkadot-overseer = { path = "../../../polkadot/node/overseer" } diff --git a/cumulus/client/relay-chain-minimal-node/Cargo.toml b/cumulus/client/relay-chain-minimal-node/Cargo.toml index b22731b3a6d..ce76fc5cd6d 100644 --- a/cumulus/client/relay-chain-minimal-node/Cargo.toml +++ b/cumulus/client/relay-chain-minimal-node/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true description = "Minimal node implementation to be used in tandem with RPC or light-client mode." license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] # polkadot deps polkadot-primitives = { path = "../../../polkadot/primitives" } @@ -50,4 +47,4 @@ array-bytes = "6.1" tracing = "0.1.37" async-trait = "0.1.73" futures = "0.3.28" -parking_lot = "0.12.1" + diff --git a/cumulus/client/relay-chain-minimal-node/src/blockchain_rpc_client.rs b/cumulus/client/relay-chain-minimal-node/src/blockchain_rpc_client.rs index ab56b62c4ca..d9e4155d9c5 100644 --- a/cumulus/client/relay-chain-minimal-node/src/blockchain_rpc_client.rs +++ b/cumulus/client/relay-chain-minimal-node/src/blockchain_rpc_client.rs @@ -24,7 +24,7 @@ use polkadot_overseer::{ChainApiBackend, RuntimeApiSubsystemClient}; use polkadot_primitives::{ async_backing::{AsyncBackingParams, BackingState}, slashing, - vstaging::{ApprovalVotingParams, NodeFeatures}, + vstaging::NodeFeatures, }; use sc_authority_discovery::{AuthorityDiscovery, Error as AuthorityDiscoveryError}; use sc_client_api::AuxStore; @@ -427,18 +427,6 @@ impl RuntimeApiSubsystemClient for BlockChainRpcClient { Ok(self.rpc_client.parachain_host_para_backing_state(at, para_id).await?) } - /// Approval voting configuration parameters - async fn approval_voting_params( - &self, - at: Hash, - session_index: polkadot_primitives::SessionIndex, - ) -> Result { - Ok(self - .rpc_client - .parachain_host_staging_approval_voting_params(at, session_index) - .await?) - } - async fn node_features(&self, at: Hash) -> Result { Ok(self.rpc_client.parachain_host_node_features(at).await?) } diff --git a/cumulus/client/relay-chain-minimal-node/src/collator_overseer.rs b/cumulus/client/relay-chain-minimal-node/src/collator_overseer.rs index 5f5bf338ef9..a785a9f6f79 100644 --- a/cumulus/client/relay-chain-minimal-node/src/collator_overseer.rs +++ b/cumulus/client/relay-chain-minimal-node/src/collator_overseer.rs @@ -15,8 +15,7 @@ // along with Polkadot. If not, see . use futures::{select, StreamExt}; -use parking_lot::Mutex; -use std::{collections::HashMap, sync::Arc}; +use std::sync::Arc; use polkadot_availability_recovery::AvailabilityRecoverySubsystem; use polkadot_collator_protocol::{CollatorProtocolSubsystem, ProtocolSide}; @@ -29,7 +28,7 @@ use polkadot_node_core_chain_api::ChainApiSubsystem; use polkadot_node_core_prospective_parachains::ProspectiveParachainsSubsystem; use polkadot_node_core_runtime_api::RuntimeApiSubsystem; use polkadot_node_network_protocol::{ - peer_set::{PeerSet, PeerSetProtocolNames}, + peer_set::PeerSetProtocolNames, request_response::{ v1::{self, AvailableDataFetchingRequest}, v2, IncomingRequestReceiver, ReqProtocolNames, @@ -43,7 +42,7 @@ use polkadot_overseer::{ use polkadot_primitives::CollatorPair; use sc_authority_discovery::Service as AuthorityDiscoveryService; -use sc_network::{NetworkStateInfo, NotificationService}; +use sc_network::NetworkStateInfo; use sc_service::TaskManager; use sc_utils::mpsc::tracing_unbounded; @@ -78,8 +77,6 @@ pub(crate) struct CollatorOverseerGenArgs<'a> { pub req_protocol_names: ReqProtocolNames, /// Peerset protocols name mapping pub peer_set_protocol_names: PeerSetProtocolNames, - /// Notification services for validation/collation protocols. - pub notification_services: HashMap>, } fn build_overseer( @@ -97,7 +94,6 @@ fn build_overseer( collator_pair, req_protocol_names, peer_set_protocol_names, - notification_services, }: CollatorOverseerGenArgs<'_>, ) -> Result< (Overseer, Arc>, OverseerHandle), @@ -105,8 +101,6 @@ fn build_overseer( > { let spawner = SpawnGlue(spawner); let network_bridge_metrics: NetworkBridgeMetrics = Metrics::register(registry)?; - let notification_sinks = Arc::new(Mutex::new(HashMap::new())); - let builder = Overseer::builder() .availability_distribution(DummySubsystem) .availability_recovery(AvailabilityRecoverySubsystem::for_collator( @@ -137,8 +131,6 @@ fn build_overseer( sync_oracle, network_bridge_metrics.clone(), peer_set_protocol_names.clone(), - notification_services, - notification_sinks.clone(), )) .network_bridge_tx(NetworkBridgeTxSubsystem::new( network_service, @@ -146,7 +138,6 @@ fn build_overseer( network_bridge_metrics, req_protocol_names, peer_set_protocol_names, - notification_sinks, )) .provisioner(DummySubsystem) .runtime_api(RuntimeApiSubsystem::new( diff --git a/cumulus/client/relay-chain-minimal-node/src/lib.rs b/cumulus/client/relay-chain-minimal-node/src/lib.rs index d121d2d3356..8801f93640c 100644 --- a/cumulus/client/relay-chain-minimal-node/src/lib.rs +++ b/cumulus/client/relay-chain-minimal-node/src/lib.rs @@ -21,7 +21,7 @@ use cumulus_relay_chain_rpc_interface::{RelayChainRpcClient, RelayChainRpcInterf use network::build_collator_network; use polkadot_network_bridge::{peer_sets_info, IsAuthority}; use polkadot_node_network_protocol::{ - peer_set::{PeerSet, PeerSetProtocolNames}, + peer_set::PeerSetProtocolNames, request_response::{ v1, v2, IncomingRequest, IncomingRequestReceiver, Protocol, ReqProtocolNames, }, @@ -175,13 +175,10 @@ async fn new_minimal_relay_chain( let peer_set_protocol_names = PeerSetProtocolNames::new(genesis_hash, config.chain_spec.fork_id()); let is_authority = if role.is_authority() { IsAuthority::Yes } else { IsAuthority::No }; - let notification_services = peer_sets_info(is_authority, &peer_set_protocol_names) - .into_iter() - .map(|(config, (peerset, service))| { - net_config.add_notification_protocol(config); - (peerset, service) - }) - .collect::>>(); + + for config in peer_sets_info(is_authority, &peer_set_protocol_names) { + net_config.add_notification_protocol(config); + } let request_protocol_names = ReqProtocolNames::new(genesis_hash, config.chain_spec.fork_id()); let (collation_req_receiver_v1, collation_req_receiver_v2, available_data_req_receiver) = @@ -221,7 +218,6 @@ async fn new_minimal_relay_chain( collator_pair, req_protocol_names: request_protocol_names, peer_set_protocol_names, - notification_services, }; let overseer_handle = diff --git a/cumulus/client/relay-chain-minimal-node/src/network.rs b/cumulus/client/relay-chain-minimal-node/src/network.rs index 95785063c1a..813dca47a03 100644 --- a/cumulus/client/relay-chain-minimal-node/src/network.rs +++ b/cumulus/client/relay-chain-minimal-node/src/network.rs @@ -26,9 +26,10 @@ use sc_network::{ NetworkService, }; -use sc_network::{config::FullNetworkConfiguration, NotificationService}; +use sc_network::config::FullNetworkConfiguration; use sc_network_common::{role::Roles, sync::message::BlockAnnouncesHandshake}; use sc_service::{error::Error, Configuration, NetworkStarter, SpawnTaskHandle}; +use sc_utils::mpsc::tracing_unbounded; use std::{iter, sync::Arc}; @@ -44,7 +45,7 @@ pub(crate) fn build_collator_network( Error, > { let protocol_id = config.protocol_id(); - let (block_announce_config, _notification_service) = get_block_announce_proto_config::( + let block_announce_config = get_block_announce_proto_config::( protocol_id.clone(), &None, Roles::from(&config.role), @@ -68,6 +69,8 @@ pub(crate) fn build_collator_network( let peer_store_handle = peer_store.handle(); spawn_handle.spawn("peer-store", Some("networking"), peer_store.run()); + // RX is not used for anything because syncing is not started for the minimal node + let (tx, _rx) = tracing_unbounded("mpsc_syncing_engine_protocol", 100_000); let network_params = sc_network::config::Params:: { role: config.role.clone(), executor: { @@ -83,6 +86,7 @@ pub(crate) fn build_collator_network( protocol_id, metrics_registry: config.prometheus_config.as_ref().map(|config| config.registry.clone()), block_announce_config, + tx, }; let network_worker = sc_network::NetworkWorker::new(network_params)?; @@ -146,7 +150,7 @@ fn get_block_announce_proto_config( best_number: NumberFor, best_hash: B::Hash, genesis_hash: B::Hash, -) -> (NonDefaultSetConfig, Box) { +) -> NonDefaultSetConfig { let block_announces_protocol = { let genesis_hash = genesis_hash.as_ref(); if let Some(ref fork_id) = fork_id { @@ -156,11 +160,12 @@ fn get_block_announce_proto_config( } }; - NonDefaultSetConfig::new( - block_announces_protocol.into(), - iter::once(format!("/{}/block-announces/1", protocol_id.as_ref()).into()).collect(), - 1024 * 1024, - Some(NotificationHandshake::new(BlockAnnouncesHandshake::::build( + NonDefaultSetConfig { + notifications_protocol: block_announces_protocol.into(), + fallback_names: iter::once(format!("/{}/block-announces/1", protocol_id.as_ref()).into()) + .collect(), + max_notification_size: 1024 * 1024, + handshake: Some(NotificationHandshake::new(BlockAnnouncesHandshake::::build( roles, best_number, best_hash, @@ -168,11 +173,11 @@ fn get_block_announce_proto_config( ))), // NOTE: `set_config` will be ignored by `protocol.rs` as the block announcement // protocol is still hardcoded into the peerset. - SetConfig { + set_config: SetConfig { in_peers: 0, out_peers: 0, reserved_nodes: Vec::new(), non_reserved_mode: NonReservedPeerMode::Deny, }, - ) + } } diff --git a/cumulus/client/relay-chain-rpc-interface/Cargo.toml b/cumulus/client/relay-chain-rpc-interface/Cargo.toml index 050bea08f0f..0159cade23f 100644 --- a/cumulus/client/relay-chain-rpc-interface/Cargo.toml +++ b/cumulus/client/relay-chain-rpc-interface/Cargo.toml @@ -6,8 +6,6 @@ edition.workspace = true description = "Implementation of the RelayChainInterface trait that connects to a remote RPC-node." license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true [dependencies] polkadot-overseer = { path = "../../../polkadot/node/overseer" } @@ -38,9 +36,9 @@ tracing = "0.1.37" async-trait = "0.1.73" url = "2.4.0" serde_json = "1.0.108" -serde = "1.0.193" +serde = "1.0.188" schnellru = "0.2.1" -smoldot = { version = "0.11.0", default_features = false, features = ["std"] } +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" thiserror = "1.0.48" diff --git a/cumulus/client/relay-chain-rpc-interface/src/rpc_client.rs b/cumulus/client/relay-chain-rpc-interface/src/rpc_client.rs index c64fff77a29..8e0d5fae677 100644 --- a/cumulus/client/relay-chain-rpc-interface/src/rpc_client.rs +++ b/cumulus/client/relay-chain-rpc-interface/src/rpc_client.rs @@ -32,7 +32,7 @@ use cumulus_primitives_core::{ relay_chain::{ async_backing::{AsyncBackingParams, BackingState}, slashing, - vstaging::{ApprovalVotingParams, NodeFeatures}, + vstaging::NodeFeatures, BlockNumber, CandidateCommitments, CandidateEvent, CandidateHash, CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, GroupRotationInfo, Hash as RelayHash, Header as RelayHeader, InboundHrmpMessage, OccupiedCoreAssumption, @@ -625,19 +625,6 @@ impl RelayChainRpcClient { } #[allow(missing_docs)] - pub async fn parachain_host_staging_approval_voting_params( - &self, - at: RelayHash, - _session_index: SessionIndex, - ) -> Result { - self.call_remote_runtime_function( - "ParachainHost_staging_approval_voting_params", - at, - None::<()>, - ) - .await - } - pub async fn parachain_host_para_backing_state( &self, at: RelayHash, diff --git a/cumulus/client/service/Cargo.toml b/cumulus/client/service/Cargo.toml index 997413ad0da..f80c65128d5 100644 --- a/cumulus/client/service/Cargo.toml +++ b/cumulus/client/service/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true description = "Common functions used to assemble the components of a parachain node." license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -[lints] -workspace = true - [dependencies] futures = "0.3.28" @@ -41,7 +38,7 @@ 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" } + diff --git a/cumulus/client/service/src/lib.rs b/cumulus/client/service/src/lib.rs index 950e59aff24..f8ebca11c8c 100644 --- a/cumulus/client/service/src/lib.rs +++ b/cumulus/client/service/src/lib.rs @@ -52,8 +52,6 @@ use sp_core::{traits::SpawnNamed, Decode}; use sp_runtime::traits::{Block as BlockT, BlockIdTo, Header}; use std::{sync::Arc, time::Duration}; -pub use cumulus_primitives_proof_size_hostfunction::storage_proof_size; - // Given the sporadic nature of the explicit recovery operation and the // possibility to retry infinite times this value is more than enough. // In practice here we expect no more than one queued messages. diff --git a/cumulus/pallets/aura-ext/Cargo.toml b/cumulus/pallets/aura-ext/Cargo.toml index 14dcd10ddfc..c9d82ead1eb 100644 --- a/cumulus/pallets/aura-ext/Cargo.toml +++ b/cumulus/pallets/aura-ext/Cargo.toml @@ -6,22 +6,19 @@ edition.workspace = true description = "AURA consensus extension pallet for parachains" license = "Apache-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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 = { 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} # Cumulus cumulus-pallet-parachain-system = { path = "../parachain-system", default-features = false } @@ -32,7 +29,7 @@ cumulus-pallet-parachain-system = { path = "../parachain-system", default-featur cumulus-pallet-parachain-system = { path = "../parachain-system" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-pallet-parachain-system/std", diff --git a/cumulus/pallets/collator-selection/Cargo.toml b/cumulus/pallets/collator-selection/Cargo.toml index 9c2af8893ca..68e4a681c2b 100644 --- a/cumulus/pallets/collator-selection/Cargo.toml +++ b/cumulus/pallets/collator-selection/Cargo.toml @@ -9,9 +9,6 @@ readme = "README.md" repository.workspace = true version = "3.0.0" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,15 +18,15 @@ codec = { default-features = false, features = ["derive"], package = "parity-sca rand = { version = "0.8.5", features = ["std_rng"], default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -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-session = { path = "../../../substrate/frame/session", default-features = false } +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-session = { path = "../../../substrate/frame/session", default-features = false} -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } +frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true} [dev-dependencies] sp-core = { path = "../../../substrate/primitives/core" } @@ -42,7 +39,7 @@ pallet-balances = { path = "../../../substrate/frame/balances" } pallet-aura = { path = "../../../substrate/frame/aura" } [features] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", @@ -78,4 +75,4 @@ try-runtime = [ "sp-runtime/try-runtime", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] diff --git a/cumulus/pallets/collator-selection/src/mock.rs b/cumulus/pallets/collator-selection/src/mock.rs index ab9ad5ec11a..46143674bb3 100644 --- a/cumulus/pallets/collator-selection/src/mock.rs +++ b/cumulus/pallets/collator-selection/src/mock.rs @@ -16,7 +16,7 @@ use super::*; use crate as collator_selection; use frame_support::{ - derive_impl, ord_parameter_types, parameter_types, + ord_parameter_types, parameter_types, traits::{ConstBool, ConstU32, ConstU64, FindAuthor, ValidatorRegistration}, PalletId, }; @@ -50,7 +50,6 @@ parameter_types! { pub const SS58Prefix: u8 = 42; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/cumulus/pallets/dmp-queue/Cargo.toml b/cumulus/pallets/dmp-queue/Cargo.toml index bdcee0f5ff8..43fb131aec2 100644 --- a/cumulus/pallets/dmp-queue/Cargo.toml +++ b/cumulus/pallets/dmp-queue/Cargo.toml @@ -7,9 +7,6 @@ repository.workspace = true description = "Migrates messages from the old DMP queue pallet." license = "Apache-2.0" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -26,7 +23,7 @@ sp-runtime = { path = "../../../substrate/primitives/runtime", default-features sp-io = { path = "../../../substrate/primitives/io", default-features = false } # Polkadot -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } +xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false} # Cumulus cumulus-primitives-core = { path = "../../primitives/core", default-features = false } @@ -36,7 +33,7 @@ sp-core = { path = "../../../substrate/primitives/core" } sp-tracing = { path = "../../../substrate/primitives/tracing" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", diff --git a/cumulus/pallets/parachain-system/Cargo.toml b/cumulus/pallets/parachain-system/Cargo.toml index d24fdfe101e..5600c95a2a6 100644 --- a/cumulus/pallets/parachain-system/Cargo.toml +++ b/cumulus/pallets/parachain-system/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true description = "Base pallet for cumulus-based parachains" license = "Apache-2.0" -[lints] -workspace = true - [dependencies] bytes = { version = "1.4.0", default-features = false } codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } @@ -19,36 +16,34 @@ trie-db = { version = "0.28.0", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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 } +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 } +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} # Polkadot -polkadot-parachain-primitives = { path = "../../../polkadot/parachain", default-features = false, features = ["wasm-api"] } +polkadot-parachain-primitives = { path = "../../../polkadot/parachain", default-features = false, features = [ "wasm-api" ]} polkadot-runtime-parachains = { path = "../../../polkadot/runtime/parachains", default-features = false } -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } +xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false} # 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 } [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" @@ -63,14 +58,13 @@ cumulus-test-client = { path = "../../test/client" } cumulus-test-relay-sproof-builder = { path = "../../test/relay-sproof-builder" } [features] -default = ["std"] +default = [ "std" ] std = [ "bytes/std", "codec/std", "cumulus-pallet-parachain-system-proc-macro/std", "cumulus-primitives-core/std", "cumulus-primitives-parachain-inherent/std", - "cumulus-primitives-proof-size-hostfunction/std", "environmental/std", "frame-benchmarking/std", "frame-support/std", diff --git a/cumulus/pallets/parachain-system/proc-macro/Cargo.toml b/cumulus/pallets/parachain-system/proc-macro/Cargo.toml index 11a2ae01374..6accfa92c57 100644 --- a/cumulus/pallets/parachain-system/proc-macro/Cargo.toml +++ b/cumulus/pallets/parachain-system/proc-macro/Cargo.toml @@ -6,18 +6,15 @@ edition.workspace = true description = "Proc macros provided by the parachain-system pallet" license = "Apache-2.0" -[lints] -workspace = true - [lib] proc-macro = true [dependencies] -syn = "2.0.40" +syn = "2.0.38" proc-macro2 = "1.0.64" quote = "1.0.33" -proc-macro-crate = "2.0.1" +proc-macro-crate = "1.3.1" [features] -default = ["std"] +default = [ "std" ] std = [] diff --git a/cumulus/pallets/parachain-system/src/validate_block/mod.rs b/cumulus/pallets/parachain-system/src/validate_block/mod.rs index 763a4cffd77..db149401638 100644 --- a/cumulus/pallets/parachain-system/src/validate_block/mod.rs +++ b/cumulus/pallets/parachain-system/src/validate_block/mod.rs @@ -26,10 +26,6 @@ mod tests; #[doc(hidden)] mod trie_cache; -#[cfg(any(test, not(feature = "std")))] -#[doc(hidden)] -mod trie_recorder; - #[cfg(not(feature = "std"))] #[doc(hidden)] pub use bytes; diff --git a/cumulus/pallets/parachain-system/src/validate_block/trie_recorder.rs b/cumulus/pallets/parachain-system/src/validate_block/trie_recorder.rs deleted file mode 100644 index e73aef70aa4..00000000000 --- a/cumulus/pallets/parachain-system/src/validate_block/trie_recorder.rs +++ /dev/null @@ -1,286 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// 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 Cumulus. If not, see . - -//! Provide a specialized trie-recorder and provider for use in validate-block. -//! -//! This file defines two main structs, [`SizeOnlyRecorder`] and -//! [`SizeOnlyRecorderProvider`]. They are used to track the current -//! proof-size without actually recording the accessed nodes themselves. - -use codec::Encode; - -use sp_std::{ - cell::{RefCell, RefMut}, - collections::{btree_map::BTreeMap, btree_set::BTreeSet}, - rc::Rc, -}; -use sp_trie::{NodeCodec, ProofSizeProvider, StorageProof}; -use trie_db::{Hasher, RecordedForKey, TrieAccess}; - -/// A trie recorder that only keeps track of the proof size. -/// -/// The internal size counting logic should align -/// with ['sp_trie::recorder::Recorder']. -pub(crate) struct SizeOnlyRecorder<'a, H: Hasher> { - seen_nodes: RefMut<'a, BTreeSet>, - encoded_size: RefMut<'a, usize>, - recorded_keys: RefMut<'a, BTreeMap, RecordedForKey>>, -} - -impl<'a, H: trie_db::Hasher> trie_db::TrieRecorder for SizeOnlyRecorder<'a, H> { - fn record(&mut self, access: TrieAccess<'_, H::Out>) { - let mut encoded_size_update = 0; - match access { - TrieAccess::NodeOwned { hash, node_owned } => - if self.seen_nodes.insert(hash) { - let node = node_owned.to_encoded::>(); - encoded_size_update += node.encoded_size(); - }, - TrieAccess::EncodedNode { hash, encoded_node } => - if self.seen_nodes.insert(hash) { - encoded_size_update += encoded_node.encoded_size(); - }, - TrieAccess::Value { hash, value, full_key } => { - if self.seen_nodes.insert(hash) { - encoded_size_update += value.encoded_size(); - } - self.recorded_keys - .entry(full_key.into()) - .and_modify(|e| *e = RecordedForKey::Value) - .or_insert_with(|| RecordedForKey::Value); - }, - TrieAccess::Hash { full_key } => { - self.recorded_keys - .entry(full_key.into()) - .or_insert_with(|| RecordedForKey::Hash); - }, - TrieAccess::NonExisting { full_key } => { - self.recorded_keys - .entry(full_key.into()) - .and_modify(|e| *e = RecordedForKey::Value) - .or_insert_with(|| RecordedForKey::Value); - }, - TrieAccess::InlineValue { full_key } => { - self.recorded_keys - .entry(full_key.into()) - .and_modify(|e| *e = RecordedForKey::Value) - .or_insert_with(|| RecordedForKey::Value); - }, - }; - - *self.encoded_size += encoded_size_update; - } - - fn trie_nodes_recorded_for_key(&self, key: &[u8]) -> RecordedForKey { - self.recorded_keys.get(key).copied().unwrap_or(RecordedForKey::None) - } -} - -#[derive(Clone)] -pub(crate) struct SizeOnlyRecorderProvider { - seen_nodes: Rc>>, - encoded_size: Rc>, - recorded_keys: Rc, RecordedForKey>>>, -} - -impl SizeOnlyRecorderProvider { - pub fn new() -> Self { - Self { - seen_nodes: Default::default(), - encoded_size: Default::default(), - recorded_keys: Default::default(), - } - } -} - -impl sp_trie::TrieRecorderProvider for SizeOnlyRecorderProvider { - type Recorder<'a> = SizeOnlyRecorder<'a, H> where H: 'a; - - fn drain_storage_proof(self) -> Option { - None - } - - fn as_trie_recorder(&self, _storage_root: H::Out) -> Self::Recorder<'_> { - SizeOnlyRecorder { - encoded_size: self.encoded_size.borrow_mut(), - seen_nodes: self.seen_nodes.borrow_mut(), - recorded_keys: self.recorded_keys.borrow_mut(), - } - } -} - -impl ProofSizeProvider for SizeOnlyRecorderProvider { - fn estimate_encoded_size(&self) -> usize { - *self.encoded_size.borrow() - } -} - -// This is safe here since we are single-threaded in WASM -unsafe impl Send for SizeOnlyRecorderProvider {} -unsafe impl Sync for SizeOnlyRecorderProvider {} - -#[cfg(test)] -mod tests { - use rand::Rng; - use sp_trie::{ - cache::{CacheSize, SharedTrieCache}, - MemoryDB, ProofSizeProvider, TrieRecorderProvider, - }; - use trie_db::{Trie, TrieDBBuilder, TrieDBMutBuilder, TrieHash, TrieMut, TrieRecorder}; - use trie_standardmap::{Alphabet, StandardMap, ValueMode}; - - use super::*; - - type Recorder = sp_trie::recorder::Recorder; - - fn create_trie() -> ( - sp_trie::MemoryDB, - TrieHash>, - Vec<(Vec, Vec)>, - ) { - let mut db = MemoryDB::default(); - let mut root = Default::default(); - - let mut seed = Default::default(); - let test_data: Vec<(Vec, Vec)> = StandardMap { - alphabet: Alphabet::Low, - min_key: 16, - journal_key: 0, - value_mode: ValueMode::Random, - count: 1000, - } - .make_with(&mut seed) - .into_iter() - .map(|(k, v)| { - // Double the length so we end up with some values of 2 bytes and some of 64 - let v = [v.clone(), v].concat(); - (k, v) - }) - .collect(); - - // Fill database with values - { - let mut trie = TrieDBMutBuilder::>::new( - &mut db, &mut root, - ) - .build(); - for (k, v) in &test_data { - trie.insert(k, v).expect("Inserts data"); - } - } - - (db, root, test_data) - } - - #[test] - fn recorder_equivalence_cache() { - let (db, root, test_data) = create_trie(); - - let mut rng = rand::thread_rng(); - for _ in 1..10 { - let reference_recorder = Recorder::default(); - let recorder_for_test: SizeOnlyRecorderProvider = - SizeOnlyRecorderProvider::new(); - let reference_cache: SharedTrieCache = - SharedTrieCache::new(CacheSize::new(1024 * 5)); - let cache_for_test: SharedTrieCache = - SharedTrieCache::new(CacheSize::new(1024 * 5)); - { - let local_cache = cache_for_test.local_cache(); - let mut trie_cache_for_reference = local_cache.as_trie_db_cache(root); - let mut reference_trie_recorder = reference_recorder.as_trie_recorder(root); - let reference_trie = - TrieDBBuilder::>::new(&db, &root) - .with_recorder(&mut reference_trie_recorder) - .with_cache(&mut trie_cache_for_reference) - .build(); - - let local_cache_for_test = reference_cache.local_cache(); - let mut trie_cache_for_test = local_cache_for_test.as_trie_db_cache(root); - let mut trie_recorder_under_test = recorder_for_test.as_trie_recorder(root); - let test_trie = - TrieDBBuilder::>::new(&db, &root) - .with_recorder(&mut trie_recorder_under_test) - .with_cache(&mut trie_cache_for_test) - .build(); - - // Access random values from the test data - for _ in 0..100 { - let index: usize = rng.gen_range(0..test_data.len()); - test_trie.get(&test_data[index].0).unwrap().unwrap(); - reference_trie.get(&test_data[index].0).unwrap().unwrap(); - } - - // Check that we have the same nodes recorded for both recorders - for (key, _) in test_data.iter() { - let reference = reference_trie_recorder.trie_nodes_recorded_for_key(key); - let test_value = trie_recorder_under_test.trie_nodes_recorded_for_key(key); - assert_eq!(format!("{:?}", reference), format!("{:?}", test_value)); - } - } - - // Check that we have the same size recorded for both recorders - assert_eq!( - reference_recorder.estimate_encoded_size(), - recorder_for_test.estimate_encoded_size() - ); - } - } - - #[test] - fn recorder_equivalence_no_cache() { - let (db, root, test_data) = create_trie(); - - let mut rng = rand::thread_rng(); - for _ in 1..10 { - let reference_recorder = Recorder::default(); - let recorder_for_test: SizeOnlyRecorderProvider = - SizeOnlyRecorderProvider::new(); - { - let mut reference_trie_recorder = reference_recorder.as_trie_recorder(root); - let reference_trie = - TrieDBBuilder::>::new(&db, &root) - .with_recorder(&mut reference_trie_recorder) - .build(); - - let mut trie_recorder_under_test = recorder_for_test.as_trie_recorder(root); - let test_trie = - TrieDBBuilder::>::new(&db, &root) - .with_recorder(&mut trie_recorder_under_test) - .build(); - - for _ in 0..200 { - let index: usize = rng.gen_range(0..test_data.len()); - test_trie.get(&test_data[index].0).unwrap().unwrap(); - reference_trie.get(&test_data[index].0).unwrap().unwrap(); - } - - // Check that we have the same nodes recorded for both recorders - for (key, _) in test_data.iter() { - let reference = reference_trie_recorder.trie_nodes_recorded_for_key(key); - let test_value = trie_recorder_under_test.trie_nodes_recorded_for_key(key); - assert_eq!(format!("{:?}", reference), format!("{:?}", test_value)); - } - } - - // Check that we have the same size recorded for both recorders - assert_eq!( - reference_recorder.estimate_encoded_size(), - recorder_for_test.estimate_encoded_size() - ); - } - } -} diff --git a/cumulus/pallets/session-benchmarking/Cargo.toml b/cumulus/pallets/session-benchmarking/Cargo.toml index af2dc2300d7..a28971d66d3 100644 --- a/cumulus/pallets/session-benchmarking/Cargo.toml +++ b/cumulus/pallets/session-benchmarking/Cargo.toml @@ -9,23 +9,20 @@ repository.workspace = true description = "FRAME sessions pallet benchmarking" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] parity-scale-codec = { version = "3.6.4", 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 } +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} [features] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", diff --git a/cumulus/pallets/solo-to-para/Cargo.toml b/cumulus/pallets/solo-to-para/Cargo.toml index e1c94cbfde9..e4ef72965c7 100644 --- a/cumulus/pallets/solo-to-para/Cargo.toml +++ b/cumulus/pallets/solo-to-para/Cargo.toml @@ -6,28 +6,25 @@ edition.workspace = true description = "Adds functionality to migrate from a Solo to a Parachain" license = "Apache-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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 = { 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} # Polkadot -polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false } +polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false} # Cumulus -cumulus-pallet-parachain-system = { path = "../parachain-system", default-features = false } +cumulus-pallet-parachain-system = { path = "../parachain-system", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-pallet-parachain-system/std", diff --git a/cumulus/pallets/xcm/Cargo.toml b/cumulus/pallets/xcm/Cargo.toml index 9bbc281154c..c8e819979bd 100644 --- a/cumulus/pallets/xcm/Cargo.toml +++ b/cumulus/pallets/xcm/Cargo.toml @@ -6,25 +6,22 @@ version = "0.1.0" license = "Apache-2.0" description = "Pallet for stuff specific to parachains' usage of XCM" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -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 = { 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} -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } +xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false} cumulus-primitives-core = { path = "../../primitives/core", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-primitives-core/std", diff --git a/cumulus/pallets/xcmp-queue/Cargo.toml b/cumulus/pallets/xcmp-queue/Cargo.toml index 50ec5cacb2e..fba006e7986 100644 --- a/cumulus/pallets/xcmp-queue/Cargo.toml +++ b/cumulus/pallets/xcmp-queue/Cargo.toml @@ -6,21 +6,18 @@ edition.workspace = true description = "Pallet to queue outbound and inbound XCMP messages." license = "Apache-2.0" -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"], default-features = false } +codec = { package = "parity-scale-codec", version = "3.0.0", features = [ "derive" ], default-features = false } log = { version = "0.4.20", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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 } +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 } +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 } # Polkadot @@ -33,7 +30,7 @@ xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm cumulus-primitives-core = { path = "../../primitives/core", default-features = false } # Optional import for benchmarking -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } +frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true} bounded-collections = { version = "0.1.4", default-features = false } # Bridges @@ -53,7 +50,7 @@ xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/x cumulus-pallet-parachain-system = { path = "../parachain-system", features = ["parameterized-consensus-hook"] } [features] -default = ["std"] +default = [ "std" ] std = [ "bounded-collections/std", "bp-xcm-bridge-hub-router?/std", @@ -99,4 +96,4 @@ try-runtime = [ "polkadot-runtime-parachains/try-runtime", "sp-runtime/try-runtime", ] -bridging = ["bp-xcm-bridge-hub-router"] +bridging = [ "bp-xcm-bridge-hub-router" ] diff --git a/cumulus/pallets/xcmp-queue/src/lib.rs b/cumulus/pallets/xcmp-queue/src/lib.rs index 71cd21d45f7..d687f83d8b3 100644 --- a/cumulus/pallets/xcmp-queue/src/lib.rs +++ b/cumulus/pallets/xcmp-queue/src/lib.rs @@ -60,7 +60,7 @@ use cumulus_primitives_core::{ use frame_support::{ defensive, defensive_assert, traits::{EnqueueMessage, EnsureOrigin, Get, QueueFootprint, QueuePausedQuery}, - weights::{Weight, WeightMeter}, + weights::{constants::WEIGHT_REF_TIME_PER_MILLIS, Weight, WeightMeter}, BoundedVec, }; use pallet_message_queue::OnQueueChanged; @@ -255,7 +255,7 @@ pub mod pallet { return meter.consumed() } - migration::v3::lazy_migrate_inbound_queue::(); + migration::lazy_migrate_inbound_queue::(); meter.consumed() } @@ -387,16 +387,36 @@ pub struct QueueConfigData { /// The number of pages which the queue must be reduced to before it signals that /// message sending may recommence after it has been suspended. resume_threshold: u32, + /// UNUSED - The amount of remaining weight under which we stop processing messages. + #[deprecated(note = "Will be removed")] + threshold_weight: Weight, + /// UNUSED - The speed to which the available weight approaches the maximum weight. A lower + /// number results in a faster progression. A value of 1 makes the entire weight available + /// initially. + #[deprecated(note = "Will be removed")] + weight_restrict_decay: Weight, + /// UNUSED - The maximum amount of weight any individual message may consume. Messages above + /// this weight go into the overweight queue and may only be serviced explicitly. + #[deprecated(note = "Will be removed")] + xcmp_max_individual_weight: Weight, } impl Default for QueueConfigData { fn default() -> Self { // NOTE that these default values are only used on genesis. They should give a rough idea of // what to set these values to, but is in no way a requirement. + #![allow(deprecated)] Self { drop_threshold: 48, // 64KiB * 48 = 3MiB suspend_threshold: 32, // 64KiB * 32 = 2MiB resume_threshold: 8, // 64KiB * 8 = 512KiB + // unused: + threshold_weight: Weight::from_parts(100_000, 0), + weight_restrict_decay: Weight::from_parts(2, 0), + xcmp_max_individual_weight: Weight::from_parts( + 20u64 * WEIGHT_REF_TIME_PER_MILLIS, + DEFAULT_POV_SIZE, + ), } } } @@ -454,21 +474,11 @@ impl Pallet { ) -> Result { let encoded_fragment = fragment.encode(); - // Optimization note: `max_message_size` could potentially be stored in - // `OutboundXcmpMessages` once known; that way it's only accessed when a new page is needed. - 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 format_size = format.encoded_size(); - // We check the encoded fragment length plus the format size agains the max message size - // because the format is concatenated if a new page is needed. - let size_to_check = encoded_fragment - .len() - .checked_add(format_size) - .ok_or(MessageSendError::TooBig)?; - if size_to_check > max_message_size { + // Max message size refers to aggregates, or pages. Not to individual fragments. + if encoded_fragment.len() > max_message_size { return Err(MessageSendError::TooBig) } diff --git a/cumulus/pallets/xcmp-queue/src/migration.rs b/cumulus/pallets/xcmp-queue/src/migration.rs index 6c86c3011d2..6d7f434b041 100644 --- a/cumulus/pallets/xcmp-queue/src/migration.rs +++ b/cumulus/pallets/xcmp-queue/src/migration.rs @@ -16,7 +16,7 @@ //! A module that is responsible for migration of storage. -use crate::{Config, OverweightIndex, Pallet, QueueConfig, QueueConfigData, DEFAULT_POV_SIZE}; +use crate::{Config, OverweightIndex, Pallet, ParaId, QueueConfig, DEFAULT_POV_SIZE}; use cumulus_primitives_core::XcmpMessageFormat; use frame_support::{ pallet_prelude::*, @@ -25,17 +25,37 @@ use frame_support::{ }; /// The current storage version. -pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(4); +pub const STORAGE_VERSION: StorageVersion = StorageVersion::new(3); pub const LOG: &str = "runtime::xcmp-queue-migration"; +/// Migrates the pallet storage to the most recent version. +pub struct MigrationToV3(PhantomData); + +impl OnRuntimeUpgrade for MigrationToV3 { + fn on_runtime_upgrade() -> Weight { + let mut weight = T::DbWeight::get().reads(1); + + if StorageVersion::get::>() == 1 { + weight.saturating_accrue(migrate_to_v2::()); + StorageVersion::new(2).put::>(); + weight.saturating_accrue(T::DbWeight::get().writes(1)); + } + + if StorageVersion::get::>() == 2 { + weight.saturating_accrue(migrate_to_v3::()); + StorageVersion::new(3).put::>(); + weight.saturating_accrue(T::DbWeight::get().writes(1)); + } + + weight + } +} + mod v1 { use super::*; use codec::{Decode, Encode}; - #[frame_support::storage_alias] - pub(crate) type QueueConfig = StorageValue, QueueConfigData, ValueQuery>; - #[derive(Encode, Decode, Debug)] pub struct QueueConfigData { pub suspend_threshold: u32, @@ -60,84 +80,6 @@ mod v1 { } } -pub mod v2 { - use super::*; - - #[frame_support::storage_alias] - pub(crate) type QueueConfig = StorageValue, QueueConfigData, ValueQuery>; - - #[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)] - pub struct QueueConfigData { - pub suspend_threshold: u32, - pub drop_threshold: u32, - pub resume_threshold: u32, - pub threshold_weight: Weight, - pub weight_restrict_decay: Weight, - pub xcmp_max_individual_weight: Weight, - } - - impl Default for QueueConfigData { - fn default() -> Self { - Self { - suspend_threshold: 2, - drop_threshold: 5, - resume_threshold: 1, - threshold_weight: Weight::from_parts(100_000, 0), - weight_restrict_decay: Weight::from_parts(2, 0), - xcmp_max_individual_weight: Weight::from_parts( - 20u64 * WEIGHT_REF_TIME_PER_MILLIS, - DEFAULT_POV_SIZE, - ), - } - } - } - - /// Migrates `QueueConfigData` from v1 (using only reference time weights) to v2 (with - /// 2D weights). - pub struct UncheckedMigrationToV2(PhantomData); - - impl OnRuntimeUpgrade for UncheckedMigrationToV2 { - #[allow(deprecated)] - fn on_runtime_upgrade() -> Weight { - let translate = |pre: v1::QueueConfigData| -> v2::QueueConfigData { - v2::QueueConfigData { - suspend_threshold: pre.suspend_threshold, - drop_threshold: pre.drop_threshold, - resume_threshold: pre.resume_threshold, - threshold_weight: Weight::from_parts(pre.threshold_weight, 0), - weight_restrict_decay: Weight::from_parts(pre.weight_restrict_decay, 0), - xcmp_max_individual_weight: Weight::from_parts( - pre.xcmp_max_individual_weight, - DEFAULT_POV_SIZE, - ), - } - }; - - if v2::QueueConfig::::translate(|pre| pre.map(translate)).is_err() { - log::error!( - target: crate::LOG_TARGET, - "unexpected error when performing translation of the QueueConfig type \ - during storage upgrade to v2" - ); - } - - T::DbWeight::get().reads_writes(1, 1) - } - } - - /// [`UncheckedMigrationToV2`] wrapped in a - /// [`VersionedMigration`](frame_support::migrations::VersionedMigration), ensuring the - /// migration is only performed when on-chain version is 1. - #[allow(dead_code)] - pub type MigrationToV2 = frame_support::migrations::VersionedMigration< - 1, - 2, - UncheckedMigrationToV2, - Pallet, - ::DbWeight, - >; -} - pub mod v3 { use super::*; use crate::*; @@ -159,10 +101,6 @@ pub mod v3 { OptionQuery, >; - #[frame_support::storage_alias] - pub(crate) type QueueConfig = - StorageValue, v2::QueueConfigData, ValueQuery>; - #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)] pub struct InboundChannelDetails { /// The `ParaId` of the parachain that this channel is connected with. @@ -183,135 +121,98 @@ pub mod v3 { Ok, Suspended, } +} - /// Migrates the pallet storage to v3. - pub struct UncheckedMigrationToV3(PhantomData); - - impl OnRuntimeUpgrade for UncheckedMigrationToV3 { - fn on_runtime_upgrade() -> Weight { - #[frame_support::storage_alias] - type Overweight = - CountedStorageMap, Twox64Concat, OverweightIndex, ParaId>; - let overweight_messages = Overweight::::initialize_counter() as u64; - - T::DbWeight::get().reads_writes(overweight_messages, 1) +/// Migrates `QueueConfigData` from v1 (using only reference time weights) to v2 (with +/// 2D weights). +/// +/// NOTE: Only use this function if you know what you're doing. Default to using +/// `migrate_to_latest`. +#[allow(deprecated)] +pub fn migrate_to_v2() -> Weight { + let translate = |pre: v1::QueueConfigData| -> super::QueueConfigData { + super::QueueConfigData { + suspend_threshold: pre.suspend_threshold, + drop_threshold: pre.drop_threshold, + resume_threshold: pre.resume_threshold, + threshold_weight: Weight::from_parts(pre.threshold_weight, 0), + weight_restrict_decay: Weight::from_parts(pre.weight_restrict_decay, 0), + xcmp_max_individual_weight: Weight::from_parts( + pre.xcmp_max_individual_weight, + DEFAULT_POV_SIZE, + ), } - } + }; - /// [`UncheckedMigrationToV3`] wrapped in a - /// [`VersionedMigration`](frame_support::migrations::VersionedMigration), ensuring the - /// migration is only performed when on-chain version is 2. - pub type MigrationToV3 = frame_support::migrations::VersionedMigration< - 2, - 3, - UncheckedMigrationToV3, - Pallet, - ::DbWeight, - >; - - pub fn lazy_migrate_inbound_queue() { - let Some(mut states) = v3::InboundXcmpStatus::::get() else { - log::debug!(target: LOG, "Lazy migration finished: item gone"); - return - }; - let Some(ref mut next) = states.first_mut() else { - log::debug!(target: LOG, "Lazy migration finished: item empty"); - v3::InboundXcmpStatus::::kill(); - return - }; - log::debug!( - "Migrating inbound HRMP channel with sibling {:?}, msgs left {}.", - next.sender, - next.message_metadata.len() + if QueueConfig::::translate(|pre| pre.map(translate)).is_err() { + log::error!( + target: super::LOG_TARGET, + "unexpected error when performing translation of the QueueConfig type during storage upgrade to v2" ); - // We take the last element since the MQ is a FIFO and we want to keep the order. - let Some((block_number, format)) = next.message_metadata.pop() else { - states.remove(0); - v3::InboundXcmpStatus::::put(states); - return - }; - if format != XcmpMessageFormat::ConcatenatedVersionedXcm { - log::warn!(target: LOG, - "Dropping message with format {:?} (not ConcatenatedVersionedXcm)", - format - ); - v3::InboundXcmpMessages::::remove(&next.sender, &block_number); - v3::InboundXcmpStatus::::put(states); - return - } + } - let Some(msg) = v3::InboundXcmpMessages::::take(&next.sender, &block_number) else { - defensive!("Storage corrupted: HRMP message missing:", (next.sender, block_number)); - v3::InboundXcmpStatus::::put(states); - return - }; + T::DbWeight::get().reads_writes(1, 1) +} - let Ok(msg): Result, _> = msg.try_into() else { - log::error!(target: LOG, "Message dropped: too big"); - v3::InboundXcmpStatus::::put(states); - return - }; +pub fn migrate_to_v3() -> Weight { + #[frame_support::storage_alias] + type Overweight = + CountedStorageMap, Twox64Concat, OverweightIndex, ParaId>; + let overweight_messages = Overweight::::initialize_counter() as u64; - // Finally! We have a proper message. - T::XcmpQueue::enqueue_message(msg.as_bounded_slice(), next.sender); - log::debug!(target: LOG, "Migrated HRMP message to MQ: {:?}", (next.sender, block_number)); - v3::InboundXcmpStatus::::put(states); - } + T::DbWeight::get().reads_writes(overweight_messages, 1) } -pub mod v4 { - use super::*; +pub fn lazy_migrate_inbound_queue() { + let Some(mut states) = v3::InboundXcmpStatus::::get() else { + log::debug!(target: LOG, "Lazy migration finished: item gone"); + return + }; + let Some(ref mut next) = states.first_mut() else { + log::debug!(target: LOG, "Lazy migration finished: item empty"); + v3::InboundXcmpStatus::::kill(); + return + }; + log::debug!( + "Migrating inbound HRMP channel with sibling {:?}, msgs left {}.", + next.sender, + next.message_metadata.len() + ); + // We take the last element since the MQ is a FIFO and we want to keep the order. + let Some((block_number, format)) = next.message_metadata.pop() else { + states.remove(0); + v3::InboundXcmpStatus::::put(states); + return + }; + if format != XcmpMessageFormat::ConcatenatedVersionedXcm { + log::warn!(target: LOG, + "Dropping message with format {:?} (not ConcatenatedVersionedXcm)", + format + ); + v3::InboundXcmpMessages::::remove(&next.sender, &block_number); + v3::InboundXcmpStatus::::put(states); + return + } - /// Migrates `QueueConfigData` to v4, removing deprecated fields and bumping page - /// thresholds to at least the default values. - pub struct UncheckedMigrationToV4(PhantomData); - - impl OnRuntimeUpgrade for UncheckedMigrationToV4 { - fn on_runtime_upgrade() -> Weight { - let translate = |pre: v2::QueueConfigData| -> QueueConfigData { - let pre_default = v2::QueueConfigData::default(); - // If the previous values are the default ones, let's replace them with the new - // default. - if pre.suspend_threshold == pre_default.suspend_threshold && - pre.drop_threshold == pre_default.drop_threshold && - pre.resume_threshold == pre_default.resume_threshold - { - return QueueConfigData::default() - } - - // If the previous values are not the default ones, let's leave them as they are. - QueueConfigData { - suspend_threshold: pre.suspend_threshold, - drop_threshold: pre.drop_threshold, - resume_threshold: pre.resume_threshold, - } - }; - - if QueueConfig::::translate(|pre| pre.map(translate)).is_err() { - log::error!( - target: crate::LOG_TARGET, - "unexpected error when performing translation of the QueueConfig type \ - during storage upgrade to v4" - ); - } + let Some(msg) = v3::InboundXcmpMessages::::take(&next.sender, &block_number) else { + defensive!("Storage corrupted: HRMP message missing:", (next.sender, block_number)); + v3::InboundXcmpStatus::::put(states); + return + }; - T::DbWeight::get().reads_writes(1, 1) - } - } + let Ok(msg): Result, _> = msg.try_into() else { + log::error!(target: LOG, "Message dropped: too big"); + v3::InboundXcmpStatus::::put(states); + return + }; - /// [`UncheckedMigrationToV4`] wrapped in a - /// [`VersionedMigration`](frame_support::migrations::VersionedMigration), ensuring the - /// migration is only performed when on-chain version is 3. - pub type MigrationToV4 = frame_support::migrations::VersionedMigration< - 3, - 4, - UncheckedMigrationToV4, - Pallet, - ::DbWeight, - >; + // Finally! We have a proper message. + T::XcmpQueue::enqueue_message(msg.as_bounded_slice(), next.sender); + log::debug!(target: LOG, "Migrated HRMP message to MQ: {:?}", (next.sender, block_number)); + v3::InboundXcmpStatus::::put(states); } -#[cfg(all(feature = "try-runtime", test))] +#[cfg(test)] mod tests { use super::*; use crate::mock::{new_test_ext, Test}; @@ -329,20 +230,14 @@ mod tests { }; new_test_ext().execute_with(|| { - let storage_version = StorageVersion::new(1); - storage_version.put::>(); - frame_support::storage::unhashed::put_raw( &crate::QueueConfig::::hashed_key(), &v1.encode(), ); - let bytes = v2::MigrationToV2::::pre_upgrade(); - assert!(bytes.is_ok()); - v2::MigrationToV2::::on_runtime_upgrade(); - assert!(v2::MigrationToV2::::post_upgrade(bytes.unwrap()).is_ok()); + migrate_to_v2::(); - let v2 = v2::QueueConfig::::get(); + let v2 = crate::QueueConfig::::get(); assert_eq!(v1.suspend_threshold, v2.suspend_threshold); assert_eq!(v1.drop_threshold, v2.drop_threshold); @@ -352,70 +247,4 @@ mod tests { assert_eq!(v1.xcmp_max_individual_weight, v2.xcmp_max_individual_weight.ref_time()); }); } - - #[test] - #[allow(deprecated)] - fn test_migration_to_v4() { - new_test_ext().execute_with(|| { - let storage_version = StorageVersion::new(3); - storage_version.put::>(); - - let v2 = v2::QueueConfigData { - drop_threshold: 5, - suspend_threshold: 2, - resume_threshold: 1, - ..Default::default() - }; - - frame_support::storage::unhashed::put_raw( - &crate::QueueConfig::::hashed_key(), - &v2.encode(), - ); - - let bytes = v4::MigrationToV4::::pre_upgrade(); - assert!(bytes.is_ok()); - v4::MigrationToV4::::on_runtime_upgrade(); - assert!(v4::MigrationToV4::::post_upgrade(bytes.unwrap()).is_ok()); - - let v4 = QueueConfig::::get(); - - assert_eq!( - v4, - QueueConfigData { suspend_threshold: 32, drop_threshold: 48, resume_threshold: 8 } - ); - }); - - new_test_ext().execute_with(|| { - let storage_version = StorageVersion::new(3); - storage_version.put::>(); - - let v2 = v2::QueueConfigData { - drop_threshold: 100, - suspend_threshold: 50, - resume_threshold: 40, - ..Default::default() - }; - - frame_support::storage::unhashed::put_raw( - &crate::QueueConfig::::hashed_key(), - &v2.encode(), - ); - - let bytes = v4::MigrationToV4::::pre_upgrade(); - assert!(bytes.is_ok()); - v4::MigrationToV4::::on_runtime_upgrade(); - assert!(v4::MigrationToV4::::post_upgrade(bytes.unwrap()).is_ok()); - - let v4 = QueueConfig::::get(); - - assert_eq!( - v4, - QueueConfigData { - suspend_threshold: 50, - drop_threshold: 100, - resume_threshold: 40 - } - ); - }); - } } diff --git a/cumulus/pallets/xcmp-queue/src/mock.rs b/cumulus/pallets/xcmp-queue/src/mock.rs index a41be6fa9ca..7c3a3bd1bd0 100644 --- a/cumulus/pallets/xcmp-queue/src/mock.rs +++ b/cumulus/pallets/xcmp-queue/src/mock.rs @@ -19,7 +19,7 @@ use core::marker::PhantomData; use cumulus_pallet_parachain_system::AnyRelayNumber; use cumulus_primitives_core::{ChannelInfo, IsSystem, ParaId}; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, Everything, Nothing, OriginTrait}, BoundedSlice, }; @@ -30,9 +30,7 @@ use sp_runtime::{ BuildStorage, }; use xcm::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter; -use xcm_builder::{FixedWeightBounds, IsConcrete, NativeAsset, ParentIsPreset}; +use xcm_builder::{CurrencyAdapter, FixedWeightBounds, IsConcrete, NativeAsset, ParentIsPreset}; use xcm_executor::traits::ConvertOrigin; type Block = frame_system::mocking::MockBlock; @@ -57,7 +55,6 @@ parameter_types! { type AccountId = u64; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = Everything; type BlockWeights = (); @@ -132,7 +129,6 @@ parameter_types! { } /// Means for transacting assets on this chain. -#[allow(deprecated)] pub type LocalAssetTransactor = CurrencyAdapter< // Use this currency: Balances, diff --git a/cumulus/pallets/xcmp-queue/src/tests.rs b/cumulus/pallets/xcmp-queue/src/tests.rs index 8e8f6e852e1..f88dedc1ece 100644 --- a/cumulus/pallets/xcmp-queue/src/tests.rs +++ b/cumulus/pallets/xcmp-queue/src/tests.rs @@ -22,7 +22,8 @@ use XcmpMessageFormat::*; use codec::Input; use cumulus_primitives_core::{ParaId, XcmpMessageHandler}; use frame_support::{ - assert_err, assert_noop, assert_ok, assert_storage_noop, hypothetically, traits::Hooks, + assert_err, assert_noop, assert_ok, assert_storage_noop, hypothetically, + traits::{Footprint, Hooks}, StorageNoopGuard, }; use mock::{new_test_ext, ParachainSystem, RuntimeOrigin as Origin, Test, XcmpQueue}; @@ -99,7 +100,7 @@ fn xcm_enqueueing_multiple_times_works() { } #[test] -#[cfg_attr(debug_assertions, should_panic = "Could not enqueue XCMP messages.")] +#[cfg_attr(debug_assertions, should_panic = "Defensive failure")] fn xcm_enqueueing_starts_dropping_on_overflow() { new_test_ext().execute_with(|| { let xcm = VersionedXcm::::from(Xcm::(vec![ClearOrigin])); @@ -111,6 +112,12 @@ fn xcm_enqueueing_starts_dropping_on_overflow() { repeat((1000.into(), 1, data.as_slice())).take(limit * 2), Weight::MAX, ); + assert_eq!(EnqueuedMessages::get().len(), limit); + // The drop threshold for pages is 48, the others numbers dont really matter: + assert_eq!( + ::XcmpQueue::footprint(1000.into()), + QueueFootprint { storage: Footprint { count: 256, size: 768 }, pages: 48 } + ); }) } @@ -724,50 +731,6 @@ fn xcmp_queue_send_xcm_works() { }) } -#[test] -fn xcmp_queue_send_too_big_xcm_fails() { - new_test_ext().execute_with(|| { - let sibling_para_id = ParaId::from(12345); - let dest = (Parent, X1(Parachain(sibling_para_id.into()))).into(); - - let max_message_size = 100_u32; - - // open HRMP channel to the sibling_para_id with a set `max_message_size` - ParachainSystem::open_custom_outbound_hrmp_channel_for_benchmarks_or_tests( - sibling_para_id, - cumulus_primitives_core::AbridgedHrmpChannel { - max_message_size, - max_capacity: 10, - max_total_size: 10_000_000_u32, - msg_count: 0, - total_size: 0, - mqc_head: None, - }, - ); - - // Message is crafted to exceed `max_message_size` - let mut message = Xcm::builder_unsafe(); - for _ in 0..97 { - message = message.clear_origin(); - } - let message = message.build(); - let encoded_message_size = message.encode().len(); - let versioned_size = 1; // VersionedXcm enum is added by `send_xcm` and it add one additional byte - assert_eq!(encoded_message_size, max_message_size as usize - versioned_size); - - // check empty outbound queue - assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty()); - - // Message is too big because after adding the VersionedXcm enum, it would reach - // `max_message_size` Then, adding the format, which is the worst case scenario in which a - // new page is needed, would get it over the limit - assert_eq!(send_xcm::(dest, message), Err(SendError::Transport("TooBig")),); - - // outbound queue is still empty - assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty()); - }); -} - #[test] fn verify_fee_factor_increase_and_decrease() { use cumulus_primitives_core::AbridgedHrmpChannel; diff --git a/cumulus/parachain-template/node/Cargo.toml b/cumulus/parachain-template/node/Cargo.toml index 4be848f4d2d..73bbbb6d771 100644 --- a/cumulus/parachain-template/node/Cargo.toml +++ b/cumulus/parachain-template/node/Cargo.toml @@ -10,14 +10,11 @@ edition.workspace = true build = "build.rs" publish = false -[lints] -workspace = true - [dependencies] -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } log = "0.4.20" codec = { package = "parity-scale-codec", version = "3.0.0" } -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } jsonrpsee = { version = "0.16.2", features = ["server"] } futures = "0.3.28" serde_json = "1.0.108" @@ -60,7 +57,7 @@ substrate-prometheus-endpoint = { path = "../../../substrate/utils/prometheus" } # Polkadot polkadot-cli = { path = "../../../polkadot/cli", features = ["rococo-native"] } polkadot-primitives = { path = "../../../polkadot/primitives" } -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } +xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false} # Cumulus cumulus-client-cli = { path = "../../client/cli" } @@ -94,3 +91,4 @@ try-runtime = [ "polkadot-cli/try-runtime", "sp-runtime/try-runtime", ] + diff --git a/cumulus/parachain-template/node/src/cli.rs b/cumulus/parachain-template/node/src/cli.rs index 73ef996b750..098f59b0f37 100644 --- a/cumulus/parachain-template/node/src/cli.rs +++ b/cumulus/parachain-template/node/src/cli.rs @@ -24,11 +24,8 @@ pub enum Subcommand { /// Remove the whole chain. PurgeChain(cumulus_client_cli::PurgeChainCmd), - /// Export the genesis head data of the parachain. - /// - /// Head data is the encoded block header. - #[command(alias = "export-genesis-state")] - ExportGenesisHead(cumulus_client_cli::ExportGenesisHeadCommand), + /// Export the genesis state of the parachain. + ExportGenesisState(cumulus_client_cli::ExportGenesisStateCommand), /// Export the genesis wasm of the parachain. ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand), diff --git a/cumulus/parachain-template/node/src/command.rs b/cumulus/parachain-template/node/src/command.rs index 6ddb68a359a..4dd8463f6be 100644 --- a/cumulus/parachain-template/node/src/command.rs +++ b/cumulus/parachain-template/node/src/command.rs @@ -162,12 +162,12 @@ pub fn run() -> Result<()> { cmd.run(config, polkadot_config) }) }, - Some(Subcommand::ExportGenesisHead(cmd)) => { + Some(Subcommand::ExportGenesisState(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| { let partials = new_partial(&config)?; - cmd.run(partials.client) + cmd.run(&*config.chain_spec, &*partials.client) }) }, Some(Subcommand::ExportGenesisWasm(cmd)) => { diff --git a/cumulus/parachain-template/node/src/rpc.rs b/cumulus/parachain-template/node/src/rpc.rs index ed4003ed6d2..b5ca484fa48 100644 --- a/cumulus/parachain-template/node/src/rpc.rs +++ b/cumulus/parachain-template/node/src/rpc.rs @@ -9,6 +9,7 @@ use std::sync::Arc; use parachain_template_runtime::{opaque::Block, AccountId, Balance, Nonce}; +use sc_client_api::AuxStore; pub use sc_rpc::{DenyUnsafe, SubscriptionTaskExecutor}; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; @@ -35,6 +36,7 @@ pub fn create_full( where C: ProvideRuntimeApi + HeaderBackend + + AuxStore + HeaderMetadata + Send + Sync diff --git a/cumulus/parachain-template/pallets/template/Cargo.toml b/cumulus/parachain-template/pallets/template/Cargo.toml index bd7f926d039..92545783934 100644 --- a/cumulus/parachain-template/pallets/template/Cargo.toml +++ b/cumulus/parachain-template/pallets/template/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true edition.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,20 +16,20 @@ codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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 } +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} [dev-dependencies] -serde = { version = "1.0.193" } +serde = { version = "1.0.188" } # Substrate -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-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] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", diff --git a/cumulus/parachain-template/pallets/template/src/mock.rs b/cumulus/parachain-template/pallets/template/src/mock.rs index 411a16b116c..8fae1019f42 100644 --- a/cumulus/parachain-template/pallets/template/src/mock.rs +++ b/cumulus/parachain-template/pallets/template/src/mock.rs @@ -1,4 +1,4 @@ -use frame_support::{derive_impl, parameter_types, traits::Everything}; +use frame_support::{parameter_types, traits::Everything}; use frame_system as system; use sp_core::H256; use sp_runtime::{ @@ -22,7 +22,6 @@ parameter_types! { pub const SS58Prefix: u8 = 42; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl system::Config for Test { type BaseCallFilter = Everything; type BlockWeights = (); diff --git a/cumulus/parachain-template/runtime/Cargo.toml b/cumulus/parachain-template/runtime/Cargo.toml index 3944ff4ca08..01e25007873 100644 --- a/cumulus/parachain-template/runtime/Cargo.toml +++ b/cumulus/parachain-template/runtime/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true edition.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -28,48 +25,48 @@ smallvec = "1.11.0" pallet-parachain-template = { path = "../pallets/template", 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 } +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-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 } -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 } +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} +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-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} # 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 = { 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} # Cumulus cumulus-pallet-aura-ext = { path = "../../pallets/aura-ext", default-features = false } cumulus-pallet-dmp-queue = { path = "../../pallets/dmp-queue", default-features = false } -cumulus-pallet-parachain-system = { path = "../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } -cumulus-pallet-session-benchmarking = { path = "../../pallets/session-benchmarking", default-features = false } +cumulus-pallet-parachain-system = { path = "../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } +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 } @@ -79,7 +76,7 @@ parachains-common = { path = "../../parachains/common", default-features = false parachain-info = { package = "staging-parachain-info", path = "../../parachains/pallets/parachain-info", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-pallet-aura-ext/std", @@ -186,4 +183,4 @@ try-runtime = [ "sp-runtime/try-runtime", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] diff --git a/cumulus/parachain-template/runtime/src/lib.rs b/cumulus/parachain-template/runtime/src/lib.rs index bf64acb4883..6646a87acde 100644 --- a/cumulus/parachain-template/runtime/src/lib.rs +++ b/cumulus/parachain-template/runtime/src/lib.rs @@ -16,7 +16,7 @@ use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, - traits::{BlakeTwo256, Block as BlockT, IdentifyAccount, Verify}, + traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, MultiSignature, }; @@ -28,11 +28,13 @@ use sp_version::RuntimeVersion; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, parameter_types, - traits::{ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, TransformOrigin}, + traits::{ + ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, Everything, TransformOrigin, + }, weights::{ constants::WEIGHT_REF_TIME_PER_SECOND, ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, @@ -273,27 +275,45 @@ parameter_types! { pub const SS58Prefix: u16 = 42; } -/// The default types are being injected by [`derive_impl`](`frame_support::derive_impl`) from -/// [`ParaChainDefaultConfig`](`struct@frame_system::config_preludes::ParaChainDefaultConfig`), -/// but overridden as needed. -#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig as frame_system::DefaultConfig)] +// Configure FRAME pallets to include in runtime. + impl frame_system::Config for Runtime { /// The identifier used to distinguish between accounts. type AccountId = AccountId; + /// The aggregated dispatch type that is available for extrinsics. + type RuntimeCall = RuntimeCall; + /// The lookup mechanism to get account ID from whatever is passed in dispatchers. + type Lookup = AccountIdLookup; /// The index type for storing how many extrinsics an account has signed. type Nonce = Nonce; /// The type for hashing blocks and tries. type Hash = Hash; + /// The hashing algorithm used. + type Hashing = BlakeTwo256; /// The block type. type Block = Block; + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + /// The ubiquitous origin type. + type RuntimeOrigin = RuntimeOrigin; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). type BlockHashCount = BlockHashCount; /// Runtime version. type Version = Version; + /// Converts a module to an index of this module in the runtime. + type PalletInfo = PalletInfo; /// The data to be stored in an account. type AccountData = pallet_balances::AccountData; + /// What to do if a new account is created. + type OnNewAccount = (); + /// What to do if an account is fully reaped from the system. + type OnKilledAccount = (); /// The weight of database operations that the runtime can invoke. type DbWeight = RocksDbWeight; + /// The basic call filter to use in dispatchable. + type BaseCallFilter = Everything; + /// Weight information for the extrinsics of this pallet. + type SystemWeightInfo = (); /// Block & extrinsics weights: base values and limits. type BlockWeights = RuntimeBlockWeights; /// The maximum length of a block (in bytes). @@ -493,7 +513,8 @@ impl pallet_parachain_template::Config for Runtime { // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( - pub struct Runtime { + pub enum Runtime + { // System support stuff. System: frame_system = 0, ParachainSystem: cumulus_pallet_parachain_system = 1, diff --git a/cumulus/parachain-template/runtime/src/xcm_config.rs b/cumulus/parachain-template/runtime/src/xcm_config.rs index 7d1a748819c..752137c96f1 100644 --- a/cumulus/parachain-template/runtime/src/xcm_config.rs +++ b/cumulus/parachain-template/runtime/src/xcm_config.rs @@ -12,15 +12,13 @@ use pallet_xcm::XcmPassthrough; use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::impls::ToAuthor; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, - DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FixedWeightBounds, IsConcrete, - NativeAsset, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, - SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, - SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, - WithComputedOrigin, WithUniqueTopic, + CurrencyAdapter, DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, + FixedWeightBounds, IsConcrete, NativeAsset, ParentIsPreset, RelayChainAsNative, + SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, + UsingComponents, WithComputedOrigin, WithUniqueTopic, }; use xcm_executor::XcmExecutor; @@ -44,7 +42,6 @@ pub type LocationToAccountId = ( ); /// Means for transacting assets on this chain. -#[allow(deprecated)] pub type LocalAssetTransactor = CurrencyAdapter< // Use this currency: Balances, diff --git a/cumulus/parachains/chain-specs/asset-hub-kusama.json b/cumulus/parachains/chain-specs/asset-hub-kusama.json index fba74b17f96..946bfc5983d 100644 --- a/cumulus/parachains/chain-specs/asset-hub-kusama.json +++ b/cumulus/parachains/chain-specs/asset-hub-kusama.json @@ -22,10 +22,7 @@ "/dns/statemine-boot-ng.dwellir.com/tcp/30343/p2p/12D3KooWQNJKBaNfW6Nn7HZDi5pSSEFmHL2Qz7chr9RksQUDR1Wk", "/dns/statemine-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWQNJKBaNfW6Nn7HZDi5pSSEFmHL2Qz7chr9RksQUDR1Wk", "/dns/statemine-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWCKUrE5uaXQ288ko3Ex3zCyozyJLG47KEYTopinnXNtYL", - "/dns/statemine-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWCKUrE5uaXQ288ko3Ex3zCyozyJLG47KEYTopinnXNtYL", - "/dns/mine14.rotko.net/tcp/33524/p2p/12D3KooWJUFnjR2PNbsJhudwPVaWCoZy1acPGKjM2cSuGj345BBu", - "/dns/mine14.rotko.net/tcp/34524/ws/p2p/12D3KooWJUFnjR2PNbsJhudwPVaWCoZy1acPGKjM2cSuGj345BBu", - "/dns/mine14.rotko.net/tcp/35524/wss/p2p/12D3KooWJUFnjR2PNbsJhudwPVaWCoZy1acPGKjM2cSuGj345BBu" + "/dns/statemine-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWCKUrE5uaXQ288ko3Ex3zCyozyJLG47KEYTopinnXNtYL" ], "telemetryEndpoints": null, "protocolId": null, diff --git a/cumulus/parachains/chain-specs/asset-hub-polkadot.json b/cumulus/parachains/chain-specs/asset-hub-polkadot.json index 685a00ddc71..c26506eb995 100644 --- a/cumulus/parachains/chain-specs/asset-hub-polkadot.json +++ b/cumulus/parachains/chain-specs/asset-hub-polkadot.json @@ -22,10 +22,7 @@ "/dns/statemint-boot-ng.dwellir.com/tcp/30344/p2p/12D3KooWEFrNuNk8fPdQS2hf34Gmqi6dGSvrETshGJUrqrvfRDZr", "/dns/statemint-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWEFrNuNk8fPdQS2hf34Gmqi6dGSvrETshGJUrqrvfRDZr", "/dns/statemint-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWLKxHom7f3XawRJqrF8RwiKK5Sj3qZqz5c7hF6eJeXhTx", - "/dns/statemint-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWLKxHom7f3XawRJqrF8RwiKK5Sj3qZqz5c7hF6eJeXhTx", - "/dns/mint14.rotko.net/tcp/33514/p2p/12D3KooWKkzLjYF6M5eEs7nYiqEtRqY8SGVouoCwo3nCWsRnThDW", - "/dns/mint14.rotko.net/tcp/34514/ws/p2p/12D3KooWKkzLjYF6M5eEs7nYiqEtRqY8SGVouoCwo3nCWsRnThDW", - "/dns/mint14.rotko.net/tcp/35514/wss/p2p/12D3KooWKkzLjYF6M5eEs7nYiqEtRqY8SGVouoCwo3nCWsRnThDW" + "/dns/statemint-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWLKxHom7f3XawRJqrF8RwiKK5Sj3qZqz5c7hF6eJeXhTx" ], "telemetryEndpoints": null, "protocolId": null, diff --git a/cumulus/parachains/chain-specs/asset-hub-westend.json b/cumulus/parachains/chain-specs/asset-hub-westend.json index 6f42b5f7d8b..f0e71981e7a 100644 --- a/cumulus/parachains/chain-specs/asset-hub-westend.json +++ b/cumulus/parachains/chain-specs/asset-hub-westend.json @@ -20,10 +20,7 @@ "/dns/westmint-boot-ng.dwellir.com/tcp/30345/p2p/12D3KooWFZ9xqApB1wnFYkbe1qJ5Jqwxe2f3i8W25F3tKNXy59ux", "/dns/westmint-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWFZ9xqApB1wnFYkbe1qJ5Jqwxe2f3i8W25F3tKNXy59ux", "/dns/westmint-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWDoq4PVdWm5nzRSvEz3DSSKjVgRhWVUaKyi5JMKwJKYbk", - "/dns/westmint-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWDoq4PVdWm5nzRSvEz3DSSKjVgRhWVUaKyi5JMKwJKYbk", - "/dns/wmint14.rotko.net/tcp/33534/p2p/12D3KooWE4UDXqgtTcMCyUQ8S4uvaT8VMzzTBA6NWmKuYwTacWuN", - "/dns/wmint14.rotko.net/tcp/34534/ws/p2p/12D3KooWE4UDXqgtTcMCyUQ8S4uvaT8VMzzTBA6NWmKuYwTacWuN", - "/dns/wmint14.rotko.net/tcp/35534/wss/p2p/12D3KooWE4UDXqgtTcMCyUQ8S4uvaT8VMzzTBA6NWmKuYwTacWuN" + "/dns/westmint-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWDoq4PVdWm5nzRSvEz3DSSKjVgRhWVUaKyi5JMKwJKYbk" ], "telemetryEndpoints": null, "protocolId": null, diff --git a/cumulus/parachains/chain-specs/bridge-hub-kusama.json b/cumulus/parachains/chain-specs/bridge-hub-kusama.json index 0ef81806cc5..9daa60fa263 100644 --- a/cumulus/parachains/chain-specs/bridge-hub-kusama.json +++ b/cumulus/parachains/chain-specs/bridge-hub-kusama.json @@ -22,10 +22,7 @@ "/dns/kusama-bridge-hub-boot-ng.dwellir.com/tcp/30337/p2p/12D3KooWBFskNCQDVjuUeBh6vrszWrUvYMBBhtZRLnoTZDdLYbW5", "/dns/kusama-bridge-hub-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWBFskNCQDVjuUeBh6vrszWrUvYMBBhtZRLnoTZDdLYbW5", "/dns/bridgehub-kusama-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWQMWofXj8v3RroDNnrhv1iURqm8vnaG98AdGnCn2YoDcW", - "/dns/bridgehub-kusama-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWQMWofXj8v3RroDNnrhv1iURqm8vnaG98AdGnCn2YoDcW", - "/dns/kbr13.rotko.net/tcp/33553/p2p/12D3KooWAmBp54mUEYtvsk2kxNEsDbAvdUMcaghxKXgUQxmPEQ66", - "/dns/kbr13.rotko.net/tcp/34553/ws/p2p/12D3KooWAmBp54mUEYtvsk2kxNEsDbAvdUMcaghxKXgUQxmPEQ66", - "/dns/kbr13.rotko.net/tcp/35553/wss/p2p/12D3KooWAmBp54mUEYtvsk2kxNEsDbAvdUMcaghxKXgUQxmPEQ66" + "/dns/bridgehub-kusama-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWQMWofXj8v3RroDNnrhv1iURqm8vnaG98AdGnCn2YoDcW" ], "telemetryEndpoints": null, "protocolId": null, diff --git a/cumulus/parachains/chain-specs/bridge-hub-polkadot.json b/cumulus/parachains/chain-specs/bridge-hub-polkadot.json index 130bdf31ef2..d3e884284b4 100644 --- a/cumulus/parachains/chain-specs/bridge-hub-polkadot.json +++ b/cumulus/parachains/chain-specs/bridge-hub-polkadot.json @@ -18,10 +18,7 @@ "/dns/boot-node.helikon.io/tcp/8220/p2p/12D3KooWC38TZJA8ZBXZgAYVrceoJ56jNNLJPdpk3ojeFkTAwZVp", "/dns/boot-node.helikon.io/tcp/8222/wss/p2p/12D3KooWC38TZJA8ZBXZgAYVrceoJ56jNNLJPdpk3ojeFkTAwZVp", "/dns/bridgehub-polkadot-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWPNZm78tWUmKbta3SXdkqTPsquRc8ekEbJjZsGGi7YiRi", - "/dns/bridgehub-polkadot-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWPNZm78tWUmKbta3SXdkqTPsquRc8ekEbJjZsGGi7YiRi", - "/dns/pbr13.rotko.net/tcp/33543/p2p/12D3KooWMxZY7tDc2Rh454VaJJ7RexKAXVS6xSBEvTnXSGCnuGDw", - "/dns/pbr13.rotko.net/tcp/34543/ws/p2p/12D3KooWMxZY7tDc2Rh454VaJJ7RexKAXVS6xSBEvTnXSGCnuGDw", - "/dns/pbr13.rotko.net/tcp/35543/wss/p2p/12D3KooWMxZY7tDc2Rh454VaJJ7RexKAXVS6xSBEvTnXSGCnuGDw" + "/dns/bridgehub-polkadot-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWPNZm78tWUmKbta3SXdkqTPsquRc8ekEbJjZsGGi7YiRi" ], "telemetryEndpoints": null, "protocolId": null, diff --git a/cumulus/parachains/chain-specs/bridge-hub-westend.json b/cumulus/parachains/chain-specs/bridge-hub-westend.json index 018ab0ee6fd..dde3d437f41 100644 --- a/cumulus/parachains/chain-specs/bridge-hub-westend.json +++ b/cumulus/parachains/chain-specs/bridge-hub-westend.json @@ -16,10 +16,7 @@ "/dns/boot-node.helikon.io/tcp/9220/p2p/12D3KooWK3K1Mu5Jjg96Lt9DUzg84KsWnZo44V4KB7mvhGqi6xnp", "/dns/boot-node.helikon.io/tcp/9222/wss/p2p/12D3KooWK3K1Mu5Jjg96Lt9DUzg84KsWnZo44V4KB7mvhGqi6xnp", "/dns/bridgehub-westend-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWBsBArCMxmQyo3feCEqMWuwyhb2LTRK8hmCCJxgrNeMke", - "/dns/bridgehub-westend-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWBsBArCMxmQyo3feCEqMWuwyhb2LTRK8hmCCJxgrNeMke", - "/dns/wbr13.rotko.net/tcp/33563/p2p/12D3KooWJyeRHpxZZbfBCNEgeUFzmRC5AMSAs2tJhjJS1k5hULkD", - "/dns/wbr13.rotko.net/tcp/34563/ws/p2p/12D3KooWJyeRHpxZZbfBCNEgeUFzmRC5AMSAs2tJhjJS1k5hULkD", - "/dns/wbr13.rotko.net/tcp/35563/wss/p2p/12D3KooWJyeRHpxZZbfBCNEgeUFzmRC5AMSAs2tJhjJS1k5hULkD" + "/dns/bridgehub-westend-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWBsBArCMxmQyo3feCEqMWuwyhb2LTRK8hmCCJxgrNeMke" ], "telemetryEndpoints": null, "protocolId": null, diff --git a/cumulus/parachains/chain-specs/collectives-polkadot.json b/cumulus/parachains/chain-specs/collectives-polkadot.json index e9f690234e4..003c6373429 100644 --- a/cumulus/parachains/chain-specs/collectives-polkadot.json +++ b/cumulus/parachains/chain-specs/collectives-polkadot.json @@ -22,10 +22,7 @@ "/dns/polkadot-collectives-boot-ng.dwellir.com/tcp/30341/p2p/12D3KooWDMFYCNRAQcSRNV7xu2xv8319goSEbSHW4TnXRz6EpPKc", "/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/collectives-polkadot-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWDumvnNwPbBg5inBEapgjKU7ECdMHHgwfYeGWUkzYUE1c" ], "telemetryEndpoints": null, "protocolId": null, diff --git a/cumulus/parachains/chain-specs/collectives-westend.json b/cumulus/parachains/chain-specs/collectives-westend.json index 7385889f0ec..e06671faa04 100644 --- a/cumulus/parachains/chain-specs/collectives-westend.json +++ b/cumulus/parachains/chain-specs/collectives-westend.json @@ -20,10 +20,7 @@ "/dns/collectives-westend.bootnode.amforc.com/tcp/30340/p2p/12D3KooWERPzUhHau6o2XZRUi3tn7544rYiaHL418Nw5t8fYWP1F", "/dns/collectives-westend.bootnode.amforc.com/tcp/30333/wss/p2p/12D3KooWERPzUhHau6o2XZRUi3tn7544rYiaHL418Nw5t8fYWP1F", "/dns/westend-collectives-boot-ng.dwellir.com/tcp/30340/p2p/12D3KooWPFM93jgm4pgxx8PM8WJKAJF49qia8jRB95uciUQwYh7m", - "/dns/westend-collectives-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWPFM93jgm4pgxx8PM8WJKAJF49qia8jRB95uciUQwYh7m", - "/dns/wch13.rotko.net/tcp/33593/p2p/12D3KooWPG85zhuSRoyptjLkFD4iJFistjiBmc15JgQ96B4fdXYr", - "/dns/wch13.rotko.net/tcp/34593/ws/p2p/12D3KooWPG85zhuSRoyptjLkFD4iJFistjiBmc15JgQ96B4fdXYr", - "/dns/wch13.rotko.net/tcp/35593/wss/p2p/12D3KooWPG85zhuSRoyptjLkFD4iJFistjiBmc15JgQ96B4fdXYr" + "/dns/westend-collectives-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWPFM93jgm4pgxx8PM8WJKAJF49qia8jRB95uciUQwYh7m" ], "telemetryEndpoints": null, "protocolId": null, diff --git a/cumulus/parachains/common/Cargo.toml b/cumulus/parachains/common/Cargo.toml index dcaea40d2da..4aad4dec236 100644 --- a/cumulus/parachains/common/Cargo.toml +++ b/cumulus/parachains/common/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true description = "Logic which is common to all parachain runtimes" license = "Apache-2.0" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -16,7 +13,7 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"], default-features = false } log = { version = "0.4.19", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -num-traits = { version = "0.2", default-features = false } +num-traits = { version = "0.2", default-features = false} smallvec = "1.11.0" # Substrate @@ -34,12 +31,12 @@ sp-runtime = { path = "../../../substrate/primitives/runtime", default-features sp-std = { path = "../../../substrate/primitives/std", default-features = false } # Polkadot -rococo-runtime-constants = { path = "../../../polkadot/runtime/rococo/constants", default-features = false } -westend-runtime-constants = { path = "../../../polkadot/runtime/westend/constants", default-features = false } -polkadot-core-primitives = { path = "../../../polkadot/core-primitives", default-features = false } -polkadot-primitives = { path = "../../../polkadot/primitives", 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 } +rococo-runtime-constants = { path = "../../../polkadot/runtime/rococo/constants", default-features = false} +westend-runtime-constants = { path = "../../../polkadot/runtime/westend/constants", default-features = false} +polkadot-core-primitives = { path = "../../../polkadot/core-primitives", default-features = false} +polkadot-primitives = { path = "../../../polkadot/primitives", 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} # Cumulus pallet-collator-selection = { path = "../../pallets/collator-selection", default-features = false } @@ -48,14 +45,14 @@ cumulus-primitives-utility = { path = "../../primitives/utility", default-featur parachain-info = { package = "staging-parachain-info", path = "../pallets/parachain-info", default-features = false } [dev-dependencies] -pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } +pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false} +sp-io = { path = "../../../substrate/primitives/io", default-features = false} [build-dependencies] substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-primitives-core/std", diff --git a/cumulus/parachains/common/src/impls.rs b/cumulus/parachains/common/src/impls.rs index 50cb1c7f3e8..81d78baba54 100644 --- a/cumulus/parachains/common/src/impls.rs +++ b/cumulus/parachains/common/src/impls.rs @@ -122,7 +122,7 @@ impl> ContainsPair for AssetsFr mod tests { use super::*; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, FindAuthor, ValidatorRegistration}, PalletId, }; @@ -155,7 +155,6 @@ mod tests { pub const MaxReserves: u32 = 50; } - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; diff --git a/cumulus/parachains/common/src/polkadot.rs b/cumulus/parachains/common/src/polkadot.rs index ca413830342..744108bce2e 100644 --- a/cumulus/parachains/common/src/polkadot.rs +++ b/cumulus/parachains/common/src/polkadot.rs @@ -31,8 +31,6 @@ pub mod account { /// It is used as a temporarily place to deposit a slashed imbalance /// before the teleport to the Treasury. pub const AMBASSADOR_REFERENDA_PALLET_ID: PalletId = PalletId(*b"py/amref"); - /// Fellowship treasury pallet ID - pub const FELLOWSHIP_TREASURY_PALLET_ID: PalletId = PalletId(*b"py/feltr"); } /// Consensus-related. diff --git a/cumulus/parachains/common/src/westend.rs b/cumulus/parachains/common/src/westend.rs index 2bd4d18a15e..9d3e0bd1a0e 100644 --- a/cumulus/parachains/common/src/westend.rs +++ b/cumulus/parachains/common/src/westend.rs @@ -13,26 +13,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -/// Universally recognized accounts. -pub mod account { - use frame_support::PalletId; - - /// Westend treasury pallet id, used to convert into AccountId - in Westend as a destination for - /// slashed funds. - pub const WESTEND_TREASURY_PALLET_ID: PalletId = PalletId(*b"py/trsry"); - /// Alliance pallet ID - used as a temporary place to deposit a slashed imbalance before the - /// teleport to the Treasury. - pub const ALLIANCE_PALLET_ID: PalletId = PalletId(*b"py/allia"); - /// Referenda pallet ID - used as a temporary place to deposit a slashed imbalance before the - /// teleport to the Treasury. - pub const REFERENDA_PALLET_ID: PalletId = PalletId(*b"py/refer"); - /// Ambassador Referenda pallet ID - used as a temporary place to deposit a slashed imbalance - /// before the teleport to the Treasury. - pub const AMBASSADOR_REFERENDA_PALLET_ID: PalletId = PalletId(*b"py/amref"); - /// Fellowship treasury pallet ID. - pub const FELLOWSHIP_TREASURY_PALLET_ID: PalletId = PalletId(*b"py/feltr"); -} - pub mod currency { use polkadot_core_primitives::Balance; use westend_runtime_constants as constants; @@ -41,7 +21,6 @@ pub mod currency { pub const EXISTENTIAL_DEPOSIT: Balance = constants::currency::EXISTENTIAL_DEPOSIT / 10; pub const UNITS: Balance = constants::currency::UNITS; - pub const DOLLARS: Balance = UNITS; // 1_000_000_000_000 pub const CENTS: Balance = constants::currency::CENTS; pub const MILLICENTS: Balance = constants::currency::MILLICENTS; pub const GRAND: Balance = constants::currency::GRAND; @@ -65,7 +44,7 @@ pub mod fee { use smallvec::smallvec; pub use sp_runtime::Perbill; - /// The block saturation level. Fees will be updated based on this value. + /// The block saturation level. Fees will be updates based on this value. pub const TARGET_BLOCK_FULLNESS: Perbill = Perbill::from_percent(25); /// Handles converting a weight scalar to a fee value, based on the scale and granularity of the @@ -131,11 +110,11 @@ pub mod fee { /// Consensus-related. pub mod consensus { - /// Maximum number of blocks simultaneously accepted by the Runtime, not yet included into the - /// relay chain. + /// Maximum number of blocks simultaneously accepted by the Runtime, not yet included + /// into the relay chain. pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 1; - /// How many parachain blocks are processed by the relay chain per parent. Limits the number of - /// blocks authored per slot. + /// How many parachain blocks are processed by the relay chain per parent. Limits the + /// number of blocks authored per slot. pub const BLOCK_PROCESSING_VELOCITY: u32 = 1; /// Relay chain slot duration, in milliseconds. pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000; diff --git a/cumulus/parachains/common/src/xcm_config.rs b/cumulus/parachains/common/src/xcm_config.rs index 7a63e720b07..4b0215d672b 100644 --- a/cumulus/parachains/common/src/xcm_config.rs +++ b/cumulus/parachains/common/src/xcm_config.rs @@ -100,25 +100,6 @@ impl, Runtime: parachain_info::C } } -/// Contains all sibling system parachains, including the one where this matcher is used. -/// -/// This structure can only be used at a parachain level. In the Relay Chain, please use -/// the `xcm_builder::IsChildSystemParachain` matcher. -pub struct AllSiblingSystemParachains; - -impl Contains for AllSiblingSystemParachains { - fn contains(l: &MultiLocation) -> bool { - log::trace!(target: "xcm::contains", "AllSiblingSystemParachains location: {:?}", l); - match *l { - // System parachain - MultiLocation { parents: 1, interior: X1(Parachain(id)) } => - ParaId::from(id).is_system(), - // Everything else - _ => false, - } - } -} - /// Accepts an asset if it is a concrete asset from the system (Relay Chain or system parachain). pub struct ConcreteAssetFromSystem(PhantomData); impl> ContainsPair @@ -139,31 +120,14 @@ impl> ContainsPair } } -/// Filter to check if a given location is the parent Relay Chain or a sibling parachain. -/// -/// This type should only be used within the context of a parachain, since it does not verify that -/// the parent is indeed a Relay Chain. -pub struct ParentRelayOrSiblingParachains; -impl Contains for ParentRelayOrSiblingParachains { - fn contains(location: &MultiLocation) -> bool { - matches!( - location, - MultiLocation { parents: 1, interior: Here } | - MultiLocation { parents: 1, interior: X1(Parachain(_)) } - ) - } -} - #[cfg(test)] mod tests { - use frame_support::{parameter_types, traits::Contains}; + use frame_support::parameter_types; use super::{ - AllSiblingSystemParachains, ConcreteAssetFromSystem, ContainsPair, GeneralIndex, Here, - MultiAsset, MultiLocation, PalletInstance, Parachain, Parent, + ConcreteAssetFromSystem, ContainsPair, GeneralIndex, Here, MultiAsset, MultiLocation, + PalletInstance, Parachain, Parent, }; - use polkadot_primitives::LOWEST_PUBLIC_ID; - use xcm::latest::prelude::*; parameter_types! { pub const RelayLocation: MultiLocation = MultiLocation::parent(); @@ -216,19 +180,4 @@ mod tests { ); } } - - #[test] - fn all_sibling_system_parachains_works() { - // system parachain - assert!(AllSiblingSystemParachains::contains(&MultiLocation::new(1, X1(Parachain(1))))); - // non-system parachain - assert!(!AllSiblingSystemParachains::contains(&MultiLocation::new( - 1, - X1(Parachain(LOWEST_PUBLIC_ID.into())) - ))); - // when used at relay chain - assert!(!AllSiblingSystemParachains::contains(&MultiLocation::new(0, X1(Parachain(1))))); - // when used with non-parachain - assert!(!AllSiblingSystemParachains::contains(&MultiLocation::new(1, X1(OnlyChild)))); - } } diff --git a/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/0_init.yml b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/0_init.yml new file mode 100644 index 00000000000..fdc1aa258d4 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/0_init.yml @@ -0,0 +1,145 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9900 + assets_parachain: &assets_parachain + wsPort: 9910 + paraId: &ap_id 1000 + penpal_parachain: &penpal_parachain + wsPort: 9920 + paraId: &pp_id 2000 + variables: + common: + xcm_version: &xcm_version 3 + require_weight_at_most: &weight_at_most {refTime: 1000000000, proofSize: 200000} + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + chains: + relay_chain: + signer: &rc_signer //Alice + assets_parachain_destination: &ap_dest { v3: { 0, interior: { x1: { parachain: *ap_id }}}} + penpal_parachain: + signer: &pp_signer //Alice + decodedCalls: + ap_force_xcm_version: + chain: *assets_parachain + pallet: polkadotXcm + call: forceXcmVersion + args: [ + { # location + parents: 1, + interior: Here + }, + *xcm_version # xcmVersion + ] + +tests: + - name: Initialize Chains + its: + - name: XCM supported versions between chains + actions: + - extrinsics: # Relay Chain sets supported version for Asset Parachain + - chain: *relay_chain + sudo: true + signer: *rc_signer + pallet: xcmPallet + call: forceXcmVersion + args: [ + { # location + parents: 0, + interior: { + X1: { + Parachain: *ap_id + } + } + }, + *xcm_version # xcmVersion + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.SupportedVersionChanged + result: { location: { parents: 0, interior: { X1: { Parachain: *ap_id }}}, version: *xcm_version } + - extrinsics: # Relay Chain sets supported version for Penpal Parachain + - chain: *relay_chain + sudo: true + signer: *rc_signer + pallet: xcmPallet + call: forceXcmVersion + args: [ + { # location + parents: 0, + interior: { + X1: { + Parachain: *pp_id + } + } + }, + *xcm_version # xcmVersion + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.SupportedVersionChanged + result: { location: { parents: 0, interior: { X1: { Parachain: *pp_id }}}, version: *xcm_version } + - extrinsics: # Asset Parachain sets supported version for Relay Chain through it + - chain: *relay_chain + signer: *rc_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + *ap_dest, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: { + limited: { + refTime: 2200000000, + proofSize: 200000 + } + } + } + }, + { + Transact: { + originKind: Superuser, + requireWeightAtMost: *weight_at_most, + call: $ap_force_xcm_version + } + } + ] + } + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.Sent + - name: dmpQueue.ExecutedDownward + chain: *assets_parachain + threshold: *weight_threshold + result: { + outcome: { Complete: { refTime: '1,019,210,000', proofSize: '200,000' }} + } + - name: polkadotXcm.SupportedVersionChanged + chain: *assets_parachain + result: { location: { parents: 1, interior: Here }, version: *xcm_version } + - extrinsics: # Penpal Parachain sets supported version for Relay Chain + - chain: *penpal_parachain + signer: *pp_signer + sudo: true + pallet: polkadotXcm + call: forceXcmVersion + args: [ + { # location + parents: 1, + interior: Here + }, + *xcm_version # xcmVersion + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: polkadotXcm.SupportedVersionChanged + result: { location: { parents: 1, interior: Here }, version: *xcm_version } diff --git a/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/1_dmp.yml b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/1_dmp.yml new file mode 100644 index 00000000000..0e207e632a0 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/1_dmp.yml @@ -0,0 +1,263 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9900 + assets_parachain: &assets_parachain + wsPort: 9910 + paraId: &ap_id 1000 + variables: + common: + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + chains: + relay_chain: + signer: &rc_signer //Alice + wallet: &rc_wallet HNZata7iMYWmk5RvZRTiAsSDhV8366zq2YGb3tLH5Upf74F + assets_parachain_destination: &ap_dest { v3: { parents: 0, interior: { x1: { parachain: *ap_id }}}} + assets_parachain_account: &ap_acc '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' + assets_parachain_beneficiary: &ap_benf { v3: { parents: 0, interior: { x1: { accountId32: { id: *ap_acc }}}}} + ksm: &rc_ksm { concrete: { parents: 0, interior: { here: true }}} + amount: &amount 1000000000000 + ksm_fungible: &rc_ksm_fungible { id: *rc_ksm, fun: { fungible: *amount }} + require_weight_at_most: &rc_weight_at_most { refTime: 1000000000, proofSize: 200000 } + assets_parachain_account: + wallet: &ap_wallet HNZata7iMYWmk5RvZRTiAsSDhV8366zq2YGb3tLH5Upf74F + asset_id: &asset_id 1 + asset_min_balance: &asset_ed 1000 + decodedCalls: + force_create_asset: + chain: *assets_parachain + pallet: assets + call: forceCreate + args: [ + *asset_id, + { Id: *ap_wallet }, # owner + true, # isSufficient + *asset_ed # minBalance + ] + +tests: + - name: DMP + its: [] + describes: + - name: xcmPallet.limitedTeleportAssets + before: &before_get_balances + - name: Get the balances of the Relay Chain's sender & Assets Parachain's receiver + actions: + - queries: + balance_rc_sender_before: + chain: *relay_chain + pallet: system + call: account + args: [ *rc_wallet ] + balance_ap_receiver_before: + chain: *assets_parachain + pallet: system + call: account + args: [ *ap_wallet ] + its: + - name: Should teleport native assets from the Relay Chain to the Assets Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + pallet: xcmPallet + call: limitedTeleportAssets + args: [ + *ap_dest, # destination + *ap_benf, # beneficiary + { v3: [ *rc_ksm_fungible ] }, + 0, # feeAssetItem + { unlimited: true } # weightLimit + ] + events: + - name: xcmPallet.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '764,772,000', proofSize: 0 }}} + - name: dmpQueue.ExecutedDownward + chain: *assets_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '166,944,000', proofSize: 0 }}} + - queries: + balance_rc_sender_after: + chain: *relay_chain + pallet: system + call: account + args: [ *rc_wallet ] + balance_ap_receiver_after: + chain: *assets_parachain + pallet: system + call: account + args: [ *ap_wallet ] + + - name: Should reduce the balance of the sender + actions: + - asserts: + balanceDecreased: + args: [ + { + balances: { + before: $balance_rc_sender_before, + after: $balance_rc_sender_after, + }, + amount: *amount + } + ] + + - name: Should increase the balance of the receiver + actions: + - asserts: + balanceIncreased: + args: [ + { + balances: { + before: $balance_ap_receiver_before, + after: $balance_ap_receiver_after, + } + } + ] + + - name: xcmPallet.send | Superuser - Transact(assets.forceCreate) + its: + - name: Relay Chain Superuser account SHOULD be able to execute a XCM Transact instruction in the Assets Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + *ap_dest, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: Unlimited + } + }, + { + Transact: { + originKind: Superuser, + requireWeightAtMost: *rc_weight_at_most, + call: $force_create_asset + } + } + ] + } + ] + events: + - name: xcmPallet.Sent + - name: dmpQueue.ExecutedDownward + chain: *assets_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '1,014,103,000', proofSize: '200,000' }}} + - queries: + forced_created_asset: + chain: *assets_parachain + pallet: assets + call: asset + args: [ *asset_id ] + - asserts: + isSome: + args: [ $forced_created_asset ] + + - name: xcmPallet.send | Native - Transact(assets.forceCreate) + its: + - name: Relay Chain Native account SHOULD NOT be able to execute a XCM Transact instruction in the Assets Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + pallet: xcmPallet + call: send + args: [ + *ap_dest, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: Unlimited + } + }, + { + Transact: { + originKind: Native, + requireWeightAtMost: *rc_weight_at_most, + call: $force_create_asset + } + } + ] + } + ] + events: + - name: system.ExtrinsicFailed + result: { dispatchError: BadOrigin } + + - name: xcmPallet.limitedReserveTransferAssets + before: *before_get_balances + its: + - name: SHOULD NOT reserved transfer native assets from the Relay Chain to the Assets Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + pallet: xcmPallet + call: limitedReserveTransferAssets + args: [ + *ap_dest, # destination + *ap_benf, # beneficiary + { v3: [ *rc_ksm_fungible ] }, # assets + 0, # feeAssetItem + { unlimited: true } # weightLimit + ] + events: + - name: xcmPallet.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '750,645,000', proofSize: 0 }}} + - name: dmpQueue.ExecutedDownward + chain: *assets_parachain + threshold: *weight_threshold + result: { + outcome: { + Incomplete: [ + { refTime: '1,000,000,000', proofSize: 0 }, + UntrustedReserveLocation + ] + } + } + - queries: + balance_rc_sender_after: + chain: *relay_chain + pallet: system + call: account + args: [ *rc_wallet ] + balance_ap_receiver_after: + chain: *assets_parachain + pallet: system + call: account + args: [ *ap_wallet ] + + - name: Should reduce the balance of the sender + actions: + - asserts: + balanceDecreased: + args: [ + { + balances: { + before: $balance_rc_sender_before, + after: $balance_rc_sender_after, + }, + amount: *amount + } + ] + + - name: Should keep the balance of the receiver + actions: + - asserts: + equal: + args: + [ + $balance_ap_receiver_before, + $balance_ap_receiver_after + ] diff --git a/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/2_ump.yml b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/2_ump.yml new file mode 100644 index 00000000000..2a0bb88090e --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/2_ump.yml @@ -0,0 +1,191 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9900 + assets_parachain: &assets_parachain + wsPort: 9910 + paraId: &ap_id 1000 + variables: + common: + amount: &amount 1000000000000 + require_weight_at_most: &weight_at_most {refTime: 1000000000, proofSize: 0} + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + chains: + relay_chain: + signer: &rc_signer //Alice + wallet: &rc_wallet HNZata7iMYWmk5RvZRTiAsSDhV8366zq2YGb3tLH5Upf74F #Alice + assets_parachain_destination: &ap_dest { v3: { 0, interior: { x1: { parachain: *ap_id }}}} + assets_parachain_account: &ap_acc '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' + assets_parachain_beneficiary: &ap_benf {v3: { parents: 0, interior: { x1: { accountId32: { id: *ap_acc }}}}} + ksm: &rc_ksm { concrete: { 0, interior: { here: true }}} + ksm_fungible: &rc_ksm_fungible { id: *rc_ksm, fun: { fungible: *amount }} + assets_parachain_account: + signer: &ap_signer //Alice + wallet: &ap_wallet HNZata7iMYWmk5RvZRTiAsSDhV8366zq2YGb3tLH5Upf74F + relay_chain_destination: &rc_dest { v3: { parents: 1, interior: { here: true }}} + assets_parachain_account: &rc_acc '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' #Alice + relay_chain_beneficiary: &rc_benf {v3: { parents: 0, interior: { x1: { accountId32: { id: *rc_acc }}}}} + ksm: &ap_ksm { concrete: { parents: 1, interior: { here: true }}} + ksm_fungible: &ap_ksm_fungible { id: *ap_ksm, fun: { fungible: *amount }} + decodedCalls: + system_remark: + chain: *relay_chain + pallet: system + call: remark + args: [ 0x0011 ] + +tests: + - name: UMP + describes: + - name: polkadotXcm.limitedTeleportAssets + before: + - name: DEPENDENCY | Do a 'limitedTeleportAssets' from the Relay Chain to the Assets Parachain to have funds to send them back + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + pallet: xcmPallet + call: limitedTeleportAssets + args: [ + *ap_dest, # destination + *ap_benf, # beneficiary + { v3: [ *rc_ksm_fungible ] }, # assets + 0, # feeAssetItem + { unlimited: true } # weightLimit + ] + events: + - name: xcmPallet.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '761,173,000', proofSize: 0 }}} + - name: dmpQueue.ExecutedDownward + chain: *assets_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '166,944,000', proofSize: 0 }}} + + - name: Get the balances of the Assets Parachain's sender & Relay Chain's receiver + actions: + - queries: + balance_ap_sender_before: + chain: *assets_parachain + pallet: system + call: account + args: [ *ap_wallet ] + balance_rc_receiver_before: + chain: *relay_chain + pallet: system + call: account + args: [ *rc_wallet ] + its: + - name: Should teleport native assets back from Assets Parachain to the Relay Chain + actions: + - extrinsics: + - chain: *assets_parachain + signer: *ap_signer + pallet: polkadotXcm + call: limitedTeleportAssets + args: [ + *rc_dest, # destination + *rc_benf, # beneficiary + { v3: [ *ap_ksm_fungible ] }, # assets + 0, # feeAssetItem + { unlimited: true } # weightLimit + ] + events: + - name: polkadotXcm.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '539,494,000', proofSize: '7,133' }}} + - name: messageQueue.Processed + chain: *relay_chain + threshold: *weight_threshold + result: { origin: { Ump: { Para: '1,000' } }, weightUsed: { refTime: '298,716,000', proofSize: '0' }, success: true } + - queries: + balance_ap_sender_after: + chain: *assets_parachain + pallet: system + call: account + args: [ *ap_wallet ] + balance_rc_receiver_after: + chain: *relay_chain + pallet: system + call: account + args: [ *rc_wallet ] + + - name: Should reduce the balance of the sender + actions: + - asserts: + balanceDecreased: + args: [ + { + balances: { + before: $balance_ap_sender_before, + after: $balance_ap_sender_after, + }, + amount: *amount + } + ] + + - name: Should increase the balance of the receiver + actions: + - asserts: + balanceIncreased: + args: [ + { + balances: { + before: $balance_rc_receiver_before, + after: $balance_rc_receiver_after, + } + } + ] + + - name: polkadotXcm.send | Native - Transact(system.remark) + its: + - name: Assets Parachain SHOULD NOT be able to dispatch 'send' call + actions: + - extrinsics: + - chain: *assets_parachain + signer: *ap_signer + pallet: polkadotXcm + call: send + args: [ + *rc_dest, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: Unlimited + } + }, + { + Transact: { + originKind: Native, + requireWeightAtMost: *weight_at_most, + call: $system_remark + } + } + ] + } + ] + events: + - name: system.ExtrinsicFailed + result: { dispatchError: BadOrigin } + + - name: polkadotXcm.limitedReserveTransferAssets + its: + - name: Should NOT be able to reserve transfer native assets from the Assets Parachain to the Relay Chain + actions: + - extrinsics: + - chain: *assets_parachain + signer: *ap_signer + pallet: polkadotXcm + call: limitedReserveTransferAssets + args: [ + *rc_dest, # destination + *rc_benf, # beneficiary + { v3: [ *ap_ksm_fungible ] }, # assets + 0, # feeAssetItem + { unlimited: true } # weightLimit + ] + events: + - name: polkadotXcm.Attempted + result: { outcome: { Error: Barrier }} diff --git a/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/3_force_hrmp-open-channels.yml b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/3_force_hrmp-open-channels.yml new file mode 100644 index 00000000000..dfdae028f00 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/3_force_hrmp-open-channels.yml @@ -0,0 +1,122 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9900 + assets_parachain: + wsPort: 9910 + paraId: &ap_id 1000 + penpal_parachain: + wsPort: 9920 + paraId: &pp_id 2000 + variables: + common: + amount: &amount 2000000000000 + hrmp_channels: + proposed_max_capacity: &max_capacity 8 + proposed_max_message_size: &max_message_size 8192 + channel: &channel { + maxCapacity: *max_capacity, + maxTotalSize: *max_message_size, + maxMessageSize: *max_message_size, + msgCount: 0, + totalSize: 0, + mqcHead: null, + senderDeposit: 0, + recipientDeposit: 0 + } + chains: + relay_chain: + signer: &rc_signer //Alice + assets_parachain_account: + sovereign_account: &ap_sovereign F7fq1jSNVTPfJmaHaXCMtatT1EZefCUsa7rRiQVNR5efcah + penpal_parachain: + sovereign_account: &pp_sovereign F7fq1jMZkfuCuoMTyiEVAP2DMpMt18WopgBqTJznLihLNbZ + +tests: + - name: HRMP + beforeEach: + - name: DEPENDENCY | Penpal Parachain Sovereign account in the Relay Chain needs to be funded + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + pallet: balances + call: transfer + args: [ + *pp_sovereign, # destination + *amount, # value + ] + events: + - name: balances.Transfer + + - name: DEPENDENCY | Assets Parachain Sovereign account in the Relay Chain needs to be funded + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + pallet: balances + call: transfer + args: [ + *ap_sovereign, # destination + *amount, # value + ] + events: + - name: balances.Transfer + describes: + - name: hrmp.forceOpenHrmpChannel (Penpal Parachain → Assets Parachain) + its: + - name: Open Penpal Parachain to Assets Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + sudo: true + pallet: hrmp + call: forceOpenHrmpChannel + args: [ + *pp_id, + *ap_id, + *max_capacity, + *max_message_size + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: hrmp.HrmpChannelForceOpened + + - name: hrmp.forceOpenHrmpChannel (Assets Parachain → PenPal Parachain) + its: + - name: Open Assets Parachain to PenPal Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + sudo: true + pallet: hrmp + call: forceOpenHrmpChannel + args: [ + *ap_id, + *pp_id, + *max_capacity, + *max_message_size + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: hrmp.HrmpChannelForceOpened + + - name: hrmp.forceProcessHrmpOpen (make sure all the channels are open) + its: + - name: Make sure all the pending channels are open + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + sudo: true + pallet: hrmp + call: forceProcessHrmpOpen + args: [ 2 ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } diff --git a/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/4_hrmp.yml b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/4_hrmp.yml new file mode 100644 index 00000000000..02e53da7558 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/0_xcm/4_hrmp.yml @@ -0,0 +1,388 @@ +--- +# Note: This tests depends on the 3_hrmp-open-channels.yml for opening channels, otherwise teleports aren't going to +# work. +settings: + chains: + relay_chain: &relay_chain + wsPort: 9900 + assets_parachain: &assets_parachain + wsPort: 9910 + paraId: &ap_id 1000 + penpal_parachain: &penpal_parachain + wsPort: 9920 + paraId: &pp_id 2000 + variables: + common: + mint_amount: &mint_amount 1000000000000 + amount: &amount 100000000000 + require_weight_at_most: &weight_at_most {refTime: 1200000000, proofSize: 20000} + amount_to_send: &amount_to_send 500000000000 + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + chains: + relay_chain: + signer: &rc_signer //Alice + assets_parachain_destination: &ap_dest { v3: { 0, interior: { x1: { parachain: *ap_id }}}} + assets_parachain_dest_routed: &ap_dest_routed { v3: { parents: 1, interior: { x1: { parachain: *ap_id } }}} + assets_parachain_account: + signer: &ap_signer //Alice + wallet: &ap_wallet HNZata7iMYWmk5RvZRTiAsSDhV8366zq2YGb3tLH5Upf74F + asset_id: &asset_id 2 + assets_pallet_id: &assets_pallet_id 50 + asset_min_balance: &asset_ed 1000 + penpal_parachain_destination: &pp_dest { v3: { parents: 1, interior: { x1: { parachain: *pp_id } }}} + ksm: &ap_ksm { concrete: { parents: 1, interior: { here: true }}} + ksm_fungible: &ap_ksm_fungible { id: *ap_ksm, fun: { fungible: *amount }} + suff_asset: &suff_asset { concrete: { parents: 0, interior: { x2: [ { PalletInstance: *assets_pallet_id }, { GeneralIndex: *asset_id } ] }}} + suff_asset_fail: &suff_asset_fail { concrete: { parents: 0, interior: { x2: [ { PalletInstance: *assets_pallet_id }, { GeneralIndex: 3 } ] }}} + suff_asset_fungible_fail: &ap_suff_asset_fungible_fail { id: *suff_asset_fail, fun: { fungible: 200000000000 }} + penpal_parachain: + sovereign_account: &pp_sovereign_sibl FBeL7EAeUroLWXW1yfKboiqTqVfbRBcsUKd6QqVf4kGBySS + signer: &pp_signer //Alice + penpal_parachain_account: &pp_acc '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' + decodedCalls: + force_create_asset: + chain: *assets_parachain + pallet: assets + call: forceCreate + args: [ + *asset_id, + { Id: *ap_wallet }, # owner + true, # isSufficient + *asset_ed # minBalance + ] + force_create_asset2: + chain: *assets_parachain + pallet: assets + call: forceCreate + args: [ + *asset_id, + { Id: *ap_wallet }, # owner + true, # isSufficient + *asset_ed # minBalance + ] + +tests: + - name: HRMP + describes: + - name: polkadotXcm.limitedReserveTransferAssets (Asset) | Assets Parachain -> Penpal Parachain + before: + - name: DEPENDENCY | A sufficient Asset should exist in the Assets Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + *ap_dest, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: Unlimited + } + }, + { + SetTopic: '0x0123456789012345678901234567891201234567890123456789012345678912' + }, + { + Transact: { + originKind: Superuser, + requireWeightAtMost: *weight_at_most, + call: $force_create_asset + } + } + ] + } + ] + events: + - name: xcmPallet.Sent + - name: dmpQueue.ExecutedDownward + chain: *assets_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '1,216,703,000', proofSize: '20,000' }}} + - queries: + forced_created_asset: + chain: *assets_parachain + pallet: assets + call: asset + args: [ *asset_id ] + - asserts: + isSome: + args: [ $forced_created_asset ] + + - name: DEPENDENCY | Some Assets should be minted for the sender + actions: + - extrinsics: + - chain: *assets_parachain + signer: *ap_signer + pallet: assets + call: mint + args: [ + *asset_id, + *ap_wallet, + *mint_amount + ] + events: + - name: assets.Issued + result: { assetId: *asset_id, owner: *ap_wallet, amount: *mint_amount } + + its: + - name: Assets Parachain should be able to reserve transfer an Asset to Penpal Parachain + actions: + - extrinsics: + - chain: *assets_parachain + signer: *ap_signer + pallet: polkadotXcm + call: limitedReserveTransferAssets + args: [ + *pp_dest, # destination + { # beneficiary + V3: { + parents: 0, + interior: { + X1: { + AccountId32: { + id: *pp_acc + } + } + } + } + }, + { # assets + V3: [ + { + id: { + Concrete: { + parents: 0, + interior: { + X2: [ + { + PalletInstance: *assets_pallet_id + }, + { + GeneralIndex: *asset_id + } + ] + } + } + }, + fun: { + Fungible: *amount_to_send + } + } + ] + }, + 0, # feeAssetItem + Unlimited # weightLimit + ] + events: + - name: polkadotXcm.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '679,150,000', proofSize: '6,196' }}} + - name: assets.Transferred + result: { + assetId: *asset_id, + from: *ap_wallet, + to: *pp_sovereign_sibl, + amount: *amount_to_send + } + + - name: polkadotXcm.limitedReserveTransferAssets (KSM) | Assets Parachain -> Penpal Parachain + its: + - name: Assets Parachain should be able to reserve transfer KSM to Penpal Parachain + actions: + - extrinsics: + - chain: *assets_parachain + signer: *ap_signer + pallet: polkadotXcm + call: limitedReserveTransferAssets + args: [ + *pp_dest, # destination + { # beneficiary + V3: { + parents: 0, + interior: { + X1: { + AccountId32: { + id: *pp_acc + } + } + } + } + }, + { # assets + V3: [ + *ap_ksm_fungible + ] + }, + 0, # feeAssetItem + Unlimited # weightLimit + ] + events: + - name: polkadotXcm.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '679,150,000', proofSize: '6,196' }}} + - name: balances.Endowed + result: { + account: *pp_sovereign_sibl, + freeBalance: *amount + } + + - name: polkadotXcm.send( assets.forceCreateAsset ) | Penpal Parachain -> Assets Parachain + before: + - name: Get the asset balance of the Penpal Parachain Sovereign account in Assets Parachain + actions: + - queries: + assets_balance_pp_sovereign_before: + chain: *assets_parachain + pallet: assets + call: account + args: [ + *asset_id, + *pp_sovereign_sibl + ] + its: + - name: Penpal Parachain should be able to send XCM message paying its fee with sufficient asset in Assets Parachain + actions: + - extrinsics: + - chain: *penpal_parachain + signer: *pp_signer + sudo: true + pallet: polkadotXcm + call: send + args: [ + *ap_dest_routed, # destination + { + v3: [ #message + { + WithdrawAsset: [ + { + id: { + concrete: { + parents: 0, + interior: { + X2: [ + { PalletInstance: *assets_pallet_id }, + { GeneralIndex: *asset_id } + ] + } + } + }, + fun: { fungible: *amount }} + ] + }, + { + BuyExecution: { + fees: { id: *suff_asset, fun: { fungible: *amount }}, + weightLimit: Unlimited + } + }, + { + Transact: { + originKind: SovereignAccount, + requireWeightAtMost: *weight_at_most, + call: $force_create_asset2 + } + }, + { + RefundSurplus + }, + { + DepositAsset: { + assets: { Wild: All }, + beneficiary: { + parents: 0, + interior: { + X1: { + AccountId32: { + network: , # None + id: *pp_acc + } + } + }} + } + } + ] + } + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: polkadotXcm.Sent + - name: assets.Burned + chain: *assets_parachain + result: { assetId: *asset_id, owner: *pp_sovereign_sibl } + - name: assets.Issued + chain: *assets_parachain + result: { assetId: *asset_id } + - queries: + assets_balance_pp_sovereign_after: + chain: *assets_parachain + pallet: assets + call: account + args: [ + *asset_id, + *pp_sovereign_sibl + ] + forced_created_asset2: + chain: *assets_parachain + pallet: assets + call: asset + args: [ 3 ] + - asserts: + isSome: + args: [ $forced_created_asset2 ] + - name: Should reduce the assets balance of the Penpal Parachain's SovereignAccount in the Assets Parachain + actions: + - asserts: + assetsDecreased: + args: [ + { + balances: { + before: $assets_balance_pp_sovereign_before, + after: $assets_balance_pp_sovereign_after, + }, + } + ] + + - name: Penpal Parachain SHOULD NOT be able to send XCM message paying its fee with sufficient assets if not enough balance + actions: + - extrinsics: + - chain: *penpal_parachain + signer: *pp_signer + sudo: true + pallet: polkadotXcm + call: send + args: [ + *ap_dest_routed, # destination + { + v3: [ #message + { + WithdrawAsset: [*ap_suff_asset_fungible_fail] + }, + { + BuyExecution: { + fees: *ap_suff_asset_fungible_fail, + weightLimit: Unlimited + } + }, + { + Transact: { + originKind: SovereignAccount, + requireWeightAtMost: *weight_at_most, + call: $force_create_asset2 + } + } + ] + } + ] + events: + - name: xcmpQueue.Fail + chain: *assets_parachain + threshold: *weight_threshold + result: { + error: FailedToTransactAsset, + weight: { refTime: '152,426,000', proofSize: '3,593' } + } diff --git a/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/config.toml b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/config.toml new file mode 100644 index 00000000000..1ec06b3fa10 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-kusama/config.toml @@ -0,0 +1,71 @@ +[relaychain] +default_command = "./bin/polkadot" +default_args = [ "-lparachain=debug", "-lxcm=trace" ] +chain = "kusama-local" + + [[relaychain.nodes]] + name = "alice" + ws_port = 9900 + validator = true + args = ["--state-cache-size=0"] + + [[relaychain.nodes]] + name = "bob" + ws_port = 9901 + validator = true + + [[relaychain.nodes]] + name = "charlie" + ws_port = 9902 + validator = true + + [[relaychain.nodes]] + name = "dave" + ws_port = 9903 + validator = true + +[[parachains]] +id = 1000 +chain = "asset-hub-kusama-local" +cumulus_based = true + + [[parachains.collators]] + name = "collator1" + ws_port = 9910 + command = "./bin/polkadot-parachain" + args = [ "-lxcm=trace", "--state-cache-size=0" ] + + [[parachains.collators]] + name = "collator2" + ws_port = 9911 + command = "./bin/polkadot-parachain" + args = [ "-lxcm=trace" ] + +[[parachains]] +id = 2000 +chain = "penpal-kusama-2000" +cumulus_based = true + + [[parachains.collators]] + name = "collator3" + ws_port = 9920 + command = "./bin/polkadot-parachain" + args = [ "-lxcm=trace", "--state-cache-size=0" ] + + [[parachains.collators]] + name = "collator4" + ws_port = 9921 + command = "./bin/polkadot-parachain" + args = [ "-lxcm=trace" ] + +# [[hrmpChannels]] +# sender = 1000 +# recipient = 2000 +# maxCapacity = 8 +# maxMessageSize = 8192 + +# [[hrmpChannels]] +# sender = 2000 +# recipient = 1000 +# maxCapacity = 8 +# maxMessageSize = 8192 diff --git a/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/0_init.yml b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/0_init.yml new file mode 100644 index 00000000000..a6d3fb3ec83 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/0_init.yml @@ -0,0 +1,145 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9800 + assets_parachain: &assets_parachain + wsPort: 9810 + paraId: &ap_id 1000 + penpal_parachain: &penpal_parachain + wsPort: 9820 + paraId: &pp_id 2000 + variables: + common: + xcm_version: &xcm_version '3' + require_weight_at_most: &weight_at_most {refTime: 1000000000, proofSize: 200000} + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + chains: + relay_chain: + signer: &rc_signer //Alice + assets_parachain_destination: &ap_dest { v3: { 0, interior: { x1: { parachain: *ap_id }}}} + penpal_parachain: + signer: &pp_signer //Alice + decodedCalls: + ap_force_xcm_version: + chain: *assets_parachain + pallet: polkadotXcm + call: forceXcmVersion + args: [ + { # location + parents: 1, + interior: Here + }, + *xcm_version # xcmVersion + ] + +tests: + - name: Initialize Chains + its: + - name: XCM supported versions between chains + actions: + - extrinsics: # Relay Chain sets supported version for Asset Parachain + - chain: *relay_chain + sudo: true + signer: *rc_signer + pallet: xcmPallet + call: forceXcmVersion + args: [ + { # location + parents: 0, + interior: { + X1: { + Parachain: *ap_id + } + } + }, + *xcm_version # xcmVersion + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.SupportedVersionChanged + result: { location: { parents: 0, interior: { X1: { Parachain: *ap_id }}}, version: *xcm_version } + - extrinsics: # Relay Chain sets supported version for Penpal Parachain + - chain: *relay_chain + sudo: true + signer: *rc_signer + pallet: xcmPallet + call: forceXcmVersion + args: [ + { # location + parents: 0, + interior: { + X1: { + Parachain: *pp_id + } + } + }, + *xcm_version # xcmVersion + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.SupportedVersionChanged + result: { location: { parents: 0, interior: { X1: { Parachain: *pp_id }}}, version: *xcm_version } + - extrinsics: # Asset Parachain sets supported version for Relay Chain through it + - chain: *relay_chain + signer: *rc_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + *ap_dest, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: { + limited: { + refTime: 3200000000, + proofSize: 200000 + } + } + } + }, + { + Transact: { + originKind: Superuser, + requireWeightAtMost: *weight_at_most, + call: $ap_force_xcm_version + } + } + ] + } + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.Sent + - name: dmpQueue.ExecutedDownward + chain: *assets_parachain + threshold: *weight_threshold + result: { + outcome: { Complete: { refTime: '1,019,210,000', proofSize: '200,000' }} + } + - name: polkadotXcm.SupportedVersionChanged + chain: *assets_parachain + result: { location: { parents: 1, interior: Here }, version: *xcm_version } + - extrinsics: # Penpal Parachain sets supported version for Relay Chain + - chain: *penpal_parachain + signer: *pp_signer + sudo: true + pallet: polkadotXcm + call: forceXcmVersion + args: [ + { # location + parents: 1, + interior: Here + }, + *xcm_version # xcmVersion + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: polkadotXcm.SupportedVersionChanged + result: { location: { parents: 1, interior: Here}, version: *xcm_version } diff --git a/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/1_dmp.yml b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/1_dmp.yml new file mode 100644 index 00000000000..36b296f3eb1 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/1_dmp.yml @@ -0,0 +1,263 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9800 + assets_parachain: &assets_parachain + wsPort: 9810 + paraId: &ap_id 1000 + variables: + common: + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + chains: + relay_chain: + signer: &rc_signer //Alice + wallet: &rc_wallet HNZata7iMYWmk5RvZRTiAsSDhV8366zq2YGb3tLH5Upf74F + assets_parachain_destination: &ap_dest { v3: { parents: 0, interior: { x1: { parachain: *ap_id }}}} + assets_parachain_account: &ap_acc '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' + assets_parachain_beneficiary: &ap_benf {v3: { parents: 0, interior: { x1: { accountId32: { id: *ap_acc }}}}} + ksm: &rc_ksm { concrete: { parents: 0, interior: { here: true }}} + amount: &amount 1000000000000 + ksm_fungible: &rc_ksm_fungible { id: *rc_ksm, fun: { fungible: *amount }} + require_weight_at_most: &rc_weight_at_most {refTime: 1000000000, proofSize: 200000} + assets_parachain_account: + wallet: &ap_wallet HNZata7iMYWmk5RvZRTiAsSDhV8366zq2YGb3tLH5Upf74F + asset_id: &asset_id 1 + asset_min_balance: &asset_ed 1000 + decodedCalls: + force_create_asset: + chain: *assets_parachain + pallet: assets + call: forceCreate + args: [ + *asset_id, + { Id: *ap_wallet }, # owner + true, # isSufficient + *asset_ed # minBalance + ] + +tests: + - name: DMP + its: [] + describes: + - name: xcmPallet.limitedTeleportAssets + before: &before_get_balances + - name: Get the balances of the Relay Chain's sender & Assets Parachain's receiver + actions: + - queries: + balance_rc_sender_before: + chain: *relay_chain + pallet: system + call: account + args: [ *rc_wallet ] + balance_ap_receiver_before: + chain: *assets_parachain + pallet: system + call: account + args: [ *ap_wallet ] + its: + - name: Should teleport native assets from the Relay Chain to the Assets Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + pallet: xcmPallet + call: limitedTeleportAssets + args: [ + *ap_dest, # destination + *ap_benf, # beneficiary + { v3: [ *rc_ksm_fungible ] }, # assets + 0, # feeAssetItem + { unlimited: true } # weightLimit + ] + events: + - name: xcmPallet.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '3,000,000,000', proofSize: 0 }}} + - name: dmpQueue.ExecutedDownward + chain: *assets_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '166,944,000', proofSize: 0 }}} + - queries: + balance_rc_sender_after: + chain: *relay_chain + pallet: system + call: account + args: [ *rc_wallet ] + balance_ap_receiver_after: + chain: *assets_parachain + pallet: system + call: account + args: [ *ap_wallet ] + + - name: Should reduce the balance of the sender + actions: + - asserts: + balanceDecreased: + args: [ + { + balances: { + before: $balance_rc_sender_before, + after: $balance_rc_sender_after, + }, + amount: *amount + } + ] + + - name: Should increase the balance of the receiver + actions: + - asserts: + balanceIncreased: + args: [ + { + balances: { + before: $balance_ap_receiver_before, + after: $balance_ap_receiver_after, + } + } + ] + + - name: xcmPallet.send | Superuser - Transact(assets.forceCreate) + its: + - name: Relay Chain Superuser account SHOULD be able to execute a XCM Transact instruction in the Assets Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + *ap_dest, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: Unlimited + } + }, + { + Transact: { + originType: Superuser, + requireWeightAtMost: *rc_weight_at_most, + call: $force_create_asset + } + } + ] + } + ] + events: + - name: xcmPallet.Sent + - name: dmpQueue.ExecutedDownward + chain: *assets_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '1,014,103,000', proofSize: '200,000' }}} + - queries: + forced_created_asset: + chain: *assets_parachain + pallet: assets + call: asset + args: [ *asset_id ] + - asserts: + isSome: + args: [ $forced_created_asset ] + + - name: xcmPallet.send | Native - Transact(assets.forceCreate) + its: + - name: Relay Chain Native account SHOULD NOT be able to execute a XCM Transact instruction in the Assets Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + pallet: xcmPallet + call: send + args: [ + *ap_dest, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: Unlimited + } + }, + { + Transact: { + originType: Native, + requireWeightAtMost: *rc_weight_at_most, + call: $force_create_asset + } + } + ] + } + ] + events: + - name: system.ExtrinsicFailed + result: { dispatchError: BadOrigin } + + - name: xcmPallet.limitedReserveTransferAssets + before: *before_get_balances + its: + - name: SHOULD NOT reserved transfer native assets from the Relay Chain to the Assets Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + pallet: xcmPallet + call: limitedReserveTransferAssets + args: [ + *ap_dest, # destination + *ap_benf, # beneficiary + { v3: [ *rc_ksm_fungible ] }, # assets + 0, # feeAssetItem + { unlimited: true } # weightLimit + ] + events: + - name: xcmPallet.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '2,000,000,000', proofSize: 0 }}} + - name: dmpQueue.ExecutedDownward + chain: *assets_parachain + threshold: *weight_threshold + result: { + outcome: { + Incomplete: [ + { refTime: '1,000,000,000', proofSize: 0 }, + UntrustedReserveLocation + ] + } + } + - queries: + balance_rc_sender_after: + chain: *relay_chain + pallet: system + call: account + args: [ *rc_wallet ] + balance_ap_receiver_after: + chain: *assets_parachain + pallet: system + call: account + args: [ *ap_wallet ] + + - name: Should reduce the balance of the sender + actions: + - asserts: + balanceDecreased: + args: [ + { + balances: { + before: $balance_rc_sender_before, + after: $balance_rc_sender_after, + }, + amount: *amount + } + ] + + - name: Should keep the balance of the receiver + actions: + - asserts: + equal: + args: + [ + $balance_ap_receiver_before, + $balance_ap_receiver_after + ] diff --git a/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/2_ump.yml b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/2_ump.yml new file mode 100644 index 00000000000..fa84d4b006a --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/2_ump.yml @@ -0,0 +1,194 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9800 + assets_parachain: &assets_parachain + wsPort: 9810 + paraId: &ap_id 1000 + variables: + common: + amount: &amount 1000000000000 + require_weight_at_most: &weight_at_most {refTime: 1000000000, proofSize: 0} + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + chains: + relay_chain: + signer: &rc_signer //Alice + wallet: &rc_wallet HNZata7iMYWmk5RvZRTiAsSDhV8366zq2YGb3tLH5Upf74F + assets_parachain_destination: &ap_dest { v3: { 0, interior: { x1: { parachain: *ap_id }}}} + assets_parachain_account: &ap_acc '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' + assets_parachain_beneficiary: &ap_benf {v3: { parents: 0, interior: { x1: { accountId32: { id: *ap_acc }}}}} + ksm: &rc_ksm { concrete: { 0, interior: { here: true }}} + ksm_fungible: &rc_ksm_fungible { id: *rc_ksm, fun: { fungible: *amount }} + assets_parachain_account: + signer: &ap_signer //Alice + wallet: &ap_wallet HNZata7iMYWmk5RvZRTiAsSDhV8366zq2YGb3tLH5Upf74F + relay_chain_destination: &rc_dest { v3: { parents: 1, interior: { here: true }}} + assets_parachain_account: &rc_acc '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' + relay_chain_beneficiary: &rc_benf {v3: { parents: 0, interior: { x1: { accountId32: { id: *rc_acc }}}}} + ksm: &ap_ksm { concrete: { parents: 1, interior: { here: true }}} + ksm_fungible: &ap_ksm_fungible { id: *ap_ksm, fun: { fungible: *amount }} + decodedCalls: + system_remark: + chain: *relay_chain + pallet: system + call: remark + args: [ 0x0011 ] + +tests: + - name: UMP + describes: + - name: polkadotXcm.limitedTeleportAssets + before: + - name: DEPENDENCY | Do a 'limitedTeleportAssets' from the Relay Chain to the Assets Parachain to have funds to send them back + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + pallet: xcmPallet + call: limitedTeleportAssets + args: [ + *ap_dest, # destination + *ap_benf, # beneficiary + { v3: [ *rc_ksm_fungible ] }, # assets + 0, # feeAssetItem + { unlimited: true } # weightLimit + ] + events: + - name: xcmPallet.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '3,000,000,000', proofSize: 0 }}} + - name: dmpQueue.ExecutedDownward + chain: *assets_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '166,944,000', proofSize: 0 }}} + + - name: Get the balances of the Assets Parachain's sender & Relay Chain's receiver + actions: + - queries: + balance_ap_sender_before: + chain: *assets_parachain + pallet: system + call: account + args: [ *ap_wallet ] + balance_rc_receiver_before: + chain: *relay_chain + pallet: system + call: account + args: [ *rc_wallet ] + + its: + - name: Should be able to teleport native assets back from Assets Parachain to the Relay Chain + actions: + - extrinsics: + - chain: *assets_parachain + signer: *ap_signer + pallet: polkadotXcm + call: limitedTeleportAssets + args: [ + *rc_dest, # destination + *rc_benf, # beneficiary + { v3: [ *ap_ksm_fungible ] }, # assets + 0, # feeAssetItem + { unlimited: true } # weightLimit + ] + events: + - name: polkadotXcm.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '533,283,000', proofSize: '7,096' }}} + - name: messageQueue.Processed + chain: *relay_chain + threshold: *weight_threshold + result: { origin: { Ump: { Para: '1,000' } }, weightUsed: { refTime: '4,000,000,000', proofSize: '0' }, success: true } + - queries: + balance_ap_sender_after: + chain: *assets_parachain + pallet: system + call: account + args: [ *ap_wallet ] + balance_rc_receiver_after: + chain: *relay_chain + pallet: system + call: account + args: [ *rc_wallet ] + + - name: Should reduce the balance of the sender + actions: + - asserts: + balanceDecreased: + args: [ + { + balances: { + before: $balance_ap_sender_before, + after: $balance_ap_sender_after, + }, + amount: *amount + } + ] + + - name: Should increase the balance of the receiver + actions: + - asserts: + balanceIncreased: + args: [ + { + balances: { + before: $balance_rc_receiver_before, + after: $balance_rc_receiver_after, + } + } + ] + + - name: polkadotXcm.send | Native - Transact(system.remark) + its: + - name: Assets Parachain SHOULD NOT be able to dispatch 'send' call + actions: + - extrinsics: + - chain: *assets_parachain + signer: *ap_signer + pallet: polkadotXcm + call: send + args: [ + *rc_dest, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: Unlimited + } + }, + { + Transact: { + originType: Native, + requireWeightAtMost: *weight_at_most, + call: $system_remark + } + } + ] + } + ] + events: + - name: system.ExtrinsicFailed + attributes: + - type: SpRuntimeDispatchError + value: BadOrigin + + - name: polkadotXcm.limitedReserveTransferAssets + its: + - name: Should NOT be able to reserve transfer native assets from the Assets Parachain to the Relay Chain + actions: + - extrinsics: + - chain: *assets_parachain + signer: *ap_signer + pallet: polkadotXcm + call: limitedReserveTransferAssets + args: [ + *rc_dest, # destination + *rc_benf, # beneficiary + { v3: [ *ap_ksm_fungible ] }, # assets + 0, # feeAssetItem + { unlimited: true } # weightLimit + ] + events: + - name: polkadotXcm.Attempted + result: { outcome: { Error: Barrier }} diff --git a/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/3_force_hrmp-open-channels.yml b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/3_force_hrmp-open-channels.yml new file mode 100644 index 00000000000..ecf344a073b --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/3_force_hrmp-open-channels.yml @@ -0,0 +1,120 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9800 + assets_parachain: + wsPort: 9810 + paraId: &ap_id 1000 + penpal_parachain: + wsPort: 9820 + paraId: &pp_id 2000 + variables: + common: + amount: &amount 2000000000000 + hrmp_channels: + proposed_max_capacity: &max_capacity 8 + proposed_max_message_size: &max_message_size 8192 + channel: &channel { + maxCapacity: *max_capacity, + maxTotalSize: *max_message_size, + maxMessageSize: *max_message_size, + msgCount: 0, + totalSize: 0, + mqcHead: null, + senderDeposit: 0, + recipientDeposit: 0 + } + chains: + relay_chain: + signer: &rc_signer //Alice + assets_parachain_account: + sovereign_account: &ap_sovereign 5Ec4AhPZk8STuex8Wsi9TwDtJQxKqzPJRCH7348Xtcs9vZLJ + penpal_parachain: + sovereign_account: &pp_sovereign F7fq1jMZkfuCuoMTyiEVAP2DMpMt18WopgBqTJznLihLNbZ + +tests: + - name: HRMP + beforeEach: + - name: DEPENDENCY | Penpal Parachain Sovereign account in the Relay Chain needs to be funded + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + pallet: balances + call: transfer + args: [ + *pp_sovereign, # destination + *amount, # value + ] + events: + - name: balances.Transfer + + - name: DEPENDENCY | Assets Parachain Sovereign account in the Relay Chain needs to be funded + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + pallet: balances + call: transfer + args: [ + *ap_sovereign, # destination + *amount, # value + ] + events: + - name: balances.Transfer + describes: + - name: hrmp.hrmpInitOpenChannel (Penpal Parachain → Assets Parachain) + its: + - name: Open Penpal Parachain to Assets Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + sudo: true + pallet: hrmp + call: forceOpenHrmpChannel + args: [ + *pp_id, + *ap_id, + *max_capacity, + *max_message_size + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: hrmp.HrmpChannelForceOpened + - name: hrmp.hrmpInitOpenChannel (Assets Parachain → PenPal Parachain) + its: + - name: Open Assets Parachain to PenPal Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + sudo: true + pallet: hrmp + call: forceOpenHrmpChannel + args: [ + *ap_id, + *pp_id, + *max_capacity, + *max_message_size + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: hrmp.HrmpChannelForceOpened + - name: hrmp.forceProcessHrmpOpen (make sure all the channels are open) + its: + - name: Make sure all the pending channels are open + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + sudo: true + pallet: hrmp + call: forceProcessHrmpOpen + args: [ 2 ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } diff --git a/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/4_hrmp.yml b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/4_hrmp.yml new file mode 100644 index 00000000000..681af698c16 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/0_xcm/4_hrmp.yml @@ -0,0 +1,388 @@ +--- +# Note: This tests depends on the 3_hrmp-open-channels.yml for opening channels, otherwise teleports aren't going to +# work. +settings: + chains: + relay_chain: &relay_chain + wsPort: 9800 + assets_parachain: &assets_parachain + wsPort: 9810 + paraId: &ap_id 1000 + penpal_parachain: &penpal_parachain + wsPort: 9820 + paraId: &pp_id 2000 + variables: + common: + mint_amount: &mint_amount 1000000000000 + amount: &amount 1000000000000 + require_weight_at_most: &weight_at_most {refTime: 1200000000, proofSize: 20000} + amount_to_send: &amount_to_send 500000000000 + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + chains: + relay_chain: + signer: &rc_signer //Alice + assets_parachain_destination: &ap_dest { v3: { 0, interior: { x1: { parachain: *ap_id }}}} + assets_parachain_dest_routed: &ap_dest_routed { v3: { parents: 1, interior: { x1: { parachain: *ap_id } }}} + assets_parachain_account: + signer: &ap_signer //Alice + wallet: &ap_wallet 15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5 + asset_id: &asset_id 2 + assets_pallet_id: &assets_pallet_id 50 + asset_min_balance: &asset_ed 1000 + penpal_parachain_destination: &pp_dest { v3: { parents: 1, interior: { x1: { parachain: *pp_id } }}} + ksm: &ap_ksm { concrete: { parents: 1, interior: { here: true }}} + ksm_fungible: &ap_ksm_fungible { id: *ap_ksm, fun: { fungible: *amount }} + suff_asset: &suff_asset { concrete: { parents: 0, interior: { x2: [ { PalletInstance: *assets_pallet_id }, { GeneralIndex: *asset_id } ] }}} + suff_asset_fail: &suff_asset_fail { concrete: { parents: 0, interior: { x2: [ { PalletInstance: *assets_pallet_id }, { GeneralIndex: 3 } ] }}} + suff_asset_fungible_fail: &ap_suff_asset_fungible_fail { id: *suff_asset_fail, fun: { fungible: 200000000000 }} + penpal_parachain: + sovereign_account: &pp_sovereign_sibl 13cKp89Msu7M2PiaCuuGr1BzAsD5V3vaVbDMs3YtjMZHdGwR + signer: &pp_signer //Alice + penpal_parachain_account: &pp_acc '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' + decodedCalls: + force_create_asset: + chain: *assets_parachain + pallet: assets + call: forceCreate + args: [ + *asset_id, + { Id: *ap_wallet }, # owner + true, # isSufficient + *asset_ed # minBalance + ] + force_create_asset2: + chain: *assets_parachain + pallet: assets + call: forceCreate + args: [ + *asset_id, + { Id: *ap_wallet }, # owner + true, # isSufficient + *asset_ed # minBalance + ] + +tests: + - name: HRMP + describes: + - name: polkadotXcm.limitedReserveTransferAssets (Asset) | Assets Parachain -> Penpal Parachain + before: + - name: DEPENDENCY | A sufficient Asset should exist in the Assets Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *rc_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + *ap_dest, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: Unlimited + } + }, + { + SetTopic: '0x0123456789012345678901234567891201234567890123456789012345678912' + }, + { + Transact: { + originKind: Superuser, + requireWeightAtMost: *weight_at_most, + call: $force_create_asset + } + } + ] + } + ] + events: + - name: xcmPallet.Sent + - name: dmpQueue.ExecutedDownward + chain: *assets_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '1,216,703,000', proofSize: '20,000' }}} + - queries: + forced_created_asset: + chain: *assets_parachain + pallet: assets + call: asset + args: [ *asset_id ] + - asserts: + isSome: + args: [ $forced_created_asset ] + + - name: DEPENDENCY | Some Assets should be minted for the sender + actions: + - extrinsics: + - chain: *assets_parachain + signer: *ap_signer + pallet: assets + call: mint + args: [ + *asset_id, + *ap_wallet, + *mint_amount + ] + events: + - name: assets.Issued + result: { assetId: *asset_id, owner: *ap_wallet, amount: *mint_amount } + + its: + - name: Assets Parachain should be able to reserve transfer an Asset to Penpal Parachain + actions: + - extrinsics: + - chain: *assets_parachain + signer: *ap_signer + pallet: polkadotXcm + call: limitedReserveTransferAssets + args: [ + *pp_dest, # destination + { # beneficiary + V3: { + parents: 0, + interior: { + X1: { + AccountId32: { + id: *pp_acc + } + } + } + } + }, + { # assets + V3: [ + { + id: { + Concrete: { + parents: 0, + interior: { + X2: [ + { + PalletInstance: *assets_pallet_id + }, + { + GeneralIndex: *asset_id + } + ] + } + } + }, + fun: { + Fungible: *amount_to_send + } + } + ] + }, + 0, # feeAssetItem + Unlimited # weightLimit + ] + events: + - name: polkadotXcm.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '673,627,000', proofSize: '6,196' }}} + - name: assets.Transferred + result: { + assetId: *asset_id, + from: *ap_wallet, + to: *pp_sovereign_sibl, + amount: *amount_to_send + } + + - name: polkadotXcm.limitedReserveTransferAssets (KSM) | Assets Parachain -> Penpal Parachain + its: + - name: Assets Parachain should be able to reserve transfer KSM to Penpal Parachain + actions: + - extrinsics: + - chain: *assets_parachain + signer: *ap_signer + pallet: polkadotXcm + call: limitedReserveTransferAssets + args: [ + *pp_dest, # destination + { # beneficiary + V3: { + parents: 0, + interior: { + X1: { + AccountId32: { + id: *pp_acc + } + } + } + } + }, + { # assets + V3: [ + *ap_ksm_fungible + ] + }, + 0, # feeAssetItem + Unlimited # weightLimit + ] + events: + - name: polkadotXcm.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '679,150,000', proofSize: '6,196' }}} + - name: balances.Endowed + result: { + account: *pp_sovereign_sibl, + freeBalance: *amount + } + + - name: polkadotXcm.send( assets.forceCreateAsset ) | Penpal Parachain -> Assets Parachain + before: + - name: Get the asset balance of the Penpal Parachain Sovereign account in Assets Parachain + actions: + - queries: + assets_balance_pp_sovereign_before: + chain: *assets_parachain + pallet: assets + call: account + args: [ + *asset_id, + *pp_sovereign_sibl + ] + its: + - name: Penpal Parachain should be able to send XCM message paying its fee with sufficient asset in Assets Parachain + actions: + - extrinsics: + - chain: *penpal_parachain + signer: *pp_signer + sudo: true + pallet: polkadotXcm + call: send + args: [ + *ap_dest_routed, # destination + { + v3: [ #message + { + WithdrawAsset: [ + { + id: { + concrete: { + parents: 0, + interior: { + X2: [ + { PalletInstance: *assets_pallet_id }, + { GeneralIndex: *asset_id } + ] + } + } + }, + fun: { fungible: *amount_to_send }} + ] + }, + { + BuyExecution: { + fees: { id: *suff_asset, fun: { fungible: *amount_to_send }}, + weightLimit: Unlimited + } + }, + { + Transact: { + originKind: SovereignAccount, + requireWeightAtMost: *weight_at_most, + call: $force_create_asset2 + } + }, + { + RefundSurplus + }, + { + DepositAsset: { + assets: { Wild: All }, + beneficiary: { + parents: 0, + interior: { + X1: { + AccountId32: { + network: , # None + id: *pp_acc + } + } + }} + } + } + ] + } + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: polkadotXcm.Sent + - name: assets.Burned + chain: *assets_parachain + result: { assetId: *asset_id, owner: *pp_sovereign_sibl } + - name: assets.Issued + chain: *assets_parachain + result: { assetId: *asset_id } + - queries: + assets_balance_pp_sovereign_after: + chain: *assets_parachain + pallet: assets + call: account + args: [ + *asset_id, + *pp_sovereign_sibl + ] + forced_created_asset2: + chain: *assets_parachain + pallet: assets + call: asset + args: [ 3 ] + - asserts: + isSome: + args: [ $forced_created_asset2 ] + - name: Should reduce the assets balance of the Penpal Parachain's SovereignAccount in the Assets Parachain + actions: + - asserts: + assetsDecreased: + args: [ + { + balances: { + before: $assets_balance_pp_sovereign_before, + after: $assets_balance_pp_sovereign_after, + }, + } + ] + + - name: Penpal Parachain SHOULD NOT be able to send XCM message paying its fee with sufficient assets if not enough balance + actions: + - extrinsics: + - chain: *penpal_parachain + signer: *pp_signer + sudo: true + pallet: polkadotXcm + call: send + args: [ + *ap_dest_routed, # destination + { + v3: [ #message + { + WithdrawAsset: [*ap_suff_asset_fungible_fail] + }, + { + BuyExecution: { + fees: *ap_suff_asset_fungible_fail, + weightLimit: Unlimited + } + }, + { + Transact: { + originKind: SovereignAccount, + requireWeightAtMost: *weight_at_most, + call: $force_create_asset2 + } + } + ] + } + ] + events: + - name: xcmpQueue.Fail + chain: *assets_parachain + threshold: *weight_threshold + result: { + error: FailedToTransactAsset, + weight: { refTime: '152,426,000', proofSize: '3,593' } + } diff --git a/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/config.toml b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/config.toml new file mode 100644 index 00000000000..da53cd0ad4f --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/assets/asset-hub-polkadot/config.toml @@ -0,0 +1,72 @@ +[relaychain] +default_command = "./bin/polkadot" +default_args = [ "-lparachain=debug", "-lxcm=trace" ] +chain = "polkadot-local" + + [[relaychain.nodes]] + name = "alice" + ws_port = 9800 + validator = true + args = ["--state-cache-size=0"] + + [[relaychain.nodes]] + name = "bob" + ws_port = 9801 + validator = true + + [[relaychain.nodes]] + name = "charlie" + ws_port = 9802 + validator = true + + [[relaychain.nodes]] + name = "dave" + ws_port = 9803 + validator = true + +[[parachains]] +id = 1000 +chain = "asset-hub-polkadot-local" +cumulus_based = true + + [[parachains.collators]] + name = "collator1" + ws_port = 9810 + command = "./bin/polkadot-parachain" + args = [ "-lxcm=trace", "--state-cache-size=0" ] + + [[parachains.collators]] + name = "collator2" + ws_port = 9811 + command = "./bin/polkadot-parachain" + args = [ "-lxcm=trace" ] + + +[[parachains]] +id = 2000 +chain = "penpal-polkadot-2000" +cumulus_based = true + + [[parachains.collators]] + name = "collator3" + ws_port = 9820 + command = "./bin/polkadot-parachain" + args = [ "-lxcm=trace", "--state-cache-size=0" ] + + [[parachains.collators]] + name = "collator4" + ws_port = 9821 + command = "./bin/polkadot-parachain" + args = [ "-lxcm=trace" ] + +# [[hrmpChannels]] +# sender = 1000 +# recipient = 2000 +# maxCapacity = 8 +# maxMessageSize = 8192 + +# [[hrmpChannels]] +# sender = 2000 +# recipient = 1000 +# maxCapacity = 8 +# maxMessageSize = 8192 diff --git a/cumulus/parachains/integration-tests/e2e/collectives/README.md b/cumulus/parachains/integration-tests/e2e/collectives/README.md new file mode 100644 index 00000000000..9c4efe7c950 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/README.md @@ -0,0 +1,26 @@ +E2E tests concerning Polkadot Governance and the Collectives Parachain. The tests run by the Parachain Integration Tests +[tool](https://github.com/paritytech/parachains-integration-tests/). + +# Requirements +The tests require some changes to the regular production runtime builds: + +## RelayChain runtime +1. Alice has SUDO +2. Public Referenda `StakingAdmin`, `FellowshipAdmin` tracks settings (see the corresponding keys of the `TRACKS_DATA` + constant in the `governance::tracks` module of the Relay Chain runtime crate): +``` yaml +prepare_period: 5 Block, +decision_period: 1 Block, +confirm_period: 1 Block, +min_enactment_period: 1 Block, +``` + +## Collectives runtime +1. Fellowship Referenda `Fellows` track settings (see the corresponding key of the `TRACKS_DATA` constant in the + `fellowship::tracks` module of the Collectives runtime crate): +``` yaml +prepare_period: 5 Block, +decision_period: 1 Block, +confirm_period: 1 Block, +min_enactment_period: 1 Block, +``` diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/0_init.yml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/0_init.yml new file mode 100644 index 00000000000..33f4d603e2a --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/0_init.yml @@ -0,0 +1,166 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9700 + collectives_parachain: &collectives_parachain + wsPort: 9710 + paraId: &cp_id 1001 + assethub_parachain: &assethub_parachain + wsPort: 9810 + paraId: &sp_id 1000 + variables: + xcm_version: &xcm_version 3 + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + chains: + accounts: + alice_signer: &alice_signer //Alice + decodedCalls: + ap_force_xcm_version: + chain: *collectives_parachain + pallet: polkadotXcm + call: forceXcmVersion + args: [ + { # location + parents: 1, + interior: Here + }, + *xcm_version + ] + +tests: + - name: Initialize Chains + its: + - name: XCM supported versions between chains + actions: + - extrinsics: # Relay Chain sets supported version for Collectives Parachain + - chain: *relay_chain + sudo: true + signer: *alice_signer + pallet: xcmPallet + call: forceXcmVersion + args: [ + { # location + parents: 0, + interior: { + X1: { + Parachain: *cp_id + } + } + }, + *xcm_version + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.SupportedVersionChanged + result: { location: { parents: 0, interior: { X1: { Parachain: *cp_id }}}, version: *xcm_version } + - extrinsics: # Collectives Parachain sets supported version for Relay Chain through it + - chain: *relay_chain + signer: *alice_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + { v3: { 0, interior: { x1: { parachain: *cp_id }}}}, # destination + { + v3: [ # message + { + UnpaidExecution: { + weightLimit: { + limited: { + refTime: 2200000000, # 2_200_000_000 + proofSize: 200000, # 200_000 + }, + } + } + }, + { + Transact: { + originKind: Superuser, + requireWeightAtMost: { + refTime: 200000000, # 200_000_000 + proofSize: 0, + }, + call: $ap_force_xcm_version + } + } + ] + } + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.Sent + - name: polkadotXcm.SupportedVersionChanged + chain: *collectives_parachain + result: { location: { parents: 1, interior: Here }, version: *xcm_version } + - name: dmpQueue.ExecutedDownward + chain: *collectives_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '2,200,000,000', proofSize: 0 }}} + - extrinsics: # Relay Chain sets supported version for AssetHub Parachain + - chain: *relay_chain + sudo: true + signer: *alice_signer + pallet: xcmPallet + call: forceXcmVersion + args: [ + { # location + parents: 0, + interior: { + X1: { + Parachain: *sp_id + } + } + }, + *xcm_version + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.SupportedVersionChanged + result: { location: { parents: 0, interior: { X1: { Parachain: *sp_id } } }, version: *xcm_version } + - extrinsics: # AssetHub Parachain sets supported version for Relay Chain through it + - chain: *relay_chain + signer: *alice_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + { v3: { 0, interior: { x1: { parachain: *sp_id }}}}, # destination + { + v3: [ # message + { + UnpaidExecution: { + weightLimit: { + limited: { + refTime: 2200000000, # 2_200_000_000 + proofSize: 200000, # 200_000 + }, + } + } + }, + { + Transact: { + originKind: Superuser, + requireWeightAtMost: { + refTime: 200000000, # 200_000_000 + proofSize: 0, + }, + call: $ap_force_xcm_version + } + } + ] + } + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.Sent + - name: polkadotXcm.SupportedVersionChanged + chain: *assethub_parachain + result: { location: { parents: 1, interior: Here }, version: *xcm_version } + - name: dmpQueue.ExecutedDownward + chain: *assethub_parachain + result: { outcome: { Complete: {} } } diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/1_teleport.yml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/1_teleport.yml new file mode 100644 index 00000000000..cda04859b19 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/1_teleport.yml @@ -0,0 +1,168 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9700 + collectives_parachain: &collectives_parachain + wsPort: 9710 + paraId: &cp_id 1001 + variables: + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + accounts: + alice_signer: &acc_alice_signer //Alice + alice_account32: &acc_alice_acc32 '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' + alice_ss58: &acc_alice_ss58 '15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5' + checking_account: &checking_account '13UVJyLnbVp9x5XDyJv8g8r3UddNwBrdaH7AADCmw9XQWvYW' + +tests: + - name: Teleport assets from Relay Chain to Collectives Parachain successful. + before: + - name: Get the Alice balances on Relay & Collectives Chains. + actions: + - queries: + balance_rc_alice_1: + chain: *relay_chain + pallet: system + call: account + args: [ *acc_alice_acc32 ] + balance_cp_alice_1: + chain: *collectives_parachain + pallet: system + call: account + args: [ *acc_alice_acc32 ] + its: + - name: Teleport assets from Relay Chain to Collectives Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *acc_alice_signer + pallet: xcmPallet + call: teleportAssets + args: [ + { v3: { 0, interior: { x1: { parachain: *cp_id }}}}, # destination + { v3: { parents: 0, interior: { x1: { accountId32: { id: *acc_alice_acc32 }}}}}, # beneficiary + { + v3: [ + # { + # # TODO use a separate Assets to pay a fee, to receive an exact amount of assets on beneficiary account. + # # a call with two assets fails with an error right now. + # id: { concrete: { 0, interior: { here: true }}}, + # fun: { fungible: 1000000000000 } # 1_000_000_000_000 + # }, + { + id: { concrete: { 0, interior: { here: true }}}, + fun: { fungible: 20000000000000 } # 20_000_000_000_000 + } + ] + }, # assets + 0, # feeAssetItem + ] + events: + - name: xcmPallet.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '3,000,000,000', proofSize: 0 }}} + - name: dmpQueue.ExecutedDownward + chain: *collectives_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '4,000,000,000', proofSize: 0 }}} + - queries: + balance_rc_alice_2: + chain: *relay_chain + pallet: system + call: account + args: [ *acc_alice_acc32 ] + balance_cp_alice_2: + chain: *collectives_parachain + pallet: system + call: account + args: [ *acc_alice_acc32 ] + - name: Alice deposit check, balance decreased on Relay Chain, increased on Collectives. + actions: + - asserts: + balanceDecreased: + args: [ + { + balances: { + before: $balance_rc_alice_1, + after: $balance_rc_alice_2, + } + } + ] + balanceIncreased: + args: [ + { + balances: { + before: $balance_cp_alice_1, + after: $balance_cp_alice_2, + } + } + ] + + - name: Teleport assets from Collectives Parachain to Relay Chain successful + actions: + - extrinsics: + - chain: *collectives_parachain + signer: *acc_alice_signer + pallet: polkadotXcm + call: teleportAssets + args: [ + { v3: { parents: 1, interior: { here: true }}}, # destination + { v3: { parents: 0, interior: { x1: { accountId32: { id: *acc_alice_acc32 }}}}}, # beneficiary + { + v3: [ + { + id: { concrete: { parents: 1, interior: { here: true }}}, + fun: { fungible: 10000000000000 } # 10_000_000_000_000 + } + ] + }, # assets + 0, # feeAssetItem + ] + events: + - name: balances.Withdraw + result: { who: *acc_alice_ss58, amount: 10000000000000 } + - name: polkadotXcm.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '3,000,000,000', proofSize: 0 }}} + - name: balances.Withdraw + chain: *relay_chain + result: { who: *checking_account, amount: 10000000000000 } # amount received and withdrawn from registry account + - name: messageQueue.Processed + chain: *relay_chain + threshold: *weight_threshold + result: { origin: { Ump: { Para: *cp_id } }, weightUsed: { refTime: '4,000,000,000', proofSize: '0' }, success: true } + - queries: + balance_rc_alice_3: + chain: *relay_chain + pallet: system + call: account + args: [ *acc_alice_acc32 ] + balance_cp_alice_3: + chain: *collectives_parachain + pallet: system + call: account + args: [ *acc_alice_acc32 ] + + - name: Alice deposit check, balance decreased on Collectives, increased on Relay Chain. + actions: + - asserts: + balanceDecreased: + args: [ + { + balances: { + before: $balance_cp_alice_2, + after: $balance_cp_alice_3, + } + } + ] + balanceIncreased: + args: [ + { + balances: { + before: $balance_rc_alice_2, + after: $balance_rc_alice_3, + } + } + ] +# TODO (P2) assert Alice balance before and after teleport (see example in kick_member test) +# TODO (P1) test: teleport of non relay chain assets fails diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/2_reserve.yml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/2_reserve.yml new file mode 100644 index 00000000000..bd17f07524a --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/2_reserve.yml @@ -0,0 +1,53 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9700 + collectives_parachain: &collectives_parachain + wsPort: 9710 + paraId: &cp_id 1001 + variables: + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + chains: + accounts: + alice_signer: &alice_signer //Alice + alice_account32: &alice_acc32 '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' + +tests: + - name: Reserve assets from Relay Chain to Collectives Parachain fails + its: + - name: Reserve assets from Relay Chain to Collectives Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *alice_signer + pallet: xcmPallet + call: reserveTransferAssets + args: [ + { v3: { 0, interior: { x1: { parachain: *cp_id }}}}, # destination + { v3: { parents: 0, interior: { x1: { accountId32: { id: *alice_acc32 }}}}}, # beneficiary + { + v3: [ + { + id: { concrete: { 0, interior: { here: true }}}, + fun: { fungible: 20000000000000 } # 20_000_000_000_000 + } + ] + }, # assets + 0, # feeAssetItem + ] + events: + - name: xcmPallet.Attempted + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '2,000,000,000', proofSize: 0 }}} + - name: dmpQueue.ExecutedDownward + chain: *collectives_parachain + threshold: *weight_threshold + result: { + outcome: { + Incomplete: [ + { refTime: '1,000,000,000', proofSize: 0 }, + UntrustedReserveLocation + ] + } + } diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/3_hrmp-open-channels.yml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/3_hrmp-open-channels.yml new file mode 100644 index 00000000000..17a16d9ccd7 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/0_xcm/3_hrmp-open-channels.yml @@ -0,0 +1,69 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9700 + collectives_parachain: &collectives_parachain + wsPort: 9710 + paraId: &cp_id 1001 + assethub_parachain: &assethub_parachain + wsPort: 9810 + paraId: &sp_id 1000 + variables: + chains: + accounts: + alice_signer: &alice_signer //Alice + hrmp: + proposed_max_capacity: &hrmp_proposed_max_capacity 8 + proposed_max_message_size: &hrmp_proposed_max_message_size 8192 +tests: + - name: HRMP + describes: + - name: Force Open HRMP Channel From Collectives Parachain → AssetHub Parachain + its: + - name: Alice calls hrmp.forceOpenHrmpChannel + actions: + - extrinsics: + - chain: *relay_chain + signer: *alice_signer + sudo: true + pallet: hrmp + call: forceOpenHrmpChannel + args: [ + *cp_id, # sender + *sp_id, # recipient + *hrmp_proposed_max_capacity, # proposedMaxCapacity + *hrmp_proposed_max_message_size # proposedMaxMessageSize + ] + events: + - name: hrmp.HrmpChannelForceOpened + result: { + sender: *cp_id, + recipient: *sp_id, + proposed_max_capacity: *hrmp_proposed_max_capacity, + proposed_max_message_size: *hrmp_proposed_max_message_size + } + - name: Force Open HRMP Channel From AssetHub Parachain → Collectives Parachain + its: + - name: Alice calls hrmp.forceOpenHrmpChannel + actions: + - extrinsics: + - chain: *relay_chain + signer: *alice_signer + sudo: true + pallet: hrmp + call: forceOpenHrmpChannel + args: [ + *sp_id, # sender + *cp_id, # recipient + *hrmp_proposed_max_capacity, # proposedMaxCapacity + *hrmp_proposed_max_message_size # proposedMaxMessageSize + ] + events: + - name: hrmp.HrmpChannelForceOpened + result: { + sender: *sp_id, + recipient: *cp_id, + proposed_max_capacity: *hrmp_proposed_max_capacity, + proposed_max_message_size: *hrmp_proposed_max_message_size + } diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/0_join_alliance_fails.yml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/0_join_alliance_fails.yml new file mode 100644 index 00000000000..9aff8b1db10 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/0_join_alliance_fails.yml @@ -0,0 +1,29 @@ +--- +settings: + chains: + relay_chain: + wsPort: 9700 + collectives_parachain: &collectives_parachain + wsPort: 9710 + variables: + accounts: + alice_signer: &alice_signer //Alice + +tests: + - name: Alice fails to join an the Alliance, since it is not initialized yet. + its: + - name: Alice joins alliance + actions: + - extrinsics: # Relay Chain sets supported version for Asset Parachain + - chain: *collectives_parachain + signer: *alice_signer + pallet: alliance + call: joinAlliance + args: [] + events: + - name: system.ExtrinsicFailed + result: { + dispatchError: { Module: { index: 50, error: '0x00000000' }} + } + # TODO assert with Alliance Error variant - alliance.AllianceNotYetInitialized + # issue - https://github.com/paritytech/parachains-integration-tests/issues/59 diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/1_init_alliance.yml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/1_init_alliance.yml new file mode 100644 index 00000000000..1e01c701744 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/1_init_alliance.yml @@ -0,0 +1,256 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9700 + collectives_parachain: &collectives_parachain + wsPort: 9710 + paraId: &coll_para_id 1001 + variables: + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + accounts: + alice_signer: &acc_alice_signer //Alice + liam_account32: &acc_liam_acc32 "0x3614671a5de540d891eb8c4939c8153a4aa790602b347c18177b86d0fc546221" # //Liam + olivia_account32: &acc_olivia_acc32 "0x24ee8a659c6716fe9f7cb4e9e028602aa12867654ca02737da9171b7ff697d5c" # //Olivia + noah_account32: &acc_noah_acc32 "0x9c6ad3bc3aa2f1b2e837898e6da9980445f7ef8b3eee0b8c8e305f8cfae68517" # //Noah + emma_account32: &acc_emma_acc32 "0x8ac272b333ba1127c8db57fa777ec820b24598a236efa648caf0d26d86f64572" # //Emma + james_account32: &acc_james_acc32 "0x9a52805151a0b5effc084af9264011139872a21a3950cb9ae0b2955c4bf92c18" # //James + ava_account32: &acc_ava_acc32 "0x348ef0b8776adbc09c862ddc29b1d193b9e24738e54eea3b0609c83856dc101c" # //Ava + mia_account32: &acc_mia_acc32 "0xaebf15374cf7e758d10232514c569a7abf81cc1b8f1e81a73dbc608a0e335264" # //Mia + decodedCalls: + init_alliance_members: + chain: *collectives_parachain + pallet: alliance + call: initMembers + args: [ + [ + *acc_liam_acc32, + *acc_olivia_acc32, + *acc_noah_acc32, + *acc_emma_acc32, + *acc_james_acc32, + *acc_ava_acc32 + ], + [ + *acc_mia_acc32 + ] + ] + init_alliance_voting_members: + chain: *collectives_parachain + pallet: alliance + call: initMembers + args: [ + [ + *acc_liam_acc32, + *acc_olivia_acc32, + *acc_noah_acc32, + *acc_emma_acc32, + *acc_james_acc32, + *acc_ava_acc32, + *acc_mia_acc32 + ], + [] + ] + disband: + chain: *collectives_parachain + pallet: alliance + call: disband + args: [ + { + fellowMembers: 6, + allyMembers: 1 + } + ] + +tests: + - name: Alliance initiated with the root call, second init call fails. Alliance disband and set again. + its: + - name: Alliance initiated, founders and fellows are set. + actions: + - extrinsics: + - chain: *relay_chain + signer: *acc_alice_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + { v3: { parents: 0, interior: { x1: { parachain: *coll_para_id }}}}, # destination + { + v3: [ # message + { + UnpaidExecution: { + weightLimit: { + limited: { + refTime: 3000000000, # 3_000_000_000 + proofSize: 2000000, # 2_000_000 + }, + } + } + }, + { + Transact: { + originKind: Superuser, + requireWeightAtMost: { + refTime: 1000000000, # 1_000_000_000 + proofSize: 1000000, # 1_000_000 + }, + call: $init_alliance_members + } + } + ] + } + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.Sent + result: { origin: { parents: 0, interior: Here }, destination: { parents: 0, interior: { X1: { Parachain: *coll_para_id }}}} + - name: alliance.MembersInitialized + chain: *collectives_parachain + - name: dmpQueue.ExecutedDownward + chain: *collectives_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '3,000,000,000', proofSize: '1,000,000' }}} + + - name: Alliance init call fails. + actions: + - extrinsics: + - chain: *relay_chain + signer: *acc_alice_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + { v3: { parents: 0, interior: { x1: { parachain: *coll_para_id }}}}, # destination + { + v3: [ # message + { + UnpaidExecution: { + weightLimit: { + limited: { + refTime: 3000000000, # 3_000_000_000 + proofSize: 2000000, # 2_000_000 + }, + } + } + }, + { + Transact: { + originKind: Superuser, + requireWeightAtMost: { + refTime: 1000000000, # 1_000_000_000 + proofSize: 1000000, # 1_000_000 + }, + call: $init_alliance_voting_members + } + } + ] + } + ] + events: + # TODO can not currently assert variant AllianceAlreadyInitialized, XCM Transact fails silently + # issue - https://github.com/paritytech/polkadot/issues/4623 + # Next test with a disband call will fail, if this call does not fail, + # since a witness data from a disband call will be invalid. + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.Sent + result: { origin: { parents: 0, interior: Here }, destination: { parents: 0, interior: { X1: { Parachain: *coll_para_id }}}} + - name: dmpQueue.ExecutedDownward + chain: *collectives_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '3,000,000,000', proofSize: '1,000,000' }}} + + - name: Alliance disbanded and initialized again. + actions: + - extrinsics: + - chain: *relay_chain + signer: *acc_alice_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + { v3: { parents: 0, interior: { x1: { parachain: *coll_para_id }}}}, # destination + { + v3: [ # message + { + UnpaidExecution: { + weightLimit: { + limited: { + refTime: 5000000000, # 3_000_000_000 + proofSize: 1000000, # 1_000_000 + }, + } + } + }, + { + Transact: { + originKind: Superuser, + requireWeightAtMost: { + refTime: 3000000000, # 3_000_000_000 + proofSize: 200000, # 200_000 + }, + call: $disband + } + } + ] + } + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.Sent + result: { origin: { parents: 0, interior: Here }, destination: { parents: 0, interior: { X1: { Parachain: *coll_para_id }}}} + - name: alliance.AllianceDisbanded + chain: *collectives_parachain + result: { fellowMembers: 6, allyMembers: 1, unreserved: 0 } + - name: dmpQueue.ExecutedDownward + chain: *collectives_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '3,321,495,872', proofSize: '181,779' }}} + - name: Alliance initiated, founders and fellows are set. + actions: + - extrinsics: + - chain: *relay_chain + signer: *acc_alice_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + { v3: { parents: 0, interior: { x1: { parachain: *coll_para_id }}}}, # destination + { + v3: [ # message + { + UnpaidExecution: { + weightLimit: { + limited: { + refTime: 3000000000, # 3_000_000_000 + proofSize: 2000000, # 2_000_000 + }, + } + } + }, + { + Transact: { + originKind: Superuser, + requireWeightAtMost: { + refTime: 1000000000, # 1_000_000_000 + proofSize: 1000000, # 1_000_000 + }, + call: $init_alliance_members + } + } + ] + } + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.Sent + result: { origin: { parents: 0, interior: Here }, destination: { parents: 0, interior: { X1: { Parachain: *coll_para_id }}}} + - name: alliance.MembersInitialized + chain: *collectives_parachain + - name: dmpQueue.ExecutedDownward + chain: *collectives_parachain + threshold: *weight_threshold + result: { outcome: { Complete: { refTime: '3,000,000,000', proofSize: '1,000,000' }}} diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/2_join_alliance_fails.yml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/2_join_alliance_fails.yml new file mode 100644 index 00000000000..2afdadae602 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/2_join_alliance_fails.yml @@ -0,0 +1,30 @@ +--- +settings: + chains: + relay_chain: + wsPort: 9700 + collectives_parachain: &collectives_parachain + wsPort: 9710 + paraId: 1001 + variables: + accounts: + liam_signer: &acc_liam_signer //Liam + +tests: + - name: Liam fails to join an the Alliance, Liam is already a member. + its: + - name: Alice joins alliance + actions: + - extrinsics: # Relay Chain sets supported version for Asset Parachain + - chain: *collectives_parachain + signer: *acc_liam_signer + pallet: alliance + call: joinAlliance + args: [] + events: + - name: system.ExtrinsicFailed + result: { + dispatchError: { Module: { index: 50, error: '0x02000000' }} + } + # TODO assert with Alliance Error variant - alliance.AllianceNotYetInitialized + # issue - https://github.com/paritytech/parachains-integration-tests/issues/59 diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/3_kick_member.yml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/3_kick_member.yml new file mode 100644 index 00000000000..a5941cb4723 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/1_alliance/3_kick_member.yml @@ -0,0 +1,175 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9700 + collectives_parachain: &collectives_parachain + wsPort: 9710 + paraId: &cp_id 1001 + variables: + weight_threshold: &weight_threshold { refTime: [10, 10], proofSize: [10, 10] } + init_teleport_amount: &init_teleport_amount 20000000000000 # 20_000_000_000_000 + accounts: + alice_signer: &acc_alice_signer //Alice + treasury_account32: &acc_treasury_acc32 '0x6d6f646c70792f74727372790000000000000000000000000000000000000000' + alice_account32: &acc_alice_acc32 '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' + alice_ss58: &acc_alice_ss58 '15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5' + decodedCalls: + alliance_kick_member: + chain: *collectives_parachain + pallet: alliance + call: kickMember + args: [ + {Id: *acc_alice_acc32} + ] + +tests: + - name: Member kicked out, deposited assets slashed and teleported to Relay Chain treasury. + before: + - name: DEPENDENCY | Do a 'limitedTeleportAssets' from the Relay Chain to the Collectives Parachain + actions: + - extrinsics: + - chain: *relay_chain + signer: *acc_alice_signer + pallet: xcmPallet + call: limitedTeleportAssets + args: [ + { v3: { 0, interior: { x1: { parachain: *cp_id }}}}, # destination + { v3: { parents: 0, interior: { x1: { accountId32: { id: *acc_alice_acc32 }}}}}, # beneficiary + { v3: [ { id: { concrete: { 0, interior: { here: true }}}, fun: { fungible: *init_teleport_amount }} ] }, # assets + 0, # feeAssetItem + { unlimited: true } # weightLimit + ] + events: + - name: xcmPallet.Attempted + threshold: *weight_threshold + result: { + outcome: { Complete: { refTime: '3,000,000,000', proofSize: 0 }} + } + - name: balances.Deposit + chain: *collectives_parachain + result: { who: *acc_alice_ss58 } + - name: dmpQueue.ExecutedDownward + chain: *collectives_parachain + threshold: *weight_threshold + result: { + outcome: { Complete: { refTime: '4,000,000,000', proofSize: 0 }} + } + - name: Get the balances of the Relay Chain's treasury & Collectives parachain's future alliance member + actions: + - queries: + balance_rc_treasury_before: + chain: *relay_chain + pallet: system + call: account + args: [ *acc_treasury_acc32 ] + balance_cp_alice_before: + chain: *collectives_parachain + pallet: system + call: account + args: [ *acc_alice_acc32 ] + its: + - name: Alice joins alliance + actions: + - extrinsics: + - chain: *collectives_parachain + signer: *acc_alice_signer + pallet: alliance + call: joinAlliance + args: [] + events: + - name: balances.Reserved + chain: *collectives_parachain + result: { who: *acc_alice_ss58, amount: 10000000000000 } + - name: alliance.NewAllyJoined + result: {ally: *acc_alice_ss58, reserved: 10000000000000 } + - queries: + balance_cp_alice_after: + chain: *collectives_parachain + pallet: system + call: account + args: [ *acc_alice_acc32 ] + - name: Alice deposit check, balance decreased + actions: + - asserts: + balanceDecreased: + args: [ + { + balances: { + before: $balance_cp_alice_before, + after: $balance_cp_alice_after, + } + # TODO (P3) set `amount` and `fee` for more strict assert + } + ] + - name: Kick Alice from alliance + actions: + - extrinsics: # Asset Parachain sets supported version for Relay Chain through it + - chain: *relay_chain + signer: *acc_alice_signer + sudo: true + pallet: xcmPallet + call: send + args: [ + { v3: { parents: 0, interior: { x1: { parachain: *cp_id }}}}, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: { + limited: { + refTime: 4000000000, # 4_000_000_000 + proofSize: 2000000, # 2_000_000 + }, + } + } + }, + { + Transact: { + originKind: Superuser, + requireWeightAtMost: { + refTime: 2000000000, # 2_000_000_000 + proofSize: 1000000, # 1_000_000 + }, + call: $alliance_kick_member + } + } + ] + } + ] + events: + - name: sudo.Sudid + result: { sudoResult: Ok } + - name: xcmPallet.Sent + result: { origin: { parents: 0, interior: Here }, destination: { parents: 0, interior: { X1: { Parachain: *cp_id }}}} + - name: alliance.MemberKicked + chain: *collectives_parachain + result: { member: *acc_alice_ss58, slashed: 10000000000000 } + - name: dmpQueue.ExecutedDownward + chain: *collectives_parachain + threshold: *weight_threshold + result: { + outcome: { Complete: { refTime: '4,000,000,000', proofSize: '1,000,000' }} + } + - name: messageQueue.Processed + result: { origin: { Ump: { Para: *cp_id }}, success: true } + + - queries: + balance_rc_treasury_after: + chain: *relay_chain + pallet: system + call: account + args: [ *acc_treasury_acc32 ] + - name: Slashed balance appears on the relay chain treasury account + actions: + - asserts: + balanceIncreased: + args: [ + { + balances: { + before: $balance_rc_treasury_before, + after: $balance_rc_treasury_after, + } + # TODO (P3) set `amount` and `fee` for more strict assert + } + ] diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/2_opengov/0_assethub.yml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/2_opengov/0_assethub.yml new file mode 100644 index 00000000000..c53efff51fb --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/2_opengov/0_assethub.yml @@ -0,0 +1,149 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9700 + assethub_parachain: &assethub_parachain + wsPort: 9810 + paraId: &ap_id 1000 + variables: + proposal_index: &proposal_index 0 + chains: + accounts: + alice_signer: &alice_signer //Alice + bob_signer: &bob_signer //Bob + decodedCalls: + set_candidates_ap: + chain: *assethub_parachain + encode: true + pallet: collatorSelection + call: setDesiredCandidates + args: [ + 3 + ] + send_set_candidates_rc: + chain: *relay_chain + encode: false + pallet: xcmPallet + call: send + args: [ + { v3: { parents: 0, interior: { x1: { parachain: *ap_id }}}}, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: Unlimited + } + }, + { + Transact: { + originKind: Xcm, + requireWeightAtMost: { + refTime: 200000000, # 200_000_000 + proofSize: 100000, # 100_000 + }, + call: $set_candidates_ap + } + } + ] + } + ] +tests: + - name: OpenGov + describes: + - name: Set desired candidates on AssetHub from Relay Chain OpenGov Staking track + its: + - name: Note preimage from xcm send set_desired_candidates call + actions: + - extrinsics: + - chain: *relay_chain + signer: *alice_signer + pallet: preimage + call: notePreimage + args: [ + $send_set_candidates_rc + ] + events: + - name: preimage.Noted + result: {hash_: $send_set_candidates_rc.hash } + - name: Submit a proposal to set desired candidates + actions: + - extrinsics: + - chain: *relay_chain + signer: *alice_signer + pallet: referenda + call: submit + args: [ + { + "Origins": "StakingAdmin", + }, + { + "Lookup": { + "hash_": $send_set_candidates_rc.hash, + "len": $send_set_candidates_rc.len, + }, + }, + { + "After": 1, + }, + ] + events: + - name: referenda.Submitted + result: { + index: *proposal_index, + proposal: { Lookup: { hash_: $send_set_candidates_rc.hash, len: $send_set_candidates_rc.len }} + } + - name: Alice Vote Aye + actions: + - extrinsics: + - chain: *relay_chain + signer: *alice_signer + pallet: convictionVoting + call: vote + args: [ + *proposal_index, + { + "Standard": { + "vote": { + "aye": true, + "conviction": "Locked1x", + }, + "balance": 200000000000000, + } + }, + ] # TODO no event to catch https://github.com/paritytech/substrate/issues/14687 + - name: Bob Vote Aye + actions: + - extrinsics: + - chain: *relay_chain + signer: *bob_signer + pallet: convictionVoting + call: vote + args: [ + *proposal_index, + { + "Standard": { + "vote": { + "aye": true, + "conviction": "Locked1x", + }, + "balance": 200000000000000, + } + }, + ] # TODO no event to catch https://github.com/paritytech/substrate/issues/14687 + - name: Submit the decision deposit + actions: + - extrinsics: + - chain: *relay_chain + signer: *alice_signer + pallet: referenda + call: placeDecisionDeposit + args: [ + *proposal_index, + ] + events: + - name: referenda.DecisionDepositPlaced + result: { index: *proposal_index } + - name: collatorSelection.NewDesiredCandidates + chain: *assethub_parachain + result: { desiredCandidates: 3 } diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/3_fellowship/0_init.yml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/3_fellowship/0_init.yml new file mode 100644 index 00000000000..1e4b2dabe21 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/3_fellowship/0_init.yml @@ -0,0 +1,209 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9700 + collectives_parachain: &collectives_parachain + wsPort: 9710 + paraId: &cp_id 1001 + variables: + proposal_index: &proposal_index 1 + chains: + accounts: + alice_signer: &alice_signer //Alice + bob_signer: &bob_signer //Bob + alice_account32: &acc_alice_acc32 '0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d' + alice_ss58: &acc_alice_ss58 '15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5' + decodedCalls: + fellowship_induct_alice_cp: + chain: *collectives_parachain + encode: true + pallet: fellowshipCore + call: induct + args: [ + *acc_alice_acc32 + ] + fellowship_promote_1_alice_cp: + chain: *collectives_parachain + encode: true + pallet: fellowshipCore + call: promote + args: [ + *acc_alice_acc32, + 1 + ] + fellowship_promote_2_alice_cp: + chain: *collectives_parachain + encode: true + pallet: fellowshipCore + call: promote + args: [ + *acc_alice_acc32, + 2 + ] + fellowship_promote_3_alice_cp: + chain: *collectives_parachain + encode: true + pallet: fellowshipCore + call: promote + args: [ + *acc_alice_acc32, + 3 + ] + send_init_fellowship_rc: + chain: *relay_chain + encode: false + pallet: xcmPallet + call: send + args: [ + { v3: { parents: 0, interior: { x1: { parachain: *cp_id }}}}, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: Unlimited + } + }, + { # since batch_all not yet allowed over xcm, we have to send multiple `Transact`. + Transact: { + originKind: Xcm, + requireWeightAtMost: { + refTime: 1500000000, # 1_500_000_000 + proofSize: 10000, # 10_000 + }, + call: $fellowship_induct_alice_cp + } + }, + { + Transact: { + originKind: Xcm, + requireWeightAtMost: { + refTime: 1500000000, # 1_500_000_000 + proofSize: 10000, # 10_000 + }, + call: $fellowship_promote_1_alice_cp + } + }, + { + Transact: { + originKind: Xcm, + requireWeightAtMost: { + refTime: 1500000000, # 1_500_000_000 + proofSize: 10000, # 10_000 + }, + call: $fellowship_promote_2_alice_cp + } + }, + { + Transact: { + originKind: Xcm, + requireWeightAtMost: { + refTime: 1500000000, # 1_500_000_000 + proofSize: 10000, # 10_000 + }, + call: $fellowship_promote_3_alice_cp + } + } + ] + } + ] + +tests: + - name: Fellowship + describes: + - name: Init the Fellowship + its: + - name: Note preimage from init fellowship call + actions: + - extrinsics: + - chain: *relay_chain + signer: *alice_signer + pallet: preimage + call: notePreimage + args: [ + $send_init_fellowship_rc + ] + events: + - name: preimage.Noted + result: { hash_: $send_init_fellowship_rc.hash } + - name: Submit a proposal to init the Fellowship + actions: + - extrinsics: + - chain: *relay_chain + signer: *alice_signer + pallet: referenda + call: submit + args: [ + { + "Origins": "FellowshipAdmin", + }, + { + "Lookup": { + "hash_": $send_init_fellowship_rc.hash, + "len": $send_init_fellowship_rc.len, + }, + }, + { + "After": 1, + }, + ] + events: + - name: referenda.Submitted + result: { + index: *proposal_index, + proposal: { Lookup: { hash_: $send_init_fellowship_rc.hash, len: $send_init_fellowship_rc.len }} + } + - name: Alice Vote Aye + actions: + - extrinsics: + - chain: *relay_chain + signer: *alice_signer + pallet: convictionVoting + call: vote + args: [ + *proposal_index, + { + "Standard": { + "vote": { + "aye": true, + "conviction": "Locked1x", + }, + "balance": 200000000000000, + } + }, + ] # TODO no Aye event to catch https://github.com/paritytech/substrate/issues/14687 + - name: Bob Vote Aye + actions: + - extrinsics: + - chain: *relay_chain + signer: *bob_signer + pallet: convictionVoting + call: vote + args: [ + *proposal_index, + { + "Standard": { + "vote": { + "aye": true, + "conviction": "Locked1x", + }, + "balance": 200000000000000, + } + }, + ] # TODO no Aye event to catch https://github.com/paritytech/substrate/issues/14687 + - name: Submit the decision deposit + actions: + - extrinsics: + - chain: *relay_chain + signer: *alice_signer + pallet: referenda + call: placeDecisionDeposit + args: [ + *proposal_index, + ] + events: + - name: referenda.DecisionDepositPlaced + result: { index: *proposal_index } + - name: fellowshipCollective.MemberAdded + chain: *collectives_parachain + result: { who: *acc_alice_ss58 } diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/3_fellowship/1_whitelist_call.yml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/3_fellowship/1_whitelist_call.yml new file mode 100644 index 00000000000..5991c7ae2f8 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/3_fellowship/1_whitelist_call.yml @@ -0,0 +1,146 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9700 + collectives_parachain: &collectives_parachain + wsPort: 9710 + paraId: &cp_id 1001 + variables: + fellows_proposal_index: &fellows_proposal_index 0 + chains: + accounts: + alice_signer: &alice_signer //Alice + decodedCalls: + remark_rc: + chain: *relay_chain + encode: false + pallet: system + call: remark + args: [ + "0x10" + ] + whitelist_remark_rc: + chain: *relay_chain + encode: true + pallet: whitelist + call: whitelistCall + args: [ + $remark_rc.hash + ] + send_whitelist_remark_cp: + chain: *collectives_parachain + encode: false + pallet: polkadotXcm + call: send + args: [ + { v3: { parents: 1, interior: { here: true }}}, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: Unlimited + } + }, + { + Transact: { + originKind: Xcm, + requireWeightAtMost: { + refTime: 500000000, # 500_000_000 + proofSize: 20000, # 20_000 + }, + call: $whitelist_remark_rc + } + } + ] + } + ] + +tests: + - name: Fellowship + describes: + - name: The Fellowship white list the call + its: + - name: Note preimage from the whitelist call on the Relay Chain + actions: + - extrinsics: + - chain: *relay_chain + signer: *alice_signer + pallet: preimage + call: notePreimage + args: [ + $remark_rc + ] + events: + - name: preimage.Noted + result: { hash_: $remark_rc.hash } + - name: Note preimage from the xcm send call to white list the call above + actions: + - extrinsics: + - chain: *collectives_parachain + signer: *alice_signer + pallet: preimage + call: notePreimage + args: [ + $send_whitelist_remark_cp, + ] + events: + - name: preimage.Noted + result: { hash_: $send_whitelist_remark_cp.hash } + - name: Submit a proposal to while list the call + actions: + - extrinsics: + - chain: *collectives_parachain + signer: *alice_signer + pallet: fellowshipReferenda + call: submit + args: [ + { + "FellowshipOrigins": "Fellows", + }, + { + "Lookup": { + "hash_": $send_whitelist_remark_cp.hash, + "len": $send_whitelist_remark_cp.len, + }, + }, + { + "After": 1, + }, + ] + events: + - name: fellowshipReferenda.Submitted + result: { + index: *fellows_proposal_index, + proposal: { Lookup: { hash_: $send_whitelist_remark_cp.hash, len: $send_whitelist_remark_cp.len}} + } + - name: Vote Aye + actions: + - extrinsics: + - chain: *collectives_parachain + signer: *alice_signer + pallet: fellowshipCollective + call: vote + args: [ + *fellows_proposal_index, + true, + ] + events: + - name: fellowshipCollective.Voted + result: { poll: *fellows_proposal_index, vote: { Aye: 1 } } + - name: Submit the decision deposit + actions: + - extrinsics: + - chain: *collectives_parachain + signer: *alice_signer + pallet: fellowshipReferenda + call: placeDecisionDeposit + args: [ + *fellows_proposal_index, + ] + events: + - name: fellowshipReferenda.DecisionDepositPlaced + result: {index: *fellows_proposal_index} + - name: whitelist.CallWhitelisted + chain: *relay_chain + result: { callHash: $remark_rc.hash } diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/3_fellowship/2_assethub.yml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/3_fellowship/2_assethub.yml new file mode 100644 index 00000000000..c0805594808 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/3_fellowship/2_assethub.yml @@ -0,0 +1,126 @@ +--- +settings: + chains: + relay_chain: &relay_chain + wsPort: 9700 + collectives_parachain: &collectives_parachain + wsPort: 9710 + paraId: &cp_id 1001 + assethub_parachain: &assethub_parachain + wsPort: 9810 + paraId: &ap_id 1000 + variables: + fellows_proposal_index: &fellows_proposal_index 1 + chains: + accounts: + alice_signer: &alice_signer //Alice + + decodedCalls: + xcmp_resume_execution_ap: + chain: *assethub_parachain + encode: true + pallet: xcmpQueue + call: resumeXcmExecution + args: [] + send_xcmp_resume_execution_cp: + chain: *collectives_parachain + encode: false + pallet: polkadotXcm + call: send + args: [ + { v3: { parents: 1, interior: { x1: { parachain: *ap_id }}}}, # destination + { + v3: [ #message + { + UnpaidExecution: { + weightLimit: Unlimited + } + }, + { + Transact: { + originKind: Xcm, + requireWeightAtMost: { + refTime: 300000000, # 300_000_000 + proofSize: 10000, # 10_000 + }, + call: $xcmp_resume_execution_ap + } + } + ] + } + ] + +tests: + - name: Fellowship + describes: + - name: The Fellowship resume xcm execution for the xcmp queue on AssetHub + its: + - name: Note preimage from the xcm send call to suspend_xcm_execution + actions: + - extrinsics: + - chain: *collectives_parachain + signer: *alice_signer + pallet: preimage + call: notePreimage + args: [ + $send_xcmp_resume_execution_cp + ] + events: + - name: preimage.Noted + result: {hash_: $send_xcmp_resume_execution_cp.hash } + - name: Submit a proposal to resume xcm execution on AssetHub + actions: + - extrinsics: + - chain: *collectives_parachain + signer: *alice_signer + pallet: fellowshipReferenda + call: submit + args: [ + { + "FellowshipOrigins": "Fellows", + }, + { + "Lookup": { + "hash_": $send_xcmp_resume_execution_cp.hash, + "len": $send_xcmp_resume_execution_cp.len, + }, + }, + { + "After": 1, + }, + ] + events: + - name: fellowshipReferenda.Submitted + result: { + index: 1, + proposal: {Lookup: {hash_: $send_xcmp_resume_execution_cp.hash, len: $send_xcmp_resume_execution_cp.len}} + } + - name: Vote Aye + actions: + - extrinsics: + - chain: *collectives_parachain + signer: *alice_signer + pallet: fellowshipCollective + call: vote + args: [ + *fellows_proposal_index, + true, + ] + events: + - name: fellowshipCollective.Voted + result: { poll: *fellows_proposal_index, vote: { Aye: 1 } } + - name: Submit the decision deposit + actions: + - extrinsics: + - chain: *collectives_parachain + signer: *alice_signer + pallet: fellowshipReferenda + call: placeDecisionDeposit + args: [ + *fellows_proposal_index, + ] + events: + - name: fellowshipReferenda.DecisionDepositPlaced + result: {index: *fellows_proposal_index} + - name: xcmpQueue.Success + chain: *assethub_parachain diff --git a/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/config.toml b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/config.toml new file mode 100644 index 00000000000..20fda92bd08 --- /dev/null +++ b/cumulus/parachains/integration-tests/e2e/collectives/collectives-polkadot/config.toml @@ -0,0 +1,42 @@ +[relaychain] +default_command = "./bin/polkadot" +default_args = [ "-lparachain=trace", "-lxcm=trace" ] +chain = "polkadot-local" + + [[relaychain.nodes]] + name = "alice" + ws_port = 9700 + validator = true + args = ["--state-cache-size=0"] + + [[relaychain.nodes]] + name = "bob" + ws_port = 9701 + validator = true + + [[relaychain.nodes]] + name = "charlie" + ws_port = 9702 + validator = true + + [[relaychain.nodes]] + name = "dave" + ws_port = 9703 + validator = true + +[[parachains]] +id = 1001 +chain = "collectives-polkadot-local" +cumulus_based = true + + [[parachains.collators]] + name = "collator1" + ws_port = 9710 + command = "./bin/polkadot-parachain" + args = [ "-lxcm=trace", "--state-cache-size=0" ] + + [[parachains.collators]] + name = "collator2" + ws_port = 9711 + command = "./bin/polkadot-parachain" + args = ["-lxcm=trace"] 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 1596169efbe..dbf7e9c9a70 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 @@ -7,9 +7,6 @@ license = "Apache-2.0" description = "Asset Hub Rococo emulated chain" publish = false -[lints] -workspace = true - [dependencies] serde_json = "1.0.104" diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/src/lib.rs index 05454a2e573..1ed22b3cc4f 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/src/lib.rs @@ -21,8 +21,8 @@ use frame_support::traits::OnInitialize; // Cumulus use emulated_integration_tests_common::{ impl_accounts_helpers_for_parachain, impl_assert_events_helpers_for_parachain, - impl_assets_helpers_for_parachain, impl_foreign_assets_helpers_for_parachain, - impl_xcm_helpers_for_parachain, impls::Parachain, xcm_emulator::decl_test_parachains, + impl_assets_helpers_for_parachain, impl_foreign_assets_helpers_for_parachain, impls::Parachain, + xcm_emulator::decl_test_parachains, }; use rococo_emulated_chain::Rococo; @@ -52,7 +52,6 @@ decl_test_parachains! { // AssetHubRococo implementation impl_accounts_helpers_for_parachain!(AssetHubRococo); -impl_assert_events_helpers_for_parachain!(AssetHubRococo); +impl_assert_events_helpers_for_parachain!(AssetHubRococo, false); impl_assets_helpers_for_parachain!(AssetHubRococo, Rococo); impl_foreign_assets_helpers_for_parachain!(AssetHubRococo, Rococo); -impl_xcm_helpers_for_parachain!(AssetHubRococo); 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 ff5a70628db..0ff817b6b96 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 @@ -7,9 +7,6 @@ license = "Apache-2.0" description = "Asset Hub Westend emulated chain" publish = false -[lints] -workspace = true - [dependencies] serde_json = "1.0.104" diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/src/lib.rs index 56382fad564..4dcdb613ac2 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/src/lib.rs @@ -21,8 +21,8 @@ use frame_support::traits::OnInitialize; // Cumulus use emulated_integration_tests_common::{ impl_accounts_helpers_for_parachain, impl_assert_events_helpers_for_parachain, - impl_assets_helpers_for_parachain, impl_foreign_assets_helpers_for_parachain, - impl_xcm_helpers_for_parachain, impls::Parachain, xcm_emulator::decl_test_parachains, + impl_assets_helpers_for_parachain, impl_foreign_assets_helpers_for_parachain, impls::Parachain, + xcm_emulator::decl_test_parachains, }; use westend_emulated_chain::Westend; @@ -52,7 +52,6 @@ decl_test_parachains! { // AssetHubWestend implementation impl_accounts_helpers_for_parachain!(AssetHubWestend); -impl_assert_events_helpers_for_parachain!(AssetHubWestend); +impl_assert_events_helpers_for_parachain!(AssetHubWestend, false); impl_assets_helpers_for_parachain!(AssetHubWestend, Westend); impl_foreign_assets_helpers_for_parachain!(AssetHubWestend, Westend); -impl_xcm_helpers_for_parachain!(AssetHubWestend); 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 8a56bb7b27f..43c0f5fd14c 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 @@ -7,9 +7,6 @@ license = "Apache-2.0" description = "Bridge Hub Rococo emulated chain" publish = false -[lints] -workspace = true - [dependencies] serde_json = "1.0.104" diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/src/lib.rs index 8162823dfce..ea0c9513abc 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/src/lib.rs @@ -21,7 +21,7 @@ use frame_support::traits::OnInitialize; // Cumulus use emulated_integration_tests_common::{ impl_accounts_helpers_for_parachain, impl_assert_events_helpers_for_parachain, - impl_xcm_helpers_for_parachain, impls::Parachain, xcm_emulator::decl_test_parachains, + impls::Parachain, xcm_emulator::decl_test_parachains, }; // BridgeHubRococo Parachain declaration @@ -46,5 +46,4 @@ decl_test_parachains! { // BridgeHubRococo implementation impl_accounts_helpers_for_parachain!(BridgeHubRococo); -impl_assert_events_helpers_for_parachain!(BridgeHubRococo); -impl_xcm_helpers_for_parachain!(BridgeHubRococo); +impl_assert_events_helpers_for_parachain!(BridgeHubRococo, false); 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 a2268f3b17a..e5e6fd70739 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 @@ -7,9 +7,6 @@ license = "Apache-2.0" description = "Bridge Hub Westend emulated chain" publish = false -[lints] -workspace = true - [dependencies] serde_json = "1.0.104" diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/lib.rs index c996b8045e7..4a130ac1f27 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/lib.rs @@ -21,7 +21,7 @@ use frame_support::traits::OnInitialize; // Cumulus use emulated_integration_tests_common::{ impl_accounts_helpers_for_parachain, impl_assert_events_helpers_for_parachain, - impl_xcm_helpers_for_parachain, impls::Parachain, xcm_emulator::decl_test_parachains, + impls::Parachain, xcm_emulator::decl_test_parachains, }; // BridgeHubWestend Parachain declaration @@ -46,5 +46,4 @@ decl_test_parachains! { // BridgeHubWestend implementation impl_accounts_helpers_for_parachain!(BridgeHubWestend); -impl_assert_events_helpers_for_parachain!(BridgeHubWestend); -impl_xcm_helpers_for_parachain!(BridgeHubWestend); +impl_assert_events_helpers_for_parachain!(BridgeHubWestend, false); 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 deleted file mode 100644 index 54d2d9b6b98..00000000000 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "collectives-westend-emulated-chain" -version = "0.0.0" -authors.workspace = true -edition.workspace = true -license = "Apache-2.0" -description = "Collectives Westend emulated chain" -publish = false - -[lints] -workspace = true - -[dependencies] -serde_json = "1.0.104" - -# Substrate -sp-core = { path = "../../../../../../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../../../../../../substrate/primitives/runtime", default-features = false } -frame-support = { path = "../../../../../../../../substrate/frame/support", default-features = false } - -# Polakadot -parachains-common = { path = "../../../../../../../parachains/common" } - -# Cumulus -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" } -westend-emulated-chain = { path = "../../../relays/westend" } diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/src/genesis.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/src/genesis.rs deleted file mode 100644 index d79ef55072a..00000000000 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/src/genesis.rs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Substrate -use sp_core::storage::Storage; - -// Cumulus -use emulated_integration_tests_common::{ - accounts, build_genesis_storage, collators, SAFE_XCM_VERSION, -}; -use parachains_common::Balance; - -pub const PARA_ID: u32 = 1001; -pub const ED: Balance = parachains_common::westend::currency::EXISTENTIAL_DEPOSIT; - -pub fn genesis() -> Storage { - let genesis_config = collectives_westend_runtime::RuntimeGenesisConfig { - system: collectives_westend_runtime::SystemConfig::default(), - balances: collectives_westend_runtime::BalancesConfig { - balances: accounts::init_balances().iter().cloned().map(|k| (k, ED * 4096)).collect(), - }, - parachain_info: collectives_westend_runtime::ParachainInfoConfig { - parachain_id: PARA_ID.into(), - ..Default::default() - }, - collator_selection: collectives_westend_runtime::CollatorSelectionConfig { - invulnerables: collators::invulnerables().iter().cloned().map(|(acc, _)| acc).collect(), - candidacy_bond: ED * 16, - ..Default::default() - }, - session: collectives_westend_runtime::SessionConfig { - keys: collators::invulnerables() - .into_iter() - .map(|(acc, aura)| { - ( - acc.clone(), // account id - acc, // validator id - collectives_westend_runtime::SessionKeys { aura }, // session keys - ) - }) - .collect(), - }, - polkadot_xcm: collectives_westend_runtime::PolkadotXcmConfig { - safe_xcm_version: Some(SAFE_XCM_VERSION), - ..Default::default() - }, - ..Default::default() - }; - - build_genesis_storage( - &genesis_config, - collectives_westend_runtime::WASM_BINARY - .expect("WASM binary was not built, please build it!"), - ) -} diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/src/lib.rs deleted file mode 100644 index 5d553b6f103..00000000000 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/src/lib.rs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -pub mod genesis; - -// Substrate -use frame_support::traits::OnInitialize; - -// Cumulus -use emulated_integration_tests_common::{ - impl_accounts_helpers_for_parachain, impl_assert_events_helpers_for_parachain, - impls::Parachain, xcm_emulator::decl_test_parachains, -}; - -// CollectivesWestend Parachain declaration -decl_test_parachains! { - pub struct CollectivesWestend { - genesis = genesis::genesis(), - on_init = { - collectives_westend_runtime::AuraExt::on_initialize(1); - }, - runtime = collectives_westend_runtime, - core = { - XcmpMessageHandler: collectives_westend_runtime::XcmpQueue, - LocationToAccountId: collectives_westend_runtime::xcm_config::LocationToAccountId, - ParachainInfo: collectives_westend_runtime::ParachainInfo, - }, - pallets = { - PolkadotXcm: collectives_westend_runtime::PolkadotXcm, - Balances: collectives_westend_runtime::Balances, - FellowshipTreasury: collectives_westend_runtime::FellowshipTreasury, - AssetRate: collectives_westend_runtime::AssetRate, - } - }, -} - -// AssetHubWestend implementation -impl_accounts_helpers_for_parachain!(CollectivesWestend); -impl_assert_events_helpers_for_parachain!(CollectivesWestend); 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 d325b78fa66..c55b10d7180 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 @@ -7,9 +7,6 @@ license = "Apache-2.0" description = "Penpal emulated chain" publish = false -[lints] -workspace = true - [dependencies] serde_json = "1.0.104" @@ -26,4 +23,3 @@ cumulus-primitives-core = { path = "../../../../../../../primitives/core", defau emulated-integration-tests-common = { path = "../../../../common", default-features = false } penpal-runtime = { path = "../../../../../../runtimes/testing/penpal" } rococo-emulated-chain = { path = "../../../relays/rococo" } -westend-emulated-chain = { path = "../../../relays/westend" } diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal/src/lib.rs index 62bafb5cb30..f9a422bfcba 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal/src/lib.rs @@ -15,7 +15,6 @@ mod genesis; pub use genesis::{genesis, ED, PARA_ID_A, PARA_ID_B}; -pub use penpal_runtime::xcm_config::{LocalTeleportableToAssetHub, XcmConfig}; // Substrate use frame_support::traits::OnInitialize; @@ -26,7 +25,6 @@ use emulated_integration_tests_common::{ impl_assets_helpers_for_parachain, impls::Parachain, xcm_emulator::decl_test_parachains, }; use rococo_emulated_chain::Rococo; -use westend_emulated_chain::Westend; // Penpal Parachain declaration decl_test_parachains! { @@ -68,8 +66,6 @@ decl_test_parachains! { // Penpal implementation impl_accounts_helpers_for_parachain!(PenpalA); -impl_accounts_helpers_for_parachain!(PenpalB); impl_assets_helpers_for_parachain!(PenpalA, Rococo); -impl_assets_helpers_for_parachain!(PenpalB, Westend); -impl_assert_events_helpers_for_parachain!(PenpalA); -impl_assert_events_helpers_for_parachain!(PenpalB); +impl_assert_events_helpers_for_parachain!(PenpalA, true); +impl_assert_events_helpers_for_parachain!(PenpalB, 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 d2e54367de2..325c7229517 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/Cargo.toml @@ -7,9 +7,6 @@ license = "Apache-2.0" description = "Rococo emulated chain" publish = false -[lints] -workspace = true - [dependencies] serde_json = "1.0.104" diff --git a/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/src/genesis.rs b/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/src/genesis.rs index 45e1e94de01..6f5f3923ead 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/src/genesis.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/src/genesis.rs @@ -16,6 +16,7 @@ // Substrate use beefy_primitives::ecdsa_crypto::AuthorityId as BeefyId; use grandpa::AuthorityId as GrandpaId; +use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; use sp_consensus_babe::AuthorityId as BabeId; use sp_core::{sr25519, storage::Storage}; @@ -37,6 +38,7 @@ const ENDOWMENT: u128 = 1_000_000 * ROC; fn session_keys( babe: BabeId, grandpa: GrandpaId, + im_online: ImOnlineId, para_validator: ValidatorId, para_assignment: AssignmentId, authority_discovery: AuthorityDiscoveryId, @@ -45,6 +47,7 @@ fn session_keys( rococo_runtime::SessionKeys { babe, grandpa, + im_online, para_validator, para_assignment, authority_discovery, @@ -71,6 +74,7 @@ pub fn genesis() -> Storage { x.4.clone(), x.5.clone(), x.6.clone(), + x.7.clone(), get_from_seed::("Alice"), ), ) diff --git a/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/src/lib.rs index 0791f63235f..7ace9614710 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/src/lib.rs @@ -24,7 +24,7 @@ use emulated_integration_tests_common::{ // Rococo declaration decl_test_relay_chains! { - #[api_version(10)] + #[api_version(9)] pub struct Rococo { genesis = genesis::genesis(), on_init = (), 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 b073bbb94f9..20b9737735f 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/relays/westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/chains/relays/westend/Cargo.toml @@ -7,9 +7,6 @@ license = "Apache-2.0" description = "Westend emulated chain" publish = false -[lints] -workspace = true - [dependencies] serde_json = "1.0.104" diff --git a/cumulus/parachains/integration-tests/emulated/chains/relays/westend/src/genesis.rs b/cumulus/parachains/integration-tests/emulated/chains/relays/westend/src/genesis.rs index e2297100a45..e87b85881d3 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/relays/westend/src/genesis.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/relays/westend/src/genesis.rs @@ -16,6 +16,7 @@ // Substrate use beefy_primitives::ecdsa_crypto::AuthorityId as BeefyId; use grandpa::AuthorityId as GrandpaId; +use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; use sp_consensus_babe::AuthorityId as BabeId; use sp_core::storage::Storage; @@ -38,6 +39,7 @@ const STASH: u128 = 100 * WND; fn session_keys( babe: BabeId, grandpa: GrandpaId, + im_online: ImOnlineId, para_validator: ValidatorId, para_assignment: AssignmentId, authority_discovery: AuthorityDiscoveryId, @@ -46,6 +48,7 @@ fn session_keys( westend_runtime::SessionKeys { babe, grandpa, + im_online, para_validator, para_assignment, authority_discovery, @@ -72,6 +75,7 @@ pub fn genesis() -> Storage { x.4.clone(), x.5.clone(), x.6.clone(), + x.7.clone(), get_from_seed::("Alice"), ), ) diff --git a/cumulus/parachains/integration-tests/emulated/chains/relays/westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/relays/westend/src/lib.rs index 8a5d4bbf808..2ba47250d56 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/relays/westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/relays/westend/src/lib.rs @@ -24,7 +24,7 @@ use emulated_integration_tests_common::{ // Westend declaration decl_test_relay_chains! { - #[api_version(10)] + #[api_version(9)] pub struct Westend { genesis = genesis::genesis(), on_init = (), diff --git a/cumulus/parachains/integration-tests/emulated/common/Cargo.toml b/cumulus/parachains/integration-tests/emulated/common/Cargo.toml index f2e799df810..08bb284cded 100644 --- a/cumulus/parachains/integration-tests/emulated/common/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/common/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license = "Apache-2.0" description = "Common resources for integration testing with xcm-emulator" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.4.0", default-features = false } paste = "1.0.14" @@ -16,29 +13,29 @@ serde_json = "1.0.108" # Substrate grandpa = { package = "sc-consensus-grandpa", path = "../../../../../substrate/client/consensus/grandpa" } -sp-authority-discovery = { path = "../../../../../substrate/primitives/authority-discovery", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-consensus-babe = { path = "../../../../../substrate/primitives/consensus/babe", default-features = false } -pallet-assets = { path = "../../../../../substrate/frame/assets", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -pallet-im-online = { path = "../../../../../substrate/frame/im-online", default-features = false } +sp-authority-discovery = { path = "../../../../../substrate/primitives/authority-discovery", default-features = false} +sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false} +frame-support = { path = "../../../../../substrate/frame/support", default-features = false} +sp-core = { path = "../../../../../substrate/primitives/core", default-features = false} +sp-consensus-babe = { path = "../../../../../substrate/primitives/consensus/babe", default-features = false} +pallet-assets = { path = "../../../../../substrate/frame/assets", default-features = false} +pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false} +pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false} +pallet-im-online = { path = "../../../../../substrate/frame/im-online", default-features = false} beefy-primitives = { package = "sp-consensus-beefy", path = "../../../../../substrate/primitives/consensus/beefy" } # Polkadot polkadot-service = { path = "../../../../../polkadot/node/service", default-features = false, features = ["full-node"] } -polkadot-primitives = { path = "../../../../../polkadot/primitives", default-features = false } +polkadot-primitives = { path = "../../../../../polkadot/primitives", default-features = false} polkadot-runtime-parachains = { path = "../../../../../polkadot/runtime/parachains" } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } +xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false} +pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false} # Cumulus parachains-common = { path = "../../../common" } cumulus-primitives-core = { path = "../../../../primitives/core" } -xcm-emulator = { path = "../../../../xcm/xcm-emulator", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false } +xcm-emulator = { path = "../../../../xcm/xcm-emulator", default-features = false} +cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false} cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system" } asset-test-utils = { path = "../../../runtimes/assets/test-utils" } diff --git a/cumulus/parachains/integration-tests/emulated/common/src/impls.rs b/cumulus/parachains/integration-tests/emulated/common/src/impls.rs index 42b5847d17c..8c94df6d888 100644 --- a/cumulus/parachains/integration-tests/emulated/common/src/impls.rs +++ b/cumulus/parachains/integration-tests/emulated/common/src/impls.rs @@ -38,7 +38,7 @@ pub use polkadot_runtime_parachains::{ inclusion::{AggregateMessageOrigin, UmpQueueId}, }; pub use xcm::{ - prelude::{MultiLocation, OriginKind, Outcome, VersionedXcm, XcmVersion}, + prelude::{MultiLocation, OriginKind, Outcome, VersionedXcm}, v3::Error, DoubleEncoded, }; @@ -173,14 +173,10 @@ macro_rules! impl_accounts_helpers_for_relay_chain { pub fn fund_accounts(accounts: Vec<($crate::impls::AccountId, $crate::impls::Balance)>) { ::execute_with(|| { for account in accounts { - let who = account.0; - let actual = ]>::Balances::free_balance(&who); - let actual = actual.saturating_add(]>::Balances::reserved_balance(&who)); - $crate::impls::assert_ok!(]>::Balances::force_set_balance( ::RuntimeOrigin::root(), - who.into(), - actual.saturating_add(account.1), + account.0.into(), + account.1, )); } }); @@ -390,26 +386,15 @@ macro_rules! impl_accounts_helpers_for_parachain { pub fn fund_accounts(accounts: Vec<($crate::impls::AccountId, $crate::impls::Balance)>) { ::execute_with(|| { for account in accounts { - let who = account.0; - let actual = ]>::Balances::free_balance(&who); - let actual = actual.saturating_add(]>::Balances::reserved_balance(&who)); - $crate::impls::assert_ok!(]>::Balances::force_set_balance( ::RuntimeOrigin::root(), - who.into(), - actual.saturating_add(account.1), + account.0.into(), + account.1, )); } }); } - /// Fund a sovereign account of sibling para. - pub fn fund_para_sovereign(sibling_para_id: $crate::impls::ParaId, balance: $crate::impls::Balance) { - let sibling_location = Self::sibling_location_of(sibling_para_id); - let sovereign_account = Self::sovereign_account_id_of(sibling_location); - Self::fund_accounts(vec![(sovereign_account.into(), balance)]) - } - /// Return local sovereign account of `para_id` on other `network_id` pub fn sovereign_account_of_parachain_on_other_global_consensus( network_id: $crate::impls::NetworkId, @@ -433,7 +418,7 @@ macro_rules! impl_accounts_helpers_for_parachain { #[macro_export] macro_rules! impl_assert_events_helpers_for_parachain { - ( $chain:ident ) => { + ( $chain:ident, $ignore_weight:expr ) => { $crate::impls::paste::paste! { type [<$chain RuntimeEvent>] = <$chain as $crate::impls::Chain>::RuntimeEvent; @@ -446,7 +431,7 @@ macro_rules! impl_assert_events_helpers_for_parachain { [<$chain RuntimeEvent>]::::PolkadotXcm( $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Complete(weight) } ) => { - weight: $crate::impls::weight_within_threshold( + weight: $ignore_weight || $crate::impls::weight_within_threshold( ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), expected_weight.unwrap_or(*weight), *weight @@ -468,7 +453,7 @@ macro_rules! impl_assert_events_helpers_for_parachain { [<$chain RuntimeEvent>]::::PolkadotXcm( $crate::impls::pallet_xcm::Event::Attempted { outcome: $crate::impls::Outcome::Incomplete(weight, error) } ) => { - weight: $crate::impls::weight_within_threshold( + weight: $ignore_weight || $crate::impls::weight_within_threshold( ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), expected_weight.unwrap_or(*weight), *weight @@ -524,7 +509,7 @@ macro_rules! impl_assert_events_helpers_for_parachain { [<$chain RuntimeEvent>]::::MessageQueue($crate::impls::pallet_message_queue::Event::Processed { success: true, weight_used: weight, .. }) => { - weight: $crate::impls::weight_within_threshold( + weight: $ignore_weight || $crate::impls::weight_within_threshold( ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), expected_weight.unwrap_or(*weight), *weight @@ -544,7 +529,7 @@ macro_rules! impl_assert_events_helpers_for_parachain { [<$chain RuntimeEvent>]::::MessageQueue($crate::impls::pallet_message_queue::Event::Processed { success: false, weight_used: weight, .. }) => { - weight: $crate::impls::weight_within_threshold( + weight: $ignore_weight || $crate::impls::weight_within_threshold( ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), expected_weight.unwrap_or(*weight), *weight @@ -575,7 +560,7 @@ macro_rules! impl_assert_events_helpers_for_parachain { vec![ [<$chain RuntimeEvent>]::::MessageQueue($crate::impls::pallet_message_queue::Event::Processed { success: true, weight_used: weight, .. } ) => { - weight: $crate::impls::weight_within_threshold( + weight: $ignore_weight || $crate::impls::weight_within_threshold( ($crate::impls::REF_TIME_THRESHOLD, $crate::impls::PROOF_SIZE_THRESHOLD), expected_weight.unwrap_or(*weight), *weight @@ -805,33 +790,3 @@ macro_rules! impl_foreign_assets_helpers_for_parachain { } }; } - -#[macro_export] -macro_rules! impl_xcm_helpers_for_parachain { - ( $chain:ident ) => { - $crate::impls::paste::paste! { - impl $chain { - /// Set XCM version for destination. - pub fn force_xcm_version(dest: $crate::impls::MultiLocation, version: $crate::impls::XcmVersion) { - ::execute_with(|| { - $crate::impls::assert_ok!(]>::PolkadotXcm::force_xcm_version( - ::RuntimeOrigin::root(), - $crate::impls::bx!(dest), - version, - )); - }); - } - - /// Set default/safe XCM version for runtime. - pub fn force_default_xcm_version(version: Option<$crate::impls::XcmVersion>) { - ::execute_with(|| { - $crate::impls::assert_ok!(]>::PolkadotXcm::force_default_xcm_version( - ::RuntimeOrigin::root(), - version, - )); - }); - } - } - } - } -} diff --git a/cumulus/parachains/integration-tests/emulated/common/src/lib.rs b/cumulus/parachains/integration-tests/emulated/common/src/lib.rs index 58222f622c2..952b053f2aa 100644 --- a/cumulus/parachains/integration-tests/emulated/common/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/common/src/lib.rs @@ -21,6 +21,7 @@ pub use xcm_emulator; // Substrate use grandpa::AuthorityId as GrandpaId; +use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use sp_authority_discovery::AuthorityId as AuthorityDiscoveryId; use sp_consensus_babe::AuthorityId as BabeId; use sp_core::{sr25519, storage::Storage, Pair, Public}; @@ -162,6 +163,7 @@ pub mod validators { AccountId, BabeId, GrandpaId, + ImOnlineId, ValidatorId, AssignmentId, AuthorityDiscoveryId, diff --git a/cumulus/parachains/integration-tests/emulated/common/src/macros.rs b/cumulus/parachains/integration-tests/emulated/common/src/macros.rs index 8718f1e83a0..6ea3524ed4a 100644 --- a/cumulus/parachains/integration-tests/emulated/common/src/macros.rs +++ b/cumulus/parachains/integration-tests/emulated/common/src/macros.rs @@ -120,102 +120,3 @@ macro_rules! test_parachain_is_trusted_teleporter { } }; } - -#[macro_export] -macro_rules! include_penpal_create_foreign_asset_on_asset_hub { - ( $penpal:ident, $asset_hub:ident, $relay_ed:expr, $weight_to_fee:expr) => { - $crate::impls::paste::paste! { - pub fn penpal_create_foreign_asset_on_asset_hub( - asset_id_on_penpal: u32, - foreign_asset_at_asset_hub: MultiLocation, - ah_as_seen_by_penpal: MultiLocation, - is_sufficient: bool, - asset_owner: AccountId, - prefund_amount: u128, - ) { - use frame_support::weights::WeightToFee; - let ah_check_account = $asset_hub::execute_with(|| { - <$asset_hub as [<$asset_hub Pallet>]>::PolkadotXcm::check_account() - }); - let penpal_check_account = - $penpal::execute_with(|| <$penpal as [<$penpal Pallet>]>::PolkadotXcm::check_account()); - let penpal_as_seen_by_ah = $asset_hub::sibling_location_of($penpal::para_id()); - - // prefund SA of Penpal on AssetHub with enough native tokens to pay for creating - // new foreign asset, also prefund CheckingAccount with ED, because teleported asset - // itself might not be sufficient and CheckingAccount cannot be created otherwise - let sov_penpal_on_ah = $asset_hub::sovereign_account_id_of(penpal_as_seen_by_ah); - $asset_hub::fund_accounts(vec![ - (sov_penpal_on_ah.clone().into(), $relay_ed * 100_000_000_000), - (ah_check_account.clone().into(), $relay_ed * 1000), - ]); - - // prefund SA of AssetHub on Penpal with native asset - let sov_ah_on_penpal = $penpal::sovereign_account_id_of(ah_as_seen_by_penpal); - $penpal::fund_accounts(vec![ - (sov_ah_on_penpal.into(), $relay_ed * 1_000_000_000), - (penpal_check_account.clone().into(), $relay_ed * 1000), - ]); - - // Force create asset on $penpal and prefund [<$penpal Sender>] - $penpal::force_create_and_mint_asset( - asset_id_on_penpal, - ASSET_MIN_BALANCE, - is_sufficient, - asset_owner, - None, - prefund_amount, - ); - - let require_weight_at_most = Weight::from_parts(1_100_000_000_000, 30_000); - // `OriginKind::Xcm` required by ForeignCreators pallet-assets origin filter - let origin_kind = OriginKind::Xcm; - let call_create_foreign_assets = - <$asset_hub as Chain>::RuntimeCall::ForeignAssets(pallet_assets::Call::< - <$asset_hub as Chain>::Runtime, - pallet_assets::Instance2, - >::create { - id: foreign_asset_at_asset_hub, - min_balance: ASSET_MIN_BALANCE, - admin: sov_penpal_on_ah.into(), - }) - .encode(); - let buy_execution_fee_amount = $weight_to_fee::weight_to_fee( - &Weight::from_parts(10_100_000_000_000, 300_000), - ); - let buy_execution_fee = MultiAsset { - id: Concrete(MultiLocation { parents: 1, interior: Here }), - fun: Fungible(buy_execution_fee_amount), - }; - let xcm = VersionedXcm::from(Xcm(vec![ - WithdrawAsset { 0: vec![buy_execution_fee.clone()].into() }, - BuyExecution { fees: buy_execution_fee.clone(), weight_limit: Unlimited }, - Transact { require_weight_at_most, origin_kind, call: call_create_foreign_assets.into() }, - ExpectTransactStatus(MaybeErrorCode::Success), - RefundSurplus, - DepositAsset { assets: All.into(), beneficiary: penpal_as_seen_by_ah }, - ])); - // Send XCM message from penpal => asset_hub - let sudo_penpal_origin = <$penpal as Chain>::RuntimeOrigin::root(); - $penpal::execute_with(|| { - assert_ok!(<$penpal as [<$penpal Pallet>]>::PolkadotXcm::send( - sudo_penpal_origin.clone(), - bx!(ah_as_seen_by_penpal.into()), - bx!(xcm), - )); - type RuntimeEvent = <$penpal as Chain>::RuntimeEvent; - assert_expected_events!( - $penpal, - vec![ - RuntimeEvent::PolkadotXcm(pallet_xcm::Event::Sent { .. }) => {}, - ] - ); - }); - $asset_hub::execute_with(|| { - type ForeignAssets = <$asset_hub as [<$asset_hub Pallet>]>::ForeignAssets; - assert!(ForeignAssets::asset_exists(foreign_asset_at_asset_hub)); - }); - } - } - }; -} diff --git a/cumulus/parachains/integration-tests/emulated/common/src/xcm_helpers.rs b/cumulus/parachains/integration-tests/emulated/common/src/xcm_helpers.rs index 70a9408c309..47e92ed075f 100644 --- a/cumulus/parachains/integration-tests/emulated/common/src/xcm_helpers.rs +++ b/cumulus/parachains/integration-tests/emulated/common/src/xcm_helpers.rs @@ -59,17 +59,3 @@ pub fn xcm_transact_unpaid_execution( Transact { require_weight_at_most, origin_kind, call }, ])) } - -/// Helper method to get the non-fee asset used in multiple assets transfer -pub fn non_fee_asset(assets: &MultiAssets, fee_idx: usize) -> Option<(MultiLocation, u128)> { - let asset = assets.inner().into_iter().enumerate().find(|a| a.0 != fee_idx)?.1.clone(); - let asset_id = match asset.id { - Concrete(id) => id, - _ => return None, - }; - let asset_amount = match asset.fun { - Fungible(amount) => amount, - _ => return None, - }; - Some((asset_id, asset_amount)) -} diff --git a/cumulus/parachains/integration-tests/emulated/networks/rococo-system/Cargo.toml b/cumulus/parachains/integration-tests/emulated/networks/rococo-system/Cargo.toml index bb31f8e467d..713cc2ecdbb 100644 --- a/cumulus/parachains/integration-tests/emulated/networks/rococo-system/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/networks/rococo-system/Cargo.toml @@ -7,9 +7,6 @@ license = "Apache-2.0" description = "Rococo System emulated network" publish = false -[lints] -workspace = true - [dependencies] # Cumulus emulated-integration-tests-common = { path = "../../common", default-features = false } 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 2a538b8e28c..34713f5b48e 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 @@ -7,9 +7,6 @@ license = "Apache-2.0" description = "Rococo<>Westend emulated bridged network" publish = false -[lints] -workspace = true - [dependencies] # Cumulus emulated-integration-tests-common = { path = "../../common", default-features = false } 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 80ffb9cfd6c..a4360076d6b 100644 --- a/cumulus/parachains/integration-tests/emulated/networks/westend-system/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/networks/westend-system/Cargo.toml @@ -7,14 +7,10 @@ license = "Apache-2.0" description = "Westend System emulated network" publish = false -[lints] -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" } diff --git a/cumulus/parachains/integration-tests/emulated/networks/westend-system/src/lib.rs b/cumulus/parachains/integration-tests/emulated/networks/westend-system/src/lib.rs index 26cd5c7e860..667b44a6986 100644 --- a/cumulus/parachains/integration-tests/emulated/networks/westend-system/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/networks/westend-system/src/lib.rs @@ -15,13 +15,11 @@ pub use asset_hub_westend_emulated_chain; pub use bridge_hub_westend_emulated_chain; -pub use collectives_westend_emulated_chain; pub use penpal_emulated_chain; pub use westend_emulated_chain; use asset_hub_westend_emulated_chain::AssetHubWestend; use bridge_hub_westend_emulated_chain::BridgeHubWestend; -use collectives_westend_emulated_chain::CollectivesWestend; use penpal_emulated_chain::{PenpalA, PenpalB}; use westend_emulated_chain::Westend; @@ -37,7 +35,6 @@ decl_test_networks! { parachains = vec![ AssetHubWestend, BridgeHubWestend, - CollectivesWestend, PenpalA, PenpalB, ], @@ -49,7 +46,6 @@ decl_test_sender_receiver_accounts_parameter_types! { WestendRelay { sender: ALICE, receiver: BOB }, AssetHubWestendPara { sender: ALICE, receiver: BOB }, BridgeHubWestendPara { sender: ALICE, receiver: BOB }, - CollectivesWestendPara { sender: ALICE, receiver: BOB }, PenpalAPara { sender: ALICE, receiver: BOB }, PenpalBPara { sender: ALICE, receiver: BOB } } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/Cargo.toml index 445395fc783..23f80f33f78 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 @@ -7,25 +7,22 @@ license = "Apache-2.0" description = "Asset Hub Rococo runtime integration tests with xcm-emulator" publish = false -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.4.0", default-features = false } assert_matches = "1.5.0" # 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 } +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 } # 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 = { 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" } # Cumulus @@ -33,4 +30,5 @@ asset-test-utils = { path = "../../../../../runtimes/assets/test-utils" } parachains-common = { path = "../../../../../../parachains/common" } asset-hub-rococo-runtime = { path = "../../../../../runtimes/assets/asset-hub-rococo" } emulated-integration-tests-common = { path = "../../../common", default-features = false } -rococo-system-emulated-network = { path = "../../../networks/rococo-system" } +penpal-runtime = { path = "../../../../../runtimes/testing/penpal" } +rococo-system-emulated-network ={ path = "../../../networks/rococo-system" } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/mod.rs index c9270934ddf..b3841af0e6c 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/mod.rs @@ -18,11 +18,3 @@ mod send; mod set_xcm_versions; mod swap; mod teleport; - -use crate::*; -emulated_integration_tests_common::include_penpal_create_foreign_asset_on_asset_hub!( - PenpalA, - AssetHubRococo, - ROCOCO_ED, - parachains_common::rococo::fee::WeightToFee -); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/reserve_transfer.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/reserve_transfer.rs index e6142e29b7c..d0e9b72176b 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/reserve_transfer.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/reserve_transfer.rs @@ -15,12 +15,14 @@ use crate::*; use asset_hub_rococo_runtime::xcm_config::XcmConfig as AssetHubRococoXcmConfig; +use penpal_runtime::xcm_config::XcmConfig as PenpalRococoXcmConfig; use rococo_runtime::xcm_config::XcmConfig as RococoXcmConfig; -use rococo_system_emulated_network::penpal_emulated_chain::XcmConfig as PenpalRococoXcmConfig; fn relay_to_para_sender_assertions(t: RelayToParaTest) { type RuntimeEvent = ::RuntimeEvent; + Rococo::assert_xcm_pallet_attempted_complete(Some(Weight::from_parts(864_610_000, 8_799))); + assert_expected_events!( Rococo, vec![ @@ -38,12 +40,27 @@ fn relay_to_para_sender_assertions(t: RelayToParaTest) { ); } +fn relay_to_para_receiver_assertions(_: Test) { + type RuntimeEvent = ::RuntimeEvent; + assert_expected_events!( + PenpalA, + vec![ + RuntimeEvent::Balances(pallet_balances::Event::Deposit { .. }) => {}, + RuntimeEvent::MessageQueue( + pallet_message_queue::Event::Processed { success: true, .. } + ) => {}, + ] + ); +} + fn system_para_to_para_sender_assertions(t: SystemParaToParaTest) { type RuntimeEvent = ::RuntimeEvent; + AssetHubRococo::assert_xcm_pallet_attempted_complete(Some(Weight::from_parts( 864_610_000, 8_799, ))); + assert_expected_events!( AssetHubRococo, vec![ @@ -61,7 +78,7 @@ fn system_para_to_para_sender_assertions(t: SystemParaToParaTest) { ); } -fn para_receiver_assertions(_: Test) { +fn system_para_to_para_receiver_assertions(_: Test) { type RuntimeEvent = ::RuntimeEvent; assert_expected_events!( PenpalA, @@ -76,7 +93,9 @@ fn para_receiver_assertions(_: Test) { fn para_to_system_para_sender_assertions(t: ParaToSystemParaTest) { type RuntimeEvent = ::RuntimeEvent; + PenpalA::assert_xcm_pallet_attempted_complete(Some(Weight::from_parts(864_610_000, 8_799))); + assert_expected_events!( PenpalA, vec![ @@ -93,13 +112,15 @@ fn para_to_system_para_sender_assertions(t: ParaToSystemParaTest) { fn para_to_system_para_receiver_assertions(t: ParaToSystemParaTest) { type RuntimeEvent = ::RuntimeEvent; + let sov_penpal_on_ahr = AssetHubRococo::sovereign_account_id_of( AssetHubRococo::sibling_location_of(PenpalA::para_id()), ); + assert_expected_events!( AssetHubRococo, vec![ - // Amount to reserve transfer is withdrawn from Parachain's Sovereign account + // Amount to reserve transfer is transferred to Parachain's Sovereign account RuntimeEvent::Balances( pallet_balances::Event::Withdraw { who, amount } ) => { @@ -116,10 +137,12 @@ fn para_to_system_para_receiver_assertions(t: ParaToSystemParaTest) { fn system_para_to_para_assets_sender_assertions(t: SystemParaToParaTest) { type RuntimeEvent = ::RuntimeEvent; + AssetHubRococo::assert_xcm_pallet_attempted_complete(Some(Weight::from_parts( 864_610_000, 8799, ))); + assert_expected_events!( AssetHubRococo, vec![ @@ -152,7 +175,7 @@ fn system_para_to_para_assets_receiver_assertions(_: Test) { ); } -fn relay_to_para_reserve_transfer_assets(t: RelayToParaTest) -> DispatchResult { +fn relay_to_para_limited_reserve_transfer_assets(t: RelayToParaTest) -> DispatchResult { ::XcmPallet::limited_reserve_transfer_assets( t.signed_origin, bx!(t.args.dest.into()), @@ -163,7 +186,7 @@ fn relay_to_para_reserve_transfer_assets(t: RelayToParaTest) -> DispatchResult { ) } -fn system_para_to_para_reserve_transfer_assets(t: SystemParaToParaTest) -> DispatchResult { +fn system_para_to_para_limited_reserve_transfer_assets(t: SystemParaToParaTest) -> DispatchResult { ::PolkadotXcm::limited_reserve_transfer_assets( t.signed_origin, bx!(t.args.dest.into()), @@ -174,7 +197,7 @@ fn system_para_to_para_reserve_transfer_assets(t: SystemParaToParaTest) -> Dispa ) } -fn para_to_system_para_reserve_transfer_assets(t: ParaToSystemParaTest) -> DispatchResult { +fn para_to_system_para_limited_reserve_transfer_assets(t: ParaToSystemParaTest) -> DispatchResult { ::PolkadotXcm::limited_reserve_transfer_assets( t.signed_origin, bx!(t.args.dest.into()), @@ -274,8 +297,8 @@ fn reserve_transfer_native_asset_from_relay_to_para() { let receiver_balance_before = test.receiver.balance; test.set_assertion::(relay_to_para_sender_assertions); - test.set_assertion::(para_receiver_assertions); - test.set_dispatchable::(relay_to_para_reserve_transfer_assets); + test.set_assertion::(relay_to_para_receiver_assertions); + test.set_dispatchable::(relay_to_para_limited_reserve_transfer_assets); test.assert(); let delivery_fees = Rococo::execute_with(|| { @@ -291,10 +314,6 @@ fn reserve_transfer_native_asset_from_relay_to_para() { assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after); // Receiver's balance is increased assert!(receiver_balance_after > receiver_balance_before); - // Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`; - // `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown but - // should be non-zero - assert!(receiver_balance_after < receiver_balance_before + amount_to_send); } /// Reserve Transfers of native asset from System Parachain to Parachain should work @@ -318,8 +337,8 @@ fn reserve_transfer_native_asset_from_system_para_to_para() { let receiver_balance_before = test.receiver.balance; test.set_assertion::(system_para_to_para_sender_assertions); - test.set_assertion::(para_receiver_assertions); - test.set_dispatchable::(system_para_to_para_reserve_transfer_assets); + test.set_assertion::(system_para_to_para_receiver_assertions); + test.set_dispatchable::(system_para_to_para_limited_reserve_transfer_assets); test.assert(); let sender_balance_after = test.sender.balance; @@ -335,10 +354,6 @@ fn reserve_transfer_native_asset_from_system_para_to_para() { assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after); // Receiver's balance is increased assert!(receiver_balance_after > receiver_balance_before); - // Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`; - // `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown but - // should be non-zero - assert!(receiver_balance_after < receiver_balance_before + amount_to_send); } /// Reserve Transfers of native asset from Parachain to System Parachain should work @@ -369,7 +384,7 @@ fn reserve_transfer_native_asset_from_para_to_system_para() { test.set_assertion::(para_to_system_para_sender_assertions); test.set_assertion::(para_to_system_para_receiver_assertions); - test.set_dispatchable::(para_to_system_para_reserve_transfer_assets); + test.set_dispatchable::(para_to_system_para_limited_reserve_transfer_assets); test.assert(); let sender_balance_after = test.sender.balance; @@ -385,10 +400,6 @@ fn reserve_transfer_native_asset_from_para_to_system_para() { assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after); // Receiver's balance is increased assert!(receiver_balance_after > receiver_balance_before); - // Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`; - // `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown but - // should be non-zero - assert!(receiver_balance_after < receiver_balance_before + amount_to_send); } /// Reserve Transfers of a local asset and native asset from System Parachain to Parachain should @@ -409,7 +420,7 @@ fn reserve_transfer_assets_from_system_para_to_para() { ASSET_MIN_BALANCE, false, PenpalASender::get(), - None, + Some(Weight::from_parts(1_019_445_000, 200_000)), 0, ); @@ -464,7 +475,7 @@ fn reserve_transfer_assets_from_system_para_to_para() { test.set_assertion::(system_para_to_para_assets_sender_assertions); test.set_assertion::(system_para_to_para_assets_receiver_assertions); - test.set_dispatchable::(system_para_to_para_reserve_transfer_assets); + test.set_dispatchable::(system_para_to_para_limited_reserve_transfer_assets); test.assert(); let sender_balance_after = test.sender.balance; @@ -474,10 +485,6 @@ fn reserve_transfer_assets_from_system_para_to_para() { assert!(sender_balance_after < sender_balance_before); // Receiver's balance is increased assert!(receiver_balance_after > receiver_balance_before); - // Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`; - // `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown but - // should be non-zero - assert!(receiver_balance_after < receiver_balance_before + fee_amount_to_send); let sender_assets_after = AssetHubRococo::execute_with(|| { type Assets = ::Assets; @@ -488,8 +495,8 @@ fn reserve_transfer_assets_from_system_para_to_para() { >::balance(ASSET_ID, &PenpalAReceiver::get()) }); - // Sender's balance is reduced by exact amount + // Sender's balance is reduced assert_eq!(sender_assets_before - asset_amount_to_send, sender_assets_after); - // Receiver's balance is increased by exact amount - assert_eq!(receiver_assets_after, receiver_assets_before + asset_amount_to_send); + // Receiver's balance is increased + assert!(receiver_assets_after > receiver_assets_before); } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/swap.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/swap.rs index 35a660ed3c4..e08af50c14e 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/swap.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/swap.rs @@ -14,10 +14,9 @@ // limitations under the License. use crate::*; -use frame_support::BoundedVec; +use frame_support::{instances::Instance2, BoundedVec}; use parachains_common::rococo::currency::EXISTENTIAL_DEPOSIT; -use rococo_system_emulated_network::penpal_emulated_chain::LocalTeleportableToAssetHub as PenpalLocalTeleportableToAssetHub; -use sp_runtime::ModuleError; +use sp_runtime::{DispatchError, ModuleError}; #[test] fn swap_locally_on_chain_using_local_assets() { @@ -45,6 +44,12 @@ fn swap_locally_on_chain_using_local_assets() { 100_000_000_000_000, )); + assert_ok!(::Balances::force_set_balance( + ::RuntimeOrigin::root(), + AssetHubRococoSender::get().into(), + 100_000_000_000_000, + )); + assert_ok!(::AssetConversion::create_pool( ::RuntimeOrigin::signed(AssetHubRococoSender::get()), asset_native.clone(), @@ -113,37 +118,114 @@ fn swap_locally_on_chain_using_local_assets() { #[test] fn swap_locally_on_chain_using_foreign_assets() { + use frame_support::weights::WeightToFee; + let asset_native = Box::new(asset_hub_rococo_runtime::xcm_config::TokenLocation::get()); - let ah_as_seen_by_penpal = PenpalA::sibling_location_of(AssetHubRococo::para_id()); - let asset_location_on_penpal = PenpalLocalTeleportableToAssetHub::get(); - let asset_id_on_penpal = match asset_location_on_penpal.last() { - Some(GeneralIndex(id)) => *id as u32, - _ => unreachable!(), - }; - let asset_owner_on_penpal = PenpalASender::get(); - let foreign_asset_at_asset_hub_rococo = - MultiLocation { parents: 1, interior: X1(Parachain(PenpalA::para_id().into())) } - .appended_with(asset_location_on_penpal) - .unwrap(); - - // 1. Create asset on penpal and, 2. Create foreign asset on asset_hub_rococo - super::penpal_create_foreign_asset_on_asset_hub( - asset_id_on_penpal, - foreign_asset_at_asset_hub_rococo, - ah_as_seen_by_penpal, - true, - asset_owner_on_penpal, - ASSET_MIN_BALANCE * 1_000_000, - ); - let penpal_as_seen_by_ah = AssetHubRococo::sibling_location_of(PenpalA::para_id()); - let sov_penpal_on_ahr = AssetHubRococo::sovereign_account_id_of(penpal_as_seen_by_ah); + let foreign_asset1_at_asset_hub_rococo = Box::new(MultiLocation { + parents: 1, + interior: X3( + Parachain(PenpalA::para_id().into()), + PalletInstance(ASSETS_PALLET_ID), + GeneralIndex(ASSET_ID.into()), + ), + }); + + let assets_para_destination: VersionedMultiLocation = + MultiLocation { parents: 1, interior: X1(Parachain(AssetHubRococo::para_id().into())) } + .into(); + + let penpal_location = + MultiLocation { parents: 1, interior: X1(Parachain(PenpalA::para_id().into())) }; + + // 1. Create asset on penpal: + PenpalA::execute_with(|| { + assert_ok!(::Assets::create( + ::RuntimeOrigin::signed(PenpalASender::get()), + ASSET_ID.into(), + PenpalASender::get().into(), + 1000, + )); + + assert!(::Assets::asset_exists(ASSET_ID)); + }); + + // 2. Create foreign asset on asset_hub_rococo: + + let require_weight_at_most = Weight::from_parts(1_100_000_000_000, 30_000); + let origin_kind = OriginKind::Xcm; + let sov_penpal_on_asset_hub_rococo = AssetHubRococo::sovereign_account_id_of(penpal_location); + AssetHubRococo::fund_accounts(vec![ (AssetHubRococoSender::get().into(), 5_000_000 * ROCOCO_ED), /* An account to swap dot * for something else. */ + (sov_penpal_on_asset_hub_rococo.clone().into(), 1000_000_000_000_000_000 * ROCOCO_ED), ]); + let sov_penpal_on_asset_hub_rococo_as_location: MultiLocation = MultiLocation { + parents: 0, + interior: X1(AccountId32Junction { + network: None, + id: sov_penpal_on_asset_hub_rococo.clone().into(), + }), + }; + + let call_foreign_assets_create = + ::RuntimeCall::ForeignAssets(pallet_assets::Call::< + ::Runtime, + Instance2, + >::create { + id: *foreign_asset1_at_asset_hub_rococo, + min_balance: 1000, + admin: sov_penpal_on_asset_hub_rococo.clone().into(), + }) + .encode() + .into(); + + let buy_execution_fee_amount = parachains_common::rococo::fee::WeightToFee::weight_to_fee( + &Weight::from_parts(10_100_000_000_000, 300_000), + ); + let buy_execution_fee = MultiAsset { + id: Concrete(MultiLocation { parents: 1, interior: Here }), + fun: Fungible(buy_execution_fee_amount), + }; + + let xcm = VersionedXcm::from(Xcm(vec![ + WithdrawAsset { 0: vec![buy_execution_fee.clone()].into() }, + BuyExecution { fees: buy_execution_fee.clone(), weight_limit: Unlimited }, + Transact { require_weight_at_most, origin_kind, call: call_foreign_assets_create }, + RefundSurplus, + DepositAsset { + assets: All.into(), + beneficiary: sov_penpal_on_asset_hub_rococo_as_location, + }, + ])); + + // Send XCM message from penpal => asset_hub_rococo + let sudo_penpal_origin = ::RuntimeOrigin::root(); + PenpalA::execute_with(|| { + assert_ok!(::PolkadotXcm::send( + sudo_penpal_origin.clone(), + bx!(assets_para_destination.clone()), + bx!(xcm), + )); + + type RuntimeEvent = ::RuntimeEvent; + + assert_expected_events!( + PenpalA, + vec![ + RuntimeEvent::PolkadotXcm(pallet_xcm::Event::Sent { .. }) => {}, + ] + ); + }); + + // Receive XCM message in Assets Parachain AssetHubRococo::execute_with(|| { + assert!(::ForeignAssets::asset_exists( + *foreign_asset1_at_asset_hub_rococo + )); + // 3: Mint foreign asset on asset_hub_rococo: // // (While it might be nice to use batch, @@ -152,9 +234,11 @@ fn swap_locally_on_chain_using_foreign_assets() { type RuntimeEvent = ::RuntimeEvent; // 3. Mint foreign asset (in reality this should be a teleport or some such) assert_ok!(::ForeignAssets::mint( - ::RuntimeOrigin::signed(sov_penpal_on_ahr.clone().into()), - foreign_asset_at_asset_hub_rococo, - sov_penpal_on_ahr.clone().into(), + ::RuntimeOrigin::signed( + sov_penpal_on_asset_hub_rococo.clone().into() + ), + *foreign_asset1_at_asset_hub_rococo, + sov_penpal_on_asset_hub_rococo.clone().into(), 3_000_000_000_000, )); @@ -165,12 +249,11 @@ fn swap_locally_on_chain_using_foreign_assets() { ] ); - let foreign_asset_at_asset_hub_rococo = Box::new(foreign_asset_at_asset_hub_rococo); // 4. Create pool: assert_ok!(::AssetConversion::create_pool( ::RuntimeOrigin::signed(AssetHubRococoSender::get()), asset_native.clone(), - foreign_asset_at_asset_hub_rococo.clone(), + foreign_asset1_at_asset_hub_rococo.clone(), )); assert_expected_events!( @@ -182,14 +265,16 @@ fn swap_locally_on_chain_using_foreign_assets() { // 5. Add liquidity: assert_ok!(::AssetConversion::add_liquidity( - ::RuntimeOrigin::signed(sov_penpal_on_ahr.clone()), + ::RuntimeOrigin::signed( + sov_penpal_on_asset_hub_rococo.clone() + ), asset_native.clone(), - foreign_asset_at_asset_hub_rococo.clone(), + foreign_asset1_at_asset_hub_rococo.clone(), 1_000_000_000_000, 2_000_000_000_000, 0, 0, - sov_penpal_on_ahr.clone().into() + sov_penpal_on_asset_hub_rococo.clone().into() )); assert_expected_events!( @@ -204,7 +289,7 @@ fn swap_locally_on_chain_using_foreign_assets() { // 6. Swap! let path = BoundedVec::<_, _>::truncate_from(vec![ asset_native.clone(), - foreign_asset_at_asset_hub_rococo.clone(), + foreign_asset1_at_asset_hub_rococo.clone(), ]); assert_ok!( @@ -230,13 +315,15 @@ fn swap_locally_on_chain_using_foreign_assets() { // 7. Remove liquidity assert_ok!(::AssetConversion::remove_liquidity( - ::RuntimeOrigin::signed(sov_penpal_on_ahr.clone()), + ::RuntimeOrigin::signed( + sov_penpal_on_asset_hub_rococo.clone() + ), asset_native, - foreign_asset_at_asset_hub_rococo, + foreign_asset1_at_asset_hub_rococo, 1414213562273 - 2_000_000_000, // all but the 2 EDs can't be retrieved. 0, 0, - sov_penpal_on_ahr.clone().into(), + sov_penpal_on_asset_hub_rococo.clone().into(), )); }); } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/teleport.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/teleport.rs index e64c02f5258..f8017f7a1c5 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/teleport.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/teleport.rs @@ -15,9 +15,7 @@ use crate::*; use asset_hub_rococo_runtime::xcm_config::XcmConfig as AssetHubRococoXcmConfig; -use emulated_integration_tests_common::xcm_helpers::non_fee_asset; use rococo_runtime::xcm_config::XcmConfig as RococoXcmConfig; -use rococo_system_emulated_network::penpal_emulated_chain::LocalTeleportableToAssetHub as PenpalLocalTeleportableToAssetHub; fn relay_origin_assertions(t: RelayToSystemParaTest) { type RuntimeEvent = ::RuntimeEvent; @@ -112,123 +110,6 @@ fn para_dest_assertions(t: RelayToSystemParaTest) { ); } -fn penpal_to_ah_foreign_assets_sender_assertions(t: ParaToSystemParaTest) { - type RuntimeEvent = ::RuntimeEvent; - PenpalA::assert_xcm_pallet_attempted_complete(None); - let expected_asset_id = t.args.asset_id.unwrap(); - let (_, expected_asset_amount) = - non_fee_asset(&t.args.assets, t.args.fee_asset_item as usize).unwrap(); - assert_expected_events!( - PenpalA, - vec![ - RuntimeEvent::Balances( - pallet_balances::Event::Withdraw { who, amount } - ) => { - who: *who == t.sender.account_id, - amount: *amount == t.args.amount, - }, - RuntimeEvent::Assets(pallet_assets::Event::Burned { asset_id, owner, balance }) => { - asset_id: *asset_id == expected_asset_id, - owner: *owner == t.sender.account_id, - balance: *balance == expected_asset_amount, - }, - ] - ); -} - -fn penpal_to_ah_foreign_assets_receiver_assertions(t: ParaToSystemParaTest) { - type RuntimeEvent = ::RuntimeEvent; - let sov_penpal_on_ahr = AssetHubRococo::sovereign_account_id_of( - AssetHubRococo::sibling_location_of(PenpalA::para_id()), - ); - let (expected_foreign_asset_id, expected_foreign_asset_amount) = - non_fee_asset(&t.args.assets, t.args.fee_asset_item as usize).unwrap(); - assert_expected_events!( - AssetHubRococo, - vec![ - // native asset reserve transfer for paying fees, withdrawn from Penpal's sov account - RuntimeEvent::Balances( - pallet_balances::Event::Withdraw { who, amount } - ) => { - who: *who == sov_penpal_on_ahr.clone().into(), - amount: *amount == t.args.amount, - }, - RuntimeEvent::Balances(pallet_balances::Event::Deposit { who, .. }) => { - who: *who == t.receiver.account_id, - }, - RuntimeEvent::ForeignAssets(pallet_assets::Event::Issued { asset_id, owner, amount }) => { - asset_id: *asset_id == expected_foreign_asset_id, - owner: *owner == t.receiver.account_id, - amount: *amount == expected_foreign_asset_amount, - }, - RuntimeEvent::Balances(pallet_balances::Event::Deposit { .. }) => {}, - RuntimeEvent::MessageQueue( - pallet_message_queue::Event::Processed { success: true, .. } - ) => {}, - ] - ); -} - -fn ah_to_penpal_foreign_assets_sender_assertions(t: SystemParaToParaTest) { - type RuntimeEvent = ::RuntimeEvent; - AssetHubRococo::assert_xcm_pallet_attempted_complete(None); - let (expected_foreign_asset_id, expected_foreign_asset_amount) = - non_fee_asset(&t.args.assets, t.args.fee_asset_item as usize).unwrap(); - assert_expected_events!( - AssetHubRococo, - vec![ - // native asset used for fees is transferred to Parachain's Sovereign account as reserve - RuntimeEvent::Balances( - pallet_balances::Event::Transfer { from, to, amount } - ) => { - from: *from == t.sender.account_id, - to: *to == AssetHubRococo::sovereign_account_id_of( - t.args.dest - ), - amount: *amount == t.args.amount, - }, - // foreign asset is burned locally as part of teleportation - RuntimeEvent::ForeignAssets(pallet_assets::Event::Burned { asset_id, owner, balance }) => { - asset_id: *asset_id == expected_foreign_asset_id, - owner: *owner == t.sender.account_id, - balance: *balance == expected_foreign_asset_amount, - }, - ] - ); -} - -fn ah_to_penpal_foreign_assets_receiver_assertions(t: SystemParaToParaTest) { - type RuntimeEvent = ::RuntimeEvent; - let expected_asset_id = t.args.asset_id.unwrap(); - let (_, expected_asset_amount) = - non_fee_asset(&t.args.assets, t.args.fee_asset_item as usize).unwrap(); - let checking_account = ::PolkadotXcm::check_account(); - assert_expected_events!( - PenpalA, - vec![ - // checking account burns local asset as part of incoming teleport - RuntimeEvent::Assets(pallet_assets::Event::Burned { asset_id, owner, balance }) => { - asset_id: *asset_id == expected_asset_id, - owner: *owner == checking_account, - balance: *balance == expected_asset_amount, - }, - // local asset is teleported into account of receiver - RuntimeEvent::Assets(pallet_assets::Event::Issued { asset_id, owner, amount }) => { - asset_id: *asset_id == expected_asset_id, - owner: *owner == t.receiver.account_id, - amount: *amount == expected_asset_amount, - }, - // native asset for fee is deposited to receiver - RuntimeEvent::Balances(pallet_balances::Event::Deposit { who, .. }) => { - who: *who == t.receiver.account_id, - }, - RuntimeEvent::MessageQueue( - pallet_message_queue::Event::Processed { success: true, .. } - ) => {}, - ] - ); -} - fn relay_limited_teleport_assets(t: RelayToSystemParaTest) -> DispatchResult { ::XcmPallet::limited_teleport_assets( t.signed_origin, @@ -271,28 +152,6 @@ fn system_para_teleport_assets(t: SystemParaToRelayTest) -> DispatchResult { ) } -fn para_to_system_para_transfer_assets(t: ParaToSystemParaTest) -> DispatchResult { - ::PolkadotXcm::transfer_assets( - t.signed_origin, - bx!(t.args.dest.into()), - bx!(t.args.beneficiary.into()), - bx!(t.args.assets.into()), - t.args.fee_asset_item, - t.args.weight_limit, - ) -} - -fn system_para_to_para_transfer_assets(t: SystemParaToParaTest) -> DispatchResult { - ::PolkadotXcm::transfer_assets( - t.signed_origin, - bx!(t.args.dest.into()), - bx!(t.args.beneficiary.into()), - bx!(t.args.assets.into()), - t.args.fee_asset_item, - t.args.weight_limit, - ) -} - /// Limited Teleport of native asset from Relay Chain to the System Parachain should work #[test] fn limited_teleport_native_assets_from_relay_to_system_para_works() { @@ -551,199 +410,3 @@ fn teleport_to_other_system_parachains_works() { (native_asset, amount) ); } - -/// Bidirectional teleports of local Penpal assets to Asset Hub as foreign assets should work -/// (using native reserve-based transfer for fees) -#[test] -fn bidirectional_teleport_foreign_assets_between_para_and_asset_hub() { - let ah_as_seen_by_penpal = PenpalA::sibling_location_of(AssetHubRococo::para_id()); - let asset_location_on_penpal = PenpalLocalTeleportableToAssetHub::get(); - let asset_id_on_penpal = match asset_location_on_penpal.last() { - Some(GeneralIndex(id)) => *id as u32, - _ => unreachable!(), - }; - let asset_owner_on_penpal = PenpalASender::get(); - let foreign_asset_at_asset_hub_rococo = - MultiLocation { parents: 1, interior: X1(Parachain(PenpalA::para_id().into())) } - .appended_with(asset_location_on_penpal) - .unwrap(); - super::penpal_create_foreign_asset_on_asset_hub( - asset_id_on_penpal, - foreign_asset_at_asset_hub_rococo, - ah_as_seen_by_penpal, - false, - asset_owner_on_penpal, - ASSET_MIN_BALANCE * 1_000_000, - ); - let penpal_to_ah_beneficiary_id = AssetHubRococoReceiver::get(); - - let fee_amount_to_send = ASSET_HUB_ROCOCO_ED * 10_000; - let asset_amount_to_send = ASSET_MIN_BALANCE * 1000; - - let penpal_assets: MultiAssets = vec![ - (Parent, fee_amount_to_send).into(), - (asset_location_on_penpal, asset_amount_to_send).into(), - ] - .into(); - let fee_asset_index = penpal_assets - .inner() - .iter() - .position(|r| r == &(Parent, fee_amount_to_send).into()) - .unwrap() as u32; - - // Penpal to AH test args - let penpal_to_ah_test_args = TestContext { - sender: PenpalASender::get(), - receiver: AssetHubRococoReceiver::get(), - args: para_test_args( - ah_as_seen_by_penpal, - penpal_to_ah_beneficiary_id, - asset_amount_to_send, - penpal_assets, - Some(asset_id_on_penpal), - fee_asset_index, - ), - }; - let mut penpal_to_ah = ParaToSystemParaTest::new(penpal_to_ah_test_args); - - let penpal_sender_balance_before = penpal_to_ah.sender.balance; - let ah_receiver_balance_before = penpal_to_ah.receiver.balance; - - let penpal_sender_assets_before = PenpalA::execute_with(|| { - type Assets = ::Assets; - >::balance(asset_id_on_penpal, &PenpalASender::get()) - }); - let ah_receiver_assets_before = AssetHubRococo::execute_with(|| { - type Assets = ::ForeignAssets; - >::balance( - foreign_asset_at_asset_hub_rococo, - &AssetHubRococoReceiver::get(), - ) - }); - - penpal_to_ah.set_assertion::(penpal_to_ah_foreign_assets_sender_assertions); - penpal_to_ah.set_assertion::(penpal_to_ah_foreign_assets_receiver_assertions); - penpal_to_ah.set_dispatchable::(para_to_system_para_transfer_assets); - penpal_to_ah.assert(); - - let penpal_sender_balance_after = penpal_to_ah.sender.balance; - let ah_receiver_balance_after = penpal_to_ah.receiver.balance; - - let penpal_sender_assets_after = PenpalA::execute_with(|| { - type Assets = ::Assets; - >::balance(asset_id_on_penpal, &PenpalASender::get()) - }); - let ah_receiver_assets_after = AssetHubRococo::execute_with(|| { - type Assets = ::ForeignAssets; - >::balance( - foreign_asset_at_asset_hub_rococo, - &AssetHubRococoReceiver::get(), - ) - }); - - // Sender's balance is reduced - assert!(penpal_sender_balance_after < penpal_sender_balance_before); - // Receiver's balance is increased - assert!(ah_receiver_balance_after > ah_receiver_balance_before); - // Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`; - // `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown but - // should be non-zero - assert!(ah_receiver_balance_after < ah_receiver_balance_before + fee_amount_to_send); - - // Sender's balance is reduced by exact amount - assert_eq!(penpal_sender_assets_before - asset_amount_to_send, penpal_sender_assets_after); - // Receiver's balance is increased by exact amount - assert_eq!(ah_receiver_assets_after, ah_receiver_assets_before + asset_amount_to_send); - - /////////////////////////////////////////////////////////////////////// - // Now test transferring foreign assets back from AssetHub to Penpal // - /////////////////////////////////////////////////////////////////////// - - // Move funds on AH from AHReceiver to AHSender - AssetHubRococo::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - assert_ok!(ForeignAssets::transfer( - ::RuntimeOrigin::signed(AssetHubRococoReceiver::get()), - foreign_asset_at_asset_hub_rococo, - AssetHubRococoSender::get().into(), - asset_amount_to_send, - )); - }); - - let ah_to_penpal_beneficiary_id = PenpalAReceiver::get(); - let penpal_as_seen_by_ah = AssetHubRococo::sibling_location_of(PenpalA::para_id()); - let ah_assets: MultiAssets = vec![ - (Parent, fee_amount_to_send).into(), - (foreign_asset_at_asset_hub_rococo, asset_amount_to_send).into(), - ] - .into(); - let fee_asset_index = ah_assets - .inner() - .iter() - .position(|r| r == &(Parent, fee_amount_to_send).into()) - .unwrap() as u32; - - // AH to Penpal test args - let ah_to_penpal_test_args = TestContext { - sender: AssetHubRococoSender::get(), - receiver: PenpalAReceiver::get(), - args: para_test_args( - penpal_as_seen_by_ah, - ah_to_penpal_beneficiary_id, - asset_amount_to_send, - ah_assets, - Some(asset_id_on_penpal), - fee_asset_index, - ), - }; - let mut ah_to_penpal = SystemParaToParaTest::new(ah_to_penpal_test_args); - - let ah_sender_balance_before = ah_to_penpal.sender.balance; - let penpal_receiver_balance_before = ah_to_penpal.receiver.balance; - - let ah_sender_assets_before = AssetHubRococo::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance( - foreign_asset_at_asset_hub_rococo, - &AssetHubRococoSender::get(), - ) - }); - let penpal_receiver_assets_before = PenpalA::execute_with(|| { - type Assets = ::Assets; - >::balance(asset_id_on_penpal, &PenpalAReceiver::get()) - }); - - ah_to_penpal.set_assertion::(ah_to_penpal_foreign_assets_sender_assertions); - ah_to_penpal.set_assertion::(ah_to_penpal_foreign_assets_receiver_assertions); - ah_to_penpal.set_dispatchable::(system_para_to_para_transfer_assets); - ah_to_penpal.assert(); - - let ah_sender_balance_after = ah_to_penpal.sender.balance; - let penpal_receiver_balance_after = ah_to_penpal.receiver.balance; - - let ah_sender_assets_after = AssetHubRococo::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance( - foreign_asset_at_asset_hub_rococo, - &AssetHubRococoSender::get(), - ) - }); - let penpal_receiver_assets_after = PenpalA::execute_with(|| { - type Assets = ::Assets; - >::balance(asset_id_on_penpal, &PenpalAReceiver::get()) - }); - - // Sender's balance is reduced - assert!(ah_sender_balance_after < ah_sender_balance_before); - // Receiver's balance is increased - assert!(penpal_receiver_balance_after > penpal_receiver_balance_before); - // Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`; - // `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown but - // should be non-zero - assert!(penpal_receiver_balance_after < penpal_receiver_balance_before + fee_amount_to_send); - - // Sender's balance is reduced by exact amount - assert_eq!(ah_sender_assets_before - asset_amount_to_send, ah_sender_assets_after); - // Receiver's balance is increased by exact amount - assert_eq!(penpal_receiver_assets_after, penpal_receiver_assets_before + asset_amount_to_send); -} 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 3b2d3367d40..7080abc0a44 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 @@ -7,30 +7,27 @@ license = "Apache-2.0" description = "Asset Hub Westend runtime integration tests with xcm-emulator" publish = false -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.4.0", default-features = false } assert_matches = "1.5.0" # Substrate -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 } -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-asset-rate = { path = "../../../../../../../substrate/frame/asset-rate", 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} +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-asset-rate = { path = "../../../../../../../substrate/frame/asset-rate", default-features = false} pallet-message-queue = { path = "../../../../../../../substrate/frame/message-queue", default-features = false } # Polkadot polkadot-runtime-common = { path = "../../../../../../../polkadot/runtime/common" } -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 = { 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} westend-runtime = { path = "../../../../../../../polkadot/runtime/westend" } westend-runtime-constants = { path = "../../../../../../../polkadot/runtime/westend/constants", default-features = false } @@ -39,7 +36,6 @@ parachains-common = { path = "../../../../../../parachains/common" } asset-hub-westend-runtime = { path = "../../../../../runtimes/assets/asset-hub-westend" } asset-test-utils = { path = "../../../../../runtimes/assets/test-utils" } cumulus-pallet-dmp-queue = { default-features = false, path = "../../../../../../pallets/dmp-queue" } -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" } +emulated-integration-tests-common = { path = "../../../common", default-features = false} +westend-system-emulated-network ={ path = "../../../networks/westend-system" } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs index e9c7a59faaf..83a867e6ae3 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs @@ -47,17 +47,11 @@ pub use westend_system_emulated_network::{ asset_hub_westend_emulated_chain::{ genesis::ED as ASSET_HUB_WESTEND_ED, AssetHubWestendParaPallet as AssetHubWestendPallet, }, - collectives_westend_emulated_chain::{ - genesis::ED as COLLECTIVES_WESTEND_ED, - CollectivesWestendParaPallet as CollectivesWestendPallet, - }, - penpal_emulated_chain::PenpalBParaPallet as PenpalBPallet, + penpal_emulated_chain::PenpalAParaPallet as PenpalAPallet, westend_emulated_chain::{genesis::ED as WESTEND_ED, WestendRelayPallet as WestendPallet}, AssetHubWestendPara as AssetHubWestend, AssetHubWestendParaReceiver as AssetHubWestendReceiver, - AssetHubWestendParaSender as AssetHubWestendSender, BridgeHubWestendPara as BridgeHubWestend, - BridgeHubWestendParaReceiver as BridgeHubWestendReceiver, - CollectivesWestendPara as CollectivesWestend, PenpalBPara as PenpalB, - PenpalBParaReceiver as PenpalBReceiver, PenpalBParaSender as PenpalBSender, + AssetHubWestendParaSender as AssetHubWestendSender, PenpalAPara as PenpalA, + PenpalAParaReceiver as PenpalAReceiver, PenpalAParaSender as PenpalASender, WestendRelay as Westend, WestendRelayReceiver as WestendReceiver, WestendRelaySender as WestendSender, }; @@ -68,20 +62,18 @@ pub const ASSET_MIN_BALANCE: u128 = 1000; pub const ASSETS_PALLET_ID: u8 = 50; pub type RelayToSystemParaTest = Test; -pub type RelayToParaTest = Test; pub type SystemParaToRelayTest = Test; -pub type SystemParaToParaTest = Test; -pub type ParaToSystemParaTest = Test; +pub type SystemParaToParaTest = Test; /// Returns a `TestArgs` instance to be used for the Relay Chain across integration tests -pub fn relay_test_args( - dest: MultiLocation, - beneficiary_id: AccountId32, - amount: Balance, -) -> TestArgs { +pub fn relay_test_args(amount: Balance) -> TestArgs { TestArgs { - dest, - beneficiary: AccountId32Junction { network: None, id: beneficiary_id.into() }.into(), + dest: Westend::child_location_of(AssetHubWestend::para_id()), + beneficiary: AccountId32Junction { + network: None, + id: AssetHubWestendReceiver::get().into(), + } + .into(), amount, assets: (Here, amount).into(), asset_id: None, @@ -90,14 +82,13 @@ pub fn relay_test_args( } } -/// Returns a `TestArgs` instance to be used by parachains across integration tests -pub fn para_test_args( +/// Returns a `TestArgs` instance to be used for the System Parachain across integration tests +pub fn system_para_test_args( dest: MultiLocation, beneficiary_id: AccountId32, amount: Balance, assets: MultiAssets, asset_id: Option, - fee_asset_item: u32, ) -> TestArgs { TestArgs { dest, @@ -105,7 +96,7 @@ pub fn para_test_args( amount, assets, asset_id, - fee_asset_item, + fee_asset_item: 0, weight_limit: WeightLimit::Unlimited, } } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/fellowship_treasury.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/fellowship_treasury.rs deleted file mode 100644 index d7de0a451f2..00000000000 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/fellowship_treasury.rs +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::*; -use emulated_integration_tests_common::accounts::{ALICE, BOB}; -use frame_support::traits::fungibles::{Create, Inspect, Mutate}; -use polkadot_runtime_common::impls::VersionedLocatableAsset; -use xcm_executor::traits::ConvertLocation; - -#[test] -fn create_and_claim_treasury_spend() { - const ASSET_ID: u32 = 1984; - const SPEND_AMOUNT: u128 = 1_000_000; - // treasury location from a sibling parachain. - let treasury_location: MultiLocation = MultiLocation::new( - 1, - X2(Parachain(CollectivesWestend::para_id().into()), PalletInstance(65)), - ); - // treasury account on a sibling parachain. - let treasury_account = - asset_hub_westend_runtime::xcm_config::LocationToAccountId::convert_location( - &treasury_location, - ) - .unwrap(); - let asset_hub_location = MultiLocation::new(1, Parachain(AssetHubWestend::para_id().into())); - let root = ::RuntimeOrigin::root(); - // asset kind to be spent from the treasury. - let asset_kind = VersionedLocatableAsset::V3 { - location: asset_hub_location, - asset_id: AssetId::Concrete((PalletInstance(50), GeneralIndex(ASSET_ID.into())).into()), - }; - // treasury spend beneficiary. - let alice: AccountId = Westend::account_id_of(ALICE); - let bob: AccountId = CollectivesWestend::account_id_of(BOB); - let bob_signed = ::RuntimeOrigin::signed(bob.clone()); - - AssetHubWestend::execute_with(|| { - type Assets = ::Assets; - - // create an asset class and mint some assets to the treasury account. - assert_ok!(>::create( - ASSET_ID, - treasury_account.clone(), - true, - SPEND_AMOUNT / 2 - )); - assert_ok!(>::mint_into(ASSET_ID, &treasury_account, SPEND_AMOUNT * 4)); - // beneficiary has zero balance. - assert_eq!(>::balance(ASSET_ID, &alice,), 0u128,); - }); - - CollectivesWestend::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - type FellowshipTreasury = - ::FellowshipTreasury; - type AssetRate = ::AssetRate; - - // create a conversion rate from `asset_kind` to the native currency. - assert_ok!(AssetRate::create(root.clone(), Box::new(asset_kind.clone()), 2.into())); - - // create and approve a treasury spend. - assert_ok!(FellowshipTreasury::spend( - root, - Box::new(asset_kind), - SPEND_AMOUNT, - Box::new(MultiLocation::new(0, Into::<[u8; 32]>::into(alice.clone())).into()), - None, - )); - // claim the spend. - assert_ok!(FellowshipTreasury::payout(bob_signed.clone(), 0)); - - assert_expected_events!( - CollectivesWestend, - vec![ - RuntimeEvent::FellowshipTreasury(pallet_treasury::Event::Paid { .. }) => {}, - ] - ); - }); - - AssetHubWestend::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - type Assets = ::Assets; - - // assert events triggered by xcm pay program - // 1. treasury asset transferred to spend beneficiary - // 2. response to the Fellowship treasury pallet instance sent back - // 3. XCM program completed - assert_expected_events!( - AssetHubWestend, - vec![ - RuntimeEvent::Assets(pallet_assets::Event::Transferred { asset_id: id, from, to, amount }) => { - id: id == &ASSET_ID, - from: from == &treasury_account, - to: to == &alice, - amount: amount == &SPEND_AMOUNT, - }, - RuntimeEvent::XcmpQueue(cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. }) => {}, - RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { success: true ,.. }) => {}, - ] - ); - // beneficiary received the assets from the treasury. - assert_eq!(>::balance(ASSET_ID, &alice,), SPEND_AMOUNT,); - }); - - CollectivesWestend::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - type FellowshipTreasury = - ::FellowshipTreasury; - - // check the payment status to ensure the response from the AssetHub was received. - assert_ok!(FellowshipTreasury::check_status(bob_signed, 0)); - assert_expected_events!( - CollectivesWestend, - vec![ - RuntimeEvent::FellowshipTreasury(pallet_treasury::Event::SpendProcessed { .. }) => {}, - ] - ); - }); -} diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/mod.rs index ee720c24480..0c9de89c5f9 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/mod.rs @@ -13,18 +13,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -mod fellowship_treasury; mod reserve_transfer; mod send; mod set_xcm_versions; mod swap; mod teleport; mod treasury; - -use crate::*; -emulated_integration_tests_common::include_penpal_create_foreign_asset_on_asset_hub!( - PenpalB, - AssetHubWestend, - WESTEND_ED, - parachains_common::westend::fee::WeightToFee -); diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/reserve_transfer.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/reserve_transfer.rs index 7472445c4ba..5b2c648b7b0 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/reserve_transfer.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/reserve_transfer.rs @@ -14,31 +14,7 @@ // limitations under the License. use crate::*; -use asset_hub_westend_runtime::xcm_config::XcmConfig as AssetHubWestendXcmConfig; -use westend_runtime::xcm_config::XcmConfig as WestendXcmConfig; -use westend_system_emulated_network::penpal_emulated_chain::XcmConfig as PenpalWestendXcmConfig; - -fn relay_to_para_sender_assertions(t: RelayToParaTest) { - type RuntimeEvent = ::RuntimeEvent; - - Westend::assert_xcm_pallet_attempted_complete(Some(Weight::from_parts(864_610_000, 8_799))); - - assert_expected_events!( - Westend, - vec![ - // Amount to reserve transfer is transferred to Parachain's Sovereign account - RuntimeEvent::Balances( - pallet_balances::Event::Transfer { from, to, amount } - ) => { - from: *from == t.sender.account_id, - to: *to == Westend::sovereign_account_id_of( - t.args.dest - ), - amount: *amount == t.args.amount, - }, - ] - ); -} +use asset_hub_westend_runtime::xcm_config::XcmConfig; fn system_para_to_para_sender_assertions(t: SystemParaToParaTest) { type RuntimeEvent = ::RuntimeEvent; @@ -66,9 +42,9 @@ fn system_para_to_para_sender_assertions(t: SystemParaToParaTest) { } fn para_receiver_assertions(_: Test) { - type RuntimeEvent = ::RuntimeEvent; + type RuntimeEvent = ::RuntimeEvent; assert_expected_events!( - PenpalB, + PenpalA, vec![ RuntimeEvent::Balances(pallet_balances::Event::Deposit { .. }) => {}, RuntimeEvent::MessageQueue( @@ -78,51 +54,7 @@ fn para_receiver_assertions(_: Test) { ); } -fn para_to_system_para_sender_assertions(t: ParaToSystemParaTest) { - type RuntimeEvent = ::RuntimeEvent; - - PenpalB::assert_xcm_pallet_attempted_complete(Some(Weight::from_parts(864_610_000, 8_799))); - - assert_expected_events!( - PenpalB, - vec![ - // Amount to reserve transfer is transferred to Parachain's Sovereign account - RuntimeEvent::Balances( - pallet_balances::Event::Withdraw { who, amount } - ) => { - who: *who == t.sender.account_id, - amount: *amount == t.args.amount, - }, - ] - ); -} - -fn para_to_system_para_receiver_assertions(t: ParaToSystemParaTest) { - type RuntimeEvent = ::RuntimeEvent; - - let sov_penpal_on_ahw = AssetHubWestend::sovereign_account_id_of( - AssetHubWestend::sibling_location_of(PenpalB::para_id()), - ); - - assert_expected_events!( - AssetHubWestend, - vec![ - // Amount to reserve transfer is transferred to Parachain's Sovereign account - RuntimeEvent::Balances( - pallet_balances::Event::Withdraw { who, amount } - ) => { - who: *who == sov_penpal_on_ahw.clone().into(), - amount: *amount == t.args.amount, - }, - RuntimeEvent::Balances(pallet_balances::Event::Deposit { .. }) => {}, - RuntimeEvent::MessageQueue( - pallet_message_queue::Event::Processed { success: true, .. } - ) => {}, - ] - ); -} - -fn system_para_to_para_assets_sender_assertions(t: SystemParaToParaTest) { +fn system_para_to_para_assets_assertions(t: SystemParaToParaTest) { type RuntimeEvent = ::RuntimeEvent; AssetHubWestend::assert_xcm_pallet_attempted_complete(Some(Weight::from_parts( @@ -148,32 +80,7 @@ fn system_para_to_para_assets_sender_assertions(t: SystemParaToParaTest) { ); } -fn system_para_to_para_assets_receiver_assertions(_: Test) { - type RuntimeEvent = ::RuntimeEvent; - assert_expected_events!( - PenpalB, - vec![ - RuntimeEvent::Balances(pallet_balances::Event::Deposit { .. }) => {}, - RuntimeEvent::Assets(pallet_assets::Event::Issued { .. }) => {}, - RuntimeEvent::MessageQueue( - pallet_message_queue::Event::Processed { success: true, .. } - ) => {}, - ] - ); -} - -fn relay_to_para_reserve_transfer_assets(t: RelayToParaTest) -> DispatchResult { - ::XcmPallet::limited_reserve_transfer_assets( - t.signed_origin, - bx!(t.args.dest.into()), - bx!(t.args.beneficiary.into()), - bx!(t.args.assets.into()), - t.args.fee_asset_item, - t.args.weight_limit, - ) -} - -fn system_para_to_para_reserve_transfer_assets(t: SystemParaToParaTest) -> DispatchResult { +fn system_para_to_para_limited_reserve_transfer_assets(t: SystemParaToParaTest) -> DispatchResult { ::PolkadotXcm::limited_reserve_transfer_assets( t.signed_origin, bx!(t.args.dest.into()), @@ -184,17 +91,6 @@ fn system_para_to_para_reserve_transfer_assets(t: SystemParaToParaTest) -> Dispa ) } -fn para_to_system_para_reserve_transfer_assets(t: ParaToSystemParaTest) -> DispatchResult { - ::PolkadotXcm::limited_reserve_transfer_assets( - t.signed_origin, - bx!(t.args.dest.into()), - bx!(t.args.beneficiary.into()), - bx!(t.args.assets.into()), - t.args.fee_asset_item, - t.args.weight_limit, - ) -} - /// Reserve Transfers of native asset from Relay Chain to the System Parachain shouldn't work #[test] fn reserve_transfer_native_asset_from_relay_to_system_para_fails() { @@ -263,62 +159,19 @@ fn reserve_transfer_native_asset_from_system_para_to_relay_fails() { }); } -/// Reserve Transfers of native asset from Relay to Parachain should work -#[test] -fn reserve_transfer_native_asset_from_relay_to_para() { - // Init values for Relay - let destination = Westend::child_location_of(PenpalB::para_id()); - let beneficiary_id = PenpalBReceiver::get(); - let amount_to_send: Balance = WESTEND_ED * 1000; - - let test_args = TestContext { - sender: WestendSender::get(), - receiver: PenpalBReceiver::get(), - args: relay_test_args(destination, beneficiary_id, amount_to_send), - }; - - let mut test = RelayToParaTest::new(test_args); - - let sender_balance_before = test.sender.balance; - let receiver_balance_before = test.receiver.balance; - - test.set_assertion::(relay_to_para_sender_assertions); - test.set_assertion::(para_receiver_assertions); - test.set_dispatchable::(relay_to_para_reserve_transfer_assets); - test.assert(); - - let delivery_fees = Westend::execute_with(|| { - xcm_helpers::transfer_assets_delivery_fees::< - ::XcmSender, - >(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest) - }); - - let sender_balance_after = test.sender.balance; - let receiver_balance_after = test.receiver.balance; - - // Sender's balance is reduced - assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after); - // Receiver's balance is increased - assert!(receiver_balance_after > receiver_balance_before); - // Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`; - // `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown but - // should be non-zero - assert!(receiver_balance_after < receiver_balance_before + amount_to_send); -} - /// Reserve Transfers of native asset from System Parachain to Parachain should work #[test] fn reserve_transfer_native_asset_from_system_para_to_para() { // Init values for System Parachain - let destination = AssetHubWestend::sibling_location_of(PenpalB::para_id()); - let beneficiary_id = PenpalBReceiver::get(); + let destination = AssetHubWestend::sibling_location_of(PenpalA::para_id()); + let beneficiary_id = PenpalAReceiver::get(); let amount_to_send: Balance = ASSET_HUB_WESTEND_ED * 1000; let assets = (Parent, amount_to_send).into(); let test_args = TestContext { sender: AssetHubWestendSender::get(), - receiver: PenpalBReceiver::get(), - args: para_test_args(destination, beneficiary_id, amount_to_send, assets, None, 0), + receiver: PenpalAReceiver::get(), + args: system_para_test_args(destination, beneficiary_id, amount_to_send, assets, None), }; let mut test = SystemParaToParaTest::new(test_args); @@ -327,179 +180,61 @@ fn reserve_transfer_native_asset_from_system_para_to_para() { let receiver_balance_before = test.receiver.balance; test.set_assertion::(system_para_to_para_sender_assertions); - test.set_assertion::(para_receiver_assertions); - test.set_dispatchable::(system_para_to_para_reserve_transfer_assets); + test.set_assertion::(para_receiver_assertions); + test.set_dispatchable::(system_para_to_para_limited_reserve_transfer_assets); test.assert(); let sender_balance_after = test.sender.balance; let receiver_balance_after = test.receiver.balance; let delivery_fees = AssetHubWestend::execute_with(|| { - xcm_helpers::transfer_assets_delivery_fees::< - ::XcmSender, - >(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest) + xcm_helpers::transfer_assets_delivery_fees::<::XcmSender>( + test.args.assets.clone(), + 0, + test.args.weight_limit, + test.args.beneficiary, + test.args.dest, + ) }); // Sender's balance is reduced assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after); // Receiver's balance is increased assert!(receiver_balance_after > receiver_balance_before); - // Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`; - // `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown but - // should be non-zero - assert!(receiver_balance_after < receiver_balance_before + amount_to_send); } -/// Reserve Transfers of native asset from Parachain to System Parachain should work +/// Reserve Transfers of a local asset from System Parachain to Parachain should work #[test] -fn reserve_transfer_native_asset_from_para_to_system_para() { - // Init values for Penpal Parachain - let destination = PenpalB::sibling_location_of(AssetHubWestend::para_id()); - let beneficiary_id = AssetHubWestendReceiver::get(); - let amount_to_send: Balance = ASSET_HUB_WESTEND_ED * 1000; - let assets = (Parent, amount_to_send).into(); - - let test_args = TestContext { - sender: PenpalBSender::get(), - receiver: AssetHubWestendReceiver::get(), - args: para_test_args(destination, beneficiary_id, amount_to_send, assets, None, 0), - }; - - let mut test = ParaToSystemParaTest::new(test_args); - - let sender_balance_before = test.sender.balance; - let receiver_balance_before = test.receiver.balance; - - let penpal_location_as_seen_by_ahw = AssetHubWestend::sibling_location_of(PenpalB::para_id()); - let sov_penpal_on_ahw = - AssetHubWestend::sovereign_account_id_of(penpal_location_as_seen_by_ahw); - - // fund the Penpal's SA on AHW with the native tokens held in reserve - AssetHubWestend::fund_accounts(vec![(sov_penpal_on_ahw.into(), amount_to_send * 2)]); - - test.set_assertion::(para_to_system_para_sender_assertions); - test.set_assertion::(para_to_system_para_receiver_assertions); - test.set_dispatchable::(para_to_system_para_reserve_transfer_assets); - test.assert(); - - let sender_balance_after = test.sender.balance; - let receiver_balance_after = test.receiver.balance; - - let delivery_fees = PenpalB::execute_with(|| { - xcm_helpers::transfer_assets_delivery_fees::< - ::XcmSender, - >(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest) - }); - - // Sender's balance is reduced - assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after); - // Receiver's balance is increased - assert!(receiver_balance_after > receiver_balance_before); - // Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`; - // `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown but - // should be non-zero - assert!(receiver_balance_after < receiver_balance_before + amount_to_send); -} - -/// Reserve Transfers of a local asset and native asset from System Parachain to Parachain should -/// work -#[test] -fn reserve_transfer_assets_from_system_para_to_para() { - // Force create asset on AssetHubWestend and PenpalB from Relay Chain +fn reserve_transfer_asset_from_system_para_to_para() { + // Force create asset from Relay Chain and mint assets for System Parachain's sender account AssetHubWestend::force_create_and_mint_asset( ASSET_ID, ASSET_MIN_BALANCE, true, AssetHubWestendSender::get(), Some(Weight::from_parts(1_019_445_000, 200_000)), - ASSET_MIN_BALANCE * 1_000_000, - ); - PenpalB::force_create_and_mint_asset( - ASSET_ID, - ASSET_MIN_BALANCE, - false, - PenpalBSender::get(), - None, - 0, + ASSET_MIN_BALANCE * 1000000, ); // Init values for System Parachain - let destination = AssetHubWestend::sibling_location_of(PenpalB::para_id()); - let beneficiary_id = PenpalBReceiver::get(); - let fee_amount_to_send = ASSET_HUB_WESTEND_ED * 1000; - let asset_amount_to_send = ASSET_MIN_BALANCE * 1000; - let assets: MultiAssets = vec![ - (Parent, fee_amount_to_send).into(), - (X2(PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())), asset_amount_to_send) - .into(), - ] - .into(); - let fee_asset_index = assets - .inner() - .iter() - .position(|r| r == &(Parent, fee_amount_to_send).into()) - .unwrap() as u32; - - let para_test_args = TestContext { + let destination = AssetHubWestend::sibling_location_of(PenpalA::para_id()); + let beneficiary_id = PenpalAReceiver::get(); + let amount_to_send = ASSET_MIN_BALANCE * 1000; + let assets = + (X2(PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())), amount_to_send) + .into(); + + let system_para_test_args = TestContext { sender: AssetHubWestendSender::get(), - receiver: PenpalBReceiver::get(), - args: para_test_args( - destination, - beneficiary_id, - asset_amount_to_send, - assets, - None, - fee_asset_index, - ), + receiver: PenpalAReceiver::get(), + args: system_para_test_args(destination, beneficiary_id, amount_to_send, assets, None), }; - let mut test = SystemParaToParaTest::new(para_test_args); - - // Create SA-of-Penpal-on-AHW with ED. - let penpal_location = AssetHubWestend::sibling_location_of(PenpalB::para_id()); - let sov_penpal_on_ahw = AssetHubWestend::sovereign_account_id_of(penpal_location); - AssetHubWestend::fund_accounts(vec![(sov_penpal_on_ahw.into(), WESTEND_ED)]); - - let sender_balance_before = test.sender.balance; - let receiver_balance_before = test.receiver.balance; - - let sender_assets_before = AssetHubWestend::execute_with(|| { - type Assets = ::Assets; - >::balance(ASSET_ID, &AssetHubWestendSender::get()) - }); - let receiver_assets_before = PenpalB::execute_with(|| { - type Assets = ::Assets; - >::balance(ASSET_ID, &PenpalBReceiver::get()) - }); - - test.set_assertion::(system_para_to_para_assets_sender_assertions); - test.set_assertion::(system_para_to_para_assets_receiver_assertions); - test.set_dispatchable::(system_para_to_para_reserve_transfer_assets); - test.assert(); - - let sender_balance_after = test.sender.balance; - let receiver_balance_after = test.receiver.balance; - - // Sender's balance is reduced - assert!(sender_balance_after < sender_balance_before); - // Receiver's balance is increased - assert!(receiver_balance_after > receiver_balance_before); - // Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`; - // `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown but - // should be non-zero - assert!(receiver_balance_after < receiver_balance_before + fee_amount_to_send); - - let sender_assets_after = AssetHubWestend::execute_with(|| { - type Assets = ::Assets; - >::balance(ASSET_ID, &AssetHubWestendSender::get()) - }); - let receiver_assets_after = PenpalB::execute_with(|| { - type Assets = ::Assets; - >::balance(ASSET_ID, &PenpalBReceiver::get()) - }); + let mut system_para_test = SystemParaToParaTest::new(system_para_test_args); - // Sender's balance is reduced by exact amount - assert_eq!(sender_assets_before - asset_amount_to_send, sender_assets_after); - // Receiver's balance is increased by exact amount - assert_eq!(receiver_assets_after, receiver_assets_before + asset_amount_to_send); + system_para_test.set_assertion::(system_para_to_para_assets_assertions); + // TODO: Add assertions when Penpal is able to manage assets + system_para_test + .set_dispatchable::(system_para_to_para_limited_reserve_transfer_assets); + system_para_test.assert(); } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/send.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/send.rs index 4b98eeb0ed3..bda9a3e69c4 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/send.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/send.rs @@ -33,7 +33,7 @@ fn send_transact_as_superuser_from_relay_to_system_para_works() { #[test] fn send_xcm_from_para_to_system_para_paying_fee_with_assets_works() { let para_sovereign_account = AssetHubWestend::sovereign_account_id_of( - AssetHubWestend::sibling_location_of(PenpalB::para_id()), + AssetHubWestend::sibling_location_of(PenpalA::para_id()), ); // Force create and mint assets for Parachain's sovereign account @@ -60,8 +60,8 @@ fn send_xcm_from_para_to_system_para_paying_fee_with_assets_works() { let native_asset = (X2(PalletInstance(ASSETS_PALLET_ID), GeneralIndex(ASSET_ID.into())), fee_amount).into(); - let root_origin = ::RuntimeOrigin::root(); - let system_para_destination = PenpalB::sibling_location_of(AssetHubWestend::para_id()).into(); + let root_origin = ::RuntimeOrigin::root(); + let system_para_destination = PenpalA::sibling_location_of(AssetHubWestend::para_id()).into(); let xcm = xcm_transact_paid_execution( call, origin_kind, @@ -69,14 +69,14 @@ fn send_xcm_from_para_to_system_para_paying_fee_with_assets_works() { para_sovereign_account.clone(), ); - PenpalB::execute_with(|| { - assert_ok!(::PolkadotXcm::send( + PenpalA::execute_with(|| { + assert_ok!(::PolkadotXcm::send( root_origin, bx!(system_para_destination), bx!(xcm), )); - PenpalB::assert_xcm_pallet_sent(); + PenpalA::assert_xcm_pallet_sent(); }); AssetHubWestend::execute_with(|| { diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/swap.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/swap.rs index 1fa77bd4565..a8e19f9ef4b 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/swap.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/swap.rs @@ -14,7 +14,6 @@ // limitations under the License. use crate::*; -use westend_system_emulated_network::penpal_emulated_chain::LocalTeleportableToAssetHub as PenpalLocalTeleportableToAssetHub; #[test] fn swap_locally_on_chain_using_local_assets() { @@ -108,37 +107,113 @@ fn swap_locally_on_chain_using_local_assets() { #[test] fn swap_locally_on_chain_using_foreign_assets() { + use frame_support::weights::WeightToFee; + let asset_native = Box::new(asset_hub_westend_runtime::xcm_config::WestendLocation::get()); - let ah_as_seen_by_penpal = PenpalB::sibling_location_of(AssetHubWestend::para_id()); - let asset_location_on_penpal = PenpalLocalTeleportableToAssetHub::get(); - let asset_id_on_penpal = match asset_location_on_penpal.last() { - Some(GeneralIndex(id)) => *id as u32, - _ => unreachable!(), - }; - let asset_owner_on_penpal = PenpalBSender::get(); - let foreign_asset_at_asset_hub_westend = - MultiLocation { parents: 1, interior: X1(Parachain(PenpalB::para_id().into())) } - .appended_with(asset_location_on_penpal) - .unwrap(); - - // 1. Create asset on penpal and, 2. Create foreign asset on asset_hub_westend - super::penpal_create_foreign_asset_on_asset_hub( - asset_id_on_penpal, - foreign_asset_at_asset_hub_westend, - ah_as_seen_by_penpal, - true, - asset_owner_on_penpal, - ASSET_MIN_BALANCE * 1_000_000, - ); - let penpal_as_seen_by_ah = AssetHubWestend::sibling_location_of(PenpalB::para_id()); - let sov_penpal_on_ahw = AssetHubWestend::sovereign_account_id_of(penpal_as_seen_by_ah); + let foreign_asset1_at_asset_hub_westend = Box::new(MultiLocation { + parents: 1, + interior: X3( + Parachain(PenpalA::para_id().into()), + PalletInstance(ASSETS_PALLET_ID), + GeneralIndex(ASSET_ID.into()), + ), + }); + + let assets_para_destination: VersionedMultiLocation = + MultiLocation { parents: 1, interior: X1(Parachain(AssetHubWestend::para_id().into())) } + .into(); + + let penpal_location = + MultiLocation { parents: 1, interior: X1(Parachain(PenpalA::para_id().into())) }; + + // 1. Create asset on penpal: + PenpalA::execute_with(|| { + assert_ok!(::Assets::create( + ::RuntimeOrigin::signed(PenpalASender::get()), + ASSET_ID.into(), + PenpalASender::get().into(), + 1000, + )); + + assert!(::Assets::asset_exists(ASSET_ID)); + }); + + // 2. Create foreign asset on asset_hub_westend: + + let require_weight_at_most = Weight::from_parts(1_100_000_000_000, 30_000); + let origin_kind = OriginKind::Xcm; + let sov_penpal_on_asset_hub_westend = AssetHubWestend::sovereign_account_id_of(penpal_location); + AssetHubWestend::fund_accounts(vec![ - (AssetHubWestendSender::get().into(), 5_000_000 * WESTEND_ED), /* An account to swap dot - * for something else. */ + (AssetHubWestendSender::get().into(), 5_000_000 * WESTEND_ED), + (sov_penpal_on_asset_hub_westend.clone().into(), 1000_000_000_000_000_000 * WESTEND_ED), ]); + let sov_penpal_on_asset_hub_westend_as_location: MultiLocation = MultiLocation { + parents: 0, + interior: X1(AccountId32Junction { + network: None, + id: sov_penpal_on_asset_hub_westend.clone().into(), + }), + }; + + let call_foreign_assets_create = + ::RuntimeCall::ForeignAssets(pallet_assets::Call::< + ::Runtime, + Instance2, + >::create { + id: *foreign_asset1_at_asset_hub_westend, + min_balance: 1000, + admin: sov_penpal_on_asset_hub_westend.clone().into(), + }) + .encode() + .into(); + + let buy_execution_fee_amount = parachains_common::westend::fee::WeightToFee::weight_to_fee( + &Weight::from_parts(10_100_000_000_000, 300_000), + ); + let buy_execution_fee = MultiAsset { + id: Concrete(MultiLocation { parents: 1, interior: Here }), + fun: Fungible(buy_execution_fee_amount), + }; + + let xcm = VersionedXcm::from(Xcm(vec![ + WithdrawAsset { 0: vec![buy_execution_fee.clone()].into() }, + BuyExecution { fees: buy_execution_fee.clone(), weight_limit: Unlimited }, + Transact { require_weight_at_most, origin_kind, call: call_foreign_assets_create }, + RefundSurplus, + DepositAsset { + assets: All.into(), + beneficiary: sov_penpal_on_asset_hub_westend_as_location, + }, + ])); + + // Send XCM message from penpal => asset_hub_westend + let sudo_penpal_origin = ::RuntimeOrigin::root(); + PenpalA::execute_with(|| { + assert_ok!(::PolkadotXcm::send( + sudo_penpal_origin.clone(), + bx!(assets_para_destination.clone()), + bx!(xcm), + )); + + type RuntimeEvent = ::RuntimeEvent; + + assert_expected_events!( + PenpalA, + vec![ + RuntimeEvent::PolkadotXcm(pallet_xcm::Event::Sent { .. }) => {}, + ] + ); + }); + + // Receive XCM message in Assets Parachain in the next block. AssetHubWestend::execute_with(|| { + assert!(::ForeignAssets::asset_exists( + *foreign_asset1_at_asset_hub_westend + )); + // 3: Mint foreign asset on asset_hub_westend: // // (While it might be nice to use batch, @@ -147,9 +222,11 @@ fn swap_locally_on_chain_using_foreign_assets() { type RuntimeEvent = ::RuntimeEvent; // 3. Mint foreign asset (in reality this should be a teleport or some such) assert_ok!(::ForeignAssets::mint( - ::RuntimeOrigin::signed(sov_penpal_on_ahw.clone().into()), - foreign_asset_at_asset_hub_westend, - sov_penpal_on_ahw.clone().into(), + ::RuntimeOrigin::signed( + sov_penpal_on_asset_hub_westend.clone().into() + ), + *foreign_asset1_at_asset_hub_westend, + sov_penpal_on_asset_hub_westend.clone().into(), 3_000_000_000_000, )); @@ -160,12 +237,11 @@ fn swap_locally_on_chain_using_foreign_assets() { ] ); - let foreign_asset_at_asset_hub_westend = Box::new(foreign_asset_at_asset_hub_westend); // 4. Create pool: assert_ok!(::AssetConversion::create_pool( ::RuntimeOrigin::signed(AssetHubWestendSender::get()), asset_native.clone(), - foreign_asset_at_asset_hub_westend.clone(), + foreign_asset1_at_asset_hub_westend.clone(), )); assert_expected_events!( @@ -177,14 +253,16 @@ fn swap_locally_on_chain_using_foreign_assets() { // 5. Add liquidity: assert_ok!(::AssetConversion::add_liquidity( - ::RuntimeOrigin::signed(sov_penpal_on_ahw.clone()), + ::RuntimeOrigin::signed( + sov_penpal_on_asset_hub_westend.clone() + ), asset_native.clone(), - foreign_asset_at_asset_hub_westend.clone(), + foreign_asset1_at_asset_hub_westend.clone(), 1_000_000_000_000, 2_000_000_000_000, 0, 0, - sov_penpal_on_ahw.clone().into() + sov_penpal_on_asset_hub_westend.clone().into() )); assert_expected_events!( @@ -199,7 +277,7 @@ fn swap_locally_on_chain_using_foreign_assets() { // 6. Swap! let path = BoundedVec::<_, _>::truncate_from(vec![ asset_native.clone(), - foreign_asset_at_asset_hub_westend.clone(), + foreign_asset1_at_asset_hub_westend.clone(), ]); assert_ok!(::AssetConversion::swap_exact_tokens_for_tokens( @@ -223,13 +301,15 @@ fn swap_locally_on_chain_using_foreign_assets() { // 7. Remove liquidity assert_ok!(::AssetConversion::remove_liquidity( - ::RuntimeOrigin::signed(sov_penpal_on_ahw.clone()), + ::RuntimeOrigin::signed( + sov_penpal_on_asset_hub_westend.clone() + ), asset_native, - foreign_asset_at_asset_hub_westend, + foreign_asset1_at_asset_hub_westend, 1414213562273 - 2_000_000_000, // all but the 2 EDs can't be retrieved. 0, 0, - sov_penpal_on_ahw.clone().into(), + sov_penpal_on_asset_hub_westend.clone().into(), )); }); } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/teleport.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/teleport.rs index 2dd68ae3a83..d618cd2fe04 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/teleport.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/teleport.rs @@ -15,9 +15,7 @@ use crate::*; use asset_hub_westend_runtime::xcm_config::XcmConfig as AssetHubWestendXcmConfig; -use emulated_integration_tests_common::xcm_helpers::non_fee_asset; use westend_runtime::xcm_config::XcmConfig as WestendXcmConfig; -use westend_system_emulated_network::penpal_emulated_chain::LocalTeleportableToAssetHub as PenpalLocalTeleportableToAssetHub; fn relay_origin_assertions(t: RelayToSystemParaTest) { type RuntimeEvent = ::RuntimeEvent; @@ -112,123 +110,6 @@ fn para_dest_assertions(t: RelayToSystemParaTest) { ); } -fn penpal_to_ah_foreign_assets_sender_assertions(t: ParaToSystemParaTest) { - type RuntimeEvent = ::RuntimeEvent; - PenpalB::assert_xcm_pallet_attempted_complete(None); - let expected_asset_id = t.args.asset_id.unwrap(); - let (_, expected_asset_amount) = - non_fee_asset(&t.args.assets, t.args.fee_asset_item as usize).unwrap(); - assert_expected_events!( - PenpalB, - vec![ - RuntimeEvent::Balances( - pallet_balances::Event::Withdraw { who, amount } - ) => { - who: *who == t.sender.account_id, - amount: *amount == t.args.amount, - }, - RuntimeEvent::Assets(pallet_assets::Event::Burned { asset_id, owner, balance }) => { - asset_id: *asset_id == expected_asset_id, - owner: *owner == t.sender.account_id, - balance: *balance == expected_asset_amount, - }, - ] - ); -} - -fn penpal_to_ah_foreign_assets_receiver_assertions(t: ParaToSystemParaTest) { - type RuntimeEvent = ::RuntimeEvent; - let sov_penpal_on_ahr = AssetHubWestend::sovereign_account_id_of( - AssetHubWestend::sibling_location_of(PenpalB::para_id()), - ); - let (expected_foreign_asset_id, expected_foreign_asset_amount) = - non_fee_asset(&t.args.assets, t.args.fee_asset_item as usize).unwrap(); - assert_expected_events!( - AssetHubWestend, - vec![ - // native asset reserve transfer for paying fees, withdrawn from Penpal's sov account - RuntimeEvent::Balances( - pallet_balances::Event::Withdraw { who, amount } - ) => { - who: *who == sov_penpal_on_ahr.clone().into(), - amount: *amount == t.args.amount, - }, - RuntimeEvent::Balances(pallet_balances::Event::Deposit { who, .. }) => { - who: *who == t.receiver.account_id, - }, - RuntimeEvent::ForeignAssets(pallet_assets::Event::Issued { asset_id, owner, amount }) => { - asset_id: *asset_id == expected_foreign_asset_id, - owner: *owner == t.receiver.account_id, - amount: *amount == expected_foreign_asset_amount, - }, - RuntimeEvent::Balances(pallet_balances::Event::Deposit { .. }) => {}, - RuntimeEvent::MessageQueue( - pallet_message_queue::Event::Processed { success: true, .. } - ) => {}, - ] - ); -} - -fn ah_to_penpal_foreign_assets_sender_assertions(t: SystemParaToParaTest) { - type RuntimeEvent = ::RuntimeEvent; - AssetHubWestend::assert_xcm_pallet_attempted_complete(None); - let (expected_foreign_asset_id, expected_foreign_asset_amount) = - non_fee_asset(&t.args.assets, t.args.fee_asset_item as usize).unwrap(); - assert_expected_events!( - AssetHubWestend, - vec![ - // native asset used for fees is transferred to Parachain's Sovereign account as reserve - RuntimeEvent::Balances( - pallet_balances::Event::Transfer { from, to, amount } - ) => { - from: *from == t.sender.account_id, - to: *to == AssetHubWestend::sovereign_account_id_of( - t.args.dest - ), - amount: *amount == t.args.amount, - }, - // foreign asset is burned locally as part of teleportation - RuntimeEvent::ForeignAssets(pallet_assets::Event::Burned { asset_id, owner, balance }) => { - asset_id: *asset_id == expected_foreign_asset_id, - owner: *owner == t.sender.account_id, - balance: *balance == expected_foreign_asset_amount, - }, - ] - ); -} - -fn ah_to_penpal_foreign_assets_receiver_assertions(t: SystemParaToParaTest) { - type RuntimeEvent = ::RuntimeEvent; - let expected_asset_id = t.args.asset_id.unwrap(); - let (_, expected_asset_amount) = - non_fee_asset(&t.args.assets, t.args.fee_asset_item as usize).unwrap(); - let checking_account = ::PolkadotXcm::check_account(); - assert_expected_events!( - PenpalB, - vec![ - // checking account burns local asset as part of incoming teleport - RuntimeEvent::Assets(pallet_assets::Event::Burned { asset_id, owner, balance }) => { - asset_id: *asset_id == expected_asset_id, - owner: *owner == checking_account, - balance: *balance == expected_asset_amount, - }, - // local asset is teleported into account of receiver - RuntimeEvent::Assets(pallet_assets::Event::Issued { asset_id, owner, amount }) => { - asset_id: *asset_id == expected_asset_id, - owner: *owner == t.receiver.account_id, - amount: *amount == expected_asset_amount, - }, - // native asset for fee is deposited to receiver - RuntimeEvent::Balances(pallet_balances::Event::Deposit { who, .. }) => { - who: *who == t.receiver.account_id, - }, - RuntimeEvent::MessageQueue( - pallet_message_queue::Event::Processed { success: true, .. } - ) => {}, - ] - ); -} - fn relay_limited_teleport_assets(t: RelayToSystemParaTest) -> DispatchResult { ::XcmPallet::limited_teleport_assets( t.signed_origin, @@ -271,39 +152,15 @@ fn system_para_teleport_assets(t: SystemParaToRelayTest) -> DispatchResult { ) } -fn system_para_to_para_transfer_assets(t: SystemParaToParaTest) -> DispatchResult { - ::PolkadotXcm::transfer_assets( - t.signed_origin, - bx!(t.args.dest.into()), - bx!(t.args.beneficiary.into()), - bx!(t.args.assets.into()), - t.args.fee_asset_item, - t.args.weight_limit, - ) -} - -fn para_to_system_para_transfer_assets(t: ParaToSystemParaTest) -> DispatchResult { - ::PolkadotXcm::transfer_assets( - t.signed_origin, - bx!(t.args.dest.into()), - bx!(t.args.beneficiary.into()), - bx!(t.args.assets.into()), - t.args.fee_asset_item, - t.args.weight_limit, - ) -} - /// Limited Teleport of native asset from Relay Chain to the System Parachain should work #[test] fn limited_teleport_native_assets_from_relay_to_system_para_works() { // Init values for Relay Chain let amount_to_send: Balance = WESTEND_ED * 1000; - let dest = Westend::child_location_of(AssetHubWestend::para_id()); - let beneficiary = AssetHubWestendReceiver::get(); let test_args = TestContext { sender: WestendSender::get(), - receiver: beneficiary.clone(), - args: relay_test_args(dest, beneficiary, amount_to_send), + receiver: AssetHubWestendReceiver::get(), + args: relay_test_args(amount_to_send), }; let mut test = RelayToSystemParaTest::new(test_args); @@ -347,7 +204,7 @@ fn limited_teleport_native_assets_back_from_system_para_to_relay_works() { let test_args = TestContext { sender: AssetHubWestendSender::get(), receiver: WestendReceiver::get(), - args: para_test_args(destination, beneficiary_id, amount_to_send, assets, None, 0), + args: system_para_test_args(destination, beneficiary_id, amount_to_send, assets, None), }; let mut test = SystemParaToRelayTest::new(test_args); @@ -388,7 +245,7 @@ fn limited_teleport_native_assets_from_system_para_to_relay_fails() { let test_args = TestContext { sender: AssetHubWestendSender::get(), receiver: WestendReceiver::get(), - args: para_test_args(destination, beneficiary_id, amount_to_send, assets, None, 0), + args: system_para_test_args(destination, beneficiary_id, amount_to_send, assets, None), }; let mut test = SystemParaToRelayTest::new(test_args); @@ -421,12 +278,10 @@ fn limited_teleport_native_assets_from_system_para_to_relay_fails() { fn teleport_native_assets_from_relay_to_system_para_works() { // Init values for Relay Chain let amount_to_send: Balance = WESTEND_ED * 1000; - let dest = Westend::child_location_of(AssetHubWestend::para_id()); - let beneficiary = AssetHubWestendReceiver::get(); let test_args = TestContext { sender: WestendSender::get(), - receiver: beneficiary.clone(), - args: relay_test_args(dest, beneficiary, amount_to_send), + receiver: AssetHubWestendReceiver::get(), + args: relay_test_args(amount_to_send), }; let mut test = RelayToSystemParaTest::new(test_args); @@ -470,7 +325,7 @@ fn teleport_native_assets_back_from_system_para_to_relay_works() { let test_args = TestContext { sender: AssetHubWestendSender::get(), receiver: WestendReceiver::get(), - args: para_test_args(destination, beneficiary_id, amount_to_send, assets, None, 0), + args: system_para_test_args(destination, beneficiary_id, amount_to_send, assets, None), }; let mut test = SystemParaToRelayTest::new(test_args); @@ -511,7 +366,7 @@ fn teleport_native_assets_from_system_para_to_relay_fails() { let test_args = TestContext { sender: AssetHubWestendSender::get(), receiver: WestendReceiver::get(), - args: para_test_args(destination, beneficiary_id, amount_to_send, assets, None, 0), + args: system_para_test_args(destination, beneficiary_id, amount_to_send, assets, None), }; let mut test = SystemParaToRelayTest::new(test_args); @@ -539,211 +394,16 @@ fn teleport_native_assets_from_system_para_to_relay_fails() { assert_eq!(receiver_balance_after, receiver_balance_before); } -#[test] -fn teleport_to_other_system_parachains_works() { - let amount = ASSET_HUB_WESTEND_ED * 100; - let native_asset: MultiAssets = (Parent, amount).into(); - - test_parachain_is_trusted_teleporter!( - AssetHubWestend, // Origin - AssetHubWestendXcmConfig, // XCM Configuration - vec![BridgeHubWestend], // Destinations - (native_asset, amount) - ); -} - -/// Bidirectional teleports of local Penpal assets to Asset Hub as foreign assets should work -/// (using native reserve-based transfer for fees) -#[test] -fn bidirectional_teleport_foreign_assets_between_para_and_asset_hub() { - let ah_as_seen_by_penpal = PenpalB::sibling_location_of(AssetHubWestend::para_id()); - let asset_location_on_penpal = PenpalLocalTeleportableToAssetHub::get(); - let asset_id_on_penpal = match asset_location_on_penpal.last() { - Some(GeneralIndex(id)) => *id as u32, - _ => unreachable!(), - }; - let asset_owner_on_penpal = PenpalBSender::get(); - let foreign_asset_at_asset_hub_westend = - MultiLocation { parents: 1, interior: X1(Parachain(PenpalB::para_id().into())) } - .appended_with(asset_location_on_penpal) - .unwrap(); - super::penpal_create_foreign_asset_on_asset_hub( - asset_id_on_penpal, - foreign_asset_at_asset_hub_westend, - ah_as_seen_by_penpal, - false, - asset_owner_on_penpal, - ASSET_MIN_BALANCE * 1_000_000, - ); - let penpal_to_ah_beneficiary_id = AssetHubWestendReceiver::get(); - - let fee_amount_to_send = ASSET_HUB_WESTEND_ED * 1000; - let asset_amount_to_send = ASSET_MIN_BALANCE * 1000; - - let penpal_assets: MultiAssets = vec![ - (Parent, fee_amount_to_send).into(), - (asset_location_on_penpal, asset_amount_to_send).into(), - ] - .into(); - let fee_asset_index = penpal_assets - .inner() - .iter() - .position(|r| r == &(Parent, fee_amount_to_send).into()) - .unwrap() as u32; - - // Penpal to AH test args - let penpal_to_ah_test_args = TestContext { - sender: PenpalBSender::get(), - receiver: AssetHubWestendReceiver::get(), - args: para_test_args( - ah_as_seen_by_penpal, - penpal_to_ah_beneficiary_id, - asset_amount_to_send, - penpal_assets, - Some(asset_id_on_penpal), - fee_asset_index, - ), - }; - let mut penpal_to_ah = ParaToSystemParaTest::new(penpal_to_ah_test_args); - - let penpal_sender_balance_before = penpal_to_ah.sender.balance; - let ah_receiver_balance_before = penpal_to_ah.receiver.balance; - - let penpal_sender_assets_before = PenpalB::execute_with(|| { - type Assets = ::Assets; - >::balance(asset_id_on_penpal, &PenpalBSender::get()) - }); - let ah_receiver_assets_before = AssetHubWestend::execute_with(|| { - type Assets = ::ForeignAssets; - >::balance( - foreign_asset_at_asset_hub_westend, - &AssetHubWestendReceiver::get(), - ) - }); - - penpal_to_ah.set_assertion::(penpal_to_ah_foreign_assets_sender_assertions); - penpal_to_ah.set_assertion::(penpal_to_ah_foreign_assets_receiver_assertions); - penpal_to_ah.set_dispatchable::(para_to_system_para_transfer_assets); - penpal_to_ah.assert(); - - let penpal_sender_balance_after = penpal_to_ah.sender.balance; - let ah_receiver_balance_after = penpal_to_ah.receiver.balance; - - let penpal_sender_assets_after = PenpalB::execute_with(|| { - type Assets = ::Assets; - >::balance(asset_id_on_penpal, &PenpalBSender::get()) - }); - let ah_receiver_assets_after = AssetHubWestend::execute_with(|| { - type Assets = ::ForeignAssets; - >::balance( - foreign_asset_at_asset_hub_westend, - &AssetHubWestendReceiver::get(), - ) - }); - - // Sender's balance is reduced - assert!(penpal_sender_balance_after < penpal_sender_balance_before); - // Receiver's balance is increased - assert!(ah_receiver_balance_after > ah_receiver_balance_before); - // Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`; - // `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown but - // should be non-zero - assert!(ah_receiver_balance_after < ah_receiver_balance_before + fee_amount_to_send); - - // Sender's balance is reduced by exact amount - assert_eq!(penpal_sender_assets_before - asset_amount_to_send, penpal_sender_assets_after); - // Receiver's balance is increased by exact amount - assert_eq!(ah_receiver_assets_after, ah_receiver_assets_before + asset_amount_to_send); - - /////////////////////////////////////////////////////////////////////// - // Now test transferring foreign assets back from AssetHub to Penpal // - /////////////////////////////////////////////////////////////////////// - - // Move funds on AH from AHReceiver to AHSender - AssetHubWestend::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - assert_ok!(ForeignAssets::transfer( - ::RuntimeOrigin::signed(AssetHubWestendReceiver::get()), - foreign_asset_at_asset_hub_westend, - AssetHubWestendSender::get().into(), - asset_amount_to_send, - )); - }); - - let ah_to_penpal_beneficiary_id = PenpalBReceiver::get(); - let penpal_as_seen_by_ah = AssetHubWestend::sibling_location_of(PenpalB::para_id()); - let ah_assets: MultiAssets = vec![ - (Parent, fee_amount_to_send).into(), - (foreign_asset_at_asset_hub_westend, asset_amount_to_send).into(), - ] - .into(); - let fee_asset_index = ah_assets - .inner() - .iter() - .position(|r| r == &(Parent, fee_amount_to_send).into()) - .unwrap() as u32; - - // AH to Penpal test args - let ah_to_penpal_test_args = TestContext { - sender: AssetHubWestendSender::get(), - receiver: PenpalBReceiver::get(), - args: para_test_args( - penpal_as_seen_by_ah, - ah_to_penpal_beneficiary_id, - asset_amount_to_send, - ah_assets, - Some(asset_id_on_penpal), - fee_asset_index, - ), - }; - let mut ah_to_penpal = SystemParaToParaTest::new(ah_to_penpal_test_args); - - let ah_sender_balance_before = ah_to_penpal.sender.balance; - let penpal_receiver_balance_before = ah_to_penpal.receiver.balance; - - let ah_sender_assets_before = AssetHubWestend::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance( - foreign_asset_at_asset_hub_westend, - &AssetHubWestendSender::get(), - ) - }); - let penpal_receiver_assets_before = PenpalB::execute_with(|| { - type Assets = ::Assets; - >::balance(asset_id_on_penpal, &PenpalBReceiver::get()) - }); - - ah_to_penpal.set_assertion::(ah_to_penpal_foreign_assets_sender_assertions); - ah_to_penpal.set_assertion::(ah_to_penpal_foreign_assets_receiver_assertions); - ah_to_penpal.set_dispatchable::(system_para_to_para_transfer_assets); - ah_to_penpal.assert(); - - let ah_sender_balance_after = ah_to_penpal.sender.balance; - let penpal_receiver_balance_after = ah_to_penpal.receiver.balance; - - let ah_sender_assets_after = AssetHubWestend::execute_with(|| { - type ForeignAssets = ::ForeignAssets; - >::balance( - foreign_asset_at_asset_hub_westend, - &AssetHubWestendSender::get(), - ) - }); - let penpal_receiver_assets_after = PenpalB::execute_with(|| { - type Assets = ::Assets; - >::balance(asset_id_on_penpal, &PenpalBReceiver::get()) - }); - - // Sender's balance is reduced - assert!(ah_sender_balance_after < ah_sender_balance_before); - // Receiver's balance is increased - assert!(penpal_receiver_balance_after > penpal_receiver_balance_before); - // Receiver's balance increased by `amount_to_send - delivery_fees - bought_execution`; - // `delivery_fees` might be paid from transfer or JIT, also `bought_execution` is unknown but - // should be non-zero - assert!(penpal_receiver_balance_after < penpal_receiver_balance_before + fee_amount_to_send); - - // Sender's balance is reduced by exact amount - assert_eq!(ah_sender_assets_before - asset_amount_to_send, ah_sender_assets_after); - // Receiver's balance is increased by exact amount - assert_eq!(penpal_receiver_assets_after, penpal_receiver_assets_before + asset_amount_to_send); -} +// TODO: uncomment when CollectivesWestend and BridgeHubWestend are implemented +// https://github.com/paritytech/polkadot-sdk/pull/1737 (CollectivesWestend) +// #[test] +// fn teleport_to_other_system_parachains_works() { +// let amount = ASSET_HUB_WESTEND_ED * 100; +// let native_asset: VersionedMultiAssets = (Parent, amount).into(); + +// test_parachain_is_trusted_teleporter!( +// AssetHubWestend, // Origin +// vec![CollectivesWestend, BridgeHubWestend], // Destinations +// (native_asset, amount) +// ); +// } 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 ce6b8c24a44..00e3af2e4ff 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 @@ -7,9 +7,6 @@ license = "Apache-2.0" description = "Bridge Hub Rococo runtime integration tests with xcm-emulator" publish = false -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.4.0", default-features = false } @@ -18,22 +15,21 @@ frame-support = { path = "../../../../../../../substrate/frame/support", default pallet-assets = { path = "../../../../../../../substrate/frame/assets", 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 } # 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 = { 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} # Bridges -pallet-bridge-messages = { path = "../../../../../../../bridges/modules/messages", default-features = false } -bp-messages = { path = "../../../../../../../bridges/primitives/messages", default-features = false } +pallet-bridge-messages = { path = "../../../../../../../bridges/modules/messages", default-features = false} +bp-messages = { path = "../../../../../../../bridges/primitives/messages", default-features = false} # Cumulus asset-test-utils = { path = "../../../../../../parachains/runtimes/assets/test-utils" } parachains-common = { path = "../../../../../../parachains/common" } -cumulus-pallet-xcmp-queue = { path = "../../../../../../pallets/xcmp-queue", default-features = false } -cumulus-pallet-dmp-queue = { path = "../../../../../../pallets/dmp-queue", default-features = false } +cumulus-pallet-xcmp-queue = { path = "../../../../../../pallets/xcmp-queue", default-features = false} +cumulus-pallet-dmp-queue = { path = "../../../../../../pallets/dmp-queue", default-features = false} bridge-hub-rococo-runtime = { path = "../../../../../../parachains/runtimes/bridge-hubs/bridge-hub-rococo", default-features = false } -emulated-integration-tests-common = { path = "../../../common", default-features = false } +emulated-integration-tests-common = { path = "../../../common", default-features = false} rococo-westend-system-emulated-network = { path = "../../../networks/rococo-westend-system" } diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/lib.rs index 4ae2c6cc902..53665437887 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/lib.rs @@ -14,12 +14,10 @@ // limitations under the License. // Substrate -pub use frame_support::{assert_err, assert_ok, pallet_prelude::DispatchResult}; -pub use sp_runtime::DispatchError; +pub use frame_support::assert_ok; // Polkadot pub use xcm::{ - latest::ParentThen, prelude::{AccountId32 as AccountId32Junction, *}, v3::{ Error, diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/asset_transfers.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/asset_transfers.rs index 5a2111a9be9..c55613f2826 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/asset_transfers.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/asset_transfers.rs @@ -13,22 +13,70 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::tests::*; +use crate::*; fn send_asset_from_asset_hub_rococo_to_asset_hub_westend(id: MultiLocation, amount: u128) { - let destination = asset_hub_westend_location(); + let signed_origin = + ::RuntimeOrigin::signed(AssetHubRococoSender::get().into()); + let asset_hub_westend_para_id = AssetHubWestend::para_id().into(); + let destination = MultiLocation { + parents: 2, + interior: X2(GlobalConsensus(NetworkId::Westend), Parachain(asset_hub_westend_para_id)), + }; + let beneficiary_id = AssetHubWestendReceiver::get(); + let beneficiary: MultiLocation = + AccountId32Junction { network: None, id: beneficiary_id.into() }.into(); + let assets: MultiAssets = (id, amount).into(); + let fee_asset_item = 0; // fund the AHR's SA on BHR for paying bridge transport fees - BridgeHubRococo::fund_para_sovereign(AssetHubRococo::para_id(), 10_000_000_000_000u128); - - // set XCM versions - AssetHubRococo::force_xcm_version(destination, XCM_VERSION); - BridgeHubRococo::force_xcm_version(bridge_hub_westend_location(), XCM_VERSION); + let ahr_as_seen_by_bhr = BridgeHubRococo::sibling_location_of(AssetHubRococo::para_id()); + let sov_ahr_on_bhr = BridgeHubRococo::sovereign_account_id_of(ahr_as_seen_by_bhr); + BridgeHubRococo::fund_accounts(vec![(sov_ahr_on_bhr.into(), 10_000_000_000_000u128)]); + + AssetHubRococo::execute_with(|| { + assert_ok!( + ::PolkadotXcm::limited_reserve_transfer_assets( + signed_origin, + bx!(destination.into()), + bx!(beneficiary.into()), + bx!(assets.into()), + fee_asset_item, + WeightLimit::Unlimited, + ) + ); + }); - // send message over bridge - assert_ok!(send_asset_from_asset_hub_rococo(destination, (id, amount))); - assert_bridge_hub_rococo_message_accepted(true); - assert_bridge_hub_westend_message_received(); + BridgeHubRococo::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + assert_expected_events!( + BridgeHubRococo, + vec![ + // pay for bridge fees + RuntimeEvent::Balances(pallet_balances::Event::Withdraw { .. }) => {}, + // message exported + RuntimeEvent::BridgeWestendMessages( + pallet_bridge_messages::Event::MessageAccepted { .. } + ) => {}, + // message processed successfully + RuntimeEvent::MessageQueue( + pallet_message_queue::Event::Processed { success: true, .. } + ) => {}, + ] + ); + }); + BridgeHubWestend::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + assert_expected_events!( + BridgeHubWestend, + vec![ + // message dispatched successfully + RuntimeEvent::XcmpQueue( + cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. } + ) => {}, + ] + ); + }); } #[test] diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/mod.rs index d102dd2e5d6..4e2ef1434fd 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/mod.rs @@ -13,102 +13,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::*; - mod asset_transfers; mod send_xcm; mod teleport; - -pub(crate) fn asset_hub_westend_location() -> MultiLocation { - MultiLocation { - parents: 2, - interior: X2( - GlobalConsensus(NetworkId::Westend), - Parachain(AssetHubWestend::para_id().into()), - ), - } -} - -pub(crate) fn bridge_hub_westend_location() -> MultiLocation { - MultiLocation { - parents: 2, - interior: X2( - GlobalConsensus(NetworkId::Westend), - Parachain(BridgeHubWestend::para_id().into()), - ), - } -} - -pub(crate) fn send_asset_from_asset_hub_rococo( - destination: MultiLocation, - (id, amount): (MultiLocation, u128), -) -> DispatchResult { - let signed_origin = - ::RuntimeOrigin::signed(AssetHubRococoSender::get().into()); - - let beneficiary: MultiLocation = - AccountId32Junction { network: None, id: AssetHubWestendReceiver::get().into() }.into(); - - let assets: MultiAssets = (id, amount).into(); - let fee_asset_item = 0; - - AssetHubRococo::execute_with(|| { - ::PolkadotXcm::limited_reserve_transfer_assets( - signed_origin, - bx!(destination.into()), - bx!(beneficiary.into()), - bx!(assets.into()), - fee_asset_item, - WeightLimit::Unlimited, - ) - }) -} - -pub(crate) fn assert_bridge_hub_rococo_message_accepted(expected_processed: bool) { - BridgeHubRococo::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - - if expected_processed { - assert_expected_events!( - BridgeHubRococo, - vec![ - // pay for bridge fees - RuntimeEvent::Balances(pallet_balances::Event::Withdraw { .. }) => {}, - // message exported - RuntimeEvent::BridgeWestendMessages( - pallet_bridge_messages::Event::MessageAccepted { .. } - ) => {}, - // message processed successfully - RuntimeEvent::MessageQueue( - pallet_message_queue::Event::Processed { success: true, .. } - ) => {}, - ] - ); - } else { - assert_expected_events!( - BridgeHubRococo, - vec![ - RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { - success: false, - .. - }) => {}, - ] - ); - } - }); -} - -pub(crate) fn assert_bridge_hub_westend_message_received() { - BridgeHubWestend::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - assert_expected_events!( - BridgeHubWestend, - vec![ - // message sent to destination - RuntimeEvent::XcmpQueue( - cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. } - ) => {}, - ] - ); - }) -} diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/send_xcm.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/send_xcm.rs index a3a7d96a14a..4e61f7ce0dd 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/send_xcm.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/send_xcm.rs @@ -13,10 +13,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::tests::*; +use crate::*; #[test] -fn send_xcm_from_rococo_relay_to_westend_asset_hub_should_fail_on_not_applicable() { +fn send_xcm_from_rococo_relay_to_westend_asset_hub() { // Init tests variables // XcmPallet send arguments let sudo_origin = ::RuntimeOrigin::root(); @@ -53,125 +53,48 @@ fn send_xcm_from_rococo_relay_to_westend_asset_hub_should_fail_on_not_applicable ] ); }); - // Receive XCM message in Bridge Hub source Parachain, it should fail, because we don't have - // opened bridge/lane. - assert_bridge_hub_rococo_message_accepted(false); -} - -#[test] -fn send_xcm_through_opened_lane_with_different_xcm_version_on_hops_works() { - // Initially set only default version on all runtimes - AssetHubRococo::force_default_xcm_version(Some(xcm::v2::prelude::XCM_VERSION)); - BridgeHubRococo::force_default_xcm_version(Some(xcm::v2::prelude::XCM_VERSION)); - BridgeHubWestend::force_default_xcm_version(Some(xcm::v2::prelude::XCM_VERSION)); - AssetHubWestend::force_default_xcm_version(Some(xcm::v2::prelude::XCM_VERSION)); - - // prepare data - let destination = asset_hub_westend_location(); - let native_token = MultiLocation::parent(); - let amount = ASSET_HUB_ROCOCO_ED * 1_000; - - // fund the AHR's SA on BHR for paying bridge transport fees - BridgeHubRococo::fund_para_sovereign(AssetHubRococo::para_id(), 10_000_000_000_000u128); - // fund sender - AssetHubRococo::fund_accounts(vec![(AssetHubRococoSender::get().into(), amount * 10)]); - - // send XCM from AssetHubRococo - fails - destination version not known - assert_err!( - send_asset_from_asset_hub_rococo(destination, (native_token, amount)), - DispatchError::Module(sp_runtime::ModuleError { - index: 31, - error: [1, 0, 0, 0], - message: Some("SendFailure") - }) - ); - - // set destination version - AssetHubRococo::force_xcm_version(destination, xcm::v3::prelude::XCM_VERSION); + // Receive XCM message in Bridge Hub source Parachain + BridgeHubRococo::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; - // TODO: remove this block, when removing `xcm:v2` - { - // send XCM from AssetHubRococo - fails - AssetHubRococo is set to the default/safe `2` - // version, which does not have the `ExportMessage` instruction. If the default `2` is - // changed to `3`, then this assert can go away" - assert_err!( - send_asset_from_asset_hub_rococo(destination, (native_token, amount)), - DispatchError::Module(sp_runtime::ModuleError { - index: 31, - error: [1, 0, 0, 0], - message: Some("SendFailure") - }) - ); - - // set exact version for BridgeHubWestend to `2` without `ExportMessage` instruction - AssetHubRococo::force_xcm_version( - ParentThen(Parachain(BridgeHubRococo::para_id().into()).into()).into(), - xcm::v2::prelude::XCM_VERSION, - ); - // send XCM from AssetHubRococo - fails - `ExportMessage` is not in `2` - assert_err!( - send_asset_from_asset_hub_rococo(destination, (native_token, amount)), - DispatchError::Module(sp_runtime::ModuleError { - index: 31, - error: [1, 0, 0, 0], - message: Some("SendFailure") - }) + assert_expected_events!( + BridgeHubRococo, + vec![ + RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { + success: true, + .. + }) => {}, + RuntimeEvent::BridgeWestendMessages(pallet_bridge_messages::Event::MessageAccepted { + lane_id: LaneId([0, 0, 0, 2]), + nonce: 1, + }) => {}, + ] ); - } - - // set version with `ExportMessage` for BridgeHubRococo - AssetHubRococo::force_xcm_version( - ParentThen(Parachain(BridgeHubRococo::para_id().into()).into()).into(), - xcm::v3::prelude::XCM_VERSION, - ); - // send XCM from AssetHubRococo - ok - assert_ok!(send_asset_from_asset_hub_rococo(destination, (native_token, amount))); - - // `ExportMessage` on local BridgeHub - fails - remote BridgeHub version not known - assert_bridge_hub_rococo_message_accepted(false); + }); - // set version for remote BridgeHub on BridgeHubRococo - BridgeHubRococo::force_xcm_version( - bridge_hub_westend_location(), - xcm::v3::prelude::XCM_VERSION, - ); - // set version for AssetHubWestend on BridgeHubWestend - BridgeHubWestend::force_xcm_version( - ParentThen(Parachain(AssetHubWestend::para_id().into()).into()).into(), - xcm::v3::prelude::XCM_VERSION, - ); + // Westend Global Consensus + // Receive XCM message in Bridge Hub target Parachain + BridgeHubWestend::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; - // send XCM from AssetHubRococo - ok - assert_ok!(send_asset_from_asset_hub_rococo(destination, (native_token, amount))); - assert_bridge_hub_rococo_message_accepted(true); - assert_bridge_hub_westend_message_received(); - // message delivered and processed at destination + assert_expected_events!( + BridgeHubWestend, + vec![ + RuntimeEvent::XcmpQueue(cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. }) => {}, + ] + ); + }); + // Receive embedded XCM message within `ExportMessage` in Parachain destination AssetHubWestend::execute_with(|| { type RuntimeEvent = ::RuntimeEvent; + assert_expected_events!( AssetHubWestend, vec![ - // message processed with failure, but for this scenario it is ok, important is that was delivered - RuntimeEvent::MessageQueue( - pallet_message_queue::Event::Processed { success: false, .. } - ) => {}, + RuntimeEvent::MessageQueue(pallet_message_queue::Event::ProcessingFailed { + .. + }) => {}, ] ); }); - - // TODO: remove this block, when removing `xcm:v2` - { - // set `2` version for remote BridgeHub on BridgeHubRococo, which does not have - // `UniversalOrigin` and `DescendOrigin` - BridgeHubRococo::force_xcm_version( - bridge_hub_westend_location(), - xcm::v2::prelude::XCM_VERSION, - ); - - // send XCM from AssetHubRococo - ok - assert_ok!(send_asset_from_asset_hub_rococo(destination, (native_token, amount))); - // message is not accepted on the local BridgeHub (`DestinationUnsupported`) because we - // cannot add `UniversalOrigin` and `DescendOrigin` - assert_bridge_hub_rococo_message_accepted(false); - } } 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 6dcb57f4161..e5b1fce5f2b 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 @@ -7,9 +7,6 @@ license = "Apache-2.0" description = "Bridge Hub Westend runtime integration tests with xcm-emulator" publish = false -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.4.0", default-features = false } @@ -18,22 +15,21 @@ frame-support = { path = "../../../../../../../substrate/frame/support", default pallet-assets = { path = "../../../../../../../substrate/frame/assets", 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 } # 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 = { 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} # Bridges -pallet-bridge-messages = { path = "../../../../../../../bridges/modules/messages", default-features = false } -bp-messages = { path = "../../../../../../../bridges/primitives/messages", default-features = false } +pallet-bridge-messages = { path = "../../../../../../../bridges/modules/messages", default-features = false} +bp-messages = { path = "../../../../../../../bridges/primitives/messages", default-features = false} # Cumulus asset-test-utils = { path = "../../../../../../parachains/runtimes/assets/test-utils" } parachains-common = { path = "../../../../../../parachains/common" } -cumulus-pallet-xcmp-queue = { path = "../../../../../../pallets/xcmp-queue", default-features = false } -cumulus-pallet-dmp-queue = { path = "../../../../../../pallets/dmp-queue", default-features = false } +cumulus-pallet-xcmp-queue = { path = "../../../../../../pallets/xcmp-queue", default-features = false} +cumulus-pallet-dmp-queue = { path = "../../../../../../pallets/dmp-queue", default-features = false} bridge-hub-westend-runtime = { path = "../../../../../../parachains/runtimes/bridge-hubs/bridge-hub-westend", default-features = false } -emulated-integration-tests-common = { path = "../../../common", default-features = false } +emulated-integration-tests-common = { path = "../../../common", default-features = false} rococo-westend-system-emulated-network = { path = "../../../networks/rococo-westend-system" } diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs index 90a11d38f77..04746aa8670 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs @@ -14,12 +14,10 @@ // limitations under the License. // Substrate -pub use frame_support::{assert_err, assert_ok, pallet_prelude::DispatchResult}; -pub use sp_runtime::DispatchError; +pub use frame_support::assert_ok; // Polkadot pub use xcm::{ - latest::ParentThen, prelude::{AccountId32 as AccountId32Junction, *}, v3::{ Error, diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/asset_transfers.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/asset_transfers.rs index 21f4b4ee235..f90514f80c3 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/asset_transfers.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/asset_transfers.rs @@ -12,22 +12,70 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -use crate::tests::*; +use crate::*; fn send_asset_from_asset_hub_westend_to_asset_hub_rococo(id: MultiLocation, amount: u128) { - let destination = asset_hub_rococo_location(); + let signed_origin = + ::RuntimeOrigin::signed(AssetHubWestendSender::get().into()); + let asset_hub_rococo_para_id = AssetHubRococo::para_id().into(); + let destination = MultiLocation { + parents: 2, + interior: X2(GlobalConsensus(NetworkId::Rococo), Parachain(asset_hub_rococo_para_id)), + }; + let beneficiary_id = AssetHubRococoReceiver::get(); + let beneficiary: MultiLocation = + AccountId32Junction { network: None, id: beneficiary_id.into() }.into(); + let assets: MultiAssets = (id, amount).into(); + let fee_asset_item = 0; // fund the AHW's SA on BHW for paying bridge transport fees - BridgeHubWestend::fund_para_sovereign(AssetHubWestend::para_id(), 10_000_000_000_000u128); - - // set XCM versions - AssetHubWestend::force_xcm_version(destination, XCM_VERSION); - BridgeHubWestend::force_xcm_version(bridge_hub_rococo_location(), XCM_VERSION); + let ahw_as_seen_by_bhw = BridgeHubWestend::sibling_location_of(AssetHubWestend::para_id()); + let sov_ahw_on_bhw = BridgeHubWestend::sovereign_account_id_of(ahw_as_seen_by_bhw); + BridgeHubWestend::fund_accounts(vec![(sov_ahw_on_bhw.into(), 10_000_000_000_000u128)]); + + AssetHubWestend::execute_with(|| { + assert_ok!( + ::PolkadotXcm::limited_reserve_transfer_assets( + signed_origin, + bx!(destination.into()), + bx!(beneficiary.into()), + bx!(assets.into()), + fee_asset_item, + WeightLimit::Unlimited, + ) + ); + }); - // send message over bridge - assert_ok!(send_asset_from_asset_hub_westend(destination, (id, amount))); - assert_bridge_hub_westend_message_accepted(true); - assert_bridge_hub_rococo_message_received(); + BridgeHubWestend::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + assert_expected_events!( + BridgeHubWestend, + vec![ + // pay for bridge fees + RuntimeEvent::Balances(pallet_balances::Event::Withdraw { .. }) => {}, + // message exported + RuntimeEvent::BridgeRococoMessages( + pallet_bridge_messages::Event::MessageAccepted { .. } + ) => {}, + // message processed successfully + RuntimeEvent::MessageQueue( + pallet_message_queue::Event::Processed { success: true, .. } + ) => {}, + ] + ); + }); + BridgeHubRococo::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; + assert_expected_events!( + BridgeHubRococo, + vec![ + // message dispatched successfully + RuntimeEvent::XcmpQueue( + cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. } + ) => {}, + ] + ); + }); } #[test] diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/mod.rs index ec2e68fc889..4e2ef1434fd 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/mod.rs @@ -13,102 +13,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::*; - mod asset_transfers; mod send_xcm; mod teleport; - -pub(crate) fn asset_hub_rococo_location() -> MultiLocation { - MultiLocation { - parents: 2, - interior: X2( - GlobalConsensus(NetworkId::Rococo), - Parachain(AssetHubRococo::para_id().into()), - ), - } -} - -pub(crate) fn bridge_hub_rococo_location() -> MultiLocation { - MultiLocation { - parents: 2, - interior: X2( - GlobalConsensus(NetworkId::Rococo), - Parachain(BridgeHubRococo::para_id().into()), - ), - } -} - -pub(crate) fn send_asset_from_asset_hub_westend( - destination: MultiLocation, - (id, amount): (MultiLocation, u128), -) -> DispatchResult { - let signed_origin = - ::RuntimeOrigin::signed(AssetHubWestendSender::get().into()); - - let beneficiary: MultiLocation = - AccountId32Junction { network: None, id: AssetHubRococoReceiver::get().into() }.into(); - - let assets: MultiAssets = (id, amount).into(); - let fee_asset_item = 0; - - AssetHubWestend::execute_with(|| { - ::PolkadotXcm::limited_reserve_transfer_assets( - signed_origin, - bx!(destination.into()), - bx!(beneficiary.into()), - bx!(assets.into()), - fee_asset_item, - WeightLimit::Unlimited, - ) - }) -} - -pub(crate) fn assert_bridge_hub_westend_message_accepted(expected_processed: bool) { - BridgeHubWestend::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - - if expected_processed { - assert_expected_events!( - BridgeHubWestend, - vec![ - // pay for bridge fees - RuntimeEvent::Balances(pallet_balances::Event::Withdraw { .. }) => {}, - // message exported - RuntimeEvent::BridgeRococoMessages( - pallet_bridge_messages::Event::MessageAccepted { .. } - ) => {}, - // message processed successfully - RuntimeEvent::MessageQueue( - pallet_message_queue::Event::Processed { success: true, .. } - ) => {}, - ] - ); - } else { - assert_expected_events!( - BridgeHubWestend, - vec![ - RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { - success: false, - .. - }) => {}, - ] - ); - } - }); -} - -pub(crate) fn assert_bridge_hub_rococo_message_received() { - BridgeHubRococo::execute_with(|| { - type RuntimeEvent = ::RuntimeEvent; - assert_expected_events!( - BridgeHubRococo, - vec![ - // message sent to destination - RuntimeEvent::XcmpQueue( - cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. } - ) => {}, - ] - ); - }) -} diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/send_xcm.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/send_xcm.rs index 0773cbb0599..4b21d758cd9 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/send_xcm.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/send_xcm.rs @@ -13,10 +13,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::tests::*; +use crate::*; #[test] -fn send_xcm_from_westend_relay_to_rococo_asset_hub_should_fail_on_not_applicable() { +fn send_xcm_from_westend_relay_to_rococo_asset_hub() { // Init tests variables // XcmPallet send arguments let sudo_origin = ::RuntimeOrigin::root(); @@ -53,125 +53,48 @@ fn send_xcm_from_westend_relay_to_rococo_asset_hub_should_fail_on_not_applicable ] ); }); - // Receive XCM message in Bridge Hub source Parachain, it should fail, because we don't have - // opened bridge/lane. - assert_bridge_hub_westend_message_accepted(false); -} - -#[test] -fn send_xcm_through_opened_lane_with_different_xcm_version_on_hops_works() { - // Initially set only default version on all runtimes - AssetHubRococo::force_default_xcm_version(Some(xcm::v2::prelude::XCM_VERSION)); - BridgeHubRococo::force_default_xcm_version(Some(xcm::v2::prelude::XCM_VERSION)); - BridgeHubWestend::force_default_xcm_version(Some(xcm::v2::prelude::XCM_VERSION)); - AssetHubWestend::force_default_xcm_version(Some(xcm::v2::prelude::XCM_VERSION)); - - // prepare data - let destination = asset_hub_rococo_location(); - let native_token = MultiLocation::parent(); - let amount = ASSET_HUB_WESTEND_ED * 1_000; - - // fund the AHR's SA on BHR for paying bridge transport fees - BridgeHubWestend::fund_para_sovereign(AssetHubWestend::para_id(), 10_000_000_000_000u128); - // fund sender - AssetHubWestend::fund_accounts(vec![(AssetHubWestendSender::get().into(), amount * 10)]); - - // send XCM from AssetHubWestend - fails - destination version not known - assert_err!( - send_asset_from_asset_hub_westend(destination, (native_token, amount)), - DispatchError::Module(sp_runtime::ModuleError { - index: 31, - error: [1, 0, 0, 0], - message: Some("SendFailure") - }) - ); - - // set destination version - AssetHubWestend::force_xcm_version(destination, xcm::v3::prelude::XCM_VERSION); + // Receive XCM message in Bridge Hub source Parachain + BridgeHubWestend::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; - // TODO: remove this block, when removing `xcm:v2` - { - // send XCM from AssetHubRococo - fails - AssetHubRococo is set to the default/safe `2` - // version, which does not have the `ExportMessage` instruction. If the default `2` is - // changed to `3`, then this assert can go away" - assert_err!( - send_asset_from_asset_hub_westend(destination, (native_token, amount)), - DispatchError::Module(sp_runtime::ModuleError { - index: 31, - error: [1, 0, 0, 0], - message: Some("SendFailure") - }) - ); - - // set exact version for BridgeHubWestend to `2` without `ExportMessage` instruction - AssetHubWestend::force_xcm_version( - ParentThen(Parachain(BridgeHubWestend::para_id().into()).into()).into(), - xcm::v2::prelude::XCM_VERSION, - ); - // send XCM from AssetHubWestend - fails - `ExportMessage` is not in `2` - assert_err!( - send_asset_from_asset_hub_westend(destination, (native_token, amount)), - DispatchError::Module(sp_runtime::ModuleError { - index: 31, - error: [1, 0, 0, 0], - message: Some("SendFailure") - }) + assert_expected_events!( + BridgeHubWestend, + vec![ + RuntimeEvent::MessageQueue(pallet_message_queue::Event::Processed { + success: true, + .. + }) => {}, + RuntimeEvent::BridgeRococoMessages(pallet_bridge_messages::Event::MessageAccepted { + lane_id: LaneId([0, 0, 0, 2]), + nonce: 1, + }) => {}, + ] ); - } - - // set version with `ExportMessage` for BridgeHubWestend - AssetHubWestend::force_xcm_version( - ParentThen(Parachain(BridgeHubWestend::para_id().into()).into()).into(), - xcm::v3::prelude::XCM_VERSION, - ); - // send XCM from AssetHubWestend - ok - assert_ok!(send_asset_from_asset_hub_westend(destination, (native_token, amount))); - - // `ExportMessage` on local BridgeHub - fails - remote BridgeHub version not known - assert_bridge_hub_westend_message_accepted(false); + }); - // set version for remote BridgeHub on BridgeHubWestend - BridgeHubWestend::force_xcm_version( - bridge_hub_rococo_location(), - xcm::v3::prelude::XCM_VERSION, - ); - // set version for AssetHubRococo on BridgeHubRococo - BridgeHubRococo::force_xcm_version( - ParentThen(Parachain(AssetHubRococo::para_id().into()).into()).into(), - xcm::v3::prelude::XCM_VERSION, - ); + // Rococo Global Consensus + // Receive XCM message in Bridge Hub target Parachain + BridgeHubRococo::execute_with(|| { + type RuntimeEvent = ::RuntimeEvent; - // send XCM from AssetHubWestend - ok - assert_ok!(send_asset_from_asset_hub_westend(destination, (native_token, amount))); - assert_bridge_hub_westend_message_accepted(true); - assert_bridge_hub_rococo_message_received(); - // message delivered and processed at destination + assert_expected_events!( + BridgeHubRococo, + vec![ + RuntimeEvent::XcmpQueue(cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. }) => {}, + ] + ); + }); + // Receive embedded XCM message within `ExportMessage` in Parachain destination AssetHubRococo::execute_with(|| { type RuntimeEvent = ::RuntimeEvent; + assert_expected_events!( AssetHubRococo, vec![ - // message processed with failure, but for this scenario it is ok, important is that was delivered - RuntimeEvent::MessageQueue( - pallet_message_queue::Event::Processed { success: false, .. } - ) => {}, + RuntimeEvent::MessageQueue(pallet_message_queue::Event::ProcessingFailed { + .. + }) => {}, ] ); }); - - // TODO: remove this block, when removing `xcm:v2` - { - // set `2` version for remote BridgeHub on BridgeHubRococo, which does not have - // `UniversalOrigin` and `DescendOrigin` - BridgeHubWestend::force_xcm_version( - bridge_hub_rococo_location(), - xcm::v2::prelude::XCM_VERSION, - ); - - // send XCM from AssetHubWestend - ok - assert_ok!(send_asset_from_asset_hub_westend(destination, (native_token, amount))); - // message is not accepted on the local BridgeHub (`DestinationUnsupported`) because we - // cannot add `UniversalOrigin` and `DescendOrigin` - assert_bridge_hub_westend_message_accepted(false); - } } diff --git a/cumulus/parachains/pallets/collective-content/Cargo.toml b/cumulus/parachains/pallets/collective-content/Cargo.toml index 9ed2822fa30..e3f8023f419 100644 --- a/cumulus/parachains/pallets/collective-content/Cargo.toml +++ b/cumulus/parachains/pallets/collective-content/Cargo.toml @@ -6,9 +6,6 @@ edition = "2021" description = "Managed content" license = "Apache-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } @@ -25,7 +22,7 @@ sp-std = { path = "../../../../substrate/primitives/std", default-features = fal sp-io = { path = "../../../../substrate/primitives/io", default-features = false } [features] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", diff --git a/cumulus/parachains/pallets/collective-content/src/mock.rs b/cumulus/parachains/pallets/collective-content/src/mock.rs index 7a752da71fc..2ae5943f332 100644 --- a/cumulus/parachains/pallets/collective-content/src/mock.rs +++ b/cumulus/parachains/pallets/collective-content/src/mock.rs @@ -18,7 +18,7 @@ pub use crate as pallet_collective_content; use crate::WeightInfo; use frame_support::{ - derive_impl, ord_parameter_types, parameter_types, + ord_parameter_types, parameter_types, traits::{ConstU32, ConstU64}, weights::Weight, }; @@ -55,7 +55,6 @@ impl pallet_collective_content::Config for Test { type WeightInfo = CCWeightInfo; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = (); type BlockWeights = (); diff --git a/cumulus/parachains/pallets/parachain-info/Cargo.toml b/cumulus/parachains/pallets/parachain-info/Cargo.toml index 31f7b8aef39..727182dfb8e 100644 --- a/cumulus/parachains/pallets/parachain-info/Cargo.toml +++ b/cumulus/parachains/pallets/parachain-info/Cargo.toml @@ -6,23 +6,20 @@ version = "0.1.0" license = "Apache-2.0" description = "Pallet to store the parachain ID" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } +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-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false} +sp-std = { path = "../../../../substrate/primitives/std", default-features = false} cumulus-primitives-core = { path = "../../../primitives/core", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-primitives-core/std", diff --git a/cumulus/parachains/pallets/ping/Cargo.toml b/cumulus/parachains/pallets/ping/Cargo.toml index 5c1099a110a..0133befa855 100644 --- a/cumulus/parachains/pallets/ping/Cargo.toml +++ b/cumulus/parachains/pallets/ping/Cargo.toml @@ -6,25 +6,22 @@ version = "0.1.0" license = "Apache-2.0" description = "Ping Pallet for Cumulus XCM/UMP testing." -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -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 = { 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} -xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false } +xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false} cumulus-primitives-core = { path = "../../../primitives/core", default-features = false } cumulus-pallet-xcm = { path = "../../../pallets/xcm", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-pallet-xcm/std", diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-kusama/Cargo.toml new file mode 100644 index 00000000000..f71499e0c29 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/Cargo.toml @@ -0,0 +1,236 @@ +[package] +name = "asset-hub-kusama-runtime" +version = "0.9.420" +authors.workspace = true +edition.workspace = true +description = "Kusama variant of Asset Hub parachain runtime" +license = "Apache-2.0" + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } +hex-literal = { version = "0.4.1" } +log = { version = "0.4.20", default-features = false } +scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } +smallvec = "1.11.0" + +# 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-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, optional = true } +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} +sp-weights = { path = "../../../../../substrate/primitives/weights", default-features = false} +# num-traits feature needed for dex integer sq root: +primitive-types = { version = "0.12.1", default-features = false, features = ["codec", "scale-info", "num-traits"] } + +# 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-core-primitives = { path = "../../../../../polkadot/core-primitives", 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} + +# 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-dmp-queue = { path = "../../../../pallets/dmp-queue", default-features = false } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } +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 = "../common", default-features = false } + +[dev-dependencies] +asset-test-utils = { path = "../test-utils" } + +[build-dependencies] +substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } + +[features] +default = [ "std" ] +# When enabled the `state_version` is set to `1`. +# This means that the chain will start using the new state format. The migration is lazy, so +# it requires to write a storage value to use the new state format. To migrate all the other +# storage values that aren't touched the state migration pallet is added as well. +# This pallet will migrate the entire state, controlled through some account. +# +# This feature should be removed when the main-net will be migrated. +state-trie-version-1 = [ "pallet-state-trie-migration" ] +runtime-benchmarks = [ + "assets-common/runtime-benchmarks", + "cumulus-pallet-dmp-queue/runtime-benchmarks", + "cumulus-pallet-parachain-system/runtime-benchmarks", + "cumulus-pallet-session-benchmarking/runtime-benchmarks", + "cumulus-pallet-xcmp-queue/runtime-benchmarks", + "cumulus-primitives-core/runtime-benchmarks", + "cumulus-primitives-utility/runtime-benchmarks", + "frame-benchmarking/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "frame-system-benchmarking/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-asset-conversion/runtime-benchmarks", + "pallet-assets/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", + "pallet-collator-selection/runtime-benchmarks", + "pallet-message-queue/runtime-benchmarks", + "pallet-multisig/runtime-benchmarks", + "pallet-nft-fractionalization/runtime-benchmarks", + "pallet-nfts/runtime-benchmarks", + "pallet-proxy/runtime-benchmarks", + "pallet-state-trie-migration/runtime-benchmarks", + "pallet-timestamp/runtime-benchmarks", + "pallet-uniques/runtime-benchmarks", + "pallet-utility/runtime-benchmarks", + "pallet-xcm-benchmarks/runtime-benchmarks", + "pallet-xcm/runtime-benchmarks", + "parachains-common/runtime-benchmarks", + "polkadot-parachain-primitives/runtime-benchmarks", + "polkadot-runtime-common/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", + "xcm-executor/runtime-benchmarks", +] +try-runtime = [ + "cumulus-pallet-aura-ext/try-runtime", + "cumulus-pallet-dmp-queue/try-runtime", + "cumulus-pallet-parachain-system/try-runtime", + "cumulus-pallet-xcm/try-runtime", + "cumulus-pallet-xcmp-queue/try-runtime", + "frame-executive/try-runtime", + "frame-support/try-runtime", + "frame-system/try-runtime", + "frame-try-runtime/try-runtime", + "pallet-asset-conversion-tx-payment/try-runtime", + "pallet-asset-conversion/try-runtime", + "pallet-assets/try-runtime", + "pallet-aura/try-runtime", + "pallet-authorship/try-runtime", + "pallet-balances/try-runtime", + "pallet-collator-selection/try-runtime", + "pallet-message-queue/try-runtime", + "pallet-multisig/try-runtime", + "pallet-nft-fractionalization/try-runtime", + "pallet-nfts/try-runtime", + "pallet-proxy/try-runtime", + "pallet-session/try-runtime", + "pallet-state-trie-migration/try-runtime", + "pallet-timestamp/try-runtime", + "pallet-transaction-payment/try-runtime", + "pallet-uniques/try-runtime", + "pallet-utility/try-runtime", + "pallet-xcm/try-runtime", + "parachain-info/try-runtime", + "polkadot-runtime-common/try-runtime", + "sp-runtime/try-runtime", +] +std = [ + "assets-common/std", + "codec/std", + "cumulus-pallet-aura-ext/std", + "cumulus-pallet-dmp-queue/std", + "cumulus-pallet-parachain-system/std", + "cumulus-pallet-session-benchmarking/std", + "cumulus-pallet-xcm/std", + "cumulus-pallet-xcmp-queue/std", + "cumulus-primitives-core/std", + "cumulus-primitives-utility/std", + "frame-benchmarking?/std", + "frame-executive/std", + "frame-support/std", + "frame-system-benchmarking?/std", + "frame-system-rpc-runtime-api/std", + "frame-system/std", + "frame-try-runtime?/std", + "log/std", + "pallet-asset-conversion-tx-payment/std", + "pallet-asset-conversion/std", + "pallet-assets/std", + "pallet-aura/std", + "pallet-authorship/std", + "pallet-balances/std", + "pallet-collator-selection/std", + "pallet-message-queue/std", + "pallet-multisig/std", + "pallet-nft-fractionalization/std", + "pallet-nfts-runtime-api/std", + "pallet-nfts/std", + "pallet-proxy/std", + "pallet-session/std", + "pallet-state-trie-migration/std", + "pallet-timestamp/std", + "pallet-transaction-payment-rpc-runtime-api/std", + "pallet-transaction-payment/std", + "pallet-uniques/std", + "pallet-utility/std", + "pallet-xcm-benchmarks?/std", + "pallet-xcm/std", + "parachain-info/std", + "parachains-common/std", + "polkadot-core-primitives/std", + "polkadot-parachain-primitives/std", + "polkadot-runtime-common/std", + "primitive-types/std", + "scale-info/std", + "sp-api/std", + "sp-block-builder/std", + "sp-consensus-aura/std", + "sp-core/std", + "sp-genesis-builder/std", + "sp-inherents/std", + "sp-offchain/std", + "sp-runtime/std", + "sp-session/std", + "sp-std/std", + "sp-storage/std", + "sp-transaction-pool/std", + "sp-version/std", + "sp-weights/std", + "substrate-wasm-builder", + "xcm-builder/std", + "xcm-executor/std", + "xcm/std", +] + +experimental = [ "pallet-aura/experimental" ] diff --git a/substrate/frame/support/test/tests/pallet_ui/task_can_only_be_attached_to_impl.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/build.rs similarity index 63% rename from substrate/frame/support/test/tests/pallet_ui/task_can_only_be_attached_to_impl.rs rename to cumulus/parachains/runtimes/assets/asset-hub-kusama/build.rs index 95f5655af19..60f8a125129 100644 --- a/substrate/frame/support/test/tests/pallet_ui/task_can_only_be_attached_to_impl.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/build.rs @@ -1,5 +1,3 @@ -// This file is part of Substrate. - // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 @@ -15,20 +13,14 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[frame_support::pallet(dev_mode)] -mod pallet { - use frame_support::pallet_prelude::DispatchResult; - use frame_system::pallet_prelude::OriginFor; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(core::marker::PhantomData); - - #[pallet::tasks_experimental] - pub struct Task; -} - +#[cfg(feature = "std")] fn main() { + substrate_wasm_builder::WasmBuilder::new() + .with_current_project() + .export_heap_base() + .import_memory() + .build() } + +#[cfg(not(feature = "std"))] +fn main() {} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/lib.rs new file mode 100644 index 00000000000..f8998e2f954 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/lib.rs @@ -0,0 +1,1549 @@ +// 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. + +//! # Asset Hub Kusama Runtime +//! +//! Asset Hub Kusama, formerly known as "Statemine", is the canary network for its Polkadot cousin. + +#![cfg_attr(not(feature = "std"), no_std)] +#![recursion_limit = "256"] + +// Make the WASM binary available. +#[cfg(feature = "std")] +include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); + +mod weights; +pub mod xcm_config; + +use assets_common::{ + foreign_creators::ForeignCreators, + local_and_foreign_assets::{LocalAndForeignAssets, MultiLocationConverter}, + matching::FromSiblingParachain, + AssetIdForTrustBackedAssetsConvert, MultiLocationForAssetId, +}; +use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; +use sp_api::impl_runtime_apis; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; +use sp_runtime::{ + create_runtime_str, generic, impl_opaque_keys, + traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Verify}, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, Perbill, Permill, +}; + +use sp_std::prelude::*; +#[cfg(feature = "std")] +use sp_version::NativeVersion; +use sp_version::RuntimeVersion; + +use codec::{Decode, Encode, MaxEncodedLen}; +use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; +use frame_support::{ + construct_runtime, + dispatch::DispatchClass, + genesis_builder_helper::{build_config, create_default_config}, + ord_parameter_types, parameter_types, + traits::{ + AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, EitherOfDiverse, + InstanceFilter, TransformOrigin, + }, + weights::{ConstantMultiplier, Weight}, + BoundedVec, PalletId, +}; +use frame_system::{ + limits::{BlockLength, BlockWeights}, + EnsureRoot, EnsureSigned, EnsureSignedBy, +}; +use pallet_asset_conversion_tx_payment::AssetConversionAdapter; +use pallet_nfts::PalletFeatures; +pub use parachains_common as common; +use parachains_common::{ + impls::DealWithFees, + kusama::{consensus::*, currency::*, fee::WeightToFee}, + message_queue::{NarrowOriginToSibling, ParaIdToSibling}, + AccountId, AssetIdForTrustBackedAssets, AuraId, Balance, BlockNumber, Hash, Header, Nonce, + Signature, AVERAGE_ON_INITIALIZE_RATIO, DAYS, HOURS, MAXIMUM_BLOCK_WEIGHT, + NORMAL_DISPATCH_RATIO, SLOT_DURATION, +}; +use sp_runtime::RuntimeDebug; +use xcm::opaque::v3::MultiLocation; +use xcm_config::{ + FellowshipLocation, ForeignAssetsConvertedConcreteId, GovernanceLocation, KsmLocation, + PoolAssetsConvertedConcreteId, TrustBackedAssetsConvertedConcreteId, +}; + +#[cfg(any(feature = "std", test))] +pub use sp_runtime::BuildStorage; + +// Polkadot imports +use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; +use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; +use xcm::latest::BodyId; + +use crate::xcm_config::{ + ForeignCreatorsSovereignAccountOf, LocalAndForeignAssetsMultiLocationMatcher, + TrustBackedAssetsPalletLocation, +}; +use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; + +impl_opaque_keys! { + pub struct SessionKeys { + pub aura: Aura, + } +} + +#[cfg(feature = "state-trie-version-1")] +#[sp_version::runtime_version] +pub const VERSION: RuntimeVersion = RuntimeVersion { + // Note: "statemine" is the legacy name for this chain. It has been renamed to + // "asset-hub-kusama". Many wallets/tools depend on the `spec_name`, so it remains "statemine" + // for the time being. Wallets/tools should update to treat "asset-hub-kusama" equally. + spec_name: create_runtime_str!("statemine"), + impl_name: create_runtime_str!("statemine"), + authoring_version: 1, + spec_version: 10000, + impl_version: 0, + apis: RUNTIME_API_VERSIONS, + transaction_version: 13, + state_version: 1, +}; + +#[cfg(not(feature = "state-trie-version-1"))] +#[sp_version::runtime_version] +pub const VERSION: RuntimeVersion = RuntimeVersion { + // Note: "statemine" is the legacy name for this change. It has been renamed to + // "asset-hub-kusama". Many wallets/tools depend on the `spec_name`, so it remains "statemine" + // for the time being. Wallets/tools should update to treat "asset-hub-kusama" equally. + spec_name: create_runtime_str!("statemine"), + impl_name: create_runtime_str!("statemine"), + authoring_version: 1, + spec_version: 10000, + impl_version: 0, + apis: RUNTIME_API_VERSIONS, + transaction_version: 13, + state_version: 0, +}; + +/// The version information used to identify this runtime when compiled natively. +#[cfg(feature = "std")] +pub fn native_version() -> NativeVersion { + NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } +} + +parameter_types! { + pub const Version: RuntimeVersion = VERSION; + pub RuntimeBlockLength: BlockLength = + BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() + .base_block(BlockExecutionWeight::get()) + .for_class(DispatchClass::all(), |weights| { + weights.base_extrinsic = ExtrinsicBaseWeight::get(); + }) + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Operational transactions have some extra reserved space, so that they + // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); + pub const SS58Prefix: u8 = 2; +} + +// Configure FRAME pallets to include in runtime. +impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = RuntimeBlockWeights; + type BlockLength = RuntimeBlockLength; + type AccountId = AccountId; + type RuntimeCall = RuntimeCall; + type Lookup = AccountIdLookup; + type Nonce = Nonce; + type Hash = Hash; + type Hashing = BlakeTwo256; + type Block = Block; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type BlockHashCount = BlockHashCount; + type DbWeight = RocksDbWeight; + type Version = Version; + type PalletInfo = PalletInfo; + type OnNewAccount = (); + type OnKilledAccount = (); + type AccountData = pallet_balances::AccountData; + type SystemWeightInfo = weights::frame_system::WeightInfo; + type SS58Prefix = SS58Prefix; + type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + +impl pallet_timestamp::Config for Runtime { + /// A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = Aura; + type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>; + type WeightInfo = weights::pallet_timestamp::WeightInfo; +} + +impl pallet_authorship::Config for Runtime { + type FindAuthor = pallet_session::FindAccountFromAuthorIndex; + type EventHandler = (CollatorSelection,); +} + +parameter_types! { + pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT; +} + +impl pallet_balances::Config for Runtime { + type MaxLocks = ConstU32<50>; + /// The type for recording an account's balance. + type Balance = Balance; + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = weights::pallet_balances::WeightInfo; + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; + type FreezeIdentifier = (); + // We allow each account to have holds on it from: + // - `NftFractionalization`: 1 + type MaxHolds = ConstU32<1>; + type MaxFreezes = ConstU32<0>; +} + +parameter_types! { + /// Relay Chain `TransactionByteFee` / 10 + pub const TransactionByteFee: Balance = MILLICENTS; +} + +impl pallet_transaction_payment::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type OnChargeTransaction = + pallet_transaction_payment::CurrencyAdapter>; + type WeightToFee = WeightToFee; + type LengthToFee = ConstantMultiplier; + type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; + type OperationalFeeMultiplier = ConstU8<5>; +} + +parameter_types! { + pub const AssetDeposit: Balance = UNITS / 10; // 1 / 10 UNITS deposit to create asset + pub const AssetAccountDeposit: Balance = deposit(1, 16); + pub const ApprovalDeposit: Balance = EXISTENTIAL_DEPOSIT; + pub const AssetsStringLimit: u32 = 50; + /// Key = 32 bytes, Value = 36 bytes (32+1+1+1+1) + // https://github.com/paritytech/substrate/blob/069917b/frame/assets/src/lib.rs#L257L271 + pub const MetadataDepositBase: Balance = deposit(1, 68); + pub const MetadataDepositPerByte: Balance = deposit(0, 1); +} + +/// We allow root to execute privileged asset operations. +pub type AssetsForceOrigin = EnsureRoot; + +// Called "Trust Backed" assets because these are generally registered by some account, and users of +// the asset assume it has some claimed backing. The pallet is called `Assets` in +// `construct_runtime` to avoid breaking changes on storage reads. +pub type TrustBackedAssetsInstance = pallet_assets::Instance1; +type TrustBackedAssetsCall = pallet_assets::Call; +impl pallet_assets::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type AssetId = AssetIdForTrustBackedAssets; + type AssetIdParameter = codec::Compact; + type Currency = Balances; + type CreateOrigin = AsEnsureOriginWithArg>; + type ForceOrigin = AssetsForceOrigin; + type AssetDeposit = AssetDeposit; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = AssetsStringLimit; + type Freezer = (); + type Extra = (); + type WeightInfo = weights::pallet_assets_local::WeightInfo; + type CallbackHandle = (); + type AssetAccountDeposit = AssetAccountDeposit; + type RemoveItemsLimit = frame_support::traits::ConstU32<1000>; + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); +} + +parameter_types! { + pub const AssetConversionPalletId: PalletId = PalletId(*b"py/ascon"); + pub const AllowMultiAssetPools: bool = false; + // should be non-zero if AllowMultiAssetPools is true, otherwise can be zero + pub const LiquidityWithdrawalFee: Permill = Permill::from_percent(0); +} + +ord_parameter_types! { + pub const AssetConversionOrigin: sp_runtime::AccountId32 = + AccountIdConversion::::into_account_truncating(&AssetConversionPalletId::get()); +} + +pub type PoolAssetsInstance = pallet_assets::Instance3; +impl pallet_assets::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type RemoveItemsLimit = ConstU32<1000>; + type AssetId = u32; + type AssetIdParameter = u32; + type Currency = Balances; + type CreateOrigin = + AsEnsureOriginWithArg>; + type ForceOrigin = AssetsForceOrigin; + // Deposits are zero because creation/admin is limited to Asset Conversion pallet. + type AssetDeposit = ConstU128<0>; + type AssetAccountDeposit = ConstU128<0>; + type MetadataDepositBase = ConstU128<0>; + type MetadataDepositPerByte = ConstU128<0>; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = ConstU32<50>; + type Freezer = (); + type Extra = (); + type WeightInfo = weights::pallet_assets_pool::WeightInfo; + type CallbackHandle = (); + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); +} + +impl pallet_asset_conversion::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type HigherPrecisionBalance = sp_core::U256; + type Currency = Balances; + type AssetBalance = Balance; + type AssetId = MultiLocation; + type Assets = LocalAndForeignAssets< + Assets, + AssetIdForTrustBackedAssetsConvert, + ForeignAssets, + >; + type PoolAssets = PoolAssets; + type PoolAssetId = u32; + type PoolSetupFee = ConstU128<0>; // Asset class deposit fees are sufficient to prevent spam + type PoolSetupFeeReceiver = AssetConversionOrigin; + // should be non-zero if `AllowMultiAssetPools` is true, otherwise can be zero. + type LiquidityWithdrawalFee = LiquidityWithdrawalFee; + type LPFee = ConstU32<3>; + type PalletId = AssetConversionPalletId; + type AllowMultiAssetPools = AllowMultiAssetPools; + type MaxSwapPathLength = ConstU32<4>; + type MultiAssetId = Box; + type MultiAssetIdConverter = + MultiLocationConverter; + type MintMinLiquidity = ConstU128<100>; + type WeightInfo = weights::pallet_asset_conversion::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = + crate::xcm_config::BenchmarkMultiLocationConverter>; +} + +parameter_types! { + // we just reuse the same deposits + pub const ForeignAssetsAssetDeposit: Balance = AssetDeposit::get(); + pub const ForeignAssetsAssetAccountDeposit: Balance = AssetAccountDeposit::get(); + pub const ForeignAssetsApprovalDeposit: Balance = ApprovalDeposit::get(); + pub const ForeignAssetsAssetsStringLimit: u32 = AssetsStringLimit::get(); + pub const ForeignAssetsMetadataDepositBase: Balance = MetadataDepositBase::get(); + pub const ForeignAssetsMetadataDepositPerByte: Balance = MetadataDepositPerByte::get(); +} + +/// Assets managed by some foreign location. Note: we do not declare a `ForeignAssetsCall` type, as +/// this type is used in proxy definitions. We assume that a foreign location would not want to set +/// an individual, local account as a proxy for the issuance of their assets. This issuance should +/// be managed by the foreign location's governance. +pub type ForeignAssetsInstance = pallet_assets::Instance2; +impl pallet_assets::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type AssetId = MultiLocationForAssetId; + type AssetIdParameter = MultiLocationForAssetId; + type Currency = Balances; + type CreateOrigin = ForeignCreators< + (FromSiblingParachain>,), + ForeignCreatorsSovereignAccountOf, + AccountId, + >; + type ForceOrigin = AssetsForceOrigin; + type AssetDeposit = ForeignAssetsAssetDeposit; + type MetadataDepositBase = ForeignAssetsMetadataDepositBase; + type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte; + type ApprovalDeposit = ForeignAssetsApprovalDeposit; + type StringLimit = ForeignAssetsAssetsStringLimit; + type Freezer = (); + type Extra = (); + type WeightInfo = weights::pallet_assets_foreign::WeightInfo; + type CallbackHandle = (); + type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit; + type RemoveItemsLimit = frame_support::traits::ConstU32<1000>; + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = xcm_config::XcmBenchmarkHelper; +} + +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); + // Additional storage item size of 32 bytes. + pub const DepositFactor: Balance = deposit(0, 32); + pub const MaxSignatories: u32 = 100; +} + +impl pallet_multisig::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type Currency = Balances; + type DepositBase = DepositBase; + type DepositFactor = DepositFactor; + type MaxSignatories = MaxSignatories; + type WeightInfo = weights::pallet_multisig::WeightInfo; +} + +impl pallet_utility::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type PalletsOrigin = OriginCaller; + type WeightInfo = weights::pallet_utility::WeightInfo; +} + +parameter_types! { + // One storage item; key size 32, value size 8; . + pub const ProxyDepositBase: Balance = deposit(1, 40); + // Additional storage item size of 33 bytes. + pub const ProxyDepositFactor: Balance = deposit(0, 33); + pub const MaxProxies: u16 = 32; + // One storage item; key size 32, value size 16 + pub const AnnouncementDepositBase: Balance = deposit(1, 48); + pub const AnnouncementDepositFactor: Balance = deposit(0, 66); + pub const MaxPending: u16 = 32; +} + +/// The type used to represent the kinds of proxying allowed. +#[derive( + Copy, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Encode, + Decode, + RuntimeDebug, + MaxEncodedLen, + scale_info::TypeInfo, +)] +pub enum ProxyType { + /// Fully permissioned proxy. Can execute any call on behalf of _proxied_. + Any, + /// Can execute any call that does not transfer funds or assets. + NonTransfer, + /// Proxy with the ability to reject time-delay proxy announcements. + CancelProxy, + /// Assets proxy. Can execute any call from `assets`, **including asset transfers**. + Assets, + /// Owner proxy. Can execute calls related to asset ownership. + AssetOwner, + /// Asset manager. Can execute calls related to asset management. + AssetManager, + /// Collator selection proxy. Can execute calls related to collator selection mechanism. + Collator, +} +impl Default for ProxyType { + fn default() -> Self { + Self::Any + } +} + +impl InstanceFilter for ProxyType { + fn filter(&self, c: &RuntimeCall) -> bool { + match self { + ProxyType::Any => true, + ProxyType::NonTransfer => !matches!( + c, + RuntimeCall::Balances { .. } | + RuntimeCall::Assets { .. } | + RuntimeCall::NftFractionalization { .. } | + RuntimeCall::Nfts { .. } | + RuntimeCall::Uniques { .. } + ), + ProxyType::CancelProxy => matches!( + c, + RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }) | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + ProxyType::Assets => { + matches!( + c, + RuntimeCall::Assets { .. } | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } | + RuntimeCall::NftFractionalization { .. } | + RuntimeCall::Nfts { .. } | RuntimeCall::Uniques { .. } + ) + }, + ProxyType::AssetOwner => matches!( + c, + RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::create { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::destroy { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::redeposit { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::transfer_ownership { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::set_team { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::set_collection_max_supply { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::lock_collection { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::create { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::destroy { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::transfer_ownership { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::set_team { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::set_metadata { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::set_attribute { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::set_collection_metadata { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::clear_metadata { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::clear_attribute { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::clear_collection_metadata { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::set_collection_max_supply { .. }) | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + ProxyType::AssetManager => matches!( + c, + RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::force_mint { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::update_mint_settings { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::mint_pre_signed { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::set_attributes_pre_signed { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::lock_item_transfer { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::unlock_item_transfer { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::lock_item_properties { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::set_metadata { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::clear_metadata { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::set_collection_metadata { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::clear_collection_metadata { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::mint { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::burn { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::freeze { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::thaw { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::freeze_collection { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::thaw_collection { .. }) | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + ProxyType::Collator => matches!( + c, + RuntimeCall::CollatorSelection { .. } | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + } + } + + fn is_superset(&self, o: &Self) -> bool { + match (self, o) { + (x, y) if x == y => true, + (ProxyType::Any, _) => true, + (_, ProxyType::Any) => false, + (ProxyType::Assets, ProxyType::AssetOwner) => true, + (ProxyType::Assets, ProxyType::AssetManager) => true, + (ProxyType::NonTransfer, ProxyType::Collator) => true, + _ => false, + } + } +} + +impl pallet_proxy::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type Currency = Balances; + type ProxyType = ProxyType; + type ProxyDepositBase = ProxyDepositBase; + type ProxyDepositFactor = ProxyDepositFactor; + type MaxProxies = MaxProxies; + type WeightInfo = weights::pallet_proxy::WeightInfo; + type MaxPending = MaxPending; + type CallHasher = BlakeTwo256; + type AnnouncementDepositBase = AnnouncementDepositBase; + type AnnouncementDepositFactor = AnnouncementDepositFactor; +} + +parameter_types! { + pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); + pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); +} + +impl cumulus_pallet_parachain_system::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type OnSystemEvent = (); + type SelfParaId = parachain_info::Pallet; + type DmpQueue = frame_support::traits::EnqueueWithOrigin; + type ReservedDmpWeight = ReservedDmpWeight; + type OutboundXcmpMessageSource = XcmpQueue; + type XcmpMessageHandler = XcmpQueue; + type ReservedXcmpWeight = ReservedXcmpWeight; + type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases; + type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook< + Runtime, + RELAY_CHAIN_SLOT_DURATION_MILLIS, + BLOCK_PROCESSING_VELOCITY, + UNINCLUDED_SEGMENT_CAPACITY, + >; +} + +impl parachain_info::Config for Runtime {} + +parameter_types! { + pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block; +} + +impl pallet_message_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type WeightInfo = weights::pallet_message_queue::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor< + cumulus_primitives_core::AggregateMessageOrigin, + >; + #[cfg(not(feature = "runtime-benchmarks"))] + type MessageProcessor = xcm_builder::ProcessXcmMessage< + AggregateMessageOrigin, + xcm_executor::XcmExecutor, + RuntimeCall, + >; + type Size = u32; + // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin: + type QueueChangeHandler = NarrowOriginToSibling; + type QueuePausedQuery = NarrowOriginToSibling; + type HeapSize = sp_core::ConstU32<{ 64 * 1024 }>; + type MaxStale = sp_core::ConstU32<8>; + type ServiceWeight = MessageQueueServiceWeight; +} + +impl cumulus_pallet_aura_ext::Config for Runtime {} + +parameter_types! { + // Fellows pluralistic body. + pub const FellowsBodyId: BodyId = BodyId::Technical; +} + +impl cumulus_pallet_xcmp_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type ChannelInfo = ParachainSystem; + type VersionWrapper = PolkadotXcm; + // Enqueue XCMP messages from siblings for later processing. + type XcmpQueue = TransformOrigin; + type MaxInboundSuspended = sp_core::ConstU32<1_000>; + type ControllerOrigin = EitherOfDiverse< + EnsureRoot, + EnsureXcm>, + >; + type ControllerOriginConverter = xcm_config::XcmOriginToTransactDispatchOrigin; + type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; + type PriceForSiblingDelivery = NoPriceForMessageDelivery; +} + +parameter_types! { + pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent; +} + +impl cumulus_pallet_dmp_queue::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_dmp_queue::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type DmpSink = frame_support::traits::EnqueueWithOrigin; +} + +parameter_types! { + pub const Period: u32 = 6 * HOURS; + pub const Offset: u32 = 0; +} + +impl pallet_session::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type ValidatorId = ::AccountId; + // we don't have stash and controller, thus we don't need the convert as well. + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ShouldEndSession = pallet_session::PeriodicSessions; + type NextSessionRotation = pallet_session::PeriodicSessions; + type SessionManager = CollatorSelection; + // Essentially just Aura, but let's be pedantic. + type SessionHandler = ::KeyTypeIdProviders; + type Keys = SessionKeys; + type WeightInfo = weights::pallet_session::WeightInfo; +} + +impl pallet_aura::Config for Runtime { + type AuthorityId = AuraId; + type DisabledValidators = (); + type MaxAuthorities = ConstU32<100_000>; + type AllowMultipleBlocksPerSlot = ConstBool; + #[cfg(feature = "experimental")] + type SlotDuration = pallet_aura::MinimumPeriodTimesTwo; +} + +parameter_types! { + pub const PotId: PalletId = PalletId(*b"PotStake"); + pub const SessionLength: BlockNumber = 6 * HOURS; + // StakingAdmin pluralistic body. + pub const StakingAdminBodyId: BodyId = BodyId::Defense; +} + +/// We allow root and the `StakingAdmin` to execute privileged collator selection operations. +pub type CollatorSelectionUpdateOrigin = EitherOfDiverse< + EnsureRoot, + EnsureXcm>, +>; + +impl pallet_collator_selection::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type UpdateOrigin = CollatorSelectionUpdateOrigin; + type PotId = PotId; + type MaxCandidates = ConstU32<100>; + type MinEligibleCollators = ConstU32<4>; + type MaxInvulnerables = ConstU32<20>; + // should be a multiple of session or things will get inconsistent + type KickThreshold = Period; + type ValidatorId = ::AccountId; + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ValidatorRegistration = Session; + type WeightInfo = weights::pallet_collator_selection::WeightInfo; +} + +impl pallet_asset_conversion_tx_payment::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Fungibles = LocalAndForeignAssets< + Assets, + AssetIdForTrustBackedAssetsConvert, + ForeignAssets, + >; + type OnChargeAssetTransaction = AssetConversionAdapter; +} + +parameter_types! { + pub const UniquesCollectionDeposit: Balance = UNITS / 10; // 1 / 10 UNIT deposit to create a collection + pub const UniquesItemDeposit: Balance = UNITS / 1_000; // 1 / 1000 UNIT deposit to mint an item + pub const UniquesMetadataDepositBase: Balance = deposit(1, 129); + pub const UniquesAttributeDepositBase: Balance = deposit(1, 0); + pub const UniquesDepositPerByte: Balance = deposit(0, 1); +} + +impl pallet_uniques::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type CollectionId = u32; + type ItemId = u32; + type Currency = Balances; + type ForceOrigin = AssetsForceOrigin; + type CollectionDeposit = UniquesCollectionDeposit; + type ItemDeposit = UniquesItemDeposit; + type MetadataDepositBase = UniquesMetadataDepositBase; + type AttributeDepositBase = UniquesAttributeDepositBase; + type DepositPerByte = UniquesDepositPerByte; + type StringLimit = ConstU32<128>; + type KeyLimit = ConstU32<32>; + type ValueLimit = ConstU32<64>; + type WeightInfo = weights::pallet_uniques::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type Helper = (); + type CreateOrigin = AsEnsureOriginWithArg>; + type Locker = (); +} + +parameter_types! { + pub const NftFractionalizationPalletId: PalletId = PalletId(*b"fraction"); + pub NewAssetSymbol: BoundedVec = (*b"FRAC").to_vec().try_into().unwrap(); + pub NewAssetName: BoundedVec = (*b"Frac").to_vec().try_into().unwrap(); +} + +impl pallet_nft_fractionalization::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Deposit = AssetDeposit; + type Currency = Balances; + type NewAssetSymbol = NewAssetSymbol; + type NewAssetName = NewAssetName; + type StringLimit = AssetsStringLimit; + type NftCollectionId = ::CollectionId; + type NftId = ::ItemId; + type AssetBalance = ::Balance; + type AssetId = >::AssetId; + type Assets = Assets; + type Nfts = Nfts; + type PalletId = NftFractionalizationPalletId; + type WeightInfo = pallet_nft_fractionalization::weights::SubstrateWeight; + type RuntimeHoldReason = RuntimeHoldReason; + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); +} + +parameter_types! { + pub NftsPalletFeatures: PalletFeatures = PalletFeatures::all_enabled(); + pub const NftsMaxDeadlineDuration: BlockNumber = 12 * 30 * DAYS; + // re-use the Uniques deposits + pub const NftsCollectionDeposit: Balance = UniquesCollectionDeposit::get(); + pub const NftsItemDeposit: Balance = UniquesItemDeposit::get(); + pub const NftsMetadataDepositBase: Balance = UniquesMetadataDepositBase::get(); + pub const NftsAttributeDepositBase: Balance = UniquesAttributeDepositBase::get(); + pub const NftsDepositPerByte: Balance = UniquesDepositPerByte::get(); +} + +impl pallet_nfts::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type CollectionId = u32; + type ItemId = u32; + type Currency = Balances; + type CreateOrigin = AsEnsureOriginWithArg>; + type ForceOrigin = AssetsForceOrigin; + type Locker = (); + type CollectionDeposit = NftsCollectionDeposit; + type ItemDeposit = NftsItemDeposit; + type MetadataDepositBase = NftsMetadataDepositBase; + type AttributeDepositBase = NftsAttributeDepositBase; + type DepositPerByte = NftsDepositPerByte; + type StringLimit = ConstU32<256>; + type KeyLimit = ConstU32<64>; + type ValueLimit = ConstU32<256>; + type ApprovalsLimit = ConstU32<20>; + type ItemAttributesApprovalsLimit = ConstU32<30>; + type MaxTips = ConstU32<10>; + type MaxDeadlineDuration = NftsMaxDeadlineDuration; + type MaxAttributesPerCall = ConstU32<10>; + type Features = NftsPalletFeatures; + type OffchainSignature = Signature; + type OffchainPublic = ::Signer; + type WeightInfo = weights::pallet_nfts::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type Helper = (); +} + +// Create the runtime by composing the FRAME pallets that were previously configured. +construct_runtime!( + pub enum Runtime + { + // System support stuff. + System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, + ParachainSystem: cumulus_pallet_parachain_system::{ + Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned, + } = 1, + // RandomnessCollectiveFlip = 2 removed + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 3, + ParachainInfo: parachain_info::{Pallet, Storage, Config} = 4, + + // Monetary stuff. + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, + TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 11, + AssetTxPayment: pallet_asset_conversion_tx_payment::{Pallet, Event} = 13, + + // Collator support. the order of these 5 are important and shall not change. + Authorship: pallet_authorship::{Pallet, Storage} = 20, + CollatorSelection: pallet_collator_selection::{Pallet, Call, Storage, Event, Config} = 21, + Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, + Aura: pallet_aura::{Pallet, Storage, Config} = 23, + AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config} = 24, + + // XCM helpers. + XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, + PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 31, + CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, + // Temporary to migrate the remaining DMP messages: + DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, + MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event} = 34, + + // Handy utilities. + Utility: pallet_utility::{Pallet, Call, Event} = 40, + Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 41, + Proxy: pallet_proxy::{Pallet, Call, Storage, Event} = 42, + + // The main stage. + Assets: pallet_assets::::{Pallet, Call, Storage, Event} = 50, + Uniques: pallet_uniques::{Pallet, Call, Storage, Event} = 51, + Nfts: pallet_nfts::{Pallet, Call, Storage, Event} = 52, + ForeignAssets: pallet_assets::::{Pallet, Call, Storage, Event} = 53, + NftFractionalization: pallet_nft_fractionalization::{Pallet, Call, Storage, Event, HoldReason} = 54, + + PoolAssets: pallet_assets::::{Pallet, Call, Storage, Event} = 55, + AssetConversion: pallet_asset_conversion::{Pallet, Call, Storage, Event} = 56, + + #[cfg(feature = "state-trie-version-1")] + StateTrieMigration: pallet_state_trie_migration = 70, + } +); + +/// The address format for describing accounts. +pub type Address = sp_runtime::MultiAddress; +/// Block type as expected by this runtime. +pub type Block = generic::Block; +/// A Block signed with a Justification +pub type SignedBlock = generic::SignedBlock; +/// BlockId type as expected by this runtime. +pub type BlockId = generic::BlockId; +/// The extension to the basic transaction logic. +pub type TxExtension = ( + frame_system::CheckNonZeroSender, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_asset_conversion_tx_payment::ChargeAssetTxPayment, +); +/// Unchecked extrinsic type as expected by this runtime. +pub type UncheckedExtrinsic = + generic::UncheckedExtrinsic; +/// Migrations to apply on runtime upgrade. +pub type Migrations = (pallet_collator_selection::migration::v1::MigrateToV1,); + +/// Executive: handles dispatch to the various modules. +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + Migrations, +>; + +#[cfg(feature = "runtime-benchmarks")] +mod benches { + frame_benchmarking::define_benchmarks!( + [frame_system, SystemBench::] + [pallet_assets, Local] + [pallet_assets, Foreign] + [pallet_assets, Pool] + [pallet_asset_conversion, AssetConversion] + [pallet_balances, Balances] + [pallet_message_queue, MessageQueue] + [pallet_multisig, Multisig] + [pallet_nft_fractionalization, NftFractionalization] + [pallet_nfts, Nfts] + [pallet_proxy, Proxy] + [pallet_session, SessionBench::] + [pallet_uniques, Uniques] + [pallet_utility, Utility] + [pallet_timestamp, Timestamp] + [pallet_collator_selection, CollatorSelection] + [cumulus_pallet_parachain_system, ParachainSystem] + [cumulus_pallet_xcmp_queue, XcmpQueue] + [cumulus_pallet_dmp_queue, DmpQueue] + // XCM + [pallet_xcm, PalletXcmExtrinsicsBenchmark::] + // NOTE: Make sure you point to the individual modules below. + [pallet_xcm_benchmarks::fungible, XcmBalances] + [pallet_xcm_benchmarks::generic, XcmGeneric] + ); +} + +impl_runtime_apis! { + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + + fn authorities() -> Vec { + Aura::authorities().into_inner() + } + } + + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + + fn metadata_at_version(version: u32) -> Option { + Runtime::metadata_at_version(version) + } + + fn metadata_versions() -> sp_std::vec::Vec { + Runtime::metadata_versions() + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { + System::account_nonce(account) + } + } + + impl pallet_asset_conversion::AssetConversionApi< + Block, + Balance, + u128, + Box, + > for Runtime + { + fn quote_price_exact_tokens_for_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { + AssetConversion::quote_price_exact_tokens_for_tokens(asset1, asset2, amount, include_fee) + } + fn quote_price_tokens_for_exact_tokens(asset1: Box, asset2: Box, amount: u128, include_fee: bool) -> Option { + AssetConversion::quote_price_tokens_for_exact_tokens(asset1, asset2, amount, include_fee) + } + fn get_reserves(asset1: Box, asset2: Box) -> Option<(Balance, Balance)> { + AssetConversion::get_reserves(&asset1, &asset2).ok() + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi + for Runtime + { + fn query_call_info( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::RuntimeDispatchInfo { + TransactionPayment::query_call_info(call, len) + } + fn query_call_fee_details( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_call_fee_details(call, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl assets_common::runtime_api::FungiblesApi< + Block, + AccountId, + > for Runtime + { + fn query_account_balances(account: AccountId) -> Result { + use assets_common::fungible_conversion::{convert, convert_balance}; + Ok([ + // collect pallet_balance + { + let balance = Balances::free_balance(account.clone()); + if balance > 0 { + vec![convert_balance::(balance)?] + } else { + vec![] + } + }, + // collect pallet_assets (TrustBackedAssets) + convert::<_, _, _, _, TrustBackedAssetsConvertedConcreteId>( + Assets::account_balances(account.clone()) + .iter() + .filter(|(_, balance)| balance > &0) + )?, + // collect pallet_assets (ForeignAssets) + convert::<_, _, _, _, ForeignAssetsConvertedConcreteId>( + ForeignAssets::account_balances(account.clone()) + .iter() + .filter(|(_, balance)| balance > &0) + )?, + // collect pallet_assets (PoolAssets) + convert::<_, _, _, _, PoolAssetsConvertedConcreteId>( + PoolAssets::account_balances(account) + .iter() + .filter(|(_, balance)| balance > &0) + )?, + // collect ... e.g. other tokens + ].concat().into()) + } + } + + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { + ParachainSystem::collect_collation_info(header) + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { + let weight = Executive::try_runtime_upgrade(checks).unwrap(); + (weight, RuntimeBlockWeights::get().max_block) + } + + fn execute_block( + block: Block, + state_root_check: bool, + signature_check: bool, + select: frame_try_runtime::TryStateSelect, + ) -> Weight { + // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to + // have a backtrace here. + Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap() + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; + + // This is defined once again in dispatch_benchmark, because list_benchmarks! + // and add_benchmarks! are macros exported by define_benchmarks! macros and those types + // are referenced in that call. + type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::; + type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::; + + // Benchmark files generated for `Assets/ForeignAssets` instances are by default + // `pallet_assets_assets.rs / pallet_assets_foreign_assets`, which is not really nice, + // so with this redefinition we can change names to nicer: + // `pallet_assets_local.rs / pallet_assets_foreign.rs`. + type Local = pallet_assets::Pallet::; + type Foreign = pallet_assets::Pallet::; + type Pool = pallet_assets::Pallet::; + + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsWithSystem::storage_info(); + (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; + use sp_storage::TrackedStorageKey; + + use frame_system_benchmarking::Pallet as SystemBench; + impl frame_system_benchmarking::Config for Runtime { + fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); + Ok(()) + } + + fn verify_set_code() { + System::assert_last_event(cumulus_pallet_parachain_system::Event::::ValidationFunctionStored.into()); + } + } + + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + impl cumulus_pallet_session_benchmarking::Config for Runtime {} + + use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; + impl pallet_xcm::benchmarking::Config for Runtime { + fn reachable_dest() -> Option { + Some(Parent.into()) + } + + fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + // Relay/native token can be teleported between AH and Relay. + Some(( + MultiAsset { + fun: Fungible(EXISTENTIAL_DEPOSIT), + id: Concrete(Parent.into()) + }, + Parent.into(), + )) + } + + fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + // AH can reserve transfer native token to some random parachain. + let random_para_id = 43211234; + ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( + random_para_id.into() + ); + Some(( + MultiAsset { + fun: Fungible(EXISTENTIAL_DEPOSIT), + id: Concrete(Parent.into()) + }, + ParentThen(Parachain(random_para_id).into()).into(), + )) + } + } + + use xcm::latest::prelude::*; + use xcm_config::{KsmLocation, MaxAssetsIntoHolding}; + use pallet_xcm_benchmarks::asset_instance_from; + + parameter_types! { + pub ExistentialDepositMultiAsset: Option = Some(( + KsmLocation::get(), + ExistentialDeposit::get() + ).into()); + } + + impl pallet_xcm_benchmarks::Config for Runtime { + type XcmConfig = xcm_config::XcmConfig; + type AccountIdConverter = xcm_config::LocationToAccountId; + type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< + xcm_config::XcmConfig, + ExistentialDepositMultiAsset, + xcm_config::PriceForParentDelivery, + >; + fn valid_destination() -> Result { + Ok(KsmLocation::get()) + } + fn worst_case_holding(depositable_count: u32) -> MultiAssets { + // A mix of fungible, non-fungible, and concrete assets. + let holding_non_fungibles = MaxAssetsIntoHolding::get() / 2 - depositable_count; + let holding_fungibles = holding_non_fungibles.saturating_sub(1); + let fungibles_amount: u128 = 100; + let mut assets = (0..holding_fungibles) + .map(|i| { + MultiAsset { + id: Concrete(GeneralIndex(i as u128).into()), + fun: Fungible(fungibles_amount * i as u128), + } + }) + .chain(core::iter::once(MultiAsset { id: Concrete(Here.into()), fun: Fungible(u128::MAX) })) + .chain((0..holding_non_fungibles).map(|i| MultiAsset { + id: Concrete(GeneralIndex(i as u128).into()), + fun: NonFungible(asset_instance_from(i)), + })) + .collect::>(); + + assets.push(MultiAsset { + id: Concrete(KsmLocation::get()), + fun: Fungible(1_000_000 * UNITS), + }); + assets.into() + } + } + + parameter_types! { + pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + KsmLocation::get(), + MultiAsset { fun: Fungible(UNITS), id: Concrete(KsmLocation::get()) }, + )); + pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; + pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None; + } + + impl pallet_xcm_benchmarks::fungible::Config for Runtime { + type TransactAsset = Balances; + + type CheckedAccount = CheckedAccount; + type TrustedTeleporter = TrustedTeleporter; + type TrustedReserve = TrustedReserve; + + fn get_multi_asset() -> MultiAsset { + MultiAsset { + id: Concrete(KsmLocation::get()), + fun: Fungible(UNITS), + } + } + } + + impl pallet_xcm_benchmarks::generic::Config for Runtime { + type TransactAsset = Balances; + type RuntimeCall = RuntimeCall; + + fn worst_case_response() -> (u64, Response) { + (0u64, Response::Version(Default::default())) + } + + fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + Ok((KsmLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) + } + + fn subscribe_origin() -> Result { + Ok(KsmLocation::get()) + } + + fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + let origin = KsmLocation::get(); + let assets: MultiAssets = (Concrete(KsmLocation::get()), 1_000 * UNITS).into(); + let ticket = MultiLocation { parents: 0, interior: Here }; + Ok((origin, ticket, assets)) + } + + fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn export_message_origin_and_destination( + ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + Err(BenchmarkError::Skip) + } + } + + type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::; + type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::; + + type Local = pallet_assets::Pallet::; + type Foreign = pallet_assets::Pallet::; + type Pool = pallet_assets::Pallet::; + + let whitelist: Vec = vec![ + // Block Number + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), + // Total Issuance + hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), + // Execution Phase + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), + // Event Count + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), + // System Events + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), + //TODO: use from relay_well_known_keys::ACTIVE_CONFIG + hex_literal::hex!("06de3d8a54d27e44a9d5ce189618f22db4b49d95320d9021994c850f25b8e385").to_vec().into(), + ]; + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + add_benchmarks!(params, batches); + + Ok(batches) + } + } + + impl sp_genesis_builder::GenesisBuilder for Runtime { + fn create_default_config() -> Vec { + create_default_config::() + } + + fn build_config(config: Vec) -> sp_genesis_builder::Result { + build_config::(config) + } + } +} + +cumulus_pallet_parachain_system::register_validate_block! { + Runtime = Runtime, + BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, +} + +#[cfg(feature = "state-trie-version-1")] +parameter_types! { + // The deposit configuration for the singed migration. Specially if you want to allow any signed account to do the migration (see `SignedFilter`, these deposits should be high) + pub const MigrationSignedDepositPerItem: Balance = CENTS; + pub const MigrationSignedDepositBase: Balance = 2_000 * CENTS; + pub const MigrationMaxKeyLen: u32 = 512; +} + +#[cfg(feature = "state-trie-version-1")] +impl pallet_state_trie_migration::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type SignedDepositPerItem = MigrationSignedDepositPerItem; + type SignedDepositBase = MigrationSignedDepositBase; + // An origin that can control the whole pallet: should be Root, or a part of your council. + type ControlOrigin = frame_system::EnsureSignedBy; + // specific account for the migration, can trigger the signed migrations. + type SignedFilter = frame_system::EnsureSignedBy; + + // Replace this with weight based on your runtime. + type WeightInfo = pallet_state_trie_migration::weights::SubstrateWeight; + + type MaxKeyLen = MigrationMaxKeyLen; +} + +#[cfg(feature = "state-trie-version-1")] +frame_support::ord_parameter_types! { + pub const MigController: AccountId = AccountId::from(hex_literal::hex!("8458ed39dc4b6f6c7255f7bc42be50c2967db126357c999d44e12ca7ac80dc52")); + pub const RootMigController: AccountId = AccountId::from(hex_literal::hex!("8458ed39dc4b6f6c7255f7bc42be50c2967db126357c999d44e12ca7ac80dc52")); +} + +#[cfg(feature = "state-trie-version-1")] +#[test] +fn ensure_key_ss58() { + use frame_support::traits::SortedMembers; + use sp_core::crypto::Ss58Codec; + let acc = + AccountId::from_ss58check("5F4EbSkZz18X36xhbsjvDNs6NuZ82HyYtq5UiJ1h9SBHJXZD").unwrap(); + //panic!("{:x?}", acc); + assert_eq!(acc, MigController::sorted_members()[0]); + let acc = + AccountId::from_ss58check("5F4EbSkZz18X36xhbsjvDNs6NuZ82HyYtq5UiJ1h9SBHJXZD").unwrap(); + assert_eq!(acc, RootMigController::sorted_members()[0]); + //panic!("{:x?}", acc); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{CENTS, MILLICENTS}; + use parachains_common::kusama::fee; + use sp_runtime::traits::Zero; + use sp_weights::WeightToFee; + + /// We can fit at least 1000 transfers in a block. + #[test] + fn sane_block_weight() { + use pallet_balances::WeightInfo; + let block = RuntimeBlockWeights::get().max_block; + let base = RuntimeBlockWeights::get().get(DispatchClass::Normal).base_extrinsic; + let transfer = + base + weights::pallet_balances::WeightInfo::::transfer_allow_death(); + + let fit = block.checked_div_per_component(&transfer).unwrap_or_default(); + assert!(fit >= 1000, "{} should be at least 1000", fit); + } + + /// The fee for one transfer is at most 1 CENT. + #[test] + fn sane_transfer_fee() { + use pallet_balances::WeightInfo; + let base = RuntimeBlockWeights::get().get(DispatchClass::Normal).base_extrinsic; + let transfer = + base + weights::pallet_balances::WeightInfo::::transfer_allow_death(); + + let fee: Balance = fee::WeightToFee::weight_to_fee(&transfer); + assert!(fee <= CENTS, "{} MILLICENTS should be at most 1000", fee / MILLICENTS); + } + + /// Weight is being charged for both dimensions. + #[test] + fn weight_charged_for_both_components() { + let fee: Balance = fee::WeightToFee::weight_to_fee(&Weight::from_parts(10_000, 0)); + assert!(!fee.is_zero(), "Charges for ref time"); + + let fee: Balance = fee::WeightToFee::weight_to_fee(&Weight::from_parts(0, 10_000)); + assert_eq!(fee, CENTS, "10kb maps to CENT"); + } + + /// Filling up a block by proof size is at most 30 times more expensive than ref time. + /// + /// This is just a sanity check. + #[test] + fn full_block_fee_ratio() { + let block = RuntimeBlockWeights::get().max_block; + let time_fee: Balance = + fee::WeightToFee::weight_to_fee(&Weight::from_parts(block.ref_time(), 0)); + let proof_fee: Balance = + fee::WeightToFee::weight_to_fee(&Weight::from_parts(0, block.proof_size())); + + let proof_o_time = proof_fee.checked_div(time_fee).unwrap_or_default(); + assert!(proof_o_time <= 30, "{} should be at most 30", proof_o_time); + let time_o_proof = time_fee.checked_div(proof_fee).unwrap_or_default(); + assert!(time_o_proof <= 30, "{} should be at most 30", time_o_proof); + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/block_weights.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/block_weights.rs new file mode 100644 index 00000000000..e7fdb2aae2a --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/block_weights.rs @@ -0,0 +1,53 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; + + parameter_types! { + /// Importing a block with 0 Extrinsics. + pub const BlockExecutionWeight: Weight = + Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); + } + + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; + + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::BlockExecutionWeight::get(); + + // At least 100 µs. + assert!( + w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, + "Weight should be at least 100 µs." + ); + // At most 50 ms. + assert!( + w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, + "Weight should be at most 50 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_dmp_queue.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_dmp_queue.rs new file mode 100644 index 00000000000..cc41dcd6cbb --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_dmp_queue.rs @@ -0,0 +1,131 @@ +// 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 . + +//! Autogenerated weights for `cumulus_pallet_dmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-10-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=cumulus_pallet_dmp_queue +// --chain=asset-hub-kusama-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_dmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_dmp_queue::WeightInfo for WeightInfo { + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65696` + // Estimated: `69161` + // Minimum execution time: 124_651_000 picoseconds. + Weight::from_parts(127_857_000, 0) + .saturating_add(Weight::from_parts(0, 69161)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65659` + // Estimated: `69124` + // Minimum execution time: 65_684_000 picoseconds. + Weight::from_parts(68_039_000, 0) + .saturating_add(Weight::from_parts(0, 69124)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_overweight_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65726` + // Estimated: `69191` + // Minimum execution time: 117_657_000 picoseconds. + Weight::from_parts(122_035_000, 0) + .saturating_add(Weight::from_parts(0, 69191)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + fn on_idle_overweight_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65689` + // Estimated: `69154` + // Minimum execution time: 59_799_000 picoseconds. + Weight::from_parts(61_354_000, 0) + .saturating_add(Weight::from_parts(0, 69154)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_parachain_system.rs new file mode 100644 index 00000000000..f787aa32701 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_parachain_system.rs @@ -0,0 +1,80 @@ +// 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. + +//! Autogenerated weights for `cumulus_pallet_parachain_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-03-28, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `i9`, CPU: `13th Gen Intel(R) Core(TM) i9-13900K` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --chain +// statemint-dev +// --pallet +// cumulus_pallet_parachain_system +// --extrinsic +// * +// --execution +// wasm +// --wasm-execution +// compiled +// --output +// parachains/runtimes/assets/statemint/src/weights +// --steps +// 50 +// --repeat +// 20 + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_parachain_system`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_parachain_system::WeightInfo for WeightInfo { + /// Storage: ParachainSystem LastDmqMqcHead (r:1 w:1) + /// Proof Skipped: ParachainSystem LastDmqMqcHead (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem ReservedDmpWeightOverride (r:1 w:0) + /// Proof Skipped: ParachainSystem ReservedDmpWeightOverride (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: ParachainSystem ProcessedDownwardMessages (r:0 w:1) + /// Proof Skipped: ParachainSystem ProcessedDownwardMessages (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: MessageQueue Pages (r:0 w:16) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + /// The range of component `n` is `[0, 1000]`. + fn enqueue_inbound_downward_messages(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `12` + // Estimated: `8013` + // Minimum execution time: 1_660_000 picoseconds. + Weight::from_parts(1_720_000, 0) + .saturating_add(Weight::from_parts(0, 8013)) + // Standard Error: 28_418 + .saturating_add(Weight::from_parts(24_636_963, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_xcmp_queue.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_xcmp_queue.rs new file mode 100644 index 00000000000..e394e8b837a --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_xcmp_queue.rs @@ -0,0 +1,148 @@ +// 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. + +//! Autogenerated weights for `cumulus_pallet_xcmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-09-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `Olivers-MacBook-Pro.local`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --pallet +// cumulus-pallet-xcmp-queue +// --chain +// asset-hub-kusama-dev +// --output +// cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/cumulus_pallet_xcmp_queue.rs +// --extrinsic +// + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_xcmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_xcmp_queue::WeightInfo for WeightInfo { + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:1) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn set_config_with_u32() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `1561` + // Minimum execution time: 6_000_000 picoseconds. + Weight::from_parts(6_000_000, 0) + .saturating_add(Weight::from_parts(0, 1561)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:0) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn enqueue_xcmp_message() -> Weight { + // Proof Size summary in bytes: + // Measured: `118` + // Estimated: `3517` + // Minimum execution time: 15_000_000 picoseconds. + Weight::from_parts(16_000_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn suspend_channel() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `1561` + // Minimum execution time: 3_000_000 picoseconds. + Weight::from_parts(3_000_000, 0) + .saturating_add(Weight::from_parts(0, 1561)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn resume_channel() -> Weight { + // Proof Size summary in bytes: + // Measured: `111` + // Estimated: `1596` + // Minimum execution time: 4_000_000 picoseconds. + Weight::from_parts(5_000_000, 0) + .saturating_add(Weight::from_parts(0, 1596)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn take_first_concatenated_xcm() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 44_000_000 picoseconds. + Weight::from_parts(45_000_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Storage: `XcmpQueue::InboundXcmpMessages` (r:1 w:1) + /// Proof: `XcmpQueue::InboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:0) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65747` + // Estimated: `69212` + // Minimum execution time: 62_000_000 picoseconds. + Weight::from_parts(66_000_000, 0) + .saturating_add(Weight::from_parts(0, 69212)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65710` + // Estimated: `69175` + // Minimum execution time: 42_000_000 picoseconds. + Weight::from_parts(43_000_000, 0) + .saturating_add(Weight::from_parts(0, 69175)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/extrinsic_weights.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/extrinsic_weights.rs new file mode 100644 index 00000000000..1a4adb968bb --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/extrinsic_weights.rs @@ -0,0 +1,53 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; + + parameter_types! { + /// Executing a NO-OP `System::remarks` Extrinsic. + pub const ExtrinsicBaseWeight: Weight = + Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); + } + + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; + + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::ExtrinsicBaseWeight::get(); + + // At least 10 µs. + assert!( + w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, + "Weight should be at least 10 µs." + ); + // At most 1 ms. + assert!( + w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/frame_system.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/frame_system.rs new file mode 100644 index 00000000000..6304051e6cb --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/frame_system.rs @@ -0,0 +1,154 @@ +// 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. + +//! Autogenerated weights for `frame_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=frame_system +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `frame_system`. +pub struct WeightInfo(PhantomData); +impl frame_system::WeightInfo for WeightInfo { + /// The range of component `b` is `[0, 3932160]`. + fn remark(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_106_000 picoseconds. + Weight::from_parts(1_884_213, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 0 + .saturating_add(Weight::from_parts(388, 0).saturating_mul(b.into())) + } + /// The range of component `b` is `[0, 3932160]`. + fn remark_with_event(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_528_000 picoseconds. + Weight::from_parts(27_081_927, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 7 + .saturating_add(Weight::from_parts(1_730, 0).saturating_mul(b.into())) + } + /// Storage: `System::Digest` (r:1 w:1) + /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) + /// Proof: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) + fn set_heap_pages() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `1485` + // Minimum execution time: 3_882_000 picoseconds. + Weight::from_parts(4_149_000, 0) + .saturating_add(Weight::from_parts(0, 1485)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ParachainSystem::ValidationData` (r:1 w:0) + /// Proof: `ParachainSystem::ValidationData` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpgradeRestrictionSignal` (r:1 w:0) + /// Proof: `ParachainSystem::UpgradeRestrictionSignal` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingValidationCode` (r:1 w:1) + /// Proof: `ParachainSystem::PendingValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::NewValidationCode` (r:0 w:1) + /// Proof: `ParachainSystem::NewValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::DidSetValidationCode` (r:0 w:1) + /// Proof: `ParachainSystem::DidSetValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn set_code() -> Weight { + // Proof Size summary in bytes: + // Measured: `119` + // Estimated: `1604` + // Minimum execution time: 103_389_161_000 picoseconds. + Weight::from_parts(106_870_091_000, 0) + .saturating_add(Weight::from_parts(0, 1604)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `i` is `[0, 1000]`. + fn set_storage(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_236_000 picoseconds. + Weight::from_parts(2_302_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 2_045 + .saturating_add(Weight::from_parts(763_456, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `i` is `[0, 1000]`. + fn kill_storage(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_175_000 picoseconds. + Weight::from_parts(2_238_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_040 + .saturating_add(Weight::from_parts(571_397, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `p` is `[0, 1000]`. + fn kill_prefix(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `84 + p * (69 ±0)` + // Estimated: `80 + p * (70 ±0)` + // Minimum execution time: 3_843_000 picoseconds. + Weight::from_parts(3_947_000, 0) + .saturating_add(Weight::from_parts(0, 80)) + // Standard Error: 2_188 + .saturating_add(Weight::from_parts(1_212_360, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) + .saturating_add(Weight::from_parts(0, 70).saturating_mul(p.into())) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/mod.rs new file mode 100644 index 00000000000..f04081a84fb --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/mod.rs @@ -0,0 +1,45 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod block_weights; +pub mod cumulus_pallet_dmp_queue; +pub mod cumulus_pallet_parachain_system; +pub mod cumulus_pallet_xcmp_queue; +pub mod extrinsic_weights; +pub mod frame_system; +pub mod pallet_asset_conversion; +pub mod pallet_assets_foreign; +pub mod pallet_assets_local; +pub mod pallet_assets_pool; +pub mod pallet_balances; +pub mod pallet_collator_selection; +pub mod pallet_message_queue; +pub mod pallet_multisig; +pub mod pallet_nft_fractionalization; +pub mod pallet_nfts; +pub mod pallet_proxy; +pub mod pallet_session; +pub mod pallet_timestamp; +pub mod pallet_uniques; +pub mod pallet_utility; +pub mod pallet_xcm; +pub mod paritydb_weights; +pub mod rocksdb_weights; +pub mod xcm; + +pub use block_weights::constants::BlockExecutionWeight; +pub use extrinsic_weights::constants::ExtrinsicBaseWeight; +pub use paritydb_weights::constants::ParityDbWeight; +pub use rocksdb_weights::constants::RocksDbWeight; diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_asset_conversion.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_asset_conversion.rs new file mode 100644 index 00000000000..3fcf2f8f4ec --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_asset_conversion.rs @@ -0,0 +1,154 @@ +// 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. + +//! Autogenerated weights for `pallet_asset_conversion` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/cumulus/.git/.artifacts/bench.json +// --pallet=pallet_asset_conversion +// --chain=asset-hub-kusama-dev +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_asset_conversion`. +pub struct WeightInfo(PhantomData); +impl pallet_asset_conversion::WeightInfo for WeightInfo { + /// Storage: `AssetConversion::Pools` (r:1 w:1) + /// Proof: `AssetConversion::Pools` (`max_values`: None, `max_size`: Some(1224), added: 3699, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0x76a2c49709deec21d9c05f96c1f47351` (r:1 w:0) + /// Proof: UNKNOWN KEY `0x76a2c49709deec21d9c05f96c1f47351` (r:1 w:0) + /// Storage: `System::Account` (r:2 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `AssetConversion::NextPoolAssetId` (r:1 w:1) + /// Proof: `AssetConversion::NextPoolAssetId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Account` (r:1 w:1) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn create_pool() -> Weight { + // Proof Size summary in bytes: + // Measured: `480` + // Estimated: `6196` + // Minimum execution time: 88_484_000 picoseconds. + Weight::from_parts(92_964_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(7)) + } + /// Storage: `AssetConversion::Pools` (r:1 w:0) + /// Proof: `AssetConversion::Pools` (`max_values`: None, `max_size`: Some(1224), added: 3699, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:2 w:2) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Account` (r:2 w:2) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn add_liquidity() -> Weight { + // Proof Size summary in bytes: + // Measured: `1117` + // Estimated: `7404` + // Minimum execution time: 153_015_000 picoseconds. + Weight::from_parts(157_018_000, 0) + .saturating_add(Weight::from_parts(0, 7404)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(7)) + } + /// Storage: `AssetConversion::Pools` (r:1 w:0) + /// Proof: `AssetConversion::Pools` (`max_values`: None, `max_size`: Some(1224), added: 3699, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:2 w:2) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0x2433d831722b1f4aeb1666953f1c0e77` (r:1 w:0) + /// Proof: UNKNOWN KEY `0x2433d831722b1f4aeb1666953f1c0e77` (r:1 w:0) + /// Storage: `PoolAssets::Account` (r:1 w:1) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn remove_liquidity() -> Weight { + // Proof Size summary in bytes: + // Measured: `1106` + // Estimated: `7404` + // Minimum execution time: 141_726_000 picoseconds. + Weight::from_parts(147_865_000, 0) + .saturating_add(Weight::from_parts(0, 7404)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// Storage: `ForeignAssets::Asset` (r:2 w:2) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:4 w:4) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn swap_exact_tokens_for_tokens() -> Weight { + // Proof Size summary in bytes: + // Measured: `1148` + // Estimated: `13818` + // Minimum execution time: 168_619_000 picoseconds. + Weight::from_parts(174_283_000, 0) + .saturating_add(Weight::from_parts(0, 13818)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(8)) + } + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:2 w:2) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:4 w:4) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + fn swap_tokens_for_exact_tokens() -> Weight { + // Proof Size summary in bytes: + // Measured: `1148` + // Estimated: `13818` + // Minimum execution time: 171_565_000 picoseconds. + Weight::from_parts(173_702_000, 0) + .saturating_add(Weight::from_parts(0, 13818)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(8)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_assets_foreign.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_assets_foreign.rs new file mode 100644 index 00000000000..c2688d97905 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_assets_foreign.rs @@ -0,0 +1,533 @@ +// 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. + +//! Autogenerated weights for `pallet_assets` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-06-20, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --execution=wasm +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/var/lib/gitlab-runner/builds/zyw4fam_/0/parity/mirrors/cumulus/.git/.artifacts/bench.json +// --pallet=pallet_assets +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_assets`. +pub struct WeightInfo(PhantomData); +impl pallet_assets::WeightInfo for WeightInfo { + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn create() -> Weight { + // Proof Size summary in bytes: + // Measured: `107` + // Estimated: `4273` + // Minimum execution time: 30_485_000 picoseconds. + Weight::from_parts(31_007_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn force_create() -> Weight { + // Proof Size summary in bytes: + // Measured: `4` + // Estimated: `4273` + // Minimum execution time: 12_991_000 picoseconds. + Weight::from_parts(13_304_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn start_destroy() -> Weight { + // Proof Size summary in bytes: + // Measured: `276` + // Estimated: `4273` + // Minimum execution time: 15_689_000 picoseconds. + Weight::from_parts(16_063_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: ForeignAssets Asset (r:1 w:1) + /// Proof: ForeignAssets Asset (max_values: None, max_size: Some(808), added: 3283, mode: MaxEncodedLen) + /// Storage: ForeignAssets Account (r:1001 w:1000) + /// Proof: ForeignAssets Account (max_values: None, max_size: Some(732), added: 3207, mode: MaxEncodedLen) + /// Storage: System Account (r:1000 w:1000) + /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) + /// The range of component `c` is `[0, 1000]`. + /// The range of component `c` is `[0, 1000]`. + fn destroy_accounts(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + c * (208 ±0)` + // Estimated: `4273 + c * (3207 ±0)` + // Minimum execution time: 18_533_000 picoseconds. + Weight::from_parts(18_791_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + // Standard Error: 5_059 + .saturating_add(Weight::from_parts(12_049_659, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(c.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 3207).saturating_mul(c.into())) + } + /// Storage: ForeignAssets Asset (r:1 w:1) + /// Proof: ForeignAssets Asset (max_values: None, max_size: Some(808), added: 3283, mode: MaxEncodedLen) + /// Storage: ForeignAssets Approvals (r:1001 w:1000) + /// Proof: ForeignAssets Approvals (max_values: None, max_size: Some(746), added: 3221, mode: MaxEncodedLen) + /// The range of component `a` is `[0, 1000]`. + /// The range of component `a` is `[0, 1000]`. + fn destroy_approvals(a: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `413 + a * (86 ±0)` + // Estimated: `4273 + a * (3221 ±0)` + // Minimum execution time: 20_028_000 picoseconds. + Weight::from_parts(20_148_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + // Standard Error: 3_401 + .saturating_add(Weight::from_parts(13_897_319, 0).saturating_mul(a.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(a.into()))) + .saturating_add(Weight::from_parts(0, 3221).saturating_mul(a.into())) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Metadata` (r:1 w:0) + /// Proof: `ForeignAssets::Metadata` (`max_values`: None, `max_size`: Some(738), added: 3213, mode: `MaxEncodedLen`) + fn finish_destroy() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 15_949_000 picoseconds. + Weight::from_parts(16_241_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + fn mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 27_156_000 picoseconds. + Weight::from_parts(28_182_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + fn burn() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `4273` + // Minimum execution time: 33_503_000 picoseconds. + Weight::from_parts(33_860_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:2 w:2) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `7404` + // Minimum execution time: 45_065_000 picoseconds. + Weight::from_parts(45_856_000, 0) + .saturating_add(Weight::from_parts(0, 7404)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:2 w:2) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_keep_alive() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `7404` + // Minimum execution time: 39_913_000 picoseconds. + Weight::from_parts(40_791_000, 0) + .saturating_add(Weight::from_parts(0, 7404)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:2 w:2) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `7404` + // Minimum execution time: 45_337_000 picoseconds. + Weight::from_parts(45_980_000, 0) + .saturating_add(Weight::from_parts(0, 7404)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:0) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + fn freeze() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `4273` + // Minimum execution time: 19_012_000 picoseconds. + Weight::from_parts(19_326_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:0) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + fn thaw() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `4273` + // Minimum execution time: 18_656_000 picoseconds. + Weight::from_parts(19_205_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn freeze_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `276` + // Estimated: `4273` + // Minimum execution time: 15_440_000 picoseconds. + Weight::from_parts(15_825_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn thaw_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `276` + // Estimated: `4273` + // Minimum execution time: 15_465_000 picoseconds. + Weight::from_parts(15_769_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Metadata` (r:1 w:0) + /// Proof: `ForeignAssets::Metadata` (`max_values`: None, `max_size`: Some(738), added: 3213, mode: `MaxEncodedLen`) + fn transfer_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 16_579_000 picoseconds. + Weight::from_parts(16_931_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn set_team() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 15_138_000 picoseconds. + Weight::from_parts(15_435_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: ForeignAssets Asset (r:1 w:0) + /// Proof: ForeignAssets Asset (max_values: None, max_size: Some(808), added: 3283, mode: MaxEncodedLen) + /// Storage: ForeignAssets Metadata (r:1 w:1) + /// Proof: ForeignAssets Metadata (max_values: None, max_size: Some(738), added: 3213, mode: MaxEncodedLen) + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + fn set_metadata(_n: u32, _s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 29_846_000 picoseconds. + Weight::from_parts(31_607_649, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:0) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Metadata` (r:1 w:1) + /// Proof: `ForeignAssets::Metadata` (`max_values`: None, `max_size`: Some(738), added: 3213, mode: `MaxEncodedLen`) + fn clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `406` + // Estimated: `4273` + // Minimum execution time: 30_582_000 picoseconds. + Weight::from_parts(31_008_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: ForeignAssets Asset (r:1 w:0) + /// Proof: ForeignAssets Asset (max_values: None, max_size: Some(808), added: 3283, mode: MaxEncodedLen) + /// Storage: ForeignAssets Metadata (r:1 w:1) + /// Proof: ForeignAssets Metadata (max_values: None, max_size: Some(738), added: 3213, mode: MaxEncodedLen) + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + fn force_set_metadata(_n: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `81` + // Estimated: `4273` + // Minimum execution time: 14_186_000 picoseconds. + Weight::from_parts(14_717_332, 0) + .saturating_add(Weight::from_parts(0, 4273)) + // Standard Error: 517 + .saturating_add(Weight::from_parts(2_595, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:0) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Metadata` (r:1 w:1) + /// Proof: `ForeignAssets::Metadata` (`max_values`: None, `max_size`: Some(738), added: 3213, mode: `MaxEncodedLen`) + fn force_clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `406` + // Estimated: `4273` + // Minimum execution time: 29_499_000 picoseconds. + Weight::from_parts(29_918_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn force_asset_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 13_815_000 picoseconds. + Weight::from_parts(14_138_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Approvals` (r:1 w:1) + /// Proof: `ForeignAssets::Approvals` (`max_values`: None, `max_size`: Some(746), added: 3221, mode: `MaxEncodedLen`) + fn approve_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `276` + // Estimated: `4273` + // Minimum execution time: 33_029_000 picoseconds. + Weight::from_parts(33_524_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Approvals` (r:1 w:1) + /// Proof: `ForeignAssets::Approvals` (`max_values`: None, `max_size`: Some(746), added: 3221, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:2 w:2) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_approved() -> Weight { + // Proof Size summary in bytes: + // Measured: `520` + // Estimated: `7404` + // Minimum execution time: 63_205_000 picoseconds. + Weight::from_parts(64_078_000, 0) + .saturating_add(Weight::from_parts(0, 7404)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Approvals` (r:1 w:1) + /// Proof: `ForeignAssets::Approvals` (`max_values`: None, `max_size`: Some(746), added: 3221, mode: `MaxEncodedLen`) + fn cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `446` + // Estimated: `4273` + // Minimum execution time: 34_948_000 picoseconds. + Weight::from_parts(35_484_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Approvals` (r:1 w:1) + /// Proof: `ForeignAssets::Approvals` (`max_values`: None, `max_size`: Some(746), added: 3221, mode: `MaxEncodedLen`) + fn force_cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `446` + // Estimated: `4273` + // Minimum execution time: 35_722_000 picoseconds. + Weight::from_parts(36_266_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn set_min_balance() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 15_855_000 picoseconds. + Weight::from_parts(16_182_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn touch() -> Weight { + // Proof Size summary in bytes: + // Measured: `345` + // Estimated: `4273` + // Minimum execution time: 34_984_000 picoseconds. + Weight::from_parts(35_512_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn touch_other() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 33_041_000 picoseconds. + Weight::from_parts(34_124_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn refund() -> Weight { + // Proof Size summary in bytes: + // Measured: `471` + // Estimated: `4273` + // Minimum execution time: 31_728_000 picoseconds. + Weight::from_parts(32_012_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn refund_other() -> Weight { + // Proof Size summary in bytes: + // Measured: `401` + // Estimated: `4273` + // Minimum execution time: 29_432_000 picoseconds. + Weight::from_parts(29_968_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:0) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + fn block() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `4273` + // Minimum execution time: 18_827_000 picoseconds. + Weight::from_parts(19_172_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_assets_local.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_assets_local.rs new file mode 100644 index 00000000000..957e33fcd9e --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_assets_local.rs @@ -0,0 +1,530 @@ +// 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. + +//! Autogenerated weights for `pallet_assets` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_assets +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_assets`. +pub struct WeightInfo(PhantomData); +impl pallet_assets::WeightInfo for WeightInfo { + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn create() -> Weight { + // Proof Size summary in bytes: + // Measured: `109` + // Estimated: `3675` + // Minimum execution time: 26_510_000 picoseconds. + Weight::from_parts(27_332_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn force_create() -> Weight { + // Proof Size summary in bytes: + // Measured: `6` + // Estimated: `3675` + // Minimum execution time: 10_899_000 picoseconds. + Weight::from_parts(11_395_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn start_destroy() -> Weight { + // Proof Size summary in bytes: + // Measured: `277` + // Estimated: `3675` + // Minimum execution time: 13_593_000 picoseconds. + Weight::from_parts(14_108_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1001 w:1000) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1000 w:1000) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `c` is `[0, 1000]`. + /// The range of component `c` is `[0, 1000]`. + fn destroy_accounts(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + c * (208 ±0)` + // Estimated: `3675 + c * (2609 ±0)` + // Minimum execution time: 16_216_000 picoseconds. + Weight::from_parts(16_636_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + // Standard Error: 9_346 + .saturating_add(Weight::from_parts(15_306_152, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(c.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 2609).saturating_mul(c.into())) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Approvals` (r:1001 w:1000) + /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 1000]`. + /// The range of component `a` is `[0, 1000]`. + fn destroy_approvals(a: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `414 + a * (86 ±0)` + // Estimated: `3675 + a * (2623 ±0)` + // Minimum execution time: 16_745_000 picoseconds. + Weight::from_parts(17_247_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(Weight::from_parts(15_634_963, 0).saturating_mul(a.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(Weight::from_parts(0, 2623).saturating_mul(a.into())) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:0) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + fn finish_destroy() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 13_650_000 picoseconds. + Weight::from_parts(14_721_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 24_121_000 picoseconds. + Weight::from_parts(25_023_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn burn() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `3675` + // Minimum execution time: 31_414_000 picoseconds. + Weight::from_parts(32_235_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:2 w:2) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `6208` + // Minimum execution time: 43_114_000 picoseconds. + Weight::from_parts(44_106_000, 0) + .saturating_add(Weight::from_parts(0, 6208)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:2 w:2) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_keep_alive() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `6208` + // Minimum execution time: 37_954_000 picoseconds. + Weight::from_parts(38_772_000, 0) + .saturating_add(Weight::from_parts(0, 6208)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:2 w:2) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `6208` + // Minimum execution time: 43_051_000 picoseconds. + Weight::from_parts(44_003_000, 0) + .saturating_add(Weight::from_parts(0, 6208)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn freeze() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `3675` + // Minimum execution time: 17_048_000 picoseconds. + Weight::from_parts(17_614_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn thaw() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `3675` + // Minimum execution time: 16_705_000 picoseconds. + Weight::from_parts(17_581_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn freeze_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `277` + // Estimated: `3675` + // Minimum execution time: 13_284_000 picoseconds. + Weight::from_parts(13_735_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn thaw_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `277` + // Estimated: `3675` + // Minimum execution time: 13_030_000 picoseconds. + Weight::from_parts(13_417_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:0) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + fn transfer_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 14_174_000 picoseconds. + Weight::from_parts(14_660_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn set_team() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 12_737_000 picoseconds. + Weight::from_parts(13_172_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:1) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + fn set_metadata(n: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 27_707_000 picoseconds. + Weight::from_parts(29_036_880, 0) + .saturating_add(Weight::from_parts(0, 3675)) + // Standard Error: 688 + .saturating_add(Weight::from_parts(2_426, 0).saturating_mul(n.into())) + // Standard Error: 688 + .saturating_add(Weight::from_parts(776, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:1) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + fn clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `407` + // Estimated: `3675` + // Minimum execution time: 28_514_000 picoseconds. + Weight::from_parts(29_216_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:1) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + fn force_set_metadata(n: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `82` + // Estimated: `3675` + // Minimum execution time: 12_452_000 picoseconds. + Weight::from_parts(13_095_356, 0) + .saturating_add(Weight::from_parts(0, 3675)) + // Standard Error: 275 + .saturating_add(Weight::from_parts(826, 0).saturating_mul(n.into())) + // Standard Error: 275 + .saturating_add(Weight::from_parts(808, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:1) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + fn force_clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `407` + // Estimated: `3675` + // Minimum execution time: 28_181_000 picoseconds. + Weight::from_parts(29_050_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn force_asset_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 12_253_000 picoseconds. + Weight::from_parts(12_545_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Approvals` (r:1 w:1) + /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + fn approve_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `277` + // Estimated: `3675` + // Minimum execution time: 31_084_000 picoseconds. + Weight::from_parts(32_052_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Approvals` (r:1 w:1) + /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:2 w:2) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_approved() -> Weight { + // Proof Size summary in bytes: + // Measured: `521` + // Estimated: `6208` + // Minimum execution time: 61_756_000 picoseconds. + Weight::from_parts(62_740_000, 0) + .saturating_add(Weight::from_parts(0, 6208)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Approvals` (r:1 w:1) + /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + fn cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `447` + // Estimated: `3675` + // Minimum execution time: 33_370_000 picoseconds. + Weight::from_parts(34_127_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Approvals` (r:1 w:1) + /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + fn force_cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `447` + // Estimated: `3675` + // Minimum execution time: 33_753_000 picoseconds. + Weight::from_parts(34_613_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn set_min_balance() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 13_508_000 picoseconds. + Weight::from_parts(13_997_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn touch() -> Weight { + // Proof Size summary in bytes: + // Measured: `346` + // Estimated: `3675` + // Minimum execution time: 32_578_000 picoseconds. + Weight::from_parts(33_675_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn touch_other() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 30_768_000 picoseconds. + Weight::from_parts(31_710_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn refund() -> Weight { + // Proof Size summary in bytes: + // Measured: `472` + // Estimated: `3675` + // Minimum execution time: 30_028_000 picoseconds. + Weight::from_parts(30_793_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn refund_other() -> Weight { + // Proof Size summary in bytes: + // Measured: `402` + // Estimated: `3675` + // Minimum execution time: 28_354_000 picoseconds. + Weight::from_parts(29_097_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn block() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `3675` + // Minimum execution time: 16_607_000 picoseconds. + Weight::from_parts(17_433_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_assets_pool.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_assets_pool.rs new file mode 100644 index 00000000000..e0b4ff36552 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_assets_pool.rs @@ -0,0 +1,530 @@ +// 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. + +//! Autogenerated weights for `pallet_assets` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-27, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/cumulus/.git/.artifacts/bench.json +// --pallet=pallet_assets +// --chain=asset-hub-kusama-dev +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_assets`. +pub struct WeightInfo(PhantomData); +impl pallet_assets::WeightInfo for WeightInfo { + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn create() -> Weight { + // Proof Size summary in bytes: + // Measured: `42` + // Estimated: `3675` + // Minimum execution time: 11_591_000 picoseconds. + Weight::from_parts(11_901_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn force_create() -> Weight { + // Proof Size summary in bytes: + // Measured: `42` + // Estimated: `3675` + // Minimum execution time: 11_184_000 picoseconds. + Weight::from_parts(11_640_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn start_destroy() -> Weight { + // Proof Size summary in bytes: + // Measured: `314` + // Estimated: `3675` + // Minimum execution time: 13_809_000 picoseconds. + Weight::from_parts(14_226_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Account` (r:1001 w:1000) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1000 w:1000) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `c` is `[0, 1000]`. + /// The range of component `c` is `[0, 1000]`. + /// The range of component `c` is `[0, 1000]`. + fn destroy_accounts(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + c * (208 ±0)` + // Estimated: `3675 + c * (2609 ±0)` + // Minimum execution time: 16_439_000 picoseconds. + Weight::from_parts(16_743_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + // Standard Error: 4_792 + .saturating_add(Weight::from_parts(14_463_991, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(c.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 2609).saturating_mul(c.into())) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Approvals` (r:1001 w:1000) + /// Proof: `PoolAssets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 1000]`. + /// The range of component `a` is `[0, 1000]`. + /// The range of component `a` is `[0, 1000]`. + fn destroy_approvals(a: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `451 + a * (86 ±0)` + // Estimated: `3675 + a * (2623 ±0)` + // Minimum execution time: 17_218_000 picoseconds. + Weight::from_parts(17_585_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + // Standard Error: 2_056 + .saturating_add(Weight::from_parts(5_323_866, 0).saturating_mul(a.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(a.into()))) + .saturating_add(Weight::from_parts(0, 2623).saturating_mul(a.into())) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Metadata` (r:1 w:0) + /// Proof: `PoolAssets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + fn finish_destroy() -> Weight { + // Proof Size summary in bytes: + // Measured: `280` + // Estimated: `3675` + // Minimum execution time: 13_848_000 picoseconds. + Weight::from_parts(14_325_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Account` (r:1 w:1) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `280` + // Estimated: `3675` + // Minimum execution time: 24_904_000 picoseconds. + Weight::from_parts(25_607_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Account` (r:1 w:1) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn burn() -> Weight { + // Proof Size summary in bytes: + // Measured: `388` + // Estimated: `3675` + // Minimum execution time: 31_477_000 picoseconds. + Weight::from_parts(32_338_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Account` (r:2 w:2) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `388` + // Estimated: `6208` + // Minimum execution time: 42_994_000 picoseconds. + Weight::from_parts(44_041_000, 0) + .saturating_add(Weight::from_parts(0, 6208)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Account` (r:2 w:2) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_keep_alive() -> Weight { + // Proof Size summary in bytes: + // Measured: `388` + // Estimated: `6208` + // Minimum execution time: 37_551_000 picoseconds. + Weight::from_parts(38_648_000, 0) + .saturating_add(Weight::from_parts(0, 6208)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Account` (r:2 w:2) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `388` + // Estimated: `6208` + // Minimum execution time: 42_829_000 picoseconds. + Weight::from_parts(44_029_000, 0) + .saturating_add(Weight::from_parts(0, 6208)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:0) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Account` (r:1 w:1) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn freeze() -> Weight { + // Proof Size summary in bytes: + // Measured: `388` + // Estimated: `3675` + // Minimum execution time: 17_304_000 picoseconds. + Weight::from_parts(17_782_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:0) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Account` (r:1 w:1) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn thaw() -> Weight { + // Proof Size summary in bytes: + // Measured: `388` + // Estimated: `3675` + // Minimum execution time: 17_040_000 picoseconds. + Weight::from_parts(17_698_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn freeze_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `314` + // Estimated: `3675` + // Minimum execution time: 13_238_000 picoseconds. + Weight::from_parts(13_810_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn thaw_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `314` + // Estimated: `3675` + // Minimum execution time: 13_034_000 picoseconds. + Weight::from_parts(13_603_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Metadata` (r:1 w:0) + /// Proof: `PoolAssets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + fn transfer_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `280` + // Estimated: `3675` + // Minimum execution time: 14_357_000 picoseconds. + Weight::from_parts(14_774_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn set_team() -> Weight { + // Proof Size summary in bytes: + // Measured: `280` + // Estimated: `3675` + // Minimum execution time: 13_040_000 picoseconds. + Weight::from_parts(13_616_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:0) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Metadata` (r:1 w:1) + /// Proof: `PoolAssets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + fn set_metadata(n: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `280` + // Estimated: `3675` + // Minimum execution time: 15_274_000 picoseconds. + Weight::from_parts(16_096_881, 0) + .saturating_add(Weight::from_parts(0, 3675)) + // Standard Error: 239 + .saturating_add(Weight::from_parts(1_631, 0).saturating_mul(n.into())) + // Standard Error: 239 + .saturating_add(Weight::from_parts(2_334, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:0) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Metadata` (r:1 w:1) + /// Proof: `PoolAssets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + fn clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `444` + // Estimated: `3675` + // Minimum execution time: 15_900_000 picoseconds. + Weight::from_parts(16_526_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:0) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Metadata` (r:1 w:1) + /// Proof: `PoolAssets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + fn force_set_metadata(n: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `119` + // Estimated: `3675` + // Minimum execution time: 13_391_000 picoseconds. + Weight::from_parts(14_047_176, 0) + .saturating_add(Weight::from_parts(0, 3675)) + // Standard Error: 172 + .saturating_add(Weight::from_parts(2_617, 0).saturating_mul(n.into())) + // Standard Error: 172 + .saturating_add(Weight::from_parts(2_081, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:0) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Metadata` (r:1 w:1) + /// Proof: `PoolAssets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + fn force_clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `444` + // Estimated: `3675` + // Minimum execution time: 15_794_000 picoseconds. + Weight::from_parts(16_279_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn force_asset_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `280` + // Estimated: `3675` + // Minimum execution time: 12_538_000 picoseconds. + Weight::from_parts(13_080_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Approvals` (r:1 w:1) + /// Proof: `PoolAssets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + fn approve_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `314` + // Estimated: `3675` + // Minimum execution time: 18_991_000 picoseconds. + Weight::from_parts(19_812_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Approvals` (r:1 w:1) + /// Proof: `PoolAssets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Account` (r:2 w:2) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_approved() -> Weight { + // Proof Size summary in bytes: + // Measured: `558` + // Estimated: `6208` + // Minimum execution time: 50_336_000 picoseconds. + Weight::from_parts(51_441_000, 0) + .saturating_add(Weight::from_parts(0, 6208)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Approvals` (r:1 w:1) + /// Proof: `PoolAssets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + fn cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `484` + // Estimated: `3675` + // Minimum execution time: 21_195_000 picoseconds. + Weight::from_parts(21_946_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Approvals` (r:1 w:1) + /// Proof: `PoolAssets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + fn force_cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `484` + // Estimated: `3675` + // Minimum execution time: 21_568_000 picoseconds. + Weight::from_parts(22_366_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn set_min_balance() -> Weight { + // Proof Size summary in bytes: + // Measured: `280` + // Estimated: `3675` + // Minimum execution time: 13_690_000 picoseconds. + Weight::from_parts(14_086_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PoolAssets::Account` (r:1 w:1) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn touch() -> Weight { + // Proof Size summary in bytes: + // Measured: `280` + // Estimated: `3675` + // Minimum execution time: 18_240_000 picoseconds. + Weight::from_parts(19_000_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PoolAssets::Account` (r:1 w:1) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn touch_other() -> Weight { + // Proof Size summary in bytes: + // Measured: `280` + // Estimated: `3675` + // Minimum execution time: 18_469_000 picoseconds. + Weight::from_parts(19_040_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PoolAssets::Account` (r:1 w:1) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn refund() -> Weight { + // Proof Size summary in bytes: + // Measured: `406` + // Estimated: `3675` + // Minimum execution time: 14_633_000 picoseconds. + Weight::from_parts(15_296_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PoolAssets::Account` (r:1 w:1) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Asset` (r:1 w:1) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn refund_other() -> Weight { + // Proof Size summary in bytes: + // Measured: `439` + // Estimated: `3675` + // Minimum execution time: 14_751_000 picoseconds. + Weight::from_parts(15_312_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PoolAssets::Asset` (r:1 w:0) + /// Proof: `PoolAssets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `PoolAssets::Account` (r:1 w:1) + /// Proof: `PoolAssets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn block() -> Weight { + // Proof Size summary in bytes: + // Measured: `388` + // Estimated: `3675` + // Minimum execution time: 16_930_000 picoseconds. + Weight::from_parts(17_653_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_balances.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_balances.rs new file mode 100644 index 00000000000..79c88f30580 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_balances.rs @@ -0,0 +1,152 @@ +// 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. + +//! Autogenerated weights for `pallet_balances` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_balances +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_balances`. +pub struct WeightInfo(PhantomData); +impl pallet_balances::WeightInfo for WeightInfo { + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_allow_death() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 55_040_000 picoseconds. + Weight::from_parts(56_106_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_keep_alive() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 41_342_000 picoseconds. + Weight::from_parts(41_890_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_set_balance_creating() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `3593` + // Minimum execution time: 14_723_000 picoseconds. + Weight::from_parts(15_182_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_set_balance_killing() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `3593` + // Minimum execution time: 22_073_000 picoseconds. + Weight::from_parts(22_638_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `6196` + // Minimum execution time: 57_265_000 picoseconds. + Weight::from_parts(58_222_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_all() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 51_485_000 picoseconds. + Weight::from_parts(52_003_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_unreserve() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `3593` + // Minimum execution time: 17_460_000 picoseconds. + Weight::from_parts(17_849_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:999 w:999) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `u` is `[1, 1000]`. + fn upgrade_accounts(u: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + u * (136 ±0)` + // Estimated: `990 + u * (2603 ±0)` + // Minimum execution time: 17_259_000 picoseconds. + Weight::from_parts(17_478_000, 0) + .saturating_add(Weight::from_parts(0, 990)) + // Standard Error: 16_756 + .saturating_add(Weight::from_parts(15_291_954, 0).saturating_mul(u.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(u.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(u.into()))) + .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_collator_selection.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_collator_selection.rs new file mode 100644 index 00000000000..c686bd6134a --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_collator_selection.rs @@ -0,0 +1,248 @@ +// 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. + +//! Autogenerated weights for `pallet_collator_selection` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_collator_selection +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_collator_selection`. +pub struct WeightInfo(PhantomData); +impl pallet_collator_selection::WeightInfo for WeightInfo { + /// Storage: `Session::NextKeys` (r:20 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::Invulnerables` (r:0 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// The range of component `b` is `[1, 20]`. + fn set_invulnerables(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `163 + b * (79 ±0)` + // Estimated: `1154 + b * (2555 ±0)` + // Minimum execution time: 15_408_000 picoseconds. + Weight::from_parts(13_068_592, 0) + .saturating_add(Weight::from_parts(0, 1154)) + // Standard Error: 7_395 + .saturating_add(Weight::from_parts(3_219_916, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(b.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(Weight::from_parts(0, 2555).saturating_mul(b.into())) + } + /// Storage: `Session::NextKeys` (r:1 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `b` is `[1, 19]`. + /// The range of component `c` is `[1, 99]`. + fn add_invulnerable(b: u32, c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `756 + b * (32 ±0) + c * (53 ±0)` + // Estimated: `6287 + b * (37 ±0) + c * (53 ±0)` + // Minimum execution time: 49_692_000 picoseconds. + Weight::from_parts(51_768_986, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 18_404 + .saturating_add(Weight::from_parts(55_676, 0).saturating_mul(b.into())) + // Standard Error: 3_488 + .saturating_add(Weight::from_parts(184_343, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 37).saturating_mul(b.into())) + .saturating_add(Weight::from_parts(0, 53).saturating_mul(c.into())) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:0) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// The range of component `b` is `[5, 20]`. + fn remove_invulnerable(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `119 + b * (32 ±0)` + // Estimated: `6287` + // Minimum execution time: 16_486_000 picoseconds. + Weight::from_parts(16_646_017, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 3_230 + .saturating_add(Weight::from_parts(148_941, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::DesiredCandidates` (r:0 w:1) + /// Proof: `CollatorSelection::DesiredCandidates` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn set_desired_candidates() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_806_000 picoseconds. + Weight::from_parts(8_002_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::CandidacyBond` (r:0 w:1) + /// Proof: `CollatorSelection::CandidacyBond` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + fn set_candidacy_bond(_c: u32, _k: u32) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_937_000 picoseconds. + Weight::from_parts(8_161_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::DesiredCandidates` (r:1 w:0) + /// Proof: `CollatorSelection::DesiredCandidates` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `Session::NextKeys` (r:1 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::CandidacyBond` (r:1 w:0) + /// Proof: `CollatorSelection::CandidacyBond` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// The range of component `c` is `[1, 99]`. + fn register_as_candidate(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `736 + c * (52 ±0)` + // Estimated: `6287 + c * (54 ±0)` + // Minimum execution time: 42_805_000 picoseconds. + Weight::from_parts(45_979_502, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_336 + .saturating_add(Weight::from_parts(221_049, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(2)) + .saturating_add(Weight::from_parts(0, 54).saturating_mul(c.into())) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// The range of component `c` is `[4, 100]`. + fn leave_intent(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 34_814_000 picoseconds. + Weight::from_parts(36_371_520, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_391 + .saturating_add(Weight::from_parts(201_700, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + fn update_bond(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 34_814_000 picoseconds. + Weight::from_parts(36_371_520, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_391 + .saturating_add(Weight::from_parts(201_700, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + fn take_candidate_slot(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 34_814_000 picoseconds. + Weight::from_parts(36_371_520, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_391 + .saturating_add(Weight::from_parts(201_700, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `System::BlockWeight` (r:1 w:1) + /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + fn note_author() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `6196` + // Minimum execution time: 46_989_000 picoseconds. + Weight::from_parts(48_151_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:0) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:100 w:0) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `System::BlockWeight` (r:1 w:1) + /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:97 w:97) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `r` is `[1, 100]`. + /// The range of component `c` is `[1, 100]`. + fn new_session(r: u32, c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `2243 + c * (97 ±0) + r * (112 ±0)` + // Estimated: `6287 + c * (2519 ±0) + r * (2603 ±0)` + // Minimum execution time: 17_547_000 picoseconds. + Weight::from_parts(17_854_000, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 370_637 + .saturating_add(Weight::from_parts(15_798_857, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(c.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 2519).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(0, 2603).saturating_mul(r.into())) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_message_queue.rs new file mode 100644 index 00000000000..792b7d18b67 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_message_queue.rs @@ -0,0 +1,179 @@ +// 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. + +//! Autogenerated weights for `pallet_message_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-03-24, STEPS: `2`, REPEAT: `1`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `i9`, CPU: `13th Gen Intel(R) Core(TM) i9-13900K` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --chain +// statemint-dev +// --pallet +// pallet_message_queue +// --extrinsic +// * +// --execution +// wasm +// --wasm-execution +// compiled +// --output +// parachains/runtimes/assets/statemint/src/weights + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `pallet_message_queue`. +pub struct WeightInfo(PhantomData); +impl pallet_message_queue::WeightInfo for WeightInfo { + /// Storage: MessageQueue ServiceHead (r:1 w:0) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: MessageQueue BookStateFor (r:2 w:2) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn ready_ring_knit() -> Weight { + // Proof Size summary in bytes: + // Measured: `189` + // Estimated: `7534` + // Minimum execution time: 18_976_000 picoseconds. + Weight::from_parts(18_976_000, 0) + .saturating_add(Weight::from_parts(0, 7534)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:2 w:2) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + fn ready_ring_unknit() -> Weight { + // Proof Size summary in bytes: + // Measured: `184` + // Estimated: `7534` + // Minimum execution time: 12_686_000 picoseconds. + Weight::from_parts(12_686_000, 0) + .saturating_add(Weight::from_parts(0, 7534)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn service_queue_base() -> Weight { + // Proof Size summary in bytes: + // Measured: `6` + // Estimated: `3517` + // Minimum execution time: 4_951_000 picoseconds. + Weight::from_parts(4_951_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn service_page_base_completion() -> Weight { + // Proof Size summary in bytes: + // Measured: `72` + // Estimated: `69050` + // Minimum execution time: 6_023_000 picoseconds. + Weight::from_parts(6_023_000, 0) + .saturating_add(Weight::from_parts(0, 69050)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn service_page_base_no_completion() -> Weight { + // Proof Size summary in bytes: + // Measured: `72` + // Estimated: `69050` + // Minimum execution time: 6_901_000 picoseconds. + Weight::from_parts(6_901_000, 0) + .saturating_add(Weight::from_parts(0, 69050)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn service_page_item() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 58_503_000 picoseconds. + Weight::from_parts(58_503_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: MessageQueue BookStateFor (r:1 w:0) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn bump_service_head() -> Weight { + // Proof Size summary in bytes: + // Measured: `99` + // Estimated: `5007` + // Minimum execution time: 9_318_000 picoseconds. + Weight::from_parts(9_318_000, 0) + .saturating_add(Weight::from_parts(0, 5007)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn reap_page() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 52_228_000 picoseconds. + Weight::from_parts(52_228_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn execute_overweight_page_removed() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 59_617_000 picoseconds. + Weight::from_parts(59_617_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn execute_overweight_page_updated() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 69_681_000 picoseconds. + Weight::from_parts(69_681_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_multisig.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_multisig.rs new file mode 100644 index 00000000000..d2e0f0ec7f0 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_multisig.rs @@ -0,0 +1,164 @@ +// 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. + +//! Autogenerated weights for `pallet_multisig` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_multisig +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_multisig`. +pub struct WeightInfo(PhantomData); +impl pallet_multisig::WeightInfo for WeightInfo { + /// The range of component `z` is `[0, 10000]`. + fn as_multi_threshold_1(z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 13_714_000 picoseconds. + Weight::from_parts(14_440_231, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 5 + .saturating_add(Weight::from_parts(598, 0).saturating_mul(z.into())) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_create(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `262 + s * (2 ±0)` + // Estimated: `6811` + // Minimum execution time: 44_768_000 picoseconds. + Weight::from_parts(33_662_218, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_633 + .saturating_add(Weight::from_parts(128_927, 0).saturating_mul(s.into())) + // Standard Error: 16 + .saturating_add(Weight::from_parts(1_543, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[3, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_approve(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `6811` + // Minimum execution time: 29_745_000 picoseconds. + Weight::from_parts(20_559_891, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 914 + .saturating_add(Weight::from_parts(103_601, 0).saturating_mul(s.into())) + // Standard Error: 8 + .saturating_add(Weight::from_parts(1_504, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_complete(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `385 + s * (33 ±0)` + // Estimated: `6811` + // Minimum execution time: 51_506_000 picoseconds. + Weight::from_parts(36_510_777, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 2_183 + .saturating_add(Weight::from_parts(183_764, 0).saturating_mul(s.into())) + // Standard Error: 21 + .saturating_add(Weight::from_parts(1_653, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_create(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `263 + s * (2 ±0)` + // Estimated: `6811` + // Minimum execution time: 31_072_000 picoseconds. + Weight::from_parts(32_408_621, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 913 + .saturating_add(Weight::from_parts(121_410, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_approve(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `6811` + // Minimum execution time: 18_301_000 picoseconds. + Weight::from_parts(18_223_547, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 747 + .saturating_add(Weight::from_parts(114_584, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn cancel_as_multi(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `454 + s * (1 ±0)` + // Estimated: `6811` + // Minimum execution time: 32_107_000 picoseconds. + Weight::from_parts(33_674_827, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_220 + .saturating_add(Weight::from_parts(122_011, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_nft_fractionalization.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_nft_fractionalization.rs new file mode 100644 index 00000000000..4becc569514 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_nft_fractionalization.rs @@ -0,0 +1,114 @@ +// 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. + +//! Autogenerated weights for `pallet_nft_fractionalization` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_nft_fractionalization +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_nft_fractionalization`. +pub struct WeightInfo(PhantomData); +impl pallet_nft_fractionalization::WeightInfo for WeightInfo { + /// Storage: `Nfts::Item` (r:1 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Balances::Holds` (r:1 w:1) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1 w:1) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:1) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + /// Storage: `NftFractionalization::NftToAsset` (r:0 w:1) + /// Proof: `NftFractionalization::NftToAsset` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + fn fractionalize() -> Weight { + // Proof Size summary in bytes: + // Measured: `462` + // Estimated: `4326` + // Minimum execution time: 178_501_000 picoseconds. + Weight::from_parts(180_912_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(8)) + } + /// Storage: `NftFractionalization::NftToAsset` (r:1 w:1) + /// Proof: `NftFractionalization::NftToAsset` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1 w:1) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Balances::Holds` (r:1 w:1) + /// Proof: `Balances::Holds` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:1) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemPriceOf` (r:0 w:1) + /// Proof: `Nfts::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + /// Storage: `Nfts::PendingSwapOf` (r:0 w:1) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + fn unify() -> Weight { + // Proof Size summary in bytes: + // Measured: `1275` + // Estimated: `4326` + // Minimum execution time: 125_253_000 picoseconds. + Weight::from_parts(128_238_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(10)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_nfts.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_nfts.rs new file mode 100644 index 00000000000..7a51830799a --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_nfts.rs @@ -0,0 +1,772 @@ +// 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. + +//! Autogenerated weights for `pallet_nfts` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_nfts +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_nfts`. +pub struct WeightInfo(PhantomData); +impl pallet_nfts::WeightInfo for WeightInfo { + /// Storage: `Nfts::NextCollectionId` (r:1 w:1) + /// Proof: `Nfts::NextCollectionId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:0 w:1) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:0 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionAccount` (r:0 w:1) + /// Proof: `Nfts::CollectionAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn create() -> Weight { + // Proof Size summary in bytes: + // Measured: `179` + // Estimated: `3549` + // Minimum execution time: 39_124_000 picoseconds. + Weight::from_parts(39_975_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `Nfts::NextCollectionId` (r:1 w:1) + /// Proof: `Nfts::NextCollectionId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:0 w:1) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:0 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionAccount` (r:0 w:1) + /// Proof: `Nfts::CollectionAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn force_create() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `3549` + // Minimum execution time: 23_444_000 picoseconds. + Weight::from_parts(23_857_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemMetadataOf` (r:1 w:0) + /// Proof: `Nfts::ItemMetadataOf` (`max_values`: None, `max_size`: Some(347), added: 2822, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:1) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1001 w:1000) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1000 w:1000) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionMetadataOf` (r:0 w:1) + /// Proof: `Nfts::CollectionMetadataOf` (`max_values`: None, `max_size`: Some(294), added: 2769, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:0 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionAccount` (r:0 w:1) + /// Proof: `Nfts::CollectionAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + /// The range of component `m` is `[0, 1000]`. + /// The range of component `c` is `[0, 1000]`. + /// The range of component `a` is `[0, 1000]`. + fn destroy(_m: u32, _c: u32, a: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `32204 + a * (366 ±0)` + // Estimated: `2523990 + a * (2954 ±0)` + // Minimum execution time: 1_224_365_000 picoseconds. + Weight::from_parts(1_281_136_346, 0) + .saturating_add(Weight::from_parts(0, 2523990)) + // Standard Error: 10_484 + .saturating_add(Weight::from_parts(6_910_740, 0).saturating_mul(a.into())) + .saturating_add(T::DbWeight::get().reads(1004)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) + .saturating_add(T::DbWeight::get().writes(1005)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(a.into()))) + .saturating_add(Weight::from_parts(0, 2954).saturating_mul(a.into())) + } + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:1) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + fn mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `455` + // Estimated: `4326` + // Minimum execution time: 50_489_000 picoseconds. + Weight::from_parts(51_045_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:1) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + fn force_mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `455` + // Estimated: `4326` + // Minimum execution time: 49_146_000 picoseconds. + Weight::from_parts(49_756_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Nfts::Attribute` (r:1 w:0) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemMetadataOf` (r:1 w:0) + /// Proof: `Nfts::ItemMetadataOf` (`max_values`: None, `max_size`: Some(347), added: 2822, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:1) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemPriceOf` (r:0 w:1) + /// Proof: `Nfts::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemAttributesApprovalsOf` (r:0 w:1) + /// Proof: `Nfts::ItemAttributesApprovalsOf` (`max_values`: None, `max_size`: Some(1001), added: 3476, mode: `MaxEncodedLen`) + /// Storage: `Nfts::PendingSwapOf` (r:0 w:1) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + fn burn() -> Weight { + // Proof Size summary in bytes: + // Measured: `564` + // Estimated: `4326` + // Minimum execution time: 56_059_000 picoseconds. + Weight::from_parts(57_162_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(7)) + } + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1 w:0) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:2) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemPriceOf` (r:0 w:1) + /// Proof: `Nfts::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + /// Storage: `Nfts::PendingSwapOf` (r:0 w:1) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + fn transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `593` + // Estimated: `4326` + // Minimum execution time: 42_406_000 picoseconds. + Weight::from_parts(43_187_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:5000 w:5000) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// The range of component `i` is `[0, 5000]`. + fn redeposit(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `763 + i * (108 ±0)` + // Estimated: `3549 + i * (3336 ±0)` + // Minimum execution time: 16_960_000 picoseconds. + Weight::from_parts(17_167_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + // Standard Error: 24_110 + .saturating_add(Weight::from_parts(18_046_970, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(i.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + .saturating_add(Weight::from_parts(0, 3336).saturating_mul(i.into())) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + fn lock_item_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `435` + // Estimated: `3534` + // Minimum execution time: 21_023_000 picoseconds. + Weight::from_parts(21_409_000, 0) + .saturating_add(Weight::from_parts(0, 3534)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + fn unlock_item_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `435` + // Estimated: `3534` + // Minimum execution time: 20_706_000 picoseconds. + Weight::from_parts(21_030_000, 0) + .saturating_add(Weight::from_parts(0, 3534)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + fn lock_collection() -> Weight { + // Proof Size summary in bytes: + // Measured: `340` + // Estimated: `3549` + // Minimum execution time: 17_449_000 picoseconds. + Weight::from_parts(17_804_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::OwnershipAcceptance` (r:1 w:1) + /// Proof: `Nfts::OwnershipAcceptance` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionAccount` (r:0 w:2) + /// Proof: `Nfts::CollectionAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn transfer_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `388` + // Estimated: `3549` + // Minimum execution time: 22_958_000 picoseconds. + Weight::from_parts(23_499_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:2 w:4) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + fn set_team() -> Weight { + // Proof Size summary in bytes: + // Measured: `369` + // Estimated: `6078` + // Minimum execution time: 40_105_000 picoseconds. + Weight::from_parts(40_800_000, 0) + .saturating_add(Weight::from_parts(0, 6078)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionAccount` (r:0 w:2) + /// Proof: `Nfts::CollectionAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn force_collection_owner() -> Weight { + // Proof Size summary in bytes: + // Measured: `311` + // Estimated: `3549` + // Minimum execution time: 17_832_000 picoseconds. + Weight::from_parts(18_297_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:0 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + fn force_collection_config() -> Weight { + // Proof Size summary in bytes: + // Measured: `276` + // Estimated: `3549` + // Minimum execution time: 15_027_000 picoseconds. + Weight::from_parts(15_370_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + fn lock_item_properties() -> Weight { + // Proof Size summary in bytes: + // Measured: `435` + // Estimated: `3534` + // Minimum execution time: 19_912_000 picoseconds. + Weight::from_parts(20_258_000, 0) + .saturating_add(Weight::from_parts(0, 3534)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1 w:1) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + fn set_attribute() -> Weight { + // Proof Size summary in bytes: + // Measured: `539` + // Estimated: `3944` + // Minimum execution time: 50_138_000 picoseconds. + Weight::from_parts(50_971_000, 0) + .saturating_add(Weight::from_parts(0, 3944)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1 w:1) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + fn force_set_attribute() -> Weight { + // Proof Size summary in bytes: + // Measured: `344` + // Estimated: `3944` + // Minimum execution time: 26_385_000 picoseconds. + Weight::from_parts(27_086_000, 0) + .saturating_add(Weight::from_parts(0, 3944)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Nfts::Attribute` (r:1 w:1) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + fn clear_attribute() -> Weight { + // Proof Size summary in bytes: + // Measured: `983` + // Estimated: `3944` + // Minimum execution time: 45_687_000 picoseconds. + Weight::from_parts(47_107_000, 0) + .saturating_add(Weight::from_parts(0, 3944)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Nfts::Item` (r:1 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemAttributesApprovalsOf` (r:1 w:1) + /// Proof: `Nfts::ItemAttributesApprovalsOf` (`max_values`: None, `max_size`: Some(1001), added: 3476, mode: `MaxEncodedLen`) + fn approve_item_attributes() -> Weight { + // Proof Size summary in bytes: + // Measured: `381` + // Estimated: `4466` + // Minimum execution time: 18_065_000 picoseconds. + Weight::from_parts(18_371_000, 0) + .saturating_add(Weight::from_parts(0, 4466)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:1 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemAttributesApprovalsOf` (r:1 w:1) + /// Proof: `Nfts::ItemAttributesApprovalsOf` (`max_values`: None, `max_size`: Some(1001), added: 3476, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1001 w:1000) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 1000]`. + fn cancel_item_attributes_approval(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `760 + n * (398 ±0)` + // Estimated: `4466 + n * (2954 ±0)` + // Minimum execution time: 26_680_000 picoseconds. + Weight::from_parts(27_010_000, 0) + .saturating_add(Weight::from_parts(0, 4466)) + // Standard Error: 6_351 + .saturating_add(Weight::from_parts(6_584_290, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().writes(2)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) + .saturating_add(Weight::from_parts(0, 2954).saturating_mul(n.into())) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemMetadataOf` (r:1 w:1) + /// Proof: `Nfts::ItemMetadataOf` (`max_values`: None, `max_size`: Some(347), added: 2822, mode: `MaxEncodedLen`) + fn set_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `539` + // Estimated: `3812` + // Minimum execution time: 42_038_000 picoseconds. + Weight::from_parts(42_758_000, 0) + .saturating_add(Weight::from_parts(0, 3812)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemMetadataOf` (r:1 w:1) + /// Proof: `Nfts::ItemMetadataOf` (`max_values`: None, `max_size`: Some(347), added: 2822, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + fn clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `849` + // Estimated: `3812` + // Minimum execution time: 40_220_000 picoseconds. + Weight::from_parts(41_026_000, 0) + .saturating_add(Weight::from_parts(0, 3812)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionMetadataOf` (r:1 w:1) + /// Proof: `Nfts::CollectionMetadataOf` (`max_values`: None, `max_size`: Some(294), added: 2769, mode: `MaxEncodedLen`) + fn set_collection_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `398` + // Estimated: `3759` + // Minimum execution time: 38_135_000 picoseconds. + Weight::from_parts(38_561_000, 0) + .saturating_add(Weight::from_parts(0, 3759)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionMetadataOf` (r:1 w:1) + /// Proof: `Nfts::CollectionMetadataOf` (`max_values`: None, `max_size`: Some(294), added: 2769, mode: `MaxEncodedLen`) + fn clear_collection_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `716` + // Estimated: `3759` + // Minimum execution time: 37_583_000 picoseconds. + Weight::from_parts(38_215_000, 0) + .saturating_add(Weight::from_parts(0, 3759)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + fn approve_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `410` + // Estimated: `4326` + // Minimum execution time: 21_405_000 picoseconds. + Weight::from_parts(21_803_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + fn cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `418` + // Estimated: `4326` + // Minimum execution time: 18_713_000 picoseconds. + Weight::from_parts(19_185_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + fn clear_all_transfer_approvals() -> Weight { + // Proof Size summary in bytes: + // Measured: `418` + // Estimated: `4326` + // Minimum execution time: 17_803_000 picoseconds. + Weight::from_parts(18_270_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::OwnershipAcceptance` (r:1 w:1) + /// Proof: `Nfts::OwnershipAcceptance` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + fn set_accept_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `3517` + // Minimum execution time: 15_982_000 picoseconds. + Weight::from_parts(16_700_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + fn set_collection_max_supply() -> Weight { + // Proof Size summary in bytes: + // Measured: `340` + // Estimated: `3549` + // Minimum execution time: 19_501_000 picoseconds. + Weight::from_parts(19_785_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + fn update_mint_settings() -> Weight { + // Proof Size summary in bytes: + // Measured: `323` + // Estimated: `3538` + // Minimum execution time: 18_914_000 picoseconds. + Weight::from_parts(19_292_000, 0) + .saturating_add(Weight::from_parts(0, 3538)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:1 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemPriceOf` (r:0 w:1) + /// Proof: `Nfts::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + fn set_price() -> Weight { + // Proof Size summary in bytes: + // Measured: `518` + // Estimated: `4326` + // Minimum execution time: 24_625_000 picoseconds. + Weight::from_parts(25_257_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemPriceOf` (r:1 w:1) + /// Proof: `Nfts::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1 w:0) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:2) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Nfts::PendingSwapOf` (r:0 w:1) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + fn buy_item() -> Weight { + // Proof Size summary in bytes: + // Measured: `705` + // Estimated: `4326` + // Minimum execution time: 50_833_000 picoseconds. + Weight::from_parts(52_161_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// The range of component `n` is `[0, 10]`. + fn pay_tips(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_220_000 picoseconds. + Weight::from_parts(3_476_001, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 7_084 + .saturating_add(Weight::from_parts(3_844_820, 0).saturating_mul(n.into())) + } + /// Storage: `Nfts::Item` (r:2 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::PendingSwapOf` (r:0 w:1) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + fn create_swap() -> Weight { + // Proof Size summary in bytes: + // Measured: `494` + // Estimated: `7662` + // Minimum execution time: 21_983_000 picoseconds. + Weight::from_parts(22_746_000, 0) + .saturating_add(Weight::from_parts(0, 7662)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::PendingSwapOf` (r:1 w:1) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + fn cancel_swap() -> Weight { + // Proof Size summary in bytes: + // Measured: `513` + // Estimated: `4326` + // Minimum execution time: 20_875_000 picoseconds. + Weight::from_parts(21_465_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:2 w:2) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::PendingSwapOf` (r:1 w:2) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:2 w:0) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:2 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:4) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemPriceOf` (r:0 w:2) + /// Proof: `Nfts::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + fn claim_swap() -> Weight { + // Proof Size summary in bytes: + // Measured: `834` + // Estimated: `7662` + // Minimum execution time: 84_771_000 picoseconds. + Weight::from_parts(86_078_000, 0) + .saturating_add(Weight::from_parts(0, 7662)) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(10)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:2 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:10 w:10) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemMetadataOf` (r:1 w:1) + /// Proof: `Nfts::ItemMetadataOf` (`max_values`: None, `max_size`: Some(347), added: 2822, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:1) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 10]`. + fn mint_pre_signed(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `558` + // Estimated: `6078 + n * (2954 ±0)` + // Minimum execution time: 143_265_000 picoseconds. + Weight::from_parts(150_978_773, 0) + .saturating_add(Weight::from_parts(0, 6078)) + // Standard Error: 49_443 + .saturating_add(Weight::from_parts(31_888_255, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().writes(6)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) + .saturating_add(Weight::from_parts(0, 2954).saturating_mul(n.into())) + } + /// Storage: `Nfts::Item` (r:1 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemAttributesApprovalsOf` (r:1 w:1) + /// Proof: `Nfts::ItemAttributesApprovalsOf` (`max_values`: None, `max_size`: Some(1001), added: 3476, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:10 w:10) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 10]`. + fn set_attributes_pre_signed(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `588` + // Estimated: `4466 + n * (2954 ±0)` + // Minimum execution time: 83_754_000 picoseconds. + Weight::from_parts(96_685_026, 0) + .saturating_add(Weight::from_parts(0, 4466)) + // Standard Error: 72_592 + .saturating_add(Weight::from_parts(30_914_858, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().writes(2)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) + .saturating_add(Weight::from_parts(0, 2954).saturating_mul(n.into())) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_proxy.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_proxy.rs new file mode 100644 index 00000000000..0cdffc653bc --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_proxy.rs @@ -0,0 +1,225 @@ +// 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. + +//! Autogenerated weights for `pallet_proxy` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_proxy +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_proxy`. +pub struct WeightInfo(PhantomData); +impl pallet_proxy::WeightInfo for WeightInfo { + /// Storage: `Proxy::Proxies` (r:1 w:0) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn proxy(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `127 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 16_417_000 picoseconds. + Weight::from_parts(17_283_443, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 2_409 + .saturating_add(Weight::from_parts(32_123, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:0) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// Storage: `Proxy::Announcements` (r:1 w:1) + /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 31]`. + /// The range of component `p` is `[1, 31]`. + fn proxy_announced(a: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `454 + a * (68 ±0) + p * (37 ±0)` + // Estimated: `5698` + // Minimum execution time: 37_572_000 picoseconds. + Weight::from_parts(37_045_756, 0) + .saturating_add(Weight::from_parts(0, 5698)) + // Standard Error: 2_896 + .saturating_add(Weight::from_parts(139_561, 0).saturating_mul(a.into())) + // Standard Error: 2_993 + .saturating_add(Weight::from_parts(73_270, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Proxy::Announcements` (r:1 w:1) + /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 31]`. + /// The range of component `p` is `[1, 31]`. + fn remove_announcement(a: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `369 + a * (68 ±0)` + // Estimated: `5698` + // Minimum execution time: 24_066_000 picoseconds. + Weight::from_parts(24_711_403, 0) + .saturating_add(Weight::from_parts(0, 5698)) + // Standard Error: 1_626 + .saturating_add(Weight::from_parts(128_391, 0).saturating_mul(a.into())) + // Standard Error: 1_680 + .saturating_add(Weight::from_parts(23_124, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Proxy::Announcements` (r:1 w:1) + /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 31]`. + /// The range of component `p` is `[1, 31]`. + fn reject_announcement(a: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `369 + a * (68 ±0)` + // Estimated: `5698` + // Minimum execution time: 24_162_000 picoseconds. + Weight::from_parts(23_928_058, 0) + .saturating_add(Weight::from_parts(0, 5698)) + // Standard Error: 2_072 + .saturating_add(Weight::from_parts(152_299, 0).saturating_mul(a.into())) + // Standard Error: 2_141 + .saturating_add(Weight::from_parts(39_775, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Proxy::Proxies` (r:1 w:0) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// Storage: `Proxy::Announcements` (r:1 w:1) + /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 31]`. + /// The range of component `p` is `[1, 31]`. + fn announce(a: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `386 + a * (68 ±0) + p * (37 ±0)` + // Estimated: `5698` + // Minimum execution time: 33_858_000 picoseconds. + Weight::from_parts(33_568_059, 0) + .saturating_add(Weight::from_parts(0, 5698)) + // Standard Error: 1_816 + .saturating_add(Weight::from_parts(134_400, 0).saturating_mul(a.into())) + // Standard Error: 1_876 + .saturating_add(Weight::from_parts(57_028, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn add_proxy(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `127 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 24_947_000 picoseconds. + Weight::from_parts(26_235_199, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 1_363 + .saturating_add(Weight::from_parts(41_435, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn remove_proxy(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `127 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 25_186_000 picoseconds. + Weight::from_parts(26_823_133, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 2_259 + .saturating_add(Weight::from_parts(34_224, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn remove_proxies(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `127 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 22_156_000 picoseconds. + Weight::from_parts(23_304_060, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 1_738 + .saturating_add(Weight::from_parts(39_612, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn create_pure(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `139` + // Estimated: `4706` + // Minimum execution time: 26_914_000 picoseconds. + Weight::from_parts(28_009_062, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 1_978 + .saturating_add(Weight::from_parts(12_255, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[0, 30]`. + fn kill_pure(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `164 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 23_281_000 picoseconds. + Weight::from_parts(24_392_989, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 2_943 + .saturating_add(Weight::from_parts(30_287, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_session.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_session.rs new file mode 100644 index 00000000000..73c3c06945d --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_session.rs @@ -0,0 +1,80 @@ +// 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. + +//! Autogenerated weights for `pallet_session` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_session +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_session`. +pub struct WeightInfo(PhantomData); +impl pallet_session::WeightInfo for WeightInfo { + /// Storage: `Session::NextKeys` (r:1 w:1) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Session::KeyOwner` (r:1 w:1) + /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn set_keys() -> Weight { + // Proof Size summary in bytes: + // Measured: `270` + // Estimated: `3735` + // Minimum execution time: 16_932_000 picoseconds. + Weight::from_parts(17_357_000, 0) + .saturating_add(Weight::from_parts(0, 3735)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Session::NextKeys` (r:1 w:1) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Session::KeyOwner` (r:0 w:1) + /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn purge_keys() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `3707` + // Minimum execution time: 12_157_000 picoseconds. + Weight::from_parts(12_770_000, 0) + .saturating_add(Weight::from_parts(0, 3707)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_timestamp.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_timestamp.rs new file mode 100644 index 00000000000..e27289a49e9 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_timestamp.rs @@ -0,0 +1,74 @@ +// 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. + +//! Autogenerated weights for `pallet_timestamp` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_timestamp +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_timestamp`. +pub struct WeightInfo(PhantomData); +impl pallet_timestamp::WeightInfo for WeightInfo { + /// Storage: `Timestamp::Now` (r:1 w:1) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `Aura::CurrentSlot` (r:1 w:0) + /// Proof: `Aura::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + fn set() -> Weight { + // Proof Size summary in bytes: + // Measured: `86` + // Estimated: `1493` + // Minimum execution time: 9_313_000 picoseconds. + Weight::from_parts(9_775_000, 0) + .saturating_add(Weight::from_parts(0, 1493)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn on_finalize() -> Weight { + // Proof Size summary in bytes: + // Measured: `57` + // Estimated: `0` + // Minimum execution time: 3_322_000 picoseconds. + Weight::from_parts(3_577_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_uniques.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_uniques.rs new file mode 100644 index 00000000000..69d3e773afb --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_uniques.rs @@ -0,0 +1,466 @@ +// 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. + +//! Autogenerated weights for `pallet_uniques` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_uniques +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_uniques`. +pub struct WeightInfo(PhantomData); +impl pallet_uniques::WeightInfo for WeightInfo { + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassAccount` (r:0 w:1) + /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn create() -> Weight { + // Proof Size summary in bytes: + // Measured: `145` + // Estimated: `3643` + // Minimum execution time: 28_845_000 picoseconds. + Weight::from_parts(29_675_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassAccount` (r:0 w:1) + /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn force_create() -> Weight { + // Proof Size summary in bytes: + // Measured: `42` + // Estimated: `3643` + // Minimum execution time: 13_492_000 picoseconds. + Weight::from_parts(14_049_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:1001 w:1000) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::InstanceMetadataOf` (r:1000 w:1000) + /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Attribute` (r:1000 w:1000) + /// Proof: `Uniques::Attribute` (`max_values`: None, `max_size`: Some(172), added: 2647, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassAccount` (r:0 w:1) + /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassMetadataOf` (r:0 w:1) + /// Proof: `Uniques::ClassMetadataOf` (`max_values`: None, `max_size`: Some(167), added: 2642, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Account` (r:0 w:1000) + /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Uniques::CollectionMaxSupply` (r:0 w:1) + /// Proof: `Uniques::CollectionMaxSupply` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 1000]`. + /// The range of component `m` is `[0, 1000]`. + /// The range of component `a` is `[0, 1000]`. + fn destroy(n: u32, m: u32, a: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `257 + a * (107 ±0) + m * (56 ±0) + n * (76 ±0)` + // Estimated: `3643 + a * (2647 ±0) + m * (2662 ±0) + n * (2597 ±0)` + // Minimum execution time: 2_920_070_000 picoseconds. + Weight::from_parts(2_983_862_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + // Standard Error: 36_415 + .saturating_add(Weight::from_parts(7_589_778, 0).saturating_mul(n.into())) + // Standard Error: 36_415 + .saturating_add(Weight::from_parts(479_496, 0).saturating_mul(m.into())) + // Standard Error: 36_415 + .saturating_add(Weight::from_parts(562_056, 0).saturating_mul(a.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(m.into()))) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) + .saturating_add(T::DbWeight::get().writes(4)) + .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(m.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(a.into()))) + .saturating_add(Weight::from_parts(0, 2647).saturating_mul(a.into())) + .saturating_add(Weight::from_parts(0, 2662).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 2597).saturating_mul(n.into())) + } + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::CollectionMaxSupply` (r:1 w:0) + /// Proof: `Uniques::CollectionMaxSupply` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Account` (r:0 w:1) + /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + fn mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 35_329_000 picoseconds. + Weight::from_parts(36_019_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Account` (r:0 w:1) + /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ItemPriceOf` (r:0 w:1) + /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + fn burn() -> Weight { + // Proof Size summary in bytes: + // Measured: `428` + // Estimated: `3643` + // Minimum execution time: 36_474_000 picoseconds. + Weight::from_parts(37_190_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Account` (r:0 w:2) + /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ItemPriceOf` (r:0 w:1) + /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + fn transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `428` + // Estimated: `3643` + // Minimum execution time: 26_786_000 picoseconds. + Weight::from_parts(27_400_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:5000 w:5000) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// The range of component `i` is `[0, 5000]`. + fn redeposit(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `738 + i * (76 ±0)` + // Estimated: `3643 + i * (2597 ±0)` + // Minimum execution time: 14_546_000 picoseconds. + Weight::from_parts(14_831_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + // Standard Error: 24_362 + .saturating_add(Weight::from_parts(17_972_938, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(i.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + .saturating_add(Weight::from_parts(0, 2597).saturating_mul(i.into())) + } + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + fn freeze() -> Weight { + // Proof Size summary in bytes: + // Measured: `428` + // Estimated: `3643` + // Minimum execution time: 18_919_000 picoseconds. + Weight::from_parts(19_547_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + fn thaw() -> Weight { + // Proof Size summary in bytes: + // Measured: `428` + // Estimated: `3643` + // Minimum execution time: 18_643_000 picoseconds. + Weight::from_parts(19_000_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + fn freeze_collection() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 13_530_000 picoseconds. + Weight::from_parts(14_165_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + fn thaw_collection() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 13_523_000 picoseconds. + Weight::from_parts(14_055_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::OwnershipAcceptance` (r:1 w:1) + /// Proof: `Uniques::OwnershipAcceptance` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassAccount` (r:0 w:2) + /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn transfer_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `356` + // Estimated: `3643` + // Minimum execution time: 22_131_000 picoseconds. + Weight::from_parts(22_628_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + fn set_team() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 13_841_000 picoseconds. + Weight::from_parts(14_408_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassAccount` (r:0 w:1) + /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn force_item_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 16_954_000 picoseconds. + Weight::from_parts(17_482_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::InstanceMetadataOf` (r:1 w:0) + /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Attribute` (r:1 w:1) + /// Proof: `Uniques::Attribute` (`max_values`: None, `max_size`: Some(172), added: 2647, mode: `MaxEncodedLen`) + fn set_attribute() -> Weight { + // Proof Size summary in bytes: + // Measured: `559` + // Estimated: `3652` + // Minimum execution time: 38_493_000 picoseconds. + Weight::from_parts(39_513_000, 0) + .saturating_add(Weight::from_parts(0, 3652)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::InstanceMetadataOf` (r:1 w:0) + /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Attribute` (r:1 w:1) + /// Proof: `Uniques::Attribute` (`max_values`: None, `max_size`: Some(172), added: 2647, mode: `MaxEncodedLen`) + fn clear_attribute() -> Weight { + // Proof Size summary in bytes: + // Measured: `756` + // Estimated: `3652` + // Minimum execution time: 37_918_000 picoseconds. + Weight::from_parts(38_666_000, 0) + .saturating_add(Weight::from_parts(0, 3652)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::InstanceMetadataOf` (r:1 w:1) + /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) + fn set_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `348` + // Estimated: `3652` + // Minimum execution time: 29_810_000 picoseconds. + Weight::from_parts(30_363_000, 0) + .saturating_add(Weight::from_parts(0, 3652)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::InstanceMetadataOf` (r:1 w:1) + /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) + fn clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `559` + // Estimated: `3652` + // Minimum execution time: 30_877_000 picoseconds. + Weight::from_parts(31_430_000, 0) + .saturating_add(Weight::from_parts(0, 3652)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassMetadataOf` (r:1 w:1) + /// Proof: `Uniques::ClassMetadataOf` (`max_values`: None, `max_size`: Some(167), added: 2642, mode: `MaxEncodedLen`) + fn set_collection_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 30_478_000 picoseconds. + Weight::from_parts(31_065_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassMetadataOf` (r:1 w:1) + /// Proof: `Uniques::ClassMetadataOf` (`max_values`: None, `max_size`: Some(167), added: 2642, mode: `MaxEncodedLen`) + fn clear_collection_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `473` + // Estimated: `3643` + // Minimum execution time: 29_582_000 picoseconds. + Weight::from_parts(30_160_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + fn approve_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `428` + // Estimated: `3643` + // Minimum execution time: 19_328_000 picoseconds. + Weight::from_parts(19_866_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + fn cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `461` + // Estimated: `3643` + // Minimum execution time: 19_131_000 picoseconds. + Weight::from_parts(19_569_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::OwnershipAcceptance` (r:1 w:1) + /// Proof: `Uniques::OwnershipAcceptance` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + fn set_accept_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `42` + // Estimated: `3517` + // Minimum execution time: 15_212_000 picoseconds. + Weight::from_parts(15_691_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::CollectionMaxSupply` (r:1 w:1) + /// Proof: `Uniques::CollectionMaxSupply` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + fn set_collection_max_supply() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 16_290_000 picoseconds. + Weight::from_parts(16_654_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Asset` (r:1 w:0) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ItemPriceOf` (r:0 w:1) + /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + fn set_price() -> Weight { + // Proof Size summary in bytes: + // Measured: `259` + // Estimated: `3587` + // Minimum execution time: 16_095_000 picoseconds. + Weight::from_parts(16_555_000, 0) + .saturating_add(Weight::from_parts(0, 3587)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ItemPriceOf` (r:1 w:1) + /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Account` (r:0 w:2) + /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + fn buy_item() -> Weight { + // Proof Size summary in bytes: + // Measured: `540` + // Estimated: `3643` + // Minimum execution time: 35_506_000 picoseconds. + Weight::from_parts(36_305_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(4)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_utility.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_utility.rs new file mode 100644 index 00000000000..e6c3e1295ef --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_utility.rs @@ -0,0 +1,101 @@ +// 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. + +//! Autogenerated weights for `pallet_utility` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_utility +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_utility`. +pub struct WeightInfo(PhantomData); +impl pallet_utility::WeightInfo for WeightInfo { + /// The range of component `c` is `[0, 1000]`. + fn batch(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_103_000 picoseconds. + Weight::from_parts(7_226_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 2_732 + .saturating_add(Weight::from_parts(6_560_347, 0).saturating_mul(c.into())) + } + fn as_derivative() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 5_208_000 picoseconds. + Weight::from_parts(5_480_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// The range of component `c` is `[0, 1000]`. + fn batch_all(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_070_000 picoseconds. + Weight::from_parts(1_321_270, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 3_454 + .saturating_add(Weight::from_parts(6_864_640, 0).saturating_mul(c.into())) + } + fn dispatch_as() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 9_255_000 picoseconds. + Weight::from_parts(9_683_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// The range of component `c` is `[0, 1000]`. + fn force_batch(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_852_000 picoseconds. + Weight::from_parts(7_007_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_745 + .saturating_add(Weight::from_parts(6_562_902, 0).saturating_mul(c.into())) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_xcm.rs new file mode 100644 index 00000000000..1e4a723e10f --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/pallet_xcm.rs @@ -0,0 +1,324 @@ +// 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 . + +//! Autogenerated weights for `pallet_xcm` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-11-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_xcm +// --chain=asset-hub-kusama-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_xcm`. +pub struct WeightInfo(PhantomData); +impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn send() -> Weight { + // Proof Size summary in bytes: + // Measured: `145` + // Estimated: `3610` + // Minimum execution time: 25_043_000 picoseconds. + Weight::from_parts(25_670_000, 0) + .saturating_add(Weight::from_parts(0, 3610)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn teleport_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `1489` + // Minimum execution time: 18_893_000 picoseconds. + Weight::from_parts(19_261_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + .saturating_add(T::DbWeight::get().reads(1)) + } + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn reserve_transfer_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `1489` + // Minimum execution time: 14_107_000 picoseconds. + Weight::from_parts(14_500_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + .saturating_add(T::DbWeight::get().reads(1)) + } + /// Storage: `Benchmark::Override` (r:0 w:0) + /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn execute() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 18_446_744_073_709_551_000 picoseconds. + Weight::from_parts(18_446_744_073_709_551_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: `PolkadotXcm::SupportedVersion` (r:0 w:1) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_xcm_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_175_000 picoseconds. + Weight::from_parts(7_493_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:0 w:1) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn force_default_xcm_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_162_000 picoseconds. + Weight::from_parts(2_278_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_subscribe_version_notify() -> Weight { + // Proof Size summary in bytes: + // Measured: `145` + // Estimated: `3610` + // Minimum execution time: 29_144_000 picoseconds. + Weight::from_parts(30_134_000, 0) + .saturating_add(Weight::from_parts(0, 3610)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_unsubscribe_version_notify() -> Weight { + // Proof Size summary in bytes: + // Measured: `363` + // Estimated: `3828` + // Minimum execution time: 31_522_000 picoseconds. + Weight::from_parts(32_679_000, 0) + .saturating_add(Weight::from_parts(0, 3828)) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PolkadotXcm::XcmExecutionSuspended` (r:0 w:1) + /// Proof: `PolkadotXcm::XcmExecutionSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn force_suspension() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_338_000 picoseconds. + Weight::from_parts(2_494_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::SupportedVersion` (r:4 w:2) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_supported_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `162` + // Estimated: `11052` + // Minimum execution time: 17_315_000 picoseconds. + Weight::from_parts(17_787_000, 0) + .saturating_add(Weight::from_parts(0, 11052)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_version_notifiers() -> Weight { + // Proof Size summary in bytes: + // Measured: `166` + // Estimated: `11056` + // Minimum execution time: 17_273_000 picoseconds. + Weight::from_parts(17_712_000, 0) + .saturating_add(Weight::from_parts(0, 11056)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:5 w:0) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn already_notified_target() -> Weight { + // Proof Size summary in bytes: + // Measured: `173` + // Estimated: `13538` + // Minimum execution time: 18_395_000 picoseconds. + Weight::from_parts(19_095_000, 0) + .saturating_add(Weight::from_parts(0, 13538)) + .saturating_add(T::DbWeight::get().reads(5)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:2 w:1) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn notify_current_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `212` + // Estimated: `6152` + // Minimum execution time: 27_343_000 picoseconds. + Weight::from_parts(28_068_000, 0) + .saturating_add(Weight::from_parts(0, 6152)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:3 w:0) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn notify_target_migration_fail() -> Weight { + // Proof Size summary in bytes: + // Measured: `206` + // Estimated: `8621` + // Minimum execution time: 9_156_000 picoseconds. + Weight::from_parts(9_552_000, 0) + .saturating_add(Weight::from_parts(0, 8621)) + .saturating_add(T::DbWeight::get().reads(3)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_version_notify_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `173` + // Estimated: `11063` + // Minimum execution time: 17_454_000 picoseconds. + Weight::from_parts(17_831_000, 0) + .saturating_add(Weight::from_parts(0, 11063)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn migrate_and_notify_old_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `215` + // Estimated: `11105` + // Minimum execution time: 34_299_000 picoseconds. + Weight::from_parts(35_156_000, 0) + .saturating_add(Weight::from_parts(0, 11105)) + .saturating_add(T::DbWeight::get().reads(10)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn new_query() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `1588` + // Minimum execution time: 4_508_000 picoseconds. + Weight::from_parts(4_702_000, 0) + .saturating_add(Weight::from_parts(0, 1588)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::Queries` (r:1 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn take_response() -> Weight { + // Proof Size summary in bytes: + // Measured: `7740` + // Estimated: `11205` + // Minimum execution time: 26_557_000 picoseconds. + Weight::from_parts(26_980_000, 0) + .saturating_add(Weight::from_parts(0, 11205)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/paritydb_weights.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/paritydb_weights.rs new file mode 100644 index 00000000000..25679703831 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/paritydb_weights.rs @@ -0,0 +1,63 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; + + parameter_types! { + /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights + /// are available for brave runtime engineers who may want to try this out as default. + pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + }; + } + + #[cfg(test)] + mod test_db_weights { + use super::constants::ParityDbWeight as W; + use frame_support::weights::constants; + + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Write weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/rocksdb_weights.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/rocksdb_weights.rs new file mode 100644 index 00000000000..3dd817aa6f1 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/rocksdb_weights.rs @@ -0,0 +1,63 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; + + parameter_types! { + /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout + /// the runtime. + pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + }; + } + + #[cfg(test)] + mod test_db_weights { + use super::constants::RocksDbWeight as W; + use frame_support::weights::constants; + + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Write weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/mod.rs new file mode 100644 index 00000000000..405d7c72e55 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/mod.rs @@ -0,0 +1,244 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +mod pallet_xcm_benchmarks_fungible; +mod pallet_xcm_benchmarks_generic; + +use crate::{xcm_config::MaxAssetsIntoHolding, Runtime}; +use frame_support::weights::Weight; +use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; +use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; +use sp_std::prelude::*; +use xcm::{latest::prelude::*, DoubleEncoded}; + +trait WeighMultiAssets { + fn weigh_multi_assets(&self, weight: Weight) -> Weight; +} + +const MAX_ASSETS: u64 = 100; + +impl WeighMultiAssets for MultiAssetFilter { + fn weigh_multi_assets(&self, weight: Weight) -> Weight { + match self { + Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64), + Self::Wild(asset) => match asset { + All => weight.saturating_mul(MAX_ASSETS), + AllOf { fun, .. } => match fun { + WildFungibility::Fungible => weight, + // Magic number 2 has to do with the fact that we could have up to 2 times + // MaxAssetsIntoHolding in the worst-case scenario. + WildFungibility::NonFungible => + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + }, + AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), + AllOfCounted { count, .. } => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), + }, + } + } +} + +impl WeighMultiAssets for MultiAssets { + fn weigh_multi_assets(&self, weight: Weight) -> Weight { + weight.saturating_mul(self.inner().iter().count() as u64) + } +} + +pub struct AssetHubKusamaXcmWeight(core::marker::PhantomData); +impl XcmWeightInfo for AssetHubKusamaXcmWeight { + fn withdraw_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + } + fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::reserve_asset_deposited()) + } + fn receive_teleported_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + } + fn query_response( + _query_id: &u64, + _response: &Response, + _max_weight: &Weight, + _querier: &Option, + ) -> Weight { + XcmGeneric::::query_response() + } + fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + } + fn transfer_reserve_asset( + assets: &MultiAssets, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + } + fn transact( + _origin_type: &OriginKind, + _require_weight_at_most: &Weight, + _call: &DoubleEncoded, + ) -> Weight { + XcmGeneric::::transact() + } + fn hrmp_new_channel_open_request( + _sender: &u32, + _max_message_size: &u32, + _max_capacity: &u32, + ) -> Weight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX + } + fn hrmp_channel_accepted(_recipient: &u32) -> Weight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX + } + fn hrmp_channel_closing(_initiator: &u32, _sender: &u32, _recipient: &u32) -> Weight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX + } + fn clear_origin() -> Weight { + XcmGeneric::::clear_origin() + } + fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + XcmGeneric::::descend_origin() + } + fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::report_error() + } + + fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()) + } + fn deposit_reserve_asset( + assets: &MultiAssetFilter, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + } + fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + Weight::MAX + } + fn initiate_reserve_withdraw( + assets: &MultiAssetFilter, + _reserve: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) + } + fn initiate_teleport( + assets: &MultiAssetFilter, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()) + } + fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + XcmGeneric::::report_holding() + } + fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + XcmGeneric::::buy_execution() + } + fn refund_surplus() -> Weight { + XcmGeneric::::refund_surplus() + } + fn set_error_handler(_xcm: &Xcm) -> Weight { + XcmGeneric::::set_error_handler() + } + fn set_appendix(_xcm: &Xcm) -> Weight { + XcmGeneric::::set_appendix() + } + fn clear_error() -> Weight { + XcmGeneric::::clear_error() + } + fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + XcmGeneric::::claim_asset() + } + fn trap(_code: &u64) -> Weight { + XcmGeneric::::trap() + } + fn subscribe_version(_query_id: &QueryId, _max_response_weight: &Weight) -> Weight { + XcmGeneric::::subscribe_version() + } + fn unsubscribe_version() -> Weight { + XcmGeneric::::unsubscribe_version() + } + fn burn_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + } + fn expect_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + } + fn expect_origin(_origin: &Option) -> Weight { + XcmGeneric::::expect_origin() + } + fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { + XcmGeneric::::expect_error() + } + fn expect_transact_status(_transact_status: &MaybeErrorCode) -> Weight { + XcmGeneric::::expect_transact_status() + } + fn query_pallet(_module_name: &Vec, _response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::query_pallet() + } + fn expect_pallet( + _index: &u32, + _name: &Vec, + _module_name: &Vec, + _crate_major: &u32, + _min_crate_minor: &u32, + ) -> Weight { + XcmGeneric::::expect_pallet() + } + fn report_transact_status(_response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::report_transact_status() + } + fn clear_transact_status() -> Weight { + XcmGeneric::::clear_transact_status() + } + fn universal_origin(_: &Junction) -> Weight { + Weight::MAX + } + fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight { + Weight::MAX + } + fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn set_fees_mode(_: &bool) -> Weight { + XcmGeneric::::set_fees_mode() + } + fn set_topic(_topic: &[u8; 32]) -> Weight { + XcmGeneric::::set_topic() + } + fn clear_topic() -> Weight { + XcmGeneric::::clear_topic() + } + fn alias_origin(_: &MultiLocation) -> Weight { + // XCM Executor does not currently support alias origin operations + Weight::MAX + } + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + XcmGeneric::::unpaid_execution() + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs new file mode 100644 index 00000000000..e680c2d5c11 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -0,0 +1,187 @@ +// 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. + +//! Autogenerated weights for `pallet_xcm_benchmarks::fungible` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-09-28, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-nbnwcyh-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: Compiled, CHAIN: Some("asset-hub-kusama-dev"), DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_xcm_benchmarks::fungible +// --chain=asset-hub-kusama-dev +// --header=./cumulus/file_header.txt +// --template=./cumulus/templates/xcm-bench-template.hbs +// --output=./cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weights for `pallet_xcm_benchmarks::fungible`. +pub struct WeightInfo(PhantomData); +impl WeightInfo { + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + pub fn withdraw_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `101` + // Estimated: `3593` + // Minimum execution time: 25_602_000 picoseconds. + Weight::from_parts(26_312_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + // Storage: `System::Account` (r:2 w:2) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + pub fn transfer_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `101` + // Estimated: `6196` + // Minimum execution time: 51_173_000 picoseconds. + Weight::from_parts(52_221_000, 6196) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + // Storage: `System::Account` (r:2 w:2) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn transfer_reserve_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `246` + // Estimated: `6196` + // Minimum execution time: 74_651_000 picoseconds. + Weight::from_parts(76_500_000, 6196) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(4)) + } + // Storage: `Benchmark::Override` (r:0 w:0) + // Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn reserve_asset_deposited() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 18_446_744_073_709_551_000 picoseconds. + Weight::from_parts(18_446_744_073_709_551_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_reserve_withdraw() -> Weight { + // Proof Size summary in bytes: + // Measured: `145` + // Estimated: `3610` + // Minimum execution time: 458_666_000 picoseconds. + Weight::from_parts(470_470_000, 3610) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn receive_teleported_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_701_000 picoseconds. + Weight::from_parts(3_887_000, 0) + } + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + pub fn deposit_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 25_709_000 picoseconds. + Weight::from_parts(26_320_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn deposit_reserve_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `145` + // Estimated: `3610` + // Minimum execution time: 51_663_000 picoseconds. + Weight::from_parts(52_538_000, 3610) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(3)) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_teleport() -> Weight { + // Proof Size summary in bytes: + // Measured: `145` + // Estimated: `3610` + // Minimum execution time: 31_972_000 picoseconds. + Weight::from_parts(32_834_000, 3610) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_generic.rs new file mode 100644 index 00000000000..9e8f3bfe75c --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -0,0 +1,328 @@ +// 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. + +//! Autogenerated weights for `pallet_xcm_benchmarks::generic` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: , WASM-EXECUTION: Compiled, CHAIN: Some("asset-hub-kusama-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --template=./templates/xcm-bench-template.hbs +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_xcm_benchmarks::generic +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_generic.rs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weights for `pallet_xcm_benchmarks::generic`. +pub struct WeightInfo(PhantomData); +impl WeightInfo { + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn report_holding() -> Weight { + // Proof Size summary in bytes: + // Measured: `109` + // Estimated: `3574` + // Minimum execution time: 432_196_000 picoseconds. + Weight::from_parts(438_017_000, 3574) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn buy_execution() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_223_000 picoseconds. + Weight::from_parts(4_412_000, 0) + } + // Storage: `PolkadotXcm::Queries` (r:1 w:0) + // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn query_response() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `3568` + // Minimum execution time: 11_582_000 picoseconds. + Weight::from_parts(11_830_000, 3568) + .saturating_add(T::DbWeight::get().reads(1)) + } + pub fn transact() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 13_955_000 picoseconds. + Weight::from_parts(14_320_000, 0) + } + pub fn refund_surplus() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_423_000 picoseconds. + Weight::from_parts(4_709_000, 0) + } + pub fn set_error_handler() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_028_000 picoseconds. + Weight::from_parts(3_151_000, 0) + } + pub fn set_appendix() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_966_000 picoseconds. + Weight::from_parts(3_076_000, 0) + } + pub fn clear_error() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_971_000 picoseconds. + Weight::from_parts(3_119_000, 0) + } + pub fn descend_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_772_000 picoseconds. + Weight::from_parts(3_853_000, 0) + } + pub fn clear_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_940_000 picoseconds. + Weight::from_parts(3_050_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn report_error() -> Weight { + // Proof Size summary in bytes: + // Measured: `109` + // Estimated: `3574` + // Minimum execution time: 27_734_000 picoseconds. + Weight::from_parts(28_351_000, 3574) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + // Storage: `PolkadotXcm::AssetTraps` (r:1 w:1) + // Proof: `PolkadotXcm::AssetTraps` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn claim_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `160` + // Estimated: `3625` + // Minimum execution time: 16_456_000 picoseconds. + Weight::from_parts(16_846_000, 3625) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + pub fn trap() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_974_000 picoseconds. + Weight::from_parts(3_108_000, 0) + } + // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) + // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn subscribe_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `109` + // Estimated: `3574` + // Minimum execution time: 29_823_000 picoseconds. + Weight::from_parts(30_776_000, 3574) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(3)) + } + // Storage: `PolkadotXcm::VersionNotifyTargets` (r:0 w:1) + // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn unsubscribe_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_966_000 picoseconds. + Weight::from_parts(5_157_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) + } + pub fn burn_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 141_875_000 picoseconds. + Weight::from_parts(144_925_000, 0) + } + pub fn expect_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 13_147_000 picoseconds. + Weight::from_parts(13_420_000, 0) + } + pub fn expect_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_050_000 picoseconds. + Weight::from_parts(3_161_000, 0) + } + pub fn expect_error() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_930_000 picoseconds. + Weight::from_parts(3_077_000, 0) + } + pub fn expect_transact_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_188_000 picoseconds. + Weight::from_parts(3_299_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn query_pallet() -> Weight { + // Proof Size summary in bytes: + // Measured: `109` + // Estimated: `3574` + // Minimum execution time: 31_678_000 picoseconds. + Weight::from_parts(32_462_000, 3574) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn expect_pallet() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 5_638_000 picoseconds. + Weight::from_parts(5_756_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn report_transact_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `109` + // Estimated: `3574` + // Minimum execution time: 27_556_000 picoseconds. + Weight::from_parts(28_240_000, 3574) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn clear_transact_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_932_000 picoseconds. + Weight::from_parts(3_097_000, 0) + } + pub fn set_topic() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_860_000 picoseconds. + Weight::from_parts(2_957_000, 0) + } + pub fn clear_topic() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_886_000 picoseconds. + Weight::from_parts(3_015_000, 0) + } + pub fn set_fees_mode() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_874_000 picoseconds. + Weight::from_parts(3_060_000, 0) + } + pub fn unpaid_execution() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_029_000 picoseconds. + Weight::from_parts(3_158_000, 0) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/xcm_config.rs new file mode 100644 index 00000000000..05262e07410 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/xcm_config.rs @@ -0,0 +1,634 @@ +// 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::{ + AccountId, AllPalletsWithSystem, Assets, Authorship, Balance, Balances, ParachainInfo, + ParachainSystem, PolkadotXcm, PoolAssets, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, + TransactionByteFee, TrustBackedAssetsInstance, WeightToFee, XcmpQueue, +}; +use crate::{ForeignAssets, CENTS}; +use assets_common::{ + local_and_foreign_assets::MatchesLocalAndForeignAssetsMultiLocation, + matching::{FromSiblingParachain, IsForeignConcreteAsset}, +}; +use frame_support::{ + match_types, parameter_types, + traits::{ConstU32, Contains, Everything, Nothing, PalletInfoAccess}, +}; +use frame_system::EnsureRoot; +use pallet_xcm::XcmPassthrough; +use parachains_common::{ + impls::ToStakingPot, + xcm_config::{AssetFeeAsExistentialDepositMultiplier, ConcreteAssetFromSystem}, +}; +use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; +use sp_runtime::traits::ConvertInto; +use xcm::latest::prelude::*; +use xcm_builder::{ + AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, + AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, + DenyReserveTransferToRelayChain, DenyThenTry, DescribeAllTerminal, DescribeFamily, + EnsureXcmOrigin, FungiblesAdapter, HashedDescription, IsConcrete, LocalMint, NoChecking, + ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, StartsWith, StartsWithExplicitGlobalConsensus, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, +}; +use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; + +#[cfg(feature = "runtime-benchmarks")] +use {cumulus_primitives_core::ParaId, sp_core::Get}; + +parameter_types! { + pub const KsmLocation: MultiLocation = MultiLocation::parent(); + pub const RelayNetwork: Option = Some(NetworkId::Kusama); + pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); + pub UniversalLocation: InteriorMultiLocation = + X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocationNetworkId: NetworkId = UniversalLocation::get().global_consensus().unwrap(); + pub TrustBackedAssetsPalletLocation: MultiLocation = + PalletInstance(::index() as u8).into(); + pub ForeignAssetsPalletLocation: MultiLocation = + PalletInstance(::index() as u8).into(); + pub PoolAssetsPalletLocation: MultiLocation = + PalletInstance(::index() as u8).into(); + pub CheckingAccount: AccountId = PolkadotXcm::check_account(); + pub const GovernanceLocation: MultiLocation = MultiLocation::parent(); + pub const FellowshipLocation: MultiLocation = MultiLocation::parent(); +} + +/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// when determining ownership of accounts for asset transacting and when attempting to use XCM +/// `Transact` in order to determine the dispatch Origin. +pub type LocationToAccountId = ( + // The parent (Relay-chain) origin converts to the parent `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, + // Foreign locations alias into accounts according to a hash of their standard description. + HashedDescription>, +); + +/// Means for transacting the native currency on this chain. +pub type CurrencyTransactor = CurrencyAdapter< + // Use this currency: + Balances, + // Use this currency when it is a fungible asset matching the given location or name: + IsConcrete, + // Convert an XCM MultiLocation into a local account id: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We don't track any teleports of `Balances`. + (), +>; + +/// `AssetId`/`Balance` converter for `PoolAssets`. +pub type TrustBackedAssetsConvertedConcreteId = + assets_common::TrustBackedAssetsConvertedConcreteId; + +/// Means for transacting assets besides the native currency on this chain. +pub type FungiblesTransactor = FungiblesAdapter< + // Use this fungibles implementation: + Assets, + // Use this currency when it is a fungible asset matching the given location or name: + TrustBackedAssetsConvertedConcreteId, + // Convert an XCM MultiLocation into a local account id: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We only want to allow teleports of known assets. We use non-zero issuance as an indication + // that this asset is known. + LocalMint>, + // The account to use for tracking teleports. + CheckingAccount, +>; + +/// `AssetId/Balance` converter for `TrustBackedAssets` +pub type ForeignAssetsConvertedConcreteId = assets_common::ForeignAssetsConvertedConcreteId< + ( + // Ignore `TrustBackedAssets` explicitly + StartsWith, + // Ignore assets that start explicitly with our `GlobalConsensus(NetworkId)`, means: + // - foreign assets from our consensus should be: `MultiLocation {parents: 1, + // X*(Parachain(xyz), ..)}` + // - foreign assets outside our consensus with the same `GlobalConsensus(NetworkId)` won't + // be accepted here + StartsWithExplicitGlobalConsensus, + ), + Balance, +>; + +/// Means for transacting foreign assets from different global consensus. +pub type ForeignFungiblesTransactor = FungiblesAdapter< + // Use this fungibles implementation: + ForeignAssets, + // Use this currency when it is a fungible asset matching the given location or name: + ForeignAssetsConvertedConcreteId, + // Convert an XCM MultiLocation into a local account id: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We dont need to check teleports here. + NoChecking, + // The account to use for tracking teleports. + CheckingAccount, +>; + +/// `AssetId`/`Balance` converter for `PoolAssets`. +pub type PoolAssetsConvertedConcreteId = + assets_common::PoolAssetsConvertedConcreteId; + +/// Means for transacting asset conversion pool assets on this chain. +pub type PoolFungiblesTransactor = FungiblesAdapter< + // Use this fungibles implementation: + PoolAssets, + // Use this currency when it is a fungible asset matching the given location or name: + PoolAssetsConvertedConcreteId, + // Convert an XCM MultiLocation into a local account id: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We only want to allow teleports of known assets. We use non-zero issuance as an indication + // that this asset is known. + LocalMint>, + // The account to use for tracking teleports. + CheckingAccount, +>; + +/// Means for transacting assets on this chain. +pub type AssetTransactors = + (CurrencyTransactor, FungiblesTransactor, ForeignFungiblesTransactor, PoolFungiblesTransactor); + +/// Simple `MultiLocation` matcher for Local and Foreign asset `MultiLocation`. +pub struct LocalAndForeignAssetsMultiLocationMatcher; +impl MatchesLocalAndForeignAssetsMultiLocation for LocalAndForeignAssetsMultiLocationMatcher { + fn is_local(location: &MultiLocation) -> bool { + use assets_common::fungible_conversion::MatchesMultiLocation; + TrustBackedAssetsConvertedConcreteId::contains(location) + } + fn is_foreign(location: &MultiLocation) -> bool { + use assets_common::fungible_conversion::MatchesMultiLocation; + ForeignAssetsConvertedConcreteId::contains(location) + } +} +impl Contains for LocalAndForeignAssetsMultiLocationMatcher { + fn contains(location: &MultiLocation) -> bool { + Self::is_local(location) || Self::is_foreign(location) + } +} + +/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, +/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can +/// biases the kind of local `Origin` it will become. +pub type XcmOriginToTransactDispatchOrigin = ( + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, + // Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when + // recognised. + RelayChainAsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognised. + SiblingParachainAsNative, + // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a + // transaction from the Root origin. + ParentAsSuperuser, + // Native signed account converter; this just converts an `AccountId32` origin into a normal + // `RuntimeOrigin::Signed` origin of the same 32-byte value. + SignedAccountId32AsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, +); + +parameter_types! { + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; + pub XcmAssetFeesReceiver: Option = Authorship::author(); +} + +match_types! { + pub type ParentOrParentsPlurality: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(Plurality { .. }) } + }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; +} + +/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly +/// account for proof size weights. +/// +/// Calls that are allowed through this filter must: +/// 1. Have a fixed weight; +/// 2. Cannot lead to another call being made; +/// 3. Have a defined proof size weight, e.g. no unbounded vecs in call parameters. +pub struct SafeCallFilter; +impl Contains for SafeCallFilter { + fn contains(call: &RuntimeCall) -> bool { + #[cfg(feature = "runtime-benchmarks")] + { + if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { + return true + } + } + + matches!( + call, + RuntimeCall::PolkadotXcm(pallet_xcm::Call::force_xcm_version { .. }) | + RuntimeCall::System( + frame_system::Call::set_heap_pages { .. } | + frame_system::Call::set_code { .. } | + frame_system::Call::set_code_without_checks { .. } | + frame_system::Call::kill_prefix { .. }, + ) | RuntimeCall::ParachainSystem(..) | + RuntimeCall::Timestamp(..) | + RuntimeCall::Balances(..) | + RuntimeCall::CollatorSelection( + pallet_collator_selection::Call::set_desired_candidates { .. } | + pallet_collator_selection::Call::set_candidacy_bond { .. } | + pallet_collator_selection::Call::register_as_candidate { .. } | + pallet_collator_selection::Call::leave_intent { .. } | + pallet_collator_selection::Call::set_invulnerables { .. } | + pallet_collator_selection::Call::add_invulnerable { .. } | + pallet_collator_selection::Call::remove_invulnerable { .. }, + ) | RuntimeCall::Session(pallet_session::Call::purge_keys { .. }) | + RuntimeCall::XcmpQueue(..) | + RuntimeCall::MessageQueue(..) | + RuntimeCall::Assets( + pallet_assets::Call::create { .. } | + pallet_assets::Call::force_create { .. } | + pallet_assets::Call::start_destroy { .. } | + pallet_assets::Call::destroy_accounts { .. } | + pallet_assets::Call::destroy_approvals { .. } | + pallet_assets::Call::finish_destroy { .. } | + pallet_assets::Call::block { .. } | + pallet_assets::Call::mint { .. } | + pallet_assets::Call::burn { .. } | + pallet_assets::Call::transfer { .. } | + pallet_assets::Call::transfer_keep_alive { .. } | + pallet_assets::Call::force_transfer { .. } | + pallet_assets::Call::freeze { .. } | + pallet_assets::Call::thaw { .. } | + pallet_assets::Call::freeze_asset { .. } | + pallet_assets::Call::thaw_asset { .. } | + pallet_assets::Call::transfer_ownership { .. } | + pallet_assets::Call::set_team { .. } | + pallet_assets::Call::set_metadata { .. } | + pallet_assets::Call::clear_metadata { .. } | + pallet_assets::Call::force_set_metadata { .. } | + pallet_assets::Call::force_clear_metadata { .. } | + pallet_assets::Call::force_asset_status { .. } | + pallet_assets::Call::approve_transfer { .. } | + pallet_assets::Call::cancel_approval { .. } | + pallet_assets::Call::force_cancel_approval { .. } | + pallet_assets::Call::transfer_approved { .. } | + pallet_assets::Call::touch { .. } | + pallet_assets::Call::touch_other { .. } | + pallet_assets::Call::refund { .. } | + pallet_assets::Call::refund_other { .. }, + ) | RuntimeCall::ForeignAssets( + pallet_assets::Call::create { .. } | + pallet_assets::Call::force_create { .. } | + pallet_assets::Call::start_destroy { .. } | + pallet_assets::Call::destroy_accounts { .. } | + pallet_assets::Call::destroy_approvals { .. } | + pallet_assets::Call::finish_destroy { .. } | + pallet_assets::Call::block { .. } | + pallet_assets::Call::mint { .. } | + pallet_assets::Call::burn { .. } | + pallet_assets::Call::transfer { .. } | + pallet_assets::Call::transfer_keep_alive { .. } | + pallet_assets::Call::force_transfer { .. } | + pallet_assets::Call::freeze { .. } | + pallet_assets::Call::thaw { .. } | + pallet_assets::Call::freeze_asset { .. } | + pallet_assets::Call::thaw_asset { .. } | + pallet_assets::Call::transfer_ownership { .. } | + pallet_assets::Call::set_team { .. } | + pallet_assets::Call::set_metadata { .. } | + pallet_assets::Call::clear_metadata { .. } | + pallet_assets::Call::force_set_metadata { .. } | + pallet_assets::Call::force_clear_metadata { .. } | + pallet_assets::Call::force_asset_status { .. } | + pallet_assets::Call::approve_transfer { .. } | + pallet_assets::Call::cancel_approval { .. } | + pallet_assets::Call::force_cancel_approval { .. } | + pallet_assets::Call::transfer_approved { .. } | + pallet_assets::Call::touch { .. } | + pallet_assets::Call::touch_other { .. } | + pallet_assets::Call::refund { .. } | + pallet_assets::Call::refund_other { .. }, + ) | RuntimeCall::PoolAssets( + pallet_assets::Call::force_create { .. } | + pallet_assets::Call::block { .. } | + pallet_assets::Call::burn { .. } | + pallet_assets::Call::transfer { .. } | + pallet_assets::Call::transfer_keep_alive { .. } | + pallet_assets::Call::force_transfer { .. } | + pallet_assets::Call::freeze { .. } | + pallet_assets::Call::thaw { .. } | + pallet_assets::Call::freeze_asset { .. } | + pallet_assets::Call::thaw_asset { .. } | + pallet_assets::Call::transfer_ownership { .. } | + pallet_assets::Call::set_team { .. } | + pallet_assets::Call::set_metadata { .. } | + pallet_assets::Call::clear_metadata { .. } | + pallet_assets::Call::force_set_metadata { .. } | + pallet_assets::Call::force_clear_metadata { .. } | + pallet_assets::Call::force_asset_status { .. } | + pallet_assets::Call::approve_transfer { .. } | + pallet_assets::Call::cancel_approval { .. } | + pallet_assets::Call::force_cancel_approval { .. } | + pallet_assets::Call::transfer_approved { .. } | + pallet_assets::Call::touch { .. } | + pallet_assets::Call::touch_other { .. } | + pallet_assets::Call::refund { .. } | + pallet_assets::Call::refund_other { .. }, + ) | RuntimeCall::AssetConversion( + pallet_asset_conversion::Call::create_pool { .. } | + pallet_asset_conversion::Call::add_liquidity { .. } | + pallet_asset_conversion::Call::remove_liquidity { .. } | + pallet_asset_conversion::Call::swap_tokens_for_exact_tokens { .. } | + pallet_asset_conversion::Call::swap_exact_tokens_for_tokens { .. }, + ) | RuntimeCall::NftFractionalization( + pallet_nft_fractionalization::Call::fractionalize { .. } | + pallet_nft_fractionalization::Call::unify { .. }, + ) | RuntimeCall::Nfts( + pallet_nfts::Call::create { .. } | + pallet_nfts::Call::force_create { .. } | + pallet_nfts::Call::destroy { .. } | + pallet_nfts::Call::mint { .. } | + pallet_nfts::Call::force_mint { .. } | + pallet_nfts::Call::burn { .. } | + pallet_nfts::Call::transfer { .. } | + pallet_nfts::Call::lock_item_transfer { .. } | + pallet_nfts::Call::unlock_item_transfer { .. } | + pallet_nfts::Call::lock_collection { .. } | + pallet_nfts::Call::transfer_ownership { .. } | + pallet_nfts::Call::set_team { .. } | + pallet_nfts::Call::force_collection_owner { .. } | + pallet_nfts::Call::force_collection_config { .. } | + pallet_nfts::Call::approve_transfer { .. } | + pallet_nfts::Call::cancel_approval { .. } | + pallet_nfts::Call::clear_all_transfer_approvals { .. } | + pallet_nfts::Call::lock_item_properties { .. } | + pallet_nfts::Call::set_attribute { .. } | + pallet_nfts::Call::force_set_attribute { .. } | + pallet_nfts::Call::clear_attribute { .. } | + pallet_nfts::Call::approve_item_attributes { .. } | + pallet_nfts::Call::cancel_item_attributes_approval { .. } | + pallet_nfts::Call::set_metadata { .. } | + pallet_nfts::Call::clear_metadata { .. } | + pallet_nfts::Call::set_collection_metadata { .. } | + pallet_nfts::Call::clear_collection_metadata { .. } | + pallet_nfts::Call::set_accept_ownership { .. } | + pallet_nfts::Call::set_collection_max_supply { .. } | + pallet_nfts::Call::update_mint_settings { .. } | + pallet_nfts::Call::set_price { .. } | + pallet_nfts::Call::buy_item { .. } | + pallet_nfts::Call::pay_tips { .. } | + pallet_nfts::Call::create_swap { .. } | + pallet_nfts::Call::cancel_swap { .. } | + pallet_nfts::Call::claim_swap { .. }, + ) | RuntimeCall::Uniques( + pallet_uniques::Call::create { .. } | + pallet_uniques::Call::force_create { .. } | + pallet_uniques::Call::destroy { .. } | + pallet_uniques::Call::mint { .. } | + pallet_uniques::Call::burn { .. } | + pallet_uniques::Call::transfer { .. } | + pallet_uniques::Call::freeze { .. } | + pallet_uniques::Call::thaw { .. } | + pallet_uniques::Call::freeze_collection { .. } | + pallet_uniques::Call::thaw_collection { .. } | + pallet_uniques::Call::transfer_ownership { .. } | + pallet_uniques::Call::set_team { .. } | + pallet_uniques::Call::approve_transfer { .. } | + pallet_uniques::Call::cancel_approval { .. } | + pallet_uniques::Call::force_item_status { .. } | + pallet_uniques::Call::set_attribute { .. } | + pallet_uniques::Call::clear_attribute { .. } | + pallet_uniques::Call::set_metadata { .. } | + pallet_uniques::Call::clear_metadata { .. } | + pallet_uniques::Call::set_collection_metadata { .. } | + pallet_uniques::Call::clear_collection_metadata { .. } | + pallet_uniques::Call::set_accept_ownership { .. } | + pallet_uniques::Call::set_collection_max_supply { .. } | + pallet_uniques::Call::set_price { .. } | + pallet_uniques::Call::buy_item { .. } + ) + ) + } +} + +pub type Barrier = TrailingSetTopicAsId< + DenyThenTry< + DenyReserveTransferToRelayChain, + ( + TakeWeightCredit, + // Expected responses are OK. + AllowKnownQueryResponses, + // Allow XCMs with some computed origins to pass through. + WithComputedOrigin< + ( + // If the message is one that immediately attempts to pay for execution, then + // allow it. + AllowTopLevelPaidExecutionFrom, + // Parent and its pluralities (i.e. governance bodies) get free execution. + AllowExplicitUnpaidExecutionFrom, + // Subscriptions for version tracking are OK. + AllowSubscriptionsFrom, + ), + UniversalLocation, + ConstU32<8>, + >, + ), + >, +>; + +pub type AssetFeeAsExistentialDepositMultiplierFeeCharger = AssetFeeAsExistentialDepositMultiplier< + Runtime, + WeightToFee, + pallet_assets::BalanceToAssetBalance, + TrustBackedAssetsInstance, +>; + +/// Cases where a remote origin is accepted as trusted Teleporter for a given asset: +/// +/// - KSM with the parent Relay Chain and sibling system parachains; and +/// - Sibling parachains' assets from where they originate (as `ForeignCreators`). +pub type TrustedTeleporters = ( + ConcreteAssetFromSystem, + IsForeignConcreteAsset>>, +); + +pub struct XcmConfig; +impl xcm_executor::Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = AssetTransactors; + type OriginConverter = XcmOriginToTransactDispatchOrigin; + // Asset Hub Kusama does not recognize a reserve location for any asset. This does not prevent + // Asset Hub acting _as_ a reserve location for KSM and assets created under `pallet-assets`. + // For KSM, users must use teleport where allowed (e.g. with the Relay Chain). + type IsReserve = (); + type IsTeleporter = TrustedTeleporters; + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = WeightInfoBounds< + crate::weights::xcm::AssetHubKusamaXcmWeight, + RuntimeCall, + MaxInstructions, + >; + type Trader = ( + UsingComponents>, + cumulus_primitives_utility::TakeFirstAssetTrader< + AccountId, + AssetFeeAsExistentialDepositMultiplierFeeCharger, + TrustBackedAssetsConvertedConcreteId, + Assets, + cumulus_primitives_utility::XcmFeesTo32ByteAccount< + FungiblesTransactor, + AccountId, + XcmAssetFeesReceiver, + >, + >, + ); + type ResponseHandler = PolkadotXcm; + type AssetTrap = PolkadotXcm; + type AssetClaims = PolkadotXcm; + type SubscriptionService = PolkadotXcm; + type PalletInstancesInfo = AllPalletsWithSystem; + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type AssetLocker = (); + type AssetExchanger = (); + type FeeManager = (); + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = WithOriginFilter; + type SafeCallFilter = SafeCallFilter; + type Aliasers = Nothing; +} + +/// Converts a local signed origin into an XCM multilocation. +/// Forms the basis for local origins sending/executing XCMs. +pub type LocalOriginToLocation = SignedToAccountId32; + +parameter_types! { + /// The asset ID for the asset that we use to pay for message delivery fees. + pub FeeAssetId: AssetId = Concrete(KsmLocation::get()); + /// The base fee for the message delivery fees. + pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); +} + +pub type PriceForParentDelivery = + ExponentialPrice; + +/// The means for routing XCM messages which are not for local execution into the right message +/// queues. +pub type XcmRouter = WithUniqueTopic<( + // Two routers - use UMP to communicate with the relay chain: + cumulus_primitives_utility::ParentAsUmp, + // ..and XCMP to communicate with the sibling chains. + XcmpQueue, +)>; + +impl pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + // We want to disallow users sending (arbitrary) XCMs from this chain. + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + // We support local origins dispatching XCM executions in principle... + type ExecuteXcmOrigin = EnsureXcmOrigin; + // ... but disallow generic XCM execution. As a result only teleports and reserve transfers are + // allowed. + type XcmExecuteFilter = Nothing; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Everything; + type XcmReserveTransferFilter = Everything; + type Weigher = WeightInfoBounds< + crate::weights::xcm::AssetHubKusamaXcmWeight, + RuntimeCall, + MaxInstructions, + >; + type UniversalLocation = UniversalLocation; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type Currency = Balances; + type CurrencyMatcher = (); + type TrustedLockers = (); + type SovereignAccountOf = LocationToAccountId; + type MaxLockers = ConstU32<8>; + type WeightInfo = crate::weights::pallet_xcm::WeightInfo; + type AdminOrigin = EnsureRoot; + type MaxRemoteLockConsumers = ConstU32<0>; + type RemoteLockConsumerIdentifier = (); +} + +impl cumulus_pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type XcmExecutor = XcmExecutor; +} + +pub type ForeignCreatorsSovereignAccountOf = ( + SiblingParachainConvertsVia, + AccountId32Aliases, + ParentIsPreset, +); + +/// Simple conversion of `u32` into an `AssetId` for use in benchmarking. +pub struct XcmBenchmarkHelper; +#[cfg(feature = "runtime-benchmarks")] +impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { + fn create_asset_id_parameter(id: u32) -> MultiLocation { + MultiLocation { parents: 1, interior: X1(Parachain(id)) } + } +} + +#[cfg(feature = "runtime-benchmarks")] +pub struct BenchmarkMultiLocationConverter { + _phantom: sp_std::marker::PhantomData, +} + +#[cfg(feature = "runtime-benchmarks")] +impl + pallet_asset_conversion::BenchmarkHelper> + for BenchmarkMultiLocationConverter +where + SelfParaId: Get, +{ + fn asset_id(asset_id: u32) -> MultiLocation { + MultiLocation { + parents: 1, + interior: X3( + Parachain(SelfParaId::get().into()), + PalletInstance(::index() as u8), + GeneralIndex(asset_id.into()), + ), + } + } + fn multiasset_id(asset_id: u32) -> sp_std::boxed::Box { + sp_std::boxed::Box::new(Self::asset_id(asset_id)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/tests/tests.rs new file mode 100644 index 00000000000..cdd4290770f --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/tests/tests.rs @@ -0,0 +1,658 @@ +// This file is part of Cumulus. + +// 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 the Statemine (Kusama Assets Hub) chain. + +use asset_hub_kusama_runtime::xcm_config::{ + AssetFeeAsExistentialDepositMultiplierFeeCharger, KsmLocation, LocationToAccountId, + TrustBackedAssetsPalletLocation, +}; +pub use asset_hub_kusama_runtime::{ + xcm_config::{CheckingAccount, ForeignCreatorsSovereignAccountOf, XcmConfig}, + AllPalletsWithoutSystem, AssetDeposit, Assets, Balances, ExistentialDeposit, ForeignAssets, + ForeignAssetsInstance, MetadataDepositBase, MetadataDepositPerByte, ParachainSystem, Runtime, + RuntimeCall, RuntimeEvent, SessionKeys, System, TrustBackedAssetsInstance, XcmpQueue, +}; +use asset_test_utils::{CollatorSessionKeys, ExtBuilder}; +use codec::{Decode, Encode}; +use cumulus_primitives_utility::ChargeWeightInFungibles; +use frame_support::{ + assert_noop, assert_ok, + traits::fungibles::InspectEnumerable, + weights::{Weight, WeightToFee as WeightToFeeT}, +}; +use parachains_common::{ + kusama::fee::WeightToFee, AccountId, AssetIdForTrustBackedAssets, AuraId, Balance, +}; +use sp_runtime::traits::MaybeEquivalence; +use xcm::latest::prelude::*; +use xcm_executor::traits::{Identity, JustTry, WeightTrader}; + +const ALICE: [u8; 32] = [1u8; 32]; +const SOME_ASSET_ADMIN: [u8; 32] = [5u8; 32]; + +type AssetIdForTrustBackedAssetsConvert = + assets_common::AssetIdForTrustBackedAssetsConvert; + +type RuntimeHelper = asset_test_utils::RuntimeHelper; + +fn collator_session_keys() -> CollatorSessionKeys { + CollatorSessionKeys::new( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) }, + ) +} + +#[test] +fn test_asset_xcm_trader() { + ExtBuilder::::default() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + // We need root origin to create a sufficient asset + let minimum_asset_balance = 3333333_u128; + let local_asset_id = 1; + assert_ok!(Assets::force_create( + RuntimeHelper::root_origin(), + local_asset_id.into(), + AccountId::from(ALICE).into(), + true, + minimum_asset_balance + )); + + // We first mint enough asset for the account to exist for assets + assert_ok!(Assets::mint( + RuntimeHelper::origin_of(AccountId::from(ALICE)), + local_asset_id.into(), + AccountId::from(ALICE).into(), + minimum_asset_balance + )); + + // get asset id as multilocation + let asset_multilocation = + AssetIdForTrustBackedAssetsConvert::convert_back(&local_asset_id).unwrap(); + + // Set Alice as block author, who will receive fees + RuntimeHelper::run_to_block(2, AccountId::from(ALICE)); + + // We are going to buy 4e9 weight + let bought = Weight::from_parts(4_000_000_000u64, 0); + + // Lets calculate amount needed + let asset_amount_needed = + AssetFeeAsExistentialDepositMultiplierFeeCharger::charge_weight_in_fungibles( + local_asset_id, + bought, + ) + .expect("failed to compute"); + + // Lets pay with: asset_amount_needed + asset_amount_extra + let asset_amount_extra = 100_u128; + let asset: MultiAsset = + (asset_multilocation, asset_amount_needed + asset_amount_extra).into(); + + let mut trader = ::Trader::new(); + let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; + + // Lets buy_weight and make sure buy_weight does not return an error + let unused_assets = trader.buy_weight(bought, asset.into(), &ctx).expect("Expected Ok"); + // Check whether a correct amount of unused assets is returned + assert_ok!( + unused_assets.ensure_contains(&(asset_multilocation, asset_amount_extra).into()) + ); + + // Drop trader + drop(trader); + + // Make sure author(Alice) has received the amount + assert_eq!( + Assets::balance(local_asset_id, AccountId::from(ALICE)), + minimum_asset_balance + asset_amount_needed + ); + + // We also need to ensure the total supply increased + assert_eq!( + Assets::total_supply(local_asset_id), + minimum_asset_balance + asset_amount_needed + ); + }); +} + +#[test] +fn test_asset_xcm_trader_with_refund() { + ExtBuilder::::default() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + // We need root origin to create a sufficient asset + // We set existential deposit to be identical to the one for Balances first + assert_ok!(Assets::force_create( + RuntimeHelper::root_origin(), + 1.into(), + AccountId::from(ALICE).into(), + true, + ExistentialDeposit::get() + )); + + // We first mint enough asset for the account to exist for assets + assert_ok!(Assets::mint( + RuntimeHelper::origin_of(AccountId::from(ALICE)), + 1.into(), + AccountId::from(ALICE).into(), + ExistentialDeposit::get() + )); + + let mut trader = ::Trader::new(); + let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; + + // Set Alice as block author, who will receive fees + RuntimeHelper::run_to_block(2, AccountId::from(ALICE)); + + // We are going to buy 4e9 weight + let bought = Weight::from_parts(4_000_000_000u64, 0); + + let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + + // lets calculate amount needed + let amount_bought = WeightToFee::weight_to_fee(&bought); + + let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + + // Make sure buy_weight does not return an error + assert_ok!(trader.buy_weight(bought, asset.clone().into(), &ctx)); + + // Make sure again buy_weight does return an error + // This assert relies on the fact, that we use `TakeFirstAssetTrader` in `WeightTrader` + // tuple chain, which cannot be called twice + assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); + + // We actually use half of the weight + let weight_used = bought / 2; + + // Make sure refurnd works. + let amount_refunded = WeightToFee::weight_to_fee(&(bought - weight_used)); + + assert_eq!( + trader.refund_weight(bought - weight_used, &ctx), + Some((asset_multilocation, amount_refunded).into()) + ); + + // Drop trader + drop(trader); + + // We only should have paid for half of the bought weight + let fees_paid = WeightToFee::weight_to_fee(&weight_used); + + assert_eq!( + Assets::balance(1, AccountId::from(ALICE)), + ExistentialDeposit::get() + fees_paid + ); + + // We also need to ensure the total supply increased + assert_eq!(Assets::total_supply(1), ExistentialDeposit::get() + fees_paid); + }); +} + +#[test] +fn test_asset_xcm_trader_refund_not_possible_since_amount_less_than_ed() { + ExtBuilder::::default() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + // We need root origin to create a sufficient asset + // We set existential deposit to be identical to the one for Balances first + assert_ok!(Assets::force_create( + RuntimeHelper::root_origin(), + 1.into(), + AccountId::from(ALICE).into(), + true, + ExistentialDeposit::get() + )); + + let mut trader = ::Trader::new(); + let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; + + // Set Alice as block author, who will receive fees + RuntimeHelper::run_to_block(2, AccountId::from(ALICE)); + + // We are going to buy small amount + let bought = Weight::from_parts(500_000_000u64, 0); + + let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + + let amount_bought = WeightToFee::weight_to_fee(&bought); + + assert!( + amount_bought < ExistentialDeposit::get(), + "we are testing what happens when the amount does not exceed ED" + ); + + let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + + // Buy weight should return an error + assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); + + // not credited since the ED is higher than this value + assert_eq!(Assets::balance(1, AccountId::from(ALICE)), 0); + + // We also need to ensure the total supply did not increase + assert_eq!(Assets::total_supply(1), 0); + }); +} + +#[test] +fn test_that_buying_ed_refund_does_not_refund() { + ExtBuilder::::default() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + // We need root origin to create a sufficient asset + // We set existential deposit to be identical to the one for Balances first + assert_ok!(Assets::force_create( + RuntimeHelper::root_origin(), + 1.into(), + AccountId::from(ALICE).into(), + true, + ExistentialDeposit::get() + )); + + let mut trader = ::Trader::new(); + let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; + + // Set Alice as block author, who will receive fees + RuntimeHelper::run_to_block(2, AccountId::from(ALICE)); + + // We are gonna buy ED + let bought = Weight::from_parts(ExistentialDeposit::get().try_into().unwrap(), 0); + + let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + + let amount_bought = WeightToFee::weight_to_fee(&bought); + + assert!( + amount_bought < ExistentialDeposit::get(), + "we are testing what happens when the amount does not exceed ED" + ); + + // We know we will have to buy at least ED, so lets make sure first it will + // fail with a payment of less than ED + let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); + + // Now lets buy ED at least + let asset: MultiAsset = (asset_multilocation, ExistentialDeposit::get()).into(); + + // Buy weight should work + assert_ok!(trader.buy_weight(bought, asset.into(), &ctx)); + + // Should return None. We have a specific check making sure we dont go below ED for + // drop payment + assert_eq!(trader.refund_weight(bought, &ctx), None); + + // Drop trader + drop(trader); + + // Make sure author(Alice) has received the amount + assert_eq!(Assets::balance(1, AccountId::from(ALICE)), ExistentialDeposit::get()); + + // We also need to ensure the total supply increased + assert_eq!(Assets::total_supply(1), ExistentialDeposit::get()); + }); +} + +#[test] +fn test_asset_xcm_trader_not_possible_for_non_sufficient_assets() { + ExtBuilder::::default() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + // Create a non-sufficient asset with specific existential deposit + let minimum_asset_balance = 1_000_000_u128; + assert_ok!(Assets::force_create( + RuntimeHelper::root_origin(), + 1.into(), + AccountId::from(ALICE).into(), + false, + minimum_asset_balance + )); + + // We first mint enough asset for the account to exist for assets + assert_ok!(Assets::mint( + RuntimeHelper::origin_of(AccountId::from(ALICE)), + 1.into(), + AccountId::from(ALICE).into(), + minimum_asset_balance + )); + + let mut trader = ::Trader::new(); + let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; + + // Set Alice as block author, who will receive fees + RuntimeHelper::run_to_block(2, AccountId::from(ALICE)); + + // We are going to buy 4e9 weight + let bought = Weight::from_parts(4_000_000_000u64, 0); + + // lets calculate amount needed + let asset_amount_needed = WeightToFee::weight_to_fee(&bought); + + let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + + let asset: MultiAsset = (asset_multilocation, asset_amount_needed).into(); + + // Make sure again buy_weight does return an error + assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); + + // Drop trader + drop(trader); + + // Make sure author(Alice) has NOT received the amount + assert_eq!(Assets::balance(1, AccountId::from(ALICE)), minimum_asset_balance); + + // We also need to ensure the total supply NOT increased + assert_eq!(Assets::total_supply(1), minimum_asset_balance); + }); +} + +#[test] +fn test_assets_balances_api_works() { + use assets_common::runtime_api::runtime_decl_for_fungibles_api::FungiblesApi; + + ExtBuilder::::default() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + let local_asset_id = 1; + let foreign_asset_id_multilocation = + MultiLocation { parents: 1, interior: X2(Parachain(1234), GeneralIndex(12345)) }; + + // check before + assert_eq!(Assets::balance(local_asset_id, AccountId::from(ALICE)), 0); + assert_eq!( + ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)), + 0 + ); + assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 0); + assert!(Runtime::query_account_balances(AccountId::from(ALICE)) + .unwrap() + .try_as::() + .unwrap() + .is_none()); + + // Drip some balance + use frame_support::traits::fungible::Mutate; + let some_currency = ExistentialDeposit::get(); + Balances::mint_into(&AccountId::from(ALICE), some_currency).unwrap(); + + // We need root origin to create a sufficient asset + let minimum_asset_balance = 3333333_u128; + assert_ok!(Assets::force_create( + RuntimeHelper::root_origin(), + local_asset_id.into(), + AccountId::from(ALICE).into(), + true, + minimum_asset_balance + )); + + // We first mint enough asset for the account to exist for assets + assert_ok!(Assets::mint( + RuntimeHelper::origin_of(AccountId::from(ALICE)), + local_asset_id.into(), + AccountId::from(ALICE).into(), + minimum_asset_balance + )); + + // create foreign asset + let foreign_asset_minimum_asset_balance = 3333333_u128; + assert_ok!(ForeignAssets::force_create( + RuntimeHelper::root_origin(), + foreign_asset_id_multilocation, + AccountId::from(SOME_ASSET_ADMIN).into(), + false, + foreign_asset_minimum_asset_balance + )); + + // We first mint enough asset for the account to exist for assets + assert_ok!(ForeignAssets::mint( + RuntimeHelper::origin_of(AccountId::from(SOME_ASSET_ADMIN)), + foreign_asset_id_multilocation, + AccountId::from(ALICE).into(), + 6 * foreign_asset_minimum_asset_balance + )); + + // check after + assert_eq!( + Assets::balance(local_asset_id, AccountId::from(ALICE)), + minimum_asset_balance + ); + assert_eq!( + ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)), + 6 * minimum_asset_balance + ); + assert_eq!(Balances::free_balance(AccountId::from(ALICE)), some_currency); + + let result: MultiAssets = Runtime::query_account_balances(AccountId::from(ALICE)) + .unwrap() + .try_into() + .unwrap(); + assert_eq!(result.len(), 3); + + // check currency + assert!(result.inner().iter().any(|asset| asset.eq( + &assets_common::fungible_conversion::convert_balance::( + some_currency + ) + .unwrap() + ))); + // check trusted asset + assert!(result.inner().iter().any(|asset| asset.eq(&( + AssetIdForTrustBackedAssetsConvert::convert_back(&local_asset_id).unwrap(), + minimum_asset_balance + ) + .into()))); + // check foreign asset + assert!(result.inner().iter().any(|asset| asset.eq(&( + Identity::convert_back(&foreign_asset_id_multilocation).unwrap(), + 6 * foreign_asset_minimum_asset_balance + ) + .into()))); + }); +} + +asset_test_utils::include_teleports_for_native_asset_works!( + Runtime, + AllPalletsWithoutSystem, + XcmConfig, + CheckingAccount, + WeightToFee, + ParachainSystem, + collator_session_keys(), + ExistentialDeposit::get(), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::PolkadotXcm(event)) => Some(event), + _ => None, + } + }), + 1000 +); + +asset_test_utils::include_teleports_for_foreign_assets_works!( + Runtime, + AllPalletsWithoutSystem, + XcmConfig, + CheckingAccount, + WeightToFee, + ParachainSystem, + ForeignCreatorsSovereignAccountOf, + ForeignAssetsInstance, + collator_session_keys(), + ExistentialDeposit::get(), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::PolkadotXcm(event)) => Some(event), + _ => None, + } + }), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::XcmpQueue(event)) => Some(event), + _ => None, + } + }) +); + +asset_test_utils::include_asset_transactor_transfer_with_local_consensus_currency_works!( + Runtime, + XcmConfig, + collator_session_keys(), + ExistentialDeposit::get(), + Box::new(|| { + assert!(Assets::asset_ids().collect::>().is_empty()); + assert!(ForeignAssets::asset_ids().collect::>().is_empty()); + }), + Box::new(|| { + assert!(Assets::asset_ids().collect::>().is_empty()); + assert!(ForeignAssets::asset_ids().collect::>().is_empty()); + }) +); + +asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_works!( + asset_transactor_transfer_with_trust_backed_assets_works, + Runtime, + XcmConfig, + TrustBackedAssetsInstance, + AssetIdForTrustBackedAssets, + AssetIdForTrustBackedAssetsConvert, + collator_session_keys(), + ExistentialDeposit::get(), + 12345, + Box::new(|| { + assert!(ForeignAssets::asset_ids().collect::>().is_empty()); + }), + Box::new(|| { + assert!(ForeignAssets::asset_ids().collect::>().is_empty()); + }) +); + +asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_works!( + asset_transactor_transfer_with_foreign_assets_works, + Runtime, + XcmConfig, + ForeignAssetsInstance, + MultiLocation, + JustTry, + collator_session_keys(), + ExistentialDeposit::get(), + MultiLocation { parents: 1, interior: X2(Parachain(1313), GeneralIndex(12345)) }, + Box::new(|| { + assert!(Assets::asset_ids().collect::>().is_empty()); + }), + Box::new(|| { + assert!(Assets::asset_ids().collect::>().is_empty()); + }) +); + +asset_test_utils::include_create_and_manage_foreign_assets_for_local_consensus_parachain_assets_works!( + Runtime, + XcmConfig, + WeightToFee, + ForeignCreatorsSovereignAccountOf, + ForeignAssetsInstance, + MultiLocation, + JustTry, + collator_session_keys(), + ExistentialDeposit::get(), + AssetDeposit::get(), + MetadataDepositBase::get(), + MetadataDepositPerByte::get(), + Box::new(|pallet_asset_call| RuntimeCall::ForeignAssets(pallet_asset_call).encode()), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::ForeignAssets(pallet_asset_event)) => Some(pallet_asset_event), + _ => None, + } + }), + Box::new(|| { + assert!(Assets::asset_ids().collect::>().is_empty()); + assert!(ForeignAssets::asset_ids().collect::>().is_empty()); + }), + Box::new(|| { + assert!(Assets::asset_ids().collect::>().is_empty()); + assert_eq!(ForeignAssets::asset_ids().collect::>().len(), 1); + }) +); + +#[test] +fn reserve_transfer_native_asset_to_non_teleport_para_works() { + asset_test_utils::test_cases::reserve_transfer_native_asset_to_non_teleport_para_works::< + Runtime, + AllPalletsWithoutSystem, + XcmConfig, + ParachainSystem, + XcmpQueue, + LocationToAccountId, + >( + collator_session_keys(), + ExistentialDeposit::get(), + AccountId::from(ALICE), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::PolkadotXcm(event)) => Some(event), + _ => None, + } + }), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::XcmpQueue(event)) => Some(event), + _ => None, + } + }), + WeightLimit::Unlimited, + ); +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/Cargo.toml new file mode 100644 index 00000000000..b5eff6b63af --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/Cargo.toml @@ -0,0 +1,215 @@ +[package] +name = "asset-hub-polkadot-runtime" +version = "0.9.420" +authors.workspace = true +edition.workspace = true +description = "Asset Hub Polkadot parachain runtime" +license = "Apache-2.0" + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } +hex-literal = { version = "0.4.1", optional = true } +log = { version = "0.4.20", default-features = false } +scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } +smallvec = "1.11.0" + +# 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-tx-payment = { path = "../../../../../substrate/frame/transaction-payment/asset-tx-payment", default-features = false } +pallet-assets = { path = "../../../../../substrate/frame/assets", 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-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-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} +sp-weights = { path = "../../../../../substrate/primitives/weights", default-features = false} + +# 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-core-primitives = { path = "../../../../../polkadot/core-primitives", 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} + +# 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-dmp-queue = { path = "../../../../pallets/dmp-queue", default-features = false } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } +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 = "../common", default-features = false } + +[dev-dependencies] +hex-literal = "0.4.1" +asset-test-utils = { path = "../test-utils" } + +[build-dependencies] +substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } + +[features] +default = [ "std" ] +runtime-benchmarks = [ + "assets-common/runtime-benchmarks", + "cumulus-pallet-dmp-queue/runtime-benchmarks", + "cumulus-pallet-parachain-system/runtime-benchmarks", + "cumulus-pallet-session-benchmarking/runtime-benchmarks", + "cumulus-pallet-xcmp-queue/runtime-benchmarks", + "cumulus-primitives-core/runtime-benchmarks", + "cumulus-primitives-utility/runtime-benchmarks", + "frame-benchmarking/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "frame-system-benchmarking/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "hex-literal", + "pallet-asset-tx-payment/runtime-benchmarks", + "pallet-assets/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", + "pallet-collator-selection/runtime-benchmarks", + "pallet-message-queue/runtime-benchmarks", + "pallet-multisig/runtime-benchmarks", + "pallet-nfts/runtime-benchmarks", + "pallet-proxy/runtime-benchmarks", + "pallet-timestamp/runtime-benchmarks", + "pallet-uniques/runtime-benchmarks", + "pallet-utility/runtime-benchmarks", + "pallet-xcm-benchmarks/runtime-benchmarks", + "pallet-xcm/runtime-benchmarks", + "parachains-common/runtime-benchmarks", + "polkadot-parachain-primitives/runtime-benchmarks", + "polkadot-runtime-common/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", + "xcm-executor/runtime-benchmarks", +] +try-runtime = [ + "cumulus-pallet-aura-ext/try-runtime", + "cumulus-pallet-dmp-queue/try-runtime", + "cumulus-pallet-parachain-system/try-runtime", + "cumulus-pallet-xcm/try-runtime", + "cumulus-pallet-xcmp-queue/try-runtime", + "frame-executive/try-runtime", + "frame-support/try-runtime", + "frame-system/try-runtime", + "frame-try-runtime/try-runtime", + "pallet-asset-tx-payment/try-runtime", + "pallet-assets/try-runtime", + "pallet-aura/try-runtime", + "pallet-authorship/try-runtime", + "pallet-balances/try-runtime", + "pallet-collator-selection/try-runtime", + "pallet-message-queue/try-runtime", + "pallet-multisig/try-runtime", + "pallet-nfts/try-runtime", + "pallet-proxy/try-runtime", + "pallet-session/try-runtime", + "pallet-timestamp/try-runtime", + "pallet-transaction-payment/try-runtime", + "pallet-uniques/try-runtime", + "pallet-utility/try-runtime", + "pallet-xcm/try-runtime", + "parachain-info/try-runtime", + "polkadot-runtime-common/try-runtime", + "sp-runtime/try-runtime", +] +std = [ + "assets-common/std", + "codec/std", + "cumulus-pallet-aura-ext/std", + "cumulus-pallet-dmp-queue/std", + "cumulus-pallet-parachain-system/std", + "cumulus-pallet-session-benchmarking/std", + "cumulus-pallet-xcm/std", + "cumulus-pallet-xcmp-queue/std", + "cumulus-primitives-core/std", + "cumulus-primitives-utility/std", + "frame-benchmarking?/std", + "frame-executive/std", + "frame-support/std", + "frame-system-benchmarking?/std", + "frame-system-rpc-runtime-api/std", + "frame-system/std", + "frame-try-runtime?/std", + "log/std", + "pallet-asset-tx-payment/std", + "pallet-assets/std", + "pallet-aura/std", + "pallet-authorship/std", + "pallet-balances/std", + "pallet-collator-selection/std", + "pallet-message-queue/std", + "pallet-multisig/std", + "pallet-nfts-runtime-api/std", + "pallet-nfts/std", + "pallet-proxy/std", + "pallet-session/std", + "pallet-timestamp/std", + "pallet-transaction-payment-rpc-runtime-api/std", + "pallet-transaction-payment/std", + "pallet-uniques/std", + "pallet-utility/std", + "pallet-xcm-benchmarks?/std", + "pallet-xcm/std", + "parachain-info/std", + "parachains-common/std", + "polkadot-core-primitives/std", + "polkadot-parachain-primitives/std", + "polkadot-runtime-common/std", + "scale-info/std", + "sp-api/std", + "sp-block-builder/std", + "sp-consensus-aura/std", + "sp-core/std", + "sp-genesis-builder/std", + "sp-inherents/std", + "sp-offchain/std", + "sp-runtime/std", + "sp-session/std", + "sp-std/std", + "sp-storage/std", + "sp-transaction-pool/std", + "sp-version/std", + "sp-weights/std", + "substrate-wasm-builder", + "xcm-builder/std", + "xcm-executor/std", + "xcm/std", +] + +experimental = [ "pallet-aura/experimental" ] diff --git a/substrate/frame/contracts/fixtures/contracts/common/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/build.rs similarity index 60% rename from substrate/frame/contracts/fixtures/contracts/common/src/lib.rs rename to cumulus/parachains/runtimes/assets/asset-hub-polkadot/build.rs index 29bdbfbb042..60f8a125129 100644 --- a/substrate/frame/contracts/fixtures/contracts/common/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/build.rs @@ -1,5 +1,3 @@ -// This file is part of Substrate. - // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 @@ -14,18 +12,15 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -#![no_std] -#![cfg(any(target_arch = "wasm32", target_arch = "riscv32"))] - -#[panic_handler] -fn panic(_info: &core::panic::PanicInfo) -> ! { - #[cfg(target_arch = "wasm32")] - core::arch::wasm32::unreachable(); - #[cfg(target_arch = "riscv32")] - // Safety: The unimp instruction is guaranteed to trap - unsafe { - core::arch::asm!("unimp"); - core::hint::unreachable_unchecked(); - } +#[cfg(feature = "std")] +fn main() { + substrate_wasm_builder::WasmBuilder::new() + .with_current_project() + .export_heap_base() + .import_memory() + .build() } + +#[cfg(not(feature = "std"))] +fn main() {} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/lib.rs new file mode 100644 index 00000000000..eba1789d2b6 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/lib.rs @@ -0,0 +1,1383 @@ +// 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. + +//! # Asset Hub Polkadot Runtime +//! +//! Asset Hub Polkadot is a parachain that provides an interface to create, manage, and use assets. +//! Assets may be fungible or non-fungible. +//! +//! ## Renaming +//! +//! This chain was originally known as "Statemint". You may see references to Statemint, Statemine, +//! and Westmint throughout the codebase. These are synonymous with "Asset Hub Polkadot, Kusama, and +//! Westend", respectively. +//! +//! ## Assets +//! +//! - Fungibles: Configuration of `pallet-assets`. +//! - Non-Fungibles (NFTs): Configuration of `pallet-uniques`. +//! +//! ## Other Functionality +//! +//! ### Native Balances +//! +//! Asset Hub Polkadot uses its parent DOT token as its native asset. +//! +//! ### Governance +//! +//! As a system parachain, Asset Hub defers its governance (namely, its `Root` origin), to its +//! Relay Chain parent, Polkadot. +//! +//! ### Collator Selection +//! +//! Asset Hub uses `pallet-collator-selection`, a simple first-come-first-served registration +//! system where collators can reserve a small bond to join the block producer set. There is no +//! slashing. +//! +//! ### XCM +//! +//! Because Asset Hub is fully under the control of the Relay Chain, it is meant to be a +//! `TrustedTeleporter`. It can also serve as a reserve location to other parachains for DOT as well +//! as other local assets. + +#![cfg_attr(not(feature = "std"), no_std)] +#![recursion_limit = "256"] + +// Make the WASM binary available. +#[cfg(feature = "std")] +include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); + +mod weights; +pub mod xcm_config; + +use assets_common::{ + foreign_creators::ForeignCreators, matching::FromSiblingParachain, MultiLocationForAssetId, +}; +use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; +use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; +use sp_api::impl_runtime_apis; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; +use sp_runtime::{ + create_runtime_str, generic, impl_opaque_keys, + traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, Verify}, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, Perbill, +}; + +use sp_std::prelude::*; +#[cfg(feature = "std")] +use sp_version::NativeVersion; +use sp_version::RuntimeVersion; + +use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::{ + construct_runtime, + dispatch::DispatchClass, + genesis_builder_helper::{build_config, create_default_config}, + parameter_types, + traits::{ + AsEnsureOriginWithArg, ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, + InstanceFilter, TransformOrigin, + }, + weights::{ConstantMultiplier, Weight}, + PalletId, +}; +use frame_system::{ + limits::{BlockLength, BlockWeights}, + EnsureRoot, EnsureSigned, +}; +use pallet_nfts::PalletFeatures; +pub use parachains_common as common; +use parachains_common::{ + impls::{AssetsToBlockAuthor, DealWithFees}, + message_queue::*, + polkadot::{consensus::*, currency::*, fee::WeightToFee}, + AccountId, AssetHubPolkadotAuraId as AuraId, AssetIdForTrustBackedAssets, Balance, BlockNumber, + Hash, Header, Nonce, Signature, AVERAGE_ON_INITIALIZE_RATIO, DAYS, HOURS, MAXIMUM_BLOCK_WEIGHT, + NORMAL_DISPATCH_RATIO, SLOT_DURATION, +}; +use sp_runtime::RuntimeDebug; +use xcm_config::{ + DotLocation, FellowshipLocation, ForeignAssetsConvertedConcreteId, GovernanceLocation, + TrustBackedAssetsConvertedConcreteId, XcmOriginToTransactDispatchOrigin, +}; + +#[cfg(any(feature = "std", test))] +pub use sp_runtime::BuildStorage; + +// Polkadot imports +use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; +use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; +use xcm::latest::BodyId; + +use crate::xcm_config::ForeignCreatorsSovereignAccountOf; +use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; + +impl_opaque_keys! { + pub struct SessionKeys { + pub aura: Aura, + } +} + +#[sp_version::runtime_version] +pub const VERSION: RuntimeVersion = RuntimeVersion { + // Note: "statemint" is the legacy name for this chain. It has been renamed to + // "asset-hub-polkadot". Many wallets/tools depend on the `spec_name`, so it remains "statemint" + // for the time being. Wallets/tools should update to treat "asset-hub-polkadot" equally. + spec_name: create_runtime_str!("statemint"), + impl_name: create_runtime_str!("statemint"), + authoring_version: 1, + spec_version: 10000, + impl_version: 0, + apis: RUNTIME_API_VERSIONS, + transaction_version: 13, + state_version: 0, +}; + +/// The version information used to identify this runtime when compiled natively. +#[cfg(feature = "std")] +pub fn native_version() -> NativeVersion { + NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } +} + +parameter_types! { + pub const Version: RuntimeVersion = VERSION; + pub RuntimeBlockLength: BlockLength = + BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() + .base_block(BlockExecutionWeight::get()) + .for_class(DispatchClass::all(), |weights| { + weights.base_extrinsic = ExtrinsicBaseWeight::get(); + }) + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Operational transactions have some extra reserved space, so that they + // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); + pub const SS58Prefix: u8 = 0; +} + +// Configure FRAME pallets to include in runtime. +impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = RuntimeBlockWeights; + type BlockLength = RuntimeBlockLength; + type AccountId = AccountId; + type RuntimeCall = RuntimeCall; + type Lookup = AccountIdLookup; + type Nonce = Nonce; + type Hash = Hash; + type Hashing = BlakeTwo256; + type Block = Block; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type BlockHashCount = BlockHashCount; + type DbWeight = RocksDbWeight; + type Version = Version; + type PalletInfo = PalletInfo; + type OnNewAccount = (); + type OnKilledAccount = (); + type AccountData = pallet_balances::AccountData; + type SystemWeightInfo = weights::frame_system::WeightInfo; + type SS58Prefix = SS58Prefix; + type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + +impl pallet_timestamp::Config for Runtime { + /// A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = Aura; + type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>; + type WeightInfo = weights::pallet_timestamp::WeightInfo; +} + +impl pallet_authorship::Config for Runtime { + type FindAuthor = pallet_session::FindAccountFromAuthorIndex; + type EventHandler = (CollatorSelection,); +} + +parameter_types! { + pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT; +} + +impl pallet_balances::Config for Runtime { + type MaxLocks = ConstU32<50>; + /// The type for recording an account's balance. + type Balance = Balance; + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = weights::pallet_balances::WeightInfo; + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; + type FreezeIdentifier = (); + type MaxHolds = ConstU32<0>; + type MaxFreezes = ConstU32<0>; +} + +parameter_types! { + /// Relay Chain `TransactionByteFee` / 10 + pub const TransactionByteFee: Balance = MILLICENTS; +} + +impl pallet_transaction_payment::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type OnChargeTransaction = + pallet_transaction_payment::CurrencyAdapter>; + type WeightToFee = WeightToFee; + type LengthToFee = ConstantMultiplier; + type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; + type OperationalFeeMultiplier = ConstU8<5>; +} + +parameter_types! { + pub const AssetDeposit: Balance = 10 * UNITS; // 10 UNITS deposit to create fungible asset class + pub const AssetAccountDeposit: Balance = deposit(1, 16); + pub const ApprovalDeposit: Balance = EXISTENTIAL_DEPOSIT; + pub const AssetsStringLimit: u32 = 50; + /// Key = 32 bytes, Value = 36 bytes (32+1+1+1+1) + // https://github.com/paritytech/substrate/blob/069917b/frame/assets/src/lib.rs#L257L271 + pub const MetadataDepositBase: Balance = deposit(1, 68); + pub const MetadataDepositPerByte: Balance = deposit(0, 1); +} + +/// We allow root to execute privileged asset operations. +pub type AssetsForceOrigin = EnsureRoot; + +// Called "Trust Backed" assets because these are generally registered by some account, and users of +// the asset assume it has some claimed backing. The pallet is called `Assets` in +// `construct_runtime` to avoid breaking changes on storage reads. +pub type TrustBackedAssetsInstance = pallet_assets::Instance1; +type TrustBackedAssetsCall = pallet_assets::Call; +impl pallet_assets::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type AssetId = AssetIdForTrustBackedAssets; + type AssetIdParameter = codec::Compact; + type Currency = Balances; + type CreateOrigin = AsEnsureOriginWithArg>; + type ForceOrigin = AssetsForceOrigin; + type AssetDeposit = AssetDeposit; + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type ApprovalDeposit = ApprovalDeposit; + type StringLimit = AssetsStringLimit; + type Freezer = (); + type Extra = (); + type WeightInfo = weights::pallet_assets_local::WeightInfo; + type CallbackHandle = (); + type AssetAccountDeposit = AssetAccountDeposit; + type RemoveItemsLimit = frame_support::traits::ConstU32<1000>; + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); +} + +parameter_types! { + // we just reuse the same deposits + pub const ForeignAssetsAssetDeposit: Balance = AssetDeposit::get(); + pub const ForeignAssetsAssetAccountDeposit: Balance = AssetAccountDeposit::get(); + pub const ForeignAssetsApprovalDeposit: Balance = ApprovalDeposit::get(); + pub const ForeignAssetsAssetsStringLimit: u32 = AssetsStringLimit::get(); + pub const ForeignAssetsMetadataDepositBase: Balance = MetadataDepositBase::get(); + pub const ForeignAssetsMetadataDepositPerByte: Balance = MetadataDepositPerByte::get(); +} + +/// Assets managed by some foreign location. Note: we do not declare a `ForeignAssetsCall` type, as +/// this type is used in proxy definitions. We assume that a foreign location would not want to set +/// an individual, local account as a proxy for the issuance of their assets. This issuance should +/// be managed by the foreign location's governance. +pub type ForeignAssetsInstance = pallet_assets::Instance2; +impl pallet_assets::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Balance = Balance; + type AssetId = MultiLocationForAssetId; + type AssetIdParameter = MultiLocationForAssetId; + type Currency = Balances; + type CreateOrigin = ForeignCreators< + (FromSiblingParachain>,), + ForeignCreatorsSovereignAccountOf, + AccountId, + >; + type ForceOrigin = AssetsForceOrigin; + type AssetDeposit = ForeignAssetsAssetDeposit; + type MetadataDepositBase = ForeignAssetsMetadataDepositBase; + type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte; + type ApprovalDeposit = ForeignAssetsApprovalDeposit; + type StringLimit = ForeignAssetsAssetsStringLimit; + type Freezer = (); + type Extra = (); + type WeightInfo = weights::pallet_assets_foreign::WeightInfo; + type CallbackHandle = (); + type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit; + type RemoveItemsLimit = frame_support::traits::ConstU32<1000>; + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = xcm_config::XcmBenchmarkHelper; +} + +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); + // Additional storage item size of 32 bytes. + pub const DepositFactor: Balance = deposit(0, 32); + pub const MaxSignatories: u32 = 100; +} + +impl pallet_multisig::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type Currency = Balances; + type DepositBase = DepositBase; + type DepositFactor = DepositFactor; + type MaxSignatories = MaxSignatories; + type WeightInfo = weights::pallet_multisig::WeightInfo; +} + +impl pallet_utility::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type PalletsOrigin = OriginCaller; + type WeightInfo = weights::pallet_utility::WeightInfo; +} + +parameter_types! { + // One storage item; key size 32, value size 8; . + pub const ProxyDepositBase: Balance = deposit(1, 40); + // Additional storage item size of 33 bytes. + pub const ProxyDepositFactor: Balance = deposit(0, 33); + pub const MaxProxies: u16 = 32; + // One storage item; key size 32, value size 16 + pub const AnnouncementDepositBase: Balance = deposit(1, 48); + pub const AnnouncementDepositFactor: Balance = deposit(0, 66); + pub const MaxPending: u16 = 32; +} + +/// The type used to represent the kinds of proxying allowed. +#[derive( + Copy, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Encode, + Decode, + RuntimeDebug, + MaxEncodedLen, + scale_info::TypeInfo, +)] +pub enum ProxyType { + /// Fully permissioned proxy. Can execute any call on behalf of _proxied_. + Any, + /// Can execute any call that does not transfer funds or assets. + NonTransfer, + /// Proxy with the ability to reject time-delay proxy announcements. + CancelProxy, + /// Assets proxy. Can execute any call from `assets`, **including asset transfers**. + Assets, + /// Owner proxy. Can execute calls related to asset ownership. + AssetOwner, + /// Asset manager. Can execute calls related to asset management. + AssetManager, + /// Collator selection proxy. Can execute calls related to collator selection mechanism. + Collator, +} +impl Default for ProxyType { + fn default() -> Self { + Self::Any + } +} + +impl InstanceFilter for ProxyType { + fn filter(&self, c: &RuntimeCall) -> bool { + match self { + ProxyType::Any => true, + ProxyType::NonTransfer => !matches!( + c, + RuntimeCall::Balances { .. } | + RuntimeCall::Assets { .. } | + RuntimeCall::Nfts { .. } | + RuntimeCall::Uniques { .. } + ), + ProxyType::CancelProxy => matches!( + c, + RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }) | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + ProxyType::Assets => { + matches!( + c, + RuntimeCall::Assets { .. } | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } | + RuntimeCall::Nfts { .. } | RuntimeCall::Uniques { .. } + ) + }, + ProxyType::AssetOwner => matches!( + c, + RuntimeCall::Assets(TrustBackedAssetsCall::create { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::start_destroy { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::destroy_accounts { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::destroy_approvals { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::finish_destroy { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::transfer_ownership { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::set_team { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::set_metadata { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::clear_metadata { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::set_min_balance { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::create { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::destroy { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::redeposit { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::transfer_ownership { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::set_team { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::set_collection_max_supply { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::lock_collection { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::create { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::destroy { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::transfer_ownership { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::set_team { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::set_metadata { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::set_attribute { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::set_collection_metadata { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::clear_metadata { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::clear_attribute { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::clear_collection_metadata { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::set_collection_max_supply { .. }) | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + ProxyType::AssetManager => matches!( + c, + RuntimeCall::Assets(TrustBackedAssetsCall::mint { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::burn { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::freeze { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::block { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::thaw { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::freeze_asset { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::thaw_asset { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::touch_other { .. }) | + RuntimeCall::Assets(TrustBackedAssetsCall::refund_other { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::force_mint { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::update_mint_settings { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::mint_pre_signed { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::set_attributes_pre_signed { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::lock_item_transfer { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::unlock_item_transfer { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::lock_item_properties { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::set_metadata { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::clear_metadata { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::set_collection_metadata { .. }) | + RuntimeCall::Nfts(pallet_nfts::Call::clear_collection_metadata { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::mint { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::burn { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::freeze { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::thaw { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::freeze_collection { .. }) | + RuntimeCall::Uniques(pallet_uniques::Call::thaw_collection { .. }) | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + ProxyType::Collator => matches!( + c, + RuntimeCall::CollatorSelection { .. } | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + } + } + + fn is_superset(&self, o: &Self) -> bool { + match (self, o) { + (x, y) if x == y => true, + (ProxyType::Any, _) => true, + (_, ProxyType::Any) => false, + (ProxyType::Assets, ProxyType::AssetOwner) => true, + (ProxyType::Assets, ProxyType::AssetManager) => true, + (ProxyType::NonTransfer, ProxyType::Collator) => true, + _ => false, + } + } +} + +impl pallet_proxy::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type Currency = Balances; + type ProxyType = ProxyType; + type ProxyDepositBase = ProxyDepositBase; + type ProxyDepositFactor = ProxyDepositFactor; + type MaxProxies = MaxProxies; + type WeightInfo = weights::pallet_proxy::WeightInfo; + type MaxPending = MaxPending; + type CallHasher = BlakeTwo256; + type AnnouncementDepositBase = AnnouncementDepositBase; + type AnnouncementDepositFactor = AnnouncementDepositFactor; +} + +parameter_types! { + pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); + pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); +} + +impl cumulus_pallet_parachain_system::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type OnSystemEvent = (); + type SelfParaId = parachain_info::Pallet; + type DmpQueue = frame_support::traits::EnqueueWithOrigin; + type ReservedDmpWeight = ReservedDmpWeight; + type OutboundXcmpMessageSource = XcmpQueue; + type XcmpMessageHandler = XcmpQueue; + type ReservedXcmpWeight = ReservedXcmpWeight; + type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases; + type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook< + Runtime, + RELAY_CHAIN_SLOT_DURATION_MILLIS, + BLOCK_PROCESSING_VELOCITY, + UNINCLUDED_SEGMENT_CAPACITY, + >; +} + +parameter_types! { + pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block; +} + +impl pallet_message_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type WeightInfo = weights::pallet_message_queue::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor< + cumulus_primitives_core::AggregateMessageOrigin, + >; + #[cfg(not(feature = "runtime-benchmarks"))] + type MessageProcessor = xcm_builder::ProcessXcmMessage< + AggregateMessageOrigin, + xcm_executor::XcmExecutor, + RuntimeCall, + >; + type Size = u32; + // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin: + type QueueChangeHandler = NarrowOriginToSibling; + type QueuePausedQuery = NarrowOriginToSibling; + type HeapSize = sp_core::ConstU32<{ 64 * 1024 }>; + type MaxStale = sp_core::ConstU32<8>; + type ServiceWeight = MessageQueueServiceWeight; +} + +impl parachain_info::Config for Runtime {} + +impl cumulus_pallet_aura_ext::Config for Runtime {} + +parameter_types! { + // Fellows pluralistic body. + pub const FellowsBodyId: BodyId = BodyId::Technical; +} + +impl cumulus_pallet_xcmp_queue::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type ChannelInfo = ParachainSystem; + type VersionWrapper = PolkadotXcm; + // Enqueue XCMP messages from siblings for later processing. + type XcmpQueue = TransformOrigin; + type MaxInboundSuspended = sp_core::ConstU32<1_000>; + type ControllerOrigin = EitherOfDiverse< + EnsureRoot, + EnsureXcm>, + >; + type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; + type PriceForSiblingDelivery = NoPriceForMessageDelivery; +} + +parameter_types! { + pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent; +} + +impl cumulus_pallet_dmp_queue::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_dmp_queue::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type DmpSink = frame_support::traits::EnqueueWithOrigin; +} + +parameter_types! { + pub const Period: u32 = 6 * HOURS; + pub const Offset: u32 = 0; +} + +impl pallet_session::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type ValidatorId = ::AccountId; + // we don't have stash and controller, thus we don't need the convert as well. + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ShouldEndSession = pallet_session::PeriodicSessions; + type NextSessionRotation = pallet_session::PeriodicSessions; + type SessionManager = CollatorSelection; + // Essentially just Aura, but let's be pedantic. + type SessionHandler = ::KeyTypeIdProviders; + type Keys = SessionKeys; + type WeightInfo = weights::pallet_session::WeightInfo; +} + +impl pallet_aura::Config for Runtime { + type AuthorityId = AuraId; + type DisabledValidators = (); + type MaxAuthorities = ConstU32<100_000>; + type AllowMultipleBlocksPerSlot = ConstBool; + #[cfg(feature = "experimental")] + type SlotDuration = pallet_aura::MinimumPeriodTimesTwo; +} + +parameter_types! { + pub const PotId: PalletId = PalletId(*b"PotStake"); + pub const SessionLength: BlockNumber = 6 * HOURS; + // `StakingAdmin` pluralistic body. + pub const StakingAdminBodyId: BodyId = BodyId::Defense; +} + +/// We allow root and the `StakingAdmin` to execute privileged collator selection operations. +pub type CollatorSelectionUpdateOrigin = EitherOfDiverse< + EnsureRoot, + EnsureXcm>, +>; + +impl pallet_collator_selection::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type UpdateOrigin = CollatorSelectionUpdateOrigin; + type PotId = PotId; + type MaxCandidates = ConstU32<100>; + type MinEligibleCollators = ConstU32<4>; + type MaxInvulnerables = ConstU32<20>; + // should be a multiple of session or things will get inconsistent + type KickThreshold = Period; + type ValidatorId = ::AccountId; + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ValidatorRegistration = Session; + type WeightInfo = weights::pallet_collator_selection::WeightInfo; +} + +impl pallet_asset_tx_payment::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Fungibles = Assets; + type OnChargeAssetTransaction = pallet_asset_tx_payment::FungiblesAdapter< + pallet_assets::BalanceToAssetBalance< + Balances, + Runtime, + ConvertInto, + TrustBackedAssetsInstance, + >, + AssetsToBlockAuthor, + >; +} + +parameter_types! { + pub const UniquesCollectionDeposit: Balance = 10 * UNITS; // 10 UNIT deposit to create uniques class + pub const UniquesItemDeposit: Balance = UNITS / 100; // 1 / 100 UNIT deposit to create uniques instance + pub const UniquesMetadataDepositBase: Balance = deposit(1, 129); + pub const UniquesAttributeDepositBase: Balance = deposit(1, 0); + pub const UniquesDepositPerByte: Balance = deposit(0, 1); +} + +impl pallet_uniques::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type CollectionId = u32; + type ItemId = u32; + type Currency = Balances; + type ForceOrigin = AssetsForceOrigin; + type CollectionDeposit = UniquesCollectionDeposit; + type ItemDeposit = UniquesItemDeposit; + type MetadataDepositBase = UniquesMetadataDepositBase; + type AttributeDepositBase = UniquesAttributeDepositBase; + type DepositPerByte = UniquesDepositPerByte; + type StringLimit = ConstU32<128>; + type KeyLimit = ConstU32<32>; // Max 32 bytes per key + type ValueLimit = ConstU32<64>; // Max 64 bytes per value + type WeightInfo = weights::pallet_uniques::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type Helper = (); + type CreateOrigin = AsEnsureOriginWithArg>; + type Locker = (); +} + +parameter_types! { + pub NftsPalletFeatures: PalletFeatures = PalletFeatures::all_enabled(); + pub const NftsMaxDeadlineDuration: BlockNumber = 12 * 30 * DAYS; + // re-use the Uniques deposits + pub const NftsCollectionDeposit: Balance = UniquesCollectionDeposit::get(); + pub const NftsItemDeposit: Balance = UniquesItemDeposit::get(); + pub const NftsMetadataDepositBase: Balance = UniquesMetadataDepositBase::get(); + pub const NftsAttributeDepositBase: Balance = UniquesAttributeDepositBase::get(); + pub const NftsDepositPerByte: Balance = UniquesDepositPerByte::get(); +} + +impl pallet_nfts::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type CollectionId = u32; + type ItemId = u32; + type Currency = Balances; + type CreateOrigin = AsEnsureOriginWithArg>; + type ForceOrigin = AssetsForceOrigin; + type Locker = (); + type CollectionDeposit = NftsCollectionDeposit; + type ItemDeposit = NftsItemDeposit; + type MetadataDepositBase = NftsMetadataDepositBase; + type AttributeDepositBase = NftsAttributeDepositBase; + type DepositPerByte = NftsDepositPerByte; + type StringLimit = ConstU32<256>; + type KeyLimit = ConstU32<64>; + type ValueLimit = ConstU32<256>; + type ApprovalsLimit = ConstU32<20>; + type ItemAttributesApprovalsLimit = ConstU32<30>; + type MaxTips = ConstU32<10>; + type MaxDeadlineDuration = NftsMaxDeadlineDuration; + type MaxAttributesPerCall = ConstU32<10>; + type Features = NftsPalletFeatures; + type OffchainSignature = Signature; + type OffchainPublic = ::Signer; + type WeightInfo = weights::pallet_nfts::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type Helper = (); +} + +// Create the runtime by composing the FRAME pallets that were previously configured. +construct_runtime!( + pub enum Runtime + { + // System support stuff. + System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, + ParachainSystem: cumulus_pallet_parachain_system::{ + Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned, + } = 1, + // RandomnessCollectiveFlip = 2 removed + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 3, + ParachainInfo: parachain_info::{Pallet, Storage, Config} = 4, + + // Monetary stuff. + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, + TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 11, + AssetTxPayment: pallet_asset_tx_payment::{Pallet, Event} = 12, + + // Collator support. the order of these 5 are important and shall not change. + Authorship: pallet_authorship::{Pallet, Storage} = 20, + CollatorSelection: pallet_collator_selection::{Pallet, Call, Storage, Event, Config} = 21, + Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, + Aura: pallet_aura::{Pallet, Storage, Config} = 23, + AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config} = 24, + + // XCM helpers. + XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, + PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 31, + CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, + DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, + MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event} = 34, + + // Handy utilities. + Utility: pallet_utility::{Pallet, Call, Event} = 40, + Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 41, + Proxy: pallet_proxy::{Pallet, Call, Storage, Event} = 42, + + // The main stage. + Assets: pallet_assets::::{Pallet, Call, Storage, Event} = 50, + Uniques: pallet_uniques::{Pallet, Call, Storage, Event} = 51, + Nfts: pallet_nfts::{Pallet, Call, Storage, Event} = 52, + ForeignAssets: pallet_assets::::{Pallet, Call, Storage, Event} = 53, + } +); + +/// The address format for describing accounts. +pub type Address = sp_runtime::MultiAddress; +/// Block type as expected by this runtime. +pub type Block = generic::Block; +/// A Block signed with a Justification +pub type SignedBlock = generic::SignedBlock; +/// BlockId type as expected by this runtime. +pub type BlockId = generic::BlockId; +/// The extension to the basic transaction logic. +pub type TxExtension = ( + frame_system::CheckNonZeroSender, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_asset_tx_payment::ChargeAssetTxPayment, +); +/// Unchecked extrinsic type as expected by this runtime. +pub type UncheckedExtrinsic = + generic::UncheckedExtrinsic; +/// Migrations to apply on runtime upgrade. +pub type Migrations = ( + // unreleased + pallet_collator_selection::migration::v1::MigrateToV1, +); + +/// Executive: handles dispatch to the various modules. +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + Migrations, +>; + +#[cfg(feature = "runtime-benchmarks")] +mod benches { + frame_benchmarking::define_benchmarks!( + [frame_system, SystemBench::] + [pallet_assets, Local] + [pallet_assets, Foreign] + [pallet_balances, Balances] + [pallet_message_queue, MessageQueue] + [pallet_multisig, Multisig] + [pallet_nfts, Nfts] + [pallet_proxy, Proxy] + [pallet_session, SessionBench::] + [pallet_uniques, Uniques] + [pallet_utility, Utility] + [pallet_timestamp, Timestamp] + [pallet_collator_selection, CollatorSelection] + [cumulus_pallet_parachain_system, ParachainSystem] + [cumulus_pallet_xcmp_queue, XcmpQueue] + [cumulus_pallet_dmp_queue, DmpQueue] + // XCM + [pallet_xcm, PalletXcmExtrinsicsBenchmark::] + // NOTE: Make sure you point to the individual modules below. + [pallet_xcm_benchmarks::fungible, XcmBalances] + [pallet_xcm_benchmarks::generic, XcmGeneric] + ); +} + +impl_runtime_apis! { + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + + fn authorities() -> Vec { + Aura::authorities().into_inner() + } + } + + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + + fn metadata_at_version(version: u32) -> Option { + Runtime::metadata_at_version(version) + } + + fn metadata_versions() -> sp_std::vec::Vec { + Runtime::metadata_versions() + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi + for Runtime + { + fn query_call_info( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::RuntimeDispatchInfo { + TransactionPayment::query_call_info(call, len) + } + fn query_call_fee_details( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_call_fee_details(call, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl assets_common::runtime_api::FungiblesApi< + Block, + AccountId, + > for Runtime + { + fn query_account_balances(account: AccountId) -> Result { + use assets_common::fungible_conversion::{convert, convert_balance}; + Ok([ + // collect pallet_balance + { + let balance = Balances::free_balance(account.clone()); + if balance > 0 { + vec![convert_balance::(balance)?] + } else { + vec![] + } + }, + // collect pallet_assets (TrustBackedAssets) + convert::<_, _, _, _, TrustBackedAssetsConvertedConcreteId>( + Assets::account_balances(account.clone()) + .iter() + .filter(|(_, balance)| balance > &0) + )?, + // collect pallet_assets (ForeignAssets) + convert::<_, _, _, _, ForeignAssetsConvertedConcreteId>( + ForeignAssets::account_balances(account) + .iter() + .filter(|(_, balance)| balance > &0) + )?, + // collect ... e.g. other tokens + ].concat().into()) + } + } + + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { + ParachainSystem::collect_collation_info(header) + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { + let weight = Executive::try_runtime_upgrade(checks).unwrap(); + (weight, RuntimeBlockWeights::get().max_block) + } + + fn execute_block( + block: Block, + state_root_check: bool, + signature_check: bool, + select: frame_try_runtime::TryStateSelect, + ) -> Weight { + // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to + // have a backtrace here. + Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap() + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; + + // This is defined once again in dispatch_benchmark, because list_benchmarks! + // and add_benchmarks! are macros exported by define_benchmarks! macros and those types + // are referenced in that call. + type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::; + type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::; + + // Benchmark files generated for `Assets/ForeignAssets` instances are by default + // `pallet_assets_assets.rs / pallet_assets_foreign_assets`, which is not really nice, + // so with this redefinition we can change names to nicer: + // `pallet_assets_local.rs / pallet_assets_foreign.rs`. + type Local = pallet_assets::Pallet::; + type Foreign = pallet_assets::Pallet::; + + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsWithSystem::storage_info(); + (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; + use sp_storage::TrackedStorageKey; + + use frame_system_benchmarking::Pallet as SystemBench; + impl frame_system_benchmarking::Config for Runtime { + fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); + Ok(()) + } + + fn verify_set_code() { + System::assert_last_event(cumulus_pallet_parachain_system::Event::::ValidationFunctionStored.into()); + } + } + + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + impl cumulus_pallet_session_benchmarking::Config for Runtime {} + + use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; + impl pallet_xcm::benchmarking::Config for Runtime { + fn reachable_dest() -> Option { + Some(Parent.into()) + } + + fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + // Relay/native token can be teleported between AH and Relay. + Some(( + MultiAsset { + fun: Fungible(EXISTENTIAL_DEPOSIT), + id: Concrete(Parent.into()) + }, + Parent.into(), + )) + } + + fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + // AH can reserve transfer native token to some random parachain. + let random_para_id = 43211234; + ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( + random_para_id.into() + ); + Some(( + MultiAsset { + fun: Fungible(EXISTENTIAL_DEPOSIT), + id: Concrete(Parent.into()) + }, + ParentThen(Parachain(random_para_id).into()).into(), + )) + } + } + + use xcm::latest::prelude::*; + use xcm_config::{DotLocation, MaxAssetsIntoHolding}; + use pallet_xcm_benchmarks::asset_instance_from; + + parameter_types! { + pub ExistentialDepositMultiAsset: Option = Some(( + xcm_config::DotLocation::get(), + ExistentialDeposit::get() + ).into()); + } + + impl pallet_xcm_benchmarks::Config for Runtime { + type XcmConfig = xcm_config::XcmConfig; + type AccountIdConverter = xcm_config::LocationToAccountId; + type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< + xcm_config::XcmConfig, + ExistentialDepositMultiAsset, + xcm_config::PriceForParentDelivery, + >; + fn valid_destination() -> Result { + Ok(DotLocation::get()) + } + fn worst_case_holding(depositable_count: u32) -> MultiAssets { + // A mix of fungible, non-fungible, and concrete assets. + let holding_non_fungibles = MaxAssetsIntoHolding::get() / 2 - depositable_count; + let holding_fungibles = holding_non_fungibles - 1; + let fungibles_amount: u128 = 100; + let mut assets = (0..holding_fungibles) + .map(|i| { + MultiAsset { + id: Concrete(GeneralIndex(i as u128).into()), + fun: Fungible(fungibles_amount * i as u128), + } + }) + .chain(core::iter::once(MultiAsset { id: Concrete(Here.into()), fun: Fungible(u128::MAX) })) + .chain((0..holding_non_fungibles).map(|i| MultiAsset { + id: Concrete(GeneralIndex(i as u128).into()), + fun: NonFungible(asset_instance_from(i)), + })) + .collect::>(); + + assets.push(MultiAsset { + id: Concrete(DotLocation::get()), + fun: Fungible(1_000_000 * UNITS), + }); + assets.into() + } + } + + parameter_types! { + pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + DotLocation::get(), + MultiAsset { fun: Fungible(UNITS), id: Concrete(DotLocation::get()) }, + )); + pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; + pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None; + } + + impl pallet_xcm_benchmarks::fungible::Config for Runtime { + type TransactAsset = Balances; + + type CheckedAccount = CheckedAccount; + type TrustedTeleporter = TrustedTeleporter; + type TrustedReserve = TrustedReserve; + + fn get_multi_asset() -> MultiAsset { + MultiAsset { + id: Concrete(DotLocation::get()), + fun: Fungible(UNITS), + } + } + } + + impl pallet_xcm_benchmarks::generic::Config for Runtime { + type TransactAsset = Balances; + type RuntimeCall = RuntimeCall; + + fn worst_case_response() -> (u64, Response) { + (0u64, Response::Version(Default::default())) + } + + fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + Ok((DotLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) + } + + fn subscribe_origin() -> Result { + Ok(DotLocation::get()) + } + + fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + let origin = DotLocation::get(); + let assets: MultiAssets = (Concrete(DotLocation::get()), 1_000 * UNITS).into(); + let ticket = MultiLocation { parents: 0, interior: Here }; + Ok((origin, ticket, assets)) + } + + fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn export_message_origin_and_destination( + ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + Err(BenchmarkError::Skip) + } + } + + type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::; + type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::; + + type Local = pallet_assets::Pallet::; + type Foreign = pallet_assets::Pallet::; + + let whitelist: Vec = vec![ + // Block Number + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), + // Total Issuance + hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), + // Execution Phase + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), + // Event Count + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), + // System Events + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), + //TODO: use from relay_well_known_keys::ACTIVE_CONFIG + hex_literal::hex!("06de3d8a54d27e44a9d5ce189618f22db4b49d95320d9021994c850f25b8e385").to_vec().into(), + ]; + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + add_benchmarks!(params, batches); + + Ok(batches) + } + } + + impl sp_genesis_builder::GenesisBuilder for Runtime { + fn create_default_config() -> Vec { + create_default_config::() + } + + fn build_config(config: Vec) -> sp_genesis_builder::Result { + build_config::(config) + } + } +} + +cumulus_pallet_parachain_system::register_validate_block! { + Runtime = Runtime, + BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{CENTS, MILLICENTS}; + use parachains_common::polkadot::fee; + use sp_runtime::traits::Zero; + use sp_weights::WeightToFee; + + /// We can fit at least 1000 transfers in a block. + #[test] + fn sane_block_weight() { + use pallet_balances::WeightInfo; + let block = RuntimeBlockWeights::get().max_block; + let base = RuntimeBlockWeights::get().get(DispatchClass::Normal).base_extrinsic; + let transfer = + base + weights::pallet_balances::WeightInfo::::transfer_allow_death(); + + let fit = block.checked_div_per_component(&transfer).unwrap_or_default(); + assert!(fit >= 1000, "{} should be at least 1000", fit); + } + + /// The fee for one transfer is at most 1 CENT. + #[test] + fn sane_transfer_fee() { + use pallet_balances::WeightInfo; + let base = RuntimeBlockWeights::get().get(DispatchClass::Normal).base_extrinsic; + let transfer = + base + weights::pallet_balances::WeightInfo::::transfer_allow_death(); + + let fee: Balance = fee::WeightToFee::weight_to_fee(&transfer); + assert!(fee <= CENTS, "{} MILLICENTS should be at most 1000", fee / MILLICENTS); + } + + /// Weight is being charged for both dimensions. + #[test] + fn weight_charged_for_both_components() { + let fee: Balance = fee::WeightToFee::weight_to_fee(&Weight::from_parts(10_000, 0)); + assert!(!fee.is_zero(), "Charges for ref time"); + + let fee: Balance = fee::WeightToFee::weight_to_fee(&Weight::from_parts(0, 10_000)); + assert_eq!(fee, CENTS, "10kb maps to CENT"); + } + + /// Filling up a block by proof size is at most 30 times more expensive than ref time. + /// + /// This is just a sanity check. + #[test] + fn full_block_fee_ratio() { + let block = RuntimeBlockWeights::get().max_block; + let time_fee: Balance = + fee::WeightToFee::weight_to_fee(&Weight::from_parts(block.ref_time(), 0)); + let proof_fee: Balance = + fee::WeightToFee::weight_to_fee(&Weight::from_parts(0, block.proof_size())); + + let proof_o_time = proof_fee.checked_div(time_fee).unwrap_or_default(); + assert!(proof_o_time <= 30, "{} should be at most 30", proof_o_time); + let time_o_proof = time_fee.checked_div(proof_fee).unwrap_or_default(); + assert!(time_o_proof <= 30, "{} should be at most 30", time_o_proof); + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/block_weights.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/block_weights.rs new file mode 100644 index 00000000000..e7fdb2aae2a --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/block_weights.rs @@ -0,0 +1,53 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; + + parameter_types! { + /// Importing a block with 0 Extrinsics. + pub const BlockExecutionWeight: Weight = + Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); + } + + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; + + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::BlockExecutionWeight::get(); + + // At least 100 µs. + assert!( + w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, + "Weight should be at least 100 µs." + ); + // At most 50 ms. + assert!( + w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, + "Weight should be at most 50 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_dmp_queue.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_dmp_queue.rs new file mode 100644 index 00000000000..cc41dcd6cbb --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_dmp_queue.rs @@ -0,0 +1,131 @@ +// 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 . + +//! Autogenerated weights for `cumulus_pallet_dmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-10-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=cumulus_pallet_dmp_queue +// --chain=asset-hub-kusama-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_dmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_dmp_queue::WeightInfo for WeightInfo { + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65696` + // Estimated: `69161` + // Minimum execution time: 124_651_000 picoseconds. + Weight::from_parts(127_857_000, 0) + .saturating_add(Weight::from_parts(0, 69161)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65659` + // Estimated: `69124` + // Minimum execution time: 65_684_000 picoseconds. + Weight::from_parts(68_039_000, 0) + .saturating_add(Weight::from_parts(0, 69124)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_overweight_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65726` + // Estimated: `69191` + // Minimum execution time: 117_657_000 picoseconds. + Weight::from_parts(122_035_000, 0) + .saturating_add(Weight::from_parts(0, 69191)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + fn on_idle_overweight_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65689` + // Estimated: `69154` + // Minimum execution time: 59_799_000 picoseconds. + Weight::from_parts(61_354_000, 0) + .saturating_add(Weight::from_parts(0, 69154)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_parachain_system.rs new file mode 100644 index 00000000000..970534560c6 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_parachain_system.rs @@ -0,0 +1,80 @@ +// 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. + +//! Autogenerated weights for `cumulus_pallet_parachain_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-03-28, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `i9`, CPU: `13th Gen Intel(R) Core(TM) i9-13900K` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("westmint-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --chain +// westmint-dev +// --pallet +// cumulus_pallet_parachain_system +// --extrinsic +// * +// --execution +// wasm +// --wasm-execution +// compiled +// --output +// parachains/runtimes/assets/westmint/src/weights +// --steps +// 50 +// --repeat +// 20 + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_parachain_system`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_parachain_system::WeightInfo for WeightInfo { + /// Storage: ParachainSystem LastDmqMqcHead (r:1 w:1) + /// Proof Skipped: ParachainSystem LastDmqMqcHead (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem ReservedDmpWeightOverride (r:1 w:0) + /// Proof Skipped: ParachainSystem ReservedDmpWeightOverride (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: ParachainSystem ProcessedDownwardMessages (r:0 w:1) + /// Proof Skipped: ParachainSystem ProcessedDownwardMessages (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: MessageQueue Pages (r:0 w:16) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + /// The range of component `n` is `[0, 1000]`. + fn enqueue_inbound_downward_messages(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `12` + // Estimated: `8013` + // Minimum execution time: 1_638_000 picoseconds. + Weight::from_parts(1_690_000, 0) + .saturating_add(Weight::from_parts(0, 8013)) + // Standard Error: 22_873 + .saturating_add(Weight::from_parts(24_208_496, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs new file mode 100644 index 00000000000..89c80d0be62 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs @@ -0,0 +1,148 @@ +// 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. + +//! Autogenerated weights for `cumulus_pallet_xcmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-09-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `Olivers-MacBook-Pro.local`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --pallet +// cumulus-pallet-xcmp-queue +// --chain +// asset-hub-polkadot-dev +// --output +// cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs +// --extrinsic +// + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_xcmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_xcmp_queue::WeightInfo for WeightInfo { + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:1) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn set_config_with_u32() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `1561` + // Minimum execution time: 6_000_000 picoseconds. + Weight::from_parts(6_000_000, 0) + .saturating_add(Weight::from_parts(0, 1561)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:0) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn enqueue_xcmp_message() -> Weight { + // Proof Size summary in bytes: + // Measured: `82` + // Estimated: `3517` + // Minimum execution time: 14_000_000 picoseconds. + Weight::from_parts(15_000_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn suspend_channel() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `1561` + // Minimum execution time: 3_000_000 picoseconds. + Weight::from_parts(4_000_000, 0) + .saturating_add(Weight::from_parts(0, 1561)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn resume_channel() -> Weight { + // Proof Size summary in bytes: + // Measured: `111` + // Estimated: `1596` + // Minimum execution time: 4_000_000 picoseconds. + Weight::from_parts(5_000_000, 0) + .saturating_add(Weight::from_parts(0, 1596)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn take_first_concatenated_xcm() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 44_000_000 picoseconds. + Weight::from_parts(46_000_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Storage: `XcmpQueue::InboundXcmpMessages` (r:1 w:1) + /// Proof: `XcmpQueue::InboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:0) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65711` + // Estimated: `69176` + // Minimum execution time: 62_000_000 picoseconds. + Weight::from_parts(68_000_000, 0) + .saturating_add(Weight::from_parts(0, 69176)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65710` + // Estimated: `69175` + // Minimum execution time: 42_000_000 picoseconds. + Weight::from_parts(45_000_000, 0) + .saturating_add(Weight::from_parts(0, 69175)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/extrinsic_weights.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/extrinsic_weights.rs new file mode 100644 index 00000000000..1a4adb968bb --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/extrinsic_weights.rs @@ -0,0 +1,53 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; + + parameter_types! { + /// Executing a NO-OP `System::remarks` Extrinsic. + pub const ExtrinsicBaseWeight: Weight = + Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); + } + + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; + + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::ExtrinsicBaseWeight::get(); + + // At least 10 µs. + assert!( + w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, + "Weight should be at least 10 µs." + ); + // At most 1 ms. + assert!( + w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/frame_system.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/frame_system.rs new file mode 100644 index 00000000000..0b988fd0f6f --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/frame_system.rs @@ -0,0 +1,154 @@ +// 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. + +//! Autogenerated weights for `frame_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=frame_system +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `frame_system`. +pub struct WeightInfo(PhantomData); +impl frame_system::WeightInfo for WeightInfo { + /// The range of component `b` is `[0, 3932160]`. + fn remark(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_956_000 picoseconds. + Weight::from_parts(3_441_280, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 0 + .saturating_add(Weight::from_parts(388, 0).saturating_mul(b.into())) + } + /// The range of component `b` is `[0, 3932160]`. + fn remark_with_event(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_267_000 picoseconds. + Weight::from_parts(7_462_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 3 + .saturating_add(Weight::from_parts(1_816, 0).saturating_mul(b.into())) + } + /// Storage: `System::Digest` (r:1 w:1) + /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) + /// Proof: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) + fn set_heap_pages() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `1485` + // Minimum execution time: 3_757_000 picoseconds. + Weight::from_parts(4_021_000, 0) + .saturating_add(Weight::from_parts(0, 1485)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ParachainSystem::ValidationData` (r:1 w:0) + /// Proof: `ParachainSystem::ValidationData` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpgradeRestrictionSignal` (r:1 w:0) + /// Proof: `ParachainSystem::UpgradeRestrictionSignal` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingValidationCode` (r:1 w:1) + /// Proof: `ParachainSystem::PendingValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::NewValidationCode` (r:0 w:1) + /// Proof: `ParachainSystem::NewValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::DidSetValidationCode` (r:0 w:1) + /// Proof: `ParachainSystem::DidSetValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn set_code() -> Weight { + // Proof Size summary in bytes: + // Measured: `119` + // Estimated: `1604` + // Minimum execution time: 97_958_650_000 picoseconds. + Weight::from_parts(102_129_539_000, 0) + .saturating_add(Weight::from_parts(0, 1604)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `i` is `[0, 1000]`. + fn set_storage(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_327_000 picoseconds. + Weight::from_parts(2_511_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 2_186 + .saturating_add(Weight::from_parts(755_085, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `i` is `[0, 1000]`. + fn kill_storage(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_114_000 picoseconds. + Weight::from_parts(2_177_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_174 + .saturating_add(Weight::from_parts(584_644, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `p` is `[0, 1000]`. + fn kill_prefix(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `84 + p * (69 ±0)` + // Estimated: `77 + p * (70 ±0)` + // Minimum execution time: 3_799_000 picoseconds. + Weight::from_parts(3_910_000, 0) + .saturating_add(Weight::from_parts(0, 77)) + // Standard Error: 1_968 + .saturating_add(Weight::from_parts(1_220_745, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) + .saturating_add(Weight::from_parts(0, 70).saturating_mul(p.into())) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/mod.rs new file mode 100644 index 00000000000..0823dcad88e --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/mod.rs @@ -0,0 +1,42 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod block_weights; +pub mod cumulus_pallet_dmp_queue; +pub mod cumulus_pallet_parachain_system; +pub mod cumulus_pallet_xcmp_queue; +pub mod extrinsic_weights; +pub mod frame_system; +pub mod pallet_assets_foreign; +pub mod pallet_assets_local; +pub mod pallet_balances; +pub mod pallet_collator_selection; +pub mod pallet_message_queue; +pub mod pallet_multisig; +pub mod pallet_nfts; +pub mod pallet_proxy; +pub mod pallet_session; +pub mod pallet_timestamp; +pub mod pallet_uniques; +pub mod pallet_utility; +pub mod pallet_xcm; +pub mod paritydb_weights; +pub mod rocksdb_weights; +pub mod xcm; + +pub use block_weights::constants::BlockExecutionWeight; +pub use extrinsic_weights::constants::ExtrinsicBaseWeight; +pub use paritydb_weights::constants::ParityDbWeight; +pub use rocksdb_weights::constants::RocksDbWeight; diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_assets_foreign.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_assets_foreign.rs new file mode 100644 index 00000000000..adb686c0afc --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_assets_foreign.rs @@ -0,0 +1,532 @@ +// 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. + +//! Autogenerated weights for `pallet_assets` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_assets +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_assets`. +pub struct WeightInfo(PhantomData); +impl pallet_assets::WeightInfo for WeightInfo { + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn create() -> Weight { + // Proof Size summary in bytes: + // Measured: `107` + // Estimated: `4273` + // Minimum execution time: 29_979_000 picoseconds. + Weight::from_parts(30_763_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn force_create() -> Weight { + // Proof Size summary in bytes: + // Measured: `4` + // Estimated: `4273` + // Minimum execution time: 12_255_000 picoseconds. + Weight::from_parts(12_614_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn start_destroy() -> Weight { + // Proof Size summary in bytes: + // Measured: `276` + // Estimated: `4273` + // Minimum execution time: 15_240_000 picoseconds. + Weight::from_parts(15_627_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:1001 w:1000) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1000 w:1000) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `c` is `[0, 1000]`. + /// The range of component `c` is `[0, 1000]`. + fn destroy_accounts(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + c * (208 ±0)` + // Estimated: `4273 + c * (3207 ±0)` + // Minimum execution time: 17_814_000 picoseconds. + Weight::from_parts(18_006_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + // Standard Error: 10_358 + .saturating_add(Weight::from_parts(15_409_972, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(c.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 3207).saturating_mul(c.into())) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Approvals` (r:1001 w:1000) + /// Proof: `ForeignAssets::Approvals` (`max_values`: None, `max_size`: Some(746), added: 3221, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 1000]`. + /// The range of component `a` is `[0, 1000]`. + fn destroy_approvals(a: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `413 + a * (86 ±0)` + // Estimated: `4273 + a * (3221 ±0)` + // Minimum execution time: 18_957_000 picoseconds. + Weight::from_parts(19_347_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + // Standard Error: 5_051 + .saturating_add(Weight::from_parts(15_416_931, 0).saturating_mul(a.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(a.into()))) + .saturating_add(Weight::from_parts(0, 3221).saturating_mul(a.into())) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Metadata` (r:1 w:0) + /// Proof: `ForeignAssets::Metadata` (`max_values`: None, `max_size`: Some(738), added: 3213, mode: `MaxEncodedLen`) + fn finish_destroy() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 15_409_000 picoseconds. + Weight::from_parts(15_835_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + fn mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 26_753_000 picoseconds. + Weight::from_parts(27_349_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + fn burn() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `4273` + // Minimum execution time: 33_918_000 picoseconds. + Weight::from_parts(34_624_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:2 w:2) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `7404` + // Minimum execution time: 45_863_000 picoseconds. + Weight::from_parts(46_674_000, 0) + .saturating_add(Weight::from_parts(0, 7404)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:2 w:2) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_keep_alive() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `7404` + // Minimum execution time: 40_592_000 picoseconds. + Weight::from_parts(41_582_000, 0) + .saturating_add(Weight::from_parts(0, 7404)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:2 w:2) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `7404` + // Minimum execution time: 46_170_000 picoseconds. + Weight::from_parts(46_880_000, 0) + .saturating_add(Weight::from_parts(0, 7404)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:0) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + fn freeze() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `4273` + // Minimum execution time: 18_421_000 picoseconds. + Weight::from_parts(19_003_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:0) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + fn thaw() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `4273` + // Minimum execution time: 18_009_000 picoseconds. + Weight::from_parts(18_683_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn freeze_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `276` + // Estimated: `4273` + // Minimum execution time: 14_702_000 picoseconds. + Weight::from_parts(15_118_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn thaw_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `276` + // Estimated: `4273` + // Minimum execution time: 14_329_000 picoseconds. + Weight::from_parts(14_857_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Metadata` (r:1 w:0) + /// Proof: `ForeignAssets::Metadata` (`max_values`: None, `max_size`: Some(738), added: 3213, mode: `MaxEncodedLen`) + fn transfer_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 15_776_000 picoseconds. + Weight::from_parts(16_337_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn set_team() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 14_290_000 picoseconds. + Weight::from_parts(14_655_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:0) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Metadata` (r:1 w:1) + /// Proof: `ForeignAssets::Metadata` (`max_values`: None, `max_size`: Some(738), added: 3213, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + fn set_metadata(_n: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 29_296_000 picoseconds. + Weight::from_parts(30_512_261, 0) + .saturating_add(Weight::from_parts(0, 4273)) + // Standard Error: 474 + .saturating_add(Weight::from_parts(530, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:0) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Metadata` (r:1 w:1) + /// Proof: `ForeignAssets::Metadata` (`max_values`: None, `max_size`: Some(738), added: 3213, mode: `MaxEncodedLen`) + fn clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `406` + // Estimated: `4273` + // Minimum execution time: 30_342_000 picoseconds. + Weight::from_parts(31_030_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:0) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Metadata` (r:1 w:1) + /// Proof: `ForeignAssets::Metadata` (`max_values`: None, `max_size`: Some(738), added: 3213, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + fn force_set_metadata(n: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `81` + // Estimated: `4273` + // Minimum execution time: 13_574_000 picoseconds. + Weight::from_parts(14_181_016, 0) + .saturating_add(Weight::from_parts(0, 4273)) + // Standard Error: 262 + .saturating_add(Weight::from_parts(420, 0).saturating_mul(n.into())) + // Standard Error: 262 + .saturating_add(Weight::from_parts(1_118, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:0) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Metadata` (r:1 w:1) + /// Proof: `ForeignAssets::Metadata` (`max_values`: None, `max_size`: Some(738), added: 3213, mode: `MaxEncodedLen`) + fn force_clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `406` + // Estimated: `4273` + // Minimum execution time: 29_679_000 picoseconds. + Weight::from_parts(30_346_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn force_asset_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 13_334_000 picoseconds. + Weight::from_parts(13_827_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Approvals` (r:1 w:1) + /// Proof: `ForeignAssets::Approvals` (`max_values`: None, `max_size`: Some(746), added: 3221, mode: `MaxEncodedLen`) + fn approve_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `276` + // Estimated: `4273` + // Minimum execution time: 32_648_000 picoseconds. + Weight::from_parts(33_555_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Approvals` (r:1 w:1) + /// Proof: `ForeignAssets::Approvals` (`max_values`: None, `max_size`: Some(746), added: 3221, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:2 w:2) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_approved() -> Weight { + // Proof Size summary in bytes: + // Measured: `520` + // Estimated: `7404` + // Minimum execution time: 65_431_000 picoseconds. + Weight::from_parts(66_502_000, 0) + .saturating_add(Weight::from_parts(0, 7404)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Approvals` (r:1 w:1) + /// Proof: `ForeignAssets::Approvals` (`max_values`: None, `max_size`: Some(746), added: 3221, mode: `MaxEncodedLen`) + fn cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `446` + // Estimated: `4273` + // Minimum execution time: 35_207_000 picoseconds. + Weight::from_parts(35_915_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Approvals` (r:1 w:1) + /// Proof: `ForeignAssets::Approvals` (`max_values`: None, `max_size`: Some(746), added: 3221, mode: `MaxEncodedLen`) + fn force_cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `446` + // Estimated: `4273` + // Minimum execution time: 35_768_000 picoseconds. + Weight::from_parts(36_553_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn set_min_balance() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 15_108_000 picoseconds. + Weight::from_parts(15_556_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn touch() -> Weight { + // Proof Size summary in bytes: + // Measured: `345` + // Estimated: `4273` + // Minimum execution time: 34_373_000 picoseconds. + Weight::from_parts(35_200_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn touch_other() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4273` + // Minimum execution time: 32_201_000 picoseconds. + Weight::from_parts(33_591_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn refund() -> Weight { + // Proof Size summary in bytes: + // Measured: `471` + // Estimated: `4273` + // Minimum execution time: 31_148_000 picoseconds. + Weight::from_parts(31_751_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Asset` (r:1 w:1) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + fn refund_other() -> Weight { + // Proof Size summary in bytes: + // Measured: `401` + // Estimated: `4273` + // Minimum execution time: 29_127_000 picoseconds. + Weight::from_parts(29_922_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ForeignAssets::Asset` (r:1 w:0) + /// Proof: `ForeignAssets::Asset` (`max_values`: None, `max_size`: Some(808), added: 3283, mode: `MaxEncodedLen`) + /// Storage: `ForeignAssets::Account` (r:1 w:1) + /// Proof: `ForeignAssets::Account` (`max_values`: None, `max_size`: Some(732), added: 3207, mode: `MaxEncodedLen`) + fn block() -> Weight { + // Proof Size summary in bytes: + // Measured: `350` + // Estimated: `4273` + // Minimum execution time: 18_386_000 picoseconds. + Weight::from_parts(18_762_000, 0) + .saturating_add(Weight::from_parts(0, 4273)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_assets_local.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_assets_local.rs new file mode 100644 index 00000000000..810f5b57c45 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_assets_local.rs @@ -0,0 +1,528 @@ +// 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. + +//! Autogenerated weights for `pallet_assets` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_assets +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_assets`. +pub struct WeightInfo(PhantomData); +impl pallet_assets::WeightInfo for WeightInfo { + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn create() -> Weight { + // Proof Size summary in bytes: + // Measured: `109` + // Estimated: `3675` + // Minimum execution time: 26_698_000 picoseconds. + Weight::from_parts(27_507_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn force_create() -> Weight { + // Proof Size summary in bytes: + // Measured: `6` + // Estimated: `3675` + // Minimum execution time: 10_833_000 picoseconds. + Weight::from_parts(11_314_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn start_destroy() -> Weight { + // Proof Size summary in bytes: + // Measured: `277` + // Estimated: `3675` + // Minimum execution time: 13_389_000 picoseconds. + Weight::from_parts(14_231_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1001 w:1000) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1000 w:1000) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `c` is `[0, 1000]`. + /// The range of component `c` is `[0, 1000]`. + fn destroy_accounts(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + c * (208 ±0)` + // Estimated: `3675 + c * (2609 ±0)` + // Minimum execution time: 16_027_000 picoseconds. + Weight::from_parts(16_455_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + // Standard Error: 10_266 + .saturating_add(Weight::from_parts(15_263_742, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(c.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 2609).saturating_mul(c.into())) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Approvals` (r:1001 w:1000) + /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 1000]`. + /// The range of component `a` is `[0, 1000]`. + fn destroy_approvals(a: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `414 + a * (86 ±0)` + // Estimated: `3675 + a * (2623 ±0)` + // Minimum execution time: 17_167_000 picoseconds. + Weight::from_parts(17_397_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + // Standard Error: 5_072 + .saturating_add(Weight::from_parts(15_429_203, 0).saturating_mul(a.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(a.into()))) + .saturating_add(Weight::from_parts(0, 2623).saturating_mul(a.into())) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:0) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + fn finish_destroy() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 13_694_000 picoseconds. + Weight::from_parts(14_239_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 24_406_000 picoseconds. + Weight::from_parts(24_981_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn burn() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `3675` + // Minimum execution time: 31_372_000 picoseconds. + Weight::from_parts(32_021_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:2 w:2) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `6208` + // Minimum execution time: 42_982_000 picoseconds. + Weight::from_parts(43_918_000, 0) + .saturating_add(Weight::from_parts(0, 6208)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:2 w:2) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_keep_alive() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `6208` + // Minimum execution time: 37_161_000 picoseconds. + Weight::from_parts(38_756_000, 0) + .saturating_add(Weight::from_parts(0, 6208)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:2 w:2) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `6208` + // Minimum execution time: 43_141_000 picoseconds. + Weight::from_parts(44_187_000, 0) + .saturating_add(Weight::from_parts(0, 6208)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn freeze() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `3675` + // Minimum execution time: 16_721_000 picoseconds. + Weight::from_parts(17_433_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn thaw() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `3675` + // Minimum execution time: 16_623_000 picoseconds. + Weight::from_parts(17_110_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn freeze_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `277` + // Estimated: `3675` + // Minimum execution time: 13_079_000 picoseconds. + Weight::from_parts(13_700_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn thaw_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `277` + // Estimated: `3675` + // Minimum execution time: 13_026_000 picoseconds. + Weight::from_parts(13_444_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:0) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + fn transfer_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 13_945_000 picoseconds. + Weight::from_parts(14_792_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn set_team() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 12_800_000 picoseconds. + Weight::from_parts(13_183_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:1) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + fn set_metadata(_n: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 27_637_000 picoseconds. + Weight::from_parts(28_967_060, 0) + .saturating_add(Weight::from_parts(0, 3675)) + // Standard Error: 464 + .saturating_add(Weight::from_parts(572, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:1) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + fn clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `407` + // Estimated: `3675` + // Minimum execution time: 28_427_000 picoseconds. + Weight::from_parts(28_961_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:1) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + /// The range of component `n` is `[0, 50]`. + /// The range of component `s` is `[0, 50]`. + fn force_set_metadata(_n: u32, s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `82` + // Estimated: `3675` + // Minimum execution time: 12_251_000 picoseconds. + Weight::from_parts(12_928_907, 0) + .saturating_add(Weight::from_parts(0, 3675)) + // Standard Error: 244 + .saturating_add(Weight::from_parts(1_800, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Metadata` (r:1 w:1) + /// Proof: `Assets::Metadata` (`max_values`: None, `max_size`: Some(140), added: 2615, mode: `MaxEncodedLen`) + fn force_clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `407` + // Estimated: `3675` + // Minimum execution time: 28_263_000 picoseconds. + Weight::from_parts(29_165_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn force_asset_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 12_343_000 picoseconds. + Weight::from_parts(12_659_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Approvals` (r:1 w:1) + /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + fn approve_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `277` + // Estimated: `3675` + // Minimum execution time: 31_113_000 picoseconds. + Weight::from_parts(31_798_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Approvals` (r:1 w:1) + /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:2 w:2) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_approved() -> Weight { + // Proof Size summary in bytes: + // Measured: `521` + // Estimated: `6208` + // Minimum execution time: 61_428_000 picoseconds. + Weight::from_parts(62_707_000, 0) + .saturating_add(Weight::from_parts(0, 6208)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Approvals` (r:1 w:1) + /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + fn cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `447` + // Estimated: `3675` + // Minimum execution time: 33_538_000 picoseconds. + Weight::from_parts(34_216_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Approvals` (r:1 w:1) + /// Proof: `Assets::Approvals` (`max_values`: None, `max_size`: Some(148), added: 2623, mode: `MaxEncodedLen`) + fn force_cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `447` + // Estimated: `3675` + // Minimum execution time: 33_870_000 picoseconds. + Weight::from_parts(34_709_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn set_min_balance() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 13_358_000 picoseconds. + Weight::from_parts(13_735_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn touch() -> Weight { + // Proof Size summary in bytes: + // Measured: `346` + // Estimated: `3675` + // Minimum execution time: 32_159_000 picoseconds. + Weight::from_parts(32_998_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn touch_other() -> Weight { + // Proof Size summary in bytes: + // Measured: `243` + // Estimated: `3675` + // Minimum execution time: 30_709_000 picoseconds. + Weight::from_parts(31_486_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn refund() -> Weight { + // Proof Size summary in bytes: + // Measured: `472` + // Estimated: `3675` + // Minimum execution time: 29_557_000 picoseconds. + Weight::from_parts(30_510_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + /// Storage: `Assets::Asset` (r:1 w:1) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + fn refund_other() -> Weight { + // Proof Size summary in bytes: + // Measured: `402` + // Estimated: `3675` + // Minimum execution time: 28_027_000 picoseconds. + Weight::from_parts(28_865_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Assets::Asset` (r:1 w:0) + /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) + /// Storage: `Assets::Account` (r:1 w:1) + /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) + fn block() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `3675` + // Minimum execution time: 16_758_000 picoseconds. + Weight::from_parts(17_280_000, 0) + .saturating_add(Weight::from_parts(0, 3675)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_balances.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_balances.rs new file mode 100644 index 00000000000..7c4501e6d88 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_balances.rs @@ -0,0 +1,152 @@ +// 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. + +//! Autogenerated weights for `pallet_balances` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_balances +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_balances`. +pub struct WeightInfo(PhantomData); +impl pallet_balances::WeightInfo for WeightInfo { + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_allow_death() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 56_173_000 picoseconds. + Weight::from_parts(57_097_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_keep_alive() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 41_470_000 picoseconds. + Weight::from_parts(42_051_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_set_balance_creating() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `3593` + // Minimum execution time: 14_771_000 picoseconds. + Weight::from_parts(15_125_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_set_balance_killing() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `3593` + // Minimum execution time: 22_210_000 picoseconds. + Weight::from_parts(22_712_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `6196` + // Minimum execution time: 57_475_000 picoseconds. + Weight::from_parts(58_343_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_all() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 52_139_000 picoseconds. + Weight::from_parts(52_601_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_unreserve() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `3593` + // Minimum execution time: 17_372_000 picoseconds. + Weight::from_parts(17_978_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:999 w:999) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `u` is `[1, 1000]`. + fn upgrade_accounts(u: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + u * (136 ±0)` + // Estimated: `990 + u * (2603 ±0)` + // Minimum execution time: 17_143_000 picoseconds. + Weight::from_parts(17_475_000, 0) + .saturating_add(Weight::from_parts(0, 990)) + // Standard Error: 16_909 + .saturating_add(Weight::from_parts(15_474_628, 0).saturating_mul(u.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(u.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(u.into()))) + .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_collator_selection.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_collator_selection.rs new file mode 100644 index 00000000000..b3062984baf --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_collator_selection.rs @@ -0,0 +1,246 @@ +// 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. + +//! Autogenerated weights for `pallet_collator_selection` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_collator_selection +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_collator_selection`. +pub struct WeightInfo(PhantomData); +impl pallet_collator_selection::WeightInfo for WeightInfo { + /// Storage: `Session::NextKeys` (r:20 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::Invulnerables` (r:0 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// The range of component `b` is `[1, 20]`. + fn set_invulnerables(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `163 + b * (79 ±0)` + // Estimated: `1154 + b * (2555 ±0)` + // Minimum execution time: 14_882_000 picoseconds. + Weight::from_parts(12_290_529, 0) + .saturating_add(Weight::from_parts(0, 1154)) + // Standard Error: 6_842 + .saturating_add(Weight::from_parts(3_189_571, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(b.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(Weight::from_parts(0, 2555).saturating_mul(b.into())) + } + /// Storage: `Session::NextKeys` (r:1 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `b` is `[1, 19]`. + /// The range of component `c` is `[1, 99]`. + fn add_invulnerable(b: u32, c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `756 + b * (32 ±0) + c * (53 ±0)` + // Estimated: `6287 + b * (37 ±0) + c * (53 ±0)` + // Minimum execution time: 48_113_000 picoseconds. + Weight::from_parts(49_767_909, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_725 + .saturating_add(Weight::from_parts(232_655, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 37).saturating_mul(b.into())) + .saturating_add(Weight::from_parts(0, 53).saturating_mul(c.into())) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:0) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// The range of component `b` is `[5, 20]`. + fn remove_invulnerable(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `119 + b * (32 ±0)` + // Estimated: `6287` + // Minimum execution time: 16_228_000 picoseconds. + Weight::from_parts(16_351_387, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_953 + .saturating_add(Weight::from_parts(140_754, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::DesiredCandidates` (r:0 w:1) + /// Proof: `CollatorSelection::DesiredCandidates` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn set_desired_candidates() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_541_000 picoseconds. + Weight::from_parts(7_720_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::CandidacyBond` (r:0 w:1) + /// Proof: `CollatorSelection::CandidacyBond` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + fn set_candidacy_bond(_c: u32, _k: u32) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_402_000 picoseconds. + Weight::from_parts(7_729_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::DesiredCandidates` (r:1 w:0) + /// Proof: `CollatorSelection::DesiredCandidates` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `Session::NextKeys` (r:1 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::CandidacyBond` (r:1 w:0) + /// Proof: `CollatorSelection::CandidacyBond` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// The range of component `c` is `[1, 99]`. + fn register_as_candidate(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `736 + c * (52 ±0)` + // Estimated: `6287 + c * (54 ±0)` + // Minimum execution time: 41_874_000 picoseconds. + Weight::from_parts(45_654_015, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_317 + .saturating_add(Weight::from_parts(221_237, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(2)) + .saturating_add(Weight::from_parts(0, 54).saturating_mul(c.into())) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// The range of component `c` is `[4, 100]`. + fn leave_intent(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 33_693_000 picoseconds. + Weight::from_parts(37_321_527, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 3_499 + .saturating_add(Weight::from_parts(182_068, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + fn update_bond(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 34_814_000 picoseconds. + Weight::from_parts(36_371_520, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_391 + .saturating_add(Weight::from_parts(201_700, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + fn take_candidate_slot(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 34_814_000 picoseconds. + Weight::from_parts(36_371_520, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_391 + .saturating_add(Weight::from_parts(201_700, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `System::BlockWeight` (r:1 w:1) + /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + fn note_author() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `6196` + // Minimum execution time: 44_412_000 picoseconds. + Weight::from_parts(45_196_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:0) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:100 w:0) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `System::BlockWeight` (r:1 w:1) + /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:97 w:97) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `r` is `[1, 100]`. + /// The range of component `c` is `[1, 100]`. + fn new_session(r: u32, c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `2243 + c * (97 ±0) + r * (112 ±0)` + // Estimated: `6287 + c * (2519 ±0) + r * (2603 ±0)` + // Minimum execution time: 17_360_000 picoseconds. + Weight::from_parts(17_599_000, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 350_829 + .saturating_add(Weight::from_parts(15_375_949, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(c.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 2519).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(0, 2603).saturating_mul(r.into())) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_message_queue.rs new file mode 100644 index 00000000000..a9f0cb07cfe --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_message_queue.rs @@ -0,0 +1,179 @@ +// 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. + +//! Autogenerated weights for `pallet_message_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-03-24, STEPS: `2`, REPEAT: `1`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `i9`, CPU: `13th Gen Intel(R) Core(TM) i9-13900K` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("westmint-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --chain +// westmint-dev +// --pallet +// pallet_message_queue +// --extrinsic +// * +// --execution +// wasm +// --wasm-execution +// compiled +// --output +// parachains/runtimes/assets/westmint/src/weights + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `pallet_message_queue`. +pub struct WeightInfo(PhantomData); +impl pallet_message_queue::WeightInfo for WeightInfo { + /// Storage: MessageQueue ServiceHead (r:1 w:0) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: MessageQueue BookStateFor (r:2 w:2) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn ready_ring_knit() -> Weight { + // Proof Size summary in bytes: + // Measured: `189` + // Estimated: `7534` + // Minimum execution time: 12_192_000 picoseconds. + Weight::from_parts(12_192_000, 0) + .saturating_add(Weight::from_parts(0, 7534)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:2 w:2) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + fn ready_ring_unknit() -> Weight { + // Proof Size summary in bytes: + // Measured: `184` + // Estimated: `7534` + // Minimum execution time: 10_447_000 picoseconds. + Weight::from_parts(10_447_000, 0) + .saturating_add(Weight::from_parts(0, 7534)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn service_queue_base() -> Weight { + // Proof Size summary in bytes: + // Measured: `6` + // Estimated: `3517` + // Minimum execution time: 4_851_000 picoseconds. + Weight::from_parts(4_851_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn service_page_base_completion() -> Weight { + // Proof Size summary in bytes: + // Measured: `72` + // Estimated: `69050` + // Minimum execution time: 6_342_000 picoseconds. + Weight::from_parts(6_342_000, 0) + .saturating_add(Weight::from_parts(0, 69050)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn service_page_base_no_completion() -> Weight { + // Proof Size summary in bytes: + // Measured: `72` + // Estimated: `69050` + // Minimum execution time: 6_199_000 picoseconds. + Weight::from_parts(6_199_000, 0) + .saturating_add(Weight::from_parts(0, 69050)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn service_page_item() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 58_612_000 picoseconds. + Weight::from_parts(58_612_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: MessageQueue BookStateFor (r:1 w:0) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn bump_service_head() -> Weight { + // Proof Size summary in bytes: + // Measured: `99` + // Estimated: `5007` + // Minimum execution time: 7_296_000 picoseconds. + Weight::from_parts(7_296_000, 0) + .saturating_add(Weight::from_parts(0, 5007)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn reap_page() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 48_345_000 picoseconds. + Weight::from_parts(48_345_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn execute_overweight_page_removed() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 56_441_000 picoseconds. + Weight::from_parts(56_441_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn execute_overweight_page_updated() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 70_858_000 picoseconds. + Weight::from_parts(70_858_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_multisig.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_multisig.rs new file mode 100644 index 00000000000..0bb05511d7a --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_multisig.rs @@ -0,0 +1,164 @@ +// 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. + +//! Autogenerated weights for `pallet_multisig` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_multisig +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_multisig`. +pub struct WeightInfo(PhantomData); +impl pallet_multisig::WeightInfo for WeightInfo { + /// The range of component `z` is `[0, 10000]`. + fn as_multi_threshold_1(z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 13_710_000 picoseconds. + Weight::from_parts(14_702_959, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 7 + .saturating_add(Weight::from_parts(568, 0).saturating_mul(z.into())) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_create(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `262 + s * (2 ±0)` + // Estimated: `6811` + // Minimum execution time: 45_518_000 picoseconds. + Weight::from_parts(35_243_068, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_634 + .saturating_add(Weight::from_parts(116_658, 0).saturating_mul(s.into())) + // Standard Error: 16 + .saturating_add(Weight::from_parts(1_444, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[3, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_approve(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `6811` + // Minimum execution time: 29_590_000 picoseconds. + Weight::from_parts(21_574_604, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_622 + .saturating_add(Weight::from_parts(95_669, 0).saturating_mul(s.into())) + // Standard Error: 15 + .saturating_add(Weight::from_parts(1_459, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_complete(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `385 + s * (33 ±0)` + // Estimated: `6811` + // Minimum execution time: 51_056_000 picoseconds. + Weight::from_parts(35_799_301, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_629 + .saturating_add(Weight::from_parts(183_343, 0).saturating_mul(s.into())) + // Standard Error: 15 + .saturating_add(Weight::from_parts(1_686, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_create(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `263 + s * (2 ±0)` + // Estimated: `6811` + // Minimum execution time: 30_910_000 picoseconds. + Weight::from_parts(32_413_023, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_346 + .saturating_add(Weight::from_parts(128_779, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_approve(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `6811` + // Minimum execution time: 17_926_000 picoseconds. + Weight::from_parts(18_477_305, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_367 + .saturating_add(Weight::from_parts(113_018, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn cancel_as_multi(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `454 + s * (1 ±0)` + // Estimated: `6811` + // Minimum execution time: 32_232_000 picoseconds. + Weight::from_parts(33_724_753, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_192 + .saturating_add(Weight::from_parts(121_574, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_nfts.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_nfts.rs new file mode 100644 index 00000000000..842daf49f59 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_nfts.rs @@ -0,0 +1,772 @@ +// 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. + +//! Autogenerated weights for `pallet_nfts` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_nfts +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_nfts`. +pub struct WeightInfo(PhantomData); +impl pallet_nfts::WeightInfo for WeightInfo { + /// Storage: `Nfts::NextCollectionId` (r:1 w:1) + /// Proof: `Nfts::NextCollectionId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:0 w:1) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:0 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionAccount` (r:0 w:1) + /// Proof: `Nfts::CollectionAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn create() -> Weight { + // Proof Size summary in bytes: + // Measured: `145` + // Estimated: `3549` + // Minimum execution time: 37_915_000 picoseconds. + Weight::from_parts(39_275_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `Nfts::NextCollectionId` (r:1 w:1) + /// Proof: `Nfts::NextCollectionId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:0 w:1) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:0 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionAccount` (r:0 w:1) + /// Proof: `Nfts::CollectionAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn force_create() -> Weight { + // Proof Size summary in bytes: + // Measured: `42` + // Estimated: `3549` + // Minimum execution time: 22_722_000 picoseconds. + Weight::from_parts(23_500_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemMetadataOf` (r:1 w:0) + /// Proof: `Nfts::ItemMetadataOf` (`max_values`: None, `max_size`: Some(347), added: 2822, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:1) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1001 w:1000) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1000 w:1000) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionMetadataOf` (r:0 w:1) + /// Proof: `Nfts::CollectionMetadataOf` (`max_values`: None, `max_size`: Some(294), added: 2769, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:0 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionAccount` (r:0 w:1) + /// Proof: `Nfts::CollectionAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + /// The range of component `m` is `[0, 1000]`. + /// The range of component `c` is `[0, 1000]`. + /// The range of component `a` is `[0, 1000]`. + fn destroy(_m: u32, _c: u32, a: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `32170 + a * (366 ±0)` + // Estimated: `2523990 + a * (2954 ±0)` + // Minimum execution time: 1_231_520_000 picoseconds. + Weight::from_parts(1_228_960_098, 0) + .saturating_add(Weight::from_parts(0, 2523990)) + // Standard Error: 8_836 + .saturating_add(Weight::from_parts(6_818_975, 0).saturating_mul(a.into())) + .saturating_add(T::DbWeight::get().reads(1004)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) + .saturating_add(T::DbWeight::get().writes(1005)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(a.into()))) + .saturating_add(Weight::from_parts(0, 2954).saturating_mul(a.into())) + } + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:1) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + fn mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `421` + // Estimated: `4326` + // Minimum execution time: 48_581_000 picoseconds. + Weight::from_parts(50_020_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:1) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + fn force_mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `421` + // Estimated: `4326` + // Minimum execution time: 47_171_000 picoseconds. + Weight::from_parts(48_084_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Nfts::Attribute` (r:1 w:0) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemMetadataOf` (r:1 w:0) + /// Proof: `Nfts::ItemMetadataOf` (`max_values`: None, `max_size`: Some(347), added: 2822, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:1) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemPriceOf` (r:0 w:1) + /// Proof: `Nfts::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemAttributesApprovalsOf` (r:0 w:1) + /// Proof: `Nfts::ItemAttributesApprovalsOf` (`max_values`: None, `max_size`: Some(1001), added: 3476, mode: `MaxEncodedLen`) + /// Storage: `Nfts::PendingSwapOf` (r:0 w:1) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + fn burn() -> Weight { + // Proof Size summary in bytes: + // Measured: `530` + // Estimated: `4326` + // Minimum execution time: 53_591_000 picoseconds. + Weight::from_parts(55_074_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(7)) + } + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1 w:0) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:2) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemPriceOf` (r:0 w:1) + /// Proof: `Nfts::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + /// Storage: `Nfts::PendingSwapOf` (r:0 w:1) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + fn transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `559` + // Estimated: `4326` + // Minimum execution time: 40_935_000 picoseconds. + Weight::from_parts(41_835_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:5000 w:5000) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// The range of component `i` is `[0, 5000]`. + fn redeposit(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `729 + i * (108 ±0)` + // Estimated: `3549 + i * (3336 ±0)` + // Minimum execution time: 16_543_000 picoseconds. + Weight::from_parts(16_769_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + // Standard Error: 23_638 + .saturating_add(Weight::from_parts(17_762_895, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(i.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + .saturating_add(Weight::from_parts(0, 3336).saturating_mul(i.into())) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + fn lock_item_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `401` + // Estimated: `3534` + // Minimum execution time: 20_446_000 picoseconds. + Weight::from_parts(20_740_000, 0) + .saturating_add(Weight::from_parts(0, 3534)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + fn unlock_item_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `401` + // Estimated: `3534` + // Minimum execution time: 20_088_000 picoseconds. + Weight::from_parts(20_627_000, 0) + .saturating_add(Weight::from_parts(0, 3534)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + fn lock_collection() -> Weight { + // Proof Size summary in bytes: + // Measured: `306` + // Estimated: `3549` + // Minimum execution time: 17_036_000 picoseconds. + Weight::from_parts(17_435_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::OwnershipAcceptance` (r:1 w:1) + /// Proof: `Nfts::OwnershipAcceptance` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionAccount` (r:0 w:2) + /// Proof: `Nfts::CollectionAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn transfer_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `354` + // Estimated: `3549` + // Minimum execution time: 22_528_000 picoseconds. + Weight::from_parts(23_047_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:2 w:4) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + fn set_team() -> Weight { + // Proof Size summary in bytes: + // Measured: `335` + // Estimated: `6078` + // Minimum execution time: 38_473_000 picoseconds. + Weight::from_parts(39_353_000, 0) + .saturating_add(Weight::from_parts(0, 6078)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionAccount` (r:0 w:2) + /// Proof: `Nfts::CollectionAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn force_collection_owner() -> Weight { + // Proof Size summary in bytes: + // Measured: `277` + // Estimated: `3549` + // Minimum execution time: 17_708_000 picoseconds. + Weight::from_parts(18_022_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:0 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + fn force_collection_config() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `3549` + // Minimum execution time: 14_606_000 picoseconds. + Weight::from_parts(14_891_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + fn lock_item_properties() -> Weight { + // Proof Size summary in bytes: + // Measured: `401` + // Estimated: `3534` + // Minimum execution time: 19_492_000 picoseconds. + Weight::from_parts(19_919_000, 0) + .saturating_add(Weight::from_parts(0, 3534)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1 w:1) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + fn set_attribute() -> Weight { + // Proof Size summary in bytes: + // Measured: `505` + // Estimated: `3944` + // Minimum execution time: 50_583_000 picoseconds. + Weight::from_parts(53_846_000, 0) + .saturating_add(Weight::from_parts(0, 3944)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1 w:1) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + fn force_set_attribute() -> Weight { + // Proof Size summary in bytes: + // Measured: `310` + // Estimated: `3944` + // Minimum execution time: 25_937_000 picoseconds. + Weight::from_parts(26_540_000, 0) + .saturating_add(Weight::from_parts(0, 3944)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Nfts::Attribute` (r:1 w:1) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + fn clear_attribute() -> Weight { + // Proof Size summary in bytes: + // Measured: `949` + // Estimated: `3944` + // Minimum execution time: 45_738_000 picoseconds. + Weight::from_parts(46_468_000, 0) + .saturating_add(Weight::from_parts(0, 3944)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Nfts::Item` (r:1 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemAttributesApprovalsOf` (r:1 w:1) + /// Proof: `Nfts::ItemAttributesApprovalsOf` (`max_values`: None, `max_size`: Some(1001), added: 3476, mode: `MaxEncodedLen`) + fn approve_item_attributes() -> Weight { + // Proof Size summary in bytes: + // Measured: `347` + // Estimated: `4466` + // Minimum execution time: 17_361_000 picoseconds. + Weight::from_parts(18_191_000, 0) + .saturating_add(Weight::from_parts(0, 4466)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:1 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemAttributesApprovalsOf` (r:1 w:1) + /// Proof: `Nfts::ItemAttributesApprovalsOf` (`max_values`: None, `max_size`: Some(1001), added: 3476, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1001 w:1000) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 1000]`. + fn cancel_item_attributes_approval(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `726 + n * (398 ±0)` + // Estimated: `4466 + n * (2954 ±0)` + // Minimum execution time: 25_884_000 picoseconds. + Weight::from_parts(26_265_000, 0) + .saturating_add(Weight::from_parts(0, 4466)) + // Standard Error: 6_423 + .saturating_add(Weight::from_parts(6_507_369, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().writes(2)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) + .saturating_add(Weight::from_parts(0, 2954).saturating_mul(n.into())) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemMetadataOf` (r:1 w:1) + /// Proof: `Nfts::ItemMetadataOf` (`max_values`: None, `max_size`: Some(347), added: 2822, mode: `MaxEncodedLen`) + fn set_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `505` + // Estimated: `3812` + // Minimum execution time: 40_802_000 picoseconds. + Weight::from_parts(41_742_000, 0) + .saturating_add(Weight::from_parts(0, 3812)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemMetadataOf` (r:1 w:1) + /// Proof: `Nfts::ItemMetadataOf` (`max_values`: None, `max_size`: Some(347), added: 2822, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + fn clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `815` + // Estimated: `3812` + // Minimum execution time: 38_904_000 picoseconds. + Weight::from_parts(39_919_000, 0) + .saturating_add(Weight::from_parts(0, 3812)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionMetadataOf` (r:1 w:1) + /// Proof: `Nfts::CollectionMetadataOf` (`max_values`: None, `max_size`: Some(294), added: 2769, mode: `MaxEncodedLen`) + fn set_collection_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `364` + // Estimated: `3759` + // Minimum execution time: 37_012_000 picoseconds. + Weight::from_parts(37_632_000, 0) + .saturating_add(Weight::from_parts(0, 3759)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionMetadataOf` (r:1 w:1) + /// Proof: `Nfts::CollectionMetadataOf` (`max_values`: None, `max_size`: Some(294), added: 2769, mode: `MaxEncodedLen`) + fn clear_collection_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `682` + // Estimated: `3759` + // Minimum execution time: 36_243_000 picoseconds. + Weight::from_parts(37_313_000, 0) + .saturating_add(Weight::from_parts(0, 3759)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + fn approve_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `376` + // Estimated: `4326` + // Minimum execution time: 20_919_000 picoseconds. + Weight::from_parts(21_505_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + fn cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `384` + // Estimated: `4326` + // Minimum execution time: 18_943_000 picoseconds. + Weight::from_parts(19_969_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + fn clear_all_transfer_approvals() -> Weight { + // Proof Size summary in bytes: + // Measured: `384` + // Estimated: `4326` + // Minimum execution time: 17_320_000 picoseconds. + Weight::from_parts(18_071_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::OwnershipAcceptance` (r:1 w:1) + /// Proof: `Nfts::OwnershipAcceptance` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + fn set_accept_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `42` + // Estimated: `3517` + // Minimum execution time: 14_934_000 picoseconds. + Weight::from_parts(15_422_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + fn set_collection_max_supply() -> Weight { + // Proof Size summary in bytes: + // Measured: `306` + // Estimated: `3549` + // Minimum execution time: 18_715_000 picoseconds. + Weight::from_parts(19_025_000, 0) + .saturating_add(Weight::from_parts(0, 3549)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:1 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:1) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + fn update_mint_settings() -> Weight { + // Proof Size summary in bytes: + // Measured: `289` + // Estimated: `3538` + // Minimum execution time: 18_249_000 picoseconds. + Weight::from_parts(18_826_000, 0) + .saturating_add(Weight::from_parts(0, 3538)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:1 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemPriceOf` (r:0 w:1) + /// Proof: `Nfts::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + fn set_price() -> Weight { + // Proof Size summary in bytes: + // Measured: `484` + // Estimated: `4326` + // Minimum execution time: 23_529_000 picoseconds. + Weight::from_parts(23_958_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemPriceOf` (r:1 w:1) + /// Proof: `Nfts::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:1 w:0) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:2) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Nfts::PendingSwapOf` (r:0 w:1) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + fn buy_item() -> Weight { + // Proof Size summary in bytes: + // Measured: `671` + // Estimated: `4326` + // Minimum execution time: 50_885_000 picoseconds. + Weight::from_parts(52_157_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// The range of component `n` is `[0, 10]`. + fn pay_tips(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_258_000 picoseconds. + Weight::from_parts(3_342_691, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 6_268 + .saturating_add(Weight::from_parts(3_761_373, 0).saturating_mul(n.into())) + } + /// Storage: `Nfts::Item` (r:2 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::PendingSwapOf` (r:0 w:1) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + fn create_swap() -> Weight { + // Proof Size summary in bytes: + // Measured: `460` + // Estimated: `7662` + // Minimum execution time: 21_220_000 picoseconds. + Weight::from_parts(21_654_000, 0) + .saturating_add(Weight::from_parts(0, 7662)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::PendingSwapOf` (r:1 w:1) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + fn cancel_swap() -> Weight { + // Proof Size summary in bytes: + // Measured: `479` + // Estimated: `4326` + // Minimum execution time: 20_430_000 picoseconds. + Weight::from_parts(21_038_000, 0) + .saturating_add(Weight::from_parts(0, 4326)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Nfts::Item` (r:2 w:2) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::PendingSwapOf` (r:1 w:2) + /// Proof: `Nfts::PendingSwapOf` (`max_values`: None, `max_size`: Some(71), added: 2546, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:0) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:2 w:0) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:2 w:0) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:4) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemPriceOf` (r:0 w:2) + /// Proof: `Nfts::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + fn claim_swap() -> Weight { + // Proof Size summary in bytes: + // Measured: `800` + // Estimated: `7662` + // Minimum execution time: 83_344_000 picoseconds. + Weight::from_parts(84_898_000, 0) + .saturating_add(Weight::from_parts(0, 7662)) + .saturating_add(T::DbWeight::get().reads(9)) + .saturating_add(T::DbWeight::get().writes(10)) + } + /// Storage: `Nfts::CollectionRoleOf` (r:2 w:0) + /// Proof: `Nfts::CollectionRoleOf` (`max_values`: None, `max_size`: Some(69), added: 2544, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Item` (r:1 w:1) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemConfigOf` (r:1 w:1) + /// Proof: `Nfts::ItemConfigOf` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:10 w:10) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemMetadataOf` (r:1 w:1) + /// Proof: `Nfts::ItemMetadataOf` (`max_values`: None, `max_size`: Some(347), added: 2822, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Account` (r:0 w:1) + /// Proof: `Nfts::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 10]`. + fn mint_pre_signed(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `524` + // Estimated: `6078 + n * (2954 ±0)` + // Minimum execution time: 143_435_000 picoseconds. + Weight::from_parts(151_744_537, 0) + .saturating_add(Weight::from_parts(0, 6078)) + // Standard Error: 44_459 + .saturating_add(Weight::from_parts(31_293_503, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().writes(6)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) + .saturating_add(Weight::from_parts(0, 2954).saturating_mul(n.into())) + } + /// Storage: `Nfts::Item` (r:1 w:0) + /// Proof: `Nfts::Item` (`max_values`: None, `max_size`: Some(861), added: 3336, mode: `MaxEncodedLen`) + /// Storage: `Nfts::ItemAttributesApprovalsOf` (r:1 w:1) + /// Proof: `Nfts::ItemAttributesApprovalsOf` (`max_values`: None, `max_size`: Some(1001), added: 3476, mode: `MaxEncodedLen`) + /// Storage: `Nfts::CollectionConfigOf` (r:1 w:0) + /// Proof: `Nfts::CollectionConfigOf` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Collection` (r:1 w:1) + /// Proof: `Nfts::Collection` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) + /// Storage: `Nfts::Attribute` (r:10 w:10) + /// Proof: `Nfts::Attribute` (`max_values`: None, `max_size`: Some(479), added: 2954, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 10]`. + fn set_attributes_pre_signed(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `554` + // Estimated: `4466 + n * (2954 ±0)` + // Minimum execution time: 84_627_000 picoseconds. + Weight::from_parts(96_076_065, 0) + .saturating_add(Weight::from_parts(0, 4466)) + // Standard Error: 62_058 + .saturating_add(Weight::from_parts(30_461_383, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().writes(2)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) + .saturating_add(Weight::from_parts(0, 2954).saturating_mul(n.into())) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_proxy.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_proxy.rs new file mode 100644 index 00000000000..b6121f2fca2 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_proxy.rs @@ -0,0 +1,225 @@ +// 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. + +//! Autogenerated weights for `pallet_proxy` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_proxy +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_proxy`. +pub struct WeightInfo(PhantomData); +impl pallet_proxy::WeightInfo for WeightInfo { + /// Storage: `Proxy::Proxies` (r:1 w:0) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn proxy(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `127 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 16_130_000 picoseconds. + Weight::from_parts(16_649_312, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 761 + .saturating_add(Weight::from_parts(42_507, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:0) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// Storage: `Proxy::Announcements` (r:1 w:1) + /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 31]`. + /// The range of component `p` is `[1, 31]`. + fn proxy_announced(a: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `454 + a * (68 ±0) + p * (37 ±0)` + // Estimated: `5698` + // Minimum execution time: 37_732_000 picoseconds. + Weight::from_parts(36_993_926, 0) + .saturating_add(Weight::from_parts(0, 5698)) + // Standard Error: 3_278 + .saturating_add(Weight::from_parts(144_955, 0).saturating_mul(a.into())) + // Standard Error: 3_387 + .saturating_add(Weight::from_parts(64_624, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Proxy::Announcements` (r:1 w:1) + /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 31]`. + /// The range of component `p` is `[1, 31]`. + fn remove_announcement(a: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `369 + a * (68 ±0)` + // Estimated: `5698` + // Minimum execution time: 24_229_000 picoseconds. + Weight::from_parts(24_199_507, 0) + .saturating_add(Weight::from_parts(0, 5698)) + // Standard Error: 1_672 + .saturating_add(Weight::from_parts(124_324, 0).saturating_mul(a.into())) + // Standard Error: 1_727 + .saturating_add(Weight::from_parts(28_481, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Proxy::Announcements` (r:1 w:1) + /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 31]`. + /// The range of component `p` is `[1, 31]`. + fn reject_announcement(a: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `369 + a * (68 ±0)` + // Estimated: `5698` + // Minimum execution time: 23_868_000 picoseconds. + Weight::from_parts(25_293_069, 0) + .saturating_add(Weight::from_parts(0, 5698)) + // Standard Error: 1_728 + .saturating_add(Weight::from_parts(114_080, 0).saturating_mul(a.into())) + // Standard Error: 1_786 + .saturating_add(Weight::from_parts(3_690, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Proxy::Proxies` (r:1 w:0) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// Storage: `Proxy::Announcements` (r:1 w:1) + /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 31]`. + /// The range of component `p` is `[1, 31]`. + fn announce(a: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `386 + a * (68 ±0) + p * (37 ±0)` + // Estimated: `5698` + // Minimum execution time: 34_343_000 picoseconds. + Weight::from_parts(34_539_112, 0) + .saturating_add(Weight::from_parts(0, 5698)) + // Standard Error: 1_917 + .saturating_add(Weight::from_parts(117_360, 0).saturating_mul(a.into())) + // Standard Error: 1_981 + .saturating_add(Weight::from_parts(40_908, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn add_proxy(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `127 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 25_506_000 picoseconds. + Weight::from_parts(26_350_920, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 2_950 + .saturating_add(Weight::from_parts(48_972, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn remove_proxy(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `127 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 25_234_000 picoseconds. + Weight::from_parts(26_232_489, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 2_468 + .saturating_add(Weight::from_parts(48_955, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn remove_proxies(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `127 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 22_184_000 picoseconds. + Weight::from_parts(22_974_929, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 2_200 + .saturating_add(Weight::from_parts(45_741, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn create_pure(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `139` + // Estimated: `4706` + // Minimum execution time: 27_044_000 picoseconds. + Weight::from_parts(27_978_605, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 2_206 + .saturating_add(Weight::from_parts(13_736, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[0, 30]`. + fn kill_pure(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `164 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 22_770_000 picoseconds. + Weight::from_parts(23_441_470, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 1_959 + .saturating_add(Weight::from_parts(47_317, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_session.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_session.rs new file mode 100644 index 00000000000..560322abeb3 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_session.rs @@ -0,0 +1,80 @@ +// 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. + +//! Autogenerated weights for `pallet_session` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_session +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_session`. +pub struct WeightInfo(PhantomData); +impl pallet_session::WeightInfo for WeightInfo { + /// Storage: `Session::NextKeys` (r:1 w:1) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Session::KeyOwner` (r:1 w:1) + /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn set_keys() -> Weight { + // Proof Size summary in bytes: + // Measured: `270` + // Estimated: `3735` + // Minimum execution time: 16_684_000 picoseconds. + Weight::from_parts(17_167_000, 0) + .saturating_add(Weight::from_parts(0, 3735)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Session::NextKeys` (r:1 w:1) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Session::KeyOwner` (r:0 w:1) + /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn purge_keys() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `3707` + // Minimum execution time: 11_692_000 picoseconds. + Weight::from_parts(12_248_000, 0) + .saturating_add(Weight::from_parts(0, 3707)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_timestamp.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_timestamp.rs new file mode 100644 index 00000000000..17b050c3e90 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_timestamp.rs @@ -0,0 +1,74 @@ +// 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. + +//! Autogenerated weights for `pallet_timestamp` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_timestamp +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_timestamp`. +pub struct WeightInfo(PhantomData); +impl pallet_timestamp::WeightInfo for WeightInfo { + /// Storage: `Timestamp::Now` (r:1 w:1) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `Aura::CurrentSlot` (r:1 w:0) + /// Proof: `Aura::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + fn set() -> Weight { + // Proof Size summary in bytes: + // Measured: `86` + // Estimated: `1493` + // Minimum execution time: 9_214_000 picoseconds. + Weight::from_parts(9_535_000, 0) + .saturating_add(Weight::from_parts(0, 1493)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn on_finalize() -> Weight { + // Proof Size summary in bytes: + // Measured: `57` + // Estimated: `0` + // Minimum execution time: 3_269_000 picoseconds. + Weight::from_parts(3_458_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_uniques.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_uniques.rs new file mode 100644 index 00000000000..5b13d56f5bb --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_uniques.rs @@ -0,0 +1,466 @@ +// 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. + +//! Autogenerated weights for `pallet_uniques` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_uniques +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_uniques`. +pub struct WeightInfo(PhantomData); +impl pallet_uniques::WeightInfo for WeightInfo { + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassAccount` (r:0 w:1) + /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn create() -> Weight { + // Proof Size summary in bytes: + // Measured: `145` + // Estimated: `3643` + // Minimum execution time: 29_513_000 picoseconds. + Weight::from_parts(30_346_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassAccount` (r:0 w:1) + /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn force_create() -> Weight { + // Proof Size summary in bytes: + // Measured: `42` + // Estimated: `3643` + // Minimum execution time: 13_600_000 picoseconds. + Weight::from_parts(14_110_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:1001 w:1000) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::InstanceMetadataOf` (r:1000 w:1000) + /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Attribute` (r:1000 w:1000) + /// Proof: `Uniques::Attribute` (`max_values`: None, `max_size`: Some(172), added: 2647, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassAccount` (r:0 w:1) + /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassMetadataOf` (r:0 w:1) + /// Proof: `Uniques::ClassMetadataOf` (`max_values`: None, `max_size`: Some(167), added: 2642, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Account` (r:0 w:1000) + /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Uniques::CollectionMaxSupply` (r:0 w:1) + /// Proof: `Uniques::CollectionMaxSupply` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 1000]`. + /// The range of component `m` is `[0, 1000]`. + /// The range of component `a` is `[0, 1000]`. + fn destroy(n: u32, m: u32, a: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `257 + a * (107 ±0) + m * (56 ±0) + n * (76 ±0)` + // Estimated: `3643 + a * (2647 ±0) + m * (2662 ±0) + n * (2597 ±0)` + // Minimum execution time: 2_945_869_000 picoseconds. + Weight::from_parts(3_037_917_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + // Standard Error: 35_850 + .saturating_add(Weight::from_parts(7_558_563, 0).saturating_mul(n.into())) + // Standard Error: 35_850 + .saturating_add(Weight::from_parts(501_089, 0).saturating_mul(m.into())) + // Standard Error: 35_850 + .saturating_add(Weight::from_parts(538_921, 0).saturating_mul(a.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(m.into()))) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(a.into()))) + .saturating_add(T::DbWeight::get().writes(4)) + .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(m.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(a.into()))) + .saturating_add(Weight::from_parts(0, 2647).saturating_mul(a.into())) + .saturating_add(Weight::from_parts(0, 2662).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 2597).saturating_mul(n.into())) + } + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::CollectionMaxSupply` (r:1 w:0) + /// Proof: `Uniques::CollectionMaxSupply` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Account` (r:0 w:1) + /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + fn mint() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 36_225_000 picoseconds. + Weight::from_parts(36_858_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Account` (r:0 w:1) + /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ItemPriceOf` (r:0 w:1) + /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + fn burn() -> Weight { + // Proof Size summary in bytes: + // Measured: `428` + // Estimated: `3643` + // Minimum execution time: 37_021_000 picoseconds. + Weight::from_parts(37_749_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Account` (r:0 w:2) + /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ItemPriceOf` (r:0 w:1) + /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + fn transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `428` + // Estimated: `3643` + // Minimum execution time: 26_884_000 picoseconds. + Weight::from_parts(27_414_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:5000 w:5000) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// The range of component `i` is `[0, 5000]`. + fn redeposit(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `738 + i * (76 ±0)` + // Estimated: `3643 + i * (2597 ±0)` + // Minimum execution time: 14_797_000 picoseconds. + Weight::from_parts(14_943_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + // Standard Error: 25_250 + .saturating_add(Weight::from_parts(18_014_600, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(i.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + .saturating_add(Weight::from_parts(0, 2597).saturating_mul(i.into())) + } + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + fn freeze() -> Weight { + // Proof Size summary in bytes: + // Measured: `428` + // Estimated: `3643` + // Minimum execution time: 18_864_000 picoseconds. + Weight::from_parts(19_299_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + fn thaw() -> Weight { + // Proof Size summary in bytes: + // Measured: `428` + // Estimated: `3643` + // Minimum execution time: 18_530_000 picoseconds. + Weight::from_parts(19_230_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + fn freeze_collection() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 13_807_000 picoseconds. + Weight::from_parts(14_270_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + fn thaw_collection() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 13_657_000 picoseconds. + Weight::from_parts(14_059_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::OwnershipAcceptance` (r:1 w:1) + /// Proof: `Uniques::OwnershipAcceptance` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassAccount` (r:0 w:2) + /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn transfer_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `356` + // Estimated: `3643` + // Minimum execution time: 22_108_000 picoseconds. + Weight::from_parts(22_520_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + fn set_team() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 14_128_000 picoseconds. + Weight::from_parts(14_481_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassAccount` (r:0 w:1) + /// Proof: `Uniques::ClassAccount` (`max_values`: None, `max_size`: Some(68), added: 2543, mode: `MaxEncodedLen`) + fn force_item_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 17_114_000 picoseconds. + Weight::from_parts(17_570_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::InstanceMetadataOf` (r:1 w:0) + /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Attribute` (r:1 w:1) + /// Proof: `Uniques::Attribute` (`max_values`: None, `max_size`: Some(172), added: 2647, mode: `MaxEncodedLen`) + fn set_attribute() -> Weight { + // Proof Size summary in bytes: + // Measured: `559` + // Estimated: `3652` + // Minimum execution time: 40_412_000 picoseconds. + Weight::from_parts(43_009_000, 0) + .saturating_add(Weight::from_parts(0, 3652)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::InstanceMetadataOf` (r:1 w:0) + /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Attribute` (r:1 w:1) + /// Proof: `Uniques::Attribute` (`max_values`: None, `max_size`: Some(172), added: 2647, mode: `MaxEncodedLen`) + fn clear_attribute() -> Weight { + // Proof Size summary in bytes: + // Measured: `756` + // Estimated: `3652` + // Minimum execution time: 38_044_000 picoseconds. + Weight::from_parts(38_871_000, 0) + .saturating_add(Weight::from_parts(0, 3652)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::InstanceMetadataOf` (r:1 w:1) + /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) + fn set_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `348` + // Estimated: `3652` + // Minimum execution time: 30_016_000 picoseconds. + Weight::from_parts(30_723_000, 0) + .saturating_add(Weight::from_parts(0, 3652)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::InstanceMetadataOf` (r:1 w:1) + /// Proof: `Uniques::InstanceMetadataOf` (`max_values`: None, `max_size`: Some(187), added: 2662, mode: `MaxEncodedLen`) + fn clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `559` + // Estimated: `3652` + // Minimum execution time: 30_942_000 picoseconds. + Weight::from_parts(31_527_000, 0) + .saturating_add(Weight::from_parts(0, 3652)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:1) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassMetadataOf` (r:1 w:1) + /// Proof: `Uniques::ClassMetadataOf` (`max_values`: None, `max_size`: Some(167), added: 2642, mode: `MaxEncodedLen`) + fn set_collection_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 30_727_000 picoseconds. + Weight::from_parts(31_688_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ClassMetadataOf` (r:1 w:1) + /// Proof: `Uniques::ClassMetadataOf` (`max_values`: None, `max_size`: Some(167), added: 2642, mode: `MaxEncodedLen`) + fn clear_collection_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `473` + // Estimated: `3643` + // Minimum execution time: 29_844_000 picoseconds. + Weight::from_parts(30_403_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + fn approve_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `428` + // Estimated: `3643` + // Minimum execution time: 19_155_000 picoseconds. + Weight::from_parts(19_909_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + fn cancel_approval() -> Weight { + // Proof Size summary in bytes: + // Measured: `461` + // Estimated: `3643` + // Minimum execution time: 19_163_000 picoseconds. + Weight::from_parts(19_804_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::OwnershipAcceptance` (r:1 w:1) + /// Proof: `Uniques::OwnershipAcceptance` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + fn set_accept_ownership() -> Weight { + // Proof Size summary in bytes: + // Measured: `42` + // Estimated: `3517` + // Minimum execution time: 15_413_000 picoseconds. + Weight::from_parts(15_762_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::CollectionMaxSupply` (r:1 w:1) + /// Proof: `Uniques::CollectionMaxSupply` (`max_values`: None, `max_size`: Some(24), added: 2499, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + fn set_collection_max_supply() -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `3643` + // Minimum execution time: 16_477_000 picoseconds. + Weight::from_parts(16_811_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Asset` (r:1 w:0) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ItemPriceOf` (r:0 w:1) + /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + fn set_price() -> Weight { + // Proof Size summary in bytes: + // Measured: `259` + // Estimated: `3587` + // Minimum execution time: 16_415_000 picoseconds. + Weight::from_parts(16_906_000, 0) + .saturating_add(Weight::from_parts(0, 3587)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Uniques::Asset` (r:1 w:1) + /// Proof: `Uniques::Asset` (`max_values`: None, `max_size`: Some(122), added: 2597, mode: `MaxEncodedLen`) + /// Storage: `Uniques::ItemPriceOf` (r:1 w:1) + /// Proof: `Uniques::ItemPriceOf` (`max_values`: None, `max_size`: Some(89), added: 2564, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Class` (r:1 w:0) + /// Proof: `Uniques::Class` (`max_values`: None, `max_size`: Some(178), added: 2653, mode: `MaxEncodedLen`) + /// Storage: `Uniques::Account` (r:0 w:2) + /// Proof: `Uniques::Account` (`max_values`: None, `max_size`: Some(88), added: 2563, mode: `MaxEncodedLen`) + fn buy_item() -> Weight { + // Proof Size summary in bytes: + // Measured: `540` + // Estimated: `3643` + // Minimum execution time: 35_814_000 picoseconds. + Weight::from_parts(36_569_000, 0) + .saturating_add(Weight::from_parts(0, 3643)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(4)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_utility.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_utility.rs new file mode 100644 index 00000000000..d028fb898a4 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_utility.rs @@ -0,0 +1,101 @@ +// 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. + +//! Autogenerated weights for `pallet_utility` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_utility +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_utility`. +pub struct WeightInfo(PhantomData); +impl pallet_utility::WeightInfo for WeightInfo { + /// The range of component `c` is `[0, 1000]`. + fn batch(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_918_000 picoseconds. + Weight::from_parts(2_421_521, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 3_252 + .saturating_add(Weight::from_parts(6_625_635, 0).saturating_mul(c.into())) + } + fn as_derivative() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 5_304_000 picoseconds. + Weight::from_parts(5_546_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// The range of component `c` is `[0, 1000]`. + fn batch_all(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_847_000 picoseconds. + Weight::from_parts(1_224_975, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 3_818 + .saturating_add(Weight::from_parts(6_891_149, 0).saturating_mul(c.into())) + } + fn dispatch_as() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 9_269_000 picoseconds. + Weight::from_parts(9_604_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// The range of component `c` is `[0, 1000]`. + fn force_batch(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_855_000 picoseconds. + Weight::from_parts(6_965_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_631 + .saturating_add(Weight::from_parts(6_545_496, 0).saturating_mul(c.into())) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_xcm.rs new file mode 100644 index 00000000000..27867e278ed --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/pallet_xcm.rs @@ -0,0 +1,324 @@ +// 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 . + +//! Autogenerated weights for `pallet_xcm` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-11-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_xcm +// --chain=asset-hub-polkadot-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_xcm`. +pub struct WeightInfo(PhantomData); +impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn send() -> Weight { + // Proof Size summary in bytes: + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 25_203_000 picoseconds. + Weight::from_parts(25_927_000, 0) + .saturating_add(Weight::from_parts(0, 3540)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn teleport_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `1489` + // Minimum execution time: 20_113_000 picoseconds. + Weight::from_parts(20_439_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + .saturating_add(T::DbWeight::get().reads(1)) + } + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn reserve_transfer_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `1489` + // Minimum execution time: 14_959_000 picoseconds. + Weight::from_parts(15_264_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + .saturating_add(T::DbWeight::get().reads(1)) + } + /// Storage: `Benchmark::Override` (r:0 w:0) + /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn execute() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 18_446_744_073_709_551_000 picoseconds. + Weight::from_parts(18_446_744_073_709_551_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: `PolkadotXcm::SupportedVersion` (r:0 w:1) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_xcm_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_399_000 picoseconds. + Weight::from_parts(7_674_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:0 w:1) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn force_default_xcm_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_388_000 picoseconds. + Weight::from_parts(2_522_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_subscribe_version_notify() -> Weight { + // Proof Size summary in bytes: + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 28_791_000 picoseconds. + Weight::from_parts(29_443_000, 0) + .saturating_add(Weight::from_parts(0, 3540)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_unsubscribe_version_notify() -> Weight { + // Proof Size summary in bytes: + // Measured: `292` + // Estimated: `3757` + // Minimum execution time: 30_880_000 picoseconds. + Weight::from_parts(31_675_000, 0) + .saturating_add(Weight::from_parts(0, 3757)) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PolkadotXcm::XcmExecutionSuspended` (r:0 w:1) + /// Proof: `PolkadotXcm::XcmExecutionSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn force_suspension() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_365_000 picoseconds. + Weight::from_parts(2_550_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::SupportedVersion` (r:4 w:2) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_supported_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `129` + // Estimated: `11019` + // Minimum execution time: 17_185_000 picoseconds. + Weight::from_parts(17_680_000, 0) + .saturating_add(Weight::from_parts(0, 11019)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_version_notifiers() -> Weight { + // Proof Size summary in bytes: + // Measured: `133` + // Estimated: `11023` + // Minimum execution time: 16_974_000 picoseconds. + Weight::from_parts(17_660_000, 0) + .saturating_add(Weight::from_parts(0, 11023)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:5 w:0) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn already_notified_target() -> Weight { + // Proof Size summary in bytes: + // Measured: `140` + // Estimated: `13505` + // Minimum execution time: 18_536_000 picoseconds. + Weight::from_parts(19_292_000, 0) + .saturating_add(Weight::from_parts(0, 13505)) + .saturating_add(T::DbWeight::get().reads(5)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:2 w:1) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn notify_current_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `6082` + // Minimum execution time: 27_368_000 picoseconds. + Weight::from_parts(28_161_000, 0) + .saturating_add(Weight::from_parts(0, 6082)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:3 w:0) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn notify_target_migration_fail() -> Weight { + // Proof Size summary in bytes: + // Measured: `172` + // Estimated: `8587` + // Minimum execution time: 9_553_000 picoseconds. + Weight::from_parts(9_899_000, 0) + .saturating_add(Weight::from_parts(0, 8587)) + .saturating_add(T::DbWeight::get().reads(3)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_version_notify_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `140` + // Estimated: `11030` + // Minimum execution time: 17_445_000 picoseconds. + Weight::from_parts(18_206_000, 0) + .saturating_add(Weight::from_parts(0, 11030)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn migrate_and_notify_old_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `146` + // Estimated: `11036` + // Minimum execution time: 34_200_000 picoseconds. + Weight::from_parts(35_198_000, 0) + .saturating_add(Weight::from_parts(0, 11036)) + .saturating_add(T::DbWeight::get().reads(10)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn new_query() -> Weight { + // Proof Size summary in bytes: + // Measured: `69` + // Estimated: `1554` + // Minimum execution time: 4_679_000 picoseconds. + Weight::from_parts(4_841_000, 0) + .saturating_add(Weight::from_parts(0, 1554)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::Queries` (r:1 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn take_response() -> Weight { + // Proof Size summary in bytes: + // Measured: `7706` + // Estimated: `11171` + // Minimum execution time: 27_281_000 picoseconds. + Weight::from_parts(27_694_000, 0) + .saturating_add(Weight::from_parts(0, 11171)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/paritydb_weights.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/paritydb_weights.rs new file mode 100644 index 00000000000..25679703831 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/paritydb_weights.rs @@ -0,0 +1,63 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; + + parameter_types! { + /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights + /// are available for brave runtime engineers who may want to try this out as default. + pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + }; + } + + #[cfg(test)] + mod test_db_weights { + use super::constants::ParityDbWeight as W; + use frame_support::weights::constants; + + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Write weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/rocksdb_weights.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/rocksdb_weights.rs new file mode 100644 index 00000000000..3dd817aa6f1 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/rocksdb_weights.rs @@ -0,0 +1,63 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; + + parameter_types! { + /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout + /// the runtime. + pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + }; + } + + #[cfg(test)] + mod test_db_weights { + use super::constants::RocksDbWeight as W; + use frame_support::weights::constants; + + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Write weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/mod.rs new file mode 100644 index 00000000000..44fcb91d688 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/mod.rs @@ -0,0 +1,244 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +mod pallet_xcm_benchmarks_fungible; +mod pallet_xcm_benchmarks_generic; + +use crate::{xcm_config::MaxAssetsIntoHolding, Runtime}; +use frame_support::weights::Weight; +use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; +use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; +use sp_std::prelude::*; +use xcm::{latest::prelude::*, DoubleEncoded}; + +trait WeighMultiAssets { + fn weigh_multi_assets(&self, weight: Weight) -> Weight; +} + +const MAX_ASSETS: u64 = 100; + +impl WeighMultiAssets for MultiAssetFilter { + fn weigh_multi_assets(&self, weight: Weight) -> Weight { + match self { + Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64), + Self::Wild(asset) => match asset { + All => weight.saturating_mul(MAX_ASSETS), + AllOf { fun, .. } => match fun { + WildFungibility::Fungible => weight, + // Magic number 2 has to do with the fact that we could have up to 2 times + // MaxAssetsIntoHolding in the worst-case scenario. + WildFungibility::NonFungible => + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + }, + AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), + AllOfCounted { count, .. } => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), + }, + } + } +} + +impl WeighMultiAssets for MultiAssets { + fn weigh_multi_assets(&self, weight: Weight) -> Weight { + weight.saturating_mul(self.inner().iter().count() as u64) + } +} + +pub struct AssetHubPolkadotXcmWeight(core::marker::PhantomData); +impl XcmWeightInfo for AssetHubPolkadotXcmWeight { + fn withdraw_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + } + fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::reserve_asset_deposited()) + } + fn receive_teleported_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + } + fn query_response( + _query_id: &u64, + _response: &Response, + _max_weight: &Weight, + _querier: &Option, + ) -> Weight { + XcmGeneric::::query_response() + } + fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + } + fn transfer_reserve_asset( + assets: &MultiAssets, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + } + fn transact( + _origin_type: &OriginKind, + _require_weight_at_most: &Weight, + _call: &DoubleEncoded, + ) -> Weight { + XcmGeneric::::transact() + } + fn hrmp_new_channel_open_request( + _sender: &u32, + _max_message_size: &u32, + _max_capacity: &u32, + ) -> Weight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX + } + fn hrmp_channel_accepted(_recipient: &u32) -> Weight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX + } + fn hrmp_channel_closing(_initiator: &u32, _sender: &u32, _recipient: &u32) -> Weight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX + } + fn clear_origin() -> Weight { + XcmGeneric::::clear_origin() + } + fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + XcmGeneric::::descend_origin() + } + fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::report_error() + } + + fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()) + } + fn deposit_reserve_asset( + assets: &MultiAssetFilter, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + } + fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + Weight::MAX + } + fn initiate_reserve_withdraw( + assets: &MultiAssetFilter, + _reserve: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) + } + fn initiate_teleport( + assets: &MultiAssetFilter, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()) + } + fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + XcmGeneric::::report_holding() + } + fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + XcmGeneric::::buy_execution() + } + fn refund_surplus() -> Weight { + XcmGeneric::::refund_surplus() + } + fn set_error_handler(_xcm: &Xcm) -> Weight { + XcmGeneric::::set_error_handler() + } + fn set_appendix(_xcm: &Xcm) -> Weight { + XcmGeneric::::set_appendix() + } + fn clear_error() -> Weight { + XcmGeneric::::clear_error() + } + fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + XcmGeneric::::claim_asset() + } + fn trap(_code: &u64) -> Weight { + XcmGeneric::::trap() + } + fn subscribe_version(_query_id: &QueryId, _max_response_weight: &Weight) -> Weight { + XcmGeneric::::subscribe_version() + } + fn unsubscribe_version() -> Weight { + XcmGeneric::::unsubscribe_version() + } + fn burn_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + } + fn expect_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + } + fn expect_origin(_origin: &Option) -> Weight { + XcmGeneric::::expect_origin() + } + fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { + XcmGeneric::::expect_error() + } + fn expect_transact_status(_transact_status: &MaybeErrorCode) -> Weight { + XcmGeneric::::expect_transact_status() + } + fn query_pallet(_module_name: &Vec, _response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::query_pallet() + } + fn expect_pallet( + _index: &u32, + _name: &Vec, + _module_name: &Vec, + _crate_major: &u32, + _min_crate_minor: &u32, + ) -> Weight { + XcmGeneric::::expect_pallet() + } + fn report_transact_status(_response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::report_transact_status() + } + fn clear_transact_status() -> Weight { + XcmGeneric::::clear_transact_status() + } + fn universal_origin(_: &Junction) -> Weight { + Weight::MAX + } + fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight { + Weight::MAX + } + fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn set_fees_mode(_: &bool) -> Weight { + XcmGeneric::::set_fees_mode() + } + fn set_topic(_topic: &[u8; 32]) -> Weight { + XcmGeneric::::set_topic() + } + fn clear_topic() -> Weight { + XcmGeneric::::clear_topic() + } + fn alias_origin(_: &MultiLocation) -> Weight { + // XCM Executor does not currently support alias origin operations + Weight::MAX + } + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + XcmGeneric::::unpaid_execution() + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs new file mode 100644 index 00000000000..1036d4cbf00 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -0,0 +1,187 @@ +// 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. + +//! Autogenerated weights for `pallet_xcm_benchmarks::fungible` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-09-27, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-nbnwcyh-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: Compiled, CHAIN: Some("asset-hub-polkadot-dev"), DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_xcm_benchmarks::fungible +// --chain=asset-hub-polkadot-dev +// --header=./cumulus/file_header.txt +// --template=./cumulus/templates/xcm-bench-template.hbs +// --output=./cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weights for `pallet_xcm_benchmarks::fungible`. +pub struct WeightInfo(PhantomData); +impl WeightInfo { + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + pub fn withdraw_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `101` + // Estimated: `3593` + // Minimum execution time: 25_903_000 picoseconds. + Weight::from_parts(26_768_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + // Storage: `System::Account` (r:2 w:2) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + pub fn transfer_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `101` + // Estimated: `6196` + // Minimum execution time: 51_042_000 picoseconds. + Weight::from_parts(51_939_000, 6196) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + // Storage: `System::Account` (r:2 w:2) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn transfer_reserve_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `176` + // Estimated: `6196` + // Minimum execution time: 74_626_000 picoseconds. + Weight::from_parts(75_963_000, 6196) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(4)) + } + // Storage: `Benchmark::Override` (r:0 w:0) + // Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn reserve_asset_deposited() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 18_446_744_073_709_551_000 picoseconds. + Weight::from_parts(18_446_744_073_709_551_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_reserve_withdraw() -> Weight { + // Proof Size summary in bytes: + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 480_030_000 picoseconds. + Weight::from_parts(486_039_000, 3540) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn receive_teleported_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_936_000 picoseconds. + Weight::from_parts(4_033_000, 0) + } + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + pub fn deposit_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 26_274_000 picoseconds. + Weight::from_parts(26_609_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn deposit_reserve_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `75` + // Estimated: `3593` + // Minimum execution time: 52_888_000 picoseconds. + Weight::from_parts(53_835_000, 3593) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(3)) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_teleport() -> Weight { + // Proof Size summary in bytes: + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 33_395_000 picoseconds. + Weight::from_parts(33_827_000, 3540) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_generic.rs new file mode 100644 index 00000000000..12ef504727e --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -0,0 +1,328 @@ +// 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. + +//! Autogenerated weights for `pallet_xcm_benchmarks::generic` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: , WASM-EXECUTION: Compiled, CHAIN: Some("asset-hub-polkadot-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --template=./templates/xcm-bench-template.hbs +// --chain=asset-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_xcm_benchmarks::generic +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_generic.rs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weights for `pallet_xcm_benchmarks::generic`. +pub struct WeightInfo(PhantomData); +impl WeightInfo { + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn report_holding() -> Weight { + // Proof Size summary in bytes: + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 425_235_000 picoseconds. + Weight::from_parts(432_935_000, 3540) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn buy_execution() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_070_000 picoseconds. + Weight::from_parts(4_329_000, 0) + } + // Storage: `PolkadotXcm::Queries` (r:1 w:0) + // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn query_response() -> Weight { + // Proof Size summary in bytes: + // Measured: `69` + // Estimated: `3534` + // Minimum execution time: 11_464_000 picoseconds. + Weight::from_parts(11_829_000, 3534) + .saturating_add(T::DbWeight::get().reads(1)) + } + pub fn transact() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 13_574_000 picoseconds. + Weight::from_parts(14_021_000, 0) + } + pub fn refund_surplus() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_276_000 picoseconds. + Weight::from_parts(4_479_000, 0) + } + pub fn set_error_handler() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_833_000 picoseconds. + Weight::from_parts(2_939_000, 0) + } + pub fn set_appendix() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_797_000 picoseconds. + Weight::from_parts(2_901_000, 0) + } + pub fn clear_error() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_855_000 picoseconds. + Weight::from_parts(2_961_000, 0) + } + pub fn descend_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_589_000 picoseconds. + Weight::from_parts(3_720_000, 0) + } + pub fn clear_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_786_000 picoseconds. + Weight::from_parts(2_889_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn report_error() -> Weight { + // Proof Size summary in bytes: + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 25_740_000 picoseconds. + Weight::from_parts(26_355_000, 3540) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + // Storage: `PolkadotXcm::AssetTraps` (r:1 w:1) + // Proof: `PolkadotXcm::AssetTraps` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn claim_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `126` + // Estimated: `3591` + // Minimum execution time: 16_206_000 picoseconds. + Weight::from_parts(16_651_000, 3591) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + pub fn trap() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_819_000 picoseconds. + Weight::from_parts(2_944_000, 0) + } + // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) + // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn subscribe_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 28_216_000 picoseconds. + Weight::from_parts(28_878_000, 3540) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(3)) + } + // Storage: `PolkadotXcm::VersionNotifyTargets` (r:0 w:1) + // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn unsubscribe_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_795_000 picoseconds. + Weight::from_parts(5_008_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) + } + pub fn burn_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 135_205_000 picoseconds. + Weight::from_parts(140_623_000, 0) + } + pub fn expect_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 12_791_000 picoseconds. + Weight::from_parts(13_114_000, 0) + } + pub fn expect_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_000_000 picoseconds. + Weight::from_parts(3_091_000, 0) + } + pub fn expect_error() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_828_000 picoseconds. + Weight::from_parts(2_947_000, 0) + } + pub fn expect_transact_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_980_000 picoseconds. + Weight::from_parts(3_123_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn query_pallet() -> Weight { + // Proof Size summary in bytes: + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 29_672_000 picoseconds. + Weight::from_parts(30_318_000, 3540) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn expect_pallet() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 5_421_000 picoseconds. + Weight::from_parts(5_614_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn report_transact_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 25_621_000 picoseconds. + Weight::from_parts(26_486_000, 3540) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn clear_transact_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_873_000 picoseconds. + Weight::from_parts(2_973_000, 0) + } + pub fn set_topic() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_861_000 picoseconds. + Weight::from_parts(2_923_000, 0) + } + pub fn clear_topic() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_845_000 picoseconds. + Weight::from_parts(2_970_000, 0) + } + pub fn set_fees_mode() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_773_000 picoseconds. + Weight::from_parts(2_922_000, 0) + } + pub fn unpaid_execution() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_980_000 picoseconds. + Weight::from_parts(3_095_000, 0) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/xcm_config.rs new file mode 100644 index 00000000000..b3c2ce4da76 --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/xcm_config.rs @@ -0,0 +1,546 @@ +// 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::{ + AccountId, AllPalletsWithSystem, Assets, Authorship, Balance, Balances, ForeignAssets, + ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, + TransactionByteFee, TrustBackedAssetsInstance, WeightToFee, XcmpQueue, CENTS, +}; +use assets_common::matching::{FromSiblingParachain, IsForeignConcreteAsset}; +use frame_support::{ + match_types, parameter_types, + traits::{ConstU32, Contains, Everything, Nothing, PalletInfoAccess}, +}; +use frame_system::EnsureRoot; +use pallet_xcm::XcmPassthrough; +use parachains_common::{ + impls::ToStakingPot, + xcm_config::{AssetFeeAsExistentialDepositMultiplier, ConcreteAssetFromSystem}, +}; +use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; +use sp_runtime::traits::ConvertInto; +use xcm::latest::prelude::*; +use xcm_builder::{ + AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, + AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, + DenyReserveTransferToRelayChain, DenyThenTry, DescribeFamily, DescribePalletTerminal, + EnsureXcmOrigin, FungiblesAdapter, HashedDescription, IsConcrete, LocalMint, NoChecking, + ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, StartsWith, StartsWithExplicitGlobalConsensus, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, +}; +use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; + +parameter_types! { + pub const DotLocation: MultiLocation = MultiLocation::parent(); + pub const RelayNetwork: Option = Some(NetworkId::Polkadot); + pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); + pub UniversalLocation: InteriorMultiLocation = + X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())); + pub UniversalLocationNetworkId: NetworkId = UniversalLocation::get().global_consensus().unwrap(); + pub TrustBackedAssetsPalletLocation: MultiLocation = + PalletInstance(::index() as u8).into(); + pub CheckingAccount: AccountId = PolkadotXcm::check_account(); + pub FellowshipLocation: MultiLocation = MultiLocation::new(1, Parachain(1001)); + pub const GovernanceLocation: MultiLocation = MultiLocation::parent(); +} + +/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// when determining ownership of accounts for asset transacting and when attempting to use XCM +/// `Transact` in order to determine the dispatch Origin. +pub type LocationToAccountId = ( + // The parent (Relay-chain) origin converts to the parent `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, + // Foreign chain account alias into local accounts according to a hash of their standard + // description. + HashedDescription>, +); + +/// Means for transacting the native currency on this chain. +pub type CurrencyTransactor = CurrencyAdapter< + // Use this currency: + Balances, + // Use this currency when it is a fungible asset matching the given location or name: + IsConcrete, + // Convert an XCM MultiLocation into a local account id: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We don't track any teleports of `Balances`. + (), +>; + +/// `AssetId`/`Balance` converter for `TrustBackedAssets`. +pub type TrustBackedAssetsConvertedConcreteId = + assets_common::TrustBackedAssetsConvertedConcreteId; + +/// Means for transacting assets besides the native currency on this chain. +pub type FungiblesTransactor = FungiblesAdapter< + // Use this fungibles implementation: + Assets, + // Use this currency when it is a fungible asset matching the given location or name: + TrustBackedAssetsConvertedConcreteId, + // Convert an XCM MultiLocation into a local account id: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We only want to allow teleports of known assets. We use non-zero issuance as an indication + // that this asset is known. + LocalMint>, + // The account to use for tracking teleports. + CheckingAccount, +>; + +/// `AssetId/Balance` converter for `TrustBackedAssets` +pub type ForeignAssetsConvertedConcreteId = assets_common::ForeignAssetsConvertedConcreteId< + ( + // Ignore `TrustBackedAssets` explicitly + StartsWith, + // Ignore assets that start explicitly with our `GlobalConsensus(NetworkId)`, means: + // - foreign assets from our consensus should be: `MultiLocation {parents: 1, + // X*(Parachain(xyz), ..)}` + // - foreign assets outside our consensus with the same `GlobalConsensus(NetworkId)` won't + // be accepted here + StartsWithExplicitGlobalConsensus, + ), + Balance, +>; + +/// Means for transacting foreign assets from different global consensus. +pub type ForeignFungiblesTransactor = FungiblesAdapter< + // Use this fungibles implementation: + ForeignAssets, + // Use this currency when it is a fungible asset matching the given location or name: + ForeignAssetsConvertedConcreteId, + // Convert an XCM MultiLocation into a local account id: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We dont need to check teleports here. + NoChecking, + // The account to use for tracking teleports. + CheckingAccount, +>; + +/// Means for transacting assets on this chain. +pub type AssetTransactors = (CurrencyTransactor, FungiblesTransactor, ForeignFungiblesTransactor); + +/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, +/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can +/// biases the kind of local `Origin` it will become. +pub type XcmOriginToTransactDispatchOrigin = ( + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, + // Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when + // recognised. + RelayChainAsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognised. + SiblingParachainAsNative, + // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a + // transaction from the Root origin. + ParentAsSuperuser, + // Native signed account converter; this just converts an `AccountId32` origin into a normal + // `RuntimeOrigin::Signed` origin of the same 32-byte value. + SignedAccountId32AsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, +); + +parameter_types! { + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; + pub XcmAssetFeesReceiver: Option = Authorship::author(); +} + +match_types! { + pub type ParentOrParentsPlurality: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(Plurality { .. }) } + }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; + pub type FellowsPlurality: impl Contains = { + MultiLocation { parents: 1, interior: X2(Parachain(1001), Plurality { id: BodyId::Technical, ..}) } + }; + pub type FellowshipSalaryPallet: impl Contains = { + MultiLocation { parents: 1, interior: X2(Parachain(1001), PalletInstance(64)) } + }; + pub type AmbassadorSalaryPallet: impl Contains = { + MultiLocation { parents: 1, interior: X2(Parachain(1001), PalletInstance(74)) } + }; +} + +/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly +/// account for proof size weights. +/// +/// Calls that are allowed through this filter must: +/// 1. Have a fixed weight; +/// 2. Cannot lead to another call being made; +/// 3. Have a defined proof size weight, e.g. no unbounded vecs in call parameters. +pub struct SafeCallFilter; +impl Contains for SafeCallFilter { + fn contains(call: &RuntimeCall) -> bool { + #[cfg(feature = "runtime-benchmarks")] + { + if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { + return true + } + } + + matches!( + call, + RuntimeCall::PolkadotXcm(pallet_xcm::Call::force_xcm_version { .. }) | + RuntimeCall::System( + frame_system::Call::set_heap_pages { .. } | + frame_system::Call::set_code { .. } | + frame_system::Call::set_code_without_checks { .. } | + frame_system::Call::kill_prefix { .. }, + ) | RuntimeCall::ParachainSystem(..) | + RuntimeCall::Timestamp(..) | + RuntimeCall::Balances(..) | + RuntimeCall::CollatorSelection( + pallet_collator_selection::Call::set_desired_candidates { .. } | + pallet_collator_selection::Call::set_candidacy_bond { .. } | + pallet_collator_selection::Call::register_as_candidate { .. } | + pallet_collator_selection::Call::leave_intent { .. } | + pallet_collator_selection::Call::set_invulnerables { .. } | + pallet_collator_selection::Call::add_invulnerable { .. } | + pallet_collator_selection::Call::remove_invulnerable { .. }, + ) | RuntimeCall::Session(pallet_session::Call::purge_keys { .. }) | + RuntimeCall::XcmpQueue(..) | + RuntimeCall::MessageQueue(..) | + RuntimeCall::Assets( + pallet_assets::Call::create { .. } | + pallet_assets::Call::force_create { .. } | + pallet_assets::Call::start_destroy { .. } | + pallet_assets::Call::destroy_accounts { .. } | + pallet_assets::Call::destroy_approvals { .. } | + pallet_assets::Call::finish_destroy { .. } | + pallet_assets::Call::mint { .. } | + pallet_assets::Call::burn { .. } | + pallet_assets::Call::transfer { .. } | + pallet_assets::Call::transfer_keep_alive { .. } | + pallet_assets::Call::force_transfer { .. } | + pallet_assets::Call::freeze { .. } | + pallet_assets::Call::thaw { .. } | + pallet_assets::Call::freeze_asset { .. } | + pallet_assets::Call::thaw_asset { .. } | + pallet_assets::Call::transfer_ownership { .. } | + pallet_assets::Call::set_team { .. } | + pallet_assets::Call::set_metadata { .. } | + pallet_assets::Call::clear_metadata { .. } | + pallet_assets::Call::force_set_metadata { .. } | + pallet_assets::Call::force_clear_metadata { .. } | + pallet_assets::Call::force_asset_status { .. } | + pallet_assets::Call::approve_transfer { .. } | + pallet_assets::Call::cancel_approval { .. } | + pallet_assets::Call::force_cancel_approval { .. } | + pallet_assets::Call::transfer_approved { .. } | + pallet_assets::Call::touch { .. } | + pallet_assets::Call::refund { .. }, + ) | RuntimeCall::ForeignAssets( + pallet_assets::Call::create { .. } | + pallet_assets::Call::force_create { .. } | + pallet_assets::Call::start_destroy { .. } | + pallet_assets::Call::destroy_accounts { .. } | + pallet_assets::Call::destroy_approvals { .. } | + pallet_assets::Call::finish_destroy { .. } | + pallet_assets::Call::mint { .. } | + pallet_assets::Call::burn { .. } | + pallet_assets::Call::transfer { .. } | + pallet_assets::Call::transfer_keep_alive { .. } | + pallet_assets::Call::force_transfer { .. } | + pallet_assets::Call::freeze { .. } | + pallet_assets::Call::thaw { .. } | + pallet_assets::Call::freeze_asset { .. } | + pallet_assets::Call::thaw_asset { .. } | + pallet_assets::Call::transfer_ownership { .. } | + pallet_assets::Call::set_team { .. } | + pallet_assets::Call::set_metadata { .. } | + pallet_assets::Call::clear_metadata { .. } | + pallet_assets::Call::force_set_metadata { .. } | + pallet_assets::Call::force_clear_metadata { .. } | + pallet_assets::Call::force_asset_status { .. } | + pallet_assets::Call::approve_transfer { .. } | + pallet_assets::Call::cancel_approval { .. } | + pallet_assets::Call::force_cancel_approval { .. } | + pallet_assets::Call::transfer_approved { .. } | + pallet_assets::Call::touch { .. } | + pallet_assets::Call::refund { .. }, + ) | RuntimeCall::Nfts( + pallet_nfts::Call::create { .. } | + pallet_nfts::Call::force_create { .. } | + pallet_nfts::Call::destroy { .. } | + pallet_nfts::Call::mint { .. } | + pallet_nfts::Call::force_mint { .. } | + pallet_nfts::Call::burn { .. } | + pallet_nfts::Call::transfer { .. } | + pallet_nfts::Call::lock_item_transfer { .. } | + pallet_nfts::Call::unlock_item_transfer { .. } | + pallet_nfts::Call::lock_collection { .. } | + pallet_nfts::Call::transfer_ownership { .. } | + pallet_nfts::Call::set_team { .. } | + pallet_nfts::Call::force_collection_owner { .. } | + pallet_nfts::Call::force_collection_config { .. } | + pallet_nfts::Call::approve_transfer { .. } | + pallet_nfts::Call::cancel_approval { .. } | + pallet_nfts::Call::clear_all_transfer_approvals { .. } | + pallet_nfts::Call::lock_item_properties { .. } | + pallet_nfts::Call::set_attribute { .. } | + pallet_nfts::Call::force_set_attribute { .. } | + pallet_nfts::Call::clear_attribute { .. } | + pallet_nfts::Call::approve_item_attributes { .. } | + pallet_nfts::Call::cancel_item_attributes_approval { .. } | + pallet_nfts::Call::set_metadata { .. } | + pallet_nfts::Call::clear_metadata { .. } | + pallet_nfts::Call::set_collection_metadata { .. } | + pallet_nfts::Call::clear_collection_metadata { .. } | + pallet_nfts::Call::set_accept_ownership { .. } | + pallet_nfts::Call::set_collection_max_supply { .. } | + pallet_nfts::Call::update_mint_settings { .. } | + pallet_nfts::Call::set_price { .. } | + pallet_nfts::Call::buy_item { .. } | + pallet_nfts::Call::pay_tips { .. } | + pallet_nfts::Call::create_swap { .. } | + pallet_nfts::Call::cancel_swap { .. } | + pallet_nfts::Call::claim_swap { .. }, + ) | RuntimeCall::Uniques( + pallet_uniques::Call::create { .. } | + pallet_uniques::Call::force_create { .. } | + pallet_uniques::Call::destroy { .. } | + pallet_uniques::Call::mint { .. } | + pallet_uniques::Call::burn { .. } | + pallet_uniques::Call::transfer { .. } | + pallet_uniques::Call::freeze { .. } | + pallet_uniques::Call::thaw { .. } | + pallet_uniques::Call::freeze_collection { .. } | + pallet_uniques::Call::thaw_collection { .. } | + pallet_uniques::Call::transfer_ownership { .. } | + pallet_uniques::Call::set_team { .. } | + pallet_uniques::Call::approve_transfer { .. } | + pallet_uniques::Call::cancel_approval { .. } | + pallet_uniques::Call::force_item_status { .. } | + pallet_uniques::Call::set_attribute { .. } | + pallet_uniques::Call::clear_attribute { .. } | + pallet_uniques::Call::set_metadata { .. } | + pallet_uniques::Call::clear_metadata { .. } | + pallet_uniques::Call::set_collection_metadata { .. } | + pallet_uniques::Call::clear_collection_metadata { .. } | + pallet_uniques::Call::set_accept_ownership { .. } | + pallet_uniques::Call::set_collection_max_supply { .. } | + pallet_uniques::Call::set_price { .. } | + pallet_uniques::Call::buy_item { .. } + ) + ) + } +} + +pub type Barrier = TrailingSetTopicAsId< + DenyThenTry< + DenyReserveTransferToRelayChain, + ( + TakeWeightCredit, + // Expected responses are OK. + AllowKnownQueryResponses, + // Allow XCMs with some computed origins to pass through. + WithComputedOrigin< + ( + // If the message is one that immediately attempts to pay for execution, then + // allow it. + AllowTopLevelPaidExecutionFrom, + // Parent, its pluralities (i.e. governance bodies), and the Fellows plurality + // get free execution. + AllowExplicitUnpaidExecutionFrom<( + ParentOrParentsPlurality, + FellowsPlurality, + FellowshipSalaryPallet, + AmbassadorSalaryPallet, + )>, + // Subscriptions for version tracking are OK. + AllowSubscriptionsFrom, + ), + UniversalLocation, + ConstU32<8>, + >, + ), + >, +>; + +pub type AssetFeeAsExistentialDepositMultiplierFeeCharger = AssetFeeAsExistentialDepositMultiplier< + Runtime, + WeightToFee, + pallet_assets::BalanceToAssetBalance, + TrustBackedAssetsInstance, +>; + +/// Cases where a remote origin is accepted as trusted Teleporter for a given asset: +/// +/// - DOT with the parent Relay Chain and sibling system parachains; and +/// - Sibling parachains' assets from where they originate (as `ForeignCreators`). +pub type TrustedTeleporters = ( + ConcreteAssetFromSystem, + IsForeignConcreteAsset>>, +); + +pub struct XcmConfig; +impl xcm_executor::Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = AssetTransactors; + type OriginConverter = XcmOriginToTransactDispatchOrigin; + // Asset Hub Polkadot does not recognize a reserve location for any asset. This does not prevent + // Asset Hub acting _as_ a reserve location for DOT and assets created under `pallet-assets`. + // For DOT, users must use teleport where allowed (e.g. with the Relay Chain). + type IsReserve = (); + type IsTeleporter = TrustedTeleporters; + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = WeightInfoBounds< + crate::weights::xcm::AssetHubPolkadotXcmWeight, + RuntimeCall, + MaxInstructions, + >; + type Trader = ( + UsingComponents>, + cumulus_primitives_utility::TakeFirstAssetTrader< + AccountId, + AssetFeeAsExistentialDepositMultiplierFeeCharger, + TrustBackedAssetsConvertedConcreteId, + Assets, + cumulus_primitives_utility::XcmFeesTo32ByteAccount< + FungiblesTransactor, + AccountId, + XcmAssetFeesReceiver, + >, + >, + ); + type ResponseHandler = PolkadotXcm; + type AssetTrap = PolkadotXcm; + type AssetClaims = PolkadotXcm; + type SubscriptionService = PolkadotXcm; + type PalletInstancesInfo = AllPalletsWithSystem; + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type AssetLocker = (); + type AssetExchanger = (); + type FeeManager = (); + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = WithOriginFilter; + type SafeCallFilter = SafeCallFilter; + type Aliasers = Nothing; +} + +/// Converts a local signed origin into an XCM multilocation. +/// Forms the basis for local origins sending/executing XCMs. +pub type LocalOriginToLocation = SignedToAccountId32; + +parameter_types! { + /// The asset ID for the asset that we use to pay for message delivery fees. + pub FeeAssetId: AssetId = Concrete(DotLocation::get()); + /// The base fee for the message delivery fees. + pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); +} + +pub type PriceForParentDelivery = + ExponentialPrice; + +/// The means for routing XCM messages which are not for local execution into the right message +/// queues. +pub type XcmRouter = WithUniqueTopic<( + // Two routers - use UMP to communicate with the relay chain: + cumulus_primitives_utility::ParentAsUmp, + // ..and XCMP to communicate with the sibling chains. + XcmpQueue, +)>; + +impl pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + // We want to disallow users sending (arbitrary) XCMs from this chain. + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + // We support local origins dispatching XCM executions in principle... + type ExecuteXcmOrigin = EnsureXcmOrigin; + // ... but disallow generic XCM execution. As a result only teleports and reserve transfers are + // allowed. + type XcmExecuteFilter = Nothing; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Everything; + type XcmReserveTransferFilter = Everything; + type Weigher = WeightInfoBounds< + crate::weights::xcm::AssetHubPolkadotXcmWeight, + RuntimeCall, + MaxInstructions, + >; + type UniversalLocation = UniversalLocation; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type Currency = Balances; + type CurrencyMatcher = (); + type TrustedLockers = (); + type SovereignAccountOf = LocationToAccountId; + type MaxLockers = ConstU32<8>; + type WeightInfo = crate::weights::pallet_xcm::WeightInfo; + type AdminOrigin = EnsureRoot; + type MaxRemoteLockConsumers = ConstU32<0>; + type RemoteLockConsumerIdentifier = (); +} + +impl cumulus_pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type XcmExecutor = XcmExecutor; +} + +pub type ForeignCreatorsSovereignAccountOf = ( + SiblingParachainConvertsVia, + AccountId32Aliases, + ParentIsPreset, +); + +/// Simple conversion of `u32` into an `AssetId` for use in benchmarking. +pub struct XcmBenchmarkHelper; +#[cfg(feature = "runtime-benchmarks")] +impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { + fn create_asset_id_parameter(id: u32) -> MultiLocation { + MultiLocation { parents: 1, interior: X1(Parachain(id)) } + } +} + +#[test] +fn foreign_pallet_has_correct_local_account() { + use sp_core::crypto::{Ss58AddressFormat, Ss58Codec}; + use xcm_executor::traits::ConvertLocation; + + const COLLECTIVES_PARAID: u32 = 1001; + const FELLOWSHIP_SALARY_PALLET_ID: u8 = 64; + let fellowship_salary = + (Parent, Parachain(COLLECTIVES_PARAID), PalletInstance(FELLOWSHIP_SALARY_PALLET_ID)); + let account = LocationToAccountId::convert_location(&fellowship_salary.into()).unwrap(); + let polkadot = Ss58AddressFormat::try_from("polkadot").unwrap(); + let address = Ss58Codec::to_ss58check_with_version(&account, polkadot); + assert_eq!(address, "13w7NdvSR1Af8xsQTArDtZmVvjE8XhWNdL4yed3iFHrUNCnS"); +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/tests/tests.rs new file mode 100644 index 00000000000..b7e44646ece --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/tests/tests.rs @@ -0,0 +1,683 @@ +// This file is part of Cumulus. + +// 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 the Statemint (Polkadot Assets Hub) chain. + +use asset_hub_polkadot_runtime::xcm_config::{ + AssetFeeAsExistentialDepositMultiplierFeeCharger, CheckingAccount, DotLocation, + ForeignCreatorsSovereignAccountOf, LocationToAccountId, TrustBackedAssetsPalletLocation, + XcmConfig, +}; +pub use asset_hub_polkadot_runtime::{ + AllPalletsWithoutSystem, AssetDeposit, Assets, Balances, ExistentialDeposit, ForeignAssets, + ForeignAssetsInstance, MetadataDepositBase, MetadataDepositPerByte, ParachainSystem, Runtime, + RuntimeCall, RuntimeEvent, SessionKeys, System, TrustBackedAssetsInstance, XcmpQueue, +}; +use asset_test_utils::{CollatorSessionKeys, ExtBuilder}; +use codec::{Decode, Encode}; +use cumulus_primitives_utility::ChargeWeightInFungibles; +use frame_support::{ + assert_noop, assert_ok, + traits::fungibles::InspectEnumerable, + weights::{Weight, WeightToFee as WeightToFeeT}, +}; +use parachains_common::{ + polkadot::fee::WeightToFee, AccountId, AssetHubPolkadotAuraId as AuraId, + AssetIdForTrustBackedAssets, Balance, +}; +use sp_runtime::traits::MaybeEquivalence; +use xcm::latest::prelude::*; +use xcm_executor::traits::{Identity, JustTry, WeightTrader}; + +const ALICE: [u8; 32] = [1u8; 32]; +const SOME_ASSET_ADMIN: [u8; 32] = [5u8; 32]; + +type AssetIdForTrustBackedAssetsConvert = + assets_common::AssetIdForTrustBackedAssetsConvert; + +type RuntimeHelper = asset_test_utils::RuntimeHelper; + +fn collator_session_keys() -> CollatorSessionKeys { + CollatorSessionKeys::new( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::ed25519::Public::from_raw(ALICE)) }, + ) +} + +#[test] +fn test_asset_xcm_trader() { + ExtBuilder::::default() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::ed25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + // We need root origin to create a sufficient asset + let minimum_asset_balance = 333333333_u128; + let local_asset_id = 1; + assert_ok!(Assets::force_create( + RuntimeHelper::root_origin(), + local_asset_id.into(), + AccountId::from(ALICE).into(), + true, + minimum_asset_balance + )); + + // We first mint enough asset for the account to exist for assets + assert_ok!(Assets::mint( + RuntimeHelper::origin_of(AccountId::from(ALICE)), + local_asset_id.into(), + AccountId::from(ALICE).into(), + minimum_asset_balance + )); + + // get asset id as multilocation + let asset_multilocation = + AssetIdForTrustBackedAssetsConvert::convert_back(&local_asset_id).unwrap(); + + // Set Alice as block author, who will receive fees + RuntimeHelper::run_to_block(2, AccountId::from(ALICE)); + + // We are going to buy 400e9 weight + // Because of the ED being higher in kusama's asset hub + // and not to complicate things, we use a little + // bit more of weight + let bought = Weight::from_parts(400_000_000_000u64, 0); + + // Lets calculate amount needed + let asset_amount_needed = + AssetFeeAsExistentialDepositMultiplierFeeCharger::charge_weight_in_fungibles( + local_asset_id, + bought, + ) + .expect("failed to compute"); + + // Lets pay with: asset_amount_needed + asset_amount_extra + let asset_amount_extra = 100_u128; + let asset: MultiAsset = + (asset_multilocation, asset_amount_needed + asset_amount_extra).into(); + + let mut trader = ::Trader::new(); + let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; + + // Lets buy_weight and make sure buy_weight does not return an error + let unused_assets = trader.buy_weight(bought, asset.into(), &ctx).expect("Expected Ok"); + // Check whether a correct amount of unused assets is returned + assert_ok!( + unused_assets.ensure_contains(&(asset_multilocation, asset_amount_extra).into()) + ); + + // Drop trader + drop(trader); + + // Make sure author(Alice) has received the amount + assert_eq!( + Assets::balance(local_asset_id, AccountId::from(ALICE)), + minimum_asset_balance + asset_amount_needed + ); + + // We also need to ensure the total supply increased + assert_eq!( + Assets::total_supply(local_asset_id), + minimum_asset_balance + asset_amount_needed + ); + }); +} + +#[test] +fn test_asset_xcm_trader_with_refund() { + ExtBuilder::::default() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::ed25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + // We need root origin to create a sufficient asset + // We set existential deposit to be identical to the one for Balances first + assert_ok!(Assets::force_create( + RuntimeHelper::root_origin(), + 1.into(), + AccountId::from(ALICE).into(), + true, + ExistentialDeposit::get() + )); + + // We first mint enough asset for the account to exist for assets + assert_ok!(Assets::mint( + RuntimeHelper::origin_of(AccountId::from(ALICE)), + 1.into(), + AccountId::from(ALICE).into(), + ExistentialDeposit::get() + )); + + let mut trader = ::Trader::new(); + let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; + + // Set Alice as block author, who will receive fees + RuntimeHelper::run_to_block(2, AccountId::from(ALICE)); + + // We are going to buy 400e9 weight + // Because of the ED being higher in kusama's asset hub + // and not to complicate things, we use a little + // bit more of weight + let bought = Weight::from_parts(400_000_000_000u64, 0); + + let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + + // lets calculate amount needed + let amount_bought = WeightToFee::weight_to_fee(&bought); + + let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + + // Make sure buy_weight does not return an error + assert_ok!(trader.buy_weight(bought, asset.clone().into(), &ctx)); + + // Make sure again buy_weight does return an error + // This assert relies on the fact, that we use `TakeFirstAssetTrader` in `WeightTrader` + // tuple chain, which cannot be called twice + assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); + + // We actually use half of the weight + let weight_used = bought / 2; + + // Make sure refurnd works. + let amount_refunded = WeightToFee::weight_to_fee(&(bought - weight_used)); + + assert_eq!( + trader.refund_weight(bought - weight_used, &ctx), + Some((asset_multilocation, amount_refunded).into()) + ); + + // Drop trader + drop(trader); + + // We only should have paid for half of the bought weight + let fees_paid = WeightToFee::weight_to_fee(&weight_used); + + assert_eq!( + Assets::balance(1, AccountId::from(ALICE)), + ExistentialDeposit::get() + fees_paid + ); + + // We also need to ensure the total supply increased + assert_eq!(Assets::total_supply(1), ExistentialDeposit::get() + fees_paid); + }); +} + +#[test] +fn test_asset_xcm_trader_refund_not_possible_since_amount_less_than_ed() { + ExtBuilder::::default() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::ed25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + // We need root origin to create a sufficient asset + // We set existential deposit to be identical to the one for Balances first + assert_ok!(Assets::force_create( + RuntimeHelper::root_origin(), + 1.into(), + AccountId::from(ALICE).into(), + true, + ExistentialDeposit::get() + )); + + let mut trader = ::Trader::new(); + let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; + + // Set Alice as block author, who will receive fees + RuntimeHelper::run_to_block(2, AccountId::from(ALICE)); + + // We are going to buy 50e9 weight + // Because of the ED being higher in kusama's asset hub + // and not to complicate things, we use a little + // bit more of weight + let bought = Weight::from_parts(50_000_000_000u64, 0); + + let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + + let amount_bought = WeightToFee::weight_to_fee(&bought); + + assert!( + amount_bought < ExistentialDeposit::get(), + "we are testing what happens when the amount does not exceed ED" + ); + + let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + + // Buy weight should return an error + assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); + + // not credited since the ED is higher than this value + assert_eq!(Assets::balance(1, AccountId::from(ALICE)), 0); + + // We also need to ensure the total supply did not increase + assert_eq!(Assets::total_supply(1), 0); + }); +} + +#[test] +fn test_that_buying_ed_refund_does_not_refund() { + ExtBuilder::::default() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::ed25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + // We need root origin to create a sufficient asset + // We set existential deposit to be identical to the one for Balances first + assert_ok!(Assets::force_create( + RuntimeHelper::root_origin(), + 1.into(), + AccountId::from(ALICE).into(), + true, + ExistentialDeposit::get() + )); + + let mut trader = ::Trader::new(); + let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; + + // Set Alice as block author, who will receive fees + RuntimeHelper::run_to_block(2, AccountId::from(ALICE)); + + // We are gonna buy ED + let bought = Weight::from_parts(ExistentialDeposit::get().try_into().unwrap(), 0); + + let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + + let amount_bought = WeightToFee::weight_to_fee(&bought); + + assert!( + amount_bought < ExistentialDeposit::get(), + "we are testing what happens when the amount does not exceed ED" + ); + + // We know we will have to buy at least ED, so lets make sure first it will + // fail with a payment of less than ED + let asset: MultiAsset = (asset_multilocation, amount_bought).into(); + assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); + + // Now lets buy ED at least + let asset: MultiAsset = (asset_multilocation, ExistentialDeposit::get()).into(); + + // Buy weight should work + assert_ok!(trader.buy_weight(bought, asset.into(), &ctx)); + + // Should return None. We have a specific check making sure we dont go below ED for + // drop payment + assert_eq!(trader.refund_weight(bought, &ctx), None); + + // Drop trader + drop(trader); + + // Make sure author(Alice) has received the amount + assert_eq!(Assets::balance(1, AccountId::from(ALICE)), ExistentialDeposit::get()); + + // We also need to ensure the total supply increased + assert_eq!(Assets::total_supply(1), ExistentialDeposit::get()); + }); +} + +#[test] +fn test_asset_xcm_trader_not_possible_for_non_sufficient_assets() { + ExtBuilder::::default() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::ed25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + // Create a non-sufficient asset + let minimum_asset_balance = 1_000_000_u128; + assert_ok!(Assets::force_create( + RuntimeHelper::root_origin(), + 1.into(), + AccountId::from(ALICE).into(), + false, + minimum_asset_balance + )); + + // We first mint enough asset for the account to exist for assets + assert_ok!(Assets::mint( + RuntimeHelper::origin_of(AccountId::from(ALICE)), + 1.into(), + AccountId::from(ALICE).into(), + minimum_asset_balance + )); + + let mut trader = ::Trader::new(); + let ctx = XcmContext { origin: None, message_id: XcmHash::default(), topic: None }; + + // Set Alice as block author, who will receive fees + RuntimeHelper::run_to_block(2, AccountId::from(ALICE)); + + // We are going to buy 400e9 weight + // Because of the ED being higher in kusama's asset hub + // and not to complicate things, we use a little + // bit more of weight + let bought = Weight::from_parts(400_000_000_000u64, 0); + + // lets calculate amount needed + let asset_amount_needed = WeightToFee::weight_to_fee(&bought); + + let asset_multilocation = AssetIdForTrustBackedAssetsConvert::convert_back(&1).unwrap(); + + let asset: MultiAsset = (asset_multilocation, asset_amount_needed).into(); + + // Make sure again buy_weight does return an error + assert_noop!(trader.buy_weight(bought, asset.into(), &ctx), XcmError::TooExpensive); + + // Drop trader + drop(trader); + + // Make sure author(Alice) has NOT received the amount + assert_eq!(Assets::balance(1, AccountId::from(ALICE)), minimum_asset_balance); + + // We also need to ensure the total supply NOT increased + assert_eq!(Assets::total_supply(1), minimum_asset_balance); + }); +} + +#[test] +fn test_assets_balances_api_works() { + use assets_common::runtime_api::runtime_decl_for_fungibles_api::FungiblesApi; + + ExtBuilder::::default() + .with_collators(vec![AccountId::from(ALICE)]) + .with_session_keys(vec![( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::ed25519::Public::from_raw(ALICE)) }, + )]) + .build() + .execute_with(|| { + let local_asset_id = 1; + let foreign_asset_id_multilocation = + MultiLocation { parents: 1, interior: X2(Parachain(1234), GeneralIndex(12345)) }; + + // check before + assert_eq!(Assets::balance(local_asset_id, AccountId::from(ALICE)), 0); + assert_eq!( + ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)), + 0 + ); + assert_eq!(Balances::free_balance(AccountId::from(ALICE)), 0); + assert!(Runtime::query_account_balances(AccountId::from(ALICE)) + .unwrap() + .try_as::() + .unwrap() + .is_none()); + + // Drip some balance + use frame_support::traits::fungible::Mutate; + let some_currency = ExistentialDeposit::get(); + Balances::mint_into(&AccountId::from(ALICE), some_currency).unwrap(); + + // We need root origin to create a sufficient asset + let minimum_asset_balance = 3333333_u128; + assert_ok!(Assets::force_create( + RuntimeHelper::root_origin(), + local_asset_id.into(), + AccountId::from(ALICE).into(), + true, + minimum_asset_balance + )); + + // We first mint enough asset for the account to exist for assets + assert_ok!(Assets::mint( + RuntimeHelper::origin_of(AccountId::from(ALICE)), + local_asset_id.into(), + AccountId::from(ALICE).into(), + minimum_asset_balance + )); + + // create foreign asset + let foreign_asset_minimum_asset_balance = 3333333_u128; + assert_ok!(ForeignAssets::force_create( + RuntimeHelper::root_origin(), + foreign_asset_id_multilocation, + AccountId::from(SOME_ASSET_ADMIN).into(), + false, + foreign_asset_minimum_asset_balance + )); + + // We first mint enough asset for the account to exist for assets + assert_ok!(ForeignAssets::mint( + RuntimeHelper::origin_of(AccountId::from(SOME_ASSET_ADMIN)), + foreign_asset_id_multilocation, + AccountId::from(ALICE).into(), + 6 * foreign_asset_minimum_asset_balance + )); + + // check after + assert_eq!( + Assets::balance(local_asset_id, AccountId::from(ALICE)), + minimum_asset_balance + ); + assert_eq!( + ForeignAssets::balance(foreign_asset_id_multilocation, AccountId::from(ALICE)), + 6 * minimum_asset_balance + ); + assert_eq!(Balances::free_balance(AccountId::from(ALICE)), some_currency); + + let result: MultiAssets = Runtime::query_account_balances(AccountId::from(ALICE)) + .unwrap() + .try_into() + .unwrap(); + assert_eq!(result.len(), 3); + + // check currency + assert!(result.inner().iter().any(|asset| asset.eq( + &assets_common::fungible_conversion::convert_balance::( + some_currency + ) + .unwrap() + ))); + // check trusted asset + assert!(result.inner().iter().any(|asset| asset.eq(&( + AssetIdForTrustBackedAssetsConvert::convert_back(&local_asset_id).unwrap(), + minimum_asset_balance + ) + .into()))); + // check foreign asset + assert!(result.inner().iter().any(|asset| asset.eq(&( + Identity::convert_back(&foreign_asset_id_multilocation).unwrap(), + 6 * foreign_asset_minimum_asset_balance + ) + .into()))); + }); +} + +asset_test_utils::include_teleports_for_native_asset_works!( + Runtime, + AllPalletsWithoutSystem, + XcmConfig, + CheckingAccount, + WeightToFee, + ParachainSystem, + collator_session_keys(), + ExistentialDeposit::get(), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::PolkadotXcm(event)) => Some(event), + _ => None, + } + }), + 1000 +); + +asset_test_utils::include_teleports_for_foreign_assets_works!( + Runtime, + AllPalletsWithoutSystem, + XcmConfig, + CheckingAccount, + WeightToFee, + ParachainSystem, + ForeignCreatorsSovereignAccountOf, + ForeignAssetsInstance, + asset_test_utils::CollatorSessionKeys::new( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::ed25519::Public::from_raw(ALICE)) } + ), + ExistentialDeposit::get(), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::PolkadotXcm(event)) => Some(event), + _ => None, + } + }), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::XcmpQueue(event)) => Some(event), + _ => None, + } + }) +); + +asset_test_utils::include_asset_transactor_transfer_with_local_consensus_currency_works!( + Runtime, + XcmConfig, + collator_session_keys(), + ExistentialDeposit::get(), + Box::new(|| { + assert!(Assets::asset_ids().collect::>().is_empty()); + assert!(ForeignAssets::asset_ids().collect::>().is_empty()); + }), + Box::new(|| { + assert!(Assets::asset_ids().collect::>().is_empty()); + assert!(ForeignAssets::asset_ids().collect::>().is_empty()); + }) +); + +asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_works!( + asset_transactor_transfer_with_trust_backed_assets_works, + Runtime, + XcmConfig, + TrustBackedAssetsInstance, + AssetIdForTrustBackedAssets, + AssetIdForTrustBackedAssetsConvert, + collator_session_keys(), + ExistentialDeposit::get(), + 12345, + Box::new(|| { + assert!(ForeignAssets::asset_ids().collect::>().is_empty()); + }), + Box::new(|| { + assert!(ForeignAssets::asset_ids().collect::>().is_empty()); + }) +); + +asset_test_utils::include_asset_transactor_transfer_with_pallet_assets_instance_works!( + asset_transactor_transfer_with_foreign_assets_works, + Runtime, + XcmConfig, + ForeignAssetsInstance, + MultiLocation, + JustTry, + asset_test_utils::CollatorSessionKeys::new( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::ed25519::Public::from_raw(ALICE)) } + ), + ExistentialDeposit::get(), + MultiLocation { parents: 1, interior: X2(Parachain(1313), GeneralIndex(12345)) }, + Box::new(|| { + assert!(Assets::asset_ids().collect::>().is_empty()); + }), + Box::new(|| { + assert!(Assets::asset_ids().collect::>().is_empty()); + }) +); + +asset_test_utils::include_create_and_manage_foreign_assets_for_local_consensus_parachain_assets_works!( + Runtime, + XcmConfig, + WeightToFee, + ForeignCreatorsSovereignAccountOf, + ForeignAssetsInstance, + MultiLocation, + JustTry, + asset_test_utils::CollatorSessionKeys::new( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::ed25519::Public::from_raw(ALICE)) } + ), + ExistentialDeposit::get(), + AssetDeposit::get(), + MetadataDepositBase::get(), + MetadataDepositPerByte::get(), + Box::new(|pallet_asset_call| RuntimeCall::ForeignAssets(pallet_asset_call).encode()), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::ForeignAssets(pallet_asset_event)) => Some(pallet_asset_event), + _ => None, + } + }), + Box::new(|| { + assert!(Assets::asset_ids().collect::>().is_empty()); + assert!(ForeignAssets::asset_ids().collect::>().is_empty()); + }), + Box::new(|| { + assert!(Assets::asset_ids().collect::>().is_empty()); + assert_eq!(ForeignAssets::asset_ids().collect::>().len(), 1); + }) +); + +#[test] +fn reserve_transfer_native_asset_to_non_teleport_para_works() { + asset_test_utils::test_cases::reserve_transfer_native_asset_to_non_teleport_para_works::< + Runtime, + AllPalletsWithoutSystem, + XcmConfig, + ParachainSystem, + XcmpQueue, + LocationToAccountId, + >( + collator_session_keys(), + ExistentialDeposit::get(), + AccountId::from(ALICE), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::PolkadotXcm(event)) => Some(event), + _ => None, + } + }), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::XcmpQueue(event)) => Some(event), + _ => None, + } + }), + WeightLimit::Unlimited, + ); +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml index 47af627d6b2..f3bdabd9cef 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml @@ -6,14 +6,16 @@ edition.workspace = true description = "Rococo variant of Asset Hub parachain runtime" license = "Apache-2.0" -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ + "derive", + "max-encoded-len", +] } hex-literal = { version = "0.4.1" } log = { version = "0.4.20", default-features = false } -scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } +scale-info = { version = "2.10.0", default-features = false, features = [ + "derive", +] } smallvec = "1.11.0" # Substrate @@ -58,7 +60,11 @@ sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction- sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } sp-weights = { path = "../../../../../substrate/primitives/weights", default-features = false } # 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 = { version = "0.12.1", default-features = false, features = [ + "codec", + "scale-info", + "num-traits", +] } # Polkadot rococo-runtime-constants = { path = "../../../../../polkadot/runtime/rococo/constants", default-features = false } @@ -73,10 +79,14 @@ xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkad # Cumulus cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = [ + "parameterized-consensus-hook", +] } 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-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false, features = [ + "bridging", +] } 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 } @@ -98,7 +108,7 @@ asset-test-utils = { path = "../test-utils" } substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] # When enabled the `state_version` is set to `1`. # This means that the chain will start using the new state format. The migration is lazy, so # it requires to write a storage value to use the new state format. To migrate all the other @@ -106,7 +116,7 @@ default = ["std"] # This pallet will migrate the entire state, controlled through some account. # # This feature should be removed when the main-net will be migrated. -state-trie-version-1 = ["pallet-state-trie-migration"] +state-trie-version-1 = [ "pallet-state-trie-migration" ] runtime-benchmarks = [ "assets-common/runtime-benchmarks", "cumulus-pallet-parachain-system/runtime-benchmarks", @@ -247,9 +257,9 @@ std = [ "xcm/std", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] # A feature that should be enabled when the runtime should be built for on-chain # deployment. This will disable stuff that shouldn't be part of the on-chain wasm # to make it smaller like logging for example. -on-chain-release-build = ["sp-api/disable-logging"] +on-chain-release-build = [ "sp-api/disable-logging" ] 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 cba294625b5..b2b46f5ee41 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs @@ -39,7 +39,9 @@ use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, - traits::{AccountIdConversion, BlakeTwo256, Block as BlockT, Saturating, Verify}, + traits::{ + AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Saturating, Verify, + }, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, Permill, }; @@ -52,7 +54,7 @@ use sp_version::RuntimeVersion; use codec::{Decode, Encode, MaxEncodedLen}; use cumulus_primitives_core::ParaId; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, ord_parameter_types, parameter_types, @@ -112,10 +114,10 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("statemine"), impl_name: create_runtime_str!("statemine"), authoring_version: 1, - spec_version: 1_005_000, + spec_version: 1_003_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, - transaction_version: 14, + transaction_version: 13, state_version: 1, }; @@ -125,10 +127,10 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("statemine"), impl_name: create_runtime_str!("statemine"), authoring_version: 1, - spec_version: 1_005_000, + spec_version: 1_003_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, - transaction_version: 14, + transaction_version: 13, state_version: 0, }; @@ -164,17 +166,25 @@ parameter_types! { } // Configure FRAME pallets to include in runtime. -#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = RuntimeBlockWeights; type BlockLength = RuntimeBlockLength; type AccountId = AccountId; + type RuntimeCall = RuntimeCall; + type Lookup = AccountIdLookup; type Nonce = Nonce; type Hash = Hash; + type Hashing = BlakeTwo256; type Block = Block; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; type BlockHashCount = BlockHashCount; type DbWeight = RocksDbWeight; type Version = Version; + type PalletInfo = PalletInfo; + type OnNewAccount = (); + type OnKilledAccount = (); type AccountData = pallet_balances::AccountData; type SystemWeightInfo = weights::frame_system::WeightInfo; type SS58Prefix = SS58Prefix; @@ -846,7 +856,6 @@ impl pallet_xcm_bridge_hub_router::Config for Runtim type UniversalLocation = xcm_config::UniversalLocation; type BridgedNetworkId = xcm_config::bridging::to_westend::WestendNetwork; type Bridges = xcm_config::bridging::NetworkExportTable; - type DestinationVersion = PolkadotXcm; #[cfg(not(feature = "runtime-benchmarks"))] type BridgeHubOrigin = EnsureXcm>; @@ -945,12 +954,8 @@ pub type TxExtension = ( pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; /// Migrations to apply on runtime upgrade. -pub type Migrations = ( - pallet_collator_selection::migration::v1::MigrateToV1, - InitStorageVersions, - // unreleased - cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4, -); +pub type Migrations = + (pallet_collator_selection::migration::v1::MigrateToV1, InitStorageVersions); /// Migration to initialize storage versions for pallets added after genesis. /// @@ -1360,55 +1365,6 @@ impl_runtime_apis! { ParentThen(Parachain(random_para_id).into()).into(), )) } - - fn set_up_complex_asset_transfer( - ) -> Option<(MultiAssets, u32, MultiLocation, Box)> { - // Transfer to Relay some local AH asset (local-reserve-transfer) while paying - // fees using teleported native token. - // (We don't care that Relay doesn't accept incoming unknown AH local asset) - let dest = Parent.into(); - - let fee_amount = EXISTENTIAL_DEPOSIT; - let fee_asset: MultiAsset = (MultiLocation::parent(), fee_amount).into(); - - let who = frame_benchmarking::whitelisted_caller(); - // Give some multiple of the existential deposit - let balance = fee_amount + EXISTENTIAL_DEPOSIT * 1000; - let _ = >::make_free_balance_be( - &who, balance, - ); - // verify initial balance - assert_eq!(Balances::free_balance(&who), balance); - - // set up local asset - let asset_amount = 10u128; - let initial_asset_amount = asset_amount * 10; - let (asset_id, _, _) = pallet_assets::benchmarking::create_default_minted_asset::< - Runtime, - pallet_assets::Instance1 - >(true, initial_asset_amount); - let asset_location = MultiLocation::new( - 0, - X2(PalletInstance(50), GeneralIndex(u32::from(asset_id).into())) - ); - let transfer_asset: MultiAsset = (asset_location, asset_amount).into(); - - let assets: MultiAssets = vec![fee_asset.clone(), transfer_asset].into(); - let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 }; - - // verify transferred successfully - let verify = Box::new(move || { - // verify native balance after transfer, decreased by transferred fee amount - // (plus transport fees) - assert!(Balances::free_balance(&who) <= balance - fee_amount); - // verify asset balance decreased by exactly transferred amount - assert_eq!( - Assets::balance(asset_id.into(), &who), - initial_asset_amount - asset_amount, - ); - }); - Some((assets, fee_index as u32, dest, verify)) - } } impl XcmBridgeHubRouterConfig for Runtime { @@ -1417,26 +1373,11 @@ impl_runtime_apis! { xcm_config::bridging::SiblingBridgeHubParaId::get().into() ); } - fn ensure_bridged_target_destination() -> Result { + fn ensure_bridged_target_destination() -> MultiLocation { ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( xcm_config::bridging::SiblingBridgeHubParaId::get().into() ); - let bridged_asset_hub = xcm_config::bridging::to_westend::AssetHubWestend::get(); - let _ = PolkadotXcm::force_xcm_version( - RuntimeOrigin::root(), - Box::new(bridged_asset_hub), - XCM_VERSION, - ).map_err(|e| { - log::error!( - "Failed to dispatch `force_xcm_version({:?}, {:?}, {:?})`, error: {:?}", - RuntimeOrigin::root(), - bridged_asset_hub, - XCM_VERSION, - e - ); - BenchmarkError::Stop("XcmVersion was not stored!") - })?; - Ok(bridged_asset_hub) + xcm_config::bridging::to_westend::AssetHubWestend::get() } } @@ -1455,7 +1396,7 @@ impl_runtime_apis! { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< - xcm_config::XcmConfig, + xcm_config::XcmConfig, ExistentialDepositMultiAsset, xcm_config::PriceForParentDelivery, >; diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm.rs index f8820bbb58c..afe85fdaf28 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-05, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-11-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-r43aesjn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: @@ -64,95 +64,37 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 25_003_000 picoseconds. - Weight::from_parts(25_800_000, 0) + // Minimum execution time: 24_498_000 picoseconds. + Weight::from_parts(25_385_000, 0) .saturating_add(Weight::from_parts(0, 3610)) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } + /// Storage: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) + /// Proof: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) - /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) - /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn teleport_assets() -> Weight { // Proof Size summary in bytes: - // Measured: `145` - // Estimated: `3610` - // Minimum execution time: 88_832_000 picoseconds. - Weight::from_parts(90_491_000, 0) - .saturating_add(Weight::from_parts(0, 3610)) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(3)) + // Measured: `39` + // Estimated: `3504` + // Minimum execution time: 19_746_000 picoseconds. + Weight::from_parts(20_535_000, 0) + .saturating_add(Weight::from_parts(0, 3504)) + .saturating_add(T::DbWeight::get().reads(2)) } + /// Storage: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) + /// Proof: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `XcmpQueue::DeliveryFeeFactor` (r:1 w:0) - /// Proof: `XcmpQueue::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::RelevantMessagingState` (r:1 w:0) - /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) - /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) - /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) fn reserve_transfer_assets() -> Weight { // Proof Size summary in bytes: - // Measured: `400` - // Estimated: `6196` - // Minimum execution time: 138_911_000 picoseconds. - Weight::from_parts(142_483_000, 0) - .saturating_add(Weight::from_parts(0, 6196)) - .saturating_add(T::DbWeight::get().reads(9)) - .saturating_add(T::DbWeight::get().writes(5)) - } - /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) - /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:2 w:2) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) - /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) - /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - fn transfer_assets() -> Weight { - // Proof Size summary in bytes: - // Measured: `496` - // Estimated: `6208` - // Minimum execution time: 146_932_000 picoseconds. - Weight::from_parts(153_200_000, 0) - .saturating_add(Weight::from_parts(0, 6208)) - .saturating_add(T::DbWeight::get().reads(12)) - .saturating_add(T::DbWeight::get().writes(7)) + // Measured: `39` + // Estimated: `3504` + // Minimum execution time: 15_059_000 picoseconds. + Weight::from_parts(15_386_000, 0) + .saturating_add(Weight::from_parts(0, 3504)) + .saturating_add(T::DbWeight::get().reads(2)) } /// Storage: `Benchmark::Override` (r:0 w:0) /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -170,8 +112,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_081_000 picoseconds. - Weight::from_parts(7_397_000, 0) + // Minimum execution time: 7_108_000 picoseconds. + Weight::from_parts(7_458_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -181,8 +123,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_007_000 picoseconds. - Weight::from_parts(2_183_000, 0) + // Minimum execution time: 2_205_000 picoseconds. + Weight::from_parts(2_360_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -208,8 +150,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 28_790_000 picoseconds. - Weight::from_parts(29_767_000, 0) + // Minimum execution time: 29_099_000 picoseconds. + Weight::from_parts(29_580_000, 0) .saturating_add(Weight::from_parts(0, 3610)) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(5)) @@ -234,8 +176,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `363` // Estimated: `3828` - // Minimum execution time: 30_951_000 picoseconds. - Weight::from_parts(31_804_000, 0) + // Minimum execution time: 31_161_000 picoseconds. + Weight::from_parts(31_933_000, 0) .saturating_add(Weight::from_parts(0, 3828)) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(4)) @@ -246,8 +188,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_164_000 picoseconds. - Weight::from_parts(2_311_000, 0) + // Minimum execution time: 2_158_000 picoseconds. + Weight::from_parts(2_316_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -257,8 +199,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `162` // Estimated: `11052` - // Minimum execution time: 16_906_000 picoseconds. - Weight::from_parts(17_612_000, 0) + // Minimum execution time: 16_934_000 picoseconds. + Weight::from_parts(17_655_000, 0) .saturating_add(Weight::from_parts(0, 11052)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -269,8 +211,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `166` // Estimated: `11056` - // Minimum execution time: 17_443_000 picoseconds. - Weight::from_parts(18_032_000, 0) + // Minimum execution time: 17_658_000 picoseconds. + Weight::from_parts(17_973_000, 0) .saturating_add(Weight::from_parts(0, 11056)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -281,8 +223,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `173` // Estimated: `13538` - // Minimum execution time: 18_992_000 picoseconds. - Weight::from_parts(19_464_000, 0) + // Minimum execution time: 18_673_000 picoseconds. + Weight::from_parts(19_027_000, 0) .saturating_add(Weight::from_parts(0, 13538)) .saturating_add(T::DbWeight::get().reads(5)) } @@ -304,8 +246,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `212` // Estimated: `6152` - // Minimum execution time: 28_011_000 picoseconds. - Weight::from_parts(28_716_000, 0) + // Minimum execution time: 27_171_000 picoseconds. + Weight::from_parts(27_802_000, 0) .saturating_add(Weight::from_parts(0, 6152)) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(3)) @@ -316,8 +258,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `206` // Estimated: `8621` - // Minimum execution time: 9_533_000 picoseconds. - Weight::from_parts(9_856_000, 0) + // Minimum execution time: 9_423_000 picoseconds. + Weight::from_parts(9_636_000, 0) .saturating_add(Weight::from_parts(0, 8621)) .saturating_add(T::DbWeight::get().reads(3)) } @@ -327,8 +269,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `173` // Estimated: `11063` - // Minimum execution time: 17_628_000 picoseconds. - Weight::from_parts(18_146_000, 0) + // Minimum execution time: 17_442_000 picoseconds. + Weight::from_parts(17_941_000, 0) .saturating_add(Weight::from_parts(0, 11063)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -351,8 +293,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `215` // Estimated: `11105` - // Minimum execution time: 34_877_000 picoseconds. - Weight::from_parts(35_607_000, 0) + // Minimum execution time: 34_340_000 picoseconds. + Weight::from_parts(34_934_000, 0) .saturating_add(Weight::from_parts(0, 11105)) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) @@ -365,8 +307,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `103` // Estimated: `1588` - // Minimum execution time: 5_370_000 picoseconds. - Weight::from_parts(5_616_000, 0) + // Minimum execution time: 5_496_000 picoseconds. + Weight::from_parts(5_652_000, 0) .saturating_add(Weight::from_parts(0, 1588)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(2)) @@ -377,8 +319,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `7740` // Estimated: `11205` - // Minimum execution time: 26_820_000 picoseconds. - Weight::from_parts(27_143_000, 0) + // Minimum execution time: 26_140_000 picoseconds. + Weight::from_parts(26_824_000, 0) .saturating_add(Weight::from_parts(0, 11205)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm_bridge_hub_router.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm_bridge_hub_router.rs index 775bc3bdb80..7e12453583d 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm_bridge_hub_router.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm_bridge_hub_router.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_bridge_hub_router` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-11-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: @@ -58,8 +58,8 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh // Proof Size summary in bytes: // Measured: `154` // Estimated: `1639` - // Minimum execution time: 7_853_000 picoseconds. - Weight::from_parts(8_443_000, 0) + // Minimum execution time: 7_924_000 picoseconds. + Weight::from_parts(8_199_000, 0) .saturating_add(Weight::from_parts(0, 1639)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(1)) @@ -72,8 +72,8 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh // Proof Size summary in bytes: // Measured: `144` // Estimated: `1629` - // Minimum execution time: 4_333_000 picoseconds. - Weight::from_parts(4_501_000, 0) + // Minimum execution time: 4_265_000 picoseconds. + Weight::from_parts(4_417_000, 0) .saturating_add(Weight::from_parts(0, 1629)) .saturating_add(T::DbWeight::get().reads(2)) } @@ -83,14 +83,12 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh // Proof Size summary in bytes: // Measured: `150` // Estimated: `1502` - // Minimum execution time: 10_167_000 picoseconds. - Weight::from_parts(10_667_000, 0) + // Minimum execution time: 10_292_000 picoseconds. + Weight::from_parts(10_797_000, 0) .saturating_add(Weight::from_parts(0, 1502)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } - /// Storage: `PolkadotXcm::SupportedVersion` (r:2 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: UNKNOWN KEY `0x3302afcb67e838a3f960251b417b9a4f` (r:1 w:0) @@ -101,6 +99,8 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh /// Proof: `ToWestendXcmRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::DeliveryFeeFactor` (r:1 w:0) /// Proof: `XcmpQueue::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) @@ -115,12 +115,12 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) fn send_message() -> Weight { // Proof Size summary in bytes: - // Measured: `448` - // Estimated: `6388` - // Minimum execution time: 60_584_000 picoseconds. - Weight::from_parts(62_467_000, 0) - .saturating_add(Weight::from_parts(0, 6388)) - .saturating_add(T::DbWeight::get().reads(12)) + // Measured: `387` + // Estimated: `3852` + // Minimum execution time: 61_995_000 picoseconds. + Weight::from_parts(65_137_000, 0) + .saturating_add(Weight::from_parts(0, 3852)) + .saturating_add(T::DbWeight::get().reads(11)) .saturating_add(T::DbWeight::get().writes(4)) } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs index 003b71093e0..4da0a2500a5 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs @@ -32,27 +32,27 @@ use pallet_xcm::XcmPassthrough; use parachains_common::{ impls::ToStakingPot, xcm_config::{ - AllSiblingSystemParachains, AssetFeeAsExistentialDepositMultiplier, - ConcreteAssetFromSystem, ParentRelayOrSiblingParachains, RelayOrOtherSystemParachains, + AssetFeeAsExistentialDepositMultiplier, ConcreteAssetFromSystem, + RelayOrOtherSystemParachains, }, TREASURY_PALLET_ID, }; use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; +use rococo_runtime_constants::system_parachain; use sp_runtime::traits::{AccountIdConversion, ConvertInto}; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, - AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, - DenyThenTry, DescribeAllTerminal, DescribeFamily, EnsureXcmOrigin, FungiblesAdapter, - GlobalConsensusParachainConvertsFor, HashedDescription, IsConcrete, LocalMint, - NetworkExportTableItem, NoChecking, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, StartsWith, StartsWithExplicitGlobalConsensus, - TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, - WithUniqueTopic, XcmFeeManagerFromComponents, XcmFeeToAccount, + AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, + DenyReserveTransferToRelayChain, DenyThenTry, DescribeAllTerminal, DescribeFamily, + EnsureXcmOrigin, FungiblesAdapter, GlobalConsensusParachainConvertsFor, HashedDescription, + IsConcrete, LocalMint, NetworkExportTableItem, NoChecking, ParentAsSuperuser, ParentIsPreset, + RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, StartsWith, + StartsWithExplicitGlobalConsensus, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, + WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, + XcmFeeToAccount, }; use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; @@ -96,7 +96,6 @@ pub type LocationToAccountId = ( ); /// Means for transacting the native currency on this chain. -#[allow(deprecated)] pub type CurrencyTransactor = CurrencyAdapter< // Use this currency: Balances, @@ -240,6 +239,10 @@ match_types! { MultiLocation { parents: 1, interior: Here } | MultiLocation { parents: 1, interior: X1(Plurality { .. }) } }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; } /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly @@ -484,7 +487,7 @@ pub type Barrier = TrailingSetTopicAsId< Equals, )>, // Subscriptions for version tracking are OK. - AllowSubscriptionsFrom, + AllowSubscriptionsFrom, ), UniversalLocation, ConstU32<8>, @@ -510,13 +513,25 @@ pub type ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger = ForeignAssetsInstance, >; +match_types! { + pub type SystemParachains: impl Contains = { + MultiLocation { + parents: 1, + interior: X1(Parachain( + system_parachain::ASSET_HUB_ID | + system_parachain::BRIDGE_HUB_ID | + system_parachain::CONTRACTS_ID | + system_parachain::ENCOINTER_ID + )), + } + }; +} + /// Locations that will not be charged fees in the executor, /// either execution or delivery. /// We only waive fees for system functions, which these locations represent. -pub type WaivedLocations = ( - RelayOrOtherSystemParachains, - Equals, -); +pub type WaivedLocations = + (RelayOrOtherSystemParachains, Equals); /// Cases where a remote origin is accepted as trusted Teleporter for a given asset: /// diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs index 030a3723319..7bb71a77de7 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs @@ -673,16 +673,9 @@ fn limited_reserve_transfer_assets_for_native_asset_over_bridge_works( mod asset_hub_rococo_tests { use super::*; - use asset_hub_rococo_runtime::{PolkadotXcm, RuntimeOrigin}; fn bridging_to_asset_hub_westend() -> TestBridgingConfig { - let _ = PolkadotXcm::force_xcm_version( - RuntimeOrigin::root(), - Box::new(bridging::to_westend::AssetHubWestend::get()), - XCM_VERSION, - ) - .expect("version saved!"); - TestBridgingConfig { + asset_test_utils::test_cases_over_bridge::TestBridgingConfig { bridged_network: bridging::to_westend::WestendNetwork::get(), local_bridge_hub_para_id: bridging::SiblingBridgeHubParaId::get(), local_bridge_hub_location: bridging::SiblingBridgeHub::get(), diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml index 1a1ed0465a3..49b80b067cf 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true description = "Westend variant of Asset Hub parachain runtime" license = "Apache-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } hex-literal = { version = "0.4.1", optional = true } @@ -17,62 +14,63 @@ scale-info = { version = "2.10.0", default-features = false, features = ["derive smallvec = "1.11.0" # 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-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-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 } +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-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-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 } +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} # 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 = { version = "0.12.1", default-features = false, features = ["codec", "scale-info", "num-traits"] } # Polkadot -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", 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-core-primitives = { path = "../../../../../polkadot/core-primitives", default-features = false } -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 } +polkadot-core-primitives = { path = "../../../../../polkadot/core-primitives", default-features = false} +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} # 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, features = ["parameterized-consensus-hook"] } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } +cumulus-pallet-dmp-queue = { path = "../../../../pallets/dmp-queue", default-features = false } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } +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-core = { path = "../../../../primitives/core", default-features = false } @@ -97,9 +95,10 @@ asset-test-utils = { path = "../test-utils" } substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ "assets-common/runtime-benchmarks", + "cumulus-pallet-dmp-queue/runtime-benchmarks", "cumulus-pallet-parachain-system/runtime-benchmarks", "cumulus-pallet-session-benchmarking/runtime-benchmarks", "cumulus-pallet-xcmp-queue/runtime-benchmarks", @@ -134,6 +133,7 @@ runtime-benchmarks = [ ] try-runtime = [ "cumulus-pallet-aura-ext/try-runtime", + "cumulus-pallet-dmp-queue/try-runtime", "cumulus-pallet-parachain-system/try-runtime", "cumulus-pallet-xcm/try-runtime", "cumulus-pallet-xcmp-queue/try-runtime", @@ -172,6 +172,7 @@ std = [ "bp-bridge-hub-westend/std", "codec/std", "cumulus-pallet-aura-ext/std", + "cumulus-pallet-dmp-queue/std", "cumulus-pallet-parachain-system/std", "cumulus-pallet-session-benchmarking/std", "cumulus-pallet-xcm/std", @@ -235,9 +236,9 @@ std = [ "xcm/std", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] # A feature that should be enabled when the runtime should be built for on-chain # deployment. This will disable stuff that shouldn't be part of the on-chain wasm # to make it smaller like logging for example. -on-chain-release-build = ["sp-api/disable-logging"] +on-chain-release-build = [ "sp-api/disable-logging" ] 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 93a8ee55927..d4ce5ebfb6a 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -38,7 +38,7 @@ use codec::{Decode, Encode, MaxEncodedLen}; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, ord_parameter_types, parameter_types, @@ -69,7 +69,9 @@ use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, - traits::{AccountIdConversion, BlakeTwo256, Block as BlockT, Saturating, Verify}, + traits::{ + AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Saturating, Verify, + }, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, Perbill, Permill, RuntimeDebug, }; @@ -109,10 +111,10 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("westmint"), impl_name: create_runtime_str!("westmint"), authoring_version: 1, - spec_version: 1_005_000, + spec_version: 1_003_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, - transaction_version: 14, + transaction_version: 13, state_version: 0, }; @@ -148,17 +150,25 @@ parameter_types! { } // Configure FRAME pallets to include in runtime. -#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = RuntimeBlockWeights; type BlockLength = RuntimeBlockLength; type AccountId = AccountId; + type RuntimeCall = RuntimeCall; + type Lookup = AccountIdLookup; type Nonce = Nonce; type Hash = Hash; + type Hashing = BlakeTwo256; type Block = Block; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; type BlockHashCount = BlockHashCount; type DbWeight = RocksDbWeight; type Version = Version; + type PalletInfo = PalletInfo; + type OnNewAccount = (); + type OnKilledAccount = (); type AccountData = pallet_balances::AccountData; type SystemWeightInfo = weights::frame_system::WeightInfo; type SS58Prefix = SS58Prefix; @@ -657,6 +667,12 @@ parameter_types! { pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent; } +impl cumulus_pallet_dmp_queue::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_dmp_queue::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type DmpSink = frame_support::traits::EnqueueWithOrigin; +} + parameter_types! { pub const Period: u32 = 6 * HOURS; pub const Offset: u32 = 0; @@ -822,7 +838,6 @@ impl pallet_xcm_bridge_hub_router::Config for Runtime type UniversalLocation = xcm_config::UniversalLocation; type BridgedNetworkId = xcm_config::bridging::to_rococo::RococoNetwork; type Bridges = xcm_config::bridging::NetworkExportTable; - type DestinationVersion = PolkadotXcm; #[cfg(not(feature = "runtime-benchmarks"))] type BridgeHubOrigin = EnsureXcm>; @@ -875,6 +890,7 @@ construct_runtime!( XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 31, CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, + DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, // Bridge utilities. ToRococoXcmRouter: pallet_xcm_bridge_hub_router::::{Pallet, Storage, Call} = 34, MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event} = 35, @@ -932,8 +948,6 @@ pub type Migrations = ( InitStorageVersions, // unreleased DeleteUndecodableStorage, - // unreleased - cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4, ); /// Asset Hub Westend has some undecodable storage, delete it. @@ -1068,6 +1082,7 @@ mod benches { [pallet_timestamp, Timestamp] [pallet_collator_selection, CollatorSelection] [cumulus_pallet_xcmp_queue, XcmpQueue] + [cumulus_pallet_dmp_queue, DmpQueue] [pallet_xcm_bridge_hub_router, ToRococo] // XCM [pallet_xcm, PalletXcmExtrinsicsBenchmark::] @@ -1432,55 +1447,6 @@ impl_runtime_apis! { ParentThen(Parachain(random_para_id).into()).into(), )) } - - fn set_up_complex_asset_transfer( - ) -> Option<(MultiAssets, u32, MultiLocation, Box)> { - // Transfer to Relay some local AH asset (local-reserve-transfer) while paying - // fees using teleported native token. - // (We don't care that Relay doesn't accept incoming unknown AH local asset) - let dest = Parent.into(); - - let fee_amount = EXISTENTIAL_DEPOSIT; - let fee_asset: MultiAsset = (MultiLocation::parent(), fee_amount).into(); - - let who = frame_benchmarking::whitelisted_caller(); - // Give some multiple of the existential deposit - let balance = fee_amount + EXISTENTIAL_DEPOSIT * 1000; - let _ = >::make_free_balance_be( - &who, balance, - ); - // verify initial balance - assert_eq!(Balances::free_balance(&who), balance); - - // set up local asset - let asset_amount = 10u128; - let initial_asset_amount = asset_amount * 10; - let (asset_id, _, _) = pallet_assets::benchmarking::create_default_minted_asset::< - Runtime, - pallet_assets::Instance1 - >(true, initial_asset_amount); - let asset_location = MultiLocation::new( - 0, - X2(PalletInstance(50), GeneralIndex(u32::from(asset_id).into())) - ); - let transfer_asset: MultiAsset = (asset_location, asset_amount).into(); - - let assets: MultiAssets = vec![fee_asset.clone(), transfer_asset].into(); - let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 }; - - // verify transferred successfully - let verify = Box::new(move || { - // verify native balance after transfer, decreased by transferred fee amount - // (plus transport fees) - assert!(Balances::free_balance(&who) <= balance - fee_amount); - // verify asset balance decreased by exactly transferred amount - assert_eq!( - Assets::balance(asset_id.into(), &who), - initial_asset_amount - asset_amount, - ); - }); - Some((assets, fee_index as u32, dest, verify)) - } } use pallet_xcm_bridge_hub_router::benchmarking::{ @@ -1494,26 +1460,11 @@ impl_runtime_apis! { xcm_config::bridging::SiblingBridgeHubParaId::get().into() ); } - fn ensure_bridged_target_destination() -> Result { + fn ensure_bridged_target_destination() -> MultiLocation { ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( xcm_config::bridging::SiblingBridgeHubParaId::get().into() ); - let bridged_asset_hub = xcm_config::bridging::to_rococo::AssetHubRococo::get(); - let _ = PolkadotXcm::force_xcm_version( - RuntimeOrigin::root(), - Box::new(bridged_asset_hub), - XCM_VERSION, - ).map_err(|e| { - log::error!( - "Failed to dispatch `force_xcm_version({:?}, {:?}, {:?})`, error: {:?}", - RuntimeOrigin::root(), - bridged_asset_hub, - XCM_VERSION, - e - ); - BenchmarkError::Stop("XcmVersion was not stored!") - })?; - Ok(bridged_asset_hub) + xcm_config::bridging::to_rococo::AssetHubRococo::get() } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/cumulus_pallet_dmp_queue.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/cumulus_pallet_dmp_queue.rs new file mode 100644 index 00000000000..cc41dcd6cbb --- /dev/null +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/cumulus_pallet_dmp_queue.rs @@ -0,0 +1,131 @@ +// 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 . + +//! Autogenerated weights for `cumulus_pallet_dmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-10-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=cumulus_pallet_dmp_queue +// --chain=asset-hub-kusama-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_dmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_dmp_queue::WeightInfo for WeightInfo { + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65696` + // Estimated: `69161` + // Minimum execution time: 124_651_000 picoseconds. + Weight::from_parts(127_857_000, 0) + .saturating_add(Weight::from_parts(0, 69161)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65659` + // Estimated: `69124` + // Minimum execution time: 65_684_000 picoseconds. + Weight::from_parts(68_039_000, 0) + .saturating_add(Weight::from_parts(0, 69124)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_overweight_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65726` + // Estimated: `69191` + // Minimum execution time: 117_657_000 picoseconds. + Weight::from_parts(122_035_000, 0) + .saturating_add(Weight::from_parts(0, 69191)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + fn on_idle_overweight_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65689` + // Estimated: `69154` + // Minimum execution time: 59_799_000 picoseconds. + Weight::from_parts(61_354_000, 0) + .saturating_add(Weight::from_parts(0, 69154)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } +} diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/mod.rs index 2462138b04a..1646c00989d 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/mod.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/mod.rs @@ -14,6 +14,7 @@ // limitations under the License. pub mod block_weights; +pub mod cumulus_pallet_dmp_queue; pub mod cumulus_pallet_parachain_system; pub mod cumulus_pallet_xcmp_queue; pub mod extrinsic_weights; diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm.rs index 504731f4a9e..340edafb0b0 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-05, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-11-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-r43aesjn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-westend-dev")`, DB CACHE: 1024 // Executed Command: @@ -64,102 +64,40 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 25_482_000 picoseconds. - Weight::from_parts(26_622_000, 0) + // Minimum execution time: 25_534_000 picoseconds. + Weight::from_parts(26_413_000, 0) .saturating_add(Weight::from_parts(0, 3610)) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) - /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) - /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn teleport_assets() -> Weight { // Proof Size summary in bytes: - // Measured: `145` - // Estimated: `3610` - // Minimum execution time: 87_319_000 picoseconds. - Weight::from_parts(89_764_000, 0) - .saturating_add(Weight::from_parts(0, 3610)) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(3)) + // Measured: `0` + // Estimated: `1489` + // Minimum execution time: 20_513_000 picoseconds. + Weight::from_parts(20_837_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + .saturating_add(T::DbWeight::get().reads(1)) } /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `XcmpQueue::DeliveryFeeFactor` (r:1 w:0) - /// Proof: `XcmpQueue::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::RelevantMessagingState` (r:1 w:0) - /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) - /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) - /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) fn reserve_transfer_assets() -> Weight { // Proof Size summary in bytes: - // Measured: `367` - // Estimated: `6196` - // Minimum execution time: 139_133_000 picoseconds. - Weight::from_parts(141_507_000, 0) - .saturating_add(Weight::from_parts(0, 6196)) - .saturating_add(T::DbWeight::get().reads(9)) - .saturating_add(T::DbWeight::get().writes(5)) - } - /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) - /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Assets::Asset` (r:1 w:1) - /// Proof: `Assets::Asset` (`max_values`: None, `max_size`: Some(210), added: 2685, mode: `MaxEncodedLen`) - /// Storage: `Assets::Account` (r:2 w:2) - /// Proof: `Assets::Account` (`max_values`: None, `max_size`: Some(134), added: 2609, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) - /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) - /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - fn transfer_assets() -> Weight { - // Proof Size summary in bytes: - // Measured: `496` - // Estimated: `6208` - // Minimum execution time: 144_241_000 picoseconds. - Weight::from_parts(149_709_000, 0) - .saturating_add(Weight::from_parts(0, 6208)) - .saturating_add(T::DbWeight::get().reads(12)) - .saturating_add(T::DbWeight::get().writes(7)) + // Measured: `0` + // Estimated: `1489` + // Minimum execution time: 14_977_000 picoseconds. + Weight::from_parts(15_207_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + .saturating_add(T::DbWeight::get().reads(1)) } fn execute() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 10_392_000 picoseconds. - Weight::from_parts(10_779_000, 0) + // Minimum execution time: 7_440_000 picoseconds. + Weight::from_parts(7_651_000, 0) .saturating_add(Weight::from_parts(0, 0)) } /// Storage: `PolkadotXcm::SupportedVersion` (r:0 w:1) @@ -168,8 +106,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_088_000 picoseconds. - Weight::from_parts(7_257_000, 0) + // Minimum execution time: 7_253_000 picoseconds. + Weight::from_parts(7_584_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -179,8 +117,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_095_000 picoseconds. - Weight::from_parts(2_136_000, 0) + // Minimum execution time: 2_299_000 picoseconds. + Weight::from_parts(2_435_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -206,8 +144,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 28_728_000 picoseconds. - Weight::from_parts(29_349_000, 0) + // Minimum execution time: 29_440_000 picoseconds. + Weight::from_parts(30_675_000, 0) .saturating_add(Weight::from_parts(0, 3610)) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(5)) @@ -232,8 +170,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `363` // Estimated: `3828` - // Minimum execution time: 30_605_000 picoseconds. - Weight::from_parts(31_477_000, 0) + // Minimum execution time: 31_876_000 picoseconds. + Weight::from_parts(32_588_000, 0) .saturating_add(Weight::from_parts(0, 3828)) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(4)) @@ -244,8 +182,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_137_000 picoseconds. - Weight::from_parts(2_303_000, 0) + // Minimum execution time: 2_385_000 picoseconds. + Weight::from_parts(2_607_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -255,8 +193,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `162` // Estimated: `11052` - // Minimum execution time: 16_719_000 picoseconds. - Weight::from_parts(17_329_000, 0) + // Minimum execution time: 16_927_000 picoseconds. + Weight::from_parts(17_554_000, 0) .saturating_add(Weight::from_parts(0, 11052)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -267,8 +205,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `166` // Estimated: `11056` - // Minimum execution time: 16_687_000 picoseconds. - Weight::from_parts(17_405_000, 0) + // Minimum execution time: 16_965_000 picoseconds. + Weight::from_parts(17_807_000, 0) .saturating_add(Weight::from_parts(0, 11056)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -279,8 +217,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `173` // Estimated: `13538` - // Minimum execution time: 18_751_000 picoseconds. - Weight::from_parts(19_130_000, 0) + // Minimum execution time: 18_763_000 picoseconds. + Weight::from_parts(19_359_000, 0) .saturating_add(Weight::from_parts(0, 13538)) .saturating_add(T::DbWeight::get().reads(5)) } @@ -302,8 +240,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `212` // Estimated: `6152` - // Minimum execution time: 27_189_000 picoseconds. - Weight::from_parts(27_760_000, 0) + // Minimum execution time: 27_371_000 picoseconds. + Weight::from_parts(28_185_000, 0) .saturating_add(Weight::from_parts(0, 6152)) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(3)) @@ -314,8 +252,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `206` // Estimated: `8621` - // Minimum execution time: 9_307_000 picoseconds. - Weight::from_parts(9_691_000, 0) + // Minimum execution time: 9_165_000 picoseconds. + Weight::from_parts(9_539_000, 0) .saturating_add(Weight::from_parts(0, 8621)) .saturating_add(T::DbWeight::get().reads(3)) } @@ -325,8 +263,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `173` // Estimated: `11063` - // Minimum execution time: 17_607_000 picoseconds. - Weight::from_parts(18_090_000, 0) + // Minimum execution time: 17_384_000 picoseconds. + Weight::from_parts(17_777_000, 0) .saturating_add(Weight::from_parts(0, 11063)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -349,8 +287,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `215` // Estimated: `11105` - // Minimum execution time: 34_322_000 picoseconds. - Weight::from_parts(35_754_000, 0) + // Minimum execution time: 34_260_000 picoseconds. + Weight::from_parts(35_428_000, 0) .saturating_add(Weight::from_parts(0, 11105)) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) @@ -363,8 +301,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `103` // Estimated: `1588` - // Minimum execution time: 4_513_000 picoseconds. - Weight::from_parts(4_754_000, 0) + // Minimum execution time: 4_710_000 picoseconds. + Weight::from_parts(4_900_000, 0) .saturating_add(Weight::from_parts(0, 1588)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(2)) @@ -375,8 +313,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `7740` // Estimated: `11205` - // Minimum execution time: 27_860_000 picoseconds. - Weight::from_parts(28_279_000, 0) + // Minimum execution time: 26_843_000 picoseconds. + Weight::from_parts(27_404_000, 0) .saturating_add(Weight::from_parts(0, 11205)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm_bridge_hub_router.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm_bridge_hub_router.rs index 84d717b0283..9d0d0cbc655 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm_bridge_hub_router.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm_bridge_hub_router.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_bridge_hub_router` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-10-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-vmdtonbz-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-westend-dev")`, DB CACHE: 1024 // Executed Command: @@ -48,8 +48,8 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm_bridge_hub_router`. pub struct WeightInfo(PhantomData); impl pallet_xcm_bridge_hub_router::WeightInfo for WeightInfo { - /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) - /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::InboundXcmpStatus` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `ToRococoXcmRouter::Bridge` (r:1 w:1) @@ -58,22 +58,22 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh // Proof Size summary in bytes: // Measured: `193` // Estimated: `1678` - // Minimum execution time: 8_095_000 picoseconds. - Weight::from_parts(8_393_000, 0) + // Minimum execution time: 8_157_000 picoseconds. + Weight::from_parts(8_481_000, 0) .saturating_add(Weight::from_parts(0, 1678)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(1)) } - /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) - /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::InboundXcmpStatus` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn on_initialize_when_congested() -> Weight { // Proof Size summary in bytes: // Measured: `111` // Estimated: `1596` - // Minimum execution time: 3_417_000 picoseconds. - Weight::from_parts(3_583_000, 0) + // Minimum execution time: 3_319_000 picoseconds. + Weight::from_parts(3_445_000, 0) .saturating_add(Weight::from_parts(0, 1596)) .saturating_add(T::DbWeight::get().reads(2)) } @@ -83,24 +83,22 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh // Proof Size summary in bytes: // Measured: `117` // Estimated: `1502` - // Minimum execution time: 10_280_000 picoseconds. - Weight::from_parts(10_703_000, 0) + // Minimum execution time: 10_396_000 picoseconds. + Weight::from_parts(10_914_000, 0) .saturating_add(Weight::from_parts(0, 1502)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } - /// Storage: `PolkadotXcm::SupportedVersion` (r:2 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: UNKNOWN KEY `0x3302afcb67e838a3f960251b417b9a4f` (r:1 w:0) - /// Proof: UNKNOWN KEY `0x3302afcb67e838a3f960251b417b9a4f` (r:1 w:0) /// Storage: UNKNOWN KEY `0x0973fe64c85043ba1c965cbc38eb63c7` (r:1 w:0) /// Proof: UNKNOWN KEY `0x0973fe64c85043ba1c965cbc38eb63c7` (r:1 w:0) /// Storage: `ToRococoXcmRouter::Bridge` (r:1 w:1) /// Proof: `ToRococoXcmRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::DeliveryFeeFactor` (r:1 w:0) /// Proof: `XcmpQueue::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) @@ -109,18 +107,18 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) - /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::InboundXcmpStatus` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) fn send_message() -> Weight { // Proof Size summary in bytes: - // Measured: `487` - // Estimated: `6427` - // Minimum execution time: 63_624_000 picoseconds. - Weight::from_parts(66_071_000, 0) - .saturating_add(Weight::from_parts(0, 6427)) - .saturating_add(T::DbWeight::get().reads(12)) + // Measured: `426` + // Estimated: `3891` + // Minimum execution time: 45_902_000 picoseconds. + Weight::from_parts(46_887_000, 0) + .saturating_add(Weight::from_parts(0, 3891)) + .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) } } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs index 4bcc2bad5f6..4760e087e24 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs @@ -32,27 +32,27 @@ use pallet_xcm::XcmPassthrough; use parachains_common::{ impls::ToStakingPot, xcm_config::{ - AllSiblingSystemParachains, AssetFeeAsExistentialDepositMultiplier, - ConcreteAssetFromSystem, RelayOrOtherSystemParachains, + AssetFeeAsExistentialDepositMultiplier, ConcreteAssetFromSystem, + RelayOrOtherSystemParachains, }, TREASURY_PALLET_ID, }; use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; use sp_runtime::traits::{AccountIdConversion, ConvertInto}; +use westend_runtime_constants::system_parachain; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, - AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, - DenyThenTry, DescribeFamily, DescribePalletTerminal, EnsureXcmOrigin, FungiblesAdapter, - GlobalConsensusParachainConvertsFor, HashedDescription, IsConcrete, LocalMint, - NetworkExportTableItem, NoChecking, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, StartsWith, StartsWithExplicitGlobalConsensus, - TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, - WithUniqueTopic, XcmFeeManagerFromComponents, XcmFeeToAccount, + AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, + DenyReserveTransferToRelayChain, DenyThenTry, DescribeFamily, DescribePalletTerminal, + EnsureXcmOrigin, FungiblesAdapter, GlobalConsensusParachainConvertsFor, HashedDescription, + IsConcrete, LocalMint, NetworkExportTableItem, NoChecking, ParentAsSuperuser, ParentIsPreset, + RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, StartsWith, + StartsWithExplicitGlobalConsensus, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, + WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, + XcmFeeToAccount, }; use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; @@ -96,7 +96,6 @@ pub type LocationToAccountId = ( ); /// Means for transacting the native currency on this chain. -#[allow(deprecated)] pub type CurrencyTransactor = CurrencyAdapter< // Use this currency: Balances, @@ -241,18 +240,6 @@ match_types! { MultiLocation { parents: 1, interior: Here } | MultiLocation { parents: 1, interior: X1(Plurality { .. }) } }; - pub type FellowshipEntities: impl Contains = { - // Fellowship Plurality - MultiLocation { parents: 1, interior: X2(Parachain(1001), Plurality { id: BodyId::Technical, ..}) } | - // Fellowship Salary Pallet - MultiLocation { parents: 1, interior: X2(Parachain(1001), PalletInstance(64)) } | - // Fellowship Treasury Pallet - MultiLocation { parents: 1, interior: X2(Parachain(1001), PalletInstance(65)) } - }; - pub type AmbassadorEntities: impl Contains = { - // Ambassador Salary Pallet - MultiLocation { parents: 1, interior: X2(Parachain(1001), PalletInstance(74)) } - }; } /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly @@ -501,8 +488,6 @@ pub type Barrier = TrailingSetTopicAsId< ParentOrParentsPlurality, Equals, Equals, - FellowshipEntities, - AmbassadorEntities, )>, // Subscriptions for version tracking are OK. AllowSubscriptionsFrom, @@ -535,15 +520,24 @@ pub type ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger = ForeignAssetsInstance, >; +match_types! { + pub type SystemParachains: impl Contains = { + MultiLocation { + parents: 1, + interior: X1(Parachain( + system_parachain::ASSET_HUB_ID | + system_parachain::COLLECTIVES_ID | + system_parachain::BRIDGE_HUB_ID + )), + } + }; +} + /// Locations that will not be charged fees in the executor, /// either execution or delivery. /// We only waive fees for system functions, which these locations represent. -pub type WaivedLocations = ( - RelayOrOtherSystemParachains, - Equals, - FellowshipEntities, - AmbassadorEntities, -); +pub type WaivedLocations = + (RelayOrOtherSystemParachains, Equals); /// Cases where a remote origin is accepted as trusted Teleporter for a given asset: /// diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs index 0aaf1d91879..7922b04e807 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs @@ -24,9 +24,9 @@ use asset_hub_westend_runtime::{ WestendLocation, XcmConfig, }, AllPalletsWithoutSystem, AssetDeposit, Assets, Balances, ExistentialDeposit, ForeignAssets, - ForeignAssetsInstance, MetadataDepositBase, MetadataDepositPerByte, ParachainSystem, - PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, SessionKeys, - ToRococoXcmRouterInstance, TrustBackedAssetsInstance, XcmpQueue, + ForeignAssetsInstance, MetadataDepositBase, MetadataDepositPerByte, ParachainSystem, Runtime, + RuntimeCall, RuntimeEvent, SessionKeys, ToRococoXcmRouterInstance, TrustBackedAssetsInstance, + XcmpQueue, }; use asset_test_utils::{ test_cases_over_bridge::TestBridgingConfig, CollatorSessionKey, CollatorSessionKeys, ExtBuilder, @@ -635,12 +635,6 @@ asset_test_utils::include_create_and_manage_foreign_assets_for_local_consensus_p ); fn bridging_to_asset_hub_rococo() -> TestBridgingConfig { - let _ = PolkadotXcm::force_xcm_version( - RuntimeOrigin::root(), - Box::new(bridging::to_rococo::AssetHubRococo::get()), - XCM_VERSION, - ) - .expect("version saved!"); TestBridgingConfig { bridged_network: bridging::to_rococo::RococoNetwork::get(), local_bridge_hub_para_id: bridging::SiblingBridgeHubParaId::get(), diff --git a/cumulus/parachains/runtimes/assets/common/Cargo.toml b/cumulus/parachains/runtimes/assets/common/Cargo.toml index 22729df5ed5..49fc2a0fa5e 100644 --- a/cumulus/parachains/runtimes/assets/common/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/common/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true description = "Assets common utilities" license = "Apache-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } @@ -16,18 +13,18 @@ log = { version = "0.4.20", default-features = false } impl-trait-for-tuples = "0.2.2" # 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 } +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 } pallet-asset-tx-payment = { path = "../../../../../substrate/frame/transaction-payment/asset-tx-payment", default-features = false } # 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 = { 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} # Cumulus parachains-common = { path = "../../../common", default-features = false } @@ -37,7 +34,7 @@ cumulus-primitives-core = { path = "../../../../primitives/core", default-featur substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-primitives-core/std", diff --git a/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml b/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml index a3ed3759600..1dc7cecbb62 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml @@ -6,26 +6,23 @@ edition.workspace = true description = "Test utils for Asset Hub runtimes." license = "Apache-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } # 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-session = { path = "../../../../../substrate/frame/session", 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-core = { path = "../../../../../substrate/primitives/core", default-features = false } +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-session = { path = "../../../../../substrate/frame/session", 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-core = { path = "../../../../../substrate/primitives/core", default-features = false} # Cumulus -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } 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 } @@ -53,7 +50,7 @@ hex-literal = "0.4.1" substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder" } [features] -default = ["std"] +default = [ "std" ] std = [ "assets-common/std", "codec/std", diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/Cargo.toml b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/Cargo.toml new file mode 100644 index 00000000000..2cd002b1c60 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/Cargo.toml @@ -0,0 +1,192 @@ +[package] +name = "bridge-hub-kusama-runtime" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +description = "Kusama's BridgeHub parachain runtime" +license = "Apache-2.0" + +[build-dependencies] +substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +hex-literal = { version = "0.4.1" } +log = { version = "0.4.20", default-features = false } +scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } +serde = { version = "1.0.188", optional = true, features = ["derive"] } +smallvec = "1.11.0" + +# 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-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-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} + +# 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-core-primitives = { path = "../../../../../polkadot/core-primitives", 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} + +# 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-dmp-queue = { path = "../../../../pallets/dmp-queue", default-features = false } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } +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 } + +[dev-dependencies] +bridge-hub-test-utils = { path = "../test-utils" } + +[features] +default = [ "std" ] +std = [ + "codec/std", + "cumulus-pallet-aura-ext/std", + "cumulus-pallet-dmp-queue/std", + "cumulus-pallet-parachain-system/std", + "cumulus-pallet-session-benchmarking/std", + "cumulus-pallet-xcm/std", + "cumulus-pallet-xcmp-queue/std", + "cumulus-primitives-core/std", + "cumulus-primitives-utility/std", + "frame-benchmarking?/std", + "frame-executive/std", + "frame-support/std", + "frame-system-benchmarking?/std", + "frame-system-rpc-runtime-api/std", + "frame-system/std", + "frame-try-runtime?/std", + "log/std", + "pallet-aura/std", + "pallet-authorship/std", + "pallet-balances/std", + "pallet-collator-selection/std", + "pallet-message-queue/std", + "pallet-multisig/std", + "pallet-session/std", + "pallet-timestamp/std", + "pallet-transaction-payment-rpc-runtime-api/std", + "pallet-transaction-payment/std", + "pallet-utility/std", + "pallet-xcm-benchmarks?/std", + "pallet-xcm/std", + "parachain-info/std", + "parachains-common/std", + "polkadot-core-primitives/std", + "polkadot-parachain-primitives/std", + "polkadot-runtime-common/std", + "scale-info/std", + "serde", + "sp-api/std", + "sp-block-builder/std", + "sp-consensus-aura/std", + "sp-core/std", + "sp-genesis-builder/std", + "sp-inherents/std", + "sp-io/std", + "sp-offchain/std", + "sp-runtime/std", + "sp-session/std", + "sp-std/std", + "sp-storage/std", + "sp-transaction-pool/std", + "sp-version/std", + "substrate-wasm-builder", + "xcm-builder/std", + "xcm-executor/std", + "xcm/std", +] + +runtime-benchmarks = [ + "cumulus-pallet-dmp-queue/runtime-benchmarks", + "cumulus-pallet-parachain-system/runtime-benchmarks", + "cumulus-pallet-session-benchmarking/runtime-benchmarks", + "cumulus-pallet-xcmp-queue/runtime-benchmarks", + "cumulus-primitives-core/runtime-benchmarks", + "cumulus-primitives-utility/runtime-benchmarks", + "frame-benchmarking/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "frame-system-benchmarking/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", + "pallet-collator-selection/runtime-benchmarks", + "pallet-message-queue/runtime-benchmarks", + "pallet-multisig/runtime-benchmarks", + "pallet-timestamp/runtime-benchmarks", + "pallet-utility/runtime-benchmarks", + "pallet-xcm-benchmarks/runtime-benchmarks", + "pallet-xcm/runtime-benchmarks", + "parachains-common/runtime-benchmarks", + "polkadot-parachain-primitives/runtime-benchmarks", + "polkadot-runtime-common/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", + "xcm-executor/runtime-benchmarks", +] + +try-runtime = [ + "cumulus-pallet-aura-ext/try-runtime", + "cumulus-pallet-dmp-queue/try-runtime", + "cumulus-pallet-parachain-system/try-runtime", + "cumulus-pallet-xcm/try-runtime", + "cumulus-pallet-xcmp-queue/try-runtime", + "frame-executive/try-runtime", + "frame-support/try-runtime", + "frame-system/try-runtime", + "frame-try-runtime/try-runtime", + "pallet-aura/try-runtime", + "pallet-authorship/try-runtime", + "pallet-balances/try-runtime", + "pallet-collator-selection/try-runtime", + "pallet-message-queue/try-runtime", + "pallet-multisig/try-runtime", + "pallet-session/try-runtime", + "pallet-timestamp/try-runtime", + "pallet-transaction-payment/try-runtime", + "pallet-utility/try-runtime", + "pallet-xcm/try-runtime", + "parachain-info/try-runtime", + "polkadot-runtime-common/try-runtime", + "sp-runtime/try-runtime", +] + +experimental = [ "pallet-aura/experimental" ] diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/build.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/build.rs new file mode 100644 index 00000000000..60f8a125129 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/build.rs @@ -0,0 +1,26 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#[cfg(feature = "std")] +fn main() { + substrate_wasm_builder::WasmBuilder::new() + .with_current_project() + .export_heap_base() + .import_memory() + .build() +} + +#[cfg(not(feature = "std"))] +fn main() {} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/lib.rs new file mode 100644 index 00000000000..bdf405be125 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/lib.rs @@ -0,0 +1,872 @@ +// 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 . + +#![cfg_attr(not(feature = "std"), no_std)] +// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. +#![recursion_limit = "256"] + +// Make the WASM binary available. +#[cfg(feature = "std")] +include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); + +mod weights; +pub mod xcm_config; + +use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; +use sp_api::impl_runtime_apis; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; +use sp_runtime::{ + create_runtime_str, generic, impl_opaque_keys, + traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, +}; + +use sp_std::prelude::*; +#[cfg(feature = "std")] +use sp_version::NativeVersion; +use sp_version::RuntimeVersion; + +use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; +use frame_support::{ + construct_runtime, + dispatch::DispatchClass, + genesis_builder_helper::{build_config, create_default_config}, + parameter_types, + traits::{ + ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, Everything, TransformOrigin, + }, + weights::{ConstantMultiplier, Weight}, + PalletId, +}; +use frame_system::{ + limits::{BlockLength, BlockWeights}, + EnsureRoot, +}; +use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; +pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; +pub use sp_runtime::{MultiAddress, Perbill, Permill}; +use xcm_config::{FellowshipLocation, GovernanceLocation, XcmOriginToTransactDispatchOrigin}; + +#[cfg(any(feature = "std", test))] +pub use sp_runtime::BuildStorage; + +use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; + +use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; + +use parachains_common::{ + impls::DealWithFees, + kusama::{consensus::*, currency::*, fee::WeightToFee}, + message_queue::{NarrowOriginToSibling, ParaIdToSibling}, + AccountId, Balance, BlockNumber, Hash, Header, Nonce, Signature, AVERAGE_ON_INITIALIZE_RATIO, + HOURS, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO, SLOT_DURATION, +}; + +// XCM Imports +use xcm::latest::prelude::BodyId; + +/// The address format for describing accounts. +pub type Address = MultiAddress; + +/// Block type as expected by this runtime. +pub type Block = generic::Block; + +/// A Block signed with a Justification +pub type SignedBlock = generic::SignedBlock; + +/// BlockId type as expected by this runtime. +pub type BlockId = generic::BlockId; + +/// The extension to the basic transaction logic. +pub type TxExtension = ( + frame_system::CheckNonZeroSender, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_transaction_payment::ChargeTransactionPayment, +); + +/// Unchecked extrinsic type as expected by this runtime. +pub type UncheckedExtrinsic = + generic::UncheckedExtrinsic; + +/// Migrations to apply on runtime upgrade. +pub type Migrations = ( + // unreleased + pallet_collator_selection::migration::v1::MigrateToV1, +); + +/// Executive: handles dispatch to the various modules. +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + Migrations, +>; + +impl_opaque_keys! { + pub struct SessionKeys { + pub aura: Aura, + } +} + +#[sp_version::runtime_version] +pub const VERSION: RuntimeVersion = RuntimeVersion { + spec_name: create_runtime_str!("bridge-hub-kusama"), + impl_name: create_runtime_str!("bridge-hub-kusama"), + authoring_version: 1, + spec_version: 10000, + impl_version: 0, + apis: RUNTIME_API_VERSIONS, + transaction_version: 3, + state_version: 1, +}; + +/// The version information used to identify this runtime when compiled natively. +#[cfg(feature = "std")] +pub fn native_version() -> NativeVersion { + NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } +} + +parameter_types! { + pub const Version: RuntimeVersion = VERSION; + pub RuntimeBlockLength: BlockLength = + BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() + .base_block(BlockExecutionWeight::get()) + .for_class(DispatchClass::all(), |weights| { + weights.base_extrinsic = ExtrinsicBaseWeight::get(); + }) + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Operational transactions have some extra reserved space, so that they + // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); + pub const SS58Prefix: u8 = 2; +} + +// Configure FRAME pallets to include in runtime. + +impl frame_system::Config for Runtime { + /// The identifier used to distinguish between accounts. + type AccountId = AccountId; + /// The aggregated dispatch type that is available for extrinsics. + type RuntimeCall = RuntimeCall; + /// The lookup mechanism to get account ID from whatever is passed in dispatchers. + type Lookup = AccountIdLookup; + /// The index type for storing how many extrinsics an account has signed. + type Nonce = Nonce; + /// The type for hashing blocks and tries. + type Hash = Hash; + /// The hashing algorithm used. + type Hashing = BlakeTwo256; + /// The block type. + type Block = Block; + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + /// The ubiquitous origin type. + type RuntimeOrigin = RuntimeOrigin; + /// Maximum number of block number to block hash mappings to keep (oldest pruned first). + type BlockHashCount = BlockHashCount; + /// Runtime version. + type Version = Version; + /// Converts a module to an index of this module in the runtime. + type PalletInfo = PalletInfo; + /// The data to be stored in an account. + type AccountData = pallet_balances::AccountData; + /// What to do if a new account is created. + type OnNewAccount = (); + /// What to do if an account is fully reaped from the system. + type OnKilledAccount = (); + /// The weight of database operations that the runtime can invoke. + type DbWeight = RocksDbWeight; + /// The basic call filter to use in dispatchable. + type BaseCallFilter = Everything; + /// Weight information for the extrinsics of this pallet. + type SystemWeightInfo = weights::frame_system::WeightInfo; + /// Block & extrinsics weights: base values and limits. + type BlockWeights = RuntimeBlockWeights; + /// The maximum length of a block (in bytes). + type BlockLength = RuntimeBlockLength; + type SS58Prefix = SS58Prefix; + /// The action to take on a Runtime Upgrade + type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; + type MaxConsumers = ConstU32<16>; +} + +impl pallet_timestamp::Config for Runtime { + /// A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = Aura; + type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>; + type WeightInfo = weights::pallet_timestamp::WeightInfo; +} + +impl pallet_authorship::Config for Runtime { + type FindAuthor = pallet_session::FindAccountFromAuthorIndex; + type EventHandler = (CollatorSelection,); +} + +parameter_types! { + pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT; +} + +impl pallet_balances::Config for Runtime { + /// The type for recording an account's balance. + type Balance = Balance; + type DustRemoval = (); + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = weights::pallet_balances::WeightInfo; + type MaxLocks = ConstU32<50>; + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; + type FreezeIdentifier = (); + type MaxHolds = ConstU32<0>; + type MaxFreezes = ConstU32<0>; +} + +parameter_types! { + /// Relay Chain `TransactionByteFee` / 10 + pub const TransactionByteFee: Balance = MILLICENTS; +} + +impl pallet_transaction_payment::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type OnChargeTransaction = + pallet_transaction_payment::CurrencyAdapter>; + type OperationalFeeMultiplier = ConstU8<5>; + type WeightToFee = WeightToFee; + type LengthToFee = ConstantMultiplier; + type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; +} + +parameter_types! { + pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); + pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); +} + +impl cumulus_pallet_parachain_system::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type OnSystemEvent = (); + type SelfParaId = parachain_info::Pallet; + type OutboundXcmpMessageSource = XcmpQueue; + type DmpQueue = frame_support::traits::EnqueueWithOrigin; + type ReservedDmpWeight = ReservedDmpWeight; + type XcmpMessageHandler = XcmpQueue; + type ReservedXcmpWeight = ReservedXcmpWeight; + type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases; + type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook< + Runtime, + RELAY_CHAIN_SLOT_DURATION_MILLIS, + BLOCK_PROCESSING_VELOCITY, + UNINCLUDED_SEGMENT_CAPACITY, + >; +} + +impl parachain_info::Config for Runtime {} + +parameter_types! { + pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block; +} + +impl pallet_message_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type WeightInfo = weights::pallet_message_queue::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor< + cumulus_primitives_core::AggregateMessageOrigin, + >; + #[cfg(not(feature = "runtime-benchmarks"))] + type MessageProcessor = xcm_builder::ProcessXcmMessage< + AggregateMessageOrigin, + xcm_executor::XcmExecutor, + RuntimeCall, + >; + type Size = u32; + // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin: + type QueueChangeHandler = NarrowOriginToSibling; + type QueuePausedQuery = NarrowOriginToSibling; + type HeapSize = sp_core::ConstU32<{ 64 * 1024 }>; + type MaxStale = sp_core::ConstU32<8>; + type ServiceWeight = MessageQueueServiceWeight; +} + +impl cumulus_pallet_aura_ext::Config for Runtime {} + +parameter_types! { + // Fellows pluralistic body. + pub const FellowsBodyId: BodyId = BodyId::Technical; +} + +/// Privileged origin that represents Root or Fellows pluralistic body. +pub type RootOrFellows = EitherOfDiverse< + EnsureRoot, + EnsureXcm>, +>; + +impl cumulus_pallet_xcmp_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type ChannelInfo = ParachainSystem; + type VersionWrapper = PolkadotXcm; + // Enqueue XCMP messages from siblings for later processing. + type XcmpQueue = TransformOrigin; + type MaxInboundSuspended = sp_core::ConstU32<1_000>; + type ControllerOrigin = RootOrFellows; + type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; + type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; + type PriceForSiblingDelivery = NoPriceForMessageDelivery; +} + +parameter_types! { + pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent; +} + +impl cumulus_pallet_dmp_queue::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_dmp_queue::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type DmpSink = frame_support::traits::EnqueueWithOrigin; +} + +pub const PERIOD: u32 = 6 * HOURS; +pub const OFFSET: u32 = 0; + +impl pallet_session::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type ValidatorId = ::AccountId; + // we don't have stash and controller, thus we don't need the convert as well. + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ShouldEndSession = pallet_session::PeriodicSessions, ConstU32>; + type NextSessionRotation = pallet_session::PeriodicSessions, ConstU32>; + type SessionManager = CollatorSelection; + // Essentially just Aura, but let's be pedantic. + type SessionHandler = ::KeyTypeIdProviders; + type Keys = SessionKeys; + type WeightInfo = weights::pallet_session::WeightInfo; +} + +impl pallet_aura::Config for Runtime { + type AuthorityId = AuraId; + type DisabledValidators = (); + type MaxAuthorities = ConstU32<100_000>; + type AllowMultipleBlocksPerSlot = ConstBool; + #[cfg(feature = "experimental")] + type SlotDuration = pallet_aura::MinimumPeriodTimesTwo; +} + +parameter_types! { + pub const PotId: PalletId = PalletId(*b"PotStake"); + pub const SessionLength: BlockNumber = 6 * HOURS; + // StakingAdmin pluralistic body. + pub const StakingAdminBodyId: BodyId = BodyId::Defense; +} + +/// We allow Root and the `StakingAdmin` to execute privileged collator selection operations. +pub type CollatorSelectionUpdateOrigin = EitherOfDiverse< + EnsureRoot, + EnsureXcm>, +>; + +impl pallet_collator_selection::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type UpdateOrigin = CollatorSelectionUpdateOrigin; + type PotId = PotId; + type MaxCandidates = ConstU32<100>; + type MinEligibleCollators = ConstU32<4>; + type MaxInvulnerables = ConstU32<20>; + // should be a multiple of session or things will get inconsistent + type KickThreshold = ConstU32; + type ValidatorId = ::AccountId; + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ValidatorRegistration = Session; + type WeightInfo = weights::pallet_collator_selection::WeightInfo; +} + +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); + // Additional storage item size of 32 bytes. + pub const DepositFactor: Balance = deposit(0, 32); +} + +impl pallet_multisig::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type Currency = Balances; + type DepositBase = DepositBase; + type DepositFactor = DepositFactor; + type MaxSignatories = ConstU32<100>; + type WeightInfo = weights::pallet_multisig::WeightInfo; +} + +impl pallet_utility::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type PalletsOrigin = OriginCaller; + type WeightInfo = weights::pallet_utility::WeightInfo; +} + +// Create the runtime by composing the FRAME pallets that were previously configured. +construct_runtime!( + pub enum Runtime + { + // System support stuff. + System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, + ParachainSystem: cumulus_pallet_parachain_system::{ + Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned, + } = 1, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2, + ParachainInfo: parachain_info::{Pallet, Storage, Config} = 3, + + // Monetary stuff. + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, + TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 11, + + // Collator support. The order of these 4 are important and shall not change. + Authorship: pallet_authorship::{Pallet, Storage} = 20, + CollatorSelection: pallet_collator_selection::{Pallet, Call, Storage, Event, Config} = 21, + Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, + Aura: pallet_aura::{Pallet, Storage, Config} = 23, + AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config} = 24, + + // XCM helpers. + XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, + PolkadotXcm: pallet_xcm::{Pallet, Call, Event, Origin, Config} = 31, + CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, + DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, + MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event} = 34, + + // Handy utilities. + Utility: pallet_utility::{Pallet, Call, Event} = 40, + Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 41, + } +); + +#[cfg(feature = "runtime-benchmarks")] +mod benches { + frame_benchmarking::define_benchmarks!( + [frame_system, SystemBench::] + [pallet_balances, Balances] + [pallet_message_queue, MessageQueue] + [pallet_multisig, Multisig] + [pallet_session, SessionBench::] + [pallet_utility, Utility] + [pallet_timestamp, Timestamp] + [pallet_collator_selection, CollatorSelection] + [cumulus_pallet_xcmp_queue, XcmpQueue] + [cumulus_pallet_dmp_queue, DmpQueue] + // XCM + [pallet_xcm, PalletXcmExtrinsicsBenchmark::] + // NOTE: Make sure you point to the individual modules below. + [pallet_xcm_benchmarks::fungible, XcmBalances] + [pallet_xcm_benchmarks::generic, XcmGeneric] + ); +} + +impl_runtime_apis! { + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + + fn authorities() -> Vec { + Aura::authorities().into_inner() + } + } + + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + + fn metadata_at_version(version: u32) -> Option { + Runtime::metadata_at_version(version) + } + + fn metadata_versions() -> sp_std::vec::Vec { + Runtime::metadata_versions() + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi + for Runtime + { + fn query_call_info( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::RuntimeDispatchInfo { + TransactionPayment::query_call_info(call, len) + } + fn query_call_fee_details( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_call_fee_details(call, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { + ParachainSystem::collect_collation_info(header) + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { + let weight = Executive::try_runtime_upgrade(checks).unwrap(); + (weight, RuntimeBlockWeights::get().max_block) + } + + fn execute_block( + block: Block, + state_root_check: bool, + signature_check: bool, + select: frame_try_runtime::TryStateSelect, + ) -> Weight { + // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to + // have a backtrace here. + Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap() + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; + + // This is defined once again in dispatch_benchmark, because list_benchmarks! + // and add_benchmarks! are macros exported by define_benchmarks! macros and those types + // are referenced in that call. + type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::; + type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::; + + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsWithSystem::storage_info(); + (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; + use sp_storage::TrackedStorageKey; + + use frame_system_benchmarking::Pallet as SystemBench; + impl frame_system_benchmarking::Config for Runtime { + fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); + Ok(()) + } + + fn verify_set_code() { + System::assert_last_event(cumulus_pallet_parachain_system::Event::::ValidationFunctionStored.into()); + } + } + + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + impl cumulus_pallet_session_benchmarking::Config for Runtime {} + + use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; + impl pallet_xcm::benchmarking::Config for Runtime { + fn reachable_dest() -> Option { + Some(Parent.into()) + } + + fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + // Relay/native token can be teleported between BH and Relay. + Some(( + MultiAsset { + fun: Fungible(EXISTENTIAL_DEPOSIT), + id: Concrete(Parent.into()) + }, + Parent.into(), + )) + } + + fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + // Reserve transfers are disabled on BH. + None + } + } + + use xcm::latest::prelude::*; + use xcm_config::KsmRelayLocation; + + parameter_types! { + pub ExistentialDepositMultiAsset: Option = Some(( + xcm_config::KsmRelayLocation::get(), + ExistentialDeposit::get() + ).into()); + } + + impl pallet_xcm_benchmarks::Config for Runtime { + type XcmConfig = xcm_config::XcmConfig; + type AccountIdConverter = xcm_config::LocationToAccountId; + type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< + xcm_config::XcmConfig, + ExistentialDepositMultiAsset, + xcm_config::PriceForParentDelivery, + >; + fn valid_destination() -> Result { + Ok(KsmRelayLocation::get()) + } + fn worst_case_holding(_depositable_count: u32) -> MultiAssets { + // just concrete assets according to relay chain. + let assets: Vec = vec![ + MultiAsset { + id: Concrete(KsmRelayLocation::get()), + fun: Fungible(1_000_000 * UNITS), + } + ]; + assets.into() + } + } + + parameter_types! { + pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + KsmRelayLocation::get(), + MultiAsset { fun: Fungible(UNITS), id: Concrete(KsmRelayLocation::get()) }, + )); + pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; + pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None; + } + + impl pallet_xcm_benchmarks::fungible::Config for Runtime { + type TransactAsset = Balances; + + type CheckedAccount = CheckedAccount; + type TrustedTeleporter = TrustedTeleporter; + type TrustedReserve = TrustedReserve; + + fn get_multi_asset() -> MultiAsset { + MultiAsset { + id: Concrete(KsmRelayLocation::get()), + fun: Fungible(UNITS), + } + } + } + + impl pallet_xcm_benchmarks::generic::Config for Runtime { + type TransactAsset = Balances; + type RuntimeCall = RuntimeCall; + + fn worst_case_response() -> (u64, Response) { + (0u64, Response::Version(Default::default())) + } + + fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + Ok((KsmRelayLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) + } + + fn subscribe_origin() -> Result { + Ok(KsmRelayLocation::get()) + } + + fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + let origin = KsmRelayLocation::get(); + let assets: MultiAssets = (Concrete(KsmRelayLocation::get()), 1_000 * UNITS).into(); + let ticket = MultiLocation { parents: 0, interior: Here }; + Ok((origin, ticket, assets)) + } + + fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn export_message_origin_and_destination( + ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + Err(BenchmarkError::Skip) + } + } + + type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::; + type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::; + + let whitelist: Vec = vec![ + // Block Number + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), + // Total Issuance + hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), + // Execution Phase + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), + // Event Count + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), + // System Events + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), + ]; + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + add_benchmarks!(params, batches); + + Ok(batches) + } + } + + impl sp_genesis_builder::GenesisBuilder for Runtime { + fn create_default_config() -> Vec { + create_default_config::() + } + + fn build_config(config: Vec) -> sp_genesis_builder::Result { + build_config::(config) + } + } +} + +cumulus_pallet_parachain_system::register_validate_block! { + Runtime = Runtime, + BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/block_weights.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/block_weights.rs new file mode 100644 index 00000000000..e7fdb2aae2a --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/block_weights.rs @@ -0,0 +1,53 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; + + parameter_types! { + /// Importing a block with 0 Extrinsics. + pub const BlockExecutionWeight: Weight = + Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); + } + + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; + + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::BlockExecutionWeight::get(); + + // At least 100 µs. + assert!( + w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, + "Weight should be at least 100 µs." + ); + // At most 50 ms. + assert!( + w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, + "Weight should be at most 50 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_dmp_queue.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_dmp_queue.rs new file mode 100644 index 00000000000..cc41dcd6cbb --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_dmp_queue.rs @@ -0,0 +1,131 @@ +// 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 . + +//! Autogenerated weights for `cumulus_pallet_dmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-10-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=cumulus_pallet_dmp_queue +// --chain=asset-hub-kusama-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_dmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_dmp_queue::WeightInfo for WeightInfo { + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65696` + // Estimated: `69161` + // Minimum execution time: 124_651_000 picoseconds. + Weight::from_parts(127_857_000, 0) + .saturating_add(Weight::from_parts(0, 69161)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65659` + // Estimated: `69124` + // Minimum execution time: 65_684_000 picoseconds. + Weight::from_parts(68_039_000, 0) + .saturating_add(Weight::from_parts(0, 69124)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_overweight_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65726` + // Estimated: `69191` + // Minimum execution time: 117_657_000 picoseconds. + Weight::from_parts(122_035_000, 0) + .saturating_add(Weight::from_parts(0, 69191)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + fn on_idle_overweight_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65689` + // Estimated: `69154` + // Minimum execution time: 59_799_000 picoseconds. + Weight::from_parts(61_354_000, 0) + .saturating_add(Weight::from_parts(0, 69154)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_parachain_system.rs new file mode 100644 index 00000000000..a30a2ae8d4d --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_parachain_system.rs @@ -0,0 +1,80 @@ +// 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. + +//! Autogenerated weights for `cumulus_pallet_parachain_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-03-28, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `i9`, CPU: `13th Gen Intel(R) Core(TM) i9-13900K` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-kusama-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --chain +// bridge-hub-kusama-dev +// --pallet +// cumulus_pallet_parachain_system +// --extrinsic +// * +// --execution +// wasm +// --wasm-execution +// compiled +// --output +// parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights +// --steps +// 50 +// --repeat +// 20 + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_parachain_system`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_parachain_system::WeightInfo for WeightInfo { + /// Storage: ParachainSystem LastDmqMqcHead (r:1 w:1) + /// Proof Skipped: ParachainSystem LastDmqMqcHead (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem ReservedDmpWeightOverride (r:1 w:0) + /// Proof Skipped: ParachainSystem ReservedDmpWeightOverride (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: ParachainSystem ProcessedDownwardMessages (r:0 w:1) + /// Proof Skipped: ParachainSystem ProcessedDownwardMessages (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: MessageQueue Pages (r:0 w:16) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + /// The range of component `n` is `[0, 1000]`. + fn enqueue_inbound_downward_messages(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `12` + // Estimated: `8013` + // Minimum execution time: 1_686_000 picoseconds. + Weight::from_parts(1_761_000, 0) + .saturating_add(Weight::from_parts(0, 8013)) + // Standard Error: 28_250 + .saturating_add(Weight::from_parts(24_261_433, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_xcmp_queue.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_xcmp_queue.rs new file mode 100644 index 00000000000..ffd311ceecd --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_xcmp_queue.rs @@ -0,0 +1,148 @@ +// 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. + +//! Autogenerated weights for `cumulus_pallet_xcmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-09-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `Olivers-MacBook-Pro.local`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --pallet +// cumulus-pallet-xcmp-queue +// --chain +// bridge-hub-kusama-dev +// --output +// cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/cumulus_pallet_xcmp_queue.rs +// --extrinsic +// + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_xcmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_xcmp_queue::WeightInfo for WeightInfo { + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:1) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn set_config_with_u32() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `1561` + // Minimum execution time: 5_000_000 picoseconds. + Weight::from_parts(6_000_000, 0) + .saturating_add(Weight::from_parts(0, 1561)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:0) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn enqueue_xcmp_message() -> Weight { + // Proof Size summary in bytes: + // Measured: `82` + // Estimated: `3517` + // Minimum execution time: 14_000_000 picoseconds. + Weight::from_parts(14_000_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn suspend_channel() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `1561` + // Minimum execution time: 3_000_000 picoseconds. + Weight::from_parts(4_000_000, 0) + .saturating_add(Weight::from_parts(0, 1561)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn resume_channel() -> Weight { + // Proof Size summary in bytes: + // Measured: `111` + // Estimated: `1596` + // Minimum execution time: 4_000_000 picoseconds. + Weight::from_parts(5_000_000, 0) + .saturating_add(Weight::from_parts(0, 1596)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn take_first_concatenated_xcm() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 44_000_000 picoseconds. + Weight::from_parts(45_000_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Storage: `XcmpQueue::InboundXcmpMessages` (r:1 w:1) + /// Proof: `XcmpQueue::InboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:0) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65711` + // Estimated: `69176` + // Minimum execution time: 60_000_000 picoseconds. + Weight::from_parts(63_000_000, 0) + .saturating_add(Weight::from_parts(0, 69176)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65710` + // Estimated: `69175` + // Minimum execution time: 42_000_000 picoseconds. + Weight::from_parts(43_000_000, 0) + .saturating_add(Weight::from_parts(0, 69175)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/extrinsic_weights.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/extrinsic_weights.rs new file mode 100644 index 00000000000..1a4adb968bb --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/extrinsic_weights.rs @@ -0,0 +1,53 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; + + parameter_types! { + /// Executing a NO-OP `System::remarks` Extrinsic. + pub const ExtrinsicBaseWeight: Weight = + Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); + } + + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; + + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::ExtrinsicBaseWeight::get(); + + // At least 10 µs. + assert!( + w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, + "Weight should be at least 10 µs." + ); + // At most 1 ms. + assert!( + w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/frame_system.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/frame_system.rs new file mode 100644 index 00000000000..6b9313cdaba --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/frame_system.rs @@ -0,0 +1,154 @@ +// 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. + +//! Autogenerated weights for `frame_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=frame_system +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `frame_system`. +pub struct WeightInfo(PhantomData); +impl frame_system::WeightInfo for WeightInfo { + /// The range of component `b` is `[0, 3932160]`. + fn remark(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_985_000 picoseconds. + Weight::from_parts(2_177_341, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 0 + .saturating_add(Weight::from_parts(386, 0).saturating_mul(b.into())) + } + /// The range of component `b` is `[0, 3932160]`. + fn remark_with_event(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_288_000 picoseconds. + Weight::from_parts(23_888_468, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 8 + .saturating_add(Weight::from_parts(1_718, 0).saturating_mul(b.into())) + } + /// Storage: `System::Digest` (r:1 w:1) + /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) + /// Proof: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) + fn set_heap_pages() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `1485` + // Minimum execution time: 3_700_000 picoseconds. + Weight::from_parts(3_867_000, 0) + .saturating_add(Weight::from_parts(0, 1485)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ParachainSystem::ValidationData` (r:1 w:0) + /// Proof: `ParachainSystem::ValidationData` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpgradeRestrictionSignal` (r:1 w:0) + /// Proof: `ParachainSystem::UpgradeRestrictionSignal` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingValidationCode` (r:1 w:1) + /// Proof: `ParachainSystem::PendingValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::NewValidationCode` (r:0 w:1) + /// Proof: `ParachainSystem::NewValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::DidSetValidationCode` (r:0 w:1) + /// Proof: `ParachainSystem::DidSetValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn set_code() -> Weight { + // Proof Size summary in bytes: + // Measured: `119` + // Estimated: `1604` + // Minimum execution time: 100_298_586_000 picoseconds. + Weight::from_parts(101_869_369_000, 0) + .saturating_add(Weight::from_parts(0, 1604)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `i` is `[0, 1000]`. + fn set_storage(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_052_000 picoseconds. + Weight::from_parts(2_115_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 2_048 + .saturating_add(Weight::from_parts(755_436, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `i` is `[0, 1000]`. + fn kill_storage(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_044_000 picoseconds. + Weight::from_parts(2_110_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_011 + .saturating_add(Weight::from_parts(569_993, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `p` is `[0, 1000]`. + fn kill_prefix(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `68 + p * (69 ±0)` + // Estimated: `66 + p * (70 ±0)` + // Minimum execution time: 3_741_000 picoseconds. + Weight::from_parts(3_838_000, 0) + .saturating_add(Weight::from_parts(0, 66)) + // Standard Error: 2_455 + .saturating_add(Weight::from_parts(1_216_154, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) + .saturating_add(Weight::from_parts(0, 70).saturating_mul(p.into())) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/mod.rs new file mode 100644 index 00000000000..36733d6d4a6 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/mod.rs @@ -0,0 +1,41 @@ +// 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. + +//! Expose the auto generated weight files. + +pub mod block_weights; +pub mod cumulus_pallet_dmp_queue; +pub mod cumulus_pallet_parachain_system; +pub mod cumulus_pallet_xcmp_queue; +pub mod extrinsic_weights; +pub mod frame_system; +pub mod pallet_balances; +pub mod pallet_collator_selection; +pub mod pallet_message_queue; +pub mod pallet_multisig; +pub mod pallet_session; +pub mod pallet_timestamp; +pub mod pallet_utility; +pub mod pallet_xcm; +pub mod paritydb_weights; +pub mod rocksdb_weights; +pub mod xcm; + +pub use block_weights::constants::BlockExecutionWeight; +pub use extrinsic_weights::constants::ExtrinsicBaseWeight; +pub use paritydb_weights::constants::ParityDbWeight; +pub use rocksdb_weights::constants::RocksDbWeight; diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_balances.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_balances.rs new file mode 100644 index 00000000000..04ceb5bed75 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_balances.rs @@ -0,0 +1,152 @@ +// 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. + +//! Autogenerated weights for `pallet_balances` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_balances +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_balances`. +pub struct WeightInfo(PhantomData); +impl pallet_balances::WeightInfo for WeightInfo { + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_allow_death() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 55_163_000 picoseconds. + Weight::from_parts(56_056_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_keep_alive() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 40_829_000 picoseconds. + Weight::from_parts(42_182_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_set_balance_creating() -> Weight { + // Proof Size summary in bytes: + // Measured: `174` + // Estimated: `3593` + // Minimum execution time: 15_212_000 picoseconds. + Weight::from_parts(15_782_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_set_balance_killing() -> Weight { + // Proof Size summary in bytes: + // Measured: `174` + // Estimated: `3593` + // Minimum execution time: 22_866_000 picoseconds. + Weight::from_parts(23_452_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `6196` + // Minimum execution time: 57_047_000 picoseconds. + Weight::from_parts(58_536_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_all() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 51_622_000 picoseconds. + Weight::from_parts(52_912_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_unreserve() -> Weight { + // Proof Size summary in bytes: + // Measured: `174` + // Estimated: `3593` + // Minimum execution time: 17_723_000 picoseconds. + Weight::from_parts(18_383_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:999 w:999) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `u` is `[1, 1000]`. + fn upgrade_accounts(u: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + u * (136 ±0)` + // Estimated: `990 + u * (2603 ±0)` + // Minimum execution time: 17_089_000 picoseconds. + Weight::from_parts(17_379_000, 0) + .saturating_add(Weight::from_parts(0, 990)) + // Standard Error: 17_071 + .saturating_add(Weight::from_parts(15_647_341, 0).saturating_mul(u.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(u.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(u.into()))) + .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_collator_selection.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_collator_selection.rs new file mode 100644 index 00000000000..72d8ba4045a --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_collator_selection.rs @@ -0,0 +1,248 @@ +// 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. + +//! Autogenerated weights for `pallet_collator_selection` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_collator_selection +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_collator_selection`. +pub struct WeightInfo(PhantomData); +impl pallet_collator_selection::WeightInfo for WeightInfo { + /// Storage: `Session::NextKeys` (r:20 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::Invulnerables` (r:0 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// The range of component `b` is `[1, 20]`. + fn set_invulnerables(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `196 + b * (79 ±0)` + // Estimated: `1187 + b * (2555 ±0)` + // Minimum execution time: 14_329_000 picoseconds. + Weight::from_parts(11_605_842, 0) + .saturating_add(Weight::from_parts(0, 1187)) + // Standard Error: 4_784 + .saturating_add(Weight::from_parts(3_297_183, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(b.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(Weight::from_parts(0, 2555).saturating_mul(b.into())) + } + /// Storage: `Session::NextKeys` (r:1 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `b` is `[1, 19]`. + /// The range of component `c` is `[1, 99]`. + fn add_invulnerable(b: u32, c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `757 + b * (32 ±0) + c * (53 ±0)` + // Estimated: `6287 + b * (37 ±0) + c * (53 ±0)` + // Minimum execution time: 47_110_000 picoseconds. + Weight::from_parts(45_234_418, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 14_452 + .saturating_add(Weight::from_parts(156_031, 0).saturating_mul(b.into())) + // Standard Error: 2_739 + .saturating_add(Weight::from_parts(216_162, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 37).saturating_mul(b.into())) + .saturating_add(Weight::from_parts(0, 53).saturating_mul(c.into())) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:0) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// The range of component `b` is `[5, 20]`. + fn remove_invulnerable(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `82 + b * (32 ±0)` + // Estimated: `6287` + // Minimum execution time: 15_326_000 picoseconds. + Weight::from_parts(14_914_611, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_274 + .saturating_add(Weight::from_parts(201_234, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::DesiredCandidates` (r:0 w:1) + /// Proof: `CollatorSelection::DesiredCandidates` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn set_desired_candidates() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_288_000 picoseconds. + Weight::from_parts(7_472_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::CandidacyBond` (r:0 w:1) + /// Proof: `CollatorSelection::CandidacyBond` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + fn set_candidacy_bond(_c: u32, _k: u32) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_137_000 picoseconds. + Weight::from_parts(7_374_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::DesiredCandidates` (r:1 w:0) + /// Proof: `CollatorSelection::DesiredCandidates` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `Session::NextKeys` (r:1 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::CandidacyBond` (r:1 w:0) + /// Proof: `CollatorSelection::CandidacyBond` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// The range of component `c` is `[1, 99]`. + fn register_as_candidate(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `740 + c * (52 ±0)` + // Estimated: `6287 + c * (54 ±0)` + // Minimum execution time: 40_718_000 picoseconds. + Weight::from_parts(43_911_837, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 3_053 + .saturating_add(Weight::from_parts(229_337, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(2)) + .saturating_add(Weight::from_parts(0, 54).saturating_mul(c.into())) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// The range of component `c` is `[3, 100]`. + fn leave_intent(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `334 + c * (49 ±0)` + // Estimated: `6287` + // Minimum execution time: 32_953_000 picoseconds. + Weight::from_parts(34_817_275, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_476 + .saturating_add(Weight::from_parts(198_023, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + fn update_bond(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 34_814_000 picoseconds. + Weight::from_parts(36_371_520, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_391 + .saturating_add(Weight::from_parts(201_700, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + fn take_candidate_slot(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 34_814_000 picoseconds. + Weight::from_parts(36_371_520, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_391 + .saturating_add(Weight::from_parts(201_700, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `System::BlockWeight` (r:1 w:1) + /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + fn note_author() -> Weight { + // Proof Size summary in bytes: + // Measured: `155` + // Estimated: `6196` + // Minimum execution time: 45_130_000 picoseconds. + Weight::from_parts(46_733_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:0) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:100 w:0) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `System::BlockWeight` (r:1 w:1) + /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:97 w:97) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `r` is `[1, 100]`. + /// The range of component `c` is `[1, 100]`. + fn new_session(r: u32, c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `2263 + c * (97 ±0) + r * (115 ±0)` + // Estimated: `6287 + c * (2519 ±0) + r * (2603 ±0)` + // Minimum execution time: 16_690_000 picoseconds. + Weight::from_parts(17_188_000, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 345_320 + .saturating_add(Weight::from_parts(15_166_422, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(c.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 2519).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(0, 2603).saturating_mul(r.into())) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_message_queue.rs new file mode 100644 index 00000000000..c5a4235055d --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_message_queue.rs @@ -0,0 +1,179 @@ +// 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. + +//! Autogenerated weights for `pallet_message_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-03-24, STEPS: `2`, REPEAT: `1`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `i9`, CPU: `13th Gen Intel(R) Core(TM) i9-13900K` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-kusama-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --chain +// bridge-hub-kusama-dev +// --pallet +// pallet_message_queue +// --extrinsic +// * +// --execution +// wasm +// --wasm-execution +// compiled +// --output +// parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `pallet_message_queue`. +pub struct WeightInfo(PhantomData); +impl pallet_message_queue::WeightInfo for WeightInfo { + /// Storage: MessageQueue ServiceHead (r:1 w:0) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: MessageQueue BookStateFor (r:2 w:2) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn ready_ring_knit() -> Weight { + // Proof Size summary in bytes: + // Measured: `189` + // Estimated: `7534` + // Minimum execution time: 11_692_000 picoseconds. + Weight::from_parts(11_692_000, 0) + .saturating_add(Weight::from_parts(0, 7534)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:2 w:2) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + fn ready_ring_unknit() -> Weight { + // Proof Size summary in bytes: + // Measured: `184` + // Estimated: `7534` + // Minimum execution time: 10_614_000 picoseconds. + Weight::from_parts(10_614_000, 0) + .saturating_add(Weight::from_parts(0, 7534)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn service_queue_base() -> Weight { + // Proof Size summary in bytes: + // Measured: `6` + // Estimated: `3517` + // Minimum execution time: 7_085_000 picoseconds. + Weight::from_parts(7_085_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn service_page_base_completion() -> Weight { + // Proof Size summary in bytes: + // Measured: `72` + // Estimated: `69050` + // Minimum execution time: 5_813_000 picoseconds. + Weight::from_parts(5_813_000, 0) + .saturating_add(Weight::from_parts(0, 69050)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn service_page_base_no_completion() -> Weight { + // Proof Size summary in bytes: + // Measured: `72` + // Estimated: `69050` + // Minimum execution time: 6_090_000 picoseconds. + Weight::from_parts(6_090_000, 0) + .saturating_add(Weight::from_parts(0, 69050)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn service_page_item() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 58_905_000 picoseconds. + Weight::from_parts(58_905_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: MessageQueue BookStateFor (r:1 w:0) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn bump_service_head() -> Weight { + // Proof Size summary in bytes: + // Measured: `99` + // Estimated: `5007` + // Minimum execution time: 6_501_000 picoseconds. + Weight::from_parts(6_501_000, 0) + .saturating_add(Weight::from_parts(0, 5007)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn reap_page() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 39_695_000 picoseconds. + Weight::from_parts(39_695_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn execute_overweight_page_removed() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 50_543_000 picoseconds. + Weight::from_parts(50_543_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn execute_overweight_page_updated() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 69_294_000 picoseconds. + Weight::from_parts(69_294_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_multisig.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_multisig.rs new file mode 100644 index 00000000000..f4135e975fb --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_multisig.rs @@ -0,0 +1,164 @@ +// 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. + +//! Autogenerated weights for `pallet_multisig` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_multisig +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_multisig`. +pub struct WeightInfo(PhantomData); +impl pallet_multisig::WeightInfo for WeightInfo { + /// The range of component `z` is `[0, 10000]`. + fn as_multi_threshold_1(z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 13_602_000 picoseconds. + Weight::from_parts(14_565_036, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 8 + .saturating_add(Weight::from_parts(518, 0).saturating_mul(z.into())) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_create(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `263 + s * (2 ±0)` + // Estimated: `6811` + // Minimum execution time: 46_075_000 picoseconds. + Weight::from_parts(33_730_493, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_049 + .saturating_add(Weight::from_parts(134_211, 0).saturating_mul(s.into())) + // Standard Error: 10 + .saturating_add(Weight::from_parts(1_448, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[3, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_approve(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `6811` + // Minimum execution time: 29_389_000 picoseconds. + Weight::from_parts(19_639_583, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 976 + .saturating_add(Weight::from_parts(106_598, 0).saturating_mul(s.into())) + // Standard Error: 9 + .saturating_add(Weight::from_parts(1_457, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_complete(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `388 + s * (33 ±0)` + // Estimated: `6811` + // Minimum execution time: 50_438_000 picoseconds. + Weight::from_parts(36_195_308, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_689 + .saturating_add(Weight::from_parts(176_067, 0).saturating_mul(s.into())) + // Standard Error: 16 + .saturating_add(Weight::from_parts(1_545, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_create(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `263 + s * (2 ±0)` + // Estimated: `6811` + // Minimum execution time: 32_134_000 picoseconds. + Weight::from_parts(32_149_785, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_082 + .saturating_add(Weight::from_parts(145_390, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_approve(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `6811` + // Minimum execution time: 17_560_000 picoseconds. + Weight::from_parts(18_144_079, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 763 + .saturating_add(Weight::from_parts(114_298, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn cancel_as_multi(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `454 + s * (1 ±0)` + // Estimated: `6811` + // Minimum execution time: 32_360_000 picoseconds. + Weight::from_parts(33_566_579, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_314 + .saturating_add(Weight::from_parts(126_583, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_session.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_session.rs new file mode 100644 index 00000000000..f508e1daaef --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_session.rs @@ -0,0 +1,80 @@ +// 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. + +//! Autogenerated weights for `pallet_session` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_session +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_session`. +pub struct WeightInfo(PhantomData); +impl pallet_session::WeightInfo for WeightInfo { + /// Storage: `Session::NextKeys` (r:1 w:1) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Session::KeyOwner` (r:1 w:1) + /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn set_keys() -> Weight { + // Proof Size summary in bytes: + // Measured: `297` + // Estimated: `3762` + // Minimum execution time: 17_170_000 picoseconds. + Weight::from_parts(17_523_000, 0) + .saturating_add(Weight::from_parts(0, 3762)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Session::NextKeys` (r:1 w:1) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Session::KeyOwner` (r:0 w:1) + /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn purge_keys() -> Weight { + // Proof Size summary in bytes: + // Measured: `279` + // Estimated: `3744` + // Minimum execution time: 13_273_000 picoseconds. + Weight::from_parts(14_200_000, 0) + .saturating_add(Weight::from_parts(0, 3744)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_timestamp.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_timestamp.rs new file mode 100644 index 00000000000..6162b1d48c5 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_timestamp.rs @@ -0,0 +1,74 @@ +// 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. + +//! Autogenerated weights for `pallet_timestamp` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_timestamp +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_timestamp`. +pub struct WeightInfo(PhantomData); +impl pallet_timestamp::WeightInfo for WeightInfo { + /// Storage: `Timestamp::Now` (r:1 w:1) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `Aura::CurrentSlot` (r:1 w:0) + /// Proof: `Aura::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + fn set() -> Weight { + // Proof Size summary in bytes: + // Measured: `49` + // Estimated: `1493` + // Minimum execution time: 7_794_000 picoseconds. + Weight::from_parts(8_075_000, 0) + .saturating_add(Weight::from_parts(0, 1493)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn on_finalize() -> Weight { + // Proof Size summary in bytes: + // Measured: `57` + // Estimated: `0` + // Minimum execution time: 3_338_000 picoseconds. + Weight::from_parts(3_471_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_utility.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_utility.rs new file mode 100644 index 00000000000..93d0ea596e7 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_utility.rs @@ -0,0 +1,101 @@ +// 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. + +//! Autogenerated weights for `pallet_utility` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_utility +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_utility`. +pub struct WeightInfo(PhantomData); +impl pallet_utility::WeightInfo for WeightInfo { + /// The range of component `c` is `[0, 1000]`. + fn batch(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_641_000 picoseconds. + Weight::from_parts(7_103_558, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_172 + .saturating_add(Weight::from_parts(4_907_384, 0).saturating_mul(c.into())) + } + fn as_derivative() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_741_000 picoseconds. + Weight::from_parts(4_870_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// The range of component `c` is `[0, 1000]`. + fn batch_all(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_561_000 picoseconds. + Weight::from_parts(12_252_064, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_750 + .saturating_add(Weight::from_parts(5_193_404, 0).saturating_mul(c.into())) + } + fn dispatch_as() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 8_646_000 picoseconds. + Weight::from_parts(8_927_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// The range of component `c` is `[0, 1000]`. + fn force_batch(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_726_000 picoseconds. + Weight::from_parts(8_025_954, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_746 + .saturating_add(Weight::from_parts(4_936_537, 0).saturating_mul(c.into())) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_xcm.rs new file mode 100644 index 00000000000..7f4c2026f2b --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/pallet_xcm.rs @@ -0,0 +1,323 @@ +// 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 . + +//! Autogenerated weights for `pallet_xcm` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-11-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_xcm +// --chain=bridge-hub-kusama-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_xcm`. +pub struct WeightInfo(PhantomData); +impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn send() -> Weight { + // Proof Size summary in bytes: + // Measured: `38` + // Estimated: `3503` + // Minimum execution time: 22_520_000 picoseconds. + Weight::from_parts(23_167_000, 0) + .saturating_add(Weight::from_parts(0, 3503)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn teleport_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `32` + // Estimated: `1489` + // Minimum execution time: 19_639_000 picoseconds. + Weight::from_parts(20_230_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + .saturating_add(T::DbWeight::get().reads(1)) + } + /// Storage: `Benchmark::Override` (r:0 w:0) + /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn reserve_transfer_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 18_446_744_073_709_551_000 picoseconds. + Weight::from_parts(18_446_744_073_709_551_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: `Benchmark::Override` (r:0 w:0) + /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn execute() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 18_446_744_073_709_551_000 picoseconds. + Weight::from_parts(18_446_744_073_709_551_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: `PolkadotXcm::SupportedVersion` (r:0 w:1) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_xcm_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_175_000 picoseconds. + Weight::from_parts(7_496_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:0 w:1) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn force_default_xcm_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_126_000 picoseconds. + Weight::from_parts(2_359_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_subscribe_version_notify() -> Weight { + // Proof Size summary in bytes: + // Measured: `38` + // Estimated: `3503` + // Minimum execution time: 27_229_000 picoseconds. + Weight::from_parts(27_673_000, 0) + .saturating_add(Weight::from_parts(0, 3503)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_unsubscribe_version_notify() -> Weight { + // Proof Size summary in bytes: + // Measured: `255` + // Estimated: `3720` + // Minimum execution time: 29_812_000 picoseconds. + Weight::from_parts(30_649_000, 0) + .saturating_add(Weight::from_parts(0, 3720)) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PolkadotXcm::XcmExecutionSuspended` (r:0 w:1) + /// Proof: `PolkadotXcm::XcmExecutionSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn force_suspension() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_212_000 picoseconds. + Weight::from_parts(2_367_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::SupportedVersion` (r:4 w:2) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_supported_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `95` + // Estimated: `10985` + // Minimum execution time: 14_768_000 picoseconds. + Weight::from_parts(15_036_000, 0) + .saturating_add(Weight::from_parts(0, 10985)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_version_notifiers() -> Weight { + // Proof Size summary in bytes: + // Measured: `99` + // Estimated: `10989` + // Minimum execution time: 14_662_000 picoseconds. + Weight::from_parts(15_155_000, 0) + .saturating_add(Weight::from_parts(0, 10989)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:5 w:0) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn already_notified_target() -> Weight { + // Proof Size summary in bytes: + // Measured: `106` + // Estimated: `13471` + // Minimum execution time: 16_198_000 picoseconds. + Weight::from_parts(16_456_000, 0) + .saturating_add(Weight::from_parts(0, 13471)) + .saturating_add(T::DbWeight::get().reads(5)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:2 w:1) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn notify_current_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `106` + // Estimated: `6046` + // Minimum execution time: 25_825_000 picoseconds. + Weight::from_parts(26_744_000, 0) + .saturating_add(Weight::from_parts(0, 6046)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:3 w:0) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn notify_target_migration_fail() -> Weight { + // Proof Size summary in bytes: + // Measured: `136` + // Estimated: `8551` + // Minimum execution time: 8_622_000 picoseconds. + Weight::from_parts(8_931_000, 0) + .saturating_add(Weight::from_parts(0, 8551)) + .saturating_add(T::DbWeight::get().reads(3)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_version_notify_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `106` + // Estimated: `10996` + // Minimum execution time: 15_397_000 picoseconds. + Weight::from_parts(15_650_000, 0) + .saturating_add(Weight::from_parts(0, 10996)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn migrate_and_notify_old_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `112` + // Estimated: `11002` + // Minimum execution time: 32_330_000 picoseconds. + Weight::from_parts(33_255_000, 0) + .saturating_add(Weight::from_parts(0, 11002)) + .saturating_add(T::DbWeight::get().reads(10)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn new_query() -> Weight { + // Proof Size summary in bytes: + // Measured: `32` + // Estimated: `1517` + // Minimum execution time: 4_142_000 picoseconds. + Weight::from_parts(4_308_000, 0) + .saturating_add(Weight::from_parts(0, 1517)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::Queries` (r:1 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn take_response() -> Weight { + // Proof Size summary in bytes: + // Measured: `7669` + // Estimated: `11134` + // Minimum execution time: 25_814_000 picoseconds. + Weight::from_parts(26_213_000, 0) + .saturating_add(Weight::from_parts(0, 11134)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/paritydb_weights.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/paritydb_weights.rs new file mode 100644 index 00000000000..25679703831 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/paritydb_weights.rs @@ -0,0 +1,63 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; + + parameter_types! { + /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights + /// are available for brave runtime engineers who may want to try this out as default. + pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + }; + } + + #[cfg(test)] + mod test_db_weights { + use super::constants::ParityDbWeight as W; + use frame_support::weights::constants; + + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Write weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/rocksdb_weights.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/rocksdb_weights.rs new file mode 100644 index 00000000000..3dd817aa6f1 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/rocksdb_weights.rs @@ -0,0 +1,63 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; + + parameter_types! { + /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout + /// the runtime. + pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + }; + } + + #[cfg(test)] + mod test_db_weights { + use super::constants::RocksDbWeight as W; + use frame_support::weights::constants; + + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Write weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/mod.rs new file mode 100644 index 00000000000..71732961d3d --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/mod.rs @@ -0,0 +1,244 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +mod pallet_xcm_benchmarks_fungible; +mod pallet_xcm_benchmarks_generic; + +use crate::{xcm_config::MaxAssetsIntoHolding, Runtime}; +use frame_support::weights::Weight; +use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; +use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; +use sp_std::prelude::*; +use xcm::{latest::prelude::*, DoubleEncoded}; + +trait WeighMultiAssets { + fn weigh_multi_assets(&self, weight: Weight) -> Weight; +} + +const MAX_ASSETS: u64 = 100; + +impl WeighMultiAssets for MultiAssetFilter { + fn weigh_multi_assets(&self, weight: Weight) -> Weight { + match self { + Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64), + Self::Wild(asset) => match asset { + All => weight.saturating_mul(MAX_ASSETS), + AllOf { fun, .. } => match fun { + WildFungibility::Fungible => weight, + // Magic number 2 has to do with the fact that we could have up to 2 times + // MaxAssetsIntoHolding in the worst-case scenario. + WildFungibility::NonFungible => + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + }, + AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), + AllOfCounted { count, .. } => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), + }, + } + } +} + +impl WeighMultiAssets for MultiAssets { + fn weigh_multi_assets(&self, weight: Weight) -> Weight { + weight.saturating_mul(self.inner().iter().count() as u64) + } +} + +pub struct BridgeHubKusamaXcmWeight(core::marker::PhantomData); +impl XcmWeightInfo for BridgeHubKusamaXcmWeight { + fn withdraw_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + } + fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::reserve_asset_deposited()) + } + fn receive_teleported_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + } + fn query_response( + _query_id: &u64, + _response: &Response, + _max_weight: &Weight, + _querier: &Option, + ) -> Weight { + XcmGeneric::::query_response() + } + fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + } + fn transfer_reserve_asset( + assets: &MultiAssets, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + } + fn transact( + _origin_type: &OriginKind, + _require_weight_at_most: &Weight, + _call: &DoubleEncoded, + ) -> Weight { + XcmGeneric::::transact() + } + fn hrmp_new_channel_open_request( + _sender: &u32, + _max_message_size: &u32, + _max_capacity: &u32, + ) -> Weight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX + } + fn hrmp_channel_accepted(_recipient: &u32) -> Weight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX + } + fn hrmp_channel_closing(_initiator: &u32, _sender: &u32, _recipient: &u32) -> Weight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX + } + fn clear_origin() -> Weight { + XcmGeneric::::clear_origin() + } + fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + XcmGeneric::::descend_origin() + } + fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::report_error() + } + + fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()) + } + fn deposit_reserve_asset( + assets: &MultiAssetFilter, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + } + fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + Weight::MAX + } + fn initiate_reserve_withdraw( + assets: &MultiAssetFilter, + _reserve: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) + } + fn initiate_teleport( + assets: &MultiAssetFilter, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()) + } + fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + XcmGeneric::::report_holding() + } + fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + XcmGeneric::::buy_execution() + } + fn refund_surplus() -> Weight { + XcmGeneric::::refund_surplus() + } + fn set_error_handler(_xcm: &Xcm) -> Weight { + XcmGeneric::::set_error_handler() + } + fn set_appendix(_xcm: &Xcm) -> Weight { + XcmGeneric::::set_appendix() + } + fn clear_error() -> Weight { + XcmGeneric::::clear_error() + } + fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + XcmGeneric::::claim_asset() + } + fn trap(_code: &u64) -> Weight { + XcmGeneric::::trap() + } + fn subscribe_version(_query_id: &QueryId, _max_response_weight: &Weight) -> Weight { + XcmGeneric::::subscribe_version() + } + fn unsubscribe_version() -> Weight { + XcmGeneric::::unsubscribe_version() + } + fn burn_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + } + fn expect_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + } + fn expect_origin(_origin: &Option) -> Weight { + XcmGeneric::::expect_origin() + } + fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { + XcmGeneric::::expect_error() + } + fn expect_transact_status(_transact_status: &MaybeErrorCode) -> Weight { + XcmGeneric::::expect_transact_status() + } + fn query_pallet(_module_name: &Vec, _response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::query_pallet() + } + fn expect_pallet( + _index: &u32, + _name: &Vec, + _module_name: &Vec, + _crate_major: &u32, + _min_crate_minor: &u32, + ) -> Weight { + XcmGeneric::::expect_pallet() + } + fn report_transact_status(_response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::report_transact_status() + } + fn clear_transact_status() -> Weight { + XcmGeneric::::clear_transact_status() + } + fn universal_origin(_: &Junction) -> Weight { + Weight::MAX + } + fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight { + Weight::MAX + } + fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn set_fees_mode(_: &bool) -> Weight { + XcmGeneric::::set_fees_mode() + } + fn set_topic(_topic: &[u8; 32]) -> Weight { + XcmGeneric::::set_topic() + } + fn clear_topic() -> Weight { + XcmGeneric::::clear_topic() + } + fn alias_origin(_: &MultiLocation) -> Weight { + // XCM Executor does not currently support alias origin operations + Weight::MAX + } + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + XcmGeneric::::unpaid_execution() + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs new file mode 100644 index 00000000000..ff3cb452a8a --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -0,0 +1,187 @@ +// 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. + +//! Autogenerated weights for `pallet_xcm_benchmarks::fungible` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-09-28, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-nbnwcyh-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-kusama-dev"), DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_xcm_benchmarks::fungible +// --chain=bridge-hub-kusama-dev +// --header=./cumulus/file_header.txt +// --template=./cumulus/templates/xcm-bench-template.hbs +// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weights for `pallet_xcm_benchmarks::fungible`. +pub struct WeightInfo(PhantomData); +impl WeightInfo { + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + pub fn withdraw_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `101` + // Estimated: `3593` + // Minimum execution time: 25_447_000 picoseconds. + Weight::from_parts(25_810_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + // Storage: `System::Account` (r:2 w:2) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + pub fn transfer_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `153` + // Estimated: `6196` + // Minimum execution time: 53_908_000 picoseconds. + Weight::from_parts(54_568_000, 6196) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + // Storage: `System::Account` (r:2 w:2) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn transfer_reserve_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `223` + // Estimated: `6196` + // Minimum execution time: 79_923_000 picoseconds. + Weight::from_parts(80_790_000, 6196) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(4)) + } + // Storage: `Benchmark::Override` (r:0 w:0) + // Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn reserve_asset_deposited() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 18_446_744_073_709_551_000 picoseconds. + Weight::from_parts(18_446_744_073_709_551_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_reserve_withdraw() -> Weight { + // Proof Size summary in bytes: + // Measured: `70` + // Estimated: `3535` + // Minimum execution time: 31_923_000 picoseconds. + Weight::from_parts(32_499_000, 3535) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn receive_teleported_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_903_000 picoseconds. + Weight::from_parts(4_065_000, 0) + } + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + pub fn deposit_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `52` + // Estimated: `3593` + // Minimum execution time: 26_987_000 picoseconds. + Weight::from_parts(27_486_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn deposit_reserve_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `122` + // Estimated: `3593` + // Minimum execution time: 56_012_000 picoseconds. + Weight::from_parts(58_067_000, 3593) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(3)) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_teleport() -> Weight { + // Proof Size summary in bytes: + // Measured: `70` + // Estimated: `3535` + // Minimum execution time: 32_350_000 picoseconds. + Weight::from_parts(33_403_000, 3535) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_generic.rs new file mode 100644 index 00000000000..c5c14e6917e --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -0,0 +1,328 @@ +// 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. + +//! Autogenerated weights for `pallet_xcm_benchmarks::generic` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: , WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-kusama-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --template=./templates/xcm-bench-template.hbs +// --chain=bridge-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_xcm_benchmarks::generic +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/weights/xcm/pallet_xcm_benchmarks_generic.rs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weights for `pallet_xcm_benchmarks::generic`. +pub struct WeightInfo(PhantomData); +impl WeightInfo { + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn report_holding() -> Weight { + // Proof Size summary in bytes: + // Measured: `70` + // Estimated: `3535` + // Minimum execution time: 33_141_000 picoseconds. + Weight::from_parts(34_380_000, 3535) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn buy_execution() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_803_000 picoseconds. + Weight::from_parts(2_904_000, 0) + } + // Storage: `PolkadotXcm::Queries` (r:1 w:0) + // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn query_response() -> Weight { + // Proof Size summary in bytes: + // Measured: `32` + // Estimated: `3497` + // Minimum execution time: 10_308_000 picoseconds. + Weight::from_parts(10_753_000, 3497) + .saturating_add(T::DbWeight::get().reads(1)) + } + pub fn transact() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 11_499_000 picoseconds. + Weight::from_parts(11_786_000, 0) + } + pub fn refund_surplus() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_102_000 picoseconds. + Weight::from_parts(3_161_000, 0) + } + pub fn set_error_handler() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_678_000 picoseconds. + Weight::from_parts(2_795_000, 0) + } + pub fn set_appendix() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_685_000 picoseconds. + Weight::from_parts(2_758_000, 0) + } + pub fn clear_error() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_590_000 picoseconds. + Weight::from_parts(2_754_000, 0) + } + pub fn descend_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_297_000 picoseconds. + Weight::from_parts(3_419_000, 0) + } + pub fn clear_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_606_000 picoseconds. + Weight::from_parts(2_717_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn report_error() -> Weight { + // Proof Size summary in bytes: + // Measured: `70` + // Estimated: `3535` + // Minimum execution time: 26_242_000 picoseconds. + Weight::from_parts(29_220_000, 3535) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + // Storage: `PolkadotXcm::AssetTraps` (r:1 w:1) + // Proof: `PolkadotXcm::AssetTraps` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn claim_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `90` + // Estimated: `3555` + // Minimum execution time: 14_106_000 picoseconds. + Weight::from_parts(14_535_000, 3555) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + pub fn trap() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_634_000 picoseconds. + Weight::from_parts(2_763_000, 0) + } + // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) + // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn subscribe_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `38` + // Estimated: `3503` + // Minimum execution time: 27_802_000 picoseconds. + Weight::from_parts(28_495_000, 3503) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(3)) + } + // Storage: `PolkadotXcm::VersionNotifyTargets` (r:0 w:1) + // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn unsubscribe_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_683_000 picoseconds. + Weight::from_parts(4_907_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) + } + pub fn burn_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_941_000 picoseconds. + Weight::from_parts(4_080_000, 0) + } + pub fn expect_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_775_000 picoseconds. + Weight::from_parts(2_908_000, 0) + } + pub fn expect_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_743_000 picoseconds. + Weight::from_parts(2_863_000, 0) + } + pub fn expect_error() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_641_000 picoseconds. + Weight::from_parts(2_771_000, 0) + } + pub fn expect_transact_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_838_000 picoseconds. + Weight::from_parts(2_950_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn query_pallet() -> Weight { + // Proof Size summary in bytes: + // Measured: `70` + // Estimated: `3535` + // Minimum execution time: 29_284_000 picoseconds. + Weight::from_parts(29_867_000, 3535) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn expect_pallet() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_734_000 picoseconds. + Weight::from_parts(4_876_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn report_transact_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `70` + // Estimated: `3535` + // Minimum execution time: 26_154_000 picoseconds. + Weight::from_parts(26_851_000, 3535) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn clear_transact_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_678_000 picoseconds. + Weight::from_parts(2_748_000, 0) + } + pub fn set_topic() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_585_000 picoseconds. + Weight::from_parts(2_697_000, 0) + } + pub fn clear_topic() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_576_000 picoseconds. + Weight::from_parts(2_701_000, 0) + } + pub fn set_fees_mode() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_597_000 picoseconds. + Weight::from_parts(2_735_000, 0) + } + pub fn unpaid_execution() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_744_000 picoseconds. + Weight::from_parts(2_809_000, 0) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/xcm_config.rs new file mode 100644 index 00000000000..b3703eee830 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/xcm_config.rs @@ -0,0 +1,280 @@ +// 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 . + +use super::{ + AccountId, AllPalletsWithSystem, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, + Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, TransactionByteFee, WeightToFee, XcmpQueue, + CENTS, +}; +use frame_support::{ + match_types, parameter_types, + traits::{ConstU32, Contains, Everything, Nothing}, +}; +use frame_system::EnsureRoot; +use pallet_xcm::XcmPassthrough; +use parachains_common::{impls::ToStakingPot, xcm_config::ConcreteAssetFromSystem}; +use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; +use xcm::latest::prelude::*; +use xcm_builder::{ + AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, + AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, + DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, IsConcrete, ParentAsSuperuser, + ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, +}; +use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; + +parameter_types! { + pub const KsmRelayLocation: MultiLocation = MultiLocation::parent(); + pub const RelayNetwork: Option = Some(NetworkId::Kusama); + pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); + pub UniversalLocation: InteriorMultiLocation = + X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())); + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; + pub const GovernanceLocation: MultiLocation = MultiLocation::parent(); + pub const FellowshipLocation: MultiLocation = MultiLocation::parent(); +} + +/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// when determining ownership of accounts for asset transacting and when attempting to use XCM +/// `Transact` in order to determine the dispatch Origin. +pub type LocationToAccountId = ( + // The parent (Relay-chain) origin converts to the parent `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, +); + +/// Means for transacting the native currency on this chain. +pub type CurrencyTransactor = CurrencyAdapter< + // Use this currency: + Balances, + // Use this currency when it is a fungible asset matching the given location or name: + IsConcrete, + // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We don't track any teleports of `Balances`. + (), +>; + +/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, +/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can +/// biases the kind of local `Origin` it will become. +pub type XcmOriginToTransactDispatchOrigin = ( + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, + // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when + // recognized. + RelayChainAsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognized. + SiblingParachainAsNative, + // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a + // transaction from the Root origin. + ParentAsSuperuser, + // Native signed account converter; this just converts an `AccountId32` origin into a normal + // `RuntimeOrigin::Signed` origin of the same 32-byte value. + SignedAccountId32AsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, +); + +match_types! { + pub type ParentOrParentsPlurality: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(Plurality { .. }) } + }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; +} +/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly +/// account for proof size weights. +/// +/// Calls that are allowed through this filter must: +/// 1. Have a fixed weight; +/// 2. Cannot lead to another call being made; +/// 3. Have a defined proof size weight, e.g. no unbounded vecs in call parameters. +pub struct SafeCallFilter; +impl Contains for SafeCallFilter { + fn contains(call: &RuntimeCall) -> bool { + #[cfg(feature = "runtime-benchmarks")] + { + if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { + return true + } + } + + matches!( + call, + RuntimeCall::PolkadotXcm(pallet_xcm::Call::force_xcm_version { .. }) | + RuntimeCall::System( + frame_system::Call::set_heap_pages { .. } | + frame_system::Call::set_code { .. } | + frame_system::Call::set_code_without_checks { .. } | + frame_system::Call::kill_prefix { .. }, + ) | RuntimeCall::ParachainSystem(..) | + RuntimeCall::Timestamp(..) | + RuntimeCall::Balances(..) | + RuntimeCall::CollatorSelection( + pallet_collator_selection::Call::set_desired_candidates { .. } | + pallet_collator_selection::Call::set_candidacy_bond { .. } | + pallet_collator_selection::Call::register_as_candidate { .. } | + pallet_collator_selection::Call::leave_intent { .. } | + pallet_collator_selection::Call::set_invulnerables { .. } | + pallet_collator_selection::Call::add_invulnerable { .. } | + pallet_collator_selection::Call::remove_invulnerable { .. }, + ) | RuntimeCall::Session(pallet_session::Call::purge_keys { .. }) | + RuntimeCall::XcmpQueue(..) | + RuntimeCall::MessageQueue(..) + ) + } +} + +pub type Barrier = TrailingSetTopicAsId< + DenyThenTry< + DenyReserveTransferToRelayChain, + ( + // Allow local users to buy weight credit. + TakeWeightCredit, + // Expected responses are OK. + AllowKnownQueryResponses, + WithComputedOrigin< + ( + // If the message is one that immediately attempts to pay for execution, then + // allow it. + AllowTopLevelPaidExecutionFrom, + // Parent and its pluralities (i.e. governance bodies) get free execution. + AllowExplicitUnpaidExecutionFrom, + // Subscriptions for version tracking are OK. + AllowSubscriptionsFrom, + ), + UniversalLocation, + ConstU32<8>, + >, + ), + >, +>; + +/// Cases where a remote origin is accepted as trusted Teleporter for a given asset: +/// - KSM with the parent Relay Chain and sibling parachains. +pub type TrustedTeleporters = ConcreteAssetFromSystem; + +pub struct XcmConfig; +impl xcm_executor::Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = CurrencyTransactor; + type OriginConverter = XcmOriginToTransactDispatchOrigin; + // BridgeHub does not recognize a reserve location for any asset. Users must teleport KSM + // where allowed (e.g. with the Relay Chain). + type IsReserve = (); + type IsTeleporter = TrustedTeleporters; + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = WeightInfoBounds< + crate::weights::xcm::BridgeHubKusamaXcmWeight, + RuntimeCall, + MaxInstructions, + >; + type Trader = + UsingComponents>; + type ResponseHandler = PolkadotXcm; + type AssetTrap = PolkadotXcm; + type AssetClaims = PolkadotXcm; + type SubscriptionService = PolkadotXcm; + type PalletInstancesInfo = AllPalletsWithSystem; + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type AssetLocker = (); + type AssetExchanger = (); + type FeeManager = (); + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = WithOriginFilter; + type SafeCallFilter = SafeCallFilter; + type Aliasers = Nothing; +} + +/// Converts a local signed origin into an XCM multilocation. +/// Forms the basis for local origins sending/executing XCMs. +pub type LocalOriginToLocation = SignedToAccountId32; + +parameter_types! { + /// The asset ID for the asset that we use to pay for message delivery fees. + pub FeeAssetId: AssetId = Concrete(KsmRelayLocation::get()); + /// The base fee for the message delivery fees. + pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); +} + +pub type PriceForParentDelivery = + ExponentialPrice; + +/// The means for routing XCM messages which are not for local execution into the right message +/// queues. +pub type XcmRouter = WithUniqueTopic<( + // Two routers - use UMP to communicate with the relay chain: + cumulus_primitives_utility::ParentAsUmp, + // ..and XCMP to communicate with the sibling chains. + XcmpQueue, +)>; + +impl pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + // We want to disallow users sending (arbitrary) XCMs from this chain. + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + // We support local origins dispatching XCM executions in principle... + type ExecuteXcmOrigin = EnsureXcmOrigin; + // ... but disallow generic XCM execution. As a result only teleports are allowed. + type XcmExecuteFilter = Nothing; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Everything; + type XcmReserveTransferFilter = Nothing; // This parachain is not meant as a reserve location. + type Weigher = WeightInfoBounds< + crate::weights::xcm::BridgeHubKusamaXcmWeight, + RuntimeCall, + MaxInstructions, + >; + type UniversalLocation = UniversalLocation; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type Currency = Balances; + type CurrencyMatcher = (); + type TrustedLockers = (); + type SovereignAccountOf = LocationToAccountId; + type MaxLockers = ConstU32<8>; + type WeightInfo = crate::weights::pallet_xcm::WeightInfo; + type AdminOrigin = EnsureRoot; + type MaxRemoteLockConsumers = ConstU32<0>; + type RemoteLockConsumerIdentifier = (); +} + +impl cumulus_pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type XcmExecutor = XcmExecutor; +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/tests/tests.rs new file mode 100644 index 00000000000..36d8f0846af --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/tests/tests.rs @@ -0,0 +1,51 @@ +// 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 . + +pub use bridge_hub_kusama_runtime::{ + xcm_config::XcmConfig, AllPalletsWithoutSystem, Balances, ExistentialDeposit, ParachainSystem, + PolkadotXcm, Runtime, RuntimeEvent, SessionKeys, +}; +use codec::Decode; +use frame_support::parameter_types; +use parachains_common::{kusama::fee::WeightToFee, AccountId, AuraId}; + +const ALICE: [u8; 32] = [1u8; 32]; + +parameter_types! { + pub CheckingAccount: AccountId = PolkadotXcm::check_account(); +} + +bridge_hub_test_utils::test_cases::include_teleports_for_native_asset_works!( + Runtime, + AllPalletsWithoutSystem, + XcmConfig, + CheckingAccount, + WeightToFee, + ParachainSystem, + bridge_hub_test_utils::CollatorSessionKeys::new( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) } + ), + ExistentialDeposit::get(), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::PolkadotXcm(event)) => Some(event), + _ => None, + } + }), + 1002 +); diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/Cargo.toml b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/Cargo.toml new file mode 100644 index 00000000000..3847a352e07 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/Cargo.toml @@ -0,0 +1,192 @@ +[package] +name = "bridge-hub-polkadot-runtime" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +description = "Polkadot's BridgeHub parachain runtime" +license = "Apache-2.0" + +[build-dependencies] +substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +hex-literal = { version = "0.4.1" } +log = { version = "0.4.20", default-features = false } +scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } +serde = { version = "1.0.188", optional = true, features = ["derive"] } +smallvec = "1.11.0" + +# 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-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-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} + +# 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-core-primitives = { path = "../../../../../polkadot/core-primitives", 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} + +# Cumulus +cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } +cumulus-pallet-dmp-queue = { path = "../../../../pallets/dmp-queue", default-features = false } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } +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 } + +[dev-dependencies] +bridge-hub-test-utils = { path = "../test-utils" } + +[features] +default = [ "std" ] +std = [ + "codec/std", + "cumulus-pallet-aura-ext/std", + "cumulus-pallet-dmp-queue/std", + "cumulus-pallet-parachain-system/std", + "cumulus-pallet-session-benchmarking/std", + "cumulus-pallet-xcm/std", + "cumulus-pallet-xcmp-queue/std", + "cumulus-primitives-core/std", + "cumulus-primitives-utility/std", + "frame-benchmarking?/std", + "frame-executive/std", + "frame-support/std", + "frame-system-benchmarking?/std", + "frame-system-rpc-runtime-api/std", + "frame-system/std", + "frame-try-runtime?/std", + "log/std", + "pallet-aura/std", + "pallet-authorship/std", + "pallet-balances/std", + "pallet-collator-selection/std", + "pallet-message-queue/std", + "pallet-multisig/std", + "pallet-session/std", + "pallet-timestamp/std", + "pallet-transaction-payment-rpc-runtime-api/std", + "pallet-transaction-payment/std", + "pallet-utility/std", + "pallet-xcm-benchmarks?/std", + "pallet-xcm/std", + "parachain-info/std", + "parachains-common/std", + "polkadot-core-primitives/std", + "polkadot-parachain-primitives/std", + "polkadot-runtime-common/std", + "scale-info/std", + "serde", + "sp-api/std", + "sp-block-builder/std", + "sp-consensus-aura/std", + "sp-core/std", + "sp-genesis-builder/std", + "sp-inherents/std", + "sp-io/std", + "sp-offchain/std", + "sp-runtime/std", + "sp-session/std", + "sp-std/std", + "sp-storage/std", + "sp-transaction-pool/std", + "sp-version/std", + "substrate-wasm-builder", + "xcm-builder/std", + "xcm-executor/std", + "xcm/std", +] + +runtime-benchmarks = [ + "cumulus-pallet-dmp-queue/runtime-benchmarks", + "cumulus-pallet-parachain-system/runtime-benchmarks", + "cumulus-pallet-session-benchmarking/runtime-benchmarks", + "cumulus-pallet-xcmp-queue/runtime-benchmarks", + "cumulus-primitives-core/runtime-benchmarks", + "cumulus-primitives-utility/runtime-benchmarks", + "frame-benchmarking/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "frame-system-benchmarking/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", + "pallet-collator-selection/runtime-benchmarks", + "pallet-message-queue/runtime-benchmarks", + "pallet-multisig/runtime-benchmarks", + "pallet-timestamp/runtime-benchmarks", + "pallet-utility/runtime-benchmarks", + "pallet-xcm-benchmarks/runtime-benchmarks", + "pallet-xcm/runtime-benchmarks", + "parachains-common/runtime-benchmarks", + "polkadot-parachain-primitives/runtime-benchmarks", + "polkadot-runtime-common/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", + "xcm-executor/runtime-benchmarks", +] + +try-runtime = [ + "cumulus-pallet-aura-ext/try-runtime", + "cumulus-pallet-dmp-queue/try-runtime", + "cumulus-pallet-parachain-system/try-runtime", + "cumulus-pallet-xcm/try-runtime", + "cumulus-pallet-xcmp-queue/try-runtime", + "frame-executive/try-runtime", + "frame-support/try-runtime", + "frame-system/try-runtime", + "frame-try-runtime/try-runtime", + "pallet-aura/try-runtime", + "pallet-authorship/try-runtime", + "pallet-balances/try-runtime", + "pallet-collator-selection/try-runtime", + "pallet-message-queue/try-runtime", + "pallet-multisig/try-runtime", + "pallet-session/try-runtime", + "pallet-timestamp/try-runtime", + "pallet-transaction-payment/try-runtime", + "pallet-utility/try-runtime", + "pallet-xcm/try-runtime", + "parachain-info/try-runtime", + "polkadot-runtime-common/try-runtime", + "sp-runtime/try-runtime", +] + +experimental = [ "pallet-aura/experimental" ] diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/build.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/build.rs new file mode 100644 index 00000000000..60f8a125129 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/build.rs @@ -0,0 +1,26 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#[cfg(feature = "std")] +fn main() { + substrate_wasm_builder::WasmBuilder::new() + .with_current_project() + .export_heap_base() + .import_memory() + .build() +} + +#[cfg(not(feature = "std"))] +fn main() {} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/lib.rs new file mode 100644 index 00000000000..dee7ec63439 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/lib.rs @@ -0,0 +1,873 @@ +// 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 . + +#![cfg_attr(not(feature = "std"), no_std)] +// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. +#![recursion_limit = "256"] + +// Make the WASM binary available. +#[cfg(feature = "std")] +include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); + +mod weights; +pub mod xcm_config; + +use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; +use sp_api::impl_runtime_apis; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; +use sp_runtime::{ + create_runtime_str, generic, impl_opaque_keys, + traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, +}; + +use sp_std::prelude::*; +#[cfg(feature = "std")] +use sp_version::NativeVersion; +use sp_version::RuntimeVersion; + +use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; +use frame_support::{ + construct_runtime, + dispatch::DispatchClass, + genesis_builder_helper::{build_config, create_default_config}, + parameter_types, + traits::{ + ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, Everything, TransformOrigin, + }, + weights::{ConstantMultiplier, Weight}, + PalletId, +}; +use frame_system::{ + limits::{BlockLength, BlockWeights}, + EnsureRoot, +}; +use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; +pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; +pub use sp_runtime::{MultiAddress, Perbill, Permill}; +use xcm_config::{FellowshipLocation, GovernanceLocation, XcmOriginToTransactDispatchOrigin}; + +#[cfg(any(feature = "std", test))] +pub use sp_runtime::BuildStorage; + +// Polkadot imports +use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; + +use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; + +use parachains_common::{ + impls::DealWithFees, + message_queue::{NarrowOriginToSibling, ParaIdToSibling}, + polkadot::{consensus::*, currency::*, fee::WeightToFee}, + AccountId, Balance, BlockNumber, Hash, Header, Nonce, Signature, AVERAGE_ON_INITIALIZE_RATIO, + HOURS, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO, SLOT_DURATION, +}; +// XCM Imports +use xcm::latest::prelude::BodyId; + +/// The address format for describing accounts. +pub type Address = MultiAddress; + +/// Block type as expected by this runtime. +pub type Block = generic::Block; + +/// A Block signed with a Justification +pub type SignedBlock = generic::SignedBlock; + +/// BlockId type as expected by this runtime. +pub type BlockId = generic::BlockId; + +/// The extension to the basic transaction logic. +pub type TxExtension = ( + frame_system::CheckNonZeroSender, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_transaction_payment::ChargeTransactionPayment, +); + +/// Unchecked extrinsic type as expected by this runtime. +pub type UncheckedExtrinsic = + generic::UncheckedExtrinsic; + +/// Migrations to apply on runtime upgrade. +pub type Migrations = ( + // unreleased + pallet_collator_selection::migration::v1::MigrateToV1, +); + +/// Executive: handles dispatch to the various modules. +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + Migrations, +>; + +impl_opaque_keys! { + pub struct SessionKeys { + pub aura: Aura, + } +} + +#[sp_version::runtime_version] +pub const VERSION: RuntimeVersion = RuntimeVersion { + spec_name: create_runtime_str!("bridge-hub-polkadot"), + impl_name: create_runtime_str!("bridge-hub-polkadot"), + authoring_version: 1, + spec_version: 10000, + impl_version: 0, + apis: RUNTIME_API_VERSIONS, + transaction_version: 2, + state_version: 1, +}; + +/// The version information used to identify this runtime when compiled natively. +#[cfg(feature = "std")] +pub fn native_version() -> NativeVersion { + NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } +} + +parameter_types! { + pub const Version: RuntimeVersion = VERSION; + pub RuntimeBlockLength: BlockLength = + BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() + .base_block(BlockExecutionWeight::get()) + .for_class(DispatchClass::all(), |weights| { + weights.base_extrinsic = ExtrinsicBaseWeight::get(); + }) + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Operational transactions have some extra reserved space, so that they + // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); + pub const SS58Prefix: u8 = 0; +} + +// Configure FRAME pallets to include in runtime. + +impl frame_system::Config for Runtime { + /// The identifier used to distinguish between accounts. + type AccountId = AccountId; + /// The aggregated dispatch type that is available for extrinsics. + type RuntimeCall = RuntimeCall; + /// The lookup mechanism to get account ID from whatever is passed in dispatchers. + type Lookup = AccountIdLookup; + /// The index type for storing how many extrinsics an account has signed. + type Nonce = Nonce; + /// The type for hashing blocks and tries. + type Hash = Hash; + /// The hashing algorithm used. + type Hashing = BlakeTwo256; + /// The block type. + type Block = Block; + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + /// The ubiquitous origin type. + type RuntimeOrigin = RuntimeOrigin; + /// Maximum number of block number to block hash mappings to keep (oldest pruned first). + type BlockHashCount = BlockHashCount; + /// Runtime version. + type Version = Version; + /// Converts a module to an index of this module in the runtime. + type PalletInfo = PalletInfo; + /// The data to be stored in an account. + type AccountData = pallet_balances::AccountData; + /// What to do if a new account is created. + type OnNewAccount = (); + /// What to do if an account is fully reaped from the system. + type OnKilledAccount = (); + /// The weight of database operations that the runtime can invoke. + type DbWeight = RocksDbWeight; + /// The basic call filter to use in dispatchable. + type BaseCallFilter = Everything; + /// Weight information for the extrinsics of this pallet. + type SystemWeightInfo = weights::frame_system::WeightInfo; + /// Block & extrinsics weights: base values and limits. + type BlockWeights = RuntimeBlockWeights; + /// The maximum length of a block (in bytes). + type BlockLength = RuntimeBlockLength; + type SS58Prefix = SS58Prefix; + /// The action to take on a Runtime Upgrade + type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; + type MaxConsumers = ConstU32<16>; +} + +impl pallet_timestamp::Config for Runtime { + /// A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = Aura; + type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>; + type WeightInfo = weights::pallet_timestamp::WeightInfo; +} + +impl pallet_authorship::Config for Runtime { + type FindAuthor = pallet_session::FindAccountFromAuthorIndex; + type EventHandler = (CollatorSelection,); +} + +parameter_types! { + pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT; +} + +impl pallet_balances::Config for Runtime { + /// The type for recording an account's balance. + type Balance = Balance; + type DustRemoval = (); + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = weights::pallet_balances::WeightInfo; + type MaxLocks = ConstU32<50>; + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; + type FreezeIdentifier = (); + type MaxHolds = ConstU32<0>; + type MaxFreezes = ConstU32<0>; +} + +parameter_types! { + /// Relay Chain `TransactionByteFee` / 10 + pub const TransactionByteFee: Balance = MILLICENTS; +} + +impl pallet_transaction_payment::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type OnChargeTransaction = + pallet_transaction_payment::CurrencyAdapter>; + type OperationalFeeMultiplier = ConstU8<5>; + type WeightToFee = WeightToFee; + type LengthToFee = ConstantMultiplier; + type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; +} + +parameter_types! { + pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); + pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); +} + +impl cumulus_pallet_parachain_system::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type OnSystemEvent = (); + type SelfParaId = parachain_info::Pallet; + type OutboundXcmpMessageSource = XcmpQueue; + type DmpQueue = frame_support::traits::EnqueueWithOrigin; + type ReservedDmpWeight = ReservedDmpWeight; + type XcmpMessageHandler = XcmpQueue; + type ReservedXcmpWeight = ReservedXcmpWeight; + type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases; + type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook< + Runtime, + RELAY_CHAIN_SLOT_DURATION_MILLIS, + BLOCK_PROCESSING_VELOCITY, + UNINCLUDED_SEGMENT_CAPACITY, + >; +} + +parameter_types! { + pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block; +} + +impl pallet_message_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type WeightInfo = weights::pallet_message_queue::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor< + cumulus_primitives_core::AggregateMessageOrigin, + >; + #[cfg(not(feature = "runtime-benchmarks"))] + type MessageProcessor = xcm_builder::ProcessXcmMessage< + AggregateMessageOrigin, + xcm_executor::XcmExecutor, + RuntimeCall, + >; + type Size = u32; + // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin: + type QueueChangeHandler = NarrowOriginToSibling; + type QueuePausedQuery = NarrowOriginToSibling; + type HeapSize = sp_core::ConstU32<{ 64 * 1024 }>; + type MaxStale = sp_core::ConstU32<8>; + type ServiceWeight = MessageQueueServiceWeight; +} + +impl parachain_info::Config for Runtime {} + +impl cumulus_pallet_aura_ext::Config for Runtime {} + +parameter_types! { + // Fellows pluralistic body. + pub const FellowsBodyId: BodyId = BodyId::Technical; +} + +/// Privileged origin that represents Root or Fellows. +pub type RootOrFellows = EitherOfDiverse< + EnsureRoot, + EnsureXcm>, +>; + +impl cumulus_pallet_xcmp_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type ChannelInfo = ParachainSystem; + type VersionWrapper = PolkadotXcm; + // Enqueue XCMP messages from siblings for later processing. + type XcmpQueue = TransformOrigin; + type MaxInboundSuspended = sp_core::ConstU32<1_000>; + type ControllerOrigin = RootOrFellows; + type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; + type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; + type PriceForSiblingDelivery = NoPriceForMessageDelivery; +} + +parameter_types! { + pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent; +} + +impl cumulus_pallet_dmp_queue::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_dmp_queue::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type DmpSink = frame_support::traits::EnqueueWithOrigin; +} + +pub const PERIOD: u32 = 6 * HOURS; +pub const OFFSET: u32 = 0; + +impl pallet_session::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type ValidatorId = ::AccountId; + // we don't have stash and controller, thus we don't need the convert as well. + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ShouldEndSession = pallet_session::PeriodicSessions, ConstU32>; + type NextSessionRotation = pallet_session::PeriodicSessions, ConstU32>; + type SessionManager = CollatorSelection; + // Essentially just Aura, but let's be pedantic. + type SessionHandler = ::KeyTypeIdProviders; + type Keys = SessionKeys; + type WeightInfo = weights::pallet_session::WeightInfo; +} + +impl pallet_aura::Config for Runtime { + type AuthorityId = AuraId; + type DisabledValidators = (); + type MaxAuthorities = ConstU32<100_000>; + type AllowMultipleBlocksPerSlot = ConstBool; + #[cfg(feature = "experimental")] + type SlotDuration = pallet_aura::MinimumPeriodTimesTwo; +} + +parameter_types! { + pub const PotId: PalletId = PalletId(*b"PotStake"); + pub const SessionLength: BlockNumber = 6 * HOURS; + // StakingAdmin pluralistic body. + pub const StakingAdminBodyId: BodyId = BodyId::Defense; +} + +/// We allow root, the StakingAdmin to execute privileged collator selection operations. +pub type CollatorSelectionUpdateOrigin = EitherOfDiverse< + EnsureRoot, + EnsureXcm>, +>; + +impl pallet_collator_selection::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type UpdateOrigin = CollatorSelectionUpdateOrigin; + type PotId = PotId; + type MaxCandidates = ConstU32<100>; + type MinEligibleCollators = ConstU32<4>; + type MaxInvulnerables = ConstU32<20>; + // should be a multiple of session or things will get inconsistent + type KickThreshold = ConstU32; + type ValidatorId = ::AccountId; + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ValidatorRegistration = Session; + type WeightInfo = weights::pallet_collator_selection::WeightInfo; +} + +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); + // Additional storage item size of 32 bytes. + pub const DepositFactor: Balance = deposit(0, 32); +} + +impl pallet_multisig::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type Currency = Balances; + type DepositBase = DepositBase; + type DepositFactor = DepositFactor; + type MaxSignatories = ConstU32<100>; + type WeightInfo = weights::pallet_multisig::WeightInfo; +} + +impl pallet_utility::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type PalletsOrigin = OriginCaller; + type WeightInfo = weights::pallet_utility::WeightInfo; +} + +// Create the runtime by composing the FRAME pallets that were previously configured. +construct_runtime!( + pub enum Runtime + { + // System support stuff. + System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, + ParachainSystem: cumulus_pallet_parachain_system::{ + Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned, + } = 1, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2, + ParachainInfo: parachain_info::{Pallet, Storage, Config} = 3, + + // Monetary stuff. + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, + TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 11, + + // Collator support. The order of these 4 are important and shall not change. + Authorship: pallet_authorship::{Pallet, Storage} = 20, + CollatorSelection: pallet_collator_selection::{Pallet, Call, Storage, Event, Config} = 21, + Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, + Aura: pallet_aura::{Pallet, Storage, Config} = 23, + AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config} = 24, + + // XCM helpers. + XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, + PolkadotXcm: pallet_xcm::{Pallet, Call, Event, Origin, Config} = 31, + CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, + DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, + MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event} = 34, + + // Handy utilities. + Utility: pallet_utility::{Pallet, Call, Event} = 40, + Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 41, + } +); + +#[cfg(feature = "runtime-benchmarks")] +mod benches { + frame_benchmarking::define_benchmarks!( + [frame_system, SystemBench::] + [pallet_balances, Balances] + [pallet_message_queue, MessageQueue] + [pallet_multisig, Multisig] + [pallet_session, SessionBench::] + [pallet_utility, Utility] + [pallet_timestamp, Timestamp] + [pallet_collator_selection, CollatorSelection] + [cumulus_pallet_parachain_system, ParachainSystem] + [cumulus_pallet_xcmp_queue, XcmpQueue] + [cumulus_pallet_dmp_queue, DmpQueue] + // XCM + [pallet_xcm, PalletXcmExtrinsicsBenchmark::] + // NOTE: Make sure you point to the individual modules below. + [pallet_xcm_benchmarks::fungible, XcmBalances] + [pallet_xcm_benchmarks::generic, XcmGeneric] + ); +} + +impl_runtime_apis! { + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + + fn authorities() -> Vec { + Aura::authorities().into_inner() + } + } + + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + + fn metadata_at_version(version: u32) -> Option { + Runtime::metadata_at_version(version) + } + + fn metadata_versions() -> sp_std::vec::Vec { + Runtime::metadata_versions() + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi + for Runtime + { + fn query_call_info( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::RuntimeDispatchInfo { + TransactionPayment::query_call_info(call, len) + } + fn query_call_fee_details( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_call_fee_details(call, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { + ParachainSystem::collect_collation_info(header) + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { + let weight = Executive::try_runtime_upgrade(checks).unwrap(); + (weight, RuntimeBlockWeights::get().max_block) + } + + fn execute_block( + block: Block, + state_root_check: bool, + signature_check: bool, + select: frame_try_runtime::TryStateSelect, + ) -> Weight { + // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to + // have a backtrace here. + Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap() + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; + + // This is defined once again in dispatch_benchmark, because list_benchmarks! + // and add_benchmarks! are macros exported by define_benchmarks! macros and those types + // are referenced in that call. + type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::; + type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::; + + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsWithSystem::storage_info(); + (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; + use sp_storage::TrackedStorageKey; + + use frame_system_benchmarking::Pallet as SystemBench; + impl frame_system_benchmarking::Config for Runtime { + fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); + Ok(()) + } + + fn verify_set_code() { + System::assert_last_event(cumulus_pallet_parachain_system::Event::::ValidationFunctionStored.into()); + } + } + + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + impl cumulus_pallet_session_benchmarking::Config for Runtime {} + + use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; + impl pallet_xcm::benchmarking::Config for Runtime { + fn reachable_dest() -> Option { + Some(Parent.into()) + } + + fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + // Relay/native token can be teleported between BH and Relay. + Some(( + MultiAsset { + fun: Fungible(EXISTENTIAL_DEPOSIT), + id: Concrete(Parent.into()) + }, + Parent.into(), + )) + } + + fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + // Reserve transfers are disabled on BH. + None + } + } + + use xcm::latest::prelude::*; + use xcm_config::DotRelayLocation; + + parameter_types! { + pub ExistentialDepositMultiAsset: Option = Some(( + xcm_config::DotRelayLocation::get(), + ExistentialDeposit::get() + ).into()); + } + + impl pallet_xcm_benchmarks::Config for Runtime { + type XcmConfig = xcm_config::XcmConfig; + type AccountIdConverter = xcm_config::LocationToAccountId; + type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< + xcm_config::XcmConfig, + ExistentialDepositMultiAsset, + xcm_config::PriceForParentDelivery, + >; + fn valid_destination() -> Result { + Ok(DotRelayLocation::get()) + } + fn worst_case_holding(_depositable_count: u32) -> MultiAssets { + // just concrete assets according to relay chain. + let assets: Vec = vec![ + MultiAsset { + id: Concrete(DotRelayLocation::get()), + fun: Fungible(1_000_000 * UNITS), + } + ]; + assets.into() + } + } + + parameter_types! { + pub const TrustedTeleporter: Option<(MultiLocation, MultiAsset)> = Some(( + DotRelayLocation::get(), + MultiAsset { fun: Fungible(UNITS), id: Concrete(DotRelayLocation::get()) }, + )); + pub const CheckedAccount: Option<(AccountId, xcm_builder::MintLocation)> = None; + pub const TrustedReserve: Option<(MultiLocation, MultiAsset)> = None; + } + + impl pallet_xcm_benchmarks::fungible::Config for Runtime { + type TransactAsset = Balances; + + type CheckedAccount = CheckedAccount; + type TrustedTeleporter = TrustedTeleporter; + type TrustedReserve = TrustedReserve; + + fn get_multi_asset() -> MultiAsset { + MultiAsset { + id: Concrete(DotRelayLocation::get()), + fun: Fungible(UNITS), + } + } + } + + impl pallet_xcm_benchmarks::generic::Config for Runtime { + type TransactAsset = Balances; + type RuntimeCall = RuntimeCall; + + fn worst_case_response() -> (u64, Response) { + (0u64, Response::Version(Default::default())) + } + + fn worst_case_asset_exchange() -> Result<(MultiAssets, MultiAssets), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn universal_alias() -> Result<(MultiLocation, Junction), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn transact_origin_and_runtime_call() -> Result<(MultiLocation, RuntimeCall), BenchmarkError> { + Ok((DotRelayLocation::get(), frame_system::Call::remark_with_event { remark: vec![] }.into())) + } + + fn subscribe_origin() -> Result { + Ok(DotRelayLocation::get()) + } + + fn claimable_asset() -> Result<(MultiLocation, MultiLocation, MultiAssets), BenchmarkError> { + let origin = DotRelayLocation::get(); + let assets: MultiAssets = (Concrete(DotRelayLocation::get()), 1_000 * UNITS).into(); + let ticket = MultiLocation { parents: 0, interior: Here }; + Ok((origin, ticket, assets)) + } + + fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn export_message_origin_and_destination( + ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { + Err(BenchmarkError::Skip) + } + + fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { + Err(BenchmarkError::Skip) + } + } + + type XcmBalances = pallet_xcm_benchmarks::fungible::Pallet::; + type XcmGeneric = pallet_xcm_benchmarks::generic::Pallet::; + + let whitelist: Vec = vec![ + // Block Number + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), + // Total Issuance + hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), + // Execution Phase + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), + // Event Count + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), + // System Events + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), + ]; + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + add_benchmarks!(params, batches); + + Ok(batches) + } + } + + impl sp_genesis_builder::GenesisBuilder for Runtime { + fn create_default_config() -> Vec { + create_default_config::() + } + + fn build_config(config: Vec) -> sp_genesis_builder::Result { + build_config::(config) + } + } +} + +cumulus_pallet_parachain_system::register_validate_block! { + Runtime = Runtime, + BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/block_weights.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/block_weights.rs new file mode 100644 index 00000000000..e7fdb2aae2a --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/block_weights.rs @@ -0,0 +1,53 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; + + parameter_types! { + /// Importing a block with 0 Extrinsics. + pub const BlockExecutionWeight: Weight = + Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); + } + + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; + + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::BlockExecutionWeight::get(); + + // At least 100 µs. + assert!( + w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, + "Weight should be at least 100 µs." + ); + // At most 50 ms. + assert!( + w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, + "Weight should be at most 50 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_dmp_queue.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_dmp_queue.rs new file mode 100644 index 00000000000..cc41dcd6cbb --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_dmp_queue.rs @@ -0,0 +1,131 @@ +// 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 . + +//! Autogenerated weights for `cumulus_pallet_dmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-10-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=cumulus_pallet_dmp_queue +// --chain=asset-hub-kusama-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_dmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_dmp_queue::WeightInfo for WeightInfo { + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65696` + // Estimated: `69161` + // Minimum execution time: 124_651_000 picoseconds. + Weight::from_parts(127_857_000, 0) + .saturating_add(Weight::from_parts(0, 69161)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65659` + // Estimated: `69124` + // Minimum execution time: 65_684_000 picoseconds. + Weight::from_parts(68_039_000, 0) + .saturating_add(Weight::from_parts(0, 69124)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_overweight_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65726` + // Estimated: `69191` + // Minimum execution time: 117_657_000 picoseconds. + Weight::from_parts(122_035_000, 0) + .saturating_add(Weight::from_parts(0, 69191)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + fn on_idle_overweight_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65689` + // Estimated: `69154` + // Minimum execution time: 59_799_000 picoseconds. + Weight::from_parts(61_354_000, 0) + .saturating_add(Weight::from_parts(0, 69154)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_parachain_system.rs new file mode 100644 index 00000000000..4b0cface146 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_parachain_system.rs @@ -0,0 +1,80 @@ +// 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. + +//! Autogenerated weights for `cumulus_pallet_parachain_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-03-28, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `i9`, CPU: `13th Gen Intel(R) Core(TM) i9-13900K` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-polkadot-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --chain +// bridge-hub-polkadot-dev +// --pallet +// cumulus_pallet_parachain_system +// --extrinsic +// * +// --execution +// wasm +// --wasm-execution +// compiled +// --output +// parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights +// --steps +// 50 +// --repeat +// 20 + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_parachain_system`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_parachain_system::WeightInfo for WeightInfo { + /// Storage: ParachainSystem LastDmqMqcHead (r:1 w:1) + /// Proof Skipped: ParachainSystem LastDmqMqcHead (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem ReservedDmpWeightOverride (r:1 w:0) + /// Proof Skipped: ParachainSystem ReservedDmpWeightOverride (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: ParachainSystem ProcessedDownwardMessages (r:0 w:1) + /// Proof Skipped: ParachainSystem ProcessedDownwardMessages (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: MessageQueue Pages (r:0 w:16) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + /// The range of component `n` is `[0, 1000]`. + fn enqueue_inbound_downward_messages(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `12` + // Estimated: `8013` + // Minimum execution time: 1_686_000 picoseconds. + Weight::from_parts(1_729_000, 0) + .saturating_add(Weight::from_parts(0, 8013)) + // Standard Error: 19_565 + .saturating_add(Weight::from_parts(24_482_828, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs new file mode 100644 index 00000000000..ac6ad093faf --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs @@ -0,0 +1,148 @@ +// 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. + +//! Autogenerated weights for `cumulus_pallet_xcmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-09-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `Olivers-MacBook-Pro.local`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --pallet +// cumulus-pallet-xcmp-queue +// --chain +// bridge-hub-polkadot-dev +// --output +// cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs +// --extrinsic +// + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_xcmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_xcmp_queue::WeightInfo for WeightInfo { + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:1) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn set_config_with_u32() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `1561` + // Minimum execution time: 6_000_000 picoseconds. + Weight::from_parts(6_000_000, 0) + .saturating_add(Weight::from_parts(0, 1561)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:0) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn enqueue_xcmp_message() -> Weight { + // Proof Size summary in bytes: + // Measured: `82` + // Estimated: `3517` + // Minimum execution time: 15_000_000 picoseconds. + Weight::from_parts(15_000_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn suspend_channel() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `1561` + // Minimum execution time: 3_000_000 picoseconds. + Weight::from_parts(4_000_000, 0) + .saturating_add(Weight::from_parts(0, 1561)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn resume_channel() -> Weight { + // Proof Size summary in bytes: + // Measured: `111` + // Estimated: `1596` + // Minimum execution time: 4_000_000 picoseconds. + Weight::from_parts(5_000_000, 0) + .saturating_add(Weight::from_parts(0, 1596)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn take_first_concatenated_xcm() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 44_000_000 picoseconds. + Weight::from_parts(45_000_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Storage: `XcmpQueue::InboundXcmpMessages` (r:1 w:1) + /// Proof: `XcmpQueue::InboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:0) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65711` + // Estimated: `69176` + // Minimum execution time: 61_000_000 picoseconds. + Weight::from_parts(64_000_000, 0) + .saturating_add(Weight::from_parts(0, 69176)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65710` + // Estimated: `69175` + // Minimum execution time: 42_000_000 picoseconds. + Weight::from_parts(44_000_000, 0) + .saturating_add(Weight::from_parts(0, 69175)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/extrinsic_weights.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/extrinsic_weights.rs new file mode 100644 index 00000000000..1a4adb968bb --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/extrinsic_weights.rs @@ -0,0 +1,53 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; + + parameter_types! { + /// Executing a NO-OP `System::remarks` Extrinsic. + pub const ExtrinsicBaseWeight: Weight = + Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); + } + + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; + + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::ExtrinsicBaseWeight::get(); + + // At least 10 µs. + assert!( + w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, + "Weight should be at least 10 µs." + ); + // At most 1 ms. + assert!( + w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/frame_system.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/frame_system.rs new file mode 100644 index 00000000000..8676be67b2f --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/frame_system.rs @@ -0,0 +1,154 @@ +// 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. + +//! Autogenerated weights for `frame_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=frame_system +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `frame_system`. +pub struct WeightInfo(PhantomData); +impl frame_system::WeightInfo for WeightInfo { + /// The range of component `b` is `[0, 3932160]`. + fn remark(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_047_000 picoseconds. + Weight::from_parts(2_087_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 0 + .saturating_add(Weight::from_parts(390, 0).saturating_mul(b.into())) + } + /// The range of component `b` is `[0, 3932160]`. + fn remark_with_event(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_335_000 picoseconds. + Weight::from_parts(7_507_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 2 + .saturating_add(Weight::from_parts(1_751, 0).saturating_mul(b.into())) + } + /// Storage: `System::Digest` (r:1 w:1) + /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) + /// Proof: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) + fn set_heap_pages() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `1485` + // Minimum execution time: 3_673_000 picoseconds. + Weight::from_parts(3_953_000, 0) + .saturating_add(Weight::from_parts(0, 1485)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ParachainSystem::ValidationData` (r:1 w:0) + /// Proof: `ParachainSystem::ValidationData` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpgradeRestrictionSignal` (r:1 w:0) + /// Proof: `ParachainSystem::UpgradeRestrictionSignal` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingValidationCode` (r:1 w:1) + /// Proof: `ParachainSystem::PendingValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::NewValidationCode` (r:0 w:1) + /// Proof: `ParachainSystem::NewValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::DidSetValidationCode` (r:0 w:1) + /// Proof: `ParachainSystem::DidSetValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn set_code() -> Weight { + // Proof Size summary in bytes: + // Measured: `119` + // Estimated: `1604` + // Minimum execution time: 98_791_992_000 picoseconds. + Weight::from_parts(101_799_041_000, 0) + .saturating_add(Weight::from_parts(0, 1604)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `i` is `[0, 1000]`. + fn set_storage(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_144_000 picoseconds. + Weight::from_parts(2_206_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 2_254 + .saturating_add(Weight::from_parts(740_881, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `i` is `[0, 1000]`. + fn kill_storage(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_117_000 picoseconds. + Weight::from_parts(2_192_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_024 + .saturating_add(Weight::from_parts(558_397, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `p` is `[0, 1000]`. + fn kill_prefix(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `68 + p * (69 ±0)` + // Estimated: `66 + p * (70 ±0)` + // Minimum execution time: 3_907_000 picoseconds. + Weight::from_parts(4_050_000, 0) + .saturating_add(Weight::from_parts(0, 66)) + // Standard Error: 2_228 + .saturating_add(Weight::from_parts(1_212_760, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) + .saturating_add(Weight::from_parts(0, 70).saturating_mul(p.into())) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/mod.rs new file mode 100644 index 00000000000..36733d6d4a6 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/mod.rs @@ -0,0 +1,41 @@ +// 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. + +//! Expose the auto generated weight files. + +pub mod block_weights; +pub mod cumulus_pallet_dmp_queue; +pub mod cumulus_pallet_parachain_system; +pub mod cumulus_pallet_xcmp_queue; +pub mod extrinsic_weights; +pub mod frame_system; +pub mod pallet_balances; +pub mod pallet_collator_selection; +pub mod pallet_message_queue; +pub mod pallet_multisig; +pub mod pallet_session; +pub mod pallet_timestamp; +pub mod pallet_utility; +pub mod pallet_xcm; +pub mod paritydb_weights; +pub mod rocksdb_weights; +pub mod xcm; + +pub use block_weights::constants::BlockExecutionWeight; +pub use extrinsic_weights::constants::ExtrinsicBaseWeight; +pub use paritydb_weights::constants::ParityDbWeight; +pub use rocksdb_weights::constants::RocksDbWeight; diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_balances.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_balances.rs new file mode 100644 index 00000000000..b95ea83585f --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_balances.rs @@ -0,0 +1,152 @@ +// 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. + +//! Autogenerated weights for `pallet_balances` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_balances +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_balances`. +pub struct WeightInfo(PhantomData); +impl pallet_balances::WeightInfo for WeightInfo { + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_allow_death() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 54_518_000 picoseconds. + Weight::from_parts(55_244_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_keep_alive() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 40_152_000 picoseconds. + Weight::from_parts(41_084_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_set_balance_creating() -> Weight { + // Proof Size summary in bytes: + // Measured: `174` + // Estimated: `3593` + // Minimum execution time: 15_234_000 picoseconds. + Weight::from_parts(15_576_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_set_balance_killing() -> Weight { + // Proof Size summary in bytes: + // Measured: `174` + // Estimated: `3593` + // Minimum execution time: 22_173_000 picoseconds. + Weight::from_parts(22_964_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `6196` + // Minimum execution time: 56_636_000 picoseconds. + Weight::from_parts(57_316_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_all() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 50_829_000 picoseconds. + Weight::from_parts(51_264_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_unreserve() -> Weight { + // Proof Size summary in bytes: + // Measured: `174` + // Estimated: `3593` + // Minimum execution time: 17_887_000 picoseconds. + Weight::from_parts(18_365_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:999 w:999) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `u` is `[1, 1000]`. + fn upgrade_accounts(u: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + u * (136 ±0)` + // Estimated: `990 + u * (2603 ±0)` + // Minimum execution time: 16_754_000 picoseconds. + Weight::from_parts(17_237_000, 0) + .saturating_add(Weight::from_parts(0, 990)) + // Standard Error: 15_088 + .saturating_add(Weight::from_parts(15_392_959, 0).saturating_mul(u.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(u.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(u.into()))) + .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_collator_selection.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_collator_selection.rs new file mode 100644 index 00000000000..f7c78f7db82 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_collator_selection.rs @@ -0,0 +1,248 @@ +// 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. + +//! Autogenerated weights for `pallet_collator_selection` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_collator_selection +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_collator_selection`. +pub struct WeightInfo(PhantomData); +impl pallet_collator_selection::WeightInfo for WeightInfo { + /// Storage: `Session::NextKeys` (r:20 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::Invulnerables` (r:0 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// The range of component `b` is `[1, 20]`. + fn set_invulnerables(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `196 + b * (79 ±0)` + // Estimated: `1187 + b * (2555 ±0)` + // Minimum execution time: 14_735_000 picoseconds. + Weight::from_parts(11_846_916, 0) + .saturating_add(Weight::from_parts(0, 1187)) + // Standard Error: 8_592 + .saturating_add(Weight::from_parts(3_270_517, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(b.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(Weight::from_parts(0, 2555).saturating_mul(b.into())) + } + /// Storage: `Session::NextKeys` (r:1 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `b` is `[1, 19]`. + /// The range of component `c` is `[1, 99]`. + fn add_invulnerable(b: u32, c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `757 + b * (32 ±0) + c * (53 ±0)` + // Estimated: `6287 + b * (37 ±0) + c * (53 ±0)` + // Minimum execution time: 48_332_000 picoseconds. + Weight::from_parts(46_158_586, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 13_938 + .saturating_add(Weight::from_parts(174_493, 0).saturating_mul(b.into())) + // Standard Error: 2_642 + .saturating_add(Weight::from_parts(196_691, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 37).saturating_mul(b.into())) + .saturating_add(Weight::from_parts(0, 53).saturating_mul(c.into())) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:0) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// The range of component `b` is `[5, 20]`. + fn remove_invulnerable(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `82 + b * (32 ±0)` + // Estimated: `6287` + // Minimum execution time: 15_323_000 picoseconds. + Weight::from_parts(15_016_873, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_970 + .saturating_add(Weight::from_parts(199_160, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::DesiredCandidates` (r:0 w:1) + /// Proof: `CollatorSelection::DesiredCandidates` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn set_desired_candidates() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_393_000 picoseconds. + Weight::from_parts(7_723_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::CandidacyBond` (r:0 w:1) + /// Proof: `CollatorSelection::CandidacyBond` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + fn set_candidacy_bond(_c: u32, _k: u32) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_426_000 picoseconds. + Weight::from_parts(7_783_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::DesiredCandidates` (r:1 w:0) + /// Proof: `CollatorSelection::DesiredCandidates` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `Session::NextKeys` (r:1 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::CandidacyBond` (r:1 w:0) + /// Proof: `CollatorSelection::CandidacyBond` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// The range of component `c` is `[1, 99]`. + fn register_as_candidate(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `740 + c * (52 ±0)` + // Estimated: `6287 + c * (54 ±0)` + // Minimum execution time: 41_040_000 picoseconds. + Weight::from_parts(43_902_200, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_360 + .saturating_add(Weight::from_parts(211_897, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(2)) + .saturating_add(Weight::from_parts(0, 54).saturating_mul(c.into())) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// The range of component `c` is `[3, 100]`. + fn leave_intent(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `334 + c * (49 ±0)` + // Estimated: `6287` + // Minimum execution time: 33_429_000 picoseconds. + Weight::from_parts(36_413_045, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_947 + .saturating_add(Weight::from_parts(177_461, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + fn update_bond(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 34_814_000 picoseconds. + Weight::from_parts(36_371_520, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_391 + .saturating_add(Weight::from_parts(201_700, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + fn take_candidate_slot(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 34_814_000 picoseconds. + Weight::from_parts(36_371_520, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_391 + .saturating_add(Weight::from_parts(201_700, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `System::BlockWeight` (r:1 w:1) + /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + fn note_author() -> Weight { + // Proof Size summary in bytes: + // Measured: `155` + // Estimated: `6196` + // Minimum execution time: 45_300_000 picoseconds. + Weight::from_parts(46_280_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:0) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:100 w:0) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `System::BlockWeight` (r:1 w:1) + /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:97 w:97) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `r` is `[1, 100]`. + /// The range of component `c` is `[1, 100]`. + fn new_session(r: u32, c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `2263 + c * (97 ±0) + r * (115 ±0)` + // Estimated: `6287 + c * (2519 ±0) + r * (2603 ±0)` + // Minimum execution time: 17_524_000 picoseconds. + Weight::from_parts(17_590_000, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 354_091 + .saturating_add(Weight::from_parts(15_829_767, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(c.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 2519).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(0, 2603).saturating_mul(r.into())) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_message_queue.rs new file mode 100644 index 00000000000..38cc21cfad9 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_message_queue.rs @@ -0,0 +1,179 @@ +// 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. + +//! Autogenerated weights for `pallet_message_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-03-24, STEPS: `2`, REPEAT: `1`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `i9`, CPU: `13th Gen Intel(R) Core(TM) i9-13900K` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-polkadot-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --chain +// bridge-hub-polkadot-dev +// --pallet +// pallet_message_queue +// --extrinsic +// * +// --execution +// wasm +// --wasm-execution +// compiled +// --output +// parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `pallet_message_queue`. +pub struct WeightInfo(PhantomData); +impl pallet_message_queue::WeightInfo for WeightInfo { + /// Storage: MessageQueue ServiceHead (r:1 w:0) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: MessageQueue BookStateFor (r:2 w:2) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn ready_ring_knit() -> Weight { + // Proof Size summary in bytes: + // Measured: `189` + // Estimated: `7534` + // Minimum execution time: 38_974_000 picoseconds. + Weight::from_parts(38_974_000, 0) + .saturating_add(Weight::from_parts(0, 7534)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:2 w:2) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + fn ready_ring_unknit() -> Weight { + // Proof Size summary in bytes: + // Measured: `184` + // Estimated: `7534` + // Minimum execution time: 11_194_000 picoseconds. + Weight::from_parts(11_194_000, 0) + .saturating_add(Weight::from_parts(0, 7534)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn service_queue_base() -> Weight { + // Proof Size summary in bytes: + // Measured: `6` + // Estimated: `3517` + // Minimum execution time: 5_196_000 picoseconds. + Weight::from_parts(5_196_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn service_page_base_completion() -> Weight { + // Proof Size summary in bytes: + // Measured: `72` + // Estimated: `69050` + // Minimum execution time: 6_408_000 picoseconds. + Weight::from_parts(6_408_000, 0) + .saturating_add(Weight::from_parts(0, 69050)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn service_page_base_no_completion() -> Weight { + // Proof Size summary in bytes: + // Measured: `72` + // Estimated: `69050` + // Minimum execution time: 6_354_000 picoseconds. + Weight::from_parts(6_354_000, 0) + .saturating_add(Weight::from_parts(0, 69050)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn service_page_item() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 63_855_000 picoseconds. + Weight::from_parts(63_855_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: MessageQueue BookStateFor (r:1 w:0) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn bump_service_head() -> Weight { + // Proof Size summary in bytes: + // Measured: `99` + // Estimated: `5007` + // Minimum execution time: 6_764_000 picoseconds. + Weight::from_parts(6_764_000, 0) + .saturating_add(Weight::from_parts(0, 5007)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn reap_page() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 40_293_000 picoseconds. + Weight::from_parts(40_293_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn execute_overweight_page_removed() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 50_903_000 picoseconds. + Weight::from_parts(50_903_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn execute_overweight_page_updated() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 96_657_000 picoseconds. + Weight::from_parts(96_657_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_multisig.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_multisig.rs new file mode 100644 index 00000000000..44f3da351f6 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_multisig.rs @@ -0,0 +1,164 @@ +// 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. + +//! Autogenerated weights for `pallet_multisig` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_multisig +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_multisig`. +pub struct WeightInfo(PhantomData); +impl pallet_multisig::WeightInfo for WeightInfo { + /// The range of component `z` is `[0, 10000]`. + fn as_multi_threshold_1(z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 13_284_000 picoseconds. + Weight::from_parts(14_761_699, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 7 + .saturating_add(Weight::from_parts(491, 0).saturating_mul(z.into())) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_create(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `263 + s * (2 ±0)` + // Estimated: `6811` + // Minimum execution time: 44_043_000 picoseconds. + Weight::from_parts(32_303_705, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_280 + .saturating_add(Weight::from_parts(133_233, 0).saturating_mul(s.into())) + // Standard Error: 12 + .saturating_add(Weight::from_parts(1_467, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[3, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_approve(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `6811` + // Minimum execution time: 28_494_000 picoseconds. + Weight::from_parts(19_053_318, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 791 + .saturating_add(Weight::from_parts(112_935, 0).saturating_mul(s.into())) + // Standard Error: 7 + .saturating_add(Weight::from_parts(1_427, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_complete(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `388 + s * (33 ±0)` + // Estimated: `6811` + // Minimum execution time: 49_505_000 picoseconds. + Weight::from_parts(36_407_515, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_595 + .saturating_add(Weight::from_parts(166_201, 0).saturating_mul(s.into())) + // Standard Error: 15 + .saturating_add(Weight::from_parts(1_481, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_create(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `263 + s * (2 ±0)` + // Estimated: `6811` + // Minimum execution time: 30_977_000 picoseconds. + Weight::from_parts(32_222_158, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_872 + .saturating_add(Weight::from_parts(125_197, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_approve(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `282` + // Estimated: `6811` + // Minimum execution time: 17_351_000 picoseconds. + Weight::from_parts(18_130_793, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 902 + .saturating_add(Weight::from_parts(109_485, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn cancel_as_multi(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `454 + s * (1 ±0)` + // Estimated: `6811` + // Minimum execution time: 31_554_000 picoseconds. + Weight::from_parts(33_116_785, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 882 + .saturating_add(Weight::from_parts(119_357, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_session.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_session.rs new file mode 100644 index 00000000000..86ecc787e97 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_session.rs @@ -0,0 +1,80 @@ +// 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. + +//! Autogenerated weights for `pallet_session` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_session +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_session`. +pub struct WeightInfo(PhantomData); +impl pallet_session::WeightInfo for WeightInfo { + /// Storage: `Session::NextKeys` (r:1 w:1) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Session::KeyOwner` (r:1 w:1) + /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn set_keys() -> Weight { + // Proof Size summary in bytes: + // Measured: `297` + // Estimated: `3762` + // Minimum execution time: 16_905_000 picoseconds. + Weight::from_parts(17_310_000, 0) + .saturating_add(Weight::from_parts(0, 3762)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Session::NextKeys` (r:1 w:1) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Session::KeyOwner` (r:0 w:1) + /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn purge_keys() -> Weight { + // Proof Size summary in bytes: + // Measured: `279` + // Estimated: `3744` + // Minimum execution time: 12_511_000 picoseconds. + Weight::from_parts(13_055_000, 0) + .saturating_add(Weight::from_parts(0, 3744)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_timestamp.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_timestamp.rs new file mode 100644 index 00000000000..a0984d72aac --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_timestamp.rs @@ -0,0 +1,74 @@ +// 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. + +//! Autogenerated weights for `pallet_timestamp` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_timestamp +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_timestamp`. +pub struct WeightInfo(PhantomData); +impl pallet_timestamp::WeightInfo for WeightInfo { + /// Storage: `Timestamp::Now` (r:1 w:1) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `Aura::CurrentSlot` (r:1 w:0) + /// Proof: `Aura::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + fn set() -> Weight { + // Proof Size summary in bytes: + // Measured: `49` + // Estimated: `1493` + // Minimum execution time: 7_675_000 picoseconds. + Weight::from_parts(7_947_000, 0) + .saturating_add(Weight::from_parts(0, 1493)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn on_finalize() -> Weight { + // Proof Size summary in bytes: + // Measured: `57` + // Estimated: `0` + // Minimum execution time: 3_342_000 picoseconds. + Weight::from_parts(3_443_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_utility.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_utility.rs new file mode 100644 index 00000000000..2f04094b347 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_utility.rs @@ -0,0 +1,101 @@ +// 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. + +//! Autogenerated weights for `pallet_utility` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=bridge-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_utility +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_utility`. +pub struct WeightInfo(PhantomData); +impl pallet_utility::WeightInfo for WeightInfo { + /// The range of component `c` is `[0, 1000]`. + fn batch(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_810_000 picoseconds. + Weight::from_parts(6_290_871, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_678 + .saturating_add(Weight::from_parts(5_193_419, 0).saturating_mul(c.into())) + } + fn as_derivative() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_753_000 picoseconds. + Weight::from_parts(4_890_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// The range of component `c` is `[0, 1000]`. + fn batch_all(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_873_000 picoseconds. + Weight::from_parts(9_780_422, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 2_035 + .saturating_add(Weight::from_parts(5_473_943, 0).saturating_mul(c.into())) + } + fn dispatch_as() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 8_443_000 picoseconds. + Weight::from_parts(8_904_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// The range of component `c` is `[0, 1000]`. + fn force_batch(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_820_000 picoseconds. + Weight::from_parts(8_206_355, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_327 + .saturating_add(Weight::from_parts(5_187_839, 0).saturating_mul(c.into())) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_xcm.rs new file mode 100644 index 00000000000..b73c009cbda --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/pallet_xcm.rs @@ -0,0 +1,323 @@ +// 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 . + +//! Autogenerated weights for `pallet_xcm` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-11-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_xcm +// --chain=bridge-hub-polkadot-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_xcm`. +pub struct WeightInfo(PhantomData); +impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn send() -> Weight { + // Proof Size summary in bytes: + // Measured: `38` + // Estimated: `3503` + // Minimum execution time: 22_442_000 picoseconds. + Weight::from_parts(23_346_000, 0) + .saturating_add(Weight::from_parts(0, 3503)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn teleport_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `32` + // Estimated: `1489` + // Minimum execution time: 19_655_000 picoseconds. + Weight::from_parts(20_086_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + .saturating_add(T::DbWeight::get().reads(1)) + } + /// Storage: `Benchmark::Override` (r:0 w:0) + /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn reserve_transfer_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 18_446_744_073_709_551_000 picoseconds. + Weight::from_parts(18_446_744_073_709_551_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: `Benchmark::Override` (r:0 w:0) + /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn execute() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 18_446_744_073_709_551_000 picoseconds. + Weight::from_parts(18_446_744_073_709_551_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: `PolkadotXcm::SupportedVersion` (r:0 w:1) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_xcm_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_858_000 picoseconds. + Weight::from_parts(7_225_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:0 w:1) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn force_default_xcm_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_099_000 picoseconds. + Weight::from_parts(2_190_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_subscribe_version_notify() -> Weight { + // Proof Size summary in bytes: + // Measured: `38` + // Estimated: `3503` + // Minimum execution time: 27_073_000 picoseconds. + Weight::from_parts(27_584_000, 0) + .saturating_add(Weight::from_parts(0, 3503)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_unsubscribe_version_notify() -> Weight { + // Proof Size summary in bytes: + // Measured: `255` + // Estimated: `3720` + // Minimum execution time: 29_949_000 picoseconds. + Weight::from_parts(30_760_000, 0) + .saturating_add(Weight::from_parts(0, 3720)) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PolkadotXcm::XcmExecutionSuspended` (r:0 w:1) + /// Proof: `PolkadotXcm::XcmExecutionSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn force_suspension() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_192_000 picoseconds. + Weight::from_parts(2_276_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::SupportedVersion` (r:4 w:2) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_supported_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `95` + // Estimated: `10985` + // Minimum execution time: 14_681_000 picoseconds. + Weight::from_parts(15_131_000, 0) + .saturating_add(Weight::from_parts(0, 10985)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_version_notifiers() -> Weight { + // Proof Size summary in bytes: + // Measured: `99` + // Estimated: `10989` + // Minimum execution time: 14_523_000 picoseconds. + Weight::from_parts(15_113_000, 0) + .saturating_add(Weight::from_parts(0, 10989)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:5 w:0) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn already_notified_target() -> Weight { + // Proof Size summary in bytes: + // Measured: `106` + // Estimated: `13471` + // Minimum execution time: 15_989_000 picoseconds. + Weight::from_parts(16_518_000, 0) + .saturating_add(Weight::from_parts(0, 13471)) + .saturating_add(T::DbWeight::get().reads(5)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:2 w:1) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn notify_current_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `106` + // Estimated: `6046` + // Minimum execution time: 25_127_000 picoseconds. + Weight::from_parts(25_773_000, 0) + .saturating_add(Weight::from_parts(0, 6046)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:3 w:0) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn notify_target_migration_fail() -> Weight { + // Proof Size summary in bytes: + // Measured: `136` + // Estimated: `8551` + // Minimum execution time: 8_352_000 picoseconds. + Weight::from_parts(8_592_000, 0) + .saturating_add(Weight::from_parts(0, 8551)) + .saturating_add(T::DbWeight::get().reads(3)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_version_notify_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `106` + // Estimated: `10996` + // Minimum execution time: 14_658_000 picoseconds. + Weight::from_parts(15_345_000, 0) + .saturating_add(Weight::from_parts(0, 10996)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn migrate_and_notify_old_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `112` + // Estimated: `11002` + // Minimum execution time: 31_478_000 picoseconds. + Weight::from_parts(32_669_000, 0) + .saturating_add(Weight::from_parts(0, 11002)) + .saturating_add(T::DbWeight::get().reads(10)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn new_query() -> Weight { + // Proof Size summary in bytes: + // Measured: `32` + // Estimated: `1517` + // Minimum execution time: 4_066_000 picoseconds. + Weight::from_parts(4_267_000, 0) + .saturating_add(Weight::from_parts(0, 1517)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::Queries` (r:1 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn take_response() -> Weight { + // Proof Size summary in bytes: + // Measured: `7669` + // Estimated: `11134` + // Minimum execution time: 25_260_000 picoseconds. + Weight::from_parts(25_570_000, 0) + .saturating_add(Weight::from_parts(0, 11134)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/paritydb_weights.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/paritydb_weights.rs new file mode 100644 index 00000000000..25679703831 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/paritydb_weights.rs @@ -0,0 +1,63 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; + + parameter_types! { + /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights + /// are available for brave runtime engineers who may want to try this out as default. + pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + }; + } + + #[cfg(test)] + mod test_db_weights { + use super::constants::ParityDbWeight as W; + use frame_support::weights::constants; + + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Write weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/rocksdb_weights.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/rocksdb_weights.rs new file mode 100644 index 00000000000..3dd817aa6f1 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/rocksdb_weights.rs @@ -0,0 +1,63 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; + + parameter_types! { + /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout + /// the runtime. + pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + }; + } + + #[cfg(test)] + mod test_db_weights { + use super::constants::RocksDbWeight as W; + use frame_support::weights::constants; + + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Write weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/mod.rs new file mode 100644 index 00000000000..33a48f36812 --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/mod.rs @@ -0,0 +1,244 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +mod pallet_xcm_benchmarks_fungible; +mod pallet_xcm_benchmarks_generic; + +use crate::{xcm_config::MaxAssetsIntoHolding, Runtime}; +use frame_support::weights::Weight; +use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; +use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; +use sp_std::prelude::*; +use xcm::{latest::prelude::*, DoubleEncoded}; + +trait WeighMultiAssets { + fn weigh_multi_assets(&self, weight: Weight) -> Weight; +} + +const MAX_ASSETS: u64 = 100; + +impl WeighMultiAssets for MultiAssetFilter { + fn weigh_multi_assets(&self, weight: Weight) -> Weight { + match self { + Self::Definite(assets) => weight.saturating_mul(assets.inner().iter().count() as u64), + Self::Wild(asset) => match asset { + All => weight.saturating_mul(MAX_ASSETS), + AllOf { fun, .. } => match fun { + WildFungibility::Fungible => weight, + // Magic number 2 has to do with the fact that we could have up to 2 times + // MaxAssetsIntoHolding in the worst-case scenario. + WildFungibility::NonFungible => + weight.saturating_mul((MaxAssetsIntoHolding::get() * 2) as u64), + }, + AllCounted(count) => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), + AllOfCounted { count, .. } => weight.saturating_mul(MAX_ASSETS.min(*count as u64)), + }, + } + } +} + +impl WeighMultiAssets for MultiAssets { + fn weigh_multi_assets(&self, weight: Weight) -> Weight { + weight.saturating_mul(self.inner().iter().count() as u64) + } +} + +pub struct BridgeHubPolkadotXcmWeight(core::marker::PhantomData); +impl XcmWeightInfo for BridgeHubPolkadotXcmWeight { + fn withdraw_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::withdraw_asset()) + } + fn reserve_asset_deposited(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::reserve_asset_deposited()) + } + fn receive_teleported_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::receive_teleported_asset()) + } + fn query_response( + _query_id: &u64, + _response: &Response, + _max_weight: &Weight, + _querier: &Option, + ) -> Weight { + XcmGeneric::::query_response() + } + fn transfer_asset(assets: &MultiAssets, _dest: &MultiLocation) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::transfer_asset()) + } + fn transfer_reserve_asset( + assets: &MultiAssets, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::transfer_reserve_asset()) + } + fn transact( + _origin_type: &OriginKind, + _require_weight_at_most: &Weight, + _call: &DoubleEncoded, + ) -> Weight { + XcmGeneric::::transact() + } + fn hrmp_new_channel_open_request( + _sender: &u32, + _max_message_size: &u32, + _max_capacity: &u32, + ) -> Weight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX + } + fn hrmp_channel_accepted(_recipient: &u32) -> Weight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX + } + fn hrmp_channel_closing(_initiator: &u32, _sender: &u32, _recipient: &u32) -> Weight { + // XCM Executor does not currently support HRMP channel operations + Weight::MAX + } + fn clear_origin() -> Weight { + XcmGeneric::::clear_origin() + } + fn descend_origin(_who: &InteriorMultiLocation) -> Weight { + XcmGeneric::::descend_origin() + } + fn report_error(_query_response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::report_error() + } + + fn deposit_asset(assets: &MultiAssetFilter, _dest: &MultiLocation) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::deposit_asset()) + } + fn deposit_reserve_asset( + assets: &MultiAssetFilter, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::deposit_reserve_asset()) + } + fn exchange_asset(_give: &MultiAssetFilter, _receive: &MultiAssets, _maximal: &bool) -> Weight { + Weight::MAX + } + fn initiate_reserve_withdraw( + assets: &MultiAssetFilter, + _reserve: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::initiate_reserve_withdraw()) + } + fn initiate_teleport( + assets: &MultiAssetFilter, + _dest: &MultiLocation, + _xcm: &Xcm<()>, + ) -> Weight { + assets.weigh_multi_assets(XcmFungibleWeight::::initiate_teleport()) + } + fn report_holding(_response_info: &QueryResponseInfo, _assets: &MultiAssetFilter) -> Weight { + XcmGeneric::::report_holding() + } + fn buy_execution(_fees: &MultiAsset, _weight_limit: &WeightLimit) -> Weight { + XcmGeneric::::buy_execution() + } + fn refund_surplus() -> Weight { + XcmGeneric::::refund_surplus() + } + fn set_error_handler(_xcm: &Xcm) -> Weight { + XcmGeneric::::set_error_handler() + } + fn set_appendix(_xcm: &Xcm) -> Weight { + XcmGeneric::::set_appendix() + } + fn clear_error() -> Weight { + XcmGeneric::::clear_error() + } + fn claim_asset(_assets: &MultiAssets, _ticket: &MultiLocation) -> Weight { + XcmGeneric::::claim_asset() + } + fn trap(_code: &u64) -> Weight { + XcmGeneric::::trap() + } + fn subscribe_version(_query_id: &QueryId, _max_response_weight: &Weight) -> Weight { + XcmGeneric::::subscribe_version() + } + fn unsubscribe_version() -> Weight { + XcmGeneric::::unsubscribe_version() + } + fn burn_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + } + fn expect_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + } + fn expect_origin(_origin: &Option) -> Weight { + XcmGeneric::::expect_origin() + } + fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { + XcmGeneric::::expect_error() + } + fn expect_transact_status(_transact_status: &MaybeErrorCode) -> Weight { + XcmGeneric::::expect_transact_status() + } + fn query_pallet(_module_name: &Vec, _response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::query_pallet() + } + fn expect_pallet( + _index: &u32, + _name: &Vec, + _module_name: &Vec, + _crate_major: &u32, + _min_crate_minor: &u32, + ) -> Weight { + XcmGeneric::::expect_pallet() + } + fn report_transact_status(_response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::report_transact_status() + } + fn clear_transact_status() -> Weight { + XcmGeneric::::clear_transact_status() + } + fn universal_origin(_: &Junction) -> Weight { + Weight::MAX + } + fn export_message(_: &NetworkId, _: &Junctions, _: &Xcm<()>) -> Weight { + Weight::MAX + } + fn lock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn unlock_asset(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn note_unlockable(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn request_unlock(_: &MultiAsset, _: &MultiLocation) -> Weight { + Weight::MAX + } + fn set_fees_mode(_: &bool) -> Weight { + XcmGeneric::::set_fees_mode() + } + fn set_topic(_topic: &[u8; 32]) -> Weight { + XcmGeneric::::set_topic() + } + fn clear_topic() -> Weight { + XcmGeneric::::clear_topic() + } + fn alias_origin(_: &MultiLocation) -> Weight { + // XCM Executor does not currently support alias origin operations + Weight::MAX + } + fn unpaid_execution(_: &WeightLimit, _: &Option) -> Weight { + XcmGeneric::::unpaid_execution() + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs new file mode 100644 index 00000000000..814c416bd4c --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -0,0 +1,187 @@ +// 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. + +//! Autogenerated weights for `pallet_xcm_benchmarks::fungible` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-09-28, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-nbnwcyh-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-polkadot-dev"), DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_xcm_benchmarks::fungible +// --chain=bridge-hub-polkadot-dev +// --header=./cumulus/file_header.txt +// --template=./cumulus/templates/xcm-bench-template.hbs +// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weights for `pallet_xcm_benchmarks::fungible`. +pub struct WeightInfo(PhantomData); +impl WeightInfo { + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + pub fn withdraw_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `101` + // Estimated: `3593` + // Minimum execution time: 24_237_000 picoseconds. + Weight::from_parts(24_697_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + // Storage: `System::Account` (r:2 w:2) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + pub fn transfer_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `153` + // Estimated: `6196` + // Minimum execution time: 52_269_000 picoseconds. + Weight::from_parts(53_848_000, 6196) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + // Storage: `System::Account` (r:2 w:2) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn transfer_reserve_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `223` + // Estimated: `6196` + // Minimum execution time: 77_611_000 picoseconds. + Weight::from_parts(82_634_000, 6196) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(4)) + } + // Storage: `Benchmark::Override` (r:0 w:0) + // Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn reserve_asset_deposited() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 18_446_744_073_709_551_000 picoseconds. + Weight::from_parts(18_446_744_073_709_551_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_reserve_withdraw() -> Weight { + // Proof Size summary in bytes: + // Measured: `70` + // Estimated: `3535` + // Minimum execution time: 29_506_000 picoseconds. + Weight::from_parts(30_269_000, 3535) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn receive_teleported_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_541_000 picoseconds. + Weight::from_parts(3_629_000, 0) + } + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + pub fn deposit_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `52` + // Estimated: `3593` + // Minimum execution time: 25_651_000 picoseconds. + Weight::from_parts(26_078_000, 3593) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + // Storage: `System::Account` (r:1 w:1) + // Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn deposit_reserve_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `122` + // Estimated: `3593` + // Minimum execution time: 52_050_000 picoseconds. + Weight::from_parts(53_293_000, 3593) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(3)) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn initiate_teleport() -> Weight { + // Proof Size summary in bytes: + // Measured: `70` + // Estimated: `3535` + // Minimum execution time: 30_009_000 picoseconds. + Weight::from_parts(30_540_000, 3535) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_generic.rs new file mode 100644 index 00000000000..9a039a6d63b --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -0,0 +1,328 @@ +// 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. + +//! Autogenerated weights for `pallet_xcm_benchmarks::generic` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: , WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-polkadot-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --template=./templates/xcm-bench-template.hbs +// --chain=bridge-hub-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_xcm_benchmarks::generic +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/weights/xcm/pallet_xcm_benchmarks_generic.rs + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weights for `pallet_xcm_benchmarks::generic`. +pub struct WeightInfo(PhantomData); +impl WeightInfo { + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn report_holding() -> Weight { + // Proof Size summary in bytes: + // Measured: `70` + // Estimated: `3535` + // Minimum execution time: 30_923_000 picoseconds. + Weight::from_parts(31_653_000, 3535) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn buy_execution() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_837_000 picoseconds. + Weight::from_parts(2_932_000, 0) + } + // Storage: `PolkadotXcm::Queries` (r:1 w:0) + // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn query_response() -> Weight { + // Proof Size summary in bytes: + // Measured: `32` + // Estimated: `3497` + // Minimum execution time: 10_319_000 picoseconds. + Weight::from_parts(10_614_000, 3497) + .saturating_add(T::DbWeight::get().reads(1)) + } + pub fn transact() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 11_466_000 picoseconds. + Weight::from_parts(12_005_000, 0) + } + pub fn refund_surplus() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_039_000 picoseconds. + Weight::from_parts(3_125_000, 0) + } + pub fn set_error_handler() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_655_000 picoseconds. + Weight::from_parts(2_717_000, 0) + } + pub fn set_appendix() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_655_000 picoseconds. + Weight::from_parts(2_695_000, 0) + } + pub fn clear_error() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_612_000 picoseconds. + Weight::from_parts(2_685_000, 0) + } + pub fn descend_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_286_000 picoseconds. + Weight::from_parts(3_425_000, 0) + } + pub fn clear_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_613_000 picoseconds. + Weight::from_parts(2_699_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn report_error() -> Weight { + // Proof Size summary in bytes: + // Measured: `70` + // Estimated: `3535` + // Minimum execution time: 24_616_000 picoseconds. + Weight::from_parts(25_147_000, 3535) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + // Storage: `PolkadotXcm::AssetTraps` (r:1 w:1) + // Proof: `PolkadotXcm::AssetTraps` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn claim_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `90` + // Estimated: `3555` + // Minimum execution time: 14_511_000 picoseconds. + Weight::from_parts(14_831_000, 3555) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + pub fn trap() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_640_000 picoseconds. + Weight::from_parts(2_702_000, 0) + } + // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) + // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn subscribe_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `38` + // Estimated: `3503` + // Minimum execution time: 26_044_000 picoseconds. + Weight::from_parts(26_561_000, 3503) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(3)) + } + // Storage: `PolkadotXcm::VersionNotifyTargets` (r:0 w:1) + // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + pub fn unsubscribe_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_568_000 picoseconds. + Weight::from_parts(4_764_000, 0) + .saturating_add(T::DbWeight::get().writes(1)) + } + pub fn burn_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_953_000 picoseconds. + Weight::from_parts(4_079_000, 0) + } + pub fn expect_asset() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_793_000 picoseconds. + Weight::from_parts(2_914_000, 0) + } + pub fn expect_origin() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_719_000 picoseconds. + Weight::from_parts(2_829_000, 0) + } + pub fn expect_error() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_710_000 picoseconds. + Weight::from_parts(2_824_000, 0) + } + pub fn expect_transact_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_941_000 picoseconds. + Weight::from_parts(3_201_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn query_pallet() -> Weight { + // Proof Size summary in bytes: + // Measured: `70` + // Estimated: `3535` + // Minimum execution time: 28_080_000 picoseconds. + Weight::from_parts(28_920_000, 3535) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn expect_pallet() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_752_000 picoseconds. + Weight::from_parts(4_982_000, 0) + } + // Storage: `ParachainInfo::ParachainId` (r:1 w:0) + // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + // Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + // Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + // Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + // Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + // Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + pub fn report_transact_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `70` + // Estimated: `3535` + // Minimum execution time: 24_810_000 picoseconds. + Weight::from_parts(25_270_000, 3535) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + pub fn clear_transact_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_676_000 picoseconds. + Weight::from_parts(2_780_000, 0) + } + pub fn set_topic() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_624_000 picoseconds. + Weight::from_parts(2_710_000, 0) + } + pub fn clear_topic() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_611_000 picoseconds. + Weight::from_parts(2_707_000, 0) + } + pub fn set_fees_mode() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_653_000 picoseconds. + Weight::from_parts(2_740_000, 0) + } + pub fn unpaid_execution() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_821_000 picoseconds. + Weight::from_parts(2_874_000, 0) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/xcm_config.rs new file mode 100644 index 00000000000..61eee1c4c5a --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/xcm_config.rs @@ -0,0 +1,284 @@ +// 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 . + +use super::{ + AccountId, AllPalletsWithSystem, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, + Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, TransactionByteFee, WeightToFee, XcmpQueue, + CENTS, +}; +use frame_support::{ + match_types, parameter_types, + traits::{ConstU32, Contains, Everything, Nothing}, +}; +use frame_system::EnsureRoot; +use pallet_xcm::XcmPassthrough; +use parachains_common::{impls::ToStakingPot, xcm_config::ConcreteAssetFromSystem}; +use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; +use xcm::latest::prelude::*; +use xcm_builder::{ + AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, + AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, + DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, IsConcrete, ParentAsSuperuser, + ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, +}; +use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; + +parameter_types! { + pub const DotRelayLocation: MultiLocation = MultiLocation::parent(); + pub const RelayNetwork: Option = Some(NetworkId::Polkadot); + pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); + pub UniversalLocation: InteriorMultiLocation = + X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())); + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; + pub FellowshipLocation: MultiLocation = MultiLocation::new(1, Parachain(1001)); + pub const GovernanceLocation: MultiLocation = MultiLocation::parent(); +} + +/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// when determining ownership of accounts for asset transacting and when attempting to use XCM +/// `Transact` in order to determine the dispatch Origin. +pub type LocationToAccountId = ( + // The parent (Relay-chain) origin converts to the parent `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, +); + +/// Means for transacting the native currency on this chain. +pub type CurrencyTransactor = CurrencyAdapter< + // Use this currency: + Balances, + // Use this currency when it is a fungible asset matching the given location or name: + IsConcrete, + // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We don't track any teleports of `Balances`. + (), +>; + +/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, +/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can +/// biases the kind of local `Origin` it will become. +pub type XcmOriginToTransactDispatchOrigin = ( + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, + // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when + // recognized. + RelayChainAsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognized. + SiblingParachainAsNative, + // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a + // transaction from the Root origin. + ParentAsSuperuser, + // Native signed account converter; this just converts an `AccountId32` origin into a normal + // `RuntimeOrigin::Signed` origin of the same 32-byte value. + SignedAccountId32AsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, +); + +match_types! { + pub type ParentOrParentsPlurality: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(Plurality { .. }) } + }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; + pub type FellowsPlurality: impl Contains = { + MultiLocation { parents: 1, interior: X2(Parachain(1001), Plurality { id: BodyId::Technical, ..}) } + }; +} +/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly +/// account for proof size weights. +/// +/// Calls that are allowed through this filter must: +/// 1. Have a fixed weight; +/// 2. Cannot lead to another call being made; +/// 3. Have a defined proof size weight, e.g. no unbounded vecs in call parameters. +pub struct SafeCallFilter; +impl Contains for SafeCallFilter { + fn contains(call: &RuntimeCall) -> bool { + #[cfg(feature = "runtime-benchmarks")] + { + if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { + return true + } + } + + matches!( + call, + RuntimeCall::PolkadotXcm(pallet_xcm::Call::force_xcm_version { .. }) | + RuntimeCall::System( + frame_system::Call::set_heap_pages { .. } | + frame_system::Call::set_code { .. } | + frame_system::Call::set_code_without_checks { .. } | + frame_system::Call::kill_prefix { .. }, + ) | RuntimeCall::ParachainSystem(..) | + RuntimeCall::Timestamp(..) | + RuntimeCall::Balances(..) | + RuntimeCall::CollatorSelection( + pallet_collator_selection::Call::set_desired_candidates { .. } | + pallet_collator_selection::Call::set_candidacy_bond { .. } | + pallet_collator_selection::Call::register_as_candidate { .. } | + pallet_collator_selection::Call::leave_intent { .. } | + pallet_collator_selection::Call::set_invulnerables { .. } | + pallet_collator_selection::Call::add_invulnerable { .. } | + pallet_collator_selection::Call::remove_invulnerable { .. }, + ) | RuntimeCall::Session(pallet_session::Call::purge_keys { .. }) | + RuntimeCall::XcmpQueue(..) | + RuntimeCall::MessageQueue(..) + ) + } +} + +pub type Barrier = TrailingSetTopicAsId< + DenyThenTry< + DenyReserveTransferToRelayChain, + ( + // Allow local users to buy weight credit. + TakeWeightCredit, + // Expected responses are OK. + AllowKnownQueryResponses, + WithComputedOrigin< + ( + // If the message is one that immediately attempts to pay for execution, then + // allow it. + AllowTopLevelPaidExecutionFrom, + // Parent, its pluralities (i.e. governance bodies), and the Fellows plurality + // get free execution. + AllowExplicitUnpaidExecutionFrom<(ParentOrParentsPlurality, FellowsPlurality)>, + // Subscriptions for version tracking are OK. + AllowSubscriptionsFrom, + ), + UniversalLocation, + ConstU32<8>, + >, + ), + >, +>; + +/// Cases where a remote origin is accepted as trusted Teleporter for a given asset: +/// - DOT with the parent Relay Chain and sibling parachains. +pub type TrustedTeleporters = ConcreteAssetFromSystem; + +pub struct XcmConfig; +impl xcm_executor::Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = CurrencyTransactor; + type OriginConverter = XcmOriginToTransactDispatchOrigin; + // BridgeHub does not recognize a reserve location for any asset. Users must teleport DOT + // where allowed (e.g. with the Relay Chain). + type IsReserve = (); + type IsTeleporter = TrustedTeleporters; + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = WeightInfoBounds< + crate::weights::xcm::BridgeHubPolkadotXcmWeight, + RuntimeCall, + MaxInstructions, + >; + type Trader = + UsingComponents>; + type ResponseHandler = PolkadotXcm; + type AssetTrap = PolkadotXcm; + type AssetClaims = PolkadotXcm; + type SubscriptionService = PolkadotXcm; + type PalletInstancesInfo = AllPalletsWithSystem; + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type AssetLocker = (); + type AssetExchanger = (); + type FeeManager = (); + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = WithOriginFilter; + type SafeCallFilter = SafeCallFilter; + type Aliasers = Nothing; +} + +/// Converts a local signed origin into an XCM multilocation. +/// Forms the basis for local origins sending/executing XCMs. +pub type LocalOriginToLocation = SignedToAccountId32; + +parameter_types! { + /// The asset ID for the asset that we use to pay for message delivery fees. + pub FeeAssetId: AssetId = Concrete(DotRelayLocation::get()); + /// The base fee for the message delivery fees. + pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); +} + +pub type PriceForParentDelivery = + ExponentialPrice; + +/// The means for routing XCM messages which are not for local execution into the right message +/// queues. +pub type XcmRouter = WithUniqueTopic<( + // Two routers - use UMP to communicate with the relay chain: + cumulus_primitives_utility::ParentAsUmp, + // ..and XCMP to communicate with the sibling chains. + XcmpQueue, +)>; + +impl pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + // We want to disallow users sending (arbitrary) XCMs from this chain. + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + // We support local origins dispatching XCM executions in principle... + type ExecuteXcmOrigin = EnsureXcmOrigin; + // ... but disallow generic XCM execution. As a result only teleports are allowed. + type XcmExecuteFilter = Nothing; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Everything; + type XcmReserveTransferFilter = Nothing; // This parachain is not meant as a reserve location. + type Weigher = WeightInfoBounds< + crate::weights::xcm::BridgeHubPolkadotXcmWeight, + RuntimeCall, + MaxInstructions, + >; + type UniversalLocation = UniversalLocation; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type Currency = Balances; + type CurrencyMatcher = (); + type TrustedLockers = (); + type SovereignAccountOf = LocationToAccountId; + type MaxLockers = ConstU32<8>; + type WeightInfo = crate::weights::pallet_xcm::WeightInfo; + type AdminOrigin = EnsureRoot; + type MaxRemoteLockConsumers = ConstU32<0>; + type RemoteLockConsumerIdentifier = (); +} + +impl cumulus_pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type XcmExecutor = XcmExecutor; +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/tests/tests.rs new file mode 100644 index 00000000000..3156a5fe68e --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/tests/tests.rs @@ -0,0 +1,51 @@ +// 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 . + +pub use bridge_hub_polkadot_runtime::{ + xcm_config::XcmConfig, AllPalletsWithoutSystem, Balances, ExistentialDeposit, ParachainSystem, + PolkadotXcm, Runtime, RuntimeEvent, SessionKeys, +}; +use codec::Decode; +use frame_support::parameter_types; +use parachains_common::{polkadot::fee::WeightToFee, AccountId, AuraId}; + +const ALICE: [u8; 32] = [1u8; 32]; + +parameter_types! { + pub CheckingAccount: AccountId = PolkadotXcm::check_account(); +} + +bridge_hub_test_utils::test_cases::include_teleports_for_native_asset_works!( + Runtime, + AllPalletsWithoutSystem, + XcmConfig, + CheckingAccount, + WeightToFee, + ParachainSystem, + bridge_hub_test_utils::CollatorSessionKeys::new( + AccountId::from(ALICE), + AccountId::from(ALICE), + SessionKeys { aura: AuraId::from(sp_core::sr25519::Public::from_raw(ALICE)) } + ), + ExistentialDeposit::get(), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::PolkadotXcm(event)) => Some(event), + _ => None, + } + }), + 1002 +); 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 f8b279e3e3d..42ea63bfea5 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true description = "Rococo's BridgeHub parachain runtime" license = "Apache-2.0" -[lints] -workspace = true - [build-dependencies] substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } @@ -21,7 +18,7 @@ log = { version = "0.4.20", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = [ "derive", ] } -serde = { version = "1.0.193", optional = true, features = ["derive"] } +serde = { version = "1.0.188", optional = true, features = ["derive"] } smallvec = "1.11.0" # Substrate @@ -87,13 +84,11 @@ parachains-common = { path = "../../../common", default-features = false } # Bridges bp-asset-hub-rococo = { path = "../../../../../bridges/primitives/chain-asset-hub-rococo", default-features = false } bp-asset-hub-westend = { path = "../../../../../bridges/primitives/chain-asset-hub-westend", default-features = false } -bp-bridge-hub-polkadot = { path = "../../../../../bridges/primitives/chain-bridge-hub-polkadot", default-features = false } bp-bridge-hub-rococo = { path = "../../../../../bridges/primitives/chain-bridge-hub-rococo", default-features = false } bp-bridge-hub-westend = { path = "../../../../../bridges/primitives/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/primitives/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 } @@ -103,7 +98,6 @@ pallet-bridge-grandpa = { path = "../../../../../bridges/modules/grandpa", defau 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 } [dev-dependencies] @@ -115,17 +109,15 @@ bridge-runtime-common = { path = "../../../../../bridges/bin/runtime-common", fe sp-keyring = { path = "../../../../../substrate/primitives/keyring" } [features] -default = ["std"] +default = [ "std" ] std = [ "bp-asset-hub-rococo/std", "bp-asset-hub-westend/std", - "bp-bridge-hub-polkadot/std", "bp-bridge-hub-rococo/std", "bp-bridge-hub-westend/std", "bp-header-chain/std", "bp-messages/std", "bp-parachains/std", - "bp-polkadot-bulletin/std", "bp-polkadot-core/std", "bp-relayers/std", "bp-rococo/std", @@ -164,7 +156,6 @@ std = [ "pallet-transaction-payment/std", "pallet-utility/std", "pallet-xcm-benchmarks?/std", - "pallet-xcm-bridge-hub/std", "pallet-xcm/std", "parachain-info/std", "parachains-common/std", @@ -216,7 +207,6 @@ runtime-benchmarks = [ "pallet-timestamp/runtime-benchmarks", "pallet-utility/runtime-benchmarks", "pallet-xcm-benchmarks/runtime-benchmarks", - "pallet-xcm-bridge-hub/runtime-benchmarks", "pallet-xcm/runtime-benchmarks", "parachains-common/runtime-benchmarks", "polkadot-parachain-primitives/runtime-benchmarks", @@ -249,16 +239,15 @@ try-runtime = [ "pallet-timestamp/try-runtime", "pallet-transaction-payment/try-runtime", "pallet-utility/try-runtime", - "pallet-xcm-bridge-hub/try-runtime", "pallet-xcm/try-runtime", "parachain-info/try-runtime", "polkadot-runtime-common/try-runtime", "sp-runtime/try-runtime", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] # A feature that should be enabled when the runtime should be built for on-chain # deployment. This will disable stuff that shouldn't be part of the on-chain wasm # to make it smaller like logging for example. -on-chain-release-build = ["sp-api/disable-logging"] +on-chain-release-build = [ "sp-api/disable-logging" ] diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_common_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_common_config.rs index 93ef9470363..8153e52beac 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_common_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_common_config.rs @@ -21,20 +21,15 @@ //! For example, the messaging pallet needs to know the sending and receiving chains, but the //! GRANDPA tracking pallet only needs to be aware of one chain. -use super::{ - weights, AccountId, Balance, Balances, BlockNumber, Runtime, RuntimeEvent, RuntimeOrigin, -}; +use super::{weights, AccountId, Balance, Balances, BlockNumber, Runtime, RuntimeEvent}; use bp_parachains::SingleParaStoredHeaderDataBuilder; -use bp_runtime::UnderlyingChainProvider; -use bridge_runtime_common::messages::ThisChainWithMessages; use frame_support::{parameter_types, traits::ConstU32}; -use sp_runtime::RuntimeDebug; parameter_types! { pub const RelayChainHeadersToKeep: u32 = 1024; pub const ParachainHeadsToKeep: u32 = 64; - pub const WestendBridgeParachainPalletName: &'static str = bp_westend::PARAS_PALLET_NAME; + pub const WestendBridgeParachainPalletName: &'static str = "Paras"; pub const MaxWestendParaHeadDataSize: u32 = bp_westend::MAX_NESTED_PARACHAIN_HEAD_DATA_SIZE; pub storage RequiredStakeForStakeAndSlash: Balance = 1_000_000; @@ -83,33 +78,3 @@ impl pallet_bridge_relayers::Config for Runtime { >; type WeightInfo = weights::pallet_bridge_relayers::WeightInfo; } - -/// Add GRANDPA bridge pallet to track Rococo Bulletin chain. -pub type BridgeGrandpaRococoBulletinInstance = pallet_bridge_grandpa::Instance4; -impl pallet_bridge_grandpa::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type BridgedChain = bp_polkadot_bulletin::PolkadotBulletin; - type MaxFreeMandatoryHeadersPerBlock = ConstU32<4>; - type HeadersToKeep = RelayChainHeadersToKeep; - // Technically this is incorrect - we have two pallet instances and ideally we shall - // benchmark every instance separately. But the benchmarking engine has a flaw - it - // messes with components. E.g. in Kusama maximal validators count is 1024 and in - // Bulletin chain it is 100. But benchmarking engine runs Bulletin benchmarks using - // components range, computed for Kusama => it causes an error. - // - // In practice, however, GRANDPA pallet works the same way for all bridged chains, so - // weights are also the same for both bridges. - type WeightInfo = weights::pallet_bridge_grandpa::WeightInfo; -} - -/// BridgeHubRococo chain from message lane point of view. -#[derive(RuntimeDebug, Clone, Copy)] -pub struct BridgeHubRococo; - -impl UnderlyingChainProvider for BridgeHubRococo { - type Chain = bp_bridge_hub_rococo::BridgeHubRococo; -} - -impl ThisChainWithMessages for BridgeHubRococo { - type RuntimeOrigin = RuntimeOrigin; -} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs deleted file mode 100644 index 8c7611bc619..00000000000 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs +++ /dev/null @@ -1,292 +0,0 @@ -// 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 . - -//! Bridge definitions used on BridgeHubRococo for bridging to Rococo Bulletin. -//! -//! Rococo Bulletin chain will be the 1:1 copy of the Polkadot Bulletin, so we -//! are reusing Polkadot Bulletin chain primitives everywhere here. - -use crate::{ - bridge_common_config::{BridgeGrandpaRococoBulletinInstance, BridgeHubRococo}, - weights, - xcm_config::UniversalLocation, - AccountId, BridgeRococoBulletinGrandpa, BridgeRococoBulletinMessages, PolkadotXcm, Runtime, - RuntimeEvent, XcmOverRococoBulletin, XcmRouter, -}; -use bp_messages::LaneId; -use bridge_runtime_common::{ - messages, - messages::{ - source::{FromBridgedChainMessagesDeliveryProof, TargetHeaderChainAdapter}, - target::{FromBridgedChainMessagesProof, SourceHeaderChainAdapter}, - MessageBridge, UnderlyingChainProvider, - }, - messages_xcm_extension::{ - SenderAndLane, XcmAsPlainPayload, XcmBlobHauler, XcmBlobHaulerAdapter, - XcmBlobMessageDispatch, XcmVersionOfDestAndRemoteBridge, - }, - refund_relayer_extension::{ - ActualFeeRefund, RefundBridgedGrandpaMessages, RefundTransactionExtensionAdapter, - RefundableMessagesLane, - }, -}; - -use frame_support::{parameter_types, traits::PalletInfoAccess}; -use sp_runtime::RuntimeDebug; -use xcm::{ - latest::prelude::*, - prelude::{InteriorMultiLocation, NetworkId}, -}; -use xcm_builder::BridgeBlobDispatcher; - -parameter_types! { - /// Maximal number of entries in the unrewarded relayers vector at the Rococo Bridge Hub. It matches the - /// maximal number of unrewarded relayers that the single confirmation transaction at Rococo Bulletin Chain - /// may process. - pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce = - bp_polkadot_bulletin::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; - /// Maximal number of unconfirmed messages at the Rococo Bridge Hub. It matches the maximal number of - /// unconfirmed messages that the single confirmation transaction at Rococo Bulletin Chain may process. - pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = - bp_polkadot_bulletin::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; - /// Bridge specific chain (network) identifier of the Rococo Bulletin Chain. - pub const RococoBulletinChainId: bp_runtime::ChainId = bp_runtime::POLKADOT_BULLETIN_CHAIN_ID; - /// Interior location (relative to this runtime) of the with-RococoBulletin messages pallet. - pub BridgeRococoToRococoBulletinMessagesPalletInstance: InteriorMultiLocation = X1( - PalletInstance(::index() as u8) - ); - /// Rococo Bulletin Network identifier. - pub RococoBulletinGlobalConsensusNetwork: NetworkId = NetworkId::PolkadotBulletin; - /// Relative location of the Rococo Bulletin chain. - pub RococoBulletinGlobalConsensusNetworkLocation: MultiLocation = MultiLocation { - parents: 2, - interior: X1(GlobalConsensus(RococoBulletinGlobalConsensusNetwork::get())) - }; - /// All active lanes that the current bridge supports. - pub ActiveOutboundLanesToRococoBulletin: &'static [bp_messages::LaneId] - = &[XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN]; - /// Lane identifier, used to connect Rococo People and Rococo Bulletin chain. - pub const RococoPeopleToRococoBulletinMessagesLane: bp_messages::LaneId - = XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN; - - /// Priority boost that the registered relayer receives for every additional message in the message - /// delivery transaction. - /// - /// It is determined semi-automatically - see `FEE_BOOST_PER_MESSAGE` constant to get the - /// meaning of this value. - pub PriorityBoostPerMessage: u64 = 182_044_444_444_444; - - /// Identifier of the sibling Rococo People parachain. - pub RococoPeopleParaId: cumulus_primitives_core::ParaId = rococo_runtime_constants::system_parachain::PEOPLE_ID.into(); - /// A route (XCM location and bridge lane) that the Rococo People Chain -> Rococo Bulletin Chain - /// message is following. - pub FromRococoPeopleToRococoBulletinRoute: SenderAndLane = SenderAndLane::new( - ParentThen(X1(Parachain(RococoPeopleParaId::get().into()))).into(), - XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN, - ); - /// All active routes and their destinations. - pub ActiveLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorMultiLocation))> = sp_std::vec![ - ( - FromRococoPeopleToRococoBulletinRoute::get(), - (RococoBulletinGlobalConsensusNetwork::get(), Here) - ) - ]; - - /// XCM message that is never sent. - pub NeverSentMessage: Option> = None; -} -pub const XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN: LaneId = LaneId([0, 0, 0, 0]); - -/// Proof of messages, coming from Rococo Bulletin chain. -pub type FromRococoBulletinMessagesProof = - FromBridgedChainMessagesProof; -/// Messages delivery proof for Rococo Bridge Hub -> Rococo Bulletin messages. -pub type ToRococoBulletinMessagesDeliveryProof = - FromBridgedChainMessagesDeliveryProof; - -/// Dispatches received XCM messages from other bridge. -type FromRococoBulletinMessageBlobDispatcher = BridgeBlobDispatcher< - XcmRouter, - UniversalLocation, - BridgeRococoToRococoBulletinMessagesPalletInstance, ->; - -/// Export XCM messages to be relayed to the other side -pub type ToRococoBulletinHaulBlobExporter = XcmOverRococoBulletin; - -pub struct ToRococoBulletinXcmBlobHauler; -impl XcmBlobHauler for ToRococoBulletinXcmBlobHauler { - type Runtime = Runtime; - type MessagesInstance = WithRococoBulletinMessagesInstance; - type ToSourceChainSender = XcmRouter; - type CongestedMessage = NeverSentMessage; - type UncongestedMessage = NeverSentMessage; -} - -/// On messages delivered callback. -type OnMessagesDeliveredFromRococoBulletin = - XcmBlobHaulerAdapter; - -/// Messaging Bridge configuration for BridgeHubRococo -> Rococo Bulletin. -pub struct WithRococoBulletinMessageBridge; -impl MessageBridge for WithRococoBulletinMessageBridge { - // Bulletin chain assumes it is bridged with Polkadot Bridge Hub - const BRIDGED_MESSAGES_PALLET_NAME: &'static str = - bp_bridge_hub_polkadot::WITH_BRIDGE_HUB_POLKADOT_MESSAGES_PALLET_NAME; - type ThisChain = BridgeHubRococo; - type BridgedChain = RococoBulletin; - type BridgedHeaderChain = BridgeRococoBulletinGrandpa; -} - -/// Message verifier for RococoBulletin messages sent from BridgeHubRococo. -pub type ToRococoBulletinMessageVerifier = - messages::source::FromThisChainMessageVerifier; - -/// Maximal outbound payload size of BridgeHubRococo -> RococoBulletin messages. -pub type ToRococoBulletinMaximalOutboundPayloadSize = - messages::source::FromThisChainMaximalOutboundPayloadSize; - -/// RococoBulletin chain from message lane point of view. -#[derive(RuntimeDebug, Clone, Copy)] -pub struct RococoBulletin; - -impl UnderlyingChainProvider for RococoBulletin { - type Chain = bp_polkadot_bulletin::PolkadotBulletin; -} - -impl messages::BridgedChainWithMessages for RococoBulletin {} - -/// Signed extension that refunds relayers that are delivering messages from the Rococo Bulletin -/// chain. -pub type OnBridgeHubRococoRefundRococoBulletinMessages = RefundTransactionExtensionAdapter< - RefundBridgedGrandpaMessages< - Runtime, - BridgeGrandpaRococoBulletinInstance, - RefundableMessagesLane< - WithRococoBulletinMessagesInstance, - RococoPeopleToRococoBulletinMessagesLane, - >, - ActualFeeRefund, - PriorityBoostPerMessage, - StrOnBridgeHubRococoRefundRococoBulletinMessages, - >, ->; -bp_runtime::generate_static_str_provider!(OnBridgeHubRococoRefundRococoBulletinMessages); - -/// Add XCM messages support for BridgeHubRococo to support Rococo->Rococo Bulletin XCM messages. -pub type WithRococoBulletinMessagesInstance = pallet_bridge_messages::Instance4; -impl pallet_bridge_messages::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type WeightInfo = - weights::pallet_bridge_messages_rococo_to_rococo_bulletin::WeightInfo; - type BridgedChainId = RococoBulletinChainId; - type ActiveOutboundLanes = ActiveOutboundLanesToRococoBulletin; - type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; - type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane; - - type MaximalOutboundPayloadSize = ToRococoBulletinMaximalOutboundPayloadSize; - type OutboundPayload = XcmAsPlainPayload; - - type InboundPayload = XcmAsPlainPayload; - type InboundRelayer = AccountId; - type DeliveryPayments = (); - - type TargetHeaderChain = TargetHeaderChainAdapter; - type LaneMessageVerifier = ToRococoBulletinMessageVerifier; - type DeliveryConfirmationPayments = (); - - type SourceHeaderChain = SourceHeaderChainAdapter; - type MessageDispatch = - XcmBlobMessageDispatch; - type OnMessagesDelivered = OnMessagesDeliveredFromRococoBulletin; -} - -/// Add support for the export and dispatch of XCM programs. -pub type XcmOverPolkadotBulletinInstance = pallet_xcm_bridge_hub::Instance2; -impl pallet_xcm_bridge_hub::Config for Runtime { - type UniversalLocation = UniversalLocation; - type BridgedNetwork = RococoBulletinGlobalConsensusNetworkLocation; - type BridgeMessagesPalletInstance = WithRococoBulletinMessagesInstance; - type MessageExportPrice = (); - type DestinationVersion = - XcmVersionOfDestAndRemoteBridge; - type Lanes = ActiveLanes; - type LanesSupport = ToRococoBulletinXcmBlobHauler; -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::bridge_common_config::BridgeGrandpaRococoBulletinInstance; - use bridge_runtime_common::{ - assert_complete_bridge_types, integrity::check_message_lane_weights, - }; - use parachains_common::{rococo, Balance}; - - /// Every additional message in the message delivery transaction boosts its priority. - /// So the priority of transaction with `N+1` messages is larger than priority of - /// transaction with `N` messages by the `PriorityBoostPerMessage`. - /// - /// Economically, it is an equivalent of adding tip to the transaction with `N` messages. - /// The `FEE_BOOST_PER_MESSAGE` constant is the value of this tip. - /// - /// We want this tip to be large enough (delivery transactions with more messages = less - /// operational costs and a faster bridge), so this value should be significant. - const FEE_BOOST_PER_MESSAGE: Balance = 2 * rococo::currency::UNITS; - - #[test] - fn ensure_bridge_hub_rococo_message_lane_weights_are_correct() { - check_message_lane_weights::< - bp_bridge_hub_rococo::BridgeHubRococo, - Runtime, - WithRococoBulletinMessagesInstance, - >( - bp_polkadot_bulletin::EXTRA_STORAGE_PROOF_SIZE, - bp_bridge_hub_rococo::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, - bp_bridge_hub_rococo::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, - true, - ); - } - - #[test] - fn ensure_bridge_integrity() { - assert_complete_bridge_types!( - runtime: Runtime, - with_bridged_chain_grandpa_instance: BridgeGrandpaRococoBulletinInstance, - with_bridged_chain_messages_instance: WithRococoBulletinMessagesInstance, - bridge: WithRococoBulletinMessageBridge, - this_chain: bp_rococo::Rococo, - bridged_chain: bp_polkadot_bulletin::PolkadotBulletin, - ); - - // we can't use `assert_complete_bridge_constants` here, because there's a trick with - // Bulletin chain - it has the same (almost) runtime for Polkadot Bulletin and Rococo - // Bulletin, so we have to adhere Polkadot names here - - bridge_runtime_common::priority_calculator::ensure_priority_boost_is_sane::< - Runtime, - WithRococoBulletinMessagesInstance, - PriorityBoostPerMessage, - >(FEE_BOOST_PER_MESSAGE); - - assert_eq!( - BridgeRococoToRococoBulletinMessagesPalletInstance::get(), - X1(PalletInstance( - bp_bridge_hub_rococo::WITH_BRIDGE_ROCOCO_TO_BULLETIN_MESSAGES_PALLET_INDEX - )) - ); - } -} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs index e8c695cb180..74583afdf76 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs @@ -14,15 +14,11 @@ // You should have received a copy of the GNU General Public License // along with Cumulus. If not, see . -//! Bridge definitions used on BridgeHubRococo for bridging to BridgeHubWestend. +//! Bridge definitions used on BridgeHub with the Rococo flavor for bridging to BridgeHubWestend. use crate::{ - bridge_common_config::{ - BridgeHubRococo, BridgeParachainWestendInstance, DeliveryRewardInBalance, - }, - weights, - xcm_config::UniversalLocation, - AccountId, BridgeWestendMessages, PolkadotXcm, Runtime, RuntimeEvent, XcmOverBridgeHubWestend, + bridge_common_config::{BridgeParachainWestendInstance, DeliveryRewardInBalance}, + weights, AccountId, BridgeWestendMessages, ParachainInfo, Runtime, RuntimeEvent, RuntimeOrigin, XcmRouter, }; use bp_messages::LaneId; @@ -31,11 +27,11 @@ use bridge_runtime_common::{ messages::{ source::{FromBridgedChainMessagesDeliveryProof, TargetHeaderChainAdapter}, target::{FromBridgedChainMessagesProof, SourceHeaderChainAdapter}, - MessageBridge, UnderlyingChainProvider, + MessageBridge, ThisChainWithMessages, UnderlyingChainProvider, }, messages_xcm_extension::{ SenderAndLane, XcmAsPlainPayload, XcmBlobHauler, XcmBlobHaulerAdapter, - XcmBlobMessageDispatch, XcmVersionOfDestAndRemoteBridge, + XcmBlobMessageDispatch, }, refund_relayer_extension::{ ActualFeeRefund, RefundBridgedParachainMessages, RefundTransactionExtensionAdapter, @@ -50,7 +46,7 @@ use xcm::{ latest::prelude::*, prelude::{InteriorMultiLocation, NetworkId}, }; -use xcm_builder::BridgeBlobDispatcher; +use xcm_builder::{BridgeBlobDispatcher, HaulBlobExporter}; parameter_types! { pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce = @@ -59,41 +55,24 @@ parameter_types! { bp_bridge_hub_rococo::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; pub const BridgeHubWestendChainId: bp_runtime::ChainId = bp_runtime::BRIDGE_HUB_WESTEND_CHAIN_ID; pub BridgeRococoToWestendMessagesPalletInstance: InteriorMultiLocation = X1(PalletInstance(::index() as u8)); + pub BridgeHubRococoUniversalLocation: InteriorMultiLocation = X2(GlobalConsensus(Rococo), Parachain(ParachainInfo::parachain_id().into())); pub WestendGlobalConsensusNetwork: NetworkId = NetworkId::Westend; - pub WestendGlobalConsensusNetworkLocation: MultiLocation = MultiLocation { - parents: 2, - interior: X1(GlobalConsensus(WestendGlobalConsensusNetwork::get())) - }; + pub ActiveOutboundLanesToBridgeHubWestend: &'static [bp_messages::LaneId] = &[XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND]; + pub const AssetHubRococoToAssetHubWestendMessagesLane: bp_messages::LaneId = XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND; // see the `FEE_BOOST_PER_MESSAGE` constant to get the meaning of this value pub PriorityBoostPerMessage: u64 = 182_044_444_444_444; pub AssetHubRococoParaId: cumulus_primitives_core::ParaId = bp_asset_hub_rococo::ASSET_HUB_ROCOCO_PARACHAIN_ID.into(); pub AssetHubWestendParaId: cumulus_primitives_core::ParaId = bp_asset_hub_westend::ASSET_HUB_WESTEND_PARACHAIN_ID.into(); - // Lanes - pub ActiveOutboundLanesToBridgeHubWestend: &'static [bp_messages::LaneId] = &[XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND]; - pub const AssetHubRococoToAssetHubWestendMessagesLane: bp_messages::LaneId = XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND; pub FromAssetHubRococoToAssetHubWestendRoute: SenderAndLane = SenderAndLane::new( ParentThen(X1(Parachain(AssetHubRococoParaId::get().into()))).into(), XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND, ); - pub ActiveLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorMultiLocation))> = sp_std::vec![ - ( - FromAssetHubRococoToAssetHubWestendRoute::get(), - (WestendGlobalConsensusNetwork::get(), X1(Parachain(AssetHubWestendParaId::get().into()))) - ) - ]; pub CongestedMessage: Xcm<()> = build_congestion_message(true).into(); - pub UncongestedMessage: Xcm<()> = build_congestion_message(false).into(); - pub BridgeHubWestendLocation: MultiLocation = MultiLocation { - parents: 2, - interior: X2( - GlobalConsensus(WestendGlobalConsensusNetwork::get()), - Parachain(::PARACHAIN_ID) - ) - }; + pub UncongestedMessage: Xcm<()> = build_congestion_message(false).into(); } pub const XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND: LaneId = LaneId([0, 0, 0, 2]); @@ -124,24 +103,31 @@ pub type ToWestendBridgeHubMessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof; /// Dispatches received XCM messages from other bridge -type FromWestendMessageBlobDispatcher = - BridgeBlobDispatcher; +type FromWestendMessageBlobDispatcher = BridgeBlobDispatcher< + XcmRouter, + BridgeHubRococoUniversalLocation, + BridgeRococoToWestendMessagesPalletInstance, +>; /// Export XCM messages to be relayed to the other side -pub type ToBridgeHubWestendHaulBlobExporter = XcmOverBridgeHubWestend; - +pub type ToBridgeHubWestendHaulBlobExporter = HaulBlobExporter< + XcmBlobHaulerAdapter, + WestendGlobalConsensusNetwork, + (), +>; pub struct ToBridgeHubWestendXcmBlobHauler; impl XcmBlobHauler for ToBridgeHubWestendXcmBlobHauler { type Runtime = Runtime; type MessagesInstance = WithBridgeHubWestendMessagesInstance; + type SenderAndLane = FromAssetHubRococoToAssetHubWestendRoute; + type ToSourceChainSender = XcmRouter; type CongestedMessage = CongestedMessage; type UncongestedMessage = UncongestedMessage; } /// On messages delivered callback. -type OnMessagesDeliveredFromWestend = - XcmBlobHaulerAdapter; +type OnMessagesDeliveredFromWestend = XcmBlobHaulerAdapter; /// Messaging Bridge configuration for BridgeHubRococo -> BridgeHubWestend pub struct WithBridgeHubWestendMessageBridge; @@ -175,6 +161,18 @@ impl UnderlyingChainProvider for BridgeHubWestend { impl messages::BridgedChainWithMessages for BridgeHubWestend {} +/// BridgeHubRococo chain from message lane point of view. +#[derive(RuntimeDebug, Clone, Copy)] +pub struct BridgeHubRococo; + +impl UnderlyingChainProvider for BridgeHubRococo { + type Chain = bp_bridge_hub_rococo::BridgeHubRococo; +} + +impl ThisChainWithMessages for BridgeHubRococo { + type RuntimeOrigin = RuntimeOrigin; +} + /// Signed extension that refunds relayers that are delivering messages from the Westend parachain. pub type OnBridgeHubRococoRefundBridgeHubWestendMessages = RefundTransactionExtensionAdapter< RefundBridgedParachainMessages< @@ -198,7 +196,7 @@ bp_runtime::generate_static_str_provider!(OnBridgeHubRococoRefundBridgeHubWesten pub type WithBridgeHubWestendMessagesInstance = pallet_bridge_messages::Instance3; impl pallet_bridge_messages::Config for Runtime { type RuntimeEvent = RuntimeEvent; - type WeightInfo = weights::pallet_bridge_messages_rococo_to_westend::WeightInfo; + type WeightInfo = weights::pallet_bridge_messages::WeightInfo; type BridgedChainId = BridgeHubWestendChainId; type ActiveOutboundLanes = ActiveOutboundLanesToBridgeHubWestend; type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; @@ -231,19 +229,6 @@ impl pallet_bridge_messages::Config for Ru type OnMessagesDelivered = OnMessagesDeliveredFromWestend; } -/// Add support for the export and dispatch of XCM programs. -pub type XcmOverBridgeHubWestendInstance = pallet_xcm_bridge_hub::Instance1; -impl pallet_xcm_bridge_hub::Config for Runtime { - type UniversalLocation = UniversalLocation; - type BridgedNetwork = WestendGlobalConsensusNetworkLocation; - type BridgeMessagesPalletInstance = WithBridgeHubWestendMessagesInstance; - type MessageExportPrice = (); - type DestinationVersion = - XcmVersionOfDestAndRemoteBridge; - type Lanes = ActiveLanes; - type LanesSupport = ToBridgeHubWestendXcmBlobHauler; -} - #[cfg(test)] mod tests { use super::*; 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 5c6b865d546..055e6cc0ac9 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 @@ -18,7 +18,6 @@ //! //! This runtime currently supports bridging between: //! - Rococo <> Westend -//! - Rococo <> Rococo Bulletin #![cfg_attr(not(feature = "std"), no_std)] // `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. @@ -29,7 +28,6 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); pub mod bridge_common_config; -pub mod bridge_to_bulletin_config; pub mod bridge_to_westend_config; mod weights; pub mod xcm_config; @@ -39,7 +37,7 @@ use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, - traits::Block as BlockT, + traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, }; @@ -51,11 +49,11 @@ use sp_version::RuntimeVersion; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, parameter_types, - traits::{ConstBool, ConstU32, ConstU64, ConstU8, TransformOrigin}, + traits::{ConstBool, ConstU32, ConstU64, ConstU8, Everything, TransformOrigin}, weights::{ConstantMultiplier, Weight}, PalletId, }; @@ -108,10 +106,7 @@ pub type TxExtension = ( frame_system::CheckWeight, pallet_transaction_payment::ChargeTransactionPayment, BridgeRejectObsoleteHeadersAndMessages, - ( - bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages, - bridge_to_bulletin_config::OnBridgeHubRococoRefundRococoBulletinMessages, - ), + (bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages,), ); /// Unchecked extrinsic type as expected by this runtime. @@ -123,7 +118,6 @@ pub type Migrations = ( pallet_collator_selection::migration::v1::MigrateToV1, pallet_multisig::migrations::v1::MigrateToV1, InitStorageVersions, - cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4, ); /// Migration to initialize storage versions for pallets added after genesis. @@ -176,10 +170,10 @@ 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_005_000, + spec_version: 1_003_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, - transaction_version: 4, + transaction_version: 3, state_version: 1, }; @@ -216,24 +210,41 @@ parameter_types! { // Configure FRAME pallets to include in runtime. -#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { /// The identifier used to distinguish between accounts. type AccountId = AccountId; + /// The aggregated dispatch type that is available for extrinsics. + type RuntimeCall = RuntimeCall; + /// The lookup mechanism to get account ID from whatever is passed in dispatchers. + type Lookup = AccountIdLookup; /// The index type for storing how many extrinsics an account has signed. type Nonce = Nonce; /// The type for hashing blocks and tries. type Hash = Hash; + /// The hashing algorithm used. + type Hashing = BlakeTwo256; /// The block type. type Block = Block; + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + /// The ubiquitous origin type. + type RuntimeOrigin = RuntimeOrigin; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). type BlockHashCount = BlockHashCount; /// Runtime version. type Version = Version; + /// Converts a module to an index of this module in the runtime. + type PalletInfo = PalletInfo; /// The data to be stored in an account. type AccountData = pallet_balances::AccountData; + /// What to do if a new account is created. + type OnNewAccount = (); + /// What to do if an account is fully reaped from the system. + type OnKilledAccount = (); /// The weight of database operations that the runtime can invoke. type DbWeight = RocksDbWeight; + /// The basic call filter to use in dispatchable. + type BaseCallFilter = Everything; /// Weight information for the extrinsics of this pallet. type SystemWeightInfo = weights::frame_system::WeightInfo; /// Block & extrinsics weights: base values and limits. @@ -488,32 +499,22 @@ construct_runtime!( Utility: pallet_utility::{Pallet, Call, Event} = 40, Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 36, - // Bridge relayers pallet, used by several bridges here. - BridgeRelayers: pallet_bridge_relayers::{Pallet, Call, Storage, Event} = 47, + // BridgeHubRococo uses: + // - BridgeWestendGrandpa + // - BridgeWestendParachains + // - BridgeWestendMessages + // - BridgeRelayers - // With-Westend GRANDPA bridge module. + // GRANDPA bridge modules. BridgeWestendGrandpa: pallet_bridge_grandpa::::{Pallet, Call, Storage, Event, Config} = 48, - // With-Westend parachain bridge module. + + // Parachain bridge modules. BridgeWestendParachains: pallet_bridge_parachains::::{Pallet, Call, Storage, Event} = 49, - // With-Westend messaging bridge module. + + // Messaging bridge modules. BridgeWestendMessages: pallet_bridge_messages::::{Pallet, Call, Storage, Event, Config} = 51, - // With-Westend bridge hub pallet. - XcmOverBridgeHubWestend: pallet_xcm_bridge_hub::::{Pallet} = 52, - - // With-Rococo Bulletin GRANDPA bridge module. - // - // we can't use `BridgeRococoBulletinGrandpa` name here, because the same Bulletin runtime will be - // used for both Rococo and Polkadot Bulletin chains AND this name affects runtime storage keys, used - // by the relayer process - BridgePolkadotBulletinGrandpa: pallet_bridge_grandpa::::{Pallet, Call, Storage, Event, Config} = 60, - // With-Rococo Bulletin messaging bridge module. - // - // we can't use `BridgeRococoBulletinMessages` name here, because the same Bulletin runtime will be - // used for both Rococo and Polkadot Bulletin chains AND this name affects runtime storage keys, used - // by this runtime and the relayer process - BridgePolkadotBulletinMessages: pallet_bridge_messages::::{Pallet, Call, Storage, Event, Config} = 61, - // With-Rococo Bulletin bridge hub pallet. - XcmOverPolkadotBulletin: pallet_xcm_bridge_hub::::{Pallet} = 62, + + BridgeRelayers: pallet_bridge_relayers::{Pallet, Call, Storage, Event} = 47, // Message Queue. Importantly, is registered last so that messages are processed after // the `on_initialize` hooks of bridging pallets. @@ -521,23 +522,14 @@ construct_runtime!( } ); -/// Proper alias for bridge GRANDPA pallet used to bridge with the bulletin chain. -pub type BridgeRococoBulletinGrandpa = BridgePolkadotBulletinGrandpa; -/// Proper alias for bridge messages pallet used to bridge with the bulletin chain. -pub type BridgeRococoBulletinMessages = BridgePolkadotBulletinMessages; -/// Proper alias for bridge messages pallet used to bridge with the bulletin chain. -pub type XcmOverRococoBulletin = XcmOverPolkadotBulletin; - bridge_runtime_common::generate_bridge_reject_obsolete_headers_and_messages! { RuntimeCall, AccountId, // Grandpa BridgeWestendGrandpa, - BridgeRococoBulletinGrandpa, // Parachains BridgeWestendParachains, // Messages - BridgeWestendMessages, - BridgeRococoBulletinMessages + BridgeWestendMessages } #[cfg(feature = "runtime-benchmarks")] @@ -562,7 +554,6 @@ mod benches { [pallet_bridge_grandpa, WestendFinality] [pallet_bridge_parachains, WithinWestend] [pallet_bridge_messages, RococoToWestend] - [pallet_bridge_messages, RococoToRococoBulletin] [pallet_bridge_relayers, BridgeRelayersBench::] ); } @@ -756,42 +747,6 @@ impl_runtime_apis! { } } - impl bp_polkadot_bulletin::PolkadotBulletinFinalityApi for Runtime { - fn best_finalized() -> Option> { - BridgePolkadotBulletinGrandpa::best_finalized() - } - - fn synced_headers_grandpa_info( - ) -> Vec> { - BridgePolkadotBulletinGrandpa::synced_headers_grandpa_info() - } - } - - impl bp_polkadot_bulletin::FromPolkadotBulletinInboundLaneApi for Runtime { - fn message_details( - lane: bp_messages::LaneId, - messages: Vec<(bp_messages::MessagePayload, bp_messages::OutboundMessageDetails)>, - ) -> Vec { - bridge_runtime_common::messages_api::inbound_message_details::< - Runtime, - bridge_to_bulletin_config::WithRococoBulletinMessagesInstance, - >(lane, messages) - } - } - - impl bp_polkadot_bulletin::ToPolkadotBulletinOutboundLaneApi for Runtime { - fn message_details( - lane: bp_messages::LaneId, - begin: bp_messages::MessageNonce, - end: bp_messages::MessageNonce, - ) -> Vec { - bridge_runtime_common::messages_api::outbound_message_details::< - Runtime, - bridge_to_bulletin_config::WithRococoBulletinMessagesInstance, - >(lane, begin, end) - } - } - #[cfg(feature = "try-runtime")] impl frame_try_runtime::TryRuntime for Runtime { fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { @@ -834,7 +789,6 @@ impl_runtime_apis! { type WestendFinality = BridgeWestendGrandpa; type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::; type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::; - type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::; let mut list = Vec::::new(); list_benchmarks!(list, extra); @@ -885,18 +839,6 @@ impl_runtime_apis! { // Reserve transfers are disabled on BH. None } - - fn set_up_complex_asset_transfer( - ) -> Option<(MultiAssets, u32, MultiLocation, Box)> { - // BH only supports teleports to system parachain. - // Relay/native token can be teleported between BH and Relay. - let native_location = Parent.into(); - let dest = Parent.into(); - pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::( - native_location, - dest - ) - } } use xcm::latest::prelude::*; @@ -913,7 +855,7 @@ impl_runtime_apis! { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< - xcm_config::XcmConfig, + xcm_config::XcmConfig, ExistentialDepositMultiAsset, xcm_config::PriceForParentDelivery, >; @@ -993,28 +935,7 @@ impl_runtime_apis! { fn export_message_origin_and_destination( ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { - // save XCM version for remote bridge hub - let _ = PolkadotXcm::force_xcm_version( - RuntimeOrigin::root(), - Box::new(bridge_to_westend_config::BridgeHubWestendLocation::get()), - XCM_VERSION, - ).map_err(|e| { - log::error!( - "Failed to dispatch `force_xcm_version({:?}, {:?}, {:?})`, error: {:?}", - RuntimeOrigin::root(), - bridge_to_westend_config::BridgeHubWestendLocation::get(), - XCM_VERSION, - e - ); - BenchmarkError::Stop("XcmVersion was not stored!") - })?; - Ok( - ( - bridge_to_westend_config::FromAssetHubRococoToAssetHubWestendRoute::get().location, - NetworkId::Westend, - X1(Parachain(bridge_to_westend_config::AssetHubWestendParaId::get().into())) - ) - ) + Ok((TokenLocation::get(), NetworkId::Westend, X1(Parachain(100)))) } fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { @@ -1028,12 +949,9 @@ impl_runtime_apis! { type WestendFinality = BridgeWestendGrandpa; type WithinWestend = pallet_bridge_parachains::benchmarking::Pallet::; type RococoToWestend = pallet_bridge_messages::benchmarking::Pallet ::; - type RococoToRococoBulletin = pallet_bridge_messages::benchmarking::Pallet ::; use bridge_runtime_common::messages_benchmarking::{ - prepare_message_delivery_proof_from_grandpa_chain, prepare_message_delivery_proof_from_parachain, - prepare_message_proof_from_grandpa_chain, prepare_message_proof_from_parachain, generate_xcm_builder_bridge_message_sample, }; @@ -1086,41 +1004,6 @@ impl_runtime_apis! { } } - impl BridgeMessagesConfig for Runtime { - fn is_relayer_rewarded(_relayer: &Self::AccountId) -> bool { - // we do not pay any rewards in this bridge - true - } - - fn prepare_message_proof( - params: MessageProofParams, - ) -> (bridge_to_bulletin_config::FromRococoBulletinMessagesProof, Weight) { - use cumulus_primitives_core::XcmpMessageSource; - assert!(XcmpQueue::take_outbound_messages(usize::MAX).is_empty()); - ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(42.into()); - prepare_message_proof_from_grandpa_chain::< - Runtime, - bridge_common_config::BridgeGrandpaRococoBulletinInstance, - bridge_to_bulletin_config::WithRococoBulletinMessageBridge, - >(params, generate_xcm_builder_bridge_message_sample(X2(GlobalConsensus(Rococo), Parachain(42)))) - } - - fn prepare_message_delivery_proof( - params: MessageDeliveryProofParams, - ) -> bridge_to_bulletin_config::ToRococoBulletinMessagesDeliveryProof { - prepare_message_delivery_proof_from_grandpa_chain::< - Runtime, - bridge_common_config::BridgeGrandpaRococoBulletinInstance, - bridge_to_bulletin_config::WithRococoBulletinMessageBridge, - >(params) - } - - fn is_message_successfully_dispatched(_nonce: bp_messages::MessageNonce) -> bool { - use cumulus_primitives_core::XcmpMessageSource; - !XcmpQueue::take_outbound_messages(usize::MAX).is_empty() - } - } - use bridge_runtime_common::parachains_benchmarking::prepare_parachain_heads_proof; use pallet_bridge_parachains::benchmarking::Config as BridgeParachainsConfig; use pallet_bridge_relayers::benchmarking::{ @@ -1232,10 +1115,7 @@ mod tests { frame_system::CheckWeight::new(), pallet_transaction_payment::ChargeTransactionPayment::from(10), BridgeRejectObsoleteHeadersAndMessages, - ( - bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages::default(), - bridge_to_bulletin_config::OnBridgeHubRococoRefundRococoBulletinMessages::default(), - ) + (bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages::default(),) ).into(); // for BridgeHubRococo diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/mod.rs index 69461be38ed..3604ab3c0ff 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/mod.rs @@ -27,8 +27,7 @@ pub mod extrinsic_weights; pub mod frame_system; pub mod pallet_balances; pub mod pallet_bridge_grandpa; -pub mod pallet_bridge_messages_rococo_to_rococo_bulletin; -pub mod pallet_bridge_messages_rococo_to_westend; +pub mod pallet_bridge_messages; pub mod pallet_bridge_parachains; pub mod pallet_bridge_relayers; pub mod pallet_collator_selection; @@ -53,26 +52,7 @@ use frame_support::weights::Weight; // import trait from dependency module use ::pallet_bridge_relayers::WeightInfoExt as _; -impl MessagesWeightInfoExt - for pallet_bridge_messages_rococo_to_rococo_bulletin::WeightInfo -{ - fn expected_extra_storage_proof_size() -> u32 { - bp_polkadot_bulletin::EXTRA_STORAGE_PROOF_SIZE - } - - fn receive_messages_proof_overhead_from_runtime() -> Weight { - pallet_bridge_relayers::WeightInfo::::receive_messages_proof_overhead_from_runtime( - ) - } - - fn receive_messages_delivery_proof_overhead_from_runtime() -> Weight { - pallet_bridge_relayers::WeightInfo::::receive_messages_delivery_proof_overhead_from_runtime() - } -} - -impl MessagesWeightInfoExt - for pallet_bridge_messages_rococo_to_westend::WeightInfo -{ +impl MessagesWeightInfoExt for pallet_bridge_messages::WeightInfo { fn expected_extra_storage_proof_size() -> u32 { bp_bridge_hub_westend::EXTRA_STORAGE_PROOF_SIZE } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_grandpa.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_grandpa.rs index 8c2435599f5..aaa6a3e0622 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_grandpa.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_grandpa.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_bridge_grandpa` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-11-14, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: @@ -66,13 +66,13 @@ impl pallet_bridge_grandpa::WeightInfo for WeightInfo pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn receive_single_message_proof() -> Weight { // Proof Size summary in bytes: - // Measured: `605` + // Measured: `538` // Estimated: `52645` - // Minimum execution time: 40_349_000 picoseconds. - Weight::from_parts(41_856_000, 0) + // Minimum execution time: 41_577_000 picoseconds. + Weight::from_parts(42_621_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) @@ -80,10 +80,10 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn receive_two_messages_proof() -> Weight { // Proof Size summary in bytes: - // Measured: `605` + // Measured: `538` // Estimated: `52645` - // Minimum execution time: 50_514_000 picoseconds. - Weight::from_parts(52_254_000, 0) + // Minimum execution time: 52_880_000 picoseconds. + Weight::from_parts(53_697_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) @@ -100,10 +100,10 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn receive_single_message_proof_with_outbound_lane_state() -> Weight { // Proof Size summary in bytes: - // Measured: `605` + // Measured: `538` // Estimated: `52645` - // Minimum execution time: 45_761_000 picoseconds. - Weight::from_parts(47_075_000, 0) + // Minimum execution time: 47_424_000 picoseconds. + Weight::from_parts(48_445_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) @@ -118,10 +118,10 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `BridgeWestendMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) fn receive_single_message_proof_1_kb() -> Weight { // Proof Size summary in bytes: - // Measured: `573` + // Measured: `506` // Estimated: `52645` - // Minimum execution time: 39_098_000 picoseconds. - Weight::from_parts(40_577_000, 0) + // Minimum execution time: 40_619_000 picoseconds. + Weight::from_parts(42_262_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(1)) @@ -136,10 +136,10 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `BridgeWestendMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) fn receive_single_message_proof_16_kb() -> Weight { // Proof Size summary in bytes: - // Measured: `573` + // Measured: `506` // Estimated: `52645` - // Minimum execution time: 69_120_000 picoseconds. - Weight::from_parts(71_810_000, 0) + // Minimum execution time: 74_603_000 picoseconds. + Weight::from_parts(78_209_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(1)) @@ -156,11 +156,11 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `BridgeRelayers::RelayerRewards` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn receive_delivery_proof_for_single_message() -> Weight { // Proof Size summary in bytes: - // Measured: `447` - // Estimated: `3912` - // Minimum execution time: 32_325_000 picoseconds. - Weight::from_parts(33_070_000, 0) - .saturating_add(Weight::from_parts(0, 3912)) + // Measured: `377` + // Estimated: `3842` + // Minimum execution time: 33_762_000 picoseconds. + Weight::from_parts(34_405_000, 0) + .saturating_add(Weight::from_parts(0, 3842)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -176,11 +176,11 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `BridgeRelayers::RelayerRewards` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { // Proof Size summary in bytes: - // Measured: `447` - // Estimated: `3912` - // Minimum execution time: 32_180_000 picoseconds. - Weight::from_parts(33_202_000, 0) - .saturating_add(Weight::from_parts(0, 3912)) + // Measured: `377` + // Estimated: `3842` + // Minimum execution time: 33_805_000 picoseconds. + Weight::from_parts(35_051_000, 0) + .saturating_add(Weight::from_parts(0, 3842)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -196,10 +196,10 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `BridgeRelayers::RelayerRewards` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { // Proof Size summary in bytes: - // Measured: `447` + // Measured: `377` // Estimated: `6086` - // Minimum execution time: 36_774_000 picoseconds. - Weight::from_parts(37_774_000, 0) + // Minimum execution time: 38_612_000 picoseconds. + Weight::from_parts(39_412_000, 0) .saturating_add(Weight::from_parts(0, 6086)) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(3)) @@ -227,16 +227,15 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `i` is `[128, 2048]`. - /// The range of component `i` is `[128, 2048]`. fn receive_single_message_proof_with_dispatch(i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `736` + // Measured: `669` // Estimated: `52645` - // Minimum execution time: 65_934_000 picoseconds. - Weight::from_parts(67_915_916, 0) + // Minimum execution time: 69_285_000 picoseconds. + Weight::from_parts(70_867_498, 0) .saturating_add(Weight::from_parts(0, 52645)) - // Standard Error: 65 - .saturating_add(Weight::from_parts(7_190, 0).saturating_mul(i.into())) + // Standard Error: 111 + .saturating_add(Weight::from_parts(7_489, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_messages_rococo_to_rococo_bulletin.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_messages_rococo_to_rococo_bulletin.rs deleted file mode 100644 index d3255ab3875..00000000000 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_messages_rococo_to_rococo_bulletin.rs +++ /dev/null @@ -1,221 +0,0 @@ -// 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 . - -//! Autogenerated weights for `pallet_bridge_messages` -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-14, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 - -// Executed Command: -// target/production/polkadot-parachain -// benchmark -// pallet -// --steps=50 -// --repeat=20 -// --extrinsic=* -// --wasm-execution=compiled -// --heap-pages=4096 -// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json -// --pallet=pallet_bridge_messages -// --chain=bridge-hub-rococo-dev -// --header=./cumulus/file_header.txt -// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/ - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(missing_docs)] - -use frame_support::{traits::Get, weights::Weight}; -use core::marker::PhantomData; - -/// Weight functions for `pallet_bridge_messages`. -pub struct WeightInfo(PhantomData); -impl pallet_bridge_messages::WeightInfo for WeightInfo { - /// Storage: `BridgePolkadotBulletinMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgePolkadotBulletinMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) - /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) - /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - fn receive_single_message_proof() -> Weight { - // Proof Size summary in bytes: - // Measured: `621` - // Estimated: `52645` - // Minimum execution time: 36_661_000 picoseconds. - Weight::from_parts(38_106_000, 0) - .saturating_add(Weight::from_parts(0, 52645)) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `BridgePolkadotBulletinMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgePolkadotBulletinMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) - /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) - /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - fn receive_two_messages_proof() -> Weight { - // Proof Size summary in bytes: - // Measured: `621` - // Estimated: `52645` - // Minimum execution time: 47_599_000 picoseconds. - Weight::from_parts(49_731_000, 0) - .saturating_add(Weight::from_parts(0, 52645)) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `BridgePolkadotBulletinMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgePolkadotBulletinMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) - /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) - /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - fn receive_single_message_proof_with_outbound_lane_state() -> Weight { - // Proof Size summary in bytes: - // Measured: `621` - // Estimated: `52645` - // Minimum execution time: 42_211_000 picoseconds. - Weight::from_parts(43_454_000, 0) - .saturating_add(Weight::from_parts(0, 52645)) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `BridgePolkadotBulletinMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgePolkadotBulletinMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) - fn receive_single_message_proof_1_kb() -> Weight { - // Proof Size summary in bytes: - // Measured: `589` - // Estimated: `52645` - // Minimum execution time: 36_072_000 picoseconds. - Weight::from_parts(37_260_000, 0) - .saturating_add(Weight::from_parts(0, 52645)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `BridgePolkadotBulletinMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgePolkadotBulletinMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) - fn receive_single_message_proof_16_kb() -> Weight { - // Proof Size summary in bytes: - // Measured: `589` - // Estimated: `52645` - // Minimum execution time: 66_995_000 picoseconds. - Weight::from_parts(68_661_000, 0) - .saturating_add(Weight::from_parts(0, 52645)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `BridgePolkadotBulletinMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinMessages::OutboundLanes` (r:1 w:1) - /// Proof: `BridgePolkadotBulletinMessages::OutboundLanes` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) - fn receive_delivery_proof_for_single_message() -> Weight { - // Proof Size summary in bytes: - // Measured: `588` - // Estimated: `2543` - // Minimum execution time: 25_553_000 picoseconds. - Weight::from_parts(26_205_000, 0) - .saturating_add(Weight::from_parts(0, 2543)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `BridgePolkadotBulletinMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinMessages::OutboundLanes` (r:1 w:1) - /// Proof: `BridgePolkadotBulletinMessages::OutboundLanes` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) - fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { - // Proof Size summary in bytes: - // Measured: `588` - // Estimated: `2543` - // Minimum execution time: 25_610_000 picoseconds. - Weight::from_parts(26_273_000, 0) - .saturating_add(Weight::from_parts(0, 2543)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `BridgePolkadotBulletinMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinMessages::OutboundLanes` (r:1 w:1) - /// Proof: `BridgePolkadotBulletinMessages::OutboundLanes` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) - fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { - // Proof Size summary in bytes: - // Measured: `588` - // Estimated: `2543` - // Minimum execution time: 25_651_000 picoseconds. - Weight::from_parts(26_172_000, 0) - .saturating_add(Weight::from_parts(0, 2543)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `BridgePolkadotBulletinMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgePolkadotBulletinMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) - /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) - /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `XcmpQueue::DeliveryFeeFactor` (r:1 w:0) - /// Proof: `XcmpQueue::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::RelevantMessagingState` (r:1 w:0) - /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) - /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) - /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// The range of component `i` is `[128, 2048]`. - /// The range of component `i` is `[128, 2048]`. - fn receive_single_message_proof_with_dispatch(i: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `780` - // Estimated: `52645` - // Minimum execution time: 64_219_000 picoseconds. - Weight::from_parts(65_848_290, 0) - .saturating_add(Weight::from_parts(0, 52645)) - // Standard Error: 43 - .saturating_add(Weight::from_parts(7_577, 0).saturating_mul(i.into())) - .saturating_add(T::DbWeight::get().reads(10)) - .saturating_add(T::DbWeight::get().writes(4)) - } -} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_parachains.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_parachains.rs index ea68852804e..5c7c4a63682 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_parachains.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_parachains.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_bridge_parachains` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-11-14, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: @@ -59,15 +59,13 @@ impl pallet_bridge_parachains::WeightInfo for WeightInf /// Storage: `BridgeWestendParachains::ImportedParaHeads` (r:0 w:1) /// Proof: `BridgeWestendParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) /// The range of component `p` is `[1, 2]`. - fn submit_parachain_heads_with_n_parachains(p: u32, ) -> Weight { + fn submit_parachain_heads_with_n_parachains(_p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `434` // Estimated: `2543` - // Minimum execution time: 31_135_000 picoseconds. - Weight::from_parts(32_061_351, 0) + // Minimum execution time: 31_987_000 picoseconds. + Weight::from_parts(33_060_534, 0) .saturating_add(Weight::from_parts(0, 2543)) - // Standard Error: 80_309 - .saturating_add(Weight::from_parts(99_724, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -85,8 +83,8 @@ impl pallet_bridge_parachains::WeightInfo for WeightInf // Proof Size summary in bytes: // Measured: `434` // Estimated: `2543` - // Minimum execution time: 32_263_000 picoseconds. - Weight::from_parts(33_139_000, 0) + // Minimum execution time: 33_360_000 picoseconds. + Weight::from_parts(34_182_000, 0) .saturating_add(Weight::from_parts(0, 2543)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) @@ -105,8 +103,8 @@ impl pallet_bridge_parachains::WeightInfo for WeightInf // Proof Size summary in bytes: // Measured: `434` // Estimated: `2543` - // Minimum execution time: 61_313_000 picoseconds. - Weight::from_parts(62_200_000, 0) + // Minimum execution time: 65_246_000 picoseconds. + Weight::from_parts(65_985_000, 0) .saturating_add(Weight::from_parts(0, 2543)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_relayers.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_relayers.rs index 5ab4cb900d8..70af694645d 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_relayers.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_relayers.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_bridge_relayers` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-11-14, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: @@ -54,10 +54,10 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn claim_rewards() -> Weight { // Proof Size summary in bytes: - // Measured: `244` + // Measured: `207` // Estimated: `3593` - // Minimum execution time: 45_393_000 picoseconds. - Weight::from_parts(46_210_000, 0) + // Minimum execution time: 46_579_000 picoseconds. + Weight::from_parts(48_298_000, 0) .saturating_add(Weight::from_parts(0, 3593)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) @@ -70,10 +70,10 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) fn register() -> Weight { // Proof Size summary in bytes: - // Measured: `97` + // Measured: `61` // Estimated: `4714` - // Minimum execution time: 23_767_000 picoseconds. - Weight::from_parts(24_217_000, 0) + // Minimum execution time: 24_219_000 picoseconds. + Weight::from_parts(24_993_000, 0) .saturating_add(Weight::from_parts(0, 4714)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(2)) @@ -84,10 +84,10 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< /// Proof: `Balances::Reserves` (`max_values`: None, `max_size`: Some(1249), added: 3724, mode: `MaxEncodedLen`) fn deregister() -> Weight { // Proof Size summary in bytes: - // Measured: `197` + // Measured: `160` // Estimated: `4714` - // Minimum execution time: 25_745_000 picoseconds. - Weight::from_parts(26_319_000, 0) + // Minimum execution time: 26_279_000 picoseconds. + Weight::from_parts(26_810_000, 0) .saturating_add(Weight::from_parts(0, 4714)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) @@ -100,10 +100,10 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn slash_and_deregister() -> Weight { // Proof Size summary in bytes: - // Measured: `300` + // Measured: `263` // Estimated: `4714` - // Minimum execution time: 27_497_000 picoseconds. - Weight::from_parts(27_939_000, 0) + // Minimum execution time: 27_672_000 picoseconds. + Weight::from_parts(28_946_000, 0) .saturating_add(Weight::from_parts(0, 4714)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(3)) @@ -112,10 +112,10 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< /// Proof: `BridgeRelayers::RelayerRewards` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn register_relayer_reward() -> Weight { // Proof Size summary in bytes: - // Measured: `42` + // Measured: `6` // Estimated: `3538` - // Minimum execution time: 5_584_000 picoseconds. - Weight::from_parts(5_908_000, 0) + // Minimum execution time: 5_487_000 picoseconds. + Weight::from_parts(5_725_000, 0) .saturating_add(Weight::from_parts(0, 3538)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_xcm.rs index 5faded42aa8..5aa4999c624 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_xcm.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-05, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-11-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-r43aesjn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: @@ -62,39 +62,26 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn send() -> Weight { // Proof Size summary in bytes: - // Measured: `38` - // Estimated: `3503` - // Minimum execution time: 23_683_000 picoseconds. - Weight::from_parts(24_199_000, 0) - .saturating_add(Weight::from_parts(0, 3503)) + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 24_179_000 picoseconds. + Weight::from_parts(24_684_000, 0) + .saturating_add(Weight::from_parts(0, 3540)) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } + /// Storage: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) + /// Proof: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) - /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) - /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn teleport_assets() -> Weight { // Proof Size summary in bytes: - // Measured: `70` - // Estimated: `3593` - // Minimum execution time: 89_524_000 picoseconds. - Weight::from_parts(91_401_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(3)) + // Measured: `38` + // Estimated: `3503` + // Minimum execution time: 21_093_000 picoseconds. + Weight::from_parts(21_523_000, 0) + .saturating_add(Weight::from_parts(0, 3503)) + .saturating_add(T::DbWeight::get().reads(2)) } /// Storage: `Benchmark::Override` (r:0 w:0) /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -106,32 +93,6 @@ impl pallet_xcm::WeightInfo for WeightInfo { Weight::from_parts(18_446_744_073_709_551_000, 0) .saturating_add(Weight::from_parts(0, 0)) } - /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) - /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) - /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) - /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - fn transfer_assets() -> Weight { - // Proof Size summary in bytes: - // Measured: `70` - // Estimated: `3593` - // Minimum execution time: 91_890_000 picoseconds. - Weight::from_parts(93_460_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(3)) - } /// Storage: `Benchmark::Override` (r:0 w:0) /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) fn execute() -> Weight { @@ -148,8 +109,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_152_000 picoseconds. - Weight::from_parts(7_355_000, 0) + // Minimum execution time: 6_938_000 picoseconds. + Weight::from_parts(7_243_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -159,8 +120,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_081_000 picoseconds. - Weight::from_parts(2_258_000, 0) + // Minimum execution time: 2_159_000 picoseconds. + Weight::from_parts(2_290_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -184,11 +145,11 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) fn force_subscribe_version_notify() -> Weight { // Proof Size summary in bytes: - // Measured: `38` - // Estimated: `3503` - // Minimum execution time: 28_067_000 picoseconds. - Weight::from_parts(28_693_000, 0) - .saturating_add(Weight::from_parts(0, 3503)) + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 28_337_000 picoseconds. + Weight::from_parts(29_265_000, 0) + .saturating_add(Weight::from_parts(0, 3540)) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(5)) } @@ -210,11 +171,11 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) fn force_unsubscribe_version_notify() -> Weight { // Proof Size summary in bytes: - // Measured: `255` - // Estimated: `3720` - // Minimum execution time: 30_420_000 picoseconds. - Weight::from_parts(31_373_000, 0) - .saturating_add(Weight::from_parts(0, 3720)) + // Measured: `292` + // Estimated: `3757` + // Minimum execution time: 30_599_000 picoseconds. + Weight::from_parts(31_272_000, 0) + .saturating_add(Weight::from_parts(0, 3757)) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -224,8 +185,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_087_000 picoseconds. - Weight::from_parts(2_243_000, 0) + // Minimum execution time: 2_132_000 picoseconds. + Weight::from_parts(2_280_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -233,11 +194,11 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) fn migrate_supported_version() -> Weight { // Proof Size summary in bytes: - // Measured: `95` - // Estimated: `10985` - // Minimum execution time: 15_142_000 picoseconds. - Weight::from_parts(15_598_000, 0) - .saturating_add(Weight::from_parts(0, 10985)) + // Measured: `187` + // Estimated: `11077` + // Minimum execution time: 18_262_000 picoseconds. + Weight::from_parts(18_640_000, 0) + .saturating_add(Weight::from_parts(0, 11077)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -245,11 +206,11 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) fn migrate_version_notifiers() -> Weight { // Proof Size summary in bytes: - // Measured: `99` - // Estimated: `10989` - // Minimum execution time: 15_041_000 picoseconds. - Weight::from_parts(15_493_000, 0) - .saturating_add(Weight::from_parts(0, 10989)) + // Measured: `191` + // Estimated: `11081` + // Minimum execution time: 18_512_000 picoseconds. + Weight::from_parts(18_888_000, 0) + .saturating_add(Weight::from_parts(0, 11081)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -257,11 +218,11 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) fn already_notified_target() -> Weight { // Proof Size summary in bytes: - // Measured: `106` - // Estimated: `13471` - // Minimum execution time: 16_624_000 picoseconds. - Weight::from_parts(17_031_000, 0) - .saturating_add(Weight::from_parts(0, 13471)) + // Measured: `198` + // Estimated: `13563` + // Minimum execution time: 19_362_000 picoseconds. + Weight::from_parts(20_056_000, 0) + .saturating_add(Weight::from_parts(0, 13563)) .saturating_add(T::DbWeight::get().reads(5)) } /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:2 w:1) @@ -280,11 +241,11 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn notify_current_targets() -> Weight { // Proof Size summary in bytes: - // Measured: `106` - // Estimated: `6046` - // Minimum execution time: 26_398_000 picoseconds. - Weight::from_parts(26_847_000, 0) - .saturating_add(Weight::from_parts(0, 6046)) + // Measured: `142` + // Estimated: `6082` + // Minimum execution time: 27_318_000 picoseconds. + Weight::from_parts(28_075_000, 0) + .saturating_add(Weight::from_parts(0, 6082)) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -292,22 +253,22 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) fn notify_target_migration_fail() -> Weight { // Proof Size summary in bytes: - // Measured: `136` - // Estimated: `8551` - // Minimum execution time: 8_741_000 picoseconds. - Weight::from_parts(8_954_000, 0) - .saturating_add(Weight::from_parts(0, 8551)) + // Measured: `172` + // Estimated: `8587` + // Minimum execution time: 9_930_000 picoseconds. + Weight::from_parts(10_192_000, 0) + .saturating_add(Weight::from_parts(0, 8587)) .saturating_add(T::DbWeight::get().reads(3)) } /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) fn migrate_version_notify_targets() -> Weight { // Proof Size summary in bytes: - // Measured: `106` - // Estimated: `10996` - // Minimum execution time: 15_306_000 picoseconds. - Weight::from_parts(15_760_000, 0) - .saturating_add(Weight::from_parts(0, 10996)) + // Measured: `198` + // Estimated: `11088` + // Minimum execution time: 18_305_000 picoseconds. + Weight::from_parts(18_738_000, 0) + .saturating_add(Weight::from_parts(0, 11088)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -327,11 +288,11 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn migrate_and_notify_old_targets() -> Weight { // Proof Size summary in bytes: - // Measured: `112` - // Estimated: `11002` - // Minimum execution time: 33_127_000 picoseconds. - Weight::from_parts(33_938_000, 0) - .saturating_add(Weight::from_parts(0, 11002)) + // Measured: `204` + // Estimated: `11094` + // Minimum execution time: 34_559_000 picoseconds. + Weight::from_parts(35_241_000, 0) + .saturating_add(Weight::from_parts(0, 11094)) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -341,11 +302,11 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) fn new_query() -> Weight { // Proof Size summary in bytes: - // Measured: `32` - // Estimated: `1517` - // Minimum execution time: 4_290_000 picoseconds. - Weight::from_parts(4_450_000, 0) - .saturating_add(Weight::from_parts(0, 1517)) + // Measured: `69` + // Estimated: `1554` + // Minimum execution time: 4_512_000 picoseconds. + Weight::from_parts(4_671_000, 0) + .saturating_add(Weight::from_parts(0, 1554)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -353,11 +314,11 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) fn take_response() -> Weight { // Proof Size summary in bytes: - // Measured: `7669` - // Estimated: `11134` - // Minimum execution time: 26_408_000 picoseconds. - Weight::from_parts(26_900_000, 0) - .saturating_add(Weight::from_parts(0, 11134)) + // Measured: `7706` + // Estimated: `11171` + // Minimum execution time: 26_473_000 picoseconds. + Weight::from_parts(26_960_000, 0) + .saturating_add(Weight::from_parts(0, 11171)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index abd84f8e89b..0ae6d0b5623 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-11-14, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-rococo-dev"), DB CACHE: 1024 // Executed Command: @@ -68,8 +68,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 61_813_000 picoseconds. - Weight::from_parts(62_996_000, 6196) + // Minimum execution time: 63_453_000 picoseconds. + Weight::from_parts(64_220_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -77,8 +77,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_044_000 picoseconds. - Weight::from_parts(2_112_000, 0) + // Minimum execution time: 2_238_000 picoseconds. + Weight::from_parts(2_351_000, 0) } // Storage: `PolkadotXcm::Queries` (r:1 w:0) // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -86,58 +86,58 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `32` // Estimated: `3497` - // Minimum execution time: 7_472_000 picoseconds. - Weight::from_parts(7_723_000, 3497) + // Minimum execution time: 7_953_000 picoseconds. + Weight::from_parts(8_162_000, 3497) .saturating_add(T::DbWeight::get().reads(1)) } pub fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_414_000 picoseconds. - Weight::from_parts(8_765_000, 0) + // Minimum execution time: 9_080_000 picoseconds. + Weight::from_parts(9_333_000, 0) } pub fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_192_000 picoseconds. - Weight::from_parts(2_243_000, 0) + // Minimum execution time: 2_415_000 picoseconds. + Weight::from_parts(2_519_000, 0) } pub fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_866_000 picoseconds. - Weight::from_parts(1_931_000, 0) + // Minimum execution time: 2_045_000 picoseconds. + Weight::from_parts(2_184_000, 0) } pub fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_847_000 picoseconds. - Weight::from_parts(1_921_000, 0) + // Minimum execution time: 2_065_000 picoseconds. + Weight::from_parts(2_125_000, 0) } pub fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_797_000 picoseconds. - Weight::from_parts(1_880_000, 0) + // Minimum execution time: 2_077_000 picoseconds. + Weight::from_parts(2_164_000, 0) } pub fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_458_000 picoseconds. - Weight::from_parts(2_523_000, 0) + // Minimum execution time: 2_868_000 picoseconds. + Weight::from_parts(2_933_000, 0) } pub fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_833_000 picoseconds. - Weight::from_parts(1_906_000, 0) + // Minimum execution time: 2_058_000 picoseconds. + Weight::from_parts(2_164_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -159,8 +159,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 54_659_000 picoseconds. - Weight::from_parts(56_025_000, 6196) + // Minimum execution time: 55_971_000 picoseconds. + Weight::from_parts(56_869_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -170,8 +170,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `90` // Estimated: `3555` - // Minimum execution time: 10_953_000 picoseconds. - Weight::from_parts(11_220_000, 3555) + // Minimum execution time: 11_382_000 picoseconds. + Weight::from_parts(11_672_000, 3555) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -179,8 +179,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_834_000 picoseconds. - Weight::from_parts(1_892_000, 0) + // Minimum execution time: 2_071_000 picoseconds. + Weight::from_parts(2_193_000, 0) } // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -200,8 +200,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `38` // Estimated: `3503` - // Minimum execution time: 22_238_000 picoseconds. - Weight::from_parts(22_690_000, 3503) + // Minimum execution time: 22_573_000 picoseconds. + Weight::from_parts(23_423_000, 3503) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -211,44 +211,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_798_000 picoseconds. - Weight::from_parts(3_936_000, 0) + // Minimum execution time: 3_870_000 picoseconds. + Weight::from_parts(3_993_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_985_000 picoseconds. - Weight::from_parts(3_099_000, 0) + // Minimum execution time: 3_483_000 picoseconds. + Weight::from_parts(3_598_000, 0) } pub fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_955_000 picoseconds. - Weight::from_parts(2_050_000, 0) + // Minimum execution time: 2_241_000 picoseconds. + Weight::from_parts(2_297_000, 0) } pub fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_939_000 picoseconds. - Weight::from_parts(1_990_000, 0) + // Minimum execution time: 2_230_000 picoseconds. + Weight::from_parts(2_318_000, 0) } pub fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_841_000 picoseconds. - Weight::from_parts(1_900_000, 0) + // Minimum execution time: 2_051_000 picoseconds. + Weight::from_parts(2_153_000, 0) } pub fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_081_000 picoseconds. - Weight::from_parts(2_145_000, 0) + // Minimum execution time: 2_306_000 picoseconds. + Weight::from_parts(2_380_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -270,8 +270,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 59_600_000 picoseconds. - Weight::from_parts(61_572_000, 6196) + // Minimum execution time: 60_201_000 picoseconds. + Weight::from_parts(61_132_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -279,8 +279,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_390_000 picoseconds. - Weight::from_parts(4_517_000, 0) + // Minimum execution time: 4_554_000 picoseconds. + Weight::from_parts(4_704_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -302,8 +302,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 53_864_000 picoseconds. - Weight::from_parts(55_527_000, 6196) + // Minimum execution time: 56_071_000 picoseconds. + Weight::from_parts(56_889_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -311,27 +311,25 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_879_000 picoseconds. - Weight::from_parts(1_947_000, 0) + // Minimum execution time: 2_093_000 picoseconds. + Weight::from_parts(2_169_000, 0) } pub fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_827_000 picoseconds. - Weight::from_parts(1_900_000, 0) + // Minimum execution time: 2_027_000 picoseconds. + Weight::from_parts(2_172_000, 0) } pub fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_824_000 picoseconds. - Weight::from_parts(1_898_000, 0) + // Minimum execution time: 2_035_000 picoseconds. + Weight::from_parts(2_164_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - // Storage: `PolkadotXcm::SupportedVersion` (r:2 w:0) - // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) // Storage: `BridgeWestendMessages::PalletOperatingMode` (r:1 w:0) // Proof: `BridgeWestendMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) // Storage: `BridgeWestendMessages::OutboundLanes` (r:1 w:1) @@ -343,27 +341,27 @@ impl WeightInfo { /// The range of component `x` is `[1, 1000]`. pub fn export_message(x: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `190` - // Estimated: `6130` - // Minimum execution time: 41_598_000 picoseconds. - Weight::from_parts(42_219_173, 6130) - // Standard Error: 426 - .saturating_add(Weight::from_parts(452_460, 0).saturating_mul(x.into())) - .saturating_add(T::DbWeight::get().reads(6)) + // Measured: `96` + // Estimated: `1529` + // Minimum execution time: 25_636_000 picoseconds. + Weight::from_parts(25_405_640, 1529) + // Standard Error: 321 + .saturating_add(Weight::from_parts(365_002, 0).saturating_mul(x.into())) + .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } pub fn set_fees_mode() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_812_000 picoseconds. - Weight::from_parts(1_898_000, 0) + // Minimum execution time: 2_036_000 picoseconds. + Weight::from_parts(2_136_000, 0) } pub fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_915_000 picoseconds. - Weight::from_parts(1_976_000, 0) + // Minimum execution time: 2_147_000 picoseconds. + Weight::from_parts(2_276_000, 0) } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs index 19fb4fdea0f..de7b5315c88 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs @@ -20,8 +20,7 @@ use super::{ TransactionByteFee, WeightToFee, XcmpQueue, }; use crate::bridge_common_config::{ - BridgeGrandpaRococoBulletinInstance, BridgeGrandpaWestendInstance, DeliveryRewardInBalance, - RequiredStakeForStakeAndSlash, + BridgeGrandpaWestendInstance, DeliveryRewardInBalance, RequiredStakeForStakeAndSlash, }; use bp_messages::LaneId; use bp_relayers::{PayRewardFromAccount, RewardsAccountOwner, RewardsAccountParams}; @@ -34,25 +33,21 @@ use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; use parachains_common::{ impls::ToStakingPot, - xcm_config::{ - AllSiblingSystemParachains, ConcreteAssetFromSystem, ParentRelayOrSiblingParachains, - RelayOrOtherSystemParachains, - }, + xcm_config::{ConcreteAssetFromSystem, RelayOrOtherSystemParachains}, TREASURY_PALLET_ID, }; use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; +use rococo_runtime_constants::system_parachain; use sp_core::Get; use sp_runtime::traits::AccountIdConversion; use sp_std::marker::PhantomData; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter; use xcm_builder::{ deposit_or_burn_fee, AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, - DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, HandleFee, IsConcrete, - ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, + CurrencyAdapter, DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, HandleFee, + IsConcrete, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, @@ -73,7 +68,6 @@ parameter_types! { pub const MaxAssetsIntoHolding: u32 = 64; pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating(); pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(rococo_runtime_constants::TREASURY_PALLET_ID)).into(); - pub SiblingPeople: MultiLocation = (Parent, Parachain(rococo_runtime_constants::system_parachain::PEOPLE_ID)).into(); } /// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used @@ -89,7 +83,6 @@ pub type LocationToAccountId = ( ); /// Means for transacting the native currency on this chain. -#[allow(deprecated)] pub type CurrencyTransactor = CurrencyAdapter< // Use this currency: Balances, @@ -132,6 +125,10 @@ match_types! { MultiLocation { parents: 1, interior: Here } | MultiLocation { parents: 1, interior: X1(Plurality { .. }) } }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; } /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly @@ -189,10 +186,6 @@ impl Contains for SafeCallFilter { RuntimeCall::BridgeWestendGrandpa(pallet_bridge_grandpa::Call::< Runtime, BridgeGrandpaWestendInstance, - >::initialize { .. }) | - RuntimeCall::BridgePolkadotBulletinGrandpa(pallet_bridge_grandpa::Call::< - Runtime, - BridgeGrandpaRococoBulletinInstance, >::initialize { .. }) ) } @@ -211,15 +204,14 @@ pub type Barrier = TrailingSetTopicAsId< // If the message is one that immediately attempts to pay for execution, then // allow it. AllowTopLevelPaidExecutionFrom, - // Parent, its pluralities (i.e. governance bodies), relay treasury pallet - // and sibling People get free execution. + // Parent, its pluralities (i.e. governance bodies) and relay treasury pallet + // get free execution. AllowExplicitUnpaidExecutionFrom<( ParentOrParentsPlurality, Equals, - Equals, )>, // Subscriptions for version tracking are OK. - AllowSubscriptionsFrom, + AllowSubscriptionsFrom, ), UniversalLocation, ConstU32<8>, @@ -228,13 +220,25 @@ pub type Barrier = TrailingSetTopicAsId< >, >; +match_types! { + pub type SystemParachains: impl Contains = { + MultiLocation { + parents: 1, + interior: X1(Parachain( + system_parachain::ASSET_HUB_ID | + system_parachain::BRIDGE_HUB_ID | + system_parachain::CONTRACTS_ID | + system_parachain::ENCOINTER_ID + )), + } + }; +} + /// Locations that will not be charged fees in the executor, /// either execution or delivery. /// We only waive fees for system functions, which these locations represent. -pub type WaivedLocations = ( - RelayOrOtherSystemParachains, - Equals, -); +pub type WaivedLocations = + (RelayOrOtherSystemParachains, Equals); /// Cases where a remote origin is accepted as trusted Teleporter for a given asset: /// - NativeToken with the parent Relay Chain and sibling parachains. @@ -280,10 +284,7 @@ impl xcm_executor::Config for XcmConfig { XcmFeeToAccount, ), >; - type MessageExporter = ( - crate::bridge_to_westend_config::ToBridgeHubWestendHaulBlobExporter, - crate::bridge_to_bulletin_config::ToRococoBulletinHaulBlobExporter, - ); + type MessageExporter = (crate::bridge_to_westend_config::ToBridgeHubWestendHaulBlobExporter,); type UniversalAliases = Nothing; type CallDispatcher = WithOriginFilter; type SafeCallFilter = SafeCallFilter; diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs index 6e9ba1feecc..70d3f09d0ef 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs @@ -18,14 +18,15 @@ use bp_polkadot_core::Signature; use bridge_hub_rococo_runtime::{ - bridge_common_config, bridge_to_bulletin_config, bridge_to_westend_config, + bridge_common_config, bridge_to_westend_config, xcm_config::{RelayNetwork, TokenLocation, XcmConfig}, AllPalletsWithoutSystem, BridgeRejectObsoleteHeadersAndMessages, Executive, ExistentialDeposit, - ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, SessionKeys, + ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, SessionKeys, TransactionPayment, TxExtension, UncheckedExtrinsic, }; use codec::{Decode, Encode}; -use frame_support::{dispatch::GetDispatchInfo, parameter_types, traits::ConstU8}; +use frame_support::{dispatch::GetDispatchInfo, parameter_types}; +use frame_system::pallet_prelude::HeaderFor; use parachains_common::{rococo::fee::WeightToFee, AccountId, AuraId, Balance}; use sp_keyring::AccountKeyring::Alice; use sp_runtime::{ @@ -34,6 +35,9 @@ use sp_runtime::{ }; use xcm::latest::prelude::*; +// Para id of sibling chain used in tests. +pub const SIBLING_PARACHAIN_ID: u32 = 1000; + parameter_types! { pub CheckingAccount: AccountId = PolkadotXcm::check_account(); } @@ -42,30 +46,24 @@ fn construct_extrinsic( sender: sp_keyring::AccountKeyring, call: RuntimeCall, ) -> UncheckedExtrinsic { - let account_id = AccountId32::from(sender.public()); let tx_ext: TxExtension = ( frame_system::CheckNonZeroSender::::new(), frame_system::CheckSpecVersion::::new(), frame_system::CheckTxVersion::::new(), frame_system::CheckGenesis::::new(), frame_system::CheckEra::::from(Era::immortal()), - frame_system::CheckNonce::::from( - frame_system::Pallet::::account(&account_id).nonce, - ), + frame_system::CheckNonce::::from(0), frame_system::CheckWeight::::new(), pallet_transaction_payment::ChargeTransactionPayment::::from(0), BridgeRejectObsoleteHeadersAndMessages::default(), - ( - bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages::default(), - bridge_to_bulletin_config::OnBridgeHubRococoRefundRococoBulletinMessages::default(), - ), + (bridge_to_westend_config::OnBridgeHubRococoRefundBridgeHubWestendMessages::default(),), ) .into(); let payload = SignedPayload::new(call.clone(), tx_ext.clone()).unwrap(); let signature = payload.using_encoded(|e| sender.sign(e)); UncheckedExtrinsic::new_signed( call, - account_id.into(), + AccountId32::from(sender.public()).into(), Signature::Sr25519(signature.clone()), tx_ext, ) @@ -73,9 +71,10 @@ fn construct_extrinsic( fn construct_and_apply_extrinsic( relayer_at_target: sp_keyring::AccountKeyring, - call: RuntimeCall, + batch: pallet_utility::Call, ) -> sp_runtime::DispatchOutcome { - let xt = construct_extrinsic(relayer_at_target, call); + let batch_call = RuntimeCall::Utility(batch); + let xt = construct_extrinsic(relayer_at_target, batch_call); let r = Executive::apply_extrinsic(xt); r.unwrap() } @@ -87,6 +86,10 @@ fn construct_and_estimate_extrinsic_fee(batch: pallet_utility::Call) -> TransactionPayment::compute_fee(xt.encoded_size() as _, &batch_info, 0) } +fn executive_init_block(header: &HeaderFor) { + Executive::initialize_block(header) +} + fn collator_session_keys() -> bridge_hub_test_utils::CollatorSessionKeys { bridge_hub_test_utils::CollatorSessionKeys::new( AccountId::from(Alice), @@ -95,61 +98,38 @@ fn collator_session_keys() -> bridge_hub_test_utils::CollatorSessionKeys| { - match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { - Ok(RuntimeEvent::PolkadotXcm(event)) => Some(event), - _ => None, - } - }), - bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID -); - -#[test] -fn change_required_stake_by_governance_works() { - bridge_hub_test_utils::test_cases::change_storage_constant_by_governance_works::< - Runtime, - bridge_common_config::RequiredStakeForStakeAndSlash, - Balance, - >( - collator_session_keys(), - bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, - Box::new(|call| RuntimeCall::System(call).encode()), - || { - ( - bridge_common_config::RequiredStakeForStakeAndSlash::key().to_vec(), - bridge_common_config::RequiredStakeForStakeAndSlash::get(), - ) - }, - |old_value| old_value.checked_mul(2).unwrap(), - ) -} - -mod bridge_hub_westend_tests { +mod bridge_hub_rococo_tests { use super::*; use bridge_common_config::{ BridgeGrandpaWestendInstance, BridgeParachainWestendInstance, DeliveryRewardInBalance, + RequiredStakeForStakeAndSlash, }; use bridge_to_westend_config::{ - BridgeHubWestendChainId, BridgeHubWestendLocation, WestendGlobalConsensusNetwork, - WithBridgeHubWestendMessageBridge, WithBridgeHubWestendMessagesInstance, - XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND, + BridgeHubWestendChainId, WestendGlobalConsensusNetwork, WithBridgeHubWestendMessageBridge, + WithBridgeHubWestendMessagesInstance, XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND, }; - // Para id of sibling chain used in tests. - pub const SIBLING_PARACHAIN_ID: u32 = 1000; + bridge_hub_test_utils::test_cases::include_teleports_for_native_asset_works!( + Runtime, + AllPalletsWithoutSystem, + XcmConfig, + CheckingAccount, + WeightToFee, + ParachainSystem, + collator_session_keys(), + ExistentialDeposit::get(), + Box::new(|runtime_event_encoded: Vec| { + match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { + Ok(RuntimeEvent::PolkadotXcm(event)) => Some(event), + _ => None, + } + }), + bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID + ); #[test] fn initialize_bridge_by_governance_works() { - // for RococoBulletin finality + // for Westend finality bridge_hub_test_utils::test_cases::initialize_bridge_by_governance_works::< Runtime, BridgeGrandpaWestendInstance, @@ -175,6 +155,26 @@ mod bridge_hub_westend_tests { ) } + #[test] + fn change_required_stake_by_governance_works() { + bridge_hub_test_utils::test_cases::change_storage_constant_by_governance_works::< + Runtime, + RequiredStakeForStakeAndSlash, + Balance, + >( + collator_session_keys(), + bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, + Box::new(|call| RuntimeCall::System(call).encode()), + || { + ( + RequiredStakeForStakeAndSlash::key().to_vec(), + RequiredStakeForStakeAndSlash::get(), + ) + }, + |old_value| old_value.checked_mul(2).unwrap(), + ) + } + #[test] fn handle_export_message_from_system_parachain_add_to_outbound_queue_works() { // for Westend @@ -192,12 +192,12 @@ mod bridge_hub_westend_tests { _ => None, } }), - || ExportMessage { network: Westend, destination: X1(Parachain(bridge_to_westend_config::AssetHubWestendParaId::get().into())), xcm: Xcm(vec![]) }, + || ExportMessage { network: Westend, destination: X1(Parachain(1234)), xcm: Xcm(vec![]) }, XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND, Some((TokenLocation::get(), ExistentialDeposit::get()).into()), // value should be >= than value generated by `can_calculate_weight_for_paid_export_message_with_reserve_transfer` Some((TokenLocation::get(), bp_bridge_hub_rococo::BridgeHubRococoBaseXcmFeeInRocs::get()).into()), - || PolkadotXcm::force_xcm_version(RuntimeOrigin::root(), Box::new(BridgeHubWestendLocation::get()), XCM_VERSION).expect("version saved!"), + || (), ) } @@ -212,7 +212,6 @@ mod bridge_hub_westend_tests { WithBridgeHubWestendMessagesInstance, RelayNetwork, WestendGlobalConsensusNetwork, - ConstU8<2>, >( collator_session_keys(), bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, @@ -237,9 +236,10 @@ mod bridge_hub_westend_tests { #[test] fn relayed_incoming_message_works() { // from Westend - bridge_hub_test_utils::test_cases::from_parachain::relayed_incoming_message_works::< + bridge_hub_test_utils::test_cases::relayed_incoming_message_works::< Runtime, AllPalletsWithoutSystem, + XcmConfig, ParachainSystem, BridgeGrandpaWestendInstance, BridgeParachainWestendInstance, @@ -249,19 +249,17 @@ mod bridge_hub_westend_tests { collator_session_keys(), bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, bp_bridge_hub_westend::BRIDGE_HUB_WESTEND_PARACHAIN_ID, - BridgeHubWestendChainId::get(), SIBLING_PARACHAIN_ID, Rococo, XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND, || (), - construct_and_apply_extrinsic, ) } #[test] pub fn complex_relay_extrinsic_works() { // for Westend - bridge_hub_test_utils::test_cases::from_parachain::complex_relay_extrinsic_works::< + bridge_hub_test_utils::test_cases::complex_relay_extrinsic_works::< Runtime, AllPalletsWithoutSystem, XcmConfig, @@ -278,8 +276,10 @@ mod bridge_hub_westend_tests { BridgeHubWestendChainId::get(), Rococo, XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND, - || (), + ExistentialDeposit::get(), + executive_init_block, construct_and_apply_extrinsic, + || (), ); } @@ -303,7 +303,7 @@ mod bridge_hub_westend_tests { #[test] pub fn can_calculate_fee_for_complex_message_delivery_transaction() { - let estimated = bridge_hub_test_utils::test_cases::from_parachain::can_calculate_fee_for_complex_message_delivery_transaction::< + let estimated = bridge_hub_test_utils::test_cases::can_calculate_fee_for_complex_message_delivery_transaction::< Runtime, BridgeGrandpaWestendInstance, BridgeParachainWestendInstance, @@ -326,7 +326,7 @@ mod bridge_hub_westend_tests { #[test] pub fn can_calculate_fee_for_complex_message_confirmation_transaction() { - let estimated = bridge_hub_test_utils::test_cases::from_parachain::can_calculate_fee_for_complex_message_confirmation_transaction::< + let estimated = bridge_hub_test_utils::test_cases::can_calculate_fee_for_complex_message_confirmation_transaction::< Runtime, BridgeGrandpaWestendInstance, BridgeParachainWestendInstance, @@ -347,198 +347,3 @@ mod bridge_hub_westend_tests { ); } } - -mod bridge_hub_bulletin_tests { - use super::*; - use bridge_common_config::BridgeGrandpaRococoBulletinInstance; - use bridge_to_bulletin_config::{ - RococoBulletinChainId, RococoBulletinGlobalConsensusNetwork, - RococoBulletinGlobalConsensusNetworkLocation, WithRococoBulletinMessageBridge, - WithRococoBulletinMessagesInstance, XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN, - }; - - // Para id of sibling chain used in tests. - pub const SIBLING_PARACHAIN_ID: u32 = rococo_runtime_constants::system_parachain::PEOPLE_ID; - - #[test] - fn initialize_bridge_by_governance_works() { - // for Bulletin finality - bridge_hub_test_utils::test_cases::initialize_bridge_by_governance_works::< - Runtime, - BridgeGrandpaRococoBulletinInstance, - >( - collator_session_keys(), - bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, - Box::new(|call| RuntimeCall::BridgePolkadotBulletinGrandpa(call).encode()), - ) - } - - #[test] - fn handle_export_message_from_system_parachain_add_to_outbound_queue_works() { - // for Bulletin - bridge_hub_test_utils::test_cases::handle_export_message_from_system_parachain_to_outbound_queue_works::< - Runtime, - XcmConfig, - WithRococoBulletinMessagesInstance, - >( - collator_session_keys(), - bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, - SIBLING_PARACHAIN_ID, - Box::new(|runtime_event_encoded: Vec| { - match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { - Ok(RuntimeEvent::BridgePolkadotBulletinMessages(event)) => Some(event), - _ => None, - } - }), - || ExportMessage { - network: RococoBulletinGlobalConsensusNetwork::get(), - destination: Here, - xcm: Xcm(vec![]), - }, - XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN, - Some((TokenLocation::get(), ExistentialDeposit::get()).into()), - None, - || PolkadotXcm::force_xcm_version(RuntimeOrigin::root(), Box::new(RococoBulletinGlobalConsensusNetworkLocation::get()), XCM_VERSION).expect("version saved!"), - ) - } - - #[test] - fn message_dispatch_routing_works() { - // from Bulletin - bridge_hub_test_utils::test_cases::message_dispatch_routing_works::< - Runtime, - AllPalletsWithoutSystem, - XcmConfig, - ParachainSystem, - WithRococoBulletinMessagesInstance, - RelayNetwork, - RococoBulletinGlobalConsensusNetwork, - ConstU8<2>, - >( - collator_session_keys(), - bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, - SIBLING_PARACHAIN_ID, - Box::new(|runtime_event_encoded: Vec| { - match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { - Ok(RuntimeEvent::ParachainSystem(event)) => Some(event), - _ => None, - } - }), - Box::new(|runtime_event_encoded: Vec| { - match RuntimeEvent::decode(&mut &runtime_event_encoded[..]) { - Ok(RuntimeEvent::XcmpQueue(event)) => Some(event), - _ => None, - } - }), - XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN, - || (), - ) - } - - #[test] - fn relayed_incoming_message_works() { - // from Bulletin - bridge_hub_test_utils::test_cases::from_grandpa_chain::relayed_incoming_message_works::< - Runtime, - AllPalletsWithoutSystem, - ParachainSystem, - BridgeGrandpaRococoBulletinInstance, - WithRococoBulletinMessagesInstance, - WithRococoBulletinMessageBridge, - >( - collator_session_keys(), - bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, - RococoBulletinChainId::get(), - SIBLING_PARACHAIN_ID, - Rococo, - XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN, - || (), - construct_and_apply_extrinsic, - ) - } - - #[test] - pub fn complex_relay_extrinsic_works() { - // for Bulletin - bridge_hub_test_utils::test_cases::from_grandpa_chain::complex_relay_extrinsic_works::< - Runtime, - AllPalletsWithoutSystem, - XcmConfig, - ParachainSystem, - BridgeGrandpaRococoBulletinInstance, - WithRococoBulletinMessagesInstance, - WithRococoBulletinMessageBridge, - >( - collator_session_keys(), - bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, - SIBLING_PARACHAIN_ID, - RococoBulletinChainId::get(), - Rococo, - XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN, - || (), - construct_and_apply_extrinsic, - ); - } - - #[test] - pub fn can_calculate_weight_for_paid_export_message_with_reserve_transfer() { - let estimated = bridge_hub_test_utils::test_cases::can_calculate_weight_for_paid_export_message_with_reserve_transfer::< - Runtime, - XcmConfig, - WeightToFee, - >(); - - // check if estimated value is sane - let max_expected = bp_bridge_hub_rococo::BridgeHubRococoBaseXcmFeeInRocs::get(); - assert!( - estimated <= max_expected, - "calculated: {:?}, max_expected: {:?}, please adjust `bp_bridge_hub_rococo::BridgeHubRococoBaseXcmFeeInRocs` value", - estimated, - max_expected - ); - } - - #[test] - pub fn can_calculate_fee_for_complex_message_delivery_transaction() { - let estimated = bridge_hub_test_utils::test_cases::from_grandpa_chain::can_calculate_fee_for_complex_message_delivery_transaction::< - Runtime, - BridgeGrandpaRococoBulletinInstance, - WithRococoBulletinMessagesInstance, - WithRococoBulletinMessageBridge, - >( - collator_session_keys(), - construct_and_estimate_extrinsic_fee - ); - - // check if estimated value is sane - let max_expected = bp_bridge_hub_rococo::BridgeHubRococoBaseDeliveryFeeInRocs::get(); - assert!( - estimated <= max_expected, - "calculated: {:?}, max_expected: {:?}, please adjust `bp_bridge_hub_rococo::BridgeHubRococoBaseDeliveryFeeInRocs` value", - estimated, - max_expected - ); - } - - #[test] - pub fn can_calculate_fee_for_complex_message_confirmation_transaction() { - let estimated = bridge_hub_test_utils::test_cases::from_grandpa_chain::can_calculate_fee_for_complex_message_confirmation_transaction::< - Runtime, - BridgeGrandpaRococoBulletinInstance, - WithRococoBulletinMessagesInstance, - WithRococoBulletinMessageBridge, - >( - collator_session_keys(), - construct_and_estimate_extrinsic_fee - ); - - // check if estimated value is sane - let max_expected = bp_bridge_hub_rococo::BridgeHubRococoBaseConfirmationFeeInRocs::get(); - assert!( - estimated <= max_expected, - "calculated: {:?}, max_expected: {:?}, please adjust `bp_bridge_hub_rococo::BridgeHubRococoBaseConfirmationFeeInRocs` value", - estimated, - max_expected - ); - } -} 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 07c1a328285..7e384126ab6 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true description = "Westend's BridgeHub parachain runtime" license = "Apache-2.0" -[lints] -workspace = true - [build-dependencies] substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } @@ -17,57 +14,58 @@ codec = { package = "parity-scale-codec", version = "3.0.0", default-features = hex-literal = { version = "0.4.1" } log = { version = "0.4.20", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", optional = true, features = ["derive"] } +serde = { version = "1.0.188", optional = true, features = ["derive"] } smallvec = "1.11.0" # 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 } +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 } +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} # Polkadot -westend-runtime-constants = { path = "../../../../../polkadot/runtime/westend/constants", default-features = false } -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } +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-core-primitives = { path = "../../../../../polkadot/core-primitives", 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 } +polkadot-core-primitives = { path = "../../../../../polkadot/core-primitives", 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} # Cumulus cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } +cumulus-pallet-dmp-queue = { path = "../../../../pallets/dmp-queue", default-features = false } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } +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-core = { path = "../../../../primitives/core", default-features = false } @@ -77,7 +75,6 @@ parachain-info = { package = "staging-parachain-info", path = "../../../pallets/ parachains-common = { path = "../../../common", default-features = false } # Bridges -bp-asset-hub-rococo = { path = "../../../../../bridges/primitives/chain-asset-hub-rococo", default-features = false } bp-asset-hub-westend = { path = "../../../../../bridges/primitives/chain-asset-hub-westend", default-features = false } bp-bridge-hub-rococo = { path = "../../../../../bridges/primitives/chain-bridge-hub-rococo", default-features = false } bp-bridge-hub-westend = { path = "../../../../../bridges/primitives/chain-bridge-hub-westend", default-features = false } @@ -93,7 +90,6 @@ pallet-bridge-grandpa = { path = "../../../../../bridges/modules/grandpa", defau 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 } [dev-dependencies] @@ -103,9 +99,8 @@ bridge-runtime-common = { path = "../../../../../bridges/bin/runtime-common", fe sp-keyring = { path = "../../../../../substrate/primitives/keyring" } [features] -default = ["std"] +default = [ "std" ] std = [ - "bp-asset-hub-rococo/std", "bp-asset-hub-westend/std", "bp-bridge-hub-rococo/std", "bp-bridge-hub-westend/std", @@ -120,6 +115,7 @@ std = [ "bridge-runtime-common/std", "codec/std", "cumulus-pallet-aura-ext/std", + "cumulus-pallet-dmp-queue/std", "cumulus-pallet-parachain-system/std", "cumulus-pallet-session-benchmarking/std", "cumulus-pallet-xcm/std", @@ -150,7 +146,6 @@ std = [ "pallet-transaction-payment/std", "pallet-utility/std", "pallet-xcm-benchmarks?/std", - "pallet-xcm-bridge-hub/std", "pallet-xcm/std", "parachain-info/std", "parachains-common/std", @@ -182,6 +177,7 @@ std = [ runtime-benchmarks = [ "bridge-runtime-common/runtime-benchmarks", + "cumulus-pallet-dmp-queue/runtime-benchmarks", "cumulus-pallet-parachain-system/runtime-benchmarks", "cumulus-pallet-session-benchmarking/runtime-benchmarks", "cumulus-pallet-xcmp-queue/runtime-benchmarks", @@ -202,7 +198,6 @@ runtime-benchmarks = [ "pallet-timestamp/runtime-benchmarks", "pallet-utility/runtime-benchmarks", "pallet-xcm-benchmarks/runtime-benchmarks", - "pallet-xcm-bridge-hub/runtime-benchmarks", "pallet-xcm/runtime-benchmarks", "parachains-common/runtime-benchmarks", "polkadot-parachain-primitives/runtime-benchmarks", @@ -214,6 +209,7 @@ runtime-benchmarks = [ try-runtime = [ "cumulus-pallet-aura-ext/try-runtime", + "cumulus-pallet-dmp-queue/try-runtime", "cumulus-pallet-parachain-system/try-runtime", "cumulus-pallet-xcm/try-runtime", "cumulus-pallet-xcmp-queue/try-runtime", @@ -235,16 +231,15 @@ try-runtime = [ "pallet-timestamp/try-runtime", "pallet-transaction-payment/try-runtime", "pallet-utility/try-runtime", - "pallet-xcm-bridge-hub/try-runtime", "pallet-xcm/try-runtime", "parachain-info/try-runtime", "polkadot-runtime-common/try-runtime", "sp-runtime/try-runtime", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] # A feature that should be enabled when the runtime should be built for on-chain # deployment. This will disable stuff that shouldn't be part of the on-chain wasm # to make it smaller like logging for example. -on-chain-release-build = ["sp-api/disable-logging"] +on-chain-release-build = [ "sp-api/disable-logging" ] diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs index 36eb7c4d25e..fdb30b19721 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs @@ -17,9 +17,8 @@ //! Bridge definitions used on BridgeHub with the Westend flavor. use crate::{ - bridge_common_config::DeliveryRewardInBalance, weights, xcm_config::UniversalLocation, - AccountId, BridgeRococoMessages, PolkadotXcm, Runtime, RuntimeEvent, RuntimeOrigin, - XcmOverBridgeHubRococo, XcmRouter, + bridge_common_config::DeliveryRewardInBalance, weights, AccountId, BridgeRococoMessages, + ParachainInfo, Runtime, RuntimeEvent, RuntimeOrigin, XcmRouter, }; use bp_messages::LaneId; use bp_parachains::SingleParaStoredHeaderDataBuilder; @@ -32,7 +31,7 @@ use bridge_runtime_common::{ }, messages_xcm_extension::{ SenderAndLane, XcmAsPlainPayload, XcmBlobHauler, XcmBlobHaulerAdapter, - XcmBlobMessageDispatch, XcmVersionOfDestAndRemoteBridge, + XcmBlobMessageDispatch, }, refund_relayer_extension::{ ActualFeeRefund, RefundBridgedParachainMessages, RefundTransactionExtensionAdapter, @@ -49,7 +48,7 @@ use xcm::{ latest::prelude::*, prelude::{InteriorMultiLocation, NetworkId}, }; -use xcm_builder::BridgeBlobDispatcher; +use xcm_builder::{BridgeBlobDispatcher, HaulBlobExporter}; parameter_types! { pub const RelayChainHeadersToKeep: u32 = 1024; @@ -63,42 +62,24 @@ parameter_types! { pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = bp_bridge_hub_westend::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; pub const BridgeHubRococoChainId: bp_runtime::ChainId = bp_runtime::BRIDGE_HUB_ROCOCO_CHAIN_ID; + pub BridgeHubWestendUniversalLocation: InteriorMultiLocation = X2(GlobalConsensus(Westend), Parachain(ParachainInfo::parachain_id().into())); pub BridgeWestendToRococoMessagesPalletInstance: InteriorMultiLocation = X1(PalletInstance(::index() as u8)); pub RococoGlobalConsensusNetwork: NetworkId = NetworkId::Rococo; - pub RococoGlobalConsensusNetworkLocation: MultiLocation = MultiLocation { - parents: 2, - interior: X1(GlobalConsensus(RococoGlobalConsensusNetwork::get())) - }; + pub ActiveOutboundLanesToBridgeHubRococo: &'static [bp_messages::LaneId] = &[XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO]; + pub const AssetHubWestendToAssetHubRococoMessagesLane: bp_messages::LaneId = XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO; // see the `FEE_BOOST_PER_MESSAGE` constant to get the meaning of this value pub PriorityBoostPerMessage: u64 = 182_044_444_444_444; pub AssetHubWestendParaId: cumulus_primitives_core::ParaId = bp_asset_hub_westend::ASSET_HUB_WESTEND_PARACHAIN_ID.into(); - pub AssetHubRococoParaId: cumulus_primitives_core::ParaId = bp_asset_hub_rococo::ASSET_HUB_ROCOCO_PARACHAIN_ID.into(); - // Lanes - pub ActiveOutboundLanesToBridgeHubRococo: &'static [bp_messages::LaneId] = &[XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO]; - pub const AssetHubWestendToAssetHubRococoMessagesLane: bp_messages::LaneId = XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO; pub FromAssetHubWestendToAssetHubRococoRoute: SenderAndLane = SenderAndLane::new( ParentThen(X1(Parachain(AssetHubWestendParaId::get().into()))).into(), XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO, ); - pub ActiveLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorMultiLocation))> = sp_std::vec![ - ( - FromAssetHubWestendToAssetHubRococoRoute::get(), - (RococoGlobalConsensusNetwork::get(), X1(Parachain(AssetHubRococoParaId::get().into()))) - ) - ]; pub CongestedMessage: Xcm<()> = build_congestion_message(true).into(); - pub UncongestedMessage: Xcm<()> = build_congestion_message(false).into(); - pub BridgeHubRococoLocation: MultiLocation = MultiLocation { - parents: 2, - interior: X2( - GlobalConsensus(RococoGlobalConsensusNetwork::get()), - Parachain(::PARACHAIN_ID) - ) - }; + pub UncongestedMessage: Xcm<()> = build_congestion_message(false).into(); } pub const XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO: LaneId = LaneId([0, 0, 0, 2]); @@ -129,16 +110,23 @@ pub type ToRococoBridgeHubMessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof; /// Dispatches received XCM messages from other bridge -type FromRococoMessageBlobDispatcher = - BridgeBlobDispatcher; +type FromRococoMessageBlobDispatcher = BridgeBlobDispatcher< + XcmRouter, + BridgeHubWestendUniversalLocation, + BridgeWestendToRococoMessagesPalletInstance, +>; /// Export XCM messages to be relayed to the other side -pub type ToBridgeHubRococoHaulBlobExporter = XcmOverBridgeHubRococo; - +pub type ToBridgeHubRococoHaulBlobExporter = HaulBlobExporter< + XcmBlobHaulerAdapter, + RococoGlobalConsensusNetwork, + (), +>; pub struct ToBridgeHubRococoXcmBlobHauler; impl XcmBlobHauler for ToBridgeHubRococoXcmBlobHauler { type Runtime = Runtime; type MessagesInstance = WithBridgeHubRococoMessagesInstance; + type SenderAndLane = FromAssetHubWestendToAssetHubRococoRoute; type ToSourceChainSender = XcmRouter; type CongestedMessage = CongestedMessage; @@ -146,7 +134,7 @@ impl XcmBlobHauler for ToBridgeHubRococoXcmBlobHauler { } /// On messages delivered callback. -type OnMessagesDelivered = XcmBlobHaulerAdapter; +type OnMessagesDelivered = XcmBlobHaulerAdapter; /// Messaging Bridge configuration for BridgeHubWestend -> BridgeHubRococo pub struct WithBridgeHubRococoMessageBridge; @@ -268,18 +256,6 @@ impl pallet_bridge_messages::Config for Run type OnMessagesDelivered = OnMessagesDelivered; } -/// Add support for the export and dispatch of XCM programs. -pub type XcmOverBridgeHubRococoInstance = pallet_xcm_bridge_hub::Instance1; -impl pallet_xcm_bridge_hub::Config for Runtime { - type UniversalLocation = UniversalLocation; - type BridgedNetwork = RococoGlobalConsensusNetworkLocation; - type BridgeMessagesPalletInstance = WithBridgeHubRococoMessagesInstance; - type MessageExportPrice = (); - type DestinationVersion = XcmVersionOfDestAndRemoteBridge; - type Lanes = ActiveLanes; - type LanesSupport = ToBridgeHubRococoXcmBlobHauler; -} - #[cfg(test)] mod tests { use super::*; 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 a2091fff760..e429dbb6d65 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 @@ -39,7 +39,7 @@ use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, - traits::Block as BlockT, + traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, }; @@ -50,11 +50,11 @@ use sp_version::NativeVersion; use sp_version::RuntimeVersion; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, parameter_types, - traits::{ConstBool, ConstU32, ConstU64, ConstU8, TransformOrigin}, + traits::{ConstBool, ConstU32, ConstU64, ConstU8, Everything, TransformOrigin}, weights::{ConstantMultiplier, Weight}, PalletId, }; @@ -118,8 +118,6 @@ pub type Migrations = ( pallet_collator_selection::migration::v1::MigrateToV1, pallet_multisig::migrations::v1::MigrateToV1, InitStorageVersions, - // unreleased - cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4, ); /// Migration to initialize storage versions for pallets added after genesis. @@ -172,10 +170,10 @@ 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_005_000, + spec_version: 1_003_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, - transaction_version: 4, + transaction_version: 3, state_version: 1, }; @@ -212,24 +210,41 @@ parameter_types! { // Configure FRAME pallets to include in runtime. -#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { /// The identifier used to distinguish between accounts. type AccountId = AccountId; + /// The aggregated dispatch type that is available for extrinsics. + type RuntimeCall = RuntimeCall; + /// The lookup mechanism to get account ID from whatever is passed in dispatchers. + type Lookup = AccountIdLookup; /// The index type for storing how many extrinsics an account has signed. type Nonce = Nonce; /// The type for hashing blocks and tries. type Hash = Hash; + /// The hashing algorithm used. + type Hashing = BlakeTwo256; /// The block type. type Block = Block; + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + /// The ubiquitous origin type. + type RuntimeOrigin = RuntimeOrigin; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). type BlockHashCount = BlockHashCount; /// Runtime version. type Version = Version; + /// Converts a module to an index of this module in the runtime. + type PalletInfo = PalletInfo; /// The data to be stored in an account. type AccountData = pallet_balances::AccountData; + /// What to do if a new account is created. + type OnNewAccount = (); + /// What to do if an account is fully reaped from the system. + type OnKilledAccount = (); /// The weight of database operations that the runtime can invoke. type DbWeight = RocksDbWeight; + /// The basic call filter to use in dispatchable. + type BaseCallFilter = Everything; /// Weight information for the extrinsics of this pallet. type SystemWeightInfo = weights::frame_system::WeightInfo; /// Block & extrinsics weights: base values and limits. @@ -378,6 +393,12 @@ parameter_types! { pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent; } +impl cumulus_pallet_dmp_queue::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_dmp_queue::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type DmpSink = frame_support::traits::EnqueueWithOrigin; +} + pub const PERIOD: u32 = 6 * HOURS; pub const OFFSET: u32 = 0; @@ -478,6 +499,7 @@ construct_runtime!( XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 31, CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, + DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, // Handy utilities. Utility: pallet_utility::{Pallet, Call, Event} = 40, @@ -488,7 +510,6 @@ construct_runtime!( BridgeRococoGrandpa: pallet_bridge_grandpa::::{Pallet, Call, Storage, Event, Config} = 42, BridgeRococoParachains: pallet_bridge_parachains::::{Pallet, Call, Storage, Event} = 43, BridgeRococoMessages: pallet_bridge_messages::::{Pallet, Call, Storage, Event, Config} = 44, - XcmOverBridgeHubRococo: pallet_xcm_bridge_hub::::{Pallet} = 45, // Message Queue. Importantly, is registered last so that messages are processed after // the `on_initialize` hooks of bridging pallets. @@ -814,18 +835,6 @@ impl_runtime_apis! { // Reserve transfers are disabled on BH. None } - - fn set_up_complex_asset_transfer( - ) -> Option<(MultiAssets, u32, MultiLocation, Box)> { - // BH only supports teleports to system parachain. - // Relay/native token can be teleported between BH and Relay. - let native_location = Parent.into(); - let dest = Parent.into(); - pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::( - native_location, - dest - ) - } } use xcm::latest::prelude::*; @@ -922,28 +931,7 @@ impl_runtime_apis! { fn export_message_origin_and_destination( ) -> Result<(MultiLocation, NetworkId, InteriorMultiLocation), BenchmarkError> { - // save XCM version for remote bridge hub - let _ = PolkadotXcm::force_xcm_version( - RuntimeOrigin::root(), - Box::new(bridge_to_rococo_config::BridgeHubRococoLocation::get()), - XCM_VERSION, - ).map_err(|e| { - log::error!( - "Failed to dispatch `force_xcm_version({:?}, {:?}, {:?})`, error: {:?}", - RuntimeOrigin::root(), - bridge_to_rococo_config::BridgeHubRococoLocation::get(), - XCM_VERSION, - e - ); - BenchmarkError::Stop("XcmVersion was not stored!") - })?; - Ok( - ( - bridge_to_rococo_config::FromAssetHubWestendToAssetHubRococoRoute::get().location, - NetworkId::Rococo, - X1(Parachain(bridge_to_rococo_config::AssetHubRococoParaId::get().into())) - ) - ) + Ok((WestendLocation::get(), NetworkId::Rococo, X1(Parachain(100)))) } fn alias_origin() -> Result<(MultiLocation, MultiLocation), BenchmarkError> { diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/cumulus_pallet_dmp_queue.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/cumulus_pallet_dmp_queue.rs new file mode 100644 index 00000000000..cc41dcd6cbb --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/cumulus_pallet_dmp_queue.rs @@ -0,0 +1,131 @@ +// 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 . + +//! Autogenerated weights for `cumulus_pallet_dmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-10-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=cumulus_pallet_dmp_queue +// --chain=asset-hub-kusama-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_dmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_dmp_queue::WeightInfo for WeightInfo { + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65696` + // Estimated: `69161` + // Minimum execution time: 124_651_000 picoseconds. + Weight::from_parts(127_857_000, 0) + .saturating_add(Weight::from_parts(0, 69161)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65659` + // Estimated: `69124` + // Minimum execution time: 65_684_000 picoseconds. + Weight::from_parts(68_039_000, 0) + .saturating_add(Weight::from_parts(0, 69124)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_overweight_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65726` + // Estimated: `69191` + // Minimum execution time: 117_657_000 picoseconds. + Weight::from_parts(122_035_000, 0) + .saturating_add(Weight::from_parts(0, 69191)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + fn on_idle_overweight_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65689` + // Estimated: `69154` + // Minimum execution time: 59_799_000 picoseconds. + Weight::from_parts(61_354_000, 0) + .saturating_add(Weight::from_parts(0, 69154)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/mod.rs index ee49c72ea5f..833944ebfa5 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/mod.rs @@ -21,6 +21,7 @@ use ::pallet_bridge_messages::WeightInfoExt as MessagesWeightInfoExt; use ::pallet_bridge_parachains::WeightInfoExt as ParachainsWeightInfoExt; pub mod block_weights; +pub mod cumulus_pallet_dmp_queue; pub mod cumulus_pallet_parachain_system; pub mod cumulus_pallet_xcmp_queue; pub mod extrinsic_weights; diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_grandpa.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_grandpa.rs index e87ed668dfc..b0634ff2ccf 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_grandpa.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_grandpa.rs @@ -17,10 +17,10 @@ //! Autogenerated weights for `pallet_bridge_grandpa` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-13, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-10-27, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-westend-dev")`, DB CACHE: 1024 +//! HOSTNAME: `runner-vmdtonbz-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: // target/production/polkadot-parachain @@ -33,9 +33,9 @@ // --heap-pages=4096 // --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json // --pallet=pallet_bridge_grandpa -// --chain=bridge-hub-westend-dev +// --chain=bridge-hub-rococo-dev // --header=./cumulus/file_header.txt -// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/ +// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -62,17 +62,21 @@ impl pallet_bridge_grandpa::WeightInfo for WeightInfo Weight { // Proof Size summary in bytes: - // Measured: `231 + p * (60 ±0)` + // Measured: `268 + p * (60 ±0)` // Estimated: `51735` - // Minimum execution time: 303_549_000 picoseconds. - Weight::from_parts(306_232_000, 0) + // Minimum execution time: 304_726_000 picoseconds. + Weight::from_parts(16_868_060, 0) .saturating_add(Weight::from_parts(0, 51735)) - // Standard Error: 4_641 - .saturating_add(Weight::from_parts(55_196_301, 0).saturating_mul(p.into())) - // Standard Error: 35_813 - .saturating_add(Weight::from_parts(70_584, 0).saturating_mul(v.into())) + // Standard Error: 2_802 + .saturating_add(Weight::from_parts(55_200_017, 0).saturating_mul(p.into())) + // Standard Error: 46_745 + .saturating_add(Weight::from_parts(2_689_151, 0).saturating_mul(v.into())) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(5)) } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_messages.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_messages.rs index 305a8726fa1..5d229497f3e 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_messages.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_messages.rs @@ -17,10 +17,10 @@ //! Autogenerated weights for `pallet_bridge_messages` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-13, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-10-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-westend-dev")`, DB CACHE: 1024 +//! HOSTNAME: `runner-vmdtonbz-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: // target/production/polkadot-parachain @@ -33,9 +33,9 @@ // --heap-pages=4096 // --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json // --pallet=pallet_bridge_messages -// --chain=bridge-hub-westend-dev +// --chain=bridge-hub-rococo-dev // --header=./cumulus/file_header.txt -// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/ +// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -48,170 +48,170 @@ use core::marker::PhantomData; /// Weight functions for `pallet_bridge_messages`. pub struct WeightInfo(PhantomData); impl pallet_bridge_messages::WeightInfo for WeightInfo { - /// Storage: `BridgeRococoMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::PalletOperatingMode` (r:1 w:0) + /// Proof: `BridgeWestendToRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:1 w:0) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgeRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHeads` (r:1 w:0) + /// Proof: `BridgeRococoParachain::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::InboundLanes` (r:1 w:1) + /// Proof: `BridgeWestendToRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn receive_single_message_proof() -> Weight { // Proof Size summary in bytes: - // Measured: `502` + // Measured: `575` // Estimated: `52645` - // Minimum execution time: 40_646_000 picoseconds. - Weight::from_parts(41_754_000, 0) + // Minimum execution time: 42_332_000 picoseconds. + Weight::from_parts(43_375_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) } - /// Storage: `BridgeRococoMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::PalletOperatingMode` (r:1 w:0) + /// Proof: `BridgeWestendToRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:1 w:0) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgeRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHeads` (r:1 w:0) + /// Proof: `BridgeRococoParachain::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::InboundLanes` (r:1 w:1) + /// Proof: `BridgeWestendToRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn receive_two_messages_proof() -> Weight { // Proof Size summary in bytes: - // Measured: `502` + // Measured: `575` // Estimated: `52645` - // Minimum execution time: 50_898_000 picoseconds. - Weight::from_parts(52_743_000, 0) + // Minimum execution time: 53_139_000 picoseconds. + Weight::from_parts(54_236_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) } - /// Storage: `BridgeRococoMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::PalletOperatingMode` (r:1 w:0) + /// Proof: `BridgeWestendToRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:1 w:0) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgeRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHeads` (r:1 w:0) + /// Proof: `BridgeRococoParachain::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::InboundLanes` (r:1 w:1) + /// Proof: `BridgeWestendToRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn receive_single_message_proof_with_outbound_lane_state() -> Weight { // Proof Size summary in bytes: - // Measured: `502` + // Measured: `575` // Estimated: `52645` - // Minimum execution time: 45_848_000 picoseconds. - Weight::from_parts(47_036_000, 0) + // Minimum execution time: 47_466_000 picoseconds. + Weight::from_parts(48_724_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) } - /// Storage: `BridgeRococoMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::PalletOperatingMode` (r:1 w:0) + /// Proof: `BridgeWestendToRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:1 w:0) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgeRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHeads` (r:1 w:0) + /// Proof: `BridgeRococoParachain::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::InboundLanes` (r:1 w:1) + /// Proof: `BridgeWestendToRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) fn receive_single_message_proof_1_kb() -> Weight { // Proof Size summary in bytes: - // Measured: `433` + // Measured: `543` // Estimated: `52645` - // Minimum execution time: 39_085_000 picoseconds. - Weight::from_parts(41_623_000, 0) + // Minimum execution time: 40_962_000 picoseconds. + Weight::from_parts(42_002_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(1)) } - /// Storage: `BridgeRococoMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::PalletOperatingMode` (r:1 w:0) + /// Proof: `BridgeWestendToRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:1 w:0) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgeRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHeads` (r:1 w:0) + /// Proof: `BridgeRococoParachain::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::InboundLanes` (r:1 w:1) + /// Proof: `BridgeWestendToRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) fn receive_single_message_proof_16_kb() -> Weight { // Proof Size summary in bytes: - // Measured: `433` + // Measured: `543` // Estimated: `52645` - // Minimum execution time: 72_754_000 picoseconds. - Weight::from_parts(74_985_000, 0) + // Minimum execution time: 71_599_000 picoseconds. + Weight::from_parts(74_307_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(1)) } - /// Storage: `BridgeRococoMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:1 w:0) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoMessages::OutboundLanes` (r:1 w:1) - /// Proof: `BridgeRococoMessages::OutboundLanes` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::PalletOperatingMode` (r:1 w:0) + /// Proof: `BridgeWestendToRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHeads` (r:1 w:0) + /// Proof: `BridgeRococoParachain::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::OutboundLanes` (r:1 w:1) + /// Proof: `BridgeWestendToRococoMessages::OutboundLanes` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) /// Storage: UNKNOWN KEY `0x6e0a18b62a1de81c5f519181cc611e18` (r:1 w:0) /// Proof: UNKNOWN KEY `0x6e0a18b62a1de81c5f519181cc611e18` (r:1 w:0) /// Storage: `BridgeRelayers::RelayerRewards` (r:1 w:1) /// Proof: `BridgeRelayers::RelayerRewards` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn receive_delivery_proof_for_single_message() -> Weight { // Proof Size summary in bytes: - // Measured: `337` - // Estimated: `3802` - // Minimum execution time: 31_479_000 picoseconds. - Weight::from_parts(32_280_000, 0) - .saturating_add(Weight::from_parts(0, 3802)) + // Measured: `414` + // Estimated: `3879` + // Minimum execution time: 31_206_000 picoseconds. + Weight::from_parts(32_045_000, 0) + .saturating_add(Weight::from_parts(0, 3879)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)) } - /// Storage: `BridgeRococoMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:1 w:0) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoMessages::OutboundLanes` (r:1 w:1) - /// Proof: `BridgeRococoMessages::OutboundLanes` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::PalletOperatingMode` (r:1 w:0) + /// Proof: `BridgeWestendToRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHeads` (r:1 w:0) + /// Proof: `BridgeRococoParachain::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::OutboundLanes` (r:1 w:1) + /// Proof: `BridgeWestendToRococoMessages::OutboundLanes` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) /// Storage: UNKNOWN KEY `0x6e0a18b62a1de81c5f519181cc611e18` (r:1 w:0) /// Proof: UNKNOWN KEY `0x6e0a18b62a1de81c5f519181cc611e18` (r:1 w:0) /// Storage: `BridgeRelayers::RelayerRewards` (r:1 w:1) /// Proof: `BridgeRelayers::RelayerRewards` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { // Proof Size summary in bytes: - // Measured: `337` - // Estimated: `3802` - // Minimum execution time: 31_807_000 picoseconds. - Weight::from_parts(32_219_000, 0) - .saturating_add(Weight::from_parts(0, 3802)) + // Measured: `414` + // Estimated: `3879` + // Minimum execution time: 31_211_000 picoseconds. + Weight::from_parts(32_171_000, 0) + .saturating_add(Weight::from_parts(0, 3879)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)) } - /// Storage: `BridgeRococoMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:1 w:0) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoMessages::OutboundLanes` (r:1 w:1) - /// Proof: `BridgeRococoMessages::OutboundLanes` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::PalletOperatingMode` (r:1 w:0) + /// Proof: `BridgeWestendToRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHeads` (r:1 w:0) + /// Proof: `BridgeRococoParachain::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::OutboundLanes` (r:1 w:1) + /// Proof: `BridgeWestendToRococoMessages::OutboundLanes` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) /// Storage: UNKNOWN KEY `0x6e0a18b62a1de81c5f519181cc611e18` (r:1 w:0) /// Proof: UNKNOWN KEY `0x6e0a18b62a1de81c5f519181cc611e18` (r:1 w:0) /// Storage: `BridgeRelayers::RelayerRewards` (r:2 w:2) /// Proof: `BridgeRelayers::RelayerRewards` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { // Proof Size summary in bytes: - // Measured: `337` + // Measured: `414` // Estimated: `6086` - // Minimum execution time: 36_450_000 picoseconds. - Weight::from_parts(37_288_000, 0) + // Minimum execution time: 33_790_000 picoseconds. + Weight::from_parts(34_708_000, 0) .saturating_add(Weight::from_parts(0, 6086)) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: `BridgeRococoMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::PalletOperatingMode` (r:1 w:0) + /// Proof: `BridgeWestendToRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:1 w:0) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgeRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHeads` (r:1 w:0) + /// Proof: `BridgeRococoParachain::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// Storage: `BridgeWestendToRococoMessages::InboundLanes` (r:1 w:1) + /// Proof: `BridgeWestendToRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::DeliveryFeeFactor` (r:1 w:0) @@ -227,15 +227,18 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) /// The range of component `i` is `[128, 2048]`. + /// The range of component `i` is `[128, 2048]`. + /// The range of component `i` is `[128, 2048]`. + /// The range of component `i` is `[128, 2048]`. fn receive_single_message_proof_with_dispatch(i: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `633` + // Measured: `777` // Estimated: `52645` - // Minimum execution time: 67_047_000 picoseconds. - Weight::from_parts(68_717_105, 0) + // Minimum execution time: 61_938_000 picoseconds. + Weight::from_parts(63_009_714, 0) .saturating_add(Weight::from_parts(0, 52645)) - // Standard Error: 138 - .saturating_add(Weight::from_parts(8_056, 0).saturating_mul(i.into())) + // Standard Error: 23 + .saturating_add(Weight::from_parts(6_677, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_parachains.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_parachains.rs index 9819bd40654..81cb0a66b7d 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_parachains.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_parachains.rs @@ -17,10 +17,10 @@ //! Autogenerated weights for `pallet_bridge_parachains` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-10-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-westend-dev")`, DB CACHE: 1024 +//! HOSTNAME: `runner-vmdtonbz-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: // target/production/polkadot-parachain @@ -33,9 +33,9 @@ // --heap-pages=4096 // --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json // --pallet=pallet_bridge_parachains -// --chain=bridge-hub-westend-dev +// --chain=bridge-hub-rococo-dev // --header=./cumulus/file_header.txt -// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/ +// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -48,63 +48,65 @@ use core::marker::PhantomData; /// Weight functions for `pallet_bridge_parachains`. pub struct WeightInfo(PhantomData); impl pallet_bridge_parachains::WeightInfo for WeightInfo { - /// Storage: `BridgeRococoParachains::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoParachains::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::PalletOperatingMode` (r:1 w:0) + /// Proof: `BridgeRococoParachain::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) /// Storage: `BridgeRococoGrandpa::ImportedHeaders` (r:1 w:0) /// Proof: `BridgeRococoGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ParasInfo` (r:1 w:1) - /// Proof: `BridgeRococoParachains::ParasInfo` (`max_values`: Some(1), `max_size`: Some(60), added: 555, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ImportedParaHashes` (r:1 w:1) - /// Proof: `BridgeRococoParachains::ImportedParaHashes` (`max_values`: Some(64), `max_size`: Some(64), added: 1054, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:0 w:1) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ParasInfo` (r:1 w:1) + /// Proof: `BridgeRococoParachain::ParasInfo` (`max_values`: Some(1), `max_size`: Some(60), added: 555, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHashes` (r:1 w:1) + /// Proof: `BridgeRococoParachain::ImportedParaHashes` (`max_values`: Some(64), `max_size`: Some(64), added: 1054, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHeads` (r:0 w:1) + /// Proof: `BridgeRococoParachain::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 2]`. + /// The range of component `p` is `[1, 2]`. /// The range of component `p` is `[1, 2]`. fn submit_parachain_heads_with_n_parachains(_p: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `291` + // Measured: `367` // Estimated: `2543` - // Minimum execution time: 29_994_000 picoseconds. - Weight::from_parts(31_005_636, 0) + // Minimum execution time: 31_241_000 picoseconds. + Weight::from_parts(32_488_584, 0) .saturating_add(Weight::from_parts(0, 2543)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: `BridgeRococoParachains::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoParachains::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::PalletOperatingMode` (r:1 w:0) + /// Proof: `BridgeRococoParachain::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) /// Storage: `BridgeRococoGrandpa::ImportedHeaders` (r:1 w:0) /// Proof: `BridgeRococoGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ParasInfo` (r:1 w:1) - /// Proof: `BridgeRococoParachains::ParasInfo` (`max_values`: Some(1), `max_size`: Some(60), added: 555, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ImportedParaHashes` (r:1 w:1) - /// Proof: `BridgeRococoParachains::ImportedParaHashes` (`max_values`: Some(64), `max_size`: Some(64), added: 1054, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:0 w:1) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ParasInfo` (r:1 w:1) + /// Proof: `BridgeRococoParachain::ParasInfo` (`max_values`: Some(1), `max_size`: Some(60), added: 555, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHashes` (r:1 w:1) + /// Proof: `BridgeRococoParachain::ImportedParaHashes` (`max_values`: Some(64), `max_size`: Some(64), added: 1054, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHeads` (r:0 w:1) + /// Proof: `BridgeRococoParachain::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) fn submit_parachain_heads_with_1kb_proof() -> Weight { // Proof Size summary in bytes: - // Measured: `291` + // Measured: `367` // Estimated: `2543` - // Minimum execution time: 31_425_000 picoseconds. - Weight::from_parts(32_163_000, 0) + // Minimum execution time: 32_962_000 picoseconds. + Weight::from_parts(33_658_000, 0) .saturating_add(Weight::from_parts(0, 2543)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: `BridgeRococoParachains::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoParachains::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::PalletOperatingMode` (r:1 w:0) + /// Proof: `BridgeRococoParachain::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(1), added: 496, mode: `MaxEncodedLen`) /// Storage: `BridgeRococoGrandpa::ImportedHeaders` (r:1 w:0) /// Proof: `BridgeRococoGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ParasInfo` (r:1 w:1) - /// Proof: `BridgeRococoParachains::ParasInfo` (`max_values`: Some(1), `max_size`: Some(60), added: 555, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ImportedParaHashes` (r:1 w:1) - /// Proof: `BridgeRococoParachains::ImportedParaHashes` (`max_values`: Some(64), `max_size`: Some(64), added: 1054, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:0 w:1) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ParasInfo` (r:1 w:1) + /// Proof: `BridgeRococoParachain::ParasInfo` (`max_values`: Some(1), `max_size`: Some(60), added: 555, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHashes` (r:1 w:1) + /// Proof: `BridgeRococoParachain::ImportedParaHashes` (`max_values`: Some(64), `max_size`: Some(64), added: 1054, mode: `MaxEncodedLen`) + /// Storage: `BridgeRococoParachain::ImportedParaHeads` (r:0 w:1) + /// Proof: `BridgeRococoParachain::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) fn submit_parachain_heads_with_16kb_proof() -> Weight { // Proof Size summary in bytes: - // Measured: `291` + // Measured: `367` // Estimated: `2543` - // Minimum execution time: 60_062_000 picoseconds. - Weight::from_parts(61_201_000, 0) + // Minimum execution time: 62_685_000 picoseconds. + Weight::from_parts(64_589_000, 0) .saturating_add(Weight::from_parts(0, 2543)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_relayers.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_relayers.rs index ed96f0cd87c..fde670ab927 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_relayers.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_relayers.rs @@ -17,10 +17,10 @@ //! Autogenerated weights for `pallet_bridge_relayers` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-10-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-westend-dev")`, DB CACHE: 1024 +//! HOSTNAME: `runner-vmdtonbz-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: // target/production/polkadot-parachain @@ -33,9 +33,9 @@ // --heap-pages=4096 // --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json // --pallet=pallet_bridge_relayers -// --chain=bridge-hub-westend-dev +// --chain=bridge-hub-rococo-dev // --header=./cumulus/file_header.txt -// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/ +// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -56,8 +56,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `207` // Estimated: `3593` - // Minimum execution time: 45_732_000 picoseconds. - Weight::from_parts(46_282_000, 0) + // Minimum execution time: 45_338_000 picoseconds. + Weight::from_parts(45_836_000, 0) .saturating_add(Weight::from_parts(0, 3593)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) @@ -72,8 +72,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `61` // Estimated: `4714` - // Minimum execution time: 22_934_000 picoseconds. - Weight::from_parts(23_531_000, 0) + // Minimum execution time: 23_561_000 picoseconds. + Weight::from_parts(24_012_000, 0) .saturating_add(Weight::from_parts(0, 4714)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(2)) @@ -86,8 +86,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `160` // Estimated: `4714` - // Minimum execution time: 25_187_000 picoseconds. - Weight::from_parts(25_679_000, 0) + // Minimum execution time: 25_133_000 picoseconds. + Weight::from_parts(25_728_000, 0) .saturating_add(Weight::from_parts(0, 4714)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) @@ -102,8 +102,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `263` // Estimated: `4714` - // Minimum execution time: 27_015_000 picoseconds. - Weight::from_parts(27_608_000, 0) + // Minimum execution time: 27_356_000 picoseconds. + Weight::from_parts(27_828_000, 0) .saturating_add(Weight::from_parts(0, 4714)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(3)) @@ -114,8 +114,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `6` // Estimated: `3538` - // Minimum execution time: 5_207_000 picoseconds. - Weight::from_parts(5_394_000, 0) + // Minimum execution time: 2_955_000 picoseconds. + Weight::from_parts(3_084_000, 0) .saturating_add(Weight::from_parts(0, 3538)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_xcm.rs index 83e4260e771..9f17d327024 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_xcm.rs @@ -17,25 +17,27 @@ //! Autogenerated weights for `pallet_xcm` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-05, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-r43aesjn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-westend-dev")`, DB CACHE: 1024 +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: -// target/production/polkadot-parachain +// ./target/production/polkadot-parachain // benchmark // pallet -// --steps=50 -// --repeat=20 -// --extrinsic=* +// --chain=bridge-hub-rococo-dev // --wasm-execution=compiled -// --heap-pages=4096 -// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json // --pallet=pallet_xcm -// --chain=bridge-hub-westend-dev -// --header=./cumulus/file_header.txt -// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/ +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -48,8 +50,6 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) @@ -62,39 +62,24 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn send() -> Weight { // Proof Size summary in bytes: - // Measured: `38` - // Estimated: `3503` - // Minimum execution time: 23_219_000 picoseconds. - Weight::from_parts(23_818_000, 0) - .saturating_add(Weight::from_parts(0, 3503)) - .saturating_add(T::DbWeight::get().reads(6)) + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 29_724_000 picoseconds. + Weight::from_parts(30_440_000, 0) + .saturating_add(Weight::from_parts(0, 3540)) + .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) - /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) - /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn teleport_assets() -> Weight { // Proof Size summary in bytes: - // Measured: `70` - // Estimated: `3593` - // Minimum execution time: 90_120_000 picoseconds. - Weight::from_parts(92_545_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(3)) + // Measured: `32` + // Estimated: `1489` + // Minimum execution time: 26_779_000 picoseconds. + Weight::from_parts(27_249_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + .saturating_add(T::DbWeight::get().reads(1)) } /// Storage: `Benchmark::Override` (r:0 w:0) /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -106,32 +91,6 @@ impl pallet_xcm::WeightInfo for WeightInfo { Weight::from_parts(18_446_744_073_709_551_000, 0) .saturating_add(Weight::from_parts(0, 0)) } - /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) - /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) - /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) - /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - fn transfer_assets() -> Weight { - // Proof Size summary in bytes: - // Measured: `70` - // Estimated: `3593` - // Minimum execution time: 91_339_000 picoseconds. - Weight::from_parts(93_204_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(3)) - } /// Storage: `Benchmark::Override` (r:0 w:0) /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) fn execute() -> Weight { @@ -148,8 +107,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_976_000 picoseconds. - Weight::from_parts(7_284_000, 0) + // Minimum execution time: 9_170_000 picoseconds. + Weight::from_parts(9_629_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -159,8 +118,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_044_000 picoseconds. - Weight::from_parts(2_223_000, 0) + // Minimum execution time: 2_769_000 picoseconds. + Weight::from_parts(2_933_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -168,8 +127,6 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) @@ -184,18 +141,16 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) fn force_subscribe_version_notify() -> Weight { // Proof Size summary in bytes: - // Measured: `38` - // Estimated: `3503` - // Minimum execution time: 27_778_000 picoseconds. - Weight::from_parts(28_318_000, 0) - .saturating_add(Weight::from_parts(0, 3503)) - .saturating_add(T::DbWeight::get().reads(8)) + // Measured: `75` + // Estimated: `3540` + // Minimum execution time: 34_547_000 picoseconds. + Weight::from_parts(35_653_000, 0) + .saturating_add(Weight::from_parts(0, 3540)) + .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) @@ -210,12 +165,12 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) fn force_unsubscribe_version_notify() -> Weight { // Proof Size summary in bytes: - // Measured: `255` - // Estimated: `3720` - // Minimum execution time: 30_446_000 picoseconds. - Weight::from_parts(31_925_000, 0) - .saturating_add(Weight::from_parts(0, 3720)) - .saturating_add(T::DbWeight::get().reads(7)) + // Measured: `292` + // Estimated: `3757` + // Minimum execution time: 36_274_000 picoseconds. + Weight::from_parts(37_281_000, 0) + .saturating_add(Weight::from_parts(0, 3757)) + .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: `PolkadotXcm::XcmExecutionSuspended` (r:0 w:1) @@ -224,8 +179,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_037_000 picoseconds. - Weight::from_parts(2_211_000, 0) + // Minimum execution time: 2_749_000 picoseconds. + Weight::from_parts(2_917_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -233,11 +188,11 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) fn migrate_supported_version() -> Weight { // Proof Size summary in bytes: - // Measured: `95` - // Estimated: `10985` - // Minimum execution time: 15_620_000 picoseconds. - Weight::from_parts(15_984_000, 0) - .saturating_add(Weight::from_parts(0, 10985)) + // Measured: `187` + // Estimated: `11077` + // Minimum execution time: 17_649_000 picoseconds. + Weight::from_parts(17_964_000, 0) + .saturating_add(Weight::from_parts(0, 11077)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -245,11 +200,11 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) fn migrate_version_notifiers() -> Weight { // Proof Size summary in bytes: - // Measured: `99` - // Estimated: `10989` - // Minimum execution time: 15_689_000 picoseconds. - Weight::from_parts(16_093_000, 0) - .saturating_add(Weight::from_parts(0, 10989)) + // Measured: `191` + // Estimated: `11081` + // Minimum execution time: 17_551_000 picoseconds. + Weight::from_parts(18_176_000, 0) + .saturating_add(Weight::from_parts(0, 11081)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -257,17 +212,15 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) fn already_notified_target() -> Weight { // Proof Size summary in bytes: - // Measured: `106` - // Estimated: `13471` - // Minimum execution time: 16_946_000 picoseconds. - Weight::from_parts(17_192_000, 0) - .saturating_add(Weight::from_parts(0, 13471)) + // Measured: `198` + // Estimated: `13563` + // Minimum execution time: 19_261_000 picoseconds. + Weight::from_parts(19_714_000, 0) + .saturating_add(Weight::from_parts(0, 13563)) .saturating_add(T::DbWeight::get().reads(5)) } /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:2 w:1) /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) @@ -280,41 +233,39 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn notify_current_targets() -> Weight { // Proof Size summary in bytes: - // Measured: `106` - // Estimated: `6046` - // Minimum execution time: 27_164_000 picoseconds. - Weight::from_parts(27_760_000, 0) - .saturating_add(Weight::from_parts(0, 6046)) - .saturating_add(T::DbWeight::get().reads(8)) + // Measured: `142` + // Estimated: `6082` + // Minimum execution time: 31_630_000 picoseconds. + Weight::from_parts(32_340_000, 0) + .saturating_add(Weight::from_parts(0, 6082)) + .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:3 w:0) /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) fn notify_target_migration_fail() -> Weight { // Proof Size summary in bytes: - // Measured: `136` - // Estimated: `8551` - // Minimum execution time: 8_689_000 picoseconds. - Weight::from_parts(8_874_000, 0) - .saturating_add(Weight::from_parts(0, 8551)) + // Measured: `172` + // Estimated: `8587` + // Minimum execution time: 9_218_000 picoseconds. + Weight::from_parts(9_558_000, 0) + .saturating_add(Weight::from_parts(0, 8587)) .saturating_add(T::DbWeight::get().reads(3)) } /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) fn migrate_version_notify_targets() -> Weight { // Proof Size summary in bytes: - // Measured: `106` - // Estimated: `10996` - // Minimum execution time: 15_944_000 picoseconds. - Weight::from_parts(16_381_000, 0) - .saturating_add(Weight::from_parts(0, 10996)) + // Measured: `198` + // Estimated: `11088` + // Minimum execution time: 18_133_000 picoseconds. + Weight::from_parts(18_663_000, 0) + .saturating_add(Weight::from_parts(0, 11088)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) @@ -327,12 +278,12 @@ impl pallet_xcm::WeightInfo for WeightInfo { /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn migrate_and_notify_old_targets() -> Weight { // Proof Size summary in bytes: - // Measured: `112` - // Estimated: `11002` - // Minimum execution time: 33_826_000 picoseconds. - Weight::from_parts(34_784_000, 0) - .saturating_add(Weight::from_parts(0, 11002)) - .saturating_add(T::DbWeight::get().reads(10)) + // Measured: `204` + // Estimated: `11094` + // Minimum execution time: 38_878_000 picoseconds. + Weight::from_parts(39_779_000, 0) + .saturating_add(Weight::from_parts(0, 11094)) + .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) @@ -343,8 +294,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `32` // Estimated: `1517` - // Minimum execution time: 4_257_000 picoseconds. - Weight::from_parts(4_383_000, 0) + // Minimum execution time: 4_142_000 picoseconds. + Weight::from_parts(4_308_000, 0) .saturating_add(Weight::from_parts(0, 1517)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(2)) @@ -355,10 +306,11 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `7669` // Estimated: `11134` - // Minimum execution time: 26_924_000 picoseconds. - Weight::from_parts(27_455_000, 0) + // Minimum execution time: 25_814_000 picoseconds. + Weight::from_parts(26_213_000, 0) .saturating_add(Weight::from_parts(0, 11134)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } } + diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 9281a880c7e..7c686190208 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -17,10 +17,10 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-10-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` -//! WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-westend-dev"), DB CACHE: 1024 +//! HOSTNAME: `runner-vmdtonbz-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-rococo-dev"), DB CACHE: 1024 // Executed Command: // target/production/polkadot-parachain @@ -33,10 +33,10 @@ // --heap-pages=4096 // --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json // --pallet=pallet_xcm_benchmarks::generic -// --chain=bridge-hub-westend-dev +// --chain=bridge-hub-rococo-dev // --header=./cumulus/file_header.txt // --template=./cumulus/templates/xcm-bench-template.hbs -// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/ +// --output=./cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/ #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(unused_parens)] @@ -48,6 +48,8 @@ use sp_std::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::generic`. pub struct WeightInfo(PhantomData); impl WeightInfo { + // Storage: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) + // Proof: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) // Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) @@ -66,79 +68,81 @@ impl WeightInfo { // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) pub fn report_holding() -> Weight { // Proof Size summary in bytes: - // Measured: `208` + // Measured: `242` // Estimated: `6196` - // Minimum execution time: 61_577_000 picoseconds. - Weight::from_parts(63_216_000, 6196) - .saturating_add(T::DbWeight::get().reads(9)) + // Minimum execution time: 62_732_000 picoseconds. + Weight::from_parts(64_581_000, 6196) + .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) } pub fn buy_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_019_000 picoseconds. - Weight::from_parts(2_146_000, 0) + // Minimum execution time: 1_987_000 picoseconds. + Weight::from_parts(2_107_000, 0) } // Storage: `PolkadotXcm::Queries` (r:1 w:0) // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) pub fn query_response() -> Weight { // Proof Size summary in bytes: - // Measured: `32` - // Estimated: `3497` - // Minimum execution time: 7_473_000 picoseconds. - Weight::from_parts(7_784_000, 3497) + // Measured: `103` + // Estimated: `3568` + // Minimum execution time: 8_098_000 picoseconds. + Weight::from_parts(8_564_000, 3568) .saturating_add(T::DbWeight::get().reads(1)) } pub fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_385_000 picoseconds. - Weight::from_parts(8_768_000, 0) + // Minimum execution time: 8_539_000 picoseconds. + Weight::from_parts(9_085_000, 0) } pub fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_181_000 picoseconds. - Weight::from_parts(2_304_000, 0) + // Minimum execution time: 2_205_000 picoseconds. + Weight::from_parts(2_369_000, 0) } pub fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_858_000 picoseconds. - Weight::from_parts(1_919_000, 0) + // Minimum execution time: 1_828_000 picoseconds. + Weight::from_parts(1_994_000, 0) } pub fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_855_000 picoseconds. - Weight::from_parts(1_979_000, 0) + // Minimum execution time: 1_869_000 picoseconds. + Weight::from_parts(1_946_000, 0) } pub fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_823_000 picoseconds. - Weight::from_parts(1_890_000, 0) + // Minimum execution time: 1_842_000 picoseconds. + Weight::from_parts(1_949_000, 0) } pub fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_407_000 picoseconds. - Weight::from_parts(2_507_000, 0) + // Minimum execution time: 2_460_000 picoseconds. + Weight::from_parts(2_593_000, 0) } pub fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_838_000 picoseconds. - Weight::from_parts(1_894_000, 0) + // Minimum execution time: 1_868_000 picoseconds. + Weight::from_parts(2_003_000, 0) } + // Storage: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) + // Proof: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) // Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) @@ -157,21 +161,21 @@ impl WeightInfo { // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) pub fn report_error() -> Weight { // Proof Size summary in bytes: - // Measured: `208` + // Measured: `242` // Estimated: `6196` - // Minimum execution time: 54_847_000 picoseconds. - Weight::from_parts(55_742_000, 6196) - .saturating_add(T::DbWeight::get().reads(9)) + // Minimum execution time: 56_813_000 picoseconds. + Weight::from_parts(57_728_000, 6196) + .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) } // Storage: `PolkadotXcm::AssetTraps` (r:1 w:1) // Proof: `PolkadotXcm::AssetTraps` (`max_values`: None, `max_size`: None, mode: `Measured`) pub fn claim_asset() -> Weight { // Proof Size summary in bytes: - // Measured: `90` - // Estimated: `3555` - // Minimum execution time: 10_614_000 picoseconds. - Weight::from_parts(11_344_000, 3555) + // Measured: `160` + // Estimated: `3625` + // Minimum execution time: 11_364_000 picoseconds. + Weight::from_parts(11_872_000, 3625) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -179,8 +183,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_826_000 picoseconds. - Weight::from_parts(1_899_000, 0) + // Minimum execution time: 1_821_000 picoseconds. + Weight::from_parts(1_936_000, 0) } // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -198,10 +202,10 @@ impl WeightInfo { // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) pub fn subscribe_version() -> Weight { // Proof Size summary in bytes: - // Measured: `38` - // Estimated: `3503` - // Minimum execution time: 22_312_000 picoseconds. - Weight::from_parts(22_607_000, 3503) + // Measured: `109` + // Estimated: `3574` + // Minimum execution time: 23_081_000 picoseconds. + Weight::from_parts(23_512_000, 3574) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -211,45 +215,47 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_728_000 picoseconds. - Weight::from_parts(3_914_000, 0) + // Minimum execution time: 3_747_000 picoseconds. + Weight::from_parts(4_068_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_054_000 picoseconds. - Weight::from_parts(3_140_000, 0) + // Minimum execution time: 3_045_000 picoseconds. + Weight::from_parts(3_208_000, 0) } pub fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_996_000 picoseconds. - Weight::from_parts(2_148_000, 0) + // Minimum execution time: 1_962_000 picoseconds. + Weight::from_parts(2_284_000, 0) } pub fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_008_000 picoseconds. - Weight::from_parts(2_077_000, 0) + // Minimum execution time: 1_951_000 picoseconds. + Weight::from_parts(2_026_000, 0) } pub fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` // Minimum execution time: 1_837_000 picoseconds. - Weight::from_parts(1_913_000, 0) + Weight::from_parts(2_084_000, 0) } pub fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_052_000 picoseconds. - Weight::from_parts(2_120_000, 0) + // Minimum execution time: 2_042_000 picoseconds. + Weight::from_parts(2_145_000, 0) } + // Storage: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) + // Proof: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) // Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) @@ -268,20 +274,22 @@ impl WeightInfo { // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) pub fn query_pallet() -> Weight { // Proof Size summary in bytes: - // Measured: `208` + // Measured: `242` // Estimated: `6196` - // Minimum execution time: 58_725_000 picoseconds. - Weight::from_parts(60_271_000, 6196) - .saturating_add(T::DbWeight::get().reads(9)) + // Minimum execution time: 61_350_000 picoseconds. + Weight::from_parts(62_440_000, 6196) + .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) } pub fn expect_pallet() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_570_000 picoseconds. - Weight::from_parts(4_707_000, 0) + // Minimum execution time: 4_993_000 picoseconds. + Weight::from_parts(5_309_000, 0) } + // Storage: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) + // Proof: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) // Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) @@ -300,70 +308,70 @@ impl WeightInfo { // Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) pub fn report_transact_status() -> Weight { // Proof Size summary in bytes: - // Measured: `208` + // Measured: `242` // Estimated: `6196` - // Minimum execution time: 54_903_000 picoseconds. - Weight::from_parts(55_711_000, 6196) - .saturating_add(T::DbWeight::get().reads(9)) + // Minimum execution time: 57_133_000 picoseconds. + Weight::from_parts(58_100_000, 6196) + .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) } pub fn clear_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_872_000 picoseconds. - Weight::from_parts(1_938_000, 0) + // Minimum execution time: 1_899_000 picoseconds. + Weight::from_parts(2_153_000, 0) } pub fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_836_000 picoseconds. - Weight::from_parts(1_903_000, 0) + // Minimum execution time: 1_880_000 picoseconds. + Weight::from_parts(1_960_000, 0) } pub fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_847_000 picoseconds. - Weight::from_parts(1_900_000, 0) + // Minimum execution time: 1_825_000 picoseconds. + Weight::from_parts(1_960_000, 0) } + // Storage: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) + // Proof: UNKNOWN KEY `0x48297505634037ef48c848c99c0b1f1b` (r:1 w:0) // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - // Storage: `PolkadotXcm::SupportedVersion` (r:2 w:0) - // Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - // Storage: `BridgeRococoMessages::PalletOperatingMode` (r:1 w:0) - // Proof: `BridgeRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - // Storage: `BridgeRococoMessages::OutboundLanes` (r:1 w:1) - // Proof: `BridgeRococoMessages::OutboundLanes` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) - // Storage: `BridgeRococoMessages::OutboundLanesCongestedSignals` (r:1 w:0) - // Proof: `BridgeRococoMessages::OutboundLanesCongestedSignals` (`max_values`: Some(1), `max_size`: Some(21), added: 516, mode: `MaxEncodedLen`) - // Storage: `BridgeRococoMessages::OutboundMessages` (r:0 w:1) - // Proof: `BridgeRococoMessages::OutboundMessages` (`max_values`: None, `max_size`: Some(2621472), added: 2623947, mode: `MaxEncodedLen`) + // Storage: `BridgeRococoToWococoMessages::PalletOperatingMode` (r:1 w:0) + // Proof: `BridgeRococoToWococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) + // Storage: `BridgeRococoToWococoMessages::OutboundLanes` (r:1 w:1) + // Proof: `BridgeRococoToWococoMessages::OutboundLanes` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) + // Storage: `BridgeRococoToWococoMessages::OutboundLanesCongestedSignals` (r:1 w:0) + // Proof: `BridgeRococoToWococoMessages::OutboundLanesCongestedSignals` (`max_values`: Some(1), `max_size`: Some(21), added: 516, mode: `MaxEncodedLen`) + // Storage: `BridgeRococoToWococoMessages::OutboundMessages` (r:0 w:1) + // Proof: `BridgeRococoToWococoMessages::OutboundMessages` (`max_values`: None, `max_size`: Some(2621472), added: 2623947, mode: `MaxEncodedLen`) /// The range of component `x` is `[1, 1000]`. pub fn export_message(x: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `225` - // Estimated: `6165` - // Minimum execution time: 41_750_000 picoseconds. - Weight::from_parts(43_496_915, 6165) - // Standard Error: 623 - .saturating_add(Weight::from_parts(457_907, 0).saturating_mul(x.into())) - .saturating_add(T::DbWeight::get().reads(6)) + // Measured: `139` + // Estimated: `3604` + // Minimum execution time: 28_419_000 picoseconds. + Weight::from_parts(29_387_791, 3604) + // Standard Error: 552 + .saturating_add(Weight::from_parts(316_277, 0).saturating_mul(x.into())) + .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)) } pub fn set_fees_mode() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_826_000 picoseconds. - Weight::from_parts(1_911_000, 0) + // Minimum execution time: 1_903_000 picoseconds. + Weight::from_parts(2_023_000, 0) } pub fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_967_000 picoseconds. - Weight::from_parts(2_096_000, 0) + // Minimum execution time: 1_963_000 picoseconds. + Weight::from_parts(2_143_000, 0) } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs index 26dc1f62950..c89ee91c5e4 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs @@ -28,23 +28,19 @@ use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; use parachains_common::{ impls::ToStakingPot, - xcm_config::{ - AllSiblingSystemParachains, ConcreteAssetFromSystem, ParentRelayOrSiblingParachains, - RelayOrOtherSystemParachains, - }, + xcm_config::{ConcreteAssetFromSystem, RelayOrOtherSystemParachains}, TREASURY_PALLET_ID, }; use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; use sp_runtime::traits::AccountIdConversion; +use westend_runtime_constants::system_parachain; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, - AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, - DenyThenTry, EnsureXcmOrigin, IsConcrete, ParentAsSuperuser, ParentIsPreset, - RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, + DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, IsConcrete, ParentAsSuperuser, + ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, XcmFeeToAccount, @@ -76,7 +72,6 @@ pub type LocationToAccountId = ( ); /// Means for transacting the native currency on this chain. -#[allow(deprecated)] pub type CurrencyTransactor = CurrencyAdapter< // Use this currency: Balances, @@ -119,6 +114,10 @@ match_types! { MultiLocation { parents: 1, interior: Here } | MultiLocation { parents: 1, interior: X1(Plurality { .. }) } }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; } /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly @@ -201,7 +200,7 @@ pub type Barrier = TrailingSetTopicAsId< Equals, )>, // Subscriptions for version tracking are OK. - AllowSubscriptionsFrom, + AllowSubscriptionsFrom, ), UniversalLocation, ConstU32<8>, @@ -210,13 +209,24 @@ pub type Barrier = TrailingSetTopicAsId< >, >; +match_types! { + pub type SystemParachains: impl Contains = { + MultiLocation { + parents: 1, + interior: X1(Parachain( + system_parachain::ASSET_HUB_ID | + system_parachain::BRIDGE_HUB_ID | + system_parachain::COLLECTIVES_ID + )), + } + }; +} + /// Locations that will not be charged fees in the executor, /// either execution or delivery. /// We only waive fees for system functions, which these locations represent. -pub type WaivedLocations = ( - RelayOrOtherSystemParachains, - Equals, -); +pub type WaivedLocations = + (RelayOrOtherSystemParachains, Equals); /// Cases where a remote origin is accepted as trusted Teleporter for a given asset: /// - NativeToken with the parent Relay Chain and sibling parachains. diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs index 4a7a7478a3f..97401826723 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs @@ -22,16 +22,17 @@ use bridge_hub_westend_runtime::{ bridge_common_config, bridge_to_rococo_config, xcm_config::{RelayNetwork, WestendLocation, XcmConfig}, AllPalletsWithoutSystem, BridgeRejectObsoleteHeadersAndMessages, Executive, ExistentialDeposit, - ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, SessionKeys, + ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, SessionKeys, TransactionPayment, TxExtension, UncheckedExtrinsic, }; use bridge_to_rococo_config::{ - BridgeGrandpaRococoInstance, BridgeHubRococoChainId, BridgeHubRococoLocation, - BridgeParachainRococoInstance, WithBridgeHubRococoMessageBridge, - WithBridgeHubRococoMessagesInstance, XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO, + BridgeGrandpaRococoInstance, BridgeHubRococoChainId, BridgeParachainRococoInstance, + WithBridgeHubRococoMessageBridge, WithBridgeHubRococoMessagesInstance, + XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO, }; use codec::{Decode, Encode}; -use frame_support::{dispatch::GetDispatchInfo, parameter_types, traits::ConstU8}; +use frame_support::{dispatch::GetDispatchInfo, parameter_types}; +use frame_system::pallet_prelude::HeaderFor; use parachains_common::{westend::fee::WeightToFee, AccountId, AuraId, Balance}; use sp_keyring::AccountKeyring::Alice; use sp_runtime::{ @@ -51,16 +52,13 @@ fn construct_extrinsic( sender: sp_keyring::AccountKeyring, call: RuntimeCall, ) -> UncheckedExtrinsic { - let account_id = AccountId32::from(sender.public()); let tx_ext: TxExtension = ( frame_system::CheckNonZeroSender::::new(), frame_system::CheckSpecVersion::::new(), frame_system::CheckTxVersion::::new(), frame_system::CheckGenesis::::new(), frame_system::CheckEra::::from(Era::immortal()), - frame_system::CheckNonce::::from( - frame_system::Pallet::::account(&account_id).nonce, - ), + frame_system::CheckNonce::::from(0), frame_system::CheckWeight::::new(), pallet_transaction_payment::ChargeTransactionPayment::::from(0), BridgeRejectObsoleteHeadersAndMessages::default(), @@ -71,7 +69,7 @@ fn construct_extrinsic( let signature = payload.using_encoded(|e| sender.sign(e)); UncheckedExtrinsic::new_signed( call, - account_id.into(), + AccountId32::from(sender.public()).into(), Signature::Sr25519(signature.clone()), tx_ext, ) @@ -79,9 +77,10 @@ fn construct_extrinsic( fn construct_and_apply_extrinsic( relayer_at_target: sp_keyring::AccountKeyring, - call: RuntimeCall, + batch: pallet_utility::Call, ) -> sp_runtime::DispatchOutcome { - let xt = construct_extrinsic(relayer_at_target, call); + let batch_call = RuntimeCall::Utility(batch); + let xt = construct_extrinsic(relayer_at_target, batch_call); let r = Executive::apply_extrinsic(xt); r.unwrap() } @@ -93,6 +92,10 @@ fn construct_and_estimate_extrinsic_fee(batch: pallet_utility::Call) -> TransactionPayment::compute_fee(xt.encoded_size() as _, &batch_info, 0) } +fn executive_init_block(header: &HeaderFor) { + Executive::initialize_block(header) +} + fn collator_session_keys() -> bridge_hub_test_utils::CollatorSessionKeys { bridge_hub_test_utils::CollatorSessionKeys::new( AccountId::from(Alice), @@ -177,12 +180,12 @@ fn handle_export_message_from_system_parachain_add_to_outbound_queue_works() { _ => None, } }), - || ExportMessage { network: Rococo, destination: X1(Parachain(bridge_to_rococo_config::AssetHubRococoParaId::get().into())), xcm: Xcm(vec![]) }, + || ExportMessage { network: Rococo, destination: X1(Parachain(4321)), xcm: Xcm(vec![]) }, XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO, Some((WestendLocation::get(), ExistentialDeposit::get()).into()), // value should be >= than value generated by `can_calculate_weight_for_paid_export_message_with_reserve_transfer` Some((WestendLocation::get(), bp_bridge_hub_westend::BridgeHubWestendBaseXcmFeeInWnds::get()).into()), - || PolkadotXcm::force_xcm_version(RuntimeOrigin::root(), Box::new(BridgeHubRococoLocation::get()), XCM_VERSION).expect("version saved!"), + || (), ) } @@ -196,7 +199,6 @@ fn message_dispatch_routing_works() { WithBridgeHubRococoMessagesInstance, RelayNetwork, bridge_to_rococo_config::RococoGlobalConsensusNetwork, - ConstU8<2>, >( collator_session_keys(), bp_bridge_hub_westend::BRIDGE_HUB_WESTEND_PARACHAIN_ID, @@ -220,9 +222,10 @@ fn message_dispatch_routing_works() { #[test] fn relayed_incoming_message_works() { - bridge_hub_test_utils::test_cases::from_parachain::relayed_incoming_message_works::< + bridge_hub_test_utils::test_cases::relayed_incoming_message_works::< Runtime, AllPalletsWithoutSystem, + XcmConfig, ParachainSystem, BridgeGrandpaRococoInstance, BridgeParachainRococoInstance, @@ -232,18 +235,16 @@ fn relayed_incoming_message_works() { collator_session_keys(), bp_bridge_hub_westend::BRIDGE_HUB_WESTEND_PARACHAIN_ID, bp_bridge_hub_rococo::BRIDGE_HUB_ROCOCO_PARACHAIN_ID, - BridgeHubRococoChainId::get(), SIBLING_PARACHAIN_ID, Westend, XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO, || (), - construct_and_apply_extrinsic, ) } #[test] pub fn complex_relay_extrinsic_works() { - bridge_hub_test_utils::test_cases::from_parachain::complex_relay_extrinsic_works::< + bridge_hub_test_utils::test_cases::complex_relay_extrinsic_works::< Runtime, AllPalletsWithoutSystem, XcmConfig, @@ -260,8 +261,10 @@ pub fn complex_relay_extrinsic_works() { BridgeHubRococoChainId::get(), Westend, XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO, - || (), + ExistentialDeposit::get(), + executive_init_block, construct_and_apply_extrinsic, + || (), ); } @@ -285,7 +288,7 @@ pub fn can_calculate_weight_for_paid_export_message_with_reserve_transfer() { #[test] pub fn can_calculate_fee_for_complex_message_delivery_transaction() { - let estimated = bridge_hub_test_utils::test_cases::from_parachain::can_calculate_fee_for_complex_message_delivery_transaction::< + let estimated = bridge_hub_test_utils::test_cases::can_calculate_fee_for_complex_message_delivery_transaction::< Runtime, BridgeGrandpaRococoInstance, BridgeParachainRococoInstance, @@ -308,7 +311,7 @@ pub fn can_calculate_fee_for_complex_message_delivery_transaction() { #[test] pub fn can_calculate_fee_for_complex_message_confirmation_transaction() { - let estimated = bridge_hub_test_utils::test_cases::from_parachain::can_calculate_fee_for_complex_message_confirmation_transaction::< + let estimated = bridge_hub_test_utils::test_cases::can_calculate_fee_for_complex_message_confirmation_transaction::< Runtime, BridgeGrandpaRococoInstance, BridgeParachainRococoInstance, diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/Cargo.toml b/cumulus/parachains/runtimes/bridge-hubs/test-utils/Cargo.toml index 3049182cd4e..bd171be53bf 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/Cargo.toml @@ -6,32 +6,27 @@ edition.workspace = true description = "Utils for BridgeHub testing" license = "Apache-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } -impl-trait-for-tuples = "0.2" log = { version = "0.4.20", 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 } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-io = { path = "../../../../../substrate/primitives/io", default-features = false } +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} +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-runtime = { path = "../../../../../substrate/primitives/runtime", 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-session = { path = "../../../../../substrate/frame/session", default-features = false } +pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false} +pallet-utility = { path = "../../../../../substrate/frame/utility", default-features = false} +pallet-session = { path = "../../../../../substrate/frame/session", default-features = false} # Cumulus asset-test-utils = { path = "../../assets/test-utils" } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } 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 } @@ -39,11 +34,11 @@ parachains-common = { path = "../../../common", default-features = false } parachains-runtimes-test-utils = { path = "../../test-utils", default-features = false } # Polkadot -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", 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 } -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 = { 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} # Bridges bp-header-chain = { path = "../../../../../bridges/primitives/header-chain", default-features = false } @@ -60,7 +55,7 @@ pallet-bridge-relayers = { path = "../../../../../bridges/modules/relayers", def bridge-runtime-common = { path = "../../../../../bridges/bin/runtime-common", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "asset-test-utils/std", "bp-header-chain/std", @@ -95,7 +90,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "xcm-builder/std", "xcm-executor/std", "xcm/std", diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/lib.rs index 445f001f1a4..26eb09b73fa 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/lib.rs @@ -17,7 +17,5 @@ //! Module contains predefined test-case scenarios for "BridgeHub" `Runtime`s. pub mod test_cases; -pub mod test_data; - pub use bp_test_utils::test_header; pub use parachains_runtimes_test_utils::*; diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases.rs new file mode 100644 index 00000000000..7a86d85c86f --- /dev/null +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases.rs @@ -0,0 +1,1564 @@ +// 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 . + +//! Module contains predefined test-case scenarios for `Runtime` with bridging capabilities. + +use bp_messages::{ + source_chain::TargetHeaderChain, + target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch, SourceHeaderChain}, + LaneId, MessageKey, OutboundLaneData, UnrewardedRelayersState, Weight, +}; +use bp_parachains::{BestParaHeadHash, ParaInfo}; +use bp_polkadot_core::parachains::{ParaHash, ParaId}; +use bp_relayers::{RewardsAccountOwner, RewardsAccountParams}; +use bp_runtime::{HeaderOf, Parachain, StorageProofSize, UnderlyingChainOf}; +use bp_test_utils::{make_default_justification, prepare_parachain_heads_proof}; +use bridge_runtime_common::{ + messages::{ + source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, + BridgedChain as MessageBridgedChain, MessageBridge, + }, + messages_generation::{ + encode_all_messages, encode_lane_data, prepare_message_delivery_storage_proof, + prepare_messages_storage_proof, + }, + messages_xcm_extension::{XcmAsPlainPayload, XcmBlobMessageDispatchResult}, +}; +use codec::Encode; +use frame_support::{ + assert_ok, + traits::{Get, OnFinalize, OnInitialize, OriginTrait, PalletInfoAccess}, +}; +use frame_system::pallet_prelude::{BlockNumberFor, HeaderFor}; +use pallet_bridge_grandpa::BridgedHeader; +use parachains_common::AccountId; +use parachains_runtimes_test_utils::{ + mock_open_hrmp_channel, AccountIdOf, BalanceOf, CollatorSessionKeys, ExtBuilder, ValidatorIdOf, + XcmReceivedFrom, +}; +use sp_core::H256; +use sp_keyring::AccountKeyring::*; +use sp_runtime::{ + traits::{Header as HeaderT, Zero}, + AccountId32, +}; +use xcm::latest::prelude::*; +use xcm_builder::DispatchBlobError; +use xcm_executor::{ + traits::{TransactAsset, WeightBounds}, + XcmExecutor, +}; + +// Re-export test_case from assets +pub use asset_test_utils::include_teleports_for_native_asset_works; + +type RuntimeHelper = + parachains_runtimes_test_utils::RuntimeHelper; + +// Re-export test_case from `parachains-runtimes-test-utils` +pub use parachains_runtimes_test_utils::test_cases::change_storage_constant_by_governance_works; + +/// Test-case makes sure that `Runtime` can process bridging initialize via governance-like call +pub fn initialize_bridge_by_governance_works( + collator_session_key: CollatorSessionKeys, + runtime_para_id: u32, + runtime_call_encode: Box< + dyn Fn(pallet_bridge_grandpa::Call) -> Vec, + >, +) where + Runtime: frame_system::Config + + pallet_balances::Config + + pallet_session::Config + + pallet_xcm::Config + + parachain_info::Config + + pallet_collator_selection::Config + + cumulus_pallet_parachain_system::Config + + pallet_bridge_grandpa::Config, + GrandpaPalletInstance: 'static, + ValidatorIdOf: From>, +{ + ExtBuilder::::default() + .with_collators(collator_session_key.collators()) + .with_session_keys(collator_session_key.session_keys()) + .with_para_id(runtime_para_id.into()) + .with_tracing() + .build() + .execute_with(|| { + // check mode before + assert_eq!( + pallet_bridge_grandpa::PalletOperatingMode::::try_get(), + Err(()) + ); + + // encode `initialize` call + let initialize_call = runtime_call_encode(pallet_bridge_grandpa::Call::< + Runtime, + GrandpaPalletInstance, + >::initialize { + init_data: test_data::initialization_data::(12345), + }); + + // overestimate - check weight for `pallet_bridge_grandpa::Pallet::initialize()` call + let require_weight_at_most = + ::DbWeight::get().reads_writes(7, 7); + + // execute XCM with Transacts to `initialize bridge` as governance does + assert_ok!(RuntimeHelper::::execute_as_governance( + initialize_call, + require_weight_at_most + ) + .ensure_complete()); + + // check mode after + assert_eq!( + pallet_bridge_grandpa::PalletOperatingMode::::try_get(), + Ok(bp_runtime::BasicOperatingMode::Normal) + ); + }) +} + +/// Test-case makes sure that `Runtime` can handle xcm `ExportMessage`: +/// Checks if received XCM messages is correctly added to the message outbound queue for delivery. +/// For SystemParachains we expect unpaid execution. +pub fn handle_export_message_from_system_parachain_to_outbound_queue_works< + Runtime, + XcmConfig, + MessagesPalletInstance, +>( + collator_session_key: CollatorSessionKeys, + runtime_para_id: u32, + sibling_parachain_id: u32, + unwrap_pallet_bridge_messages_event: Box< + dyn Fn(Vec) -> Option>, + >, + export_message_instruction: fn() -> Instruction, + expected_lane_id: LaneId, + existential_deposit: Option, + maybe_paid_export_message: Option, + prepare_configuration: impl Fn(), +) where + Runtime: frame_system::Config + + pallet_balances::Config + + pallet_session::Config + + pallet_xcm::Config + + parachain_info::Config + + pallet_collator_selection::Config + + cumulus_pallet_parachain_system::Config + + pallet_bridge_messages::Config, + XcmConfig: xcm_executor::Config, + MessagesPalletInstance: 'static, + ValidatorIdOf: From>, +{ + assert_ne!(runtime_para_id, sibling_parachain_id); + let sibling_parachain_location = MultiLocation::new(1, Parachain(sibling_parachain_id)); + + ExtBuilder::::default() + .with_collators(collator_session_key.collators()) + .with_session_keys(collator_session_key.session_keys()) + .with_para_id(runtime_para_id.into()) + .with_tracing() + .build() + .execute_with(|| { + prepare_configuration(); + + // check queue before + assert_eq!( + pallet_bridge_messages::OutboundLanes::::try_get( + expected_lane_id + ), + Err(()) + ); + + // prepare `ExportMessage` + let xcm = if let Some(fee) = maybe_paid_export_message { + // deposit ED to origin (if needed) + if let Some(ed) = existential_deposit { + XcmConfig::AssetTransactor::deposit_asset( + &ed, + &sibling_parachain_location, + Some(&XcmContext::with_message_id([0; 32])), + ) + .expect("deposited ed"); + } + // deposit fee to origin + XcmConfig::AssetTransactor::deposit_asset( + &fee, + &sibling_parachain_location, + Some(&XcmContext::with_message_id([0; 32])), + ) + .expect("deposited fee"); + + Xcm(vec![ + WithdrawAsset(MultiAssets::from(vec![fee.clone()])), + BuyExecution { fees: fee, weight_limit: Unlimited }, + export_message_instruction(), + ]) + } else { + Xcm(vec![ + UnpaidExecution { weight_limit: Unlimited, check_origin: None }, + export_message_instruction(), + ]) + }; + + // execute XCM + let hash = xcm.using_encoded(sp_io::hashing::blake2_256); + assert_ok!(XcmExecutor::::execute_xcm( + sibling_parachain_location, + xcm, + hash, + RuntimeHelper::::xcm_max_weight(XcmReceivedFrom::Sibling), + ) + .ensure_complete()); + + // check queue after + assert_eq!( + pallet_bridge_messages::OutboundLanes::::try_get( + expected_lane_id + ), + Ok(OutboundLaneData { + oldest_unpruned_nonce: 1, + latest_received_nonce: 0, + latest_generated_nonce: 1, + }) + ); + + // check events + let mut events = >::events() + .into_iter() + .filter_map(|e| unwrap_pallet_bridge_messages_event(e.event.encode())); + assert!( + events.any(|e| matches!(e, pallet_bridge_messages::Event::MessageAccepted { .. })) + ); + }) +} + +/// Test-case makes sure that Runtime can route XCM messages received in inbound queue, +/// We just test here `MessageDispatch` configuration. +/// We expect that runtime can route messages: +/// 1. to Parent (relay chain) +/// 2. to Sibling parachain +pub fn message_dispatch_routing_works< + Runtime, + AllPalletsWithoutSystem, + XcmConfig, + HrmpChannelOpener, + MessagesPalletInstance, + RuntimeNetwork, + BridgedNetwork, +>( + collator_session_key: CollatorSessionKeys, + runtime_para_id: u32, + sibling_parachain_id: u32, + unwrap_cumulus_pallet_parachain_system_event: Box< + dyn Fn(Vec) -> Option>, + >, + unwrap_cumulus_pallet_xcmp_queue_event: Box< + dyn Fn(Vec) -> Option>, + >, + expected_lane_id: LaneId, + prepare_configuration: impl Fn(), +) where + Runtime: frame_system::Config + + pallet_balances::Config + + pallet_session::Config + + pallet_xcm::Config + + parachain_info::Config + + pallet_collator_selection::Config + + cumulus_pallet_parachain_system::Config + + cumulus_pallet_xcmp_queue::Config + + pallet_bridge_messages::Config, + AllPalletsWithoutSystem: + OnInitialize> + OnFinalize>, + ::AccountId: + Into<<::RuntimeOrigin as OriginTrait>::AccountId>, + XcmConfig: xcm_executor::Config, + MessagesPalletInstance: 'static, + ValidatorIdOf: From>, + ::AccountId: From, + HrmpChannelOpener: frame_support::inherent::ProvideInherent< + Call = cumulus_pallet_parachain_system::Call, + >, + // MessageDispatcher: MessageDispatch, DispatchLevelResult = + // XcmBlobMessageDispatchResult, DispatchPayload = XcmAsPlainPayload>, + RuntimeNetwork: Get, + BridgedNetwork: Get, +{ + assert_ne!(runtime_para_id, sibling_parachain_id); + + ExtBuilder::::default() + .with_collators(collator_session_key.collators()) + .with_session_keys(collator_session_key.session_keys()) + .with_safe_xcm_version(XCM_VERSION) + .with_para_id(runtime_para_id.into()) + .with_tracing() + .build() + .execute_with(|| { + prepare_configuration(); + + let mut alice = [0u8; 32]; + alice[0] = 1; + + let included_head = RuntimeHelper::::run_to_block( + 2, + AccountId::from(alice).into(), + ); + // 1. this message is sent from other global consensus with destination of this Runtime relay chain (UMP) + let bridging_message = + test_data::simulate_message_exporter_on_bridged_chain::( + (RuntimeNetwork::get(), Here) + ); + let result = <>::MessageDispatch>::dispatch( + test_data::dispatch_message(expected_lane_id, 1, bridging_message) + ); + assert_eq!(format!("{:?}", result.dispatch_level_result), format!("{:?}", XcmBlobMessageDispatchResult::Dispatched)); + + // check events - UpwardMessageSent + let mut events = >::events() + .into_iter() + .filter_map(|e| unwrap_cumulus_pallet_parachain_system_event(e.event.encode())); + assert!( + events.any(|e| matches!(e, cumulus_pallet_parachain_system::Event::UpwardMessageSent { .. })) + ); + + // 2. this message is sent from other global consensus with destination of this Runtime sibling parachain (HRMP) + let bridging_message = + test_data::simulate_message_exporter_on_bridged_chain::( + (RuntimeNetwork::get(), X1(Parachain(sibling_parachain_id))), + ); + + // 2.1. WITHOUT opened hrmp channel -> RoutingError + let result = + <>::MessageDispatch>::dispatch( + DispatchMessage { + key: MessageKey { lane_id: expected_lane_id, nonce: 1 }, + data: DispatchMessageData { payload: Ok(bridging_message.clone()) }, + } + ); + assert_eq!(format!("{:?}", result.dispatch_level_result), format!("{:?}", XcmBlobMessageDispatchResult::NotDispatched(Some(DispatchBlobError::RoutingError)))); + + // check events - no XcmpMessageSent + assert_eq!(>::events() + .into_iter() + .filter_map(|e| unwrap_cumulus_pallet_xcmp_queue_event(e.event.encode())) + .count(), 0); + + // 2.1. WITH hrmp channel -> Ok + mock_open_hrmp_channel::(runtime_para_id.into(), sibling_parachain_id.into(), included_head, &alice); + let result = <>::MessageDispatch>::dispatch( + DispatchMessage { + key: MessageKey { lane_id: expected_lane_id, nonce: 1 }, + data: DispatchMessageData { payload: Ok(bridging_message) }, + } + ); + assert_eq!(format!("{:?}", result.dispatch_level_result), format!("{:?}", XcmBlobMessageDispatchResult::Dispatched)); + + // check events - XcmpMessageSent + let mut events = >::events() + .into_iter() + .filter_map(|e| unwrap_cumulus_pallet_xcmp_queue_event(e.event.encode())); + assert!( + events.any(|e| matches!(e, cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. })) + ); + }) +} + +/// Test-case makes sure that Runtime can dispatch XCM messages submitted by relayer, +/// with proofs (finality, para heads, message) independently submitted. +pub fn relayed_incoming_message_works( + collator_session_key: CollatorSessionKeys, + runtime_para_id: u32, + bridged_para_id: u32, + sibling_parachain_id: u32, + local_relay_chain_id: NetworkId, + lane_id: LaneId, + prepare_configuration: impl Fn(), +) where + Runtime: frame_system::Config + + pallet_balances::Config + + pallet_session::Config + + pallet_xcm::Config + + parachain_info::Config + + pallet_collator_selection::Config + + cumulus_pallet_parachain_system::Config + + cumulus_pallet_xcmp_queue::Config + + pallet_bridge_grandpa::Config + + pallet_bridge_parachains::Config + + pallet_bridge_messages::Config, + AllPalletsWithoutSystem: OnInitialize> + + OnFinalize>, + GPI: 'static, + PPI: 'static, + MPI: 'static, + MB: MessageBridge, + ::BridgedChain: Send + Sync + 'static, + ::ThisChain: Send + Sync + 'static, + UnderlyingChainOf>: bp_runtime::Chain + Parachain, + XcmConfig: xcm_executor::Config, + HrmpChannelOpener: frame_support::inherent::ProvideInherent< + Call = cumulus_pallet_parachain_system::Call, + >, + ValidatorIdOf: From>, + <>::SourceHeaderChain as SourceHeaderChain>::MessagesProof: From>, + <>::BridgedChain as bp_runtime::Chain>::Hash: From, + ParaHash: From<<>::BridgedChain as bp_runtime::Chain>::Hash>, + ::AccountId: + Into<<::RuntimeOrigin as OriginTrait>::AccountId>, + ::AccountId: From, + AccountIdOf: From, + >::InboundRelayer: From, +{ + assert_ne!(runtime_para_id, sibling_parachain_id); + + ExtBuilder::::default() + .with_collators(collator_session_key.collators()) + .with_session_keys(collator_session_key.session_keys()) + .with_safe_xcm_version(XCM_VERSION) + .with_para_id(runtime_para_id.into()) + .with_tracing() + .build() + .execute_with(|| { + prepare_configuration(); + + let mut alice = [0u8; 32]; + alice[0] = 1; + + let included_head = RuntimeHelper::::run_to_block( + 2, + AccountId::from(alice).into(), + ); + mock_open_hrmp_channel::( + runtime_para_id.into(), + sibling_parachain_id.into(), + included_head, + &alice, + ); + + // start with bridged chain block#0 + let init_data = test_data::initialization_data::(0); + pallet_bridge_grandpa::Pallet::::initialize( + RuntimeHelper::::root_origin(), + init_data, + ) + .unwrap(); + + // set up relayer details and proofs + + let message_destination = + X2(GlobalConsensus(local_relay_chain_id), Parachain(sibling_parachain_id)); + // some random numbers (checked by test) + let message_nonce = 1; + let para_header_number = 5; + let relay_header_number = 1; + + let relayer_at_target = Bob; + let relayer_id_on_target: AccountIdOf = relayer_at_target.public().into(); + let relayer_at_source = Dave; + let relayer_id_on_source: AccountId32 = relayer_at_source.public().into(); + + let xcm = vec![xcm::v3::Instruction::<()>::ClearOrigin; 42]; + let expected_dispatch = xcm::latest::Xcm::<()>({ + let mut expected_instructions = xcm.clone(); + // dispatch prepends bridge pallet instance + expected_instructions.insert( + 0, + DescendOrigin(X1(PalletInstance( + as PalletInfoAccess>::index() + as u8, + ))), + ); + expected_instructions + }); + // generate bridged relay chain finality, parachain heads and message proofs, + // to be submitted by relayer to this chain. + let ( + relay_chain_header, + grandpa_justification, + bridged_para_head, + parachain_heads, + para_heads_proof, + message_proof, + ) = test_data::make_complex_relayer_delivery_proofs::< + >::BridgedChain, + MB, + (), + >( + lane_id, + xcm.into(), + message_nonce, + message_destination, + para_header_number, + relay_header_number, + bridged_para_id, + ); + + // submit bridged relay chain finality proof + { + let result = pallet_bridge_grandpa::Pallet::::submit_finality_proof( + RuntimeHelper::::origin_of(relayer_id_on_target.clone()), + Box::new(relay_chain_header.clone()), + grandpa_justification, + ); + assert_ok!(result); + assert_eq!(result.unwrap().pays_fee, frame_support::dispatch::Pays::Yes); + } + + // verify finality proof correctly imported + assert_eq!( + pallet_bridge_grandpa::BestFinalized::::get().unwrap().1, + relay_chain_header.hash() + ); + assert!(pallet_bridge_grandpa::ImportedHeaders::::contains_key( + relay_chain_header.hash() + )); + + // submit parachain heads proof + { + let result = + pallet_bridge_parachains::Pallet::::submit_parachain_heads( + RuntimeHelper::::origin_of(relayer_id_on_target.clone()), + (relay_header_number, relay_chain_header.hash().into()), + parachain_heads, + para_heads_proof, + ); + assert_ok!(result); + assert_eq!(result.unwrap().pays_fee, frame_support::dispatch::Pays::Yes); + } + // verify parachain head proof correctly imported + assert_eq!( + pallet_bridge_parachains::ParasInfo::::get(ParaId(bridged_para_id)), + Some(ParaInfo { + best_head_hash: BestParaHeadHash { + at_relay_block_number: relay_header_number, + head_hash: bridged_para_head.hash() + }, + next_imported_hash_position: 1, + }) + ); + + // import message + assert!(RuntimeHelper::>::take_xcm( + sibling_parachain_id.into() + ) + .is_none()); + assert_eq!( + pallet_bridge_messages::InboundLanes::::get(lane_id) + .last_delivered_nonce(), + 0, + ); + // submit message proof + { + let result = pallet_bridge_messages::Pallet::::receive_messages_proof( + RuntimeHelper::::origin_of(relayer_id_on_target), + relayer_id_on_source.into(), + message_proof.into(), + 1, + Weight::MAX / 1000, + ); + assert_ok!(result); + assert_eq!(result.unwrap().pays_fee, frame_support::dispatch::Pays::Yes); + } + // verify message correctly imported and dispatched + assert_eq!( + pallet_bridge_messages::InboundLanes::::get(lane_id) + .last_delivered_nonce(), + 1, + ); + + // verify relayed bridged XCM message is dispatched to destination sibling para + let dispatched = RuntimeHelper::>::take_xcm( + sibling_parachain_id.into(), + ) + .unwrap(); + // verify contains original message + let dispatched = xcm::latest::Xcm::<()>::try_from(dispatched).unwrap(); + let mut dispatched_clone = dispatched.clone(); + for (idx, expected_instr) in expected_dispatch.0.iter().enumerate() { + assert_eq!(expected_instr, &dispatched.0[idx]); + assert_eq!(expected_instr, &dispatched_clone.0.remove(0)); + } + match dispatched_clone.0.len() { + 0 => (), + 1 => assert!(matches!(dispatched_clone.0[0], SetTopic(_))), + count => assert!(false, "Unexpected messages count: {:?}", count), + } + }) +} + +/// Test-case makes sure that Runtime can dispatch XCM messages submitted by relayer, +/// with proofs (finality, para heads, message) batched together in signed extrinsic. +/// Also verifies relayer transaction signed extensions work as intended. +pub fn complex_relay_extrinsic_works( + collator_session_key: CollatorSessionKeys, + runtime_para_id: u32, + bridged_para_id: u32, + sibling_parachain_id: u32, + bridged_chain_id: bp_runtime::ChainId, + local_relay_chain_id: NetworkId, + lane_id: LaneId, + existential_deposit: BalanceOf, + executive_init_block: fn(&HeaderFor), + construct_and_apply_extrinsic: fn( + sp_keyring::AccountKeyring, + pallet_utility::Call:: + ) -> sp_runtime::DispatchOutcome, + prepare_configuration: impl Fn(), +) where + Runtime: frame_system::Config + + pallet_balances::Config + + pallet_utility::Config + + pallet_session::Config + + pallet_xcm::Config + + parachain_info::Config + + pallet_collator_selection::Config + + cumulus_pallet_parachain_system::Config + + cumulus_pallet_xcmp_queue::Config + + pallet_bridge_grandpa::Config + + pallet_bridge_parachains::Config + + pallet_bridge_messages::Config + + pallet_bridge_relayers::Config, + AllPalletsWithoutSystem: OnInitialize> + + OnFinalize>, + GPI: 'static, + PPI: 'static, + MPI: 'static, + MB: MessageBridge, + ::BridgedChain: Send + Sync + 'static, + ::ThisChain: Send + Sync + 'static, + UnderlyingChainOf>: bp_runtime::Chain + Parachain, + XcmConfig: xcm_executor::Config, + HrmpChannelOpener: frame_support::inherent::ProvideInherent< + Call = cumulus_pallet_parachain_system::Call, + >, + ValidatorIdOf: From>, + <>::SourceHeaderChain as SourceHeaderChain>::MessagesProof: From>, + <>::BridgedChain as bp_runtime::Chain>::Hash: From, + ParaHash: From<<>::BridgedChain as bp_runtime::Chain>::Hash>, + ::AccountId: + Into<<::RuntimeOrigin as OriginTrait>::AccountId>, + AccountIdOf: From, + ::AccountId: From, + >::InboundRelayer: From, + ::RuntimeCall: + From> + + From> + + From> +{ + assert_ne!(runtime_para_id, sibling_parachain_id); + + // Relayer account at local/this BH. + let relayer_at_target = Bob; + let relayer_id_on_target: AccountIdOf = relayer_at_target.public().into(); + let relayer_initial_balance = existential_deposit * 100000u32.into(); + // Relayer account at remote/bridged BH. + let relayer_at_source = Dave; + let relayer_id_on_source: AccountId32 = relayer_at_source.public().into(); + + ExtBuilder::::default() + .with_collators(collator_session_key.collators()) + .with_session_keys(collator_session_key.session_keys()) + .with_safe_xcm_version(XCM_VERSION) + .with_para_id(runtime_para_id.into()) + .with_balances(vec![(relayer_id_on_target.clone(), relayer_initial_balance)]) + .with_tracing() + .build() + .execute_with(|| { + prepare_configuration(); + + let mut alice = [0u8; 32]; + alice[0] = 1; + + let included_head = RuntimeHelper::::run_to_block( + 2, + AccountId::from(alice).into(), + ); + let zero: BlockNumberFor = 0u32.into(); + let genesis_hash = frame_system::Pallet::::block_hash(zero); + let mut header: HeaderFor = bp_test_utils::test_header(1u32.into()); + header.set_parent_hash(genesis_hash); + executive_init_block(&header); + + mock_open_hrmp_channel::( + runtime_para_id.into(), + sibling_parachain_id.into(), + included_head, + &alice, + ); + + // start with bridged chain block#0 + let init_data = test_data::initialization_data::(0); + pallet_bridge_grandpa::Pallet::::initialize( + RuntimeHelper::::root_origin(), + init_data, + ) + .unwrap(); + + // set up relayer details and proofs + + let message_destination = + X2(GlobalConsensus(local_relay_chain_id), Parachain(sibling_parachain_id)); + // some random numbers (checked by test) + let message_nonce = 1; + let para_header_number = 5; + let relay_header_number = 1; + + let xcm = vec![xcm::latest::Instruction::<()>::ClearOrigin; 42]; + let expected_dispatch = xcm::latest::Xcm::<()>({ + let mut expected_instructions = xcm.clone(); + // dispatch prepends bridge pallet instance + expected_instructions.insert( + 0, + DescendOrigin(X1(PalletInstance( + as PalletInfoAccess>::index() + as u8, + ))), + ); + expected_instructions + }); + // generate bridged relay chain finality, parachain heads and message proofs, + // to be submitted by relayer to this chain. + let ( + relay_chain_header, + grandpa_justification, + bridged_para_head, + parachain_heads, + para_heads_proof, + message_proof, + ) = test_data::make_complex_relayer_delivery_proofs::< + >::BridgedChain, + MB, + (), + >( + lane_id, + xcm.clone().into(), + message_nonce, + message_destination, + para_header_number, + relay_header_number, + bridged_para_id, + ); + + let relay_chain_header_hash = relay_chain_header.hash(); + let batch = test_data::make_complex_relayer_delivery_batch::( + relay_chain_header, + grandpa_justification, + parachain_heads, + para_heads_proof, + message_proof, + relayer_id_on_source, + ); + + // sanity checks - before relayer extrinsic + assert!(RuntimeHelper::>::take_xcm( + sibling_parachain_id.into() + ) + .is_none()); + assert_eq!( + pallet_bridge_messages::InboundLanes::::get(lane_id) + .last_delivered_nonce(), + 0, + ); + let msg_proofs_rewards_account = RewardsAccountParams::new( + lane_id, + bridged_chain_id, + RewardsAccountOwner::ThisChain, + ); + assert_eq!( + pallet_bridge_relayers::RelayerRewards::::get( + relayer_id_on_target.clone(), + msg_proofs_rewards_account + ), + None, + ); + + // construct and apply extrinsic containing batch calls: + // bridged relay chain finality proof + // + parachain heads proof + // + submit message proof + let dispatch_outcome = construct_and_apply_extrinsic(relayer_at_target, batch); + + // verify finality proof correctly imported + assert_ok!(dispatch_outcome); + assert_eq!( + >::get().unwrap().1, + relay_chain_header_hash + ); + assert!(>::contains_key( + relay_chain_header_hash + )); + // verify parachain head proof correctly imported + assert_eq!( + pallet_bridge_parachains::ParasInfo::::get(ParaId(bridged_para_id)), + Some(ParaInfo { + best_head_hash: BestParaHeadHash { + at_relay_block_number: relay_header_number, + head_hash: bridged_para_head.hash() + }, + next_imported_hash_position: 1, + }) + ); + // verify message correctly imported and dispatched + assert_eq!( + pallet_bridge_messages::InboundLanes::::get(lane_id) + .last_delivered_nonce(), + 1, + ); + // verify relayer is refunded + assert!(pallet_bridge_relayers::RelayerRewards::::get( + relayer_id_on_target, + msg_proofs_rewards_account + ) + .is_some()); + + // verify relayed bridged XCM message is dispatched to destination sibling para + let dispatched = RuntimeHelper::>::take_xcm( + sibling_parachain_id.into(), + ) + .unwrap(); + // verify contains original message + let dispatched = xcm::latest::Xcm::<()>::try_from(dispatched).unwrap(); + let mut dispatched_clone = dispatched.clone(); + for (idx, expected_instr) in expected_dispatch.0.iter().enumerate() { + assert_eq!(expected_instr, &dispatched.0[idx]); + assert_eq!(expected_instr, &dispatched_clone.0.remove(0)); + } + match dispatched_clone.0.len() { + 0 => (), + 1 => assert!(matches!(dispatched_clone.0[0], SetTopic(_))), + count => assert!(false, "Unexpected messages count: {:?}", count), + } + }) +} + +/// Estimates XCM execution fee for paid `ExportMessage` processing. +pub fn can_calculate_weight_for_paid_export_message_with_reserve_transfer< + Runtime, + XcmConfig, + WeightToFee, +>() -> u128 +where + Runtime: frame_system::Config + pallet_balances::Config, + XcmConfig: xcm_executor::Config, + WeightToFee: frame_support::weights::WeightToFee>, + ::Balance: From + Into, +{ + // data here are not relevant for weighing + let mut xcm = Xcm(vec![ + WithdrawAsset(MultiAssets::from(vec![MultiAsset { + id: Concrete(MultiLocation { parents: 1, interior: Here }), + fun: Fungible(34333299), + }])), + BuyExecution { + fees: MultiAsset { + id: Concrete(MultiLocation { parents: 1, interior: Here }), + fun: Fungible(34333299), + }, + weight_limit: Unlimited, + }, + ExportMessage { + network: Polkadot, + destination: X1(Parachain(1000)), + xcm: Xcm(vec![ + ReserveAssetDeposited(MultiAssets::from(vec![MultiAsset { + id: Concrete(MultiLocation { + parents: 2, + interior: X1(GlobalConsensus(Kusama)), + }), + fun: Fungible(1000000000000), + }])), + ClearOrigin, + BuyExecution { + fees: MultiAsset { + id: Concrete(MultiLocation { + parents: 2, + interior: X1(GlobalConsensus(Kusama)), + }), + fun: Fungible(1000000000000), + }, + weight_limit: Unlimited, + }, + DepositAsset { + assets: Wild(AllCounted(1)), + beneficiary: MultiLocation { + parents: 0, + interior: X1(xcm::latest::prelude::AccountId32 { + network: None, + id: [ + 212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, + 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, + 109, 162, 125, + ], + }), + }, + }, + SetTopic([ + 116, 82, 194, 132, 171, 114, 217, 165, 23, 37, 161, 177, 165, 179, 247, 114, + 137, 101, 147, 70, 28, 157, 168, 32, 154, 63, 74, 228, 152, 180, 5, 63, + ]), + ]), + }, + DepositAsset { + assets: Wild(All), + beneficiary: MultiLocation { parents: 1, interior: X1(Parachain(1000)) }, + }, + SetTopic([ + 36, 224, 250, 165, 82, 195, 67, 110, 160, 170, 140, 87, 217, 62, 201, 164, 42, 98, 219, + 157, 124, 105, 248, 25, 131, 218, 199, 36, 109, 173, 100, 122, + ]), + ]); + + // get weight + let weight = XcmConfig::Weigher::weight(&mut xcm); + assert_ok!(weight); + let weight = weight.unwrap(); + // check if sane + let max_expected = Runtime::BlockWeights::get().max_block / 10; + assert!( + weight.all_lte(max_expected), + "calculated weight: {:?}, max_expected: {:?}", + weight, + max_expected + ); + + // check fee, should not be 0 + let estimated_fee = WeightToFee::weight_to_fee(&weight); + assert!(estimated_fee > BalanceOf::::zero()); + + sp_tracing::try_init_simple(); + log::error!( + target: "bridges::estimate", + "Estimate fee: {:?} for `ExportMessage` for runtime: {:?}", + estimated_fee, + Runtime::Version::get(), + ); + + estimated_fee.into() +} + +/// Estimates transaction fee for default message delivery transaction (batched with required +/// proofs) from bridged parachain. +pub fn can_calculate_fee_for_complex_message_delivery_transaction( + collator_session_key: CollatorSessionKeys, + compute_extrinsic_fee: fn(pallet_utility::Call::) -> u128, +) -> u128 +where + Runtime: frame_system::Config + + pallet_balances::Config + + pallet_session::Config + + pallet_xcm::Config + + parachain_info::Config + + pallet_collator_selection::Config + + cumulus_pallet_parachain_system::Config + + pallet_bridge_grandpa::Config + + pallet_bridge_parachains::Config + + pallet_bridge_messages::Config + + pallet_utility::Config, + GPI: 'static, + PPI: 'static, + MPI: 'static, + MB: MessageBridge, + ::BridgedChain: Send + Sync + 'static, + ::ThisChain: Send + Sync + 'static, + UnderlyingChainOf>: bp_runtime::Chain + Parachain, + ValidatorIdOf: From>, + <>::SourceHeaderChain as SourceHeaderChain>::MessagesProof: + From>, + <>::BridgedChain as bp_runtime::Chain>::Hash: From, + ParaHash: From<<>::BridgedChain as bp_runtime::Chain>::Hash>, + ::AccountId: + Into<<::RuntimeOrigin as OriginTrait>::AccountId>, + ::AccountId: From, + AccountIdOf: From, + >::InboundRelayer: From, + ::RuntimeCall: + From> + + From> + + From>, +{ + ExtBuilder::::default() + .with_collators(collator_session_key.collators()) + .with_session_keys(collator_session_key.session_keys()) + .with_safe_xcm_version(XCM_VERSION) + .with_para_id(1000.into()) + .with_tracing() + .build() + .execute_with(|| { + // generate bridged relay chain finality, parachain heads and message proofs, + // to be submitted by relayer to this chain. + // + // we don't care about parameter values here, apart from the XCM message size. But we + // do not need to have a large message here, because we're charging for every byte of + // the message additionally + let ( + relay_chain_header, + grandpa_justification, + _, + parachain_heads, + para_heads_proof, + message_proof, + ) = test_data::make_complex_relayer_delivery_proofs::< + >::BridgedChain, + MB, + (), + >( + LaneId::default(), + vec![xcm::v3::Instruction::<()>::ClearOrigin; 1_024].into(), + 1, + X2(GlobalConsensus(Polkadot), Parachain(1_000)), + 1, + 5, + 1_000, + ); + + // generate batch call that provides finality for bridged relay and parachains + message + // proof + let batch = test_data::make_complex_relayer_delivery_batch::( + relay_chain_header, + grandpa_justification, + parachain_heads, + para_heads_proof, + message_proof, + Dave.public().into(), + ); + let estimated_fee = compute_extrinsic_fee(batch); + + log::error!( + target: "bridges::estimate", + "Estimate fee: {:?} for single message delivery for runtime: {:?}", + estimated_fee, + Runtime::Version::get(), + ); + + estimated_fee + }) +} + +/// Estimates transaction fee for default message confirmation transaction (batched with required +/// proofs) from bridged parachain. +pub fn can_calculate_fee_for_complex_message_confirmation_transaction( + collator_session_key: CollatorSessionKeys, + compute_extrinsic_fee: fn(pallet_utility::Call::) -> u128, +) -> u128 +where + Runtime: frame_system::Config + + pallet_balances::Config + + pallet_session::Config + + pallet_xcm::Config + + parachain_info::Config + + pallet_collator_selection::Config + + cumulus_pallet_parachain_system::Config + + pallet_bridge_grandpa::Config + + pallet_bridge_parachains::Config + + pallet_bridge_messages::Config + + pallet_utility::Config, + GPI: 'static, + PPI: 'static, + MPI: 'static, + MB: MessageBridge, + ::BridgedChain: Send + Sync + 'static, + ::ThisChain: Send + Sync + 'static, + <::ThisChain as bp_runtime::Chain>::AccountId: From, + UnderlyingChainOf>: bp_runtime::Chain + Parachain, + ValidatorIdOf: From>, + <>::SourceHeaderChain as SourceHeaderChain>::MessagesProof: + From>, + <>::BridgedChain as bp_runtime::Chain>::Hash: From, + ParaHash: From<<>::BridgedChain as bp_runtime::Chain>::Hash>, + ::AccountId: + Into<<::RuntimeOrigin as OriginTrait>::AccountId>, + ::AccountId: From, + AccountIdOf: From, + >::InboundRelayer: From, + <>::TargetHeaderChain as TargetHeaderChain< + XcmAsPlainPayload, + Runtime::AccountId, + >>::MessagesDeliveryProof: From>, + ::RuntimeCall: + From> + + From> + + From>, +{ + ExtBuilder::::default() + .with_collators(collator_session_key.collators()) + .with_session_keys(collator_session_key.session_keys()) + .with_safe_xcm_version(XCM_VERSION) + .with_para_id(1000.into()) + .with_tracing() + .build() + .execute_with(|| { + // generate bridged relay chain finality, parachain heads and message proofs, + // to be submitted by relayer to this chain. + let unrewarded_relayers = UnrewardedRelayersState { + unrewarded_relayer_entries: 1, + total_messages: 1, + ..Default::default() + }; + let ( + relay_chain_header, + grandpa_justification, + _, + parachain_heads, + para_heads_proof, + message_delivery_proof, + ) = test_data::make_complex_relayer_confirmation_proofs::< + >::BridgedChain, + MB, + (), + >(LaneId::default(), 1, 5, 1_000, Alice.public().into(), unrewarded_relayers.clone()); + + // generate batch call that provides finality for bridged relay and parachains + message + // proof + let batch = test_data::make_complex_relayer_confirmation_batch::( + relay_chain_header, + grandpa_justification, + parachain_heads, + para_heads_proof, + message_delivery_proof, + unrewarded_relayers, + ); + let estimated_fee = compute_extrinsic_fee(batch); + + log::error!( + target: "bridges::estimate", + "Estimate fee: {:?} for single message confirmation for runtime: {:?}", + estimated_fee, + Runtime::Version::get(), + ); + + estimated_fee + }) +} + +pub mod test_data { + use super::*; + use bp_header_chain::{justification::GrandpaJustification, ChainWithGrandpa}; + use bp_messages::{DeliveredMessages, InboundLaneData, MessageNonce, UnrewardedRelayer}; + use bp_polkadot_core::parachains::{ParaHash, ParaHead, ParaHeadsProof, ParaId}; + use bp_runtime::{BasicOperatingMode, HashOf}; + use bp_test_utils::authority_list; + use sp_runtime::{DigestItem, SaturatedConversion}; + use xcm_builder::{HaulBlob, HaulBlobError, HaulBlobExporter}; + use xcm_executor::traits::{validate_export, ExportXcm}; + + pub fn prepare_inbound_xcm( + xcm_message: Xcm, + destination: InteriorMultiLocation, + ) -> Vec { + let location = xcm::VersionedInteriorMultiLocation::V3(destination); + let xcm = xcm::VersionedXcm::::V3(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 + // to the storage) + (location, xcm).encode().encode() + } + + /// Prepare a batch call with relay finality proof, parachain head proof and message proof. + pub fn make_complex_relayer_delivery_batch( + relay_chain_header: BridgedHeader, + grandpa_justification: GrandpaJustification>, + parachain_heads: Vec<(ParaId, ParaHash)>, + para_heads_proof: ParaHeadsProof, + message_proof: FromBridgedChainMessagesProof, + relayer_id_at_bridged_chain: AccountId32, + ) -> pallet_utility::Call where + Runtime:pallet_bridge_grandpa::Config + + pallet_bridge_parachains::Config + + pallet_bridge_messages::Config + + pallet_utility::Config, + GPI: 'static, + PPI: 'static, + MPI: 'static, + ParaHash: From<<>::BridgedChain as bp_runtime::Chain>::Hash>, + <>::BridgedChain as bp_runtime::Chain>::Hash: From, + <>::SourceHeaderChain as SourceHeaderChain>::MessagesProof: + From>, + >::InboundRelayer: From, + ::RuntimeCall: + From> + + From> + + From>, + { + let relay_chain_header_hash = relay_chain_header.hash(); + let relay_chain_header_number = *relay_chain_header.number(); + let submit_grandpa = pallet_bridge_grandpa::Call::::submit_finality_proof { + finality_target: Box::new(relay_chain_header), + justification: grandpa_justification, + }; + let submit_para_head = + pallet_bridge_parachains::Call::::submit_parachain_heads { + at_relay_block: ( + relay_chain_header_number.saturated_into(), + relay_chain_header_hash.into(), + ), + parachains: parachain_heads, + parachain_heads_proof: para_heads_proof, + }; + let submit_message = pallet_bridge_messages::Call::::receive_messages_proof { + relayer_id_at_bridged_chain: relayer_id_at_bridged_chain.into(), + proof: message_proof.into(), + messages_count: 1, + dispatch_weight: Weight::from_parts(1000000000, 0), + }; + pallet_utility::Call::::batch_all { + calls: vec![submit_grandpa.into(), submit_para_head.into(), submit_message.into()], + } + } + + /// Prepare a batch call with relay finality proof, parachain head proof and message delivery + /// proof. + pub fn make_complex_relayer_confirmation_batch( + relay_chain_header: BridgedHeader, + grandpa_justification: GrandpaJustification>, + parachain_heads: Vec<(ParaId, ParaHash)>, + para_heads_proof: ParaHeadsProof, + message_delivery_proof: FromBridgedChainMessagesDeliveryProof, + relayers_state: UnrewardedRelayersState, + ) -> pallet_utility::Call where + Runtime:pallet_bridge_grandpa::Config + + pallet_bridge_parachains::Config + + pallet_bridge_messages::Config + + pallet_utility::Config, + GPI: 'static, + PPI: 'static, + MPI: 'static, + ParaHash: From<<>::BridgedChain as bp_runtime::Chain>::Hash>, + <>::BridgedChain as bp_runtime::Chain>::Hash: From, + <>::TargetHeaderChain as TargetHeaderChain< + XcmAsPlainPayload, + Runtime::AccountId, + >>::MessagesDeliveryProof: From>, + ::RuntimeCall: + From> + + From> + + From>, + { + let relay_chain_header_hash = relay_chain_header.hash(); + let relay_chain_header_number = *relay_chain_header.number(); + let submit_grandpa = pallet_bridge_grandpa::Call::::submit_finality_proof { + finality_target: Box::new(relay_chain_header), + justification: grandpa_justification, + }; + let submit_para_head = + pallet_bridge_parachains::Call::::submit_parachain_heads { + at_relay_block: ( + relay_chain_header_number.saturated_into(), + relay_chain_header_hash.into(), + ), + parachains: parachain_heads, + parachain_heads_proof: para_heads_proof, + }; + let submit_message_delivery_proof = + pallet_bridge_messages::Call::::receive_messages_delivery_proof { + proof: message_delivery_proof.into(), + relayers_state, + }; + pallet_utility::Call::::batch_all { + calls: vec![ + submit_grandpa.into(), + submit_para_head.into(), + submit_message_delivery_proof.into(), + ], + } + } + + /// Prepare storage proofs of messages, stored at the source chain. + pub fn make_complex_relayer_delivery_proofs( + lane_id: LaneId, + xcm_message: Xcm, + message_nonce: MessageNonce, + message_destination: Junctions, + para_header_number: u32, + relay_header_number: u32, + bridged_para_id: u32, + ) -> ( + HeaderOf, + GrandpaJustification>, + ParaHead, + Vec<(ParaId, ParaHash)>, + ParaHeadsProof, + FromBridgedChainMessagesProof, + ) + where + BridgedRelayChain: ChainWithGrandpa, + HashOf: From, + MB: MessageBridge, + ::BridgedChain: Send + Sync + 'static, + ::ThisChain: Send + Sync + 'static, + UnderlyingChainOf>: bp_runtime::Chain + Parachain, + { + let message_payload = prepare_inbound_xcm(xcm_message, message_destination); + let message_size = StorageProofSize::Minimal(message_payload.len() as u32); + // prepare para storage proof containing message + let (para_state_root, para_storage_proof) = prepare_messages_storage_proof::( + lane_id, + message_nonce..=message_nonce, + None, + message_size, + message_payload, + encode_all_messages, + encode_lane_data, + ); + + let ( + relay_chain_header, + justification, + bridged_para_head, + parachain_heads, + para_heads_proof, + ) = make_complex_bridged_heads_proof::( + para_state_root, + para_header_number, + relay_header_number, + bridged_para_id, + ); + + let message_proof = FromBridgedChainMessagesProof { + bridged_header_hash: bridged_para_head.hash(), + storage_proof: para_storage_proof, + lane: lane_id, + nonces_start: message_nonce, + nonces_end: message_nonce, + }; + + ( + relay_chain_header, + justification, + bridged_para_head, + parachain_heads, + para_heads_proof, + message_proof, + ) + } + + /// Prepare storage proofs of message confirmations, stored at the target chain. + pub fn make_complex_relayer_confirmation_proofs( + lane_id: LaneId, + para_header_number: u32, + relay_header_number: u32, + bridged_para_id: u32, + relayer_id_at_this_chain: AccountId32, + relayers_state: UnrewardedRelayersState, + ) -> ( + HeaderOf, + GrandpaJustification>, + ParaHead, + Vec<(ParaId, ParaHash)>, + ParaHeadsProof, + FromBridgedChainMessagesDeliveryProof, + ) + where + BridgedRelayChain: ChainWithGrandpa, + HashOf: From, + MB: MessageBridge, + ::BridgedChain: Send + Sync + 'static, + ::ThisChain: Send + Sync + 'static, + <::ThisChain as bp_runtime::Chain>::AccountId: From, + UnderlyingChainOf>: bp_runtime::Chain + Parachain, + { + // prepare para storage proof containing message delivery proof + let (para_state_root, para_storage_proof) = prepare_message_delivery_storage_proof::( + lane_id, + InboundLaneData { + relayers: vec![ + UnrewardedRelayer { + relayer: relayer_id_at_this_chain.into(), + messages: DeliveredMessages::new(1) + }; + relayers_state.unrewarded_relayer_entries as usize + ] + .into(), + last_confirmed_nonce: 1, + }, + StorageProofSize::Minimal(0), + ); + + let ( + relay_chain_header, + justification, + bridged_para_head, + parachain_heads, + para_heads_proof, + ) = make_complex_bridged_heads_proof::( + para_state_root, + para_header_number, + relay_header_number, + bridged_para_id, + ); + + let message_delivery_proof = FromBridgedChainMessagesDeliveryProof { + bridged_header_hash: bridged_para_head.hash(), + storage_proof: para_storage_proof, + lane: lane_id, + }; + + ( + relay_chain_header, + justification, + bridged_para_head, + parachain_heads, + para_heads_proof, + message_delivery_proof, + ) + } + + /// Make bridged parachain header with given state root and relay header that is finalizing it. + pub fn make_complex_bridged_heads_proof( + para_state_root: ParaHash, + para_header_number: u32, + relay_header_number: u32, + bridged_para_id: u32, + ) -> ( + HeaderOf, + GrandpaJustification>, + ParaHead, + Vec<(ParaId, ParaHash)>, + ParaHeadsProof, + ) + where + BridgedRelayChain: ChainWithGrandpa, + HashOf: From, + MB: MessageBridge, + ::BridgedChain: Send + Sync + 'static, + ::ThisChain: Send + Sync + 'static, + UnderlyingChainOf>: bp_runtime::Chain + Parachain, + { + let bridged_para_head = ParaHead( + bp_test_utils::test_header_with_root::>( + para_header_number.into(), + para_state_root.into(), + ) + .encode(), + ); + let (relay_state_root, para_heads_proof, parachain_heads) = + prepare_parachain_heads_proof::>(vec![( + bridged_para_id, + bridged_para_head.clone(), + )]); + assert_eq!(bridged_para_head.hash(), parachain_heads[0].1); + + // import bridged relay chain block#1 with state root containing head#5 of bridged parachain + let mut relay_chain_header: BridgedRelayChain::Header = + bp_test_utils::test_header_with_root( + relay_header_number.into(), + relay_state_root.into(), + ); + // to compute proper cost of GRANDPA call, let's add some dummy bytes to header, so that the + // `submit_finality_proof` call size would be close to maximal expected (and refundable) + let expected_bytes_in_grandpa_call = BridgedRelayChain::AVERAGE_HEADER_SIZE_IN_JUSTIFICATION + .saturating_mul(BridgedRelayChain::REASONABLE_HEADERS_IN_JUSTIFICATON_ANCESTRY) + .saturating_add(BridgedRelayChain::MAX_HEADER_SIZE) + as usize; + let extra_bytes_required = + expected_bytes_in_grandpa_call.saturating_sub(relay_chain_header.encoded_size()); + relay_chain_header + .digest_mut() + .push(DigestItem::Other(vec![42; extra_bytes_required])); + + let justification = make_default_justification(&relay_chain_header); + (relay_chain_header, justification, bridged_para_head, parachain_heads, para_heads_proof) + } + + /// Helper that creates InitializationData mock data, that can be used to initialize bridge + /// GRANDPA pallet + pub fn initialization_data< + Runtime: pallet_bridge_grandpa::Config, + GrandpaPalletInstance: 'static, + >( + block_number: u32, + ) -> bp_header_chain::InitializationData> { + bp_header_chain::InitializationData { + header: Box::new(bp_test_utils::test_header(block_number.into())), + authority_list: authority_list(), + set_id: 1, + operating_mode: BasicOperatingMode::Normal, + } + } + + /// Dummy xcm + pub(crate) fn dummy_xcm() -> Xcm<()> { + vec![Trap(42)].into() + } + + pub(crate) fn dispatch_message( + lane_id: LaneId, + nonce: MessageNonce, + payload: Vec, + ) -> DispatchMessage> { + DispatchMessage { + key: MessageKey { lane_id, nonce }, + data: DispatchMessageData { payload: Ok(payload) }, + } + } + + /// Macro used for simulate_export_message and capturing bytes + macro_rules! grab_haul_blob ( + ($name:ident, $grabbed_payload:ident) => { + std::thread_local! { + static $grabbed_payload: std::cell::RefCell>> = std::cell::RefCell::new(None); + } + + struct $name; + impl HaulBlob for $name { + fn haul_blob(blob: Vec) -> Result<(), HaulBlobError>{ + $grabbed_payload.with(|rm| *rm.borrow_mut() = Some(blob)); + Ok(()) + } + } + } + ); + + /// Simulates `HaulBlobExporter` and all its wrapping and captures generated plain bytes, + /// which are transferred over bridge. + pub(crate) fn simulate_message_exporter_on_bridged_chain< + SourceNetwork: Get, + DestinationNetwork: Get, + >( + (destination_network, destination_junctions): (NetworkId, Junctions), + ) -> Vec { + grab_haul_blob!(GrabbingHaulBlob, GRABBED_HAUL_BLOB_PAYLOAD); + + // lets pretend that some parachain on bridged chain exported the message + let universal_source_on_bridged_chain = + X2(GlobalConsensus(SourceNetwork::get()), Parachain(5678)); + let channel = 1_u32; + + // simulate XCM message export + let (ticket, fee) = + validate_export::>( + destination_network, + channel, + universal_source_on_bridged_chain, + destination_junctions, + dummy_xcm(), + ) + .expect("validate_export to pass"); + log::info!( + target: "simulate_message_exporter_on_bridged_chain", + "HaulBlobExporter::validate fee: {:?}", + fee + ); + let xcm_hash = + HaulBlobExporter::::deliver(ticket) + .expect("deliver to pass"); + log::info!( + target: "simulate_message_exporter_on_bridged_chain", + "HaulBlobExporter::deliver xcm_hash: {:?}", + xcm_hash + ); + + GRABBED_HAUL_BLOB_PAYLOAD.with(|r| r.take().expect("Encoded message should be here")) + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_grandpa_chain.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_grandpa_chain.rs deleted file mode 100644 index 3a0bbf8f571..00000000000 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_grandpa_chain.rs +++ /dev/null @@ -1,442 +0,0 @@ -// 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 . - -//! Module contains predefined test-case scenarios for `Runtime` with bridging capabilities -//! with remote GRANDPA chain. - -use crate::{ - test_cases::{helpers, run_test}, - test_data, -}; - -use bp_header_chain::ChainWithGrandpa; -use bp_messages::{ - source_chain::TargetHeaderChain, target_chain::SourceHeaderChain, LaneId, - UnrewardedRelayersState, -}; -use bp_relayers::{RewardsAccountOwner, RewardsAccountParams}; -use bp_runtime::{HashOf, UnderlyingChainOf}; -use bridge_runtime_common::{ - messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, - BridgedChain as MessageBridgedChain, MessageBridge, ThisChain as MessageThisChain, - }, - messages_xcm_extension::XcmAsPlainPayload, -}; -use frame_support::traits::{Get, OnFinalize, OnInitialize, OriginTrait}; -use frame_system::pallet_prelude::BlockNumberFor; -use parachains_runtimes_test_utils::{ - AccountIdOf, BasicParachainRuntime, CollatorSessionKeys, ValidatorIdOf, -}; -use sp_keyring::AccountKeyring::*; -use sp_runtime::{traits::Header as HeaderT, AccountId32}; -use xcm::latest::prelude::*; - -/// Test-case makes sure that Runtime can dispatch XCM messages submitted by relayer, -/// with proofs (finality, message) independently submitted. -/// Also verifies relayer transaction signed extensions work as intended. -pub fn relayed_incoming_message_works< - Runtime, - AllPalletsWithoutSystem, - HrmpChannelOpener, - GPI, - MPI, - MB, ->( - collator_session_key: CollatorSessionKeys, - runtime_para_id: u32, - bridged_chain_id: bp_runtime::ChainId, - sibling_parachain_id: u32, - local_relay_chain_id: NetworkId, - lane_id: LaneId, - prepare_configuration: impl Fn(), - construct_and_apply_extrinsic: fn( - sp_keyring::AccountKeyring, - ::RuntimeCall, - ) -> sp_runtime::DispatchOutcome, -) where - Runtime: BasicParachainRuntime - + cumulus_pallet_xcmp_queue::Config - + pallet_bridge_grandpa::Config< - GPI, - BridgedChain = UnderlyingChainOf>, - > + pallet_bridge_messages::Config - + pallet_bridge_relayers::Config, - AllPalletsWithoutSystem: - OnInitialize> + OnFinalize>, - GPI: 'static, - MPI: 'static, - MB: MessageBridge, - ::BridgedChain: Send + Sync + 'static, - ::ThisChain: Send + Sync + 'static, - UnderlyingChainOf>: ChainWithGrandpa, - HrmpChannelOpener: frame_support::inherent::ProvideInherent< - Call = cumulus_pallet_parachain_system::Call, - >, - ValidatorIdOf: From>, - >::SourceHeaderChain: SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof>>, - >, - ::AccountId: - Into<<::RuntimeOrigin as OriginTrait>::AccountId>, - ::AccountId: From, - AccountIdOf: From, - >::InboundRelayer: From, - ::RuntimeCall: From> - + From>, -{ - helpers::relayed_incoming_message_works::< - Runtime, - AllPalletsWithoutSystem, - HrmpChannelOpener, - MPI, - >( - collator_session_key, - runtime_para_id, - sibling_parachain_id, - local_relay_chain_id, - construct_and_apply_extrinsic, - |relayer_id_at_this_chain, - relayer_id_at_bridged_chain, - message_destination, - message_nonce, - xcm| { - let relay_header_number = 5u32.into(); - - prepare_configuration(); - - // start with bridged relay chain block#0 - helpers::initialize_bridge_grandpa_pallet::( - test_data::initialization_data::(0), - ); - - // generate bridged relay chain finality, parachain heads and message proofs, - // to be submitted by relayer to this chain. - let (relay_chain_header, grandpa_justification, message_proof) = - test_data::from_grandpa_chain::make_complex_relayer_delivery_proofs::( - lane_id, - xcm.into(), - message_nonce, - message_destination, - relay_header_number, - ); - - let relay_chain_header_hash = relay_chain_header.hash(); - vec![ - ( - pallet_bridge_grandpa::Call::::submit_finality_proof { - finality_target: Box::new(relay_chain_header), - justification: grandpa_justification, - }.into(), - helpers::VerifySubmitGrandpaFinalityProofOutcome::::expect_best_header_hash(relay_chain_header_hash), - ), - ( - pallet_bridge_messages::Call::::receive_messages_proof { - relayer_id_at_bridged_chain, - proof: message_proof, - messages_count: 1, - dispatch_weight: Weight::from_parts(1000000000, 0), - }.into(), - Box::new(( - helpers::VerifySubmitMessagesProofOutcome::::expect_last_delivered_nonce(lane_id, 1), - helpers::VerifyRelayerRewarded::::expect_relayer_reward( - relayer_id_at_this_chain, - RewardsAccountParams::new( - lane_id, - bridged_chain_id, - RewardsAccountOwner::ThisChain, - ), - ), - )), - ), - ] - }, - ); -} - -/// Test-case makes sure that Runtime can dispatch XCM messages submitted by relayer, -/// with proofs (finality, message) batched together in signed extrinsic. -/// Also verifies relayer transaction signed extensions work as intended. -pub fn complex_relay_extrinsic_works< - Runtime, - AllPalletsWithoutSystem, - XcmConfig, - HrmpChannelOpener, - GPI, - MPI, - MB, ->( - collator_session_key: CollatorSessionKeys, - runtime_para_id: u32, - sibling_parachain_id: u32, - bridged_chain_id: bp_runtime::ChainId, - local_relay_chain_id: NetworkId, - lane_id: LaneId, - prepare_configuration: impl Fn(), - construct_and_apply_extrinsic: fn( - sp_keyring::AccountKeyring, - ::RuntimeCall, - ) -> sp_runtime::DispatchOutcome, -) where - Runtime: BasicParachainRuntime - + cumulus_pallet_xcmp_queue::Config - + pallet_bridge_grandpa::Config< - GPI, - BridgedChain = UnderlyingChainOf>, - > + pallet_bridge_messages::Config - + pallet_bridge_relayers::Config - + pallet_utility::Config, - AllPalletsWithoutSystem: - OnInitialize> + OnFinalize>, - GPI: 'static, - MPI: 'static, - MB: MessageBridge, - ::BridgedChain: Send + Sync + 'static, - ::ThisChain: Send + Sync + 'static, - UnderlyingChainOf>: ChainWithGrandpa, - HrmpChannelOpener: frame_support::inherent::ProvideInherent< - Call = cumulus_pallet_parachain_system::Call, - >, - ValidatorIdOf: From>, - >::SourceHeaderChain: SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof>>, - >, - ::AccountId: - Into<<::RuntimeOrigin as OriginTrait>::AccountId>, - ::AccountId: From, - AccountIdOf: From, - >::InboundRelayer: From, - ::RuntimeCall: From> - + From>, - ::RuntimeCall: From>, -{ - helpers::relayed_incoming_message_works::< - Runtime, - AllPalletsWithoutSystem, - HrmpChannelOpener, - MPI, - >( - collator_session_key, - runtime_para_id, - sibling_parachain_id, - local_relay_chain_id, - construct_and_apply_extrinsic, - |relayer_id_at_this_chain, - relayer_id_at_bridged_chain, - message_destination, - message_nonce, - xcm| { - let relay_header_number = 1u32.into(); - - prepare_configuration(); - - // start with bridged relay chain block#0 - helpers::initialize_bridge_grandpa_pallet::( - test_data::initialization_data::(0), - ); - - // generate bridged relay chain finality, parachain heads and message proofs, - // to be submitted by relayer to this chain. - let (relay_chain_header, grandpa_justification, message_proof) = - test_data::from_grandpa_chain::make_complex_relayer_delivery_proofs::( - lane_id, - xcm.into(), - message_nonce, - message_destination, - relay_header_number, - ); - - let relay_chain_header_hash = relay_chain_header.hash(); - vec![( - pallet_utility::Call::::batch_all { - calls: vec![ - pallet_bridge_grandpa::Call::::submit_finality_proof { - finality_target: Box::new(relay_chain_header), - justification: grandpa_justification, - }.into(), - pallet_bridge_messages::Call::::receive_messages_proof { - relayer_id_at_bridged_chain, - proof: message_proof, - messages_count: 1, - dispatch_weight: Weight::from_parts(1000000000, 0), - }.into(), - ], - }.into(), - Box::new(( - helpers::VerifySubmitGrandpaFinalityProofOutcome::::expect_best_header_hash(relay_chain_header_hash), - helpers::VerifySubmitMessagesProofOutcome::::expect_last_delivered_nonce(lane_id, 1), - helpers::VerifyRelayerRewarded::::expect_relayer_reward( - relayer_id_at_this_chain, - RewardsAccountParams::new( - lane_id, - bridged_chain_id, - RewardsAccountOwner::ThisChain, - ), - ), - )), - )] - }, - ); -} - -/// Estimates transaction fee for default message delivery transaction (batched with required -/// proofs) from bridged GRANDPA chain. -pub fn can_calculate_fee_for_complex_message_delivery_transaction( - collator_session_key: CollatorSessionKeys, - compute_extrinsic_fee: fn(pallet_utility::Call) -> u128, -) -> u128 -where - Runtime: BasicParachainRuntime - + pallet_bridge_grandpa::Config< - GPI, - BridgedChain = UnderlyingChainOf>, - > + pallet_bridge_messages::Config< - MPI, - InboundPayload = XcmAsPlainPayload, - InboundRelayer = bp_runtime::AccountIdOf>, - > + pallet_utility::Config, - GPI: 'static, - MPI: 'static, - MB: MessageBridge, - ::BridgedChain: Send + Sync + 'static, - ::ThisChain: Send + Sync + 'static, - UnderlyingChainOf>: bp_runtime::Chain + ChainWithGrandpa, - ValidatorIdOf: From>, - >::SourceHeaderChain: SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof>>, - >, - bp_runtime::AccountIdOf>: From, - ::RuntimeCall: From> - + From>, -{ - run_test::(collator_session_key, 1000, vec![], || { - // generate bridged relay chain finality, parachain heads and message proofs, - // to be submitted by relayer to this chain. - // - // we don't care about parameter values here, apart from the XCM message size. But we - // do not need to have a large message here, because we're charging for every byte of - // the message additionally - let (relay_chain_header, grandpa_justification, message_proof) = - test_data::from_grandpa_chain::make_complex_relayer_delivery_proofs::( - LaneId::default(), - vec![xcm::v3::Instruction::<()>::ClearOrigin; 1_024].into(), - 1, - X2(GlobalConsensus(Polkadot), Parachain(1_000)), - 1u32.into(), - ); - - // generate batch call that provides finality for bridged relay and parachains + message - // proof - let batch = test_data::from_grandpa_chain::make_complex_relayer_delivery_batch::< - Runtime, - GPI, - MPI, - >( - relay_chain_header, - grandpa_justification, - message_proof, - Dave.public().into(), - ); - let estimated_fee = compute_extrinsic_fee(batch); - - log::error!( - target: "bridges::estimate", - "Estimate fee: {:?} for single message delivery for runtime: {:?}", - estimated_fee, - Runtime::Version::get(), - ); - - estimated_fee - }) -} - -/// Estimates transaction fee for default message confirmation transaction (batched with required -/// proofs) from bridged GRANDPA chain. -pub fn can_calculate_fee_for_complex_message_confirmation_transaction( - collator_session_key: CollatorSessionKeys, - compute_extrinsic_fee: fn(pallet_utility::Call) -> u128, -) -> u128 -where - Runtime: BasicParachainRuntime - + pallet_bridge_grandpa::Config< - GPI, - BridgedChain = UnderlyingChainOf>, - > + pallet_bridge_messages::Config - + pallet_utility::Config, - GPI: 'static, - MPI: 'static, - MB: MessageBridge, - ::BridgedChain: Send + Sync + 'static, - ::ThisChain: Send + Sync + 'static, - <::ThisChain as bp_runtime::Chain>::AccountId: From, - UnderlyingChainOf>: ChainWithGrandpa, - ValidatorIdOf: From>, - ::AccountId: - Into<<::RuntimeOrigin as OriginTrait>::AccountId>, - ::AccountId: From, - AccountIdOf: From, - >::InboundRelayer: From, - >::TargetHeaderChain: TargetHeaderChain< - XcmAsPlainPayload, - Runtime::AccountId, - MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof< - HashOf>>, - >, - >, - ::RuntimeCall: From> - + From>, - bp_runtime::AccountIdOf>: From, -{ - run_test::(collator_session_key, 1000, vec![], || { - // generate bridged relay chain finality, parachain heads and message proofs, - // to be submitted by relayer to this chain. - let unrewarded_relayers = UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - total_messages: 1, - ..Default::default() - }; - let (relay_chain_header, grandpa_justification, message_delivery_proof) = - test_data::from_grandpa_chain::make_complex_relayer_confirmation_proofs::( - LaneId::default(), - 1u32.into(), - Alice.public().into(), - unrewarded_relayers.clone(), - ); - - // generate batch call that provides finality for bridged relay and parachains + message - // proof - let batch = test_data::from_grandpa_chain::make_complex_relayer_confirmation_batch::< - Runtime, - GPI, - MPI, - >( - relay_chain_header, - grandpa_justification, - message_delivery_proof, - unrewarded_relayers, - ); - let estimated_fee = compute_extrinsic_fee(batch); - - log::error!( - target: "bridges::estimate", - "Estimate fee: {:?} for single message confirmation for runtime: {:?}", - estimated_fee, - Runtime::Version::get(), - ); - - estimated_fee - }) -} diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_parachain.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_parachain.rs deleted file mode 100644 index 7e4ff8f874d..00000000000 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_parachain.rs +++ /dev/null @@ -1,544 +0,0 @@ -// 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 . - -//! Module contains predefined test-case scenarios for `Runtime` with bridging capabilities -//! with remote parachain. - -use crate::{ - test_cases::{helpers, run_test}, - test_data, -}; - -use bp_messages::{ - source_chain::TargetHeaderChain, target_chain::SourceHeaderChain, LaneId, - UnrewardedRelayersState, -}; -use bp_polkadot_core::parachains::ParaHash; -use bp_relayers::{RewardsAccountOwner, RewardsAccountParams}; -use bp_runtime::{Parachain, UnderlyingChainOf}; -use bridge_runtime_common::{ - messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, - BridgedChain as MessageBridgedChain, MessageBridge, - }, - messages_xcm_extension::XcmAsPlainPayload, -}; -use frame_support::traits::{Get, OnFinalize, OnInitialize, OriginTrait}; -use frame_system::pallet_prelude::BlockNumberFor; -use pallet_bridge_parachains::{RelayBlockHash, RelayBlockNumber}; -use parachains_runtimes_test_utils::{ - AccountIdOf, BasicParachainRuntime, CollatorSessionKeys, ValidatorIdOf, -}; -use sp_keyring::AccountKeyring::*; -use sp_runtime::{traits::Header as HeaderT, AccountId32}; -use xcm::latest::prelude::*; - -/// Test-case makes sure that Runtime can dispatch XCM messages submitted by relayer, -/// with proofs (finality, para heads, message) independently submitted. -/// Also verifies relayer transaction signed extensions work as intended. -pub fn relayed_incoming_message_works< - Runtime, - AllPalletsWithoutSystem, - HrmpChannelOpener, - GPI, - PPI, - MPI, - MB, ->( - collator_session_key: CollatorSessionKeys, - runtime_para_id: u32, - bridged_para_id: u32, - bridged_chain_id: bp_runtime::ChainId, - sibling_parachain_id: u32, - local_relay_chain_id: NetworkId, - lane_id: LaneId, - prepare_configuration: impl Fn(), - construct_and_apply_extrinsic: fn( - sp_keyring::AccountKeyring, - ::RuntimeCall, - ) -> sp_runtime::DispatchOutcome, -) where - Runtime: BasicParachainRuntime - + cumulus_pallet_xcmp_queue::Config - + cumulus_pallet_parachain_system::Config - + pallet_bridge_grandpa::Config - + pallet_bridge_parachains::Config - + pallet_bridge_messages::Config - + pallet_bridge_relayers::Config, - AllPalletsWithoutSystem: - OnInitialize> + OnFinalize>, - GPI: 'static, - PPI: 'static, - MPI: 'static, - MB: MessageBridge, - ::BridgedChain: Send + Sync + 'static, - ::ThisChain: Send + Sync + 'static, - UnderlyingChainOf>: bp_runtime::Chain + Parachain, - HrmpChannelOpener: frame_support::inherent::ProvideInherent< - Call = cumulus_pallet_parachain_system::Call, - >, - ValidatorIdOf: From>, - >::SourceHeaderChain: - SourceHeaderChain>, - >::BridgedChain: - bp_runtime::Chain, - ParaHash: From< - <>::BridgedChain as bp_runtime::Chain>::Hash, - >, - ::AccountId: - Into<<::RuntimeOrigin as OriginTrait>::AccountId>, - ::AccountId: From, - AccountIdOf: From, - >::InboundRelayer: From, - ::RuntimeCall: From> - + From> - + From>, -{ - helpers::relayed_incoming_message_works::< - Runtime, - AllPalletsWithoutSystem, - HrmpChannelOpener, - MPI, - >( - collator_session_key, - runtime_para_id, - sibling_parachain_id, - local_relay_chain_id, - construct_and_apply_extrinsic, - |relayer_id_at_this_chain, - relayer_id_at_bridged_chain, - message_destination, - message_nonce, - xcm| { - let para_header_number = 5; - let relay_header_number = 1; - - prepare_configuration(); - - // start with bridged relay chain block#0 - helpers::initialize_bridge_grandpa_pallet::( - test_data::initialization_data::(0), - ); - - // generate bridged relay chain finality, parachain heads and message proofs, - // to be submitted by relayer to this chain. - let ( - relay_chain_header, - grandpa_justification, - parachain_head, - parachain_heads, - para_heads_proof, - message_proof, - ) = test_data::from_parachain::make_complex_relayer_delivery_proofs::< - >::BridgedChain, - MB, - (), - >( - lane_id, - xcm.into(), - message_nonce, - message_destination, - para_header_number, - relay_header_number, - bridged_para_id, - ); - - let parachain_head_hash = parachain_head.hash(); - let relay_chain_header_hash = relay_chain_header.hash(); - let relay_chain_header_number = *relay_chain_header.number(); - vec![ - ( - pallet_bridge_grandpa::Call::::submit_finality_proof { - finality_target: Box::new(relay_chain_header), - justification: grandpa_justification, - }.into(), - helpers::VerifySubmitGrandpaFinalityProofOutcome::::expect_best_header_hash(relay_chain_header_hash), - ), - ( - pallet_bridge_parachains::Call::::submit_parachain_heads { - at_relay_block: (relay_chain_header_number, relay_chain_header_hash), - parachains: parachain_heads, - parachain_heads_proof: para_heads_proof, - }.into(), - helpers::VerifySubmitParachainHeaderProofOutcome::::expect_best_header_hash(bridged_para_id, parachain_head_hash), - ), - ( - pallet_bridge_messages::Call::::receive_messages_proof { - relayer_id_at_bridged_chain, - proof: message_proof, - messages_count: 1, - dispatch_weight: Weight::from_parts(1000000000, 0), - }.into(), - Box::new(( - helpers::VerifySubmitMessagesProofOutcome::::expect_last_delivered_nonce(lane_id, 1), - helpers::VerifyRelayerRewarded::::expect_relayer_reward( - relayer_id_at_this_chain, - RewardsAccountParams::new( - lane_id, - bridged_chain_id, - RewardsAccountOwner::ThisChain, - ), - ), - )), - ), - ] - }, - ); -} - -/// Test-case makes sure that Runtime can dispatch XCM messages submitted by relayer, -/// with proofs (finality, para heads, message) batched together in signed extrinsic. -/// Also verifies relayer transaction signed extensions work as intended. -pub fn complex_relay_extrinsic_works< - Runtime, - AllPalletsWithoutSystem, - XcmConfig, - HrmpChannelOpener, - GPI, - PPI, - MPI, - MB, ->( - collator_session_key: CollatorSessionKeys, - runtime_para_id: u32, - bridged_para_id: u32, - sibling_parachain_id: u32, - bridged_chain_id: bp_runtime::ChainId, - local_relay_chain_id: NetworkId, - lane_id: LaneId, - prepare_configuration: impl Fn(), - construct_and_apply_extrinsic: fn( - sp_keyring::AccountKeyring, - ::RuntimeCall, - ) -> sp_runtime::DispatchOutcome, -) where - Runtime: BasicParachainRuntime - + cumulus_pallet_xcmp_queue::Config - + cumulus_pallet_parachain_system::Config - + pallet_bridge_grandpa::Config - + pallet_bridge_parachains::Config - + pallet_bridge_messages::Config - + pallet_bridge_relayers::Config - + pallet_utility::Config, - AllPalletsWithoutSystem: - OnInitialize> + OnFinalize>, - GPI: 'static, - PPI: 'static, - MPI: 'static, - MB: MessageBridge, - ::BridgedChain: Send + Sync + 'static, - ::ThisChain: Send + Sync + 'static, - UnderlyingChainOf>: bp_runtime::Chain + Parachain, - HrmpChannelOpener: frame_support::inherent::ProvideInherent< - Call = cumulus_pallet_parachain_system::Call, - >, - ValidatorIdOf: From>, - >::SourceHeaderChain: - SourceHeaderChain>, - >::BridgedChain: - bp_runtime::Chain, - ParaHash: From< - <>::BridgedChain as bp_runtime::Chain>::Hash, - >, - ::AccountId: - Into<<::RuntimeOrigin as OriginTrait>::AccountId>, - ::AccountId: From, - AccountIdOf: From, - >::InboundRelayer: From, - ::RuntimeCall: From> - + From> - + From>, - ::RuntimeCall: From>, -{ - helpers::relayed_incoming_message_works::< - Runtime, - AllPalletsWithoutSystem, - HrmpChannelOpener, - MPI, - >( - collator_session_key, - runtime_para_id, - sibling_parachain_id, - local_relay_chain_id, - construct_and_apply_extrinsic, - |relayer_id_at_this_chain, - relayer_id_at_bridged_chain, - message_destination, - message_nonce, - xcm| { - let para_header_number = 5; - let relay_header_number = 1; - - prepare_configuration(); - - // start with bridged relay chain block#0 - helpers::initialize_bridge_grandpa_pallet::( - test_data::initialization_data::(0), - ); - - // generate bridged relay chain finality, parachain heads and message proofs, - // to be submitted by relayer to this chain. - let ( - relay_chain_header, - grandpa_justification, - parachain_head, - parachain_heads, - para_heads_proof, - message_proof, - ) = test_data::from_parachain::make_complex_relayer_delivery_proofs::< - >::BridgedChain, - MB, - (), - >( - lane_id, - xcm.into(), - message_nonce, - message_destination, - para_header_number, - relay_header_number, - bridged_para_id, - ); - - let parachain_head_hash = parachain_head.hash(); - let relay_chain_header_hash = relay_chain_header.hash(); - let relay_chain_header_number = *relay_chain_header.number(); - vec![( - pallet_utility::Call::::batch_all { - calls: vec![ - pallet_bridge_grandpa::Call::::submit_finality_proof { - finality_target: Box::new(relay_chain_header), - justification: grandpa_justification, - }.into(), - pallet_bridge_parachains::Call::::submit_parachain_heads { - at_relay_block: (relay_chain_header_number, relay_chain_header_hash), - parachains: parachain_heads, - parachain_heads_proof: para_heads_proof, - }.into(), - pallet_bridge_messages::Call::::receive_messages_proof { - relayer_id_at_bridged_chain, - proof: message_proof, - messages_count: 1, - dispatch_weight: Weight::from_parts(1000000000, 0), - }.into(), - ], - }.into(), - Box::new(( - helpers::VerifySubmitGrandpaFinalityProofOutcome::::expect_best_header_hash(relay_chain_header_hash), - helpers::VerifySubmitParachainHeaderProofOutcome::::expect_best_header_hash(bridged_para_id, parachain_head_hash), - helpers::VerifySubmitMessagesProofOutcome::::expect_last_delivered_nonce(lane_id, 1), - helpers::VerifyRelayerRewarded::::expect_relayer_reward( - relayer_id_at_this_chain, - RewardsAccountParams::new( - lane_id, - bridged_chain_id, - RewardsAccountOwner::ThisChain, - ), - ), - )), - )] - }, - ); -} - -/// Estimates transaction fee for default message delivery transaction (batched with required -/// proofs) from bridged parachain. -pub fn can_calculate_fee_for_complex_message_delivery_transaction( - collator_session_key: CollatorSessionKeys, - compute_extrinsic_fee: fn(pallet_utility::Call::) -> u128, -) -> u128 -where - Runtime: frame_system::Config - + pallet_balances::Config - + pallet_session::Config - + pallet_xcm::Config - + parachain_info::Config - + pallet_collator_selection::Config - + cumulus_pallet_parachain_system::Config - + pallet_bridge_grandpa::Config - + pallet_bridge_parachains::Config - + pallet_bridge_messages::Config - + pallet_utility::Config, - GPI: 'static, - PPI: 'static, - MPI: 'static, - MB: MessageBridge, - ::BridgedChain: Send + Sync + 'static, - ::ThisChain: Send + Sync + 'static, - UnderlyingChainOf>: bp_runtime::Chain + Parachain, - ValidatorIdOf: From>, - <>::SourceHeaderChain as SourceHeaderChain>::MessagesProof: - From>, - >::BridgedChain: bp_runtime::Chain, - ParaHash: From<<>::BridgedChain as bp_runtime::Chain>::Hash>, - ::AccountId: - Into<<::RuntimeOrigin as OriginTrait>::AccountId>, - ::AccountId: From, - AccountIdOf: From, - >::InboundRelayer: From, - ::RuntimeCall: - From> - + From> - + From>, -{ - run_test::(collator_session_key, 1000, vec![], || { - // generate bridged relay chain finality, parachain heads and message proofs, - // to be submitted by relayer to this chain. - // - // we don't care about parameter values here, apart from the XCM message size. But we - // do not need to have a large message here, because we're charging for every byte of - // the message additionally - let ( - relay_chain_header, - grandpa_justification, - _, - parachain_heads, - para_heads_proof, - message_proof, - ) = test_data::from_parachain::make_complex_relayer_delivery_proofs::< - >::BridgedChain, - MB, - (), - >( - LaneId::default(), - vec![xcm::v3::Instruction::<()>::ClearOrigin; 1_024].into(), - 1, - X2(GlobalConsensus(Polkadot), Parachain(1_000)), - 1, - 5, - 1_000, - ); - - // generate batch call that provides finality for bridged relay and parachains + message - // proof - let batch = test_data::from_parachain::make_complex_relayer_delivery_batch::< - Runtime, - GPI, - PPI, - MPI, - >( - relay_chain_header, - grandpa_justification, - parachain_heads, - para_heads_proof, - message_proof, - Dave.public().into(), - ); - let estimated_fee = compute_extrinsic_fee(batch); - - log::error!( - target: "bridges::estimate", - "Estimate fee: {:?} for single message delivery for runtime: {:?}", - estimated_fee, - Runtime::Version::get(), - ); - - estimated_fee - }) -} - -/// Estimates transaction fee for default message confirmation transaction (batched with required -/// proofs) from bridged parachain. -pub fn can_calculate_fee_for_complex_message_confirmation_transaction( - collator_session_key: CollatorSessionKeys, - compute_extrinsic_fee: fn(pallet_utility::Call::) -> u128, -) -> u128 -where - Runtime: frame_system::Config - + pallet_balances::Config - + pallet_session::Config - + pallet_xcm::Config - + parachain_info::Config - + pallet_collator_selection::Config - + cumulus_pallet_parachain_system::Config - + pallet_bridge_grandpa::Config - + pallet_bridge_parachains::Config - + pallet_bridge_messages::Config - + pallet_utility::Config, - GPI: 'static, - PPI: 'static, - MPI: 'static, - MB: MessageBridge, - ::BridgedChain: Send + Sync + 'static, - ::ThisChain: Send + Sync + 'static, - <::ThisChain as bp_runtime::Chain>::AccountId: From, - UnderlyingChainOf>: bp_runtime::Chain + Parachain, - ValidatorIdOf: From>, - <>::SourceHeaderChain as SourceHeaderChain>::MessagesProof: - From>, - >::BridgedChain: bp_runtime::Chain, - ParaHash: From<<>::BridgedChain as bp_runtime::Chain>::Hash>, - ::AccountId: - Into<<::RuntimeOrigin as OriginTrait>::AccountId>, - ::AccountId: From, - AccountIdOf: From, - >::InboundRelayer: From, - <>::TargetHeaderChain as TargetHeaderChain< - XcmAsPlainPayload, - Runtime::AccountId, - >>::MessagesDeliveryProof: From>, - ::RuntimeCall: - From> - + From> - + From>, -{ - run_test::(collator_session_key, 1000, vec![], || { - // generate bridged relay chain finality, parachain heads and message proofs, - // to be submitted by relayer to this chain. - let unrewarded_relayers = UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - total_messages: 1, - ..Default::default() - }; - let ( - relay_chain_header, - grandpa_justification, - _, - parachain_heads, - para_heads_proof, - message_delivery_proof, - ) = test_data::from_parachain::make_complex_relayer_confirmation_proofs::< - >::BridgedChain, - MB, - (), - >(LaneId::default(), 1, 5, 1_000, Alice.public().into(), unrewarded_relayers.clone()); - - // generate batch call that provides finality for bridged relay and parachains + message - // proof - let batch = test_data::from_parachain::make_complex_relayer_confirmation_batch::< - Runtime, - GPI, - PPI, - MPI, - >( - relay_chain_header, - grandpa_justification, - parachain_heads, - para_heads_proof, - message_delivery_proof, - unrewarded_relayers, - ); - let estimated_fee = compute_extrinsic_fee(batch); - - log::error!( - target: "bridges::estimate", - "Estimate fee: {:?} for single message confirmation for runtime: {:?}", - estimated_fee, - Runtime::Version::get(), - ); - - estimated_fee - }) -} diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs deleted file mode 100644 index 192aa017fff..00000000000 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs +++ /dev/null @@ -1,340 +0,0 @@ -// 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 . - -//! Module contains tests code, that is shared by all types of bridges - -use crate::test_cases::{run_test, RuntimeHelper}; - -use asset_test_utils::BasicParachainRuntime; -use bp_messages::{LaneId, MessageNonce}; -use bp_polkadot_core::parachains::{ParaHash, ParaId}; -use bp_relayers::RewardsAccountParams; -use frame_support::{ - assert_ok, - traits::{OnFinalize, OnInitialize, PalletInfoAccess}, -}; -use frame_system::pallet_prelude::BlockNumberFor; -use pallet_bridge_grandpa::{BridgedBlockHash, BridgedHeader}; -use parachains_common::AccountId; -use parachains_runtimes_test_utils::{ - mock_open_hrmp_channel, AccountIdOf, CollatorSessionKeys, ValidatorIdOf, -}; -use sp_core::Get; -use sp_keyring::AccountKeyring::*; -use sp_runtime::AccountId32; -use sp_std::marker::PhantomData; -use xcm::latest::prelude::*; - -#[impl_trait_for_tuples::impl_for_tuples(30)] -pub trait VerifyTransactionOutcome { - fn verify_outcome(&self); -} - -impl VerifyTransactionOutcome for Box { - fn verify_outcome(&self) { - VerifyTransactionOutcome::verify_outcome(&**self) - } -} - -/// Checks that the best finalized header hash in the bridge GRANDPA pallet equals to given one. -pub struct VerifySubmitGrandpaFinalityProofOutcome -where - Runtime: pallet_bridge_grandpa::Config, - GPI: 'static, -{ - expected_best_hash: BridgedBlockHash, -} - -impl VerifySubmitGrandpaFinalityProofOutcome -where - Runtime: pallet_bridge_grandpa::Config, - GPI: 'static, -{ - /// Expect given header hash to be the best after transaction. - pub fn expect_best_header_hash( - expected_best_hash: BridgedBlockHash, - ) -> Box { - Box::new(Self { expected_best_hash }) - } -} - -impl VerifyTransactionOutcome - for VerifySubmitGrandpaFinalityProofOutcome -where - Runtime: pallet_bridge_grandpa::Config, - GPI: 'static, -{ - fn verify_outcome(&self) { - assert_eq!( - pallet_bridge_grandpa::BestFinalized::::get().unwrap().1, - self.expected_best_hash - ); - assert!(pallet_bridge_grandpa::ImportedHeaders::::contains_key( - self.expected_best_hash - )); - } -} - -/// Checks that the best parachain header hash in the bridge parachains pallet equals to given one. -pub struct VerifySubmitParachainHeaderProofOutcome { - bridged_para_id: u32, - expected_best_hash: ParaHash, - _marker: PhantomData<(Runtime, PPI)>, -} - -impl VerifySubmitParachainHeaderProofOutcome -where - Runtime: pallet_bridge_parachains::Config, - PPI: 'static, -{ - /// Expect given header hash to be the best after transaction. - pub fn expect_best_header_hash( - bridged_para_id: u32, - expected_best_hash: ParaHash, - ) -> Box { - Box::new(Self { bridged_para_id, expected_best_hash, _marker: PhantomData }) - } -} - -impl VerifyTransactionOutcome - for VerifySubmitParachainHeaderProofOutcome -where - Runtime: pallet_bridge_parachains::Config, - PPI: 'static, -{ - fn verify_outcome(&self) { - assert_eq!( - pallet_bridge_parachains::ParasInfo::::get(ParaId(self.bridged_para_id)) - .map(|info| info.best_head_hash.head_hash), - Some(self.expected_best_hash), - ); - } -} - -/// Checks that the latest delivered nonce in the bridge messages pallet equals to given one. -pub struct VerifySubmitMessagesProofOutcome { - lane: LaneId, - expected_nonce: MessageNonce, - _marker: PhantomData<(Runtime, MPI)>, -} - -impl VerifySubmitMessagesProofOutcome -where - Runtime: pallet_bridge_messages::Config, - MPI: 'static, -{ - /// Expect given delivered nonce to be the latest after transaction. - pub fn expect_last_delivered_nonce( - lane: LaneId, - expected_nonce: MessageNonce, - ) -> Box { - Box::new(Self { lane, expected_nonce, _marker: PhantomData }) - } -} - -impl VerifyTransactionOutcome for VerifySubmitMessagesProofOutcome -where - Runtime: pallet_bridge_messages::Config, - MPI: 'static, -{ - fn verify_outcome(&self) { - assert_eq!( - pallet_bridge_messages::InboundLanes::::get(self.lane) - .last_delivered_nonce(), - self.expected_nonce, - ); - } -} - -/// Verifies that relayer is rewarded at this chain. -pub struct VerifyRelayerRewarded { - relayer: Runtime::AccountId, - reward_params: RewardsAccountParams, -} - -impl VerifyRelayerRewarded -where - Runtime: pallet_bridge_relayers::Config, -{ - /// Expect given delivered nonce to be the latest after transaction. - pub fn expect_relayer_reward( - relayer: Runtime::AccountId, - reward_params: RewardsAccountParams, - ) -> Box { - Box::new(Self { relayer, reward_params }) - } -} - -impl VerifyTransactionOutcome for VerifyRelayerRewarded -where - Runtime: pallet_bridge_relayers::Config, -{ - fn verify_outcome(&self) { - assert!(pallet_bridge_relayers::RelayerRewards::::get( - &self.relayer, - &self.reward_params, - ) - .is_some()); - } -} - -/// Initialize bridge GRANDPA pallet. -pub(crate) fn initialize_bridge_grandpa_pallet( - init_data: bp_header_chain::InitializationData>, -) where - Runtime: pallet_bridge_grandpa::Config, -{ - pallet_bridge_grandpa::Pallet::::initialize( - RuntimeHelper::::root_origin(), - init_data, - ) - .unwrap(); -} - -/// Runtime calls and their verifiers. -pub type CallsAndVerifiers = - Vec<(::RuntimeCall, Box)>; - -/// Test-case makes sure that Runtime can dispatch XCM messages submitted by relayer, -/// with proofs (finality, message) independently submitted. -pub fn relayed_incoming_message_works( - collator_session_key: CollatorSessionKeys, - runtime_para_id: u32, - sibling_parachain_id: u32, - local_relay_chain_id: NetworkId, - construct_and_apply_extrinsic: fn( - sp_keyring::AccountKeyring, - ::RuntimeCall, - ) -> sp_runtime::DispatchOutcome, - prepare_message_proof_import: impl FnOnce( - Runtime::AccountId, - Runtime::InboundRelayer, - InteriorMultiLocation, - MessageNonce, - Xcm<()>, - ) -> CallsAndVerifiers, -) where - Runtime: BasicParachainRuntime - + cumulus_pallet_xcmp_queue::Config - + pallet_bridge_messages::Config, - AllPalletsWithoutSystem: - OnInitialize> + OnFinalize>, - HrmpChannelOpener: frame_support::inherent::ProvideInherent< - Call = cumulus_pallet_parachain_system::Call, - >, - MPI: 'static, - ValidatorIdOf: From>, - AccountIdOf: From + From, - >::InboundRelayer: From, -{ - let relayer_at_target = Bob; - let relayer_id_on_target: AccountId32 = relayer_at_target.public().into(); - let relayer_at_source = Dave; - let relayer_id_on_source: AccountId32 = relayer_at_source.public().into(); - - assert_ne!(runtime_para_id, sibling_parachain_id); - - run_test::( - collator_session_key, - runtime_para_id, - vec![( - relayer_id_on_target.clone().into(), - Runtime::ExistentialDeposit::get() * 100000u32.into(), - )], - || { - let mut alice = [0u8; 32]; - alice[0] = 1; - - let included_head = RuntimeHelper::::run_to_block( - 2, - AccountId::from(alice).into(), - ); - mock_open_hrmp_channel::( - runtime_para_id.into(), - sibling_parachain_id.into(), - included_head, - &alice, - ); - - // set up relayer details and proofs - - let message_destination = - X2(GlobalConsensus(local_relay_chain_id), Parachain(sibling_parachain_id)); - // some random numbers (checked by test) - let message_nonce = 1; - - let xcm = vec![xcm::v3::Instruction::<()>::ClearOrigin; 42]; - let expected_dispatch = xcm::latest::Xcm::<()>({ - let mut expected_instructions = xcm.clone(); - // dispatch prepends bridge pallet instance - expected_instructions.insert( - 0, - DescendOrigin(X1(PalletInstance( - as PalletInfoAccess>::index() - as u8, - ))), - ); - expected_instructions - }); - - execute_and_verify_calls::( - relayer_at_target, - construct_and_apply_extrinsic, - prepare_message_proof_import( - relayer_id_on_target.clone().into(), - relayer_id_on_source.clone().into(), - message_destination, - message_nonce, - xcm.clone().into(), - ), - ); - - // verify that imported XCM contains original message - let imported_xcm = - RuntimeHelper::>::take_xcm( - sibling_parachain_id.into(), - ) - .unwrap(); - let dispatched = xcm::latest::Xcm::<()>::try_from(imported_xcm).unwrap(); - let mut dispatched_clone = dispatched.clone(); - for (idx, expected_instr) in expected_dispatch.0.iter().enumerate() { - assert_eq!(expected_instr, &dispatched.0[idx]); - assert_eq!(expected_instr, &dispatched_clone.0.remove(0)); - } - match dispatched_clone.0.len() { - 0 => (), - 1 => assert!(matches!(dispatched_clone.0[0], SetTopic(_))), - count => assert!(false, "Unexpected messages count: {:?}", count), - } - }, - ) -} - -/// Execute every call and verify its outcome. -fn execute_and_verify_calls( - submitter: sp_keyring::AccountKeyring, - construct_and_apply_extrinsic: fn( - sp_keyring::AccountKeyring, - ::RuntimeCall, - ) -> sp_runtime::DispatchOutcome, - calls_and_verifiers: CallsAndVerifiers, -) { - for (call, verifier) in calls_and_verifiers { - let dispatch_outcome = construct_and_apply_extrinsic(submitter, call); - assert_ok!(dispatch_outcome); - verifier.verify_outcome(); - } -} diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/mod.rs deleted file mode 100644 index cc347ecf30d..00000000000 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/mod.rs +++ /dev/null @@ -1,485 +0,0 @@ -// 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 . - -//! Module contains predefined test-case scenarios for `Runtime` with bridging capabilities. -//! -//! This file contains tests, suitable for all bridge runtimes. See `from_parachain` and -//! `from_grandpa_chain` submodules for tests, that are specific to the bridged chain type. - -pub mod from_grandpa_chain; -pub mod from_parachain; - -pub(crate) mod helpers; - -use crate::test_data; - -use asset_test_utils::BasicParachainRuntime; -use bp_messages::{ - target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch}, - LaneId, MessageKey, OutboundLaneData, -}; -use bridge_runtime_common::messages_xcm_extension::{ - XcmAsPlainPayload, XcmBlobMessageDispatchResult, -}; -use codec::Encode; -use frame_support::{ - assert_ok, - traits::{Get, OnFinalize, OnInitialize, OriginTrait}, -}; -use frame_system::pallet_prelude::BlockNumberFor; -use parachains_common::AccountId; -use parachains_runtimes_test_utils::{ - mock_open_hrmp_channel, AccountIdOf, BalanceOf, CollatorSessionKeys, ExtBuilder, ValidatorIdOf, - XcmReceivedFrom, -}; -use sp_runtime::{traits::Zero, AccountId32}; -use xcm::{latest::prelude::*, AlwaysLatest}; -use xcm_builder::DispatchBlobError; -use xcm_executor::{ - traits::{TransactAsset, WeightBounds}, - XcmExecutor, -}; - -// Re-export test_case from assets -pub use asset_test_utils::include_teleports_for_native_asset_works; - -pub type RuntimeHelper = - parachains_runtimes_test_utils::RuntimeHelper; - -// Re-export test_case from `parachains-runtimes-test-utils` -pub use parachains_runtimes_test_utils::test_cases::change_storage_constant_by_governance_works; - -/// Prepare default runtime storage and run test within this context. -pub fn run_test( - collator_session_key: CollatorSessionKeys, - runtime_para_id: u32, - balances: Vec<(Runtime::AccountId, Runtime::Balance)>, - test: impl FnOnce() -> T, -) -> T -where - Runtime: BasicParachainRuntime, - ValidatorIdOf: From>, -{ - ExtBuilder::::default() - .with_collators(collator_session_key.collators()) - .with_session_keys(collator_session_key.session_keys()) - .with_safe_xcm_version(XCM_VERSION) - .with_para_id(runtime_para_id.into()) - .with_balances(balances) - .with_tracing() - .build() - .execute_with(|| test()) -} - -/// Test-case makes sure that `Runtime` can process bridging initialize via governance-like call -pub fn initialize_bridge_by_governance_works( - collator_session_key: CollatorSessionKeys, - runtime_para_id: u32, - runtime_call_encode: Box< - dyn Fn(pallet_bridge_grandpa::Call) -> Vec, - >, -) where - Runtime: BasicParachainRuntime + pallet_bridge_grandpa::Config, - GrandpaPalletInstance: 'static, - ValidatorIdOf: From>, -{ - run_test::(collator_session_key, runtime_para_id, vec![], || { - // check mode before - assert_eq!( - pallet_bridge_grandpa::PalletOperatingMode::::try_get(), - Err(()) - ); - - // encode `initialize` call - let initialize_call = runtime_call_encode(pallet_bridge_grandpa::Call::< - Runtime, - GrandpaPalletInstance, - >::initialize { - init_data: test_data::initialization_data::(12345), - }); - - // overestimate - check weight for `pallet_bridge_grandpa::Pallet::initialize()` call - let require_weight_at_most = - ::DbWeight::get().reads_writes(7, 7); - - // execute XCM with Transacts to `initialize bridge` as governance does - assert_ok!(RuntimeHelper::::execute_as_governance( - initialize_call, - require_weight_at_most - ) - .ensure_complete()); - - // check mode after - assert_eq!( - pallet_bridge_grandpa::PalletOperatingMode::::try_get(), - Ok(bp_runtime::BasicOperatingMode::Normal) - ); - }) -} - -/// Test-case makes sure that `Runtime` can handle xcm `ExportMessage`: -/// Checks if received XCM messages is correctly added to the message outbound queue for delivery. -/// For SystemParachains we expect unpaid execution. -pub fn handle_export_message_from_system_parachain_to_outbound_queue_works< - Runtime, - XcmConfig, - MessagesPalletInstance, ->( - collator_session_key: CollatorSessionKeys, - runtime_para_id: u32, - sibling_parachain_id: u32, - unwrap_pallet_bridge_messages_event: Box< - dyn Fn(Vec) -> Option>, - >, - export_message_instruction: fn() -> Instruction, - expected_lane_id: LaneId, - existential_deposit: Option, - maybe_paid_export_message: Option, - prepare_configuration: impl Fn(), -) where - Runtime: BasicParachainRuntime + pallet_bridge_messages::Config, - XcmConfig: xcm_executor::Config, - MessagesPalletInstance: 'static, - ValidatorIdOf: From>, -{ - assert_ne!(runtime_para_id, sibling_parachain_id); - let sibling_parachain_location = MultiLocation::new(1, Parachain(sibling_parachain_id)); - - run_test::(collator_session_key, runtime_para_id, vec![], || { - prepare_configuration(); - - // check queue before - assert_eq!( - pallet_bridge_messages::OutboundLanes::::try_get( - expected_lane_id - ), - Err(()) - ); - - // prepare `ExportMessage` - let xcm = if let Some(fee) = maybe_paid_export_message { - // deposit ED to origin (if needed) - if let Some(ed) = existential_deposit { - XcmConfig::AssetTransactor::deposit_asset( - &ed, - &sibling_parachain_location, - Some(&XcmContext::with_message_id([0; 32])), - ) - .expect("deposited ed"); - } - // deposit fee to origin - XcmConfig::AssetTransactor::deposit_asset( - &fee, - &sibling_parachain_location, - Some(&XcmContext::with_message_id([0; 32])), - ) - .expect("deposited fee"); - - Xcm(vec![ - WithdrawAsset(MultiAssets::from(vec![fee.clone()])), - BuyExecution { fees: fee, weight_limit: Unlimited }, - export_message_instruction(), - ]) - } else { - Xcm(vec![ - UnpaidExecution { weight_limit: Unlimited, check_origin: None }, - export_message_instruction(), - ]) - }; - - // execute XCM - let hash = xcm.using_encoded(sp_io::hashing::blake2_256); - assert_ok!(XcmExecutor::::execute_xcm( - sibling_parachain_location, - xcm, - hash, - RuntimeHelper::::xcm_max_weight(XcmReceivedFrom::Sibling), - ) - .ensure_complete()); - - // check queue after - assert_eq!( - pallet_bridge_messages::OutboundLanes::::try_get( - expected_lane_id - ), - Ok(OutboundLaneData { - oldest_unpruned_nonce: 1, - latest_received_nonce: 0, - latest_generated_nonce: 1, - }) - ); - - // check events - let mut events = >::events() - .into_iter() - .filter_map(|e| unwrap_pallet_bridge_messages_event(e.event.encode())); - assert!(events.any(|e| matches!(e, pallet_bridge_messages::Event::MessageAccepted { .. }))); - }) -} - -/// Test-case makes sure that Runtime can route XCM messages received in inbound queue, -/// We just test here `MessageDispatch` configuration. -/// We expect that runtime can route messages: -/// 1. to Parent (relay chain) -/// 2. to Sibling parachain -pub fn message_dispatch_routing_works< - Runtime, - AllPalletsWithoutSystem, - XcmConfig, - HrmpChannelOpener, - MessagesPalletInstance, - RuntimeNetwork, - BridgedNetwork, - NetworkDistanceAsParentCount, ->( - collator_session_key: CollatorSessionKeys, - runtime_para_id: u32, - sibling_parachain_id: u32, - unwrap_cumulus_pallet_parachain_system_event: Box< - dyn Fn(Vec) -> Option>, - >, - unwrap_cumulus_pallet_xcmp_queue_event: Box< - dyn Fn(Vec) -> Option>, - >, - expected_lane_id: LaneId, - prepare_configuration: impl Fn(), -) where - Runtime: BasicParachainRuntime - + cumulus_pallet_xcmp_queue::Config - + pallet_bridge_messages::Config, - AllPalletsWithoutSystem: - OnInitialize> + OnFinalize>, - ::AccountId: - Into<<::RuntimeOrigin as OriginTrait>::AccountId>, - XcmConfig: xcm_executor::Config, - MessagesPalletInstance: 'static, - ValidatorIdOf: From>, - ::AccountId: From, - HrmpChannelOpener: frame_support::inherent::ProvideInherent< - Call = cumulus_pallet_parachain_system::Call, - >, - RuntimeNetwork: Get, - BridgedNetwork: Get, - NetworkDistanceAsParentCount: Get, -{ - struct NetworkWithParentCount(core::marker::PhantomData<(N, C)>); - impl, C: Get> Get for NetworkWithParentCount { - fn get() -> MultiLocation { - MultiLocation { parents: C::get(), interior: X1(GlobalConsensus(N::get())) } - } - } - - assert_ne!(runtime_para_id, sibling_parachain_id); - - run_test::(collator_session_key, runtime_para_id, vec![], || { - prepare_configuration(); - - let mut alice = [0u8; 32]; - alice[0] = 1; - - let included_head = RuntimeHelper::::run_to_block( - 2, - AccountId::from(alice).into(), - ); - // 1. this message is sent from other global consensus with destination of this Runtime - // relay chain (UMP) - let bridging_message = test_data::simulate_message_exporter_on_bridged_chain::< - BridgedNetwork, - NetworkWithParentCount, - AlwaysLatest, - >((RuntimeNetwork::get(), Here)); - let result = <>::MessageDispatch>::dispatch( - test_data::dispatch_message(expected_lane_id, 1, bridging_message) - ); - assert_eq!( - format!("{:?}", result.dispatch_level_result), - format!("{:?}", XcmBlobMessageDispatchResult::Dispatched) - ); - - // check events - UpwardMessageSent - let mut events = >::events() - .into_iter() - .filter_map(|e| unwrap_cumulus_pallet_parachain_system_event(e.event.encode())); - assert!(events.any(|e| matches!( - e, - cumulus_pallet_parachain_system::Event::UpwardMessageSent { .. } - ))); - - // 2. this message is sent from other global consensus with destination of this Runtime - // sibling parachain (HRMP) - let bridging_message = test_data::simulate_message_exporter_on_bridged_chain::< - BridgedNetwork, - NetworkWithParentCount, - AlwaysLatest, - >((RuntimeNetwork::get(), X1(Parachain(sibling_parachain_id)))); - - // 2.1. WITHOUT opened hrmp channel -> RoutingError - let result = - <>::MessageDispatch>::dispatch( - DispatchMessage { - key: MessageKey { lane_id: expected_lane_id, nonce: 1 }, - data: DispatchMessageData { payload: Ok(bridging_message.clone()) }, - } - ); - assert_eq!( - format!("{:?}", result.dispatch_level_result), - format!( - "{:?}", - XcmBlobMessageDispatchResult::NotDispatched(Some(DispatchBlobError::RoutingError)) - ) - ); - - // check events - no XcmpMessageSent - assert_eq!( - >::events() - .into_iter() - .filter_map(|e| unwrap_cumulus_pallet_xcmp_queue_event(e.event.encode())) - .count(), - 0 - ); - - // 2.1. WITH hrmp channel -> Ok - mock_open_hrmp_channel::( - runtime_para_id.into(), - sibling_parachain_id.into(), - included_head, - &alice, - ); - let result = <>::MessageDispatch>::dispatch( - DispatchMessage { - key: MessageKey { lane_id: expected_lane_id, nonce: 1 }, - data: DispatchMessageData { payload: Ok(bridging_message) }, - } - ); - assert_eq!( - format!("{:?}", result.dispatch_level_result), - format!("{:?}", XcmBlobMessageDispatchResult::Dispatched) - ); - - // check events - XcmpMessageSent - let mut events = >::events() - .into_iter() - .filter_map(|e| unwrap_cumulus_pallet_xcmp_queue_event(e.event.encode())); - assert!( - events.any(|e| matches!(e, cumulus_pallet_xcmp_queue::Event::XcmpMessageSent { .. })) - ); - }) -} - -/// Estimates XCM execution fee for paid `ExportMessage` processing. -pub fn can_calculate_weight_for_paid_export_message_with_reserve_transfer< - Runtime, - XcmConfig, - WeightToFee, ->() -> u128 -where - Runtime: frame_system::Config + pallet_balances::Config, - XcmConfig: xcm_executor::Config, - WeightToFee: frame_support::weights::WeightToFee>, - ::Balance: From + Into, -{ - // data here are not relevant for weighing - let mut xcm = Xcm(vec![ - WithdrawAsset(MultiAssets::from(vec![MultiAsset { - id: Concrete(MultiLocation { parents: 1, interior: Here }), - fun: Fungible(34333299), - }])), - BuyExecution { - fees: MultiAsset { - id: Concrete(MultiLocation { parents: 1, interior: Here }), - fun: Fungible(34333299), - }, - weight_limit: Unlimited, - }, - ExportMessage { - network: Polkadot, - destination: X1(Parachain(1000)), - xcm: Xcm(vec![ - ReserveAssetDeposited(MultiAssets::from(vec![MultiAsset { - id: Concrete(MultiLocation { - parents: 2, - interior: X1(GlobalConsensus(Kusama)), - }), - fun: Fungible(1000000000000), - }])), - ClearOrigin, - BuyExecution { - fees: MultiAsset { - id: Concrete(MultiLocation { - parents: 2, - interior: X1(GlobalConsensus(Kusama)), - }), - fun: Fungible(1000000000000), - }, - weight_limit: Unlimited, - }, - DepositAsset { - assets: Wild(AllCounted(1)), - beneficiary: MultiLocation { - parents: 0, - interior: X1(xcm::latest::prelude::AccountId32 { - network: None, - id: [ - 212, 53, 147, 199, 21, 253, 211, 28, 97, 20, 26, 189, 4, 169, 159, - 214, 130, 44, 133, 88, 133, 76, 205, 227, 154, 86, 132, 231, 165, - 109, 162, 125, - ], - }), - }, - }, - SetTopic([ - 116, 82, 194, 132, 171, 114, 217, 165, 23, 37, 161, 177, 165, 179, 247, 114, - 137, 101, 147, 70, 28, 157, 168, 32, 154, 63, 74, 228, 152, 180, 5, 63, - ]), - ]), - }, - DepositAsset { - assets: Wild(All), - beneficiary: MultiLocation { parents: 1, interior: X1(Parachain(1000)) }, - }, - SetTopic([ - 36, 224, 250, 165, 82, 195, 67, 110, 160, 170, 140, 87, 217, 62, 201, 164, 42, 98, 219, - 157, 124, 105, 248, 25, 131, 218, 199, 36, 109, 173, 100, 122, - ]), - ]); - - // get weight - let weight = XcmConfig::Weigher::weight(&mut xcm); - assert_ok!(weight); - let weight = weight.unwrap(); - // check if sane - let max_expected = Runtime::BlockWeights::get().max_block / 10; - assert!( - weight.all_lte(max_expected), - "calculated weight: {:?}, max_expected: {:?}", - weight, - max_expected - ); - - // check fee, should not be 0 - let estimated_fee = WeightToFee::weight_to_fee(&weight); - assert!(estimated_fee > BalanceOf::::zero()); - - sp_tracing::try_init_simple(); - log::error!( - target: "bridges::estimate", - "Estimate fee: {:?} for `ExportMessage` for runtime: {:?}", - estimated_fee, - Runtime::Version::get(), - ); - - estimated_fee.into() -} diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_grandpa_chain.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_grandpa_chain.rs deleted file mode 100644 index 017ec0fd540..00000000000 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_grandpa_chain.rs +++ /dev/null @@ -1,244 +0,0 @@ -// 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 . - -//! Generating test data for bridges with remote GRANDPA chains. - -use crate::test_data::prepare_inbound_xcm; - -use bp_messages::{ - source_chain::TargetHeaderChain, target_chain::SourceHeaderChain, LaneId, MessageNonce, - UnrewardedRelayersState, -}; -use bp_runtime::{AccountIdOf, BlockNumberOf, HeaderOf, StorageProofSize, UnderlyingChainOf}; -use bp_test_utils::make_default_justification; -use bridge_runtime_common::{ - messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, - BridgedChain as MessageBridgedChain, MessageBridge, ThisChain as MessageThisChain, - }, - messages_generation::{ - encode_all_messages, encode_lane_data, prepare_message_delivery_storage_proof, - prepare_messages_storage_proof, - }, - messages_xcm_extension::XcmAsPlainPayload, -}; -use codec::Encode; -use pallet_bridge_grandpa::{BridgedChain, BridgedHeader}; -use sp_runtime::traits::Header as HeaderT; -use xcm::latest::prelude::*; - -use bp_header_chain::{justification::GrandpaJustification, ChainWithGrandpa}; -use bp_messages::{DeliveredMessages, InboundLaneData, UnrewardedRelayer}; -use bp_runtime::HashOf; -use sp_runtime::DigestItem; - -/// Prepare a batch call with bridged GRANDPA finality and message proof. -pub fn make_complex_relayer_delivery_batch( - bridged_header: BridgedHeader, - bridged_justification: GrandpaJustification>, - message_proof: FromBridgedChainMessagesProof>>, - relayer_id_at_bridged_chain: AccountIdOf>, -) -> pallet_utility::Call -where - Runtime: pallet_bridge_grandpa::Config - + pallet_bridge_messages::Config< - MPI, - InboundPayload = XcmAsPlainPayload, - InboundRelayer = AccountIdOf>, - > + pallet_utility::Config, - GPI: 'static, - MPI: 'static, - >::SourceHeaderChain: SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof>>, - >, - ::RuntimeCall: From> - + From>, -{ - let submit_grandpa = pallet_bridge_grandpa::Call::::submit_finality_proof { - finality_target: Box::new(bridged_header), - justification: bridged_justification, - }; - let submit_message = pallet_bridge_messages::Call::::receive_messages_proof { - relayer_id_at_bridged_chain, - proof: message_proof, - messages_count: 1, - dispatch_weight: Weight::from_parts(1000000000, 0), - }; - pallet_utility::Call::::batch_all { - calls: vec![submit_grandpa.into(), submit_message.into()], - } -} - -/// Prepare a batch call with bridged GRANDPA finality and message delivery proof. -pub fn make_complex_relayer_confirmation_batch( - bridged_header: BridgedHeader, - bridged_justification: GrandpaJustification>, - message_delivery_proof: FromBridgedChainMessagesDeliveryProof< - HashOf>, - >, - relayers_state: UnrewardedRelayersState, -) -> pallet_utility::Call -where - Runtime: pallet_bridge_grandpa::Config - + pallet_bridge_messages::Config - + pallet_utility::Config, - GPI: 'static, - MPI: 'static, - >::TargetHeaderChain: TargetHeaderChain< - XcmAsPlainPayload, - Runtime::AccountId, - MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof< - HashOf>, - >, - >, - ::RuntimeCall: From> - + From>, -{ - let submit_grandpa = pallet_bridge_grandpa::Call::::submit_finality_proof { - finality_target: Box::new(bridged_header), - justification: bridged_justification, - }; - let submit_message_delivery_proof = - pallet_bridge_messages::Call::::receive_messages_delivery_proof { - proof: message_delivery_proof, - relayers_state, - }; - pallet_utility::Call::::batch_all { - calls: vec![submit_grandpa.into(), submit_message_delivery_proof.into()], - } -} - -/// Prepare storage proofs of messages, stored at the (bridged) source GRANDPA chain. -pub fn make_complex_relayer_delivery_proofs( - lane_id: LaneId, - xcm_message: Xcm, - message_nonce: MessageNonce, - message_destination: Junctions, - header_number: BlockNumberOf>, -) -> ( - HeaderOf>, - GrandpaJustification>>, - FromBridgedChainMessagesProof>>, -) -where - MB: MessageBridge, - MessageBridgedChain: Send + Sync + 'static, - UnderlyingChainOf>: ChainWithGrandpa, -{ - let message_payload = prepare_inbound_xcm(xcm_message, message_destination); - let message_size = StorageProofSize::Minimal(message_payload.len() as u32); - // prepare para storage proof containing message - let (state_root, storage_proof) = prepare_messages_storage_proof::( - lane_id, - message_nonce..=message_nonce, - None, - message_size, - message_payload, - encode_all_messages, - encode_lane_data, - ); - - let (header, justification) = make_complex_bridged_grandpa_header_proof::< - MessageBridgedChain, - >(state_root, header_number); - - let message_proof = FromBridgedChainMessagesProof { - bridged_header_hash: header.hash(), - storage_proof, - lane: lane_id, - nonces_start: message_nonce, - nonces_end: message_nonce, - }; - - (header, justification, message_proof) -} - -/// Prepare storage proofs of message confirmations, stored at the (bridged) target GRANDPA chain. -pub fn make_complex_relayer_confirmation_proofs( - lane_id: LaneId, - header_number: BlockNumberOf>, - relayer_id_at_this_chain: AccountIdOf>, - relayers_state: UnrewardedRelayersState, -) -> ( - HeaderOf>, - GrandpaJustification>>, - FromBridgedChainMessagesDeliveryProof>>, -) -where - MB: MessageBridge, - MessageBridgedChain: Send + Sync + 'static, - MessageThisChain: Send + Sync + 'static, - UnderlyingChainOf>: ChainWithGrandpa, -{ - // prepare storage proof containing message delivery proof - let (state_root, storage_proof) = prepare_message_delivery_storage_proof::( - lane_id, - InboundLaneData { - relayers: vec![ - UnrewardedRelayer { - relayer: relayer_id_at_this_chain, - messages: DeliveredMessages::new(1) - }; - relayers_state.unrewarded_relayer_entries as usize - ] - .into(), - last_confirmed_nonce: 1, - }, - StorageProofSize::Minimal(0), - ); - - let (header, justification) = - make_complex_bridged_grandpa_header_proof::(state_root, header_number); - - let message_delivery_proof = FromBridgedChainMessagesDeliveryProof { - bridged_header_hash: header.hash(), - storage_proof, - lane: lane_id, - }; - - (header, justification, message_delivery_proof) -} - -/// Make bridged GRANDPA chain header with given state root. -pub fn make_complex_bridged_grandpa_header_proof( - state_root: HashOf, - header_number: BlockNumberOf, -) -> (HeaderOf, GrandpaJustification>) -where - BridgedChain: ChainWithGrandpa, -{ - let mut header = bp_test_utils::test_header_with_root::>( - header_number.into(), - state_root.into(), - ); - - // to compute proper cost of GRANDPA call, let's add some dummy bytes to header, so that the - // `submit_finality_proof` call size would be close to maximal expected (and refundable) - let extra_bytes_required = maximal_expected_submit_finality_proof_call_size::() - .saturating_sub(header.encoded_size()); - header.digest_mut().push(DigestItem::Other(vec![42; extra_bytes_required])); - - let justification = make_default_justification(&header); - (header, justification) -} - -/// Maximal expected `submit_finality_proof` call size. -pub fn maximal_expected_submit_finality_proof_call_size() -> usize { - bp_header_chain::max_expected_submit_finality_proof_arguments_size::( - false, - BridgedChain::MAX_AUTHORITIES_COUNT * 2 / 3 + 1, - ) as usize -} diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_parachain.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_parachain.rs deleted file mode 100644 index 7ac10aa9e73..00000000000 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_parachain.rs +++ /dev/null @@ -1,326 +0,0 @@ -// 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 . - -//! Generating test data for bridges with remote parachains. - -use super::{from_grandpa_chain::make_complex_bridged_grandpa_header_proof, prepare_inbound_xcm}; - -use bp_messages::{ - source_chain::TargetHeaderChain, target_chain::SourceHeaderChain, LaneId, - UnrewardedRelayersState, Weight, -}; -use bp_runtime::{BlockNumberOf, HeaderOf, Parachain, StorageProofSize, UnderlyingChainOf}; -use bp_test_utils::prepare_parachain_heads_proof; -use bridge_runtime_common::{ - messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, - BridgedChain as MessageBridgedChain, MessageBridge, - }, - messages_generation::{ - encode_all_messages, encode_lane_data, prepare_message_delivery_storage_proof, - prepare_messages_storage_proof, - }, - messages_xcm_extension::XcmAsPlainPayload, -}; -use codec::Encode; -use pallet_bridge_grandpa::BridgedHeader; -use pallet_bridge_parachains::{RelayBlockHash, RelayBlockNumber}; -use sp_runtime::{traits::Header as HeaderT, AccountId32}; -use xcm::latest::prelude::*; - -use bp_header_chain::{justification::GrandpaJustification, ChainWithGrandpa}; -use bp_messages::{DeliveredMessages, InboundLaneData, MessageNonce, UnrewardedRelayer}; -use bp_polkadot_core::parachains::{ParaHash, ParaHead, ParaHeadsProof, ParaId}; -use sp_runtime::SaturatedConversion; - -/// Prepare a batch call with relay finality proof, parachain head proof and message proof. -pub fn make_complex_relayer_delivery_batch( - relay_chain_header: BridgedHeader, - grandpa_justification: GrandpaJustification>, - parachain_heads: Vec<(ParaId, ParaHash)>, - para_heads_proof: ParaHeadsProof, - message_proof: FromBridgedChainMessagesProof, - relayer_id_at_bridged_chain: AccountId32, -) -> pallet_utility::Call where - Runtime:pallet_bridge_grandpa::Config - + pallet_bridge_parachains::Config - + pallet_bridge_messages::Config - + pallet_utility::Config, - GPI: 'static, - PPI: 'static, - MPI: 'static, - ParaHash: From<<>::BridgedChain as bp_runtime::Chain>::Hash>, - <>::BridgedChain as bp_runtime::Chain>::Hash: From, - <>::SourceHeaderChain as SourceHeaderChain>::MessagesProof: - From>, - >::InboundRelayer: From, - ::RuntimeCall: - From> - + From> - + From>, -{ - let relay_chain_header_hash = relay_chain_header.hash(); - let relay_chain_header_number = *relay_chain_header.number(); - let submit_grandpa = pallet_bridge_grandpa::Call::::submit_finality_proof { - finality_target: Box::new(relay_chain_header), - justification: grandpa_justification, - }; - let submit_para_head = pallet_bridge_parachains::Call::::submit_parachain_heads { - at_relay_block: ( - relay_chain_header_number.saturated_into(), - relay_chain_header_hash.into(), - ), - parachains: parachain_heads, - parachain_heads_proof: para_heads_proof, - }; - let submit_message = pallet_bridge_messages::Call::::receive_messages_proof { - relayer_id_at_bridged_chain: relayer_id_at_bridged_chain.into(), - proof: message_proof.into(), - messages_count: 1, - dispatch_weight: Weight::from_parts(1000000000, 0), - }; - pallet_utility::Call::::batch_all { - calls: vec![submit_grandpa.into(), submit_para_head.into(), submit_message.into()], - } -} - -/// Prepare a batch call with relay finality proof, parachain head proof and message delivery -/// proof. -pub fn make_complex_relayer_confirmation_batch( - relay_chain_header: BridgedHeader, - grandpa_justification: GrandpaJustification>, - parachain_heads: Vec<(ParaId, ParaHash)>, - para_heads_proof: ParaHeadsProof, - message_delivery_proof: FromBridgedChainMessagesDeliveryProof, - relayers_state: UnrewardedRelayersState, -) -> pallet_utility::Call -where - Runtime: pallet_bridge_grandpa::Config - + pallet_bridge_parachains::Config - + pallet_bridge_messages::Config - + pallet_utility::Config, - GPI: 'static, - PPI: 'static, - MPI: 'static, - >::BridgedChain: - bp_runtime::Chain + ChainWithGrandpa, - <>::TargetHeaderChain as TargetHeaderChain< - XcmAsPlainPayload, - Runtime::AccountId, - >>::MessagesDeliveryProof: From>, - ::RuntimeCall: From> - + From> - + From>, -{ - let relay_chain_header_hash = relay_chain_header.hash(); - let relay_chain_header_number = *relay_chain_header.number(); - let submit_grandpa = pallet_bridge_grandpa::Call::::submit_finality_proof { - finality_target: Box::new(relay_chain_header), - justification: grandpa_justification, - }; - let submit_para_head = pallet_bridge_parachains::Call::::submit_parachain_heads { - at_relay_block: ( - relay_chain_header_number.saturated_into(), - relay_chain_header_hash.into(), - ), - parachains: parachain_heads, - parachain_heads_proof: para_heads_proof, - }; - let submit_message_delivery_proof = - pallet_bridge_messages::Call::::receive_messages_delivery_proof { - proof: message_delivery_proof.into(), - relayers_state, - }; - pallet_utility::Call::::batch_all { - calls: vec![ - submit_grandpa.into(), - submit_para_head.into(), - submit_message_delivery_proof.into(), - ], - } -} - -/// Prepare storage proofs of messages, stored at the source chain. -pub fn make_complex_relayer_delivery_proofs( - lane_id: LaneId, - xcm_message: Xcm, - message_nonce: MessageNonce, - message_destination: Junctions, - para_header_number: u32, - relay_header_number: u32, - bridged_para_id: u32, -) -> ( - HeaderOf, - GrandpaJustification>, - ParaHead, - Vec<(ParaId, ParaHash)>, - ParaHeadsProof, - FromBridgedChainMessagesProof, -) -where - BridgedRelayChain: - bp_runtime::Chain + ChainWithGrandpa, - MB: MessageBridge, - ::BridgedChain: Send + Sync + 'static, - ::ThisChain: Send + Sync + 'static, - UnderlyingChainOf>: bp_runtime::Chain + Parachain, -{ - let message_payload = prepare_inbound_xcm(xcm_message, message_destination); - let message_size = StorageProofSize::Minimal(message_payload.len() as u32); - // prepare para storage proof containing message - let (para_state_root, para_storage_proof) = prepare_messages_storage_proof::( - lane_id, - message_nonce..=message_nonce, - None, - message_size, - message_payload, - encode_all_messages, - encode_lane_data, - ); - - let (relay_chain_header, justification, bridged_para_head, parachain_heads, para_heads_proof) = - make_complex_bridged_parachain_heads_proof::( - para_state_root, - para_header_number, - relay_header_number, - bridged_para_id, - ); - - let message_proof = FromBridgedChainMessagesProof { - bridged_header_hash: bridged_para_head.hash(), - storage_proof: para_storage_proof, - lane: lane_id, - nonces_start: message_nonce, - nonces_end: message_nonce, - }; - - ( - relay_chain_header, - justification, - bridged_para_head, - parachain_heads, - para_heads_proof, - message_proof, - ) -} - -/// Prepare storage proofs of message confirmations, stored at the target parachain. -pub fn make_complex_relayer_confirmation_proofs( - lane_id: LaneId, - para_header_number: u32, - relay_header_number: u32, - bridged_para_id: u32, - relayer_id_at_this_chain: AccountId32, - relayers_state: UnrewardedRelayersState, -) -> ( - HeaderOf, - GrandpaJustification>, - ParaHead, - Vec<(ParaId, ParaHash)>, - ParaHeadsProof, - FromBridgedChainMessagesDeliveryProof, -) -where - BridgedRelayChain: - bp_runtime::Chain + ChainWithGrandpa, - MB: MessageBridge, - ::BridgedChain: Send + Sync + 'static, - ::ThisChain: Send + Sync + 'static, - <::ThisChain as bp_runtime::Chain>::AccountId: From, - UnderlyingChainOf>: bp_runtime::Chain + Parachain, -{ - // prepare para storage proof containing message delivery proof - let (para_state_root, para_storage_proof) = prepare_message_delivery_storage_proof::( - lane_id, - InboundLaneData { - relayers: vec![ - UnrewardedRelayer { - relayer: relayer_id_at_this_chain.into(), - messages: DeliveredMessages::new(1) - }; - relayers_state.unrewarded_relayer_entries as usize - ] - .into(), - last_confirmed_nonce: 1, - }, - StorageProofSize::Minimal(0), - ); - - let (relay_chain_header, justification, bridged_para_head, parachain_heads, para_heads_proof) = - make_complex_bridged_parachain_heads_proof::( - para_state_root, - para_header_number, - relay_header_number, - bridged_para_id, - ); - - let message_delivery_proof = FromBridgedChainMessagesDeliveryProof { - bridged_header_hash: bridged_para_head.hash(), - storage_proof: para_storage_proof, - lane: lane_id, - }; - - ( - relay_chain_header, - justification, - bridged_para_head, - parachain_heads, - para_heads_proof, - message_delivery_proof, - ) -} - -/// Make bridged parachain header with given state root and relay header that is finalizing it. -pub fn make_complex_bridged_parachain_heads_proof( - para_state_root: ParaHash, - para_header_number: u32, - relay_header_number: BlockNumberOf, - bridged_para_id: u32, -) -> ( - HeaderOf, - GrandpaJustification>, - ParaHead, - Vec<(ParaId, ParaHash)>, - ParaHeadsProof, -) -where - BridgedRelayChain: - bp_runtime::Chain + ChainWithGrandpa, - MB: MessageBridge, - ::BridgedChain: Send + Sync + 'static, - ::ThisChain: Send + Sync + 'static, - UnderlyingChainOf>: bp_runtime::Chain + Parachain, -{ - let bridged_para_head = ParaHead( - bp_test_utils::test_header_with_root::>( - para_header_number.into(), - para_state_root, - ) - .encode(), - ); - let (relay_state_root, para_heads_proof, parachain_heads) = - prepare_parachain_heads_proof::>(vec![( - bridged_para_id, - bridged_para_head.clone(), - )]); - assert_eq!(bridged_para_head.hash(), parachain_heads[0].1); - - let (relay_chain_header, justification) = make_complex_bridged_grandpa_header_proof::< - BridgedRelayChain, - >(relay_state_root, relay_header_number); - - (relay_chain_header, justification, bridged_para_head, parachain_heads, para_heads_proof) -} 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 deleted file mode 100644 index f905d21b187..00000000000 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/mod.rs +++ /dev/null @@ -1,144 +0,0 @@ -// 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 . - -//! Generating test data, used by all tests. - -pub mod from_grandpa_chain; -pub mod from_parachain; - -use bp_messages::{ - target_chain::{DispatchMessage, DispatchMessageData}, - LaneId, MessageKey, -}; -use codec::Encode; -use frame_support::traits::Get; -use pallet_bridge_grandpa::BridgedHeader; -use xcm::latest::prelude::*; - -use bp_messages::MessageNonce; -use bp_runtime::BasicOperatingMode; -use bp_test_utils::authority_list; -use xcm::GetVersion; -use xcm_builder::{HaulBlob, HaulBlobError, HaulBlobExporter}; -use xcm_executor::traits::{validate_export, ExportXcm}; - -pub fn prepare_inbound_xcm( - xcm_message: Xcm, - destination: InteriorMultiLocation, -) -> Vec { - let location = xcm::VersionedInteriorMultiLocation::V3(destination); - let xcm = xcm::VersionedXcm::::V3(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 - // to the storage) - (location, xcm).encode().encode() -} - -/// Helper that creates InitializationData mock data, that can be used to initialize bridge -/// GRANDPA pallet -pub fn initialization_data< - Runtime: pallet_bridge_grandpa::Config, - GrandpaPalletInstance: 'static, ->( - block_number: u32, -) -> bp_header_chain::InitializationData> { - bp_header_chain::InitializationData { - header: Box::new(bp_test_utils::test_header(block_number.into())), - authority_list: authority_list(), - set_id: 1, - operating_mode: BasicOperatingMode::Normal, - } -} - -/// Dummy xcm -pub(crate) fn dummy_xcm() -> Xcm<()> { - vec![Trap(42)].into() -} - -pub(crate) fn dispatch_message( - lane_id: LaneId, - nonce: MessageNonce, - payload: Vec, -) -> DispatchMessage> { - DispatchMessage { - key: MessageKey { lane_id, nonce }, - data: DispatchMessageData { payload: Ok(payload) }, - } -} - -/// Macro used for simulate_export_message and capturing bytes -macro_rules! grab_haul_blob ( - ($name:ident, $grabbed_payload:ident) => { - std::thread_local! { - static $grabbed_payload: std::cell::RefCell>> = std::cell::RefCell::new(None); - } - - struct $name; - impl HaulBlob for $name { - fn haul_blob(blob: Vec) -> Result<(), HaulBlobError>{ - $grabbed_payload.with(|rm| *rm.borrow_mut() = Some(blob)); - Ok(()) - } - } - } -); - -/// Simulates `HaulBlobExporter` and all its wrapping and captures generated plain bytes, -/// which are transferred over bridge. -pub(crate) fn simulate_message_exporter_on_bridged_chain< - SourceNetwork: Get, - DestinationNetwork: Get, - DestinationVersion: GetVersion, ->( - (destination_network, destination_junctions): (NetworkId, Junctions), -) -> Vec { - grab_haul_blob!(GrabbingHaulBlob, GRABBED_HAUL_BLOB_PAYLOAD); - - // lets pretend that some parachain on bridged chain exported the message - let universal_source_on_bridged_chain = - X2(GlobalConsensus(SourceNetwork::get()), Parachain(5678)); - let channel = 1_u32; - - // simulate XCM message export - let (ticket, fee) = validate_export::< - HaulBlobExporter, - >( - destination_network, - channel, - universal_source_on_bridged_chain, - destination_junctions, - dummy_xcm(), - ) - .expect("validate_export to pass"); - log::info!( - target: "simulate_message_exporter_on_bridged_chain", - "HaulBlobExporter::validate fee: {:?}", - fee - ); - let xcm_hash = - HaulBlobExporter::::deliver( - ticket, - ) - .expect("deliver to pass"); - log::info!( - target: "simulate_message_exporter_on_bridged_chain", - "HaulBlobExporter::deliver xcm_hash: {:?}", - xcm_hash - ); - - GRABBED_HAUL_BLOB_PAYLOAD.with(|r| r.take().expect("Encoded message should be here")) -} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/Cargo.toml b/cumulus/parachains/runtimes/collectives/collectives-polkadot/Cargo.toml new file mode 100644 index 00000000000..ca83b84cd8f --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/Cargo.toml @@ -0,0 +1,226 @@ +[package] +name = "collectives-polkadot-runtime" +version = "1.0.0" +authors.workspace = true +edition.workspace = true +description = "Polkadot Collectives Parachain Runtime" +license = "Apache-2.0" + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } +hex-literal = { version = "0.4.1" } +log = { version = "0.4.20", default-features = false } +scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } +smallvec = "1.11.0" + +# 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-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-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-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} + +# Polkadot +pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false} +polkadot-core-primitives = { path = "../../../../../polkadot/core-primitives", 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} + +# 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-dmp-queue = { path = "../../../../pallets/dmp-queue", default-features = false } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } +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 } +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 } + +[build-dependencies] +substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } + +[dev-dependencies] +sp-io = { path = "../../../../../substrate/primitives/io", default-features = false} + +[features] +default = [ "std" ] +runtime-benchmarks = [ + "cumulus-pallet-dmp-queue/runtime-benchmarks", + "cumulus-pallet-parachain-system/runtime-benchmarks", + "cumulus-pallet-session-benchmarking/runtime-benchmarks", + "cumulus-pallet-xcmp-queue/runtime-benchmarks", + "cumulus-primitives-core/runtime-benchmarks", + "cumulus-primitives-utility/runtime-benchmarks", + "frame-benchmarking/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "frame-system-benchmarking/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-alliance/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", + "pallet-collator-selection/runtime-benchmarks", + "pallet-collective-content/runtime-benchmarks", + "pallet-collective/runtime-benchmarks", + "pallet-core-fellowship/runtime-benchmarks", + "pallet-message-queue/runtime-benchmarks", + "pallet-multisig/runtime-benchmarks", + "pallet-preimage/runtime-benchmarks", + "pallet-proxy/runtime-benchmarks", + "pallet-ranked-collective/runtime-benchmarks", + "pallet-referenda/runtime-benchmarks", + "pallet-salary/runtime-benchmarks", + "pallet-scheduler/runtime-benchmarks", + "pallet-timestamp/runtime-benchmarks", + "pallet-utility/runtime-benchmarks", + "pallet-xcm/runtime-benchmarks", + "parachains-common/runtime-benchmarks", + "polkadot-parachain-primitives/runtime-benchmarks", + "polkadot-runtime-common/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", + "xcm-executor/runtime-benchmarks", +] +try-runtime = [ + "cumulus-pallet-aura-ext/try-runtime", + "cumulus-pallet-dmp-queue/try-runtime", + "cumulus-pallet-parachain-system/try-runtime", + "cumulus-pallet-xcm/try-runtime", + "cumulus-pallet-xcmp-queue/try-runtime", + "frame-executive/try-runtime", + "frame-support/try-runtime", + "frame-system/try-runtime", + "frame-try-runtime/try-runtime", + "pallet-alliance/try-runtime", + "pallet-aura/try-runtime", + "pallet-authorship/try-runtime", + "pallet-balances/try-runtime", + "pallet-collator-selection/try-runtime", + "pallet-collective-content/try-runtime", + "pallet-collective/try-runtime", + "pallet-core-fellowship/try-runtime", + "pallet-message-queue/try-runtime", + "pallet-multisig/try-runtime", + "pallet-preimage/try-runtime", + "pallet-proxy/try-runtime", + "pallet-ranked-collective/try-runtime", + "pallet-referenda/try-runtime", + "pallet-salary/try-runtime", + "pallet-scheduler/try-runtime", + "pallet-session/try-runtime", + "pallet-timestamp/try-runtime", + "pallet-transaction-payment/try-runtime", + "pallet-utility/try-runtime", + "pallet-xcm/try-runtime", + "parachain-info/try-runtime", + "polkadot-runtime-common/try-runtime", + "sp-runtime/try-runtime", +] +std = [ + "codec/std", + "cumulus-pallet-aura-ext/std", + "cumulus-pallet-dmp-queue/std", + "cumulus-pallet-parachain-system/std", + "cumulus-pallet-session-benchmarking/std", + "cumulus-pallet-xcm/std", + "cumulus-pallet-xcmp-queue/std", + "cumulus-primitives-core/std", + "cumulus-primitives-utility/std", + "frame-benchmarking?/std", + "frame-executive/std", + "frame-support/std", + "frame-system-benchmarking?/std", + "frame-system-rpc-runtime-api/std", + "frame-system/std", + "frame-try-runtime?/std", + "log/std", + "pallet-alliance/std", + "pallet-aura/std", + "pallet-authorship/std", + "pallet-balances/std", + "pallet-collator-selection/std", + "pallet-collective-content/std", + "pallet-collective/std", + "pallet-core-fellowship/std", + "pallet-message-queue/std", + "pallet-multisig/std", + "pallet-preimage/std", + "pallet-proxy/std", + "pallet-ranked-collective/std", + "pallet-referenda/std", + "pallet-salary/std", + "pallet-scheduler/std", + "pallet-session/std", + "pallet-timestamp/std", + "pallet-transaction-payment-rpc-runtime-api/std", + "pallet-transaction-payment/std", + "pallet-utility/std", + "pallet-xcm/std", + "parachain-info/std", + "parachains-common/std", + "polkadot-core-primitives/std", + "polkadot-parachain-primitives/std", + "polkadot-runtime-common/std", + "scale-info/std", + "sp-api/std", + "sp-arithmetic/std", + "sp-block-builder/std", + "sp-consensus-aura/std", + "sp-core/std", + "sp-genesis-builder/std", + "sp-inherents/std", + "sp-io/std", + "sp-offchain/std", + "sp-runtime/std", + "sp-session/std", + "sp-std/std", + "sp-storage/std", + "sp-transaction-pool/std", + "sp-version/std", + "substrate-wasm-builder", + "xcm-builder/std", + "xcm-executor/std", + "xcm/std", +] + +experimental = [ "pallet-aura/experimental" ] diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/build.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/build.rs new file mode 100644 index 00000000000..60f8a125129 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/build.rs @@ -0,0 +1,26 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#[cfg(feature = "std")] +fn main() { + substrate_wasm_builder::WasmBuilder::new() + .with_current_project() + .export_heap_base() + .import_memory() + .build() +} + +#[cfg(not(feature = "std"))] +fn main() {} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/mod.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/mod.rs new file mode 100644 index 00000000000..b055ffc8abf --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/mod.rs @@ -0,0 +1,255 @@ +// 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. + +//! The Ambassador Program. +//! +//! The module defines the following on-chain functionality of the Ambassador Program: +//! +//! - Managed set of program members, where every member has a [rank](ranks) +//! (via [AmbassadorCollective](pallet_ranked_collective)). +//! - Referendum functionality for the program members to propose, vote on, and execute +//! proposals on behalf of the members of a certain [rank](Origin) +//! (via [AmbassadorReferenda](pallet_referenda)). +//! - Managed content (charter, announcements) (via [pallet_collective_content]). +//! - Promotion and demotion periods, register of members' activity, and rank based salaries +//! (via [AmbassadorCore](pallet_core_fellowship)). +//! - Members' salaries (via [AmbassadorSalary](pallet_salary), requiring a member to be +//! imported or inducted into [AmbassadorCore](pallet_core_fellowship)). + +pub mod origins; +mod tracks; + +use super::*; +use crate::xcm_config::{DotAssetHub, FellowshipAdminBodyId}; +use frame_support::traits::{EitherOf, MapSuccess, TryMapSuccess}; +pub use origins::pallet_origins as pallet_ambassador_origins; +use origins::pallet_origins::{ + EnsureAmbassadorsVoice, EnsureAmbassadorsVoiceFrom, EnsureHeadAmbassadorsVoice, Origin, +}; +use parachains_common::polkadot::account; +use sp_core::ConstU128; +use sp_runtime::traits::{CheckedReduceBy, ConstU16, ConvertToValue, Replace}; +use xcm::prelude::*; +use xcm_builder::{AliasesIntoAccountId32, PayOverXcm}; + +/// The Ambassador Program's member ranks. +pub mod ranks { + use pallet_ranked_collective::Rank; + + #[allow(dead_code)] + pub const CANDIDATE: Rank = 0; + pub const AMBASSADOR_TIER_1: Rank = 1; + pub const AMBASSADOR_TIER_2: Rank = 2; + pub const SENIOR_AMBASSADOR_TIER_3: Rank = 3; + pub const SENIOR_AMBASSADOR_TIER_4: Rank = 4; + pub const HEAD_AMBASSADOR_TIER_5: Rank = 5; + pub const HEAD_AMBASSADOR_TIER_6: Rank = 6; + pub const HEAD_AMBASSADOR_TIER_7: Rank = 7; + pub const MASTER_AMBASSADOR_TIER_8: Rank = 8; + pub const MASTER_AMBASSADOR_TIER_9: Rank = 9; +} + +impl pallet_ambassador_origins::Config for Runtime {} + +pub type AmbassadorCollectiveInstance = pallet_ranked_collective::Instance2; + +/// Demotion is by any of: +/// - Root can promote arbitrarily. +/// - the FellowshipAdmin origin (i.e. token holder referendum); +/// - a senior members vote by the rank two above the current rank. +pub type DemoteOrigin = EitherOf< + frame_system::EnsureRootWithSuccess>, + EitherOf< + MapSuccess< + EnsureXcm>, + Replace>, + >, + TryMapSuccess< + EnsureAmbassadorsVoiceFrom>, + CheckedReduceBy>, + >, + >, +>; + +/// Promotion and approval (rank-retention) is by any of: +/// - Root can promote arbitrarily. +/// - the FellowshipAdmin origin (i.e. token holder referendum); +/// - a senior members vote by the rank two above the new/current rank. +/// - a member of rank `5` or above can add a candidate (rank `0`). +pub type PromoteOrigin = EitherOf< + DemoteOrigin, + TryMapSuccess< + pallet_ranked_collective::EnsureMember< + Runtime, + AmbassadorCollectiveInstance, + { ranks::HEAD_AMBASSADOR_TIER_5 }, + >, + Replace>, + >, +>; + +impl pallet_ranked_collective::Config for Runtime { + type WeightInfo = weights::pallet_ranked_collective_ambassador_collective::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type PromoteOrigin = PromoteOrigin; + type DemoteOrigin = DemoteOrigin; + type Polls = AmbassadorReferenda; + type MinRankOfClass = sp_runtime::traits::Identity; + type VoteWeight = pallet_ranked_collective::Linear; +} + +parameter_types! { + pub const AlarmInterval: BlockNumber = 1; + pub const SubmissionDeposit: Balance = 0; + pub const UndecidingTimeout: BlockNumber = 7 * DAYS; + // The Ambassador Referenda pallet account, used as a temporarily place to deposit a slashed imbalance before teleport to the treasury. + pub AmbassadorPalletAccount: AccountId = account::AMBASSADOR_REFERENDA_PALLET_ID.into_account_truncating(); +} + +pub type AmbassadorReferendaInstance = pallet_referenda::Instance2; + +impl pallet_referenda::Config for Runtime { + type WeightInfo = weights::pallet_referenda_ambassador_referenda::WeightInfo; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type Scheduler = Scheduler; + type Currency = Balances; + // A proposal can be submitted by a member of the Ambassador Program of + // [ranks::SENIOR_AMBASSADOR_TIER_3] rank or higher. + type SubmitOrigin = pallet_ranked_collective::EnsureMember< + Runtime, + AmbassadorCollectiveInstance, + { ranks::SENIOR_AMBASSADOR_TIER_3 }, + >; + type CancelOrigin = EitherOf, EnsureHeadAmbassadorsVoice>; + type KillOrigin = EitherOf, EnsureHeadAmbassadorsVoice>; + type Slash = ToParentTreasury; + type Votes = pallet_ranked_collective::Votes; + type Tally = pallet_ranked_collective::TallyOf; + type SubmissionDeposit = SubmissionDeposit; + type MaxQueued = ConstU32<20>; + type UndecidingTimeout = UndecidingTimeout; + type AlarmInterval = AlarmInterval; + type Tracks = tracks::TracksInfo; + type Preimages = Preimage; +} + +parameter_types! { + pub const AnnouncementLifetime: BlockNumber = 180 * DAYS; + pub const MaxAnnouncements: u32 = 50; +} + +pub type AmbassadorContentInstance = pallet_collective_content::Instance1; + +impl pallet_collective_content::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type CharterOrigin = EitherOf, EnsureHeadAmbassadorsVoice>; + type AnnouncementLifetime = AnnouncementLifetime; + // An announcement can be submitted by a Senior Ambassador member or an ambassador plurality + // voice taken via referendum. + type AnnouncementOrigin = EitherOfDiverse< + pallet_ranked_collective::EnsureMember< + Runtime, + AmbassadorCollectiveInstance, + { ranks::SENIOR_AMBASSADOR_TIER_3 }, + >, + EnsureAmbassadorsVoice, + >; + type MaxAnnouncements = MaxAnnouncements; + type WeightInfo = weights::pallet_collective_content::WeightInfo; +} + +pub type AmbassadorCoreInstance = pallet_core_fellowship::Instance2; + +impl pallet_core_fellowship::Config for Runtime { + type WeightInfo = weights::pallet_core_fellowship_ambassador_core::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type Members = pallet_ranked_collective::Pallet; + type Balance = Balance; + // Parameters are set by any of: + // - Root; + // - the FellowshipAdmin origin (i.e. token holder referendum); + // - a vote among all Head Ambassadors. + type ParamsOrigin = EitherOfDiverse< + EnsureXcm>, + EnsureHeadAmbassadorsVoice, + >; + // Induction (creating a candidate) is by any of: + // - Root; + // - the FellowshipAdmin origin (i.e. token holder referendum); + // - a single Head Ambassador; + // - a vote among all senior members. + type InductOrigin = EitherOfDiverse< + EnsureXcm>, + EitherOfDiverse< + pallet_ranked_collective::EnsureMember< + Runtime, + AmbassadorCollectiveInstance, + { ranks::HEAD_AMBASSADOR_TIER_5 }, + >, + EnsureAmbassadorsVoiceFrom>, + >, + >; + type ApproveOrigin = PromoteOrigin; + type PromoteOrigin = PromoteOrigin; + type EvidenceSize = ConstU32<65536>; +} + +pub type AmbassadorSalaryInstance = pallet_salary::Instance2; + +parameter_types! { + // The interior location on AssetHub for the paying account. This is the Ambassador Salary + // pallet instance (which sits at index 74). This sovereign account will need funding. + pub AmbassadorSalaryLocation: InteriorMultiLocation = PalletInstance(74).into(); +} + +/// [`PayOverXcm`] setup to pay the Ambassador salary on the AssetHub in DOT. +pub type AmbassadorSalaryPaymaster = PayOverXcm< + AmbassadorSalaryLocation, + crate::xcm_config::XcmRouter, + crate::PolkadotXcm, + ConstU32<{ 6 * HOURS }>, + AccountId, + (), + ConvertToValue, + AliasesIntoAccountId32<(), AccountId>, +>; + +impl pallet_salary::Config for Runtime { + type WeightInfo = weights::pallet_salary_ambassador_salary::WeightInfo; + type RuntimeEvent = RuntimeEvent; + + #[cfg(not(feature = "runtime-benchmarks"))] + type Paymaster = AmbassadorSalaryPaymaster; + #[cfg(feature = "runtime-benchmarks")] + type Paymaster = crate::impls::benchmarks::PayWithEnsure< + AmbassadorSalaryPaymaster, + crate::impls::benchmarks::OpenHrmpChannel>, + >; + type Members = pallet_ranked_collective::Pallet; + + #[cfg(not(feature = "runtime-benchmarks"))] + type Salary = pallet_core_fellowship::Pallet; + #[cfg(feature = "runtime-benchmarks")] + type Salary = frame_support::traits::tokens::ConvertRank< + crate::impls::benchmarks::RankToSalary, + >; + // 15 days to register for a salary payment. + type RegistrationPeriod = ConstU32<{ 15 * DAYS }>; + // 15 days to claim the salary payment. + type PayoutPeriod = ConstU32<{ 15 * DAYS }>; + // Total monthly salary budget. + type Budget = ConstU128<{ 10_000 * DOLLARS }>; +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/origins.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/origins.rs new file mode 100644 index 00000000000..3ce8a6b9e5d --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/origins.rs @@ -0,0 +1,135 @@ +// 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. + +//! The Ambassador Program's origins. + +#[frame_support::pallet] +pub mod pallet_origins { + use crate::ambassador::ranks; + use frame_support::pallet_prelude::*; + use pallet_ranked_collective::Rank; + + #[pallet::pallet] + pub struct Pallet(PhantomData); + + /// The pallet configuration trait. + #[pallet::config] + pub trait Config: frame_system::Config {} + + #[derive(PartialEq, Eq, Clone, MaxEncodedLen, Encode, Decode, TypeInfo, RuntimeDebug)] + #[pallet::origin] + pub enum Origin { + /// Plurality voice of the [ranks::AMBASSADOR_TIER_1] members or above given via + /// referendum. + Ambassadors, + /// Plurality voice of the [ranks::AMBASSADOR_TIER_2] members or above given via + /// referendum. + AmbassadorsTier2, + /// Plurality voice of the [ranks::SENIOR_AMBASSADOR_TIER_3] members or above given via + /// referendum. + SeniorAmbassadors, + /// Plurality voice of the [ranks::SENIOR_AMBASSADOR_TIER_4] members or above given via + /// referendum. + SeniorAmbassadorsTier4, + /// Plurality voice of the [ranks::HEAD_AMBASSADOR_TIER_5] members or above given via + /// referendum. + HeadAmbassadors, + /// Plurality voice of the [ranks::HEAD_AMBASSADOR_TIER_6] members or above given via + /// referendum. + HeadAmbassadorsTier6, + /// Plurality voice of the [ranks::HEAD_AMBASSADOR_TIER_7] members or above given via + /// referendum. + HeadAmbassadorsTier7, + /// Plurality voice of the [ranks::MASTER_AMBASSADOR_TIER_8] members or above given via + /// referendum. + MasterAmbassadors, + /// Plurality voice of the [ranks::MASTER_AMBASSADOR_TIER_9] members or above given via + /// referendum. + MasterAmbassadorsTier9, + } + + impl Origin { + /// Returns the rank that the origin `self` speaks for, or `None` if it doesn't speak for + /// any. + pub fn as_voice(&self) -> Option { + Some(match &self { + Origin::Ambassadors => ranks::AMBASSADOR_TIER_1, + Origin::AmbassadorsTier2 => ranks::AMBASSADOR_TIER_2, + Origin::SeniorAmbassadors => ranks::SENIOR_AMBASSADOR_TIER_3, + Origin::SeniorAmbassadorsTier4 => ranks::SENIOR_AMBASSADOR_TIER_4, + Origin::HeadAmbassadors => ranks::HEAD_AMBASSADOR_TIER_5, + Origin::HeadAmbassadorsTier6 => ranks::HEAD_AMBASSADOR_TIER_6, + Origin::HeadAmbassadorsTier7 => ranks::HEAD_AMBASSADOR_TIER_7, + Origin::MasterAmbassadors => ranks::MASTER_AMBASSADOR_TIER_8, + Origin::MasterAmbassadorsTier9 => ranks::MASTER_AMBASSADOR_TIER_9, + }) + } + } + + /// Implementation of the [EnsureOrigin] trait for the [Origin::HeadAmbassadors] origin. + pub struct EnsureHeadAmbassadorsVoice; + impl> + From> EnsureOrigin for EnsureHeadAmbassadorsVoice { + type Success = (); + fn try_origin(o: O) -> Result { + o.into().and_then(|o| match o { + Origin::HeadAmbassadors => Ok(()), + r => Err(O::from(r)), + }) + } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin() -> Result { + Ok(O::from(Origin::HeadAmbassadors)) + } + } + + /// Implementation of the [EnsureOrigin] trait for the plurality voice [Origin]s + /// from a given rank `R` with the success result of the corresponding [Rank]. + pub struct EnsureAmbassadorsVoiceFrom(PhantomData); + impl, O: Into> + From> EnsureOrigin + for EnsureAmbassadorsVoiceFrom + { + type Success = Rank; + fn try_origin(o: O) -> Result { + o.into().and_then(|o| match Origin::as_voice(&o) { + Some(r) if r >= R::get() => Ok(r), + _ => Err(O::from(o)), + }) + } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin() -> Result { + ranks::MASTER_AMBASSADOR_TIER_9 + .ge(&R::get()) + .then(|| O::from(Origin::MasterAmbassadorsTier9)) + .ok_or(()) + } + } + + /// Implementation of the [EnsureOrigin] trait for the plurality voice [Origin]s with the + /// success result of the corresponding [Rank]. + pub struct EnsureAmbassadorsVoice; + impl> + From> EnsureOrigin for EnsureAmbassadorsVoice { + type Success = Rank; + fn try_origin(o: O) -> Result { + o.into().and_then(|o| Origin::as_voice(&o).ok_or(O::from(o))) + } + + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin() -> Result { + Ok(O::from(Origin::MasterAmbassadorsTier9)) + } + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/tracks.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/tracks.rs new file mode 100644 index 00000000000..073d8e6ee36 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/ambassador/tracks.rs @@ -0,0 +1,282 @@ +// 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. + +//! The Ambassador Program's referenda voting tracks. + +use super::Origin; +use crate::{Balance, BlockNumber, RuntimeOrigin, DAYS, DOLLARS, HOURS}; +use sp_runtime::Perbill; + +/// Referendum `TrackId` type. +pub type TrackId = u16; + +/// Referendum track IDs. +pub mod constants { + use super::TrackId; + + pub const AMBASSADOR_TIER_1: TrackId = 1; + pub const AMBASSADOR_TIER_2: TrackId = 2; + pub const SENIOR_AMBASSADOR_TIER_3: TrackId = 3; + pub const SENIOR_AMBASSADOR_TIER_4: TrackId = 4; + pub const HEAD_AMBASSADOR_TIER_5: TrackId = 5; + pub const HEAD_AMBASSADOR_TIER_6: TrackId = 6; + pub const HEAD_AMBASSADOR_TIER_7: TrackId = 7; + pub const MASTER_AMBASSADOR_TIER_8: TrackId = 8; + pub const MASTER_AMBASSADOR_TIER_9: TrackId = 9; +} + +/// The type implementing the [`pallet_referenda::TracksInfo`] trait for referenda pallet. +pub struct TracksInfo; + +/// Information on the voting tracks. +impl pallet_referenda::TracksInfo for TracksInfo { + type Id = TrackId; + + type RuntimeOrigin = ::PalletsOrigin; + + /// Return the array of available tracks and their information. + fn tracks() -> &'static [(Self::Id, pallet_referenda::TrackInfo)] { + static DATA: [(TrackId, pallet_referenda::TrackInfo); 9] = [ + ( + constants::AMBASSADOR_TIER_1, + pallet_referenda::TrackInfo { + name: "ambassador tier 1", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 24 * HOURS, + decision_period: 7 * DAYS, + confirm_period: 24 * HOURS, + min_enactment_period: 1 * HOURS, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(10), + ceil: Perbill::from_percent(50), + }, + }, + ), + ( + constants::AMBASSADOR_TIER_2, + pallet_referenda::TrackInfo { + name: "ambassador tier 2", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 24 * HOURS, + decision_period: 7 * DAYS, + confirm_period: 24 * HOURS, + min_enactment_period: 1 * HOURS, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(10), + ceil: Perbill::from_percent(50), + }, + }, + ), + ( + constants::SENIOR_AMBASSADOR_TIER_3, + pallet_referenda::TrackInfo { + name: "senior ambassador tier 3", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 24 * HOURS, + decision_period: 7 * DAYS, + confirm_period: 24 * HOURS, + min_enactment_period: 1 * HOURS, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(10), + ceil: Perbill::from_percent(50), + }, + }, + ), + ( + constants::SENIOR_AMBASSADOR_TIER_4, + pallet_referenda::TrackInfo { + name: "senior ambassador tier 4", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 24 * HOURS, + decision_period: 7 * DAYS, + confirm_period: 24 * HOURS, + min_enactment_period: 1 * HOURS, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(10), + ceil: Perbill::from_percent(50), + }, + }, + ), + ( + constants::HEAD_AMBASSADOR_TIER_5, + pallet_referenda::TrackInfo { + name: "head ambassador tier 5", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 24 * HOURS, + decision_period: 7 * DAYS, + confirm_period: 24 * HOURS, + min_enactment_period: 1 * HOURS, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(10), + ceil: Perbill::from_percent(50), + }, + }, + ), + ( + constants::HEAD_AMBASSADOR_TIER_6, + pallet_referenda::TrackInfo { + name: "head ambassador tier 6", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 24 * HOURS, + decision_period: 7 * DAYS, + confirm_period: 24 * HOURS, + min_enactment_period: 1 * HOURS, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(10), + ceil: Perbill::from_percent(50), + }, + }, + ), + ( + constants::HEAD_AMBASSADOR_TIER_7, + pallet_referenda::TrackInfo { + name: "head ambassador tier 7", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 24 * HOURS, + decision_period: 7 * DAYS, + confirm_period: 24 * HOURS, + min_enactment_period: 1 * HOURS, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(10), + ceil: Perbill::from_percent(50), + }, + }, + ), + ( + constants::MASTER_AMBASSADOR_TIER_8, + pallet_referenda::TrackInfo { + name: "master ambassador tier 8", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 24 * HOURS, + decision_period: 7 * DAYS, + confirm_period: 24 * HOURS, + min_enactment_period: 1 * HOURS, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(10), + ceil: Perbill::from_percent(50), + }, + }, + ), + ( + constants::MASTER_AMBASSADOR_TIER_9, + pallet_referenda::TrackInfo { + name: "master ambassador tier 9", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 24 * HOURS, + decision_period: 7 * DAYS, + confirm_period: 24 * HOURS, + min_enactment_period: 1 * HOURS, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(10), + ceil: Perbill::from_percent(50), + }, + }, + ), + ]; + &DATA[..] + } + + /// Determine the voting track for the given `origin`. + fn track_for(id: &Self::RuntimeOrigin) -> Result { + #[cfg(feature = "runtime-benchmarks")] + { + // For benchmarks, we enable a root origin. + // It is important that this is not available in production! + let root: Self::RuntimeOrigin = frame_system::RawOrigin::Root.into(); + if &root == id { + return Ok(constants::MASTER_AMBASSADOR_TIER_9) + } + } + + match Origin::try_from(id.clone()) { + Ok(Origin::Ambassadors) => Ok(constants::AMBASSADOR_TIER_1), + Ok(Origin::AmbassadorsTier2) => Ok(constants::AMBASSADOR_TIER_2), + Ok(Origin::SeniorAmbassadors) => Ok(constants::SENIOR_AMBASSADOR_TIER_3), + Ok(Origin::SeniorAmbassadorsTier4) => Ok(constants::SENIOR_AMBASSADOR_TIER_4), + Ok(Origin::HeadAmbassadors) => Ok(constants::HEAD_AMBASSADOR_TIER_5), + Ok(Origin::HeadAmbassadorsTier6) => Ok(constants::HEAD_AMBASSADOR_TIER_6), + Ok(Origin::HeadAmbassadorsTier7) => Ok(constants::HEAD_AMBASSADOR_TIER_7), + Ok(Origin::MasterAmbassadors) => Ok(constants::MASTER_AMBASSADOR_TIER_8), + Ok(Origin::MasterAmbassadorsTier9) => Ok(constants::MASTER_AMBASSADOR_TIER_9), + _ => Err(()), + } + } +} + +// implements [`frame_support::traits::Get`] for [`TracksInfo`] +pallet_referenda::impl_tracksinfo_get!(TracksInfo, Balance, BlockNumber); diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/migration.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/migration.rs new file mode 100644 index 00000000000..9350d03a2c9 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/migration.rs @@ -0,0 +1,261 @@ +// 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 . + +//! Migrations. + +use frame_support::{pallet_prelude::*, traits::OnRuntimeUpgrade, weights::Weight}; +use log; + +/// Initial import of the Kusama Technical Fellowship. +pub(crate) mod import_kusama_fellowship { + use super::*; + use frame_support::{parameter_types, traits::RankedMembers}; + use pallet_ranked_collective::{Config, MemberCount, Pallet as RankedCollective, Rank}; + #[cfg(feature = "try-runtime")] + use sp_std::vec::Vec; + + const TARGET: &str = "runtime::migration::import_fellowship"; + + parameter_types! { + // The Fellowship addresses from Kusama state. + pub const FellowshipAddresses: [(Rank, [u8; 32]); 47] = [ + (6, hex_literal::hex!("f0673d30606ee26672707e4fd2bc8b58d3becb7aba2d5f60add64abb5fea4710"),), + (6, hex_literal::hex!("3c235e80e35082b668682531b9b062fda39a46edb94f884d9122d86885fd5f1b"),), + (6, hex_literal::hex!("7628a5be63c4d3c8dbb96c2904b1a9682e02831a1af836c7efc808020b92fa63"),), + (5, hex_literal::hex!("9c84f75e0b1b92f6b003bde6212a8b2c9b776f3720f942b33fed8709f103a268"),), + (5, hex_literal::hex!("bc64065524532ed9e805fb0d39a5c0199216b52871168e5e4d0ab612f8797d61"),), + (5, hex_literal::hex!("2e1884c53071526483b14004e894415f02b55fc2e2aef8e1df8ccf7ce5bd5570"),), + (5, hex_literal::hex!("5c5062779d44ea2ab0469e155b8cf3e004fce71b3b3d38263cd9fa9478f12f28"),), + (4, hex_literal::hex!("4adf51a47b72795366d52285e329229c836ea7bbfe139dbe8fa0700c4f86fc56"),), + (4, hex_literal::hex!("1c90e3dabd3fd0f6bc648045018f78fcee8fe24122c22d8d2a14e9905073d10f"),), + (4, hex_literal::hex!("8e851ed992228f2268ee8c614fe6075d3800060ae14098e0309413a0a81c4470"),), + (3, hex_literal::hex!("720d807d46b941703ffe0278e8b173dc6738c5af8af812ceffc90c69390bbf1f"),), + (3, hex_literal::hex!("c4965f7fe7be8174717a24ffddf684986d122c7e293ddf875cdf9700a07b6812"),), + (3, hex_literal::hex!("beae5bcad1a8c156291b7ddf46b38b0c61a6aaacebd57b21c75627bfe7f9ab71"),), + (3, hex_literal::hex!("ccd87fa65729f7bdaa8305581a7a499aa24c118e83f5714152c0e22617c6fc63"),), + (3, hex_literal::hex!("e0f0f94962fc0a8c1a0f0527dc8e592c67939c46c903b6016cc0a8515da0044d"),), + (3, hex_literal::hex!("984e16482c99cfad1436111e321a86d87d0fac203bf64538f888e45d793b5413"),), + (3, hex_literal::hex!("44a3efb5bfa9023d4ef27b7d31d76f531b4d7772b1679b7fb32b6263ac39100e"),), + (2, hex_literal::hex!("2eba9a39dbfdd5f3cba964355d45e27319f0271023c0353d97dc6df2401b0e3d"),), + (2, hex_literal::hex!("ba3e9b87792bcfcc237fa8181185b8883c77f3e24f45e4a92ab31d07a4703520"),), + (2, hex_literal::hex!("9e6eb74b0a6b39de36fb58d1fab20bc2b3fea96023ce5a47941c20480d99f92e"),), + (2, hex_literal::hex!("ee3d9d8c48ee88dce78fd7bafe3ce2052900eb465085b9324d4f5da26b145f2b"),), + (2, hex_literal::hex!("d8290537d6e31fe1ff165eaa62b63f6f3556dcc720b0d3a6d7eab96275617304"),), + (2, hex_literal::hex!("5a090c88f0438b46b451026597cee760a7bac9d396c9c7b529b68fb78aec5f43"),), + (2, hex_literal::hex!("18d30040a8245c5ff17afc9a8169d7d0771fe7ab4135a64a022c254117340720"),), + (1, hex_literal::hex!("b4f7f03bebc56ebe96bc52ea5ed3159d45a0ce3a8d7f082983c33ef133274747"),), + (1, hex_literal::hex!("caafae0aaa6333fcf4dc193146945fe8e4da74aa6c16d481eef0ca35b8279d73"),), + (1, hex_literal::hex!("a66e0f4e1a121cc83fddf3096e8ec8c9e9c85989f276e39e951fb0e4a5398763"),), + (1, hex_literal::hex!("f65f3cade8f68e8f34c6266b0d37e58a754059ca96816e964f98e17c79505073"),), + (1, hex_literal::hex!("8c232c91ef2a9983ba65c4b75bb86fcbae4d909900ea8aa06c3644ca1161db48"),), + (1, hex_literal::hex!("78e4813814891bd48bc745b79254a978833d41fbe0f387df93cd87eae2468926"),), + (1, hex_literal::hex!("d44824ac8d1edecca67639ca74d208bd2044a10e67c9677e288080191e3fec13"),), + (1, hex_literal::hex!("585e982d74da4f4290d20a73800cfd705cf59e1f5880aaee5506b5eaaf544f49"),), + (1, hex_literal::hex!("d851f44a6f0d0d2f3439a51f2f75f66f4ea1a8e6c33c32f9af75fc188afb7546"),), + (1, hex_literal::hex!("dca89b135d1a6aee0a498610a70eeaed056727c8a4d220da245842e540a54a74"),), + (1, hex_literal::hex!("aa91fc0201f26b713a018669bcd269babf25368eee2493323b1ce0190a178a27"),), + (1, hex_literal::hex!("dc20836f2e4b88c1858d1e3f918e7358043b4a8abcd2874e74d91d26c52eca2a"),), + (1, hex_literal::hex!("145d6c503d0cf97f4c7725ca773741bd02e1760bfb52e021af5a9f2de283012c"),), + (1, hex_literal::hex!("307183930b2264c5165f4a210a99520c5f1672b0413d57769fabc19e6866fb25"),), + (1, hex_literal::hex!("6201961514cf5ad87f1c4dd0c392ee28231f805f77975147bf2c33bd671b9822"),), + (1, hex_literal::hex!("c6f57237cd4abfbeed99171495fc784e45a9d5d2814d435de40de00991a73c06"),), + (1, hex_literal::hex!("c1df5c7e8ca56037450c58734326ebe34aec8f7d1928322a12164856365fea73"),), + (1, hex_literal::hex!("12c039004da5e1e846aae808277098c719cef1f4985aed00161a42ac4f0e002f"),), + (1, hex_literal::hex!("7460ac178015d2a7c289bb68ef9fdaac071596ab4425c276a0040aaac7055566"),), + (1, hex_literal::hex!("eec4bd650a277342ebba0954ac786df2623bd6a9d6d3e69b484482336c549f79"),), + (1, hex_literal::hex!("e287c7494655d636a846f5c3347ad2cb3c462a8d46e0832be70fcc0ab54ee62d"),), + (1, hex_literal::hex!("82bf733f44a840f0a5c1935a002d4e541d81298fad6d1da8124073485983860e"),), + (1, hex_literal::hex!("d5b89078eed9b9dfec5c7d8413bac0b720bad3bd4078c4d8c894325713192502"),), + ]; + } + + /// Implements `OnRuntimeUpgrade` trait. + pub struct Migration(PhantomData<(T, I)>); + + impl, I: 'static> OnRuntimeUpgrade for Migration + where + ::AccountId: From<[u8; 32]>, + { + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + let onchain_version = RankedCollective::::on_chain_storage_version(); + ensure!(onchain_version == 0, "the storage version must be 0."); + let member_count = MemberCount::::get(0); + ensure!(member_count == 0, "the collective must be uninitialized."); + + Ok(Vec::new()) + } + + fn on_runtime_upgrade() -> Weight { + let current_version = RankedCollective::::current_storage_version(); + let onchain_version = RankedCollective::::on_chain_storage_version(); + let mut weight = T::DbWeight::get().reads(1); + log::info!( + target: TARGET, + "running migration with current storage version {:?} / onchain {:?}.", + current_version, + onchain_version + ); + if onchain_version != 0 { + log::warn!( + target: TARGET, + "unsupported storage version, skipping import_fellowship migration." + ); + return weight + } + let member_count = MemberCount::::get(0); + weight.saturating_accrue(T::DbWeight::get().reads(1)); + if member_count != 0 { + log::warn!( + target: TARGET, + "the collective already initialized, skipping import_fellowship migration." + ); + return weight + } + + for (rank, account_id32) in FellowshipAddresses::get() { + let who: T::AccountId = account_id32.into(); + let _ = as RankedMembers>::induct(&who); + for _ in 0..rank { + let _ = as RankedMembers>::promote(&who); + // 1 write to `IdToIndex` and `IndexToId` per member on each rank. + weight.saturating_accrue(T::DbWeight::get().writes(2)); + } + // 1 write to `IdToIndex` and `IndexToId` per member on each rank. + weight.saturating_accrue(T::DbWeight::get().writes(2)); + // 1 read and 1 write to `Members` and `MemberCount` per member. + weight.saturating_accrue(T::DbWeight::get().reads_writes(2, 2)); + } + weight + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(_state: Vec) -> Result<(), sp_runtime::TryRuntimeError> { + ensure!(MemberCount::::get(0) == 47, "invalid members count at rank 0."); + ensure!(MemberCount::::get(1) == 47, "invalid members count at rank 1."); + ensure!(MemberCount::::get(2) == 24, "invalid members count at rank 2."); + ensure!(MemberCount::::get(3) == 17, "invalid members count at rank 3."); + ensure!(MemberCount::::get(4) == 10, "invalid members count at rank 4."); + ensure!(MemberCount::::get(5) == 7, "invalid members count at rank 5."); + ensure!(MemberCount::::get(6) == 3, "invalid members count at rank 6."); + ensure!(MemberCount::::get(7) == 0, "invalid members count at rank 7."); + Ok(()) + } + } +} + +#[cfg(test)] +pub mod tests { + use super::import_kusama_fellowship::FellowshipAddresses; + use crate::{FellowshipCollectiveInstance as Fellowship, Runtime, System}; + use frame_support::traits::OnRuntimeUpgrade; + use pallet_ranked_collective::Rank; + use parachains_common::AccountId; + use sp_core::crypto::Ss58Codec; + use sp_runtime::{AccountId32, BuildStorage}; + + #[test] + fn check_fellowship_addresses() { + let fellowship_addresses = FellowshipAddresses::get(); + let kusama_fellowship_ss58: [(Rank, _); 47] = [ + (6, "16SDAKg9N6kKAbhgDyxBXdHEwpwHUHs2CNEiLNGeZV55qHna"), /* proof https://kusama.subscan.io/extrinsic/16832707-4 */ + (6, "12MrP337azmkTdfCUKe5XLnSQrbgEKqqfZ4PQC7CZTJKAWR3"), /* proof https://kusama.subscan.io/extrinsic/16967809-2 */ + (6, "FFFF3gBSSDFSvK2HBq4qgLH75DHqXWPHeCnR1BSksAMacBs"), + (5, "G7YVCdxZb8JLpAm9WMnJdNuojNT84AzU62zmvx5P1FMNtg2"), + (5, "15G1iXDLgFyfnJ51FKq1ts44TduMyUtekvzQi9my4hgYt2hs"), /* proof https://kusama.subscan.io/extrinsic/16917610-2 */ + (5, "Dcm1BqR4N7nHuV43TXdET7pNibt1Nzm42FggPHpxKRven53"), + (5, "1363HWTPzDrzAQ6ChFiMU6mP4b6jmQid2ae55JQcKtZnpLGv"), /* proof https://kusama.subscan.io/extrinsic/16961180-2 */ + (4, "EGVQCe73TpFyAZx5uKfE1222XfkT3BSKozjgcqzLBnc5eYo"), + (4, "1eTPAR2TuqLyidmPT9rMmuycHVm9s9czu78sePqg2KHMDrE"), /* proof https://kusama.subscan.io/extrinsic/16921712-3 */ + (4, "14DsLzVyTUTDMm2eP3czwPbH53KgqnQRp3CJJZS9GR7yxGDP"), /* proof https://kusama.subscan.io/extrinsic/16917519-2 */ + (3, "13aYUFHB3umoPoxBEAHSv451iR3RpsNi3t5yBZjX2trCtTp6"), /* proof https://kusama.subscan.io/extrinsic/16917832-3 */ + (3, "H25aCspunTUqAt4D1gC776vKZ8FX3MvQJ3Jde6qDXPQaFxk"), + (3, "GtLQoW4ZqcjExMPq6qB22bYc6NaX1yMzRuGWpSRiHqnzRb9"), + (3, "15db5ksZgmhWE9U8MDq4wLKUdFivLVBybztWV8nmaJvv3NU1"), /* proof https://kusama.subscan.io/extrinsic/16876631-2 */ + (3, "HfFpz4QUxfbocHudf8UU7cMgHqkHpf855Me5X846PZAsAYE"), + (3, "14ShUZUYUR35RBZW6uVVt1zXDxmSQddkeDdXf1JkMA6P721N"), /* proof https://kusama.subscan.io/extrinsic/16918890-8 */ + (3, "12YzxR5TvGzfMVZNnhAJ5Hwi5zExpRWMKv2MuMwZTrddvgoi"), /* proof https://kusama.subscan.io/extrinsic/16924324-3 */ + (2, "Ddb9puChKMHq4gM6o47E551wAmaNeu6kHngX1jzNNqAw782"), + (2, "15DCWHQknBjc5YPFoVj8Pn2KoqrqYywJJ95BYNYJ4Fj3NLqz"), /* proof https://kusama.subscan.io/extrinsic/16834952-2 */ + (2, "14ajTQdrtCA8wZmC4PgD8Y1B2Gy8L4Z3oi2fodxq9FehcFrM"), /* proof https://kusama.subscan.io/extrinsic/16944257-2 */ + (2, "HxhDbS3grLurk1dhDgPiuDaRowHY1xHCU8Vu8on3fdg85tx"), + (2, "HTk3eccL7WBkiyxz1gBcqQRghsJigoDMD7mnQaz1UAbMpQV"), + (2, "EcNWrSPSDcVBRymwr26kk4JVFg92PdoU5Xwp87W2FgFSt9c"), + (2, "D8sM6vKjWaeKy2zCPYWGkLLbWdUtWQrXBTQqr4dSYnVQo21"), + (1, "GfbnnEgRU94n9ed4RFZ6Z9dBAWs5obykigJSwXKU9hsT2uU"), + (1, "HA5NtttvyZsxo4wGxGoJJSMaWtdEFZAuGUMFHVWD7fgenPv"), + (1, "14mDeKZ7qp9hqBjjDg51c8BFrf9o69om8piSSRwj2fT5Yb1i"), /* proof https://kusama.subscan.io/extrinsic/16919020-4 */ + (1, "16a357f5Sxab3V2ne4emGQvqJaCLeYpTMx3TCjnQhmJQ71DX"), /* proof https://kusama.subscan.io/extrinsic/16836396-5 */ + (1, "14Ak9rrF6RKHHoLLRUYMnzcvvi1t8E1yAMa7tcmiwUfaqzYK"), /* proof https://kusama.subscan.io/extrinsic/16921990-3 */ + (1, "FJq9JpA9P7EXbmfsN9YiewJaDbQyL6vQyksGtJvzfbn6zf8"), + (1, "15oLanodWWweiZJSoDTEBtrX7oGfq6e8ct5y5E6fVRDPhUgj"), /* proof https://kusama.subscan.io/extrinsic/16876423-7 */ + (1, "EaBqDJJNsZmYdQ4xn1vomPJVNh7fjA6UztZeEjn7ZzdeT7V"), + (1, "HTxCvXKVvUZ7PQq175kCRRLu7XkGfTfErrdNXr1ZuuwVZWv"), + (1, "HZe91A6a1xqbKaw6ofx3GFepJjhVXHrwHEwn6YUDDFphpX9"), + (1, "GRy2P3kBEzSHCbmDJfquku1cyUyhZaAqojRcNE4A4U3MnLd"), + (1, "HYwiBo7Mcv7uUDg4MUoKm2fxzv4dMLAtmmNfzHV8qcQJpAE"), + (1, "1ThiBx5DDxFhoD9GY6tz5Fp4Y7Xn1xfLmDddcoFQghDvvjg"), /* proof https://kusama.subscan.io/extrinsic/16918130-2 */ + (1, "DfqY6XQUSETTszBQ1juocTcG9iiDoXhvq1CoVadBSUqTGJS"), + (1, "EnpgVWGGQVrFdSB2qeXRVdtccV6U5ZscNELBoERbkFD8Wi6"), + (1, "H5BuqCmucJhUUuvjAzPazeVwVCtUSXVQdc5Dnx2q5zD7rVn"), + (1, "GxX7S1pTDdeaGUjpEPPF2we6tgHDhbatFG25pVmVFtGHLH6"), + (1, "CzuUtvKhZNZBjyAXeYviaRXwrLhVrsupJ9PrWmdq7BJTjGR"), + (1, "FCunn2Rx8JqfT5g6noUKKazph4jLDba5rUee7o3ZmJ362Ju"), + (1, "HyPMjWRHCpJS7x2SZ2R6M2XG5ZiCiZag4U4r7gBHRsE5mTc"), + (1, "1682A5hxfiS1Kn1jrUnMYv14T9EuEnsgnBbujGfYbeEbSK3w"), /* proof https://kusama.subscan.io/extrinsic/16919077-2 */ + (1, "13xS6fK6MHjApLnjdX7TJYw1niZmiXasSN91bNtiXQjgEtNx"), /* proof https://kusama.subscan.io/extrinsic/16918212-7 */ + (1, "15qE2YAQCs5Y962RHE7RzNjQxU6Pei21nhkkSM9Sojq1hHps"), /* https://kusama.subscan.io/extrinsic/17352973-2 */ + ]; + + for (index, val) in kusama_fellowship_ss58.iter().enumerate() { + let account: AccountId32 = ::from_string(val.1).unwrap(); + let account32: [u8; 32] = account.clone().into(); + assert_eq!( + fellowship_addresses[index].0, kusama_fellowship_ss58[index].0, + "ranks must be equal." + ); + assert_eq!(fellowship_addresses[index].1, account32, "accounts must be equal."); + } + } + + #[test] + fn test_fellowship_import() { + use super::import_kusama_fellowship::Migration; + use pallet_ranked_collective::{IdToIndex, IndexToId, MemberCount, MemberRecord, Members}; + + let t = frame_system::GenesisConfig::::default().build_storage().unwrap(); + let mut ext = sp_io::TestExternalities::new(t); + ext.execute_with(|| System::set_block_number(1)); + ext.execute_with(|| { + assert_eq!(MemberCount::::get(0), 0); + Migration::::on_runtime_upgrade(); + assert_eq!(MemberCount::::get(0), 47); + assert_eq!(MemberCount::::get(6), 3); + assert_eq!(MemberCount::::get(7), 0); + for (rank, account_id32) in FellowshipAddresses::get() { + let who = ::AccountId::from(account_id32); + assert!(IdToIndex::::get(0, &who).is_some()); + assert!(IdToIndex::::get(rank + 1, &who).is_none()); + let index = IdToIndex::::get(rank, &who).unwrap(); + assert_eq!(IndexToId::::get(rank, index).unwrap(), who); + assert_eq!( + Members::::get(&who).unwrap(), + MemberRecord::new(rank) + ); + } + }); + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/mod.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/mod.rs new file mode 100644 index 00000000000..2a2757ea5ce --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/mod.rs @@ -0,0 +1,239 @@ +// 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 . + +//! The Polkadot Technical Fellowship. + +pub(crate) mod migration; +mod origins; +mod tracks; +use crate::{ + impls::ToParentTreasury, + weights, + xcm_config::{FellowshipAdminBodyId, UsdtAssetHub}, + AccountId, Balance, Balances, FellowshipReferenda, GovernanceLocation, PolkadotTreasuryAccount, + Preimage, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, Scheduler, DAYS, +}; +use frame_support::{ + parameter_types, + traits::{EitherOf, EitherOfDiverse, MapSuccess, OriginTrait, TryWithMorphedArg}, +}; +use frame_system::EnsureRootWithSuccess; +pub use origins::{ + pallet_origins as pallet_fellowship_origins, Architects, EnsureCanPromoteTo, EnsureCanRetainAt, + EnsureFellowship, Fellows, Masters, Members, ToVoice, +}; +use pallet_ranked_collective::EnsureOfRank; +use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; +use parachains_common::{polkadot::account, HOURS}; +use sp_core::{ConstU128, ConstU32}; +use sp_runtime::traits::{AccountIdConversion, ConstU16, ConvertToValue, Replace, TakeFirst}; +use xcm_builder::{AliasesIntoAccountId32, PayOverXcm}; + +#[cfg(feature = "runtime-benchmarks")] +use crate::impls::benchmarks::{OpenHrmpChannel, PayWithEnsure}; + +/// The Fellowship members' ranks. +pub mod ranks { + use pallet_ranked_collective::Rank; + + pub const DAN_1: Rank = 1; // aka Members. + pub const DAN_2: Rank = 2; + pub const DAN_3: Rank = 3; // aka Fellows. + pub const DAN_4: Rank = 4; // aka Architects. + pub const DAN_5: Rank = 5; + pub const DAN_6: Rank = 6; + pub const DAN_7: Rank = 7; // aka Masters. + pub const DAN_8: Rank = 8; + pub const DAN_9: Rank = 9; +} + +parameter_types! { + // Referenda pallet account, used to temporarily deposit slashed imbalance before teleporting. + pub ReferendaPalletAccount: AccountId = account::REFERENDA_PALLET_ID.into_account_truncating(); +} + +impl pallet_fellowship_origins::Config for Runtime {} + +pub type FellowshipReferendaInstance = pallet_referenda::Instance1; + +impl pallet_referenda::Config for Runtime { + type WeightInfo = weights::pallet_referenda_fellowship_referenda::WeightInfo; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type Scheduler = Scheduler; + type Currency = Balances; + // Fellows can submit proposals. + type SubmitOrigin = EitherOf< + pallet_ranked_collective::EnsureMember, + MapSuccess< + TryWithMorphedArg< + RuntimeOrigin, + ::PalletsOrigin, + ToVoice, + EnsureOfRank, + (AccountId, u16), + >, + TakeFirst, + >, + >; + type CancelOrigin = Architects; + type KillOrigin = Masters; + type Slash = ToParentTreasury; + type Votes = pallet_ranked_collective::Votes; + type Tally = pallet_ranked_collective::TallyOf; + type SubmissionDeposit = ConstU128<0>; + type MaxQueued = ConstU32<100>; + type UndecidingTimeout = ConstU32<{ 7 * DAYS }>; + type AlarmInterval = ConstU32<1>; + type Tracks = tracks::TracksInfo; + type Preimages = Preimage; +} + +pub type FellowshipCollectiveInstance = pallet_ranked_collective::Instance1; + +impl pallet_ranked_collective::Config for Runtime { + type WeightInfo = weights::pallet_ranked_collective_fellowship_collective::WeightInfo; + type RuntimeEvent = RuntimeEvent; + + #[cfg(not(feature = "runtime-benchmarks"))] + // Promotions and the induction of new members are serviced by `FellowshipCore` pallet instance. + type PromoteOrigin = frame_system::EnsureNever; + #[cfg(feature = "runtime-benchmarks")] + // The maximum value of `u16` set as a success value for the root to ensure the benchmarks will + // pass. + type PromoteOrigin = EnsureRootWithSuccess>; + + // Demotion is by any of: + // - Root can demote arbitrarily. + // - the FellowshipAdmin origin (i.e. token holder referendum); + // + // The maximum value of `u16` set as a success value for the root to ensure the benchmarks will + // pass. + type DemoteOrigin = EitherOf< + EnsureRootWithSuccess>, + MapSuccess< + EnsureXcm>, + Replace>, + >, + >; + type Polls = FellowshipReferenda; + type MinRankOfClass = tracks::MinRankOfClass; + type VoteWeight = pallet_ranked_collective::Geometric; +} + +pub type FellowshipCoreInstance = pallet_core_fellowship::Instance1; + +impl pallet_core_fellowship::Config for Runtime { + type WeightInfo = weights::pallet_core_fellowship_fellowship_core::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type Members = pallet_ranked_collective::Pallet; + type Balance = Balance; + // Parameters are set by any of: + // - Root; + // - the FellowshipAdmin origin (i.e. token holder referendum); + // - a vote among all Fellows. + type ParamsOrigin = EitherOfDiverse< + EnsureXcm>, + Fellows, + >; + // Induction (creating a candidate) is by any of: + // - Root; + // - the FellowshipAdmin origin (i.e. token holder referendum); + // - a single Fellow; + // - a vote among all Members. + type InductOrigin = EitherOfDiverse< + EnsureXcm>, + EitherOfDiverse< + pallet_ranked_collective::EnsureMember< + Runtime, + FellowshipCollectiveInstance, + { ranks::DAN_3 }, + >, + Members, + >, + >; + // Approval (rank-retention) of a Member's current rank is by any of: + // - Root; + // - the FellowshipAdmin origin (i.e. token holder referendum); + // - a vote by the rank two above the current rank for all retention up to the Master rank. + type ApproveOrigin = EitherOf< + MapSuccess< + EnsureXcm>, + Replace>, + >, + EnsureCanRetainAt, + >; + // Promotion is by any of: + // - Root can promote arbitrarily. + // - the FellowshipAdmin origin (i.e. token holder referendum); + // - a vote by the rank two above the new rank for all promotions up to the Master rank. + type PromoteOrigin = EitherOf< + MapSuccess< + EnsureXcm>, + Replace>, + >, + EnsureCanPromoteTo, + >; + type EvidenceSize = ConstU32<65536>; +} + +pub type FellowshipSalaryInstance = pallet_salary::Instance1; + +use xcm::prelude::*; + +parameter_types! { + // The interior location on AssetHub for the paying account. This is the Fellowship Salary + // pallet instance (which sits at index 64). This sovereign account will need funding. + pub Interior: InteriorMultiLocation = PalletInstance(64).into(); +} + +const USDT_UNITS: u128 = 1_000_000; + +/// [`PayOverXcm`] setup to pay the Fellowship salary on the AssetHub in USDT. +pub type FellowshipSalaryPaymaster = PayOverXcm< + Interior, + crate::xcm_config::XcmRouter, + crate::PolkadotXcm, + ConstU32<{ 6 * HOURS }>, + AccountId, + (), + ConvertToValue, + AliasesIntoAccountId32<(), AccountId>, +>; + +impl pallet_salary::Config for Runtime { + type WeightInfo = weights::pallet_salary_fellowship_salary::WeightInfo; + type RuntimeEvent = RuntimeEvent; + + #[cfg(not(feature = "runtime-benchmarks"))] + type Paymaster = FellowshipSalaryPaymaster; + #[cfg(feature = "runtime-benchmarks")] + type Paymaster = PayWithEnsure>>; + type Members = pallet_ranked_collective::Pallet; + + #[cfg(not(feature = "runtime-benchmarks"))] + type Salary = pallet_core_fellowship::Pallet; + #[cfg(feature = "runtime-benchmarks")] + type Salary = frame_support::traits::tokens::ConvertRank< + crate::impls::benchmarks::RankToSalary, + >; + // 15 days to register for a salary payment. + type RegistrationPeriod = ConstU32<{ 15 * DAYS }>; + // 15 days to claim the salary payment. + type PayoutPeriod = ConstU32<{ 15 * DAYS }>; + // Total monthly salary budget. + type Budget = ConstU128<{ 100_000 * USDT_UNITS }>; +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/origins.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/origins.rs new file mode 100644 index 00000000000..5ed2c19f79e --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/origins.rs @@ -0,0 +1,247 @@ +// 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 . + +//! Fellowship custom origins. + +use super::ranks; +pub use pallet_origins::*; + +#[frame_support::pallet] +pub mod pallet_origins { + use super::ranks; + use frame_support::pallet_prelude::*; + use pallet_ranked_collective::Rank; + + #[pallet::config] + pub trait Config: frame_system::Config {} + + #[pallet::pallet] + pub struct Pallet(_); + + #[derive(PartialEq, Eq, Clone, MaxEncodedLen, Encode, Decode, TypeInfo, RuntimeDebug)] + #[pallet::origin] + pub enum Origin { + /// Origin aggregated through weighted votes of those with rank 1 or above; `Success` is 1. + /// Aka the "voice" of all Members. + Members, + /// Origin aggregated through weighted votes of those with rank 2 or above; `Success` is 2. + /// Aka the "voice" of members at least II Dan. + Fellowship2Dan, + /// Origin aggregated through weighted votes of those with rank 3 or above; `Success` is 3. + /// Aka the "voice" of all Fellows. + Fellows, + /// Origin aggregated through weighted votes of those with rank 4 or above; `Success` is 4. + /// Aka the "voice" of members at least IV Dan. + Architects, + /// Origin aggregated through weighted votes of those with rank 5 or above; `Success` is 5. + /// Aka the "voice" of members at least V Dan. + Fellowship5Dan, + /// Origin aggregated through weighted votes of those with rank 6 or above; `Success` is 6. + /// Aka the "voice" of members at least VI Dan. + Fellowship6Dan, + /// Origin aggregated through weighted votes of those with rank 7 or above; `Success` is 7. + /// Aka the "voice" of all Masters. + Masters, + /// Origin aggregated through weighted votes of those with rank 8 or above; `Success` is 8. + /// Aka the "voice" of members at least VIII Dan. + Fellowship8Dan, + /// Origin aggregated through weighted votes of those with rank 9 or above; `Success` is 9. + /// Aka the "voice" of members at least IX Dan. + Fellowship9Dan, + + /// Origin aggregated through weighted votes of those with rank 3 or above when voting on + /// a fortnight-long track; `Success` is 1. + RetainAt1Dan, + /// Origin aggregated through weighted votes of those with rank 4 or above when voting on + /// a fortnight-long track; `Success` is 2. + RetainAt2Dan, + /// Origin aggregated through weighted votes of those with rank 5 or above when voting on + /// a fortnight-long track; `Success` is 3. + RetainAt3Dan, + /// Origin aggregated through weighted votes of those with rank 6 or above when voting on + /// a fortnight-long track; `Success` is 4. + RetainAt4Dan, + /// Origin aggregated through weighted votes of those with rank 7 or above when voting on + /// a fortnight-long track; `Success` is 5. + RetainAt5Dan, + /// Origin aggregated through weighted votes of those with rank 8 or above when voting on + /// a fortnight-long track; `Success` is 6. + RetainAt6Dan, + + /// Origin aggregated through weighted votes of those with rank 3 or above when voting on + /// a month-long track; `Success` is 1. + PromoteTo1Dan, + /// Origin aggregated through weighted votes of those with rank 4 or above when voting on + /// a month-long track; `Success` is 2. + PromoteTo2Dan, + /// Origin aggregated through weighted votes of those with rank 5 or above when voting on + /// a month-long track; `Success` is 3. + PromoteTo3Dan, + /// Origin aggregated through weighted votes of those with rank 6 or above when voting on + /// a month-long track; `Success` is 4. + PromoteTo4Dan, + /// Origin aggregated through weighted votes of those with rank 7 or above when voting on + /// a month-long track; `Success` is 5. + PromoteTo5Dan, + /// Origin aggregated through weighted votes of those with rank 8 or above when voting on + /// a month-long track; `Success` is 6. + PromoteTo6Dan, + } + + impl Origin { + /// Returns the rank that the origin `self` speaks for, or `None` if it doesn't speak for + /// any. + /// + /// `Some` will be returned only for the first 9 elements of [Origin]. + pub fn as_voice(&self) -> Option { + Some(match &self { + Origin::Members => ranks::DAN_1, + Origin::Fellowship2Dan => ranks::DAN_2, + Origin::Fellows => ranks::DAN_3, + Origin::Architects => ranks::DAN_4, + Origin::Fellowship5Dan => ranks::DAN_5, + Origin::Fellowship6Dan => ranks::DAN_6, + Origin::Masters => ranks::DAN_7, + Origin::Fellowship8Dan => ranks::DAN_8, + Origin::Fellowship9Dan => ranks::DAN_9, + _ => return None, + }) + } + } + + /// A `TryMorph` implementation which is designed to convert an aggregate `RuntimeOrigin` + /// value into the Fellowship voice it represents if it is a Fellowship pallet origin an + /// appropriate variant. See also [Origin::as_voice]. + pub struct ToVoice; + impl<'a, O: 'a + TryInto<&'a Origin>> sp_runtime::traits::TryMorph for ToVoice { + type Outcome = pallet_ranked_collective::Rank; + fn try_morph(o: O) -> Result { + o.try_into().ok().and_then(Origin::as_voice).ok_or(()) + } + } + + macro_rules! decl_unit_ensures { + ( $name:ident: $success_type:ty = $success:expr ) => { + pub struct $name; + impl> + From> + EnsureOrigin for $name + { + type Success = $success_type; + fn try_origin(o: O) -> Result { + o.into().and_then(|o| match o { + Origin::$name => Ok($success), + r => Err(O::from(r)), + }) + } + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin() -> Result { + Ok(O::from(Origin::$name)) + } + } + }; + ( $name:ident ) => { decl_unit_ensures! { $name : () = () } }; + ( $name:ident: $success_type:ty = $success:expr, $( $rest:tt )* ) => { + decl_unit_ensures! { $name: $success_type = $success } + decl_unit_ensures! { $( $rest )* } + }; + ( $name:ident, $( $rest:tt )* ) => { + decl_unit_ensures! { $name } + decl_unit_ensures! { $( $rest )* } + }; + () => {} + } + decl_unit_ensures!( + Members: Rank = ranks::DAN_1, + Fellows: Rank = ranks::DAN_3, + Architects: Rank = ranks::DAN_4, + Masters: Rank = ranks::DAN_7, + ); + + macro_rules! decl_ensure { + ( + $vis:vis type $name:ident: EnsureOrigin { + $( $item:ident = $success:expr, )* + } + ) => { + $vis struct $name; + impl> + From> + EnsureOrigin for $name + { + type Success = $success_type; + fn try_origin(o: O) -> Result { + o.into().and_then(|o| match o { + $( + Origin::$item => Ok($success), + )* + r => Err(O::from(r)), + }) + } + #[cfg(feature = "runtime-benchmarks")] + fn try_successful_origin() -> Result { + // By convention the more privileged origins go later, so for greatest chance + // of success, we want the last one. + let _result: Result = Err(()); + $( + let _result: Result = Ok(O::from(Origin::$item)); + )* + _result + } + } + } + } + + // Fellowship origin indicating weighted voting from at least the rank of `Success` on a + // week-long track. + decl_ensure! { + pub type EnsureFellowship: EnsureOrigin { + Members = ranks::DAN_1, + Fellowship2Dan = ranks::DAN_2, + Fellows = ranks::DAN_3, + Architects = ranks::DAN_4, + Fellowship5Dan = ranks::DAN_5, + Fellowship6Dan = ranks::DAN_6, + Masters = ranks::DAN_7, + Fellowship8Dan = ranks::DAN_8, + Fellowship9Dan = ranks::DAN_9, + } + } + + // Fellowship origin indicating weighted voting from at least the rank of `Success + 2` on + // a fortnight-long track; needed for Fellowship retention voting. + decl_ensure! { + pub type EnsureCanRetainAt: EnsureOrigin { + RetainAt1Dan = ranks::DAN_1, + RetainAt2Dan = ranks::DAN_2, + RetainAt3Dan = ranks::DAN_3, + RetainAt4Dan = ranks::DAN_4, + RetainAt5Dan = ranks::DAN_5, + RetainAt6Dan = ranks::DAN_6, + } + } + + // Fellowship origin indicating weighted voting from at least the rank of `Success + 2` on + // a month-long track; needed for Fellowship promotion voting. + decl_ensure! { + pub type EnsureCanPromoteTo: EnsureOrigin { + PromoteTo1Dan = ranks::DAN_1, + PromoteTo2Dan = ranks::DAN_2, + PromoteTo3Dan = ranks::DAN_3, + PromoteTo4Dan = ranks::DAN_4, + PromoteTo5Dan = ranks::DAN_5, + PromoteTo6Dan = ranks::DAN_6, + } + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/tracks.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/tracks.rs new file mode 100644 index 00000000000..f4ba4e05ec1 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/fellowship/tracks.rs @@ -0,0 +1,532 @@ +// 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 . + +//! Track configurations for Fellowship. + +use crate::{Balance, BlockNumber, RuntimeOrigin, DAYS, DOLLARS, HOURS, MINUTES}; +use pallet_ranked_collective::Rank; +use sp_runtime::{traits::Convert, Perbill}; + +/// Referendum `TrackId` type. +pub type TrackId = u16; + +/// Referendum track IDs. +pub mod constants { + use super::TrackId; + + // Regular tracks (7 days) used for general operations. The required rank for voting is the + // same as that which is named (and also the track ID). + pub const MEMBERS: TrackId = 1; + pub const PROFICIENTS: TrackId = 2; + pub const FELLOWS: TrackId = 3; + pub const ARCHITECTS: TrackId = 4; + pub const ARCHITECTS_ADEPT: TrackId = 5; + pub const GRAND_ARCHITECTS: TrackId = 6; + pub const MASTERS: TrackId = 7; + pub const MASTERS_CONSTANT: TrackId = 8; + pub const GRAND_MASTERS: TrackId = 9; + + // Longer tracks (14 days) used for rank retention. These require a rank of two more than the + // grade at which they retain (as per the whitepaper). This works out as the track ID minus 8. + pub const RETAIN_AT_1DAN: TrackId = 11; + pub const RETAIN_AT_2DAN: TrackId = 12; + pub const RETAIN_AT_3DAN: TrackId = 13; + pub const RETAIN_AT_4DAN: TrackId = 14; + pub const RETAIN_AT_5DAN: TrackId = 15; + pub const RETAIN_AT_6DAN: TrackId = 16; + + // Longest tracks (30 days) used for promotions. These require a rank of two more than the + // grade to which they promote (as per the whitepaper). This works out as the track ID minus 18. + pub const PROMOTE_TO_1DAN: TrackId = 21; + pub const PROMOTE_TO_2DAN: TrackId = 22; + pub const PROMOTE_TO_3DAN: TrackId = 23; + pub const PROMOTE_TO_4DAN: TrackId = 24; + pub const PROMOTE_TO_5DAN: TrackId = 25; + pub const PROMOTE_TO_6DAN: TrackId = 26; +} + +/// Convert the track ID (defined above) into the minimum rank (i.e. fellowship Dan grade) required +/// to vote on the track. +pub struct MinRankOfClass; +impl Convert for MinRankOfClass { + fn convert(a: TrackId) -> Rank { + match a { + // Just a regular vote: the track ID is conveniently the same as the minimum rank. + regular @ 1..=9 => regular, + // A retention vote; the track ID turns out to be 8 more than the minimum required rank. + retention @ 11..=16 => retention - 8, + // A promotion vote; the track ID turns out to be 18 more than the minimum required + // rank. + promotion @ 21..=26 => promotion - 18, + _ => Rank::max_value(), + } + } +} + +const RETAIN_MAX_DECIDING: u32 = 25; +const RETAIN_DECISION_DEPOSIT: Balance = 5 * DOLLARS; +const RETAIN_PREPARE_PERIOD: BlockNumber = 0; +const RETAIN_DECISION_PERIOD: BlockNumber = 14 * DAYS; +const RETAIN_CONFIRM_PERIOD: BlockNumber = 1 * HOURS; +const RETAIN_MIN_ENACTMENT_PERIOD: BlockNumber = 0; +const RETAIN_MIN_APPROVAL: pallet_referenda::Curve = pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(60), + ceil: Perbill::from_percent(100), +}; +const RETAIN_MIN_SUPPORT: pallet_referenda::Curve = pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(10), + ceil: Perbill::from_percent(100), +}; + +const PROMOTE_MAX_DECIDING: u32 = 10; +const PROMOTE_DECISION_DEPOSIT: Balance = 5 * DOLLARS; +const PROMOTE_PREPARE_PERIOD: BlockNumber = 0; +const PROMOTE_DECISION_PERIOD: BlockNumber = 30 * DAYS; +const PROMOTE_CONFIRM_PERIOD: BlockNumber = 1 * HOURS; +const PROMOTE_MIN_ENACTMENT_PERIOD: BlockNumber = 0; +const PROMOTE_MIN_APPROVAL: pallet_referenda::Curve = pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(60), + ceil: Perbill::from_percent(100), +}; +const PROMOTE_MIN_SUPPORT: pallet_referenda::Curve = pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(10), + ceil: Perbill::from_percent(100), +}; + +pub struct TracksInfo; +impl pallet_referenda::TracksInfo for TracksInfo { + type Id = TrackId; + type RuntimeOrigin = ::PalletsOrigin; + fn tracks() -> &'static [(Self::Id, pallet_referenda::TrackInfo)] { + use constants as tracks; + static DATA: [(TrackId, pallet_referenda::TrackInfo); 21] = [ + ( + tracks::MEMBERS, + pallet_referenda::TrackInfo { + name: "members", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 30 * MINUTES, + decision_period: 7 * DAYS, + confirm_period: 30 * MINUTES, + min_enactment_period: 5 * MINUTES, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(0), + ceil: Perbill::from_percent(100), + }, + }, + ), + ( + tracks::PROFICIENTS, + pallet_referenda::TrackInfo { + name: "proficient members", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 30 * MINUTES, + decision_period: 7 * DAYS, + confirm_period: 30 * MINUTES, + min_enactment_period: 5 * MINUTES, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(0), + ceil: Perbill::from_percent(100), + }, + }, + ), + ( + tracks::FELLOWS, + pallet_referenda::TrackInfo { + name: "fellows", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 30 * MINUTES, + decision_period: 7 * DAYS, + confirm_period: 30 * MINUTES, + min_enactment_period: 5 * MINUTES, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(0), + ceil: Perbill::from_percent(100), + }, + }, + ), + ( + tracks::ARCHITECTS, + pallet_referenda::TrackInfo { + name: "architects", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 30 * MINUTES, + decision_period: 7 * DAYS, + confirm_period: 30 * MINUTES, + min_enactment_period: 5 * MINUTES, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(0), + ceil: Perbill::from_percent(100), + }, + }, + ), + ( + tracks::ARCHITECTS_ADEPT, + pallet_referenda::TrackInfo { + name: "architects adept", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 30 * MINUTES, + decision_period: 7 * DAYS, + confirm_period: 30 * MINUTES, + min_enactment_period: 5 * MINUTES, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(0), + ceil: Perbill::from_percent(100), + }, + }, + ), + ( + tracks::GRAND_ARCHITECTS, + pallet_referenda::TrackInfo { + name: "grand architects", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 30 * MINUTES, + decision_period: 7 * DAYS, + confirm_period: 30 * MINUTES, + min_enactment_period: 5 * MINUTES, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(0), + ceil: Perbill::from_percent(100), + }, + }, + ), + ( + tracks::MASTERS, + pallet_referenda::TrackInfo { + name: "masters", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 30 * MINUTES, + decision_period: 7 * DAYS, + confirm_period: 30 * MINUTES, + min_enactment_period: 5 * MINUTES, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(0), + ceil: Perbill::from_percent(100), + }, + }, + ), + ( + tracks::MASTERS_CONSTANT, + pallet_referenda::TrackInfo { + name: "masters constant", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 30 * MINUTES, + decision_period: 7 * DAYS, + confirm_period: 30 * MINUTES, + min_enactment_period: 5 * MINUTES, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(0), + ceil: Perbill::from_percent(100), + }, + }, + ), + ( + tracks::GRAND_MASTERS, + pallet_referenda::TrackInfo { + name: "grand masters", + max_deciding: 10, + decision_deposit: 5 * DOLLARS, + prepare_period: 30 * MINUTES, + decision_period: 7 * DAYS, + confirm_period: 30 * MINUTES, + min_enactment_period: 5 * MINUTES, + min_approval: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(50), + ceil: Perbill::from_percent(100), + }, + min_support: pallet_referenda::Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(0), + ceil: Perbill::from_percent(100), + }, + }, + ), + ( + tracks::RETAIN_AT_1DAN, + pallet_referenda::TrackInfo { + name: "retain at I Dan", + max_deciding: RETAIN_MAX_DECIDING, + decision_deposit: RETAIN_DECISION_DEPOSIT, + prepare_period: RETAIN_PREPARE_PERIOD, + decision_period: RETAIN_DECISION_PERIOD, + confirm_period: RETAIN_CONFIRM_PERIOD, + min_enactment_period: RETAIN_MIN_ENACTMENT_PERIOD, + min_approval: RETAIN_MIN_APPROVAL, + min_support: RETAIN_MIN_SUPPORT, + }, + ), + ( + tracks::RETAIN_AT_2DAN, + pallet_referenda::TrackInfo { + name: "retain at II Dan", + max_deciding: RETAIN_MAX_DECIDING, + decision_deposit: RETAIN_DECISION_DEPOSIT, + prepare_period: RETAIN_PREPARE_PERIOD, + decision_period: RETAIN_DECISION_PERIOD, + confirm_period: RETAIN_CONFIRM_PERIOD, + min_enactment_period: RETAIN_MIN_ENACTMENT_PERIOD, + min_approval: RETAIN_MIN_APPROVAL, + min_support: RETAIN_MIN_SUPPORT, + }, + ), + ( + tracks::RETAIN_AT_3DAN, + pallet_referenda::TrackInfo { + name: "retain at III Dan", + max_deciding: RETAIN_MAX_DECIDING, + decision_deposit: RETAIN_DECISION_DEPOSIT, + prepare_period: RETAIN_PREPARE_PERIOD, + decision_period: RETAIN_DECISION_PERIOD, + confirm_period: RETAIN_CONFIRM_PERIOD, + min_enactment_period: RETAIN_MIN_ENACTMENT_PERIOD, + min_approval: RETAIN_MIN_APPROVAL, + min_support: RETAIN_MIN_SUPPORT, + }, + ), + ( + tracks::RETAIN_AT_4DAN, + pallet_referenda::TrackInfo { + name: "retain at IV Dan", + max_deciding: RETAIN_MAX_DECIDING, + decision_deposit: RETAIN_DECISION_DEPOSIT, + prepare_period: RETAIN_PREPARE_PERIOD, + decision_period: RETAIN_DECISION_PERIOD, + confirm_period: RETAIN_CONFIRM_PERIOD, + min_enactment_period: RETAIN_MIN_ENACTMENT_PERIOD, + min_approval: RETAIN_MIN_APPROVAL, + min_support: RETAIN_MIN_SUPPORT, + }, + ), + ( + tracks::RETAIN_AT_5DAN, + pallet_referenda::TrackInfo { + name: "retain at V Dan", + max_deciding: RETAIN_MAX_DECIDING, + decision_deposit: RETAIN_DECISION_DEPOSIT, + prepare_period: RETAIN_PREPARE_PERIOD, + decision_period: RETAIN_DECISION_PERIOD, + confirm_period: RETAIN_CONFIRM_PERIOD, + min_enactment_period: RETAIN_MIN_ENACTMENT_PERIOD, + min_approval: RETAIN_MIN_APPROVAL, + min_support: RETAIN_MIN_SUPPORT, + }, + ), + ( + tracks::RETAIN_AT_6DAN, + pallet_referenda::TrackInfo { + name: "retain at VI Dan", + max_deciding: RETAIN_MAX_DECIDING, + decision_deposit: RETAIN_DECISION_DEPOSIT, + prepare_period: RETAIN_PREPARE_PERIOD, + decision_period: RETAIN_DECISION_PERIOD, + confirm_period: RETAIN_CONFIRM_PERIOD, + min_enactment_period: RETAIN_MIN_ENACTMENT_PERIOD, + min_approval: RETAIN_MIN_APPROVAL, + min_support: RETAIN_MIN_SUPPORT, + }, + ), + ( + tracks::PROMOTE_TO_1DAN, + pallet_referenda::TrackInfo { + name: "promote to I Dan", + max_deciding: PROMOTE_MAX_DECIDING, + decision_deposit: PROMOTE_DECISION_DEPOSIT, + prepare_period: PROMOTE_PREPARE_PERIOD, + decision_period: PROMOTE_DECISION_PERIOD, + confirm_period: PROMOTE_CONFIRM_PERIOD, + min_enactment_period: PROMOTE_MIN_ENACTMENT_PERIOD, + min_approval: PROMOTE_MIN_APPROVAL, + min_support: PROMOTE_MIN_SUPPORT, + }, + ), + ( + tracks::PROMOTE_TO_2DAN, + pallet_referenda::TrackInfo { + name: "promote to II Dan", + max_deciding: PROMOTE_MAX_DECIDING, + decision_deposit: PROMOTE_DECISION_DEPOSIT, + prepare_period: PROMOTE_PREPARE_PERIOD, + decision_period: PROMOTE_DECISION_PERIOD, + confirm_period: PROMOTE_CONFIRM_PERIOD, + min_enactment_period: PROMOTE_MIN_ENACTMENT_PERIOD, + min_approval: PROMOTE_MIN_APPROVAL, + min_support: PROMOTE_MIN_SUPPORT, + }, + ), + ( + tracks::PROMOTE_TO_3DAN, + pallet_referenda::TrackInfo { + name: "promote to III Dan", + max_deciding: PROMOTE_MAX_DECIDING, + decision_deposit: PROMOTE_DECISION_DEPOSIT, + prepare_period: PROMOTE_PREPARE_PERIOD, + decision_period: PROMOTE_DECISION_PERIOD, + confirm_period: PROMOTE_CONFIRM_PERIOD, + min_enactment_period: PROMOTE_MIN_ENACTMENT_PERIOD, + min_approval: PROMOTE_MIN_APPROVAL, + min_support: PROMOTE_MIN_SUPPORT, + }, + ), + ( + tracks::PROMOTE_TO_4DAN, + pallet_referenda::TrackInfo { + name: "promote to IV Dan", + max_deciding: PROMOTE_MAX_DECIDING, + decision_deposit: PROMOTE_DECISION_DEPOSIT, + prepare_period: PROMOTE_PREPARE_PERIOD, + decision_period: PROMOTE_DECISION_PERIOD, + confirm_period: PROMOTE_CONFIRM_PERIOD, + min_enactment_period: PROMOTE_MIN_ENACTMENT_PERIOD, + min_approval: PROMOTE_MIN_APPROVAL, + min_support: PROMOTE_MIN_SUPPORT, + }, + ), + ( + tracks::PROMOTE_TO_5DAN, + pallet_referenda::TrackInfo { + name: "promote to V Dan", + max_deciding: PROMOTE_MAX_DECIDING, + decision_deposit: PROMOTE_DECISION_DEPOSIT, + prepare_period: PROMOTE_PREPARE_PERIOD, + decision_period: PROMOTE_DECISION_PERIOD, + confirm_period: PROMOTE_CONFIRM_PERIOD, + min_enactment_period: PROMOTE_MIN_ENACTMENT_PERIOD, + min_approval: PROMOTE_MIN_APPROVAL, + min_support: PROMOTE_MIN_SUPPORT, + }, + ), + ( + tracks::PROMOTE_TO_6DAN, + pallet_referenda::TrackInfo { + name: "promote to VI Dan", + max_deciding: PROMOTE_MAX_DECIDING, + decision_deposit: PROMOTE_DECISION_DEPOSIT, + prepare_period: PROMOTE_PREPARE_PERIOD, + decision_period: PROMOTE_DECISION_PERIOD, + confirm_period: PROMOTE_CONFIRM_PERIOD, + min_enactment_period: PROMOTE_MIN_ENACTMENT_PERIOD, + min_approval: PROMOTE_MIN_APPROVAL, + min_support: PROMOTE_MIN_SUPPORT, + }, + ), + ]; + &DATA[..] + } + fn track_for(id: &Self::RuntimeOrigin) -> Result { + use super::origins::Origin; + use constants as tracks; + + #[cfg(feature = "runtime-benchmarks")] + { + // For benchmarks, we enable a root origin. + // It is important that this is not available in production! + let root: Self::RuntimeOrigin = frame_system::RawOrigin::Root.into(); + if &root == id { + return Ok(tracks::GRAND_MASTERS) + } + } + + match Origin::try_from(id.clone()) { + Ok(Origin::Members) => Ok(tracks::MEMBERS), + Ok(Origin::Fellowship2Dan) => Ok(tracks::PROFICIENTS), + Ok(Origin::Fellows) => Ok(tracks::FELLOWS), + Ok(Origin::Architects) => Ok(tracks::ARCHITECTS), + Ok(Origin::Fellowship5Dan) => Ok(tracks::ARCHITECTS_ADEPT), + Ok(Origin::Fellowship6Dan) => Ok(tracks::GRAND_ARCHITECTS), + Ok(Origin::Masters) => Ok(tracks::MASTERS), + Ok(Origin::Fellowship8Dan) => Ok(tracks::MASTERS_CONSTANT), + Ok(Origin::Fellowship9Dan) => Ok(tracks::GRAND_MASTERS), + + Ok(Origin::RetainAt1Dan) => Ok(tracks::RETAIN_AT_1DAN), + Ok(Origin::RetainAt2Dan) => Ok(tracks::RETAIN_AT_2DAN), + Ok(Origin::RetainAt3Dan) => Ok(tracks::RETAIN_AT_3DAN), + Ok(Origin::RetainAt4Dan) => Ok(tracks::RETAIN_AT_4DAN), + Ok(Origin::RetainAt5Dan) => Ok(tracks::RETAIN_AT_5DAN), + Ok(Origin::RetainAt6Dan) => Ok(tracks::RETAIN_AT_6DAN), + + Ok(Origin::PromoteTo1Dan) => Ok(tracks::PROMOTE_TO_1DAN), + Ok(Origin::PromoteTo2Dan) => Ok(tracks::PROMOTE_TO_2DAN), + Ok(Origin::PromoteTo3Dan) => Ok(tracks::PROMOTE_TO_3DAN), + Ok(Origin::PromoteTo4Dan) => Ok(tracks::PROMOTE_TO_4DAN), + Ok(Origin::PromoteTo5Dan) => Ok(tracks::PROMOTE_TO_5DAN), + Ok(Origin::PromoteTo6Dan) => Ok(tracks::PROMOTE_TO_6DAN), + + _ => Err(()), + } + } +} +pallet_referenda::impl_tracksinfo_get!(TracksInfo, Balance, BlockNumber); diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/impls.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/impls.rs new file mode 100644 index 00000000000..9f4c2a6a4c9 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/impls.rs @@ -0,0 +1,229 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::OriginCaller; +use frame_support::{ + dispatch::DispatchResultWithPostInfo, + traits::{Currency, Get, Imbalance, OnUnbalanced, OriginTrait, PrivilegeCmp}, + weights::Weight, +}; +use log; +use pallet_alliance::{ProposalIndex, ProposalProvider}; +use parachains_common::impls::NegativeImbalance; +use sp_runtime::DispatchError; +use sp_std::{cmp::Ordering, marker::PhantomData, prelude::*}; +use xcm::latest::{Fungibility, Junction, Parent}; + +type AccountIdOf = ::AccountId; + +type ProposalOf = >::Proposal; + +type HashOf = ::Hash; + +/// Type alias to conveniently refer to the `Currency::Balance` associated type. +pub type BalanceOf = + as Currency<::AccountId>>::Balance; + +/// Implements `OnUnbalanced::on_unbalanced` to teleport slashed assets to relay chain treasury +/// account. +pub struct ToParentTreasury( + PhantomData<(TreasuryAccount, PalletAccount, T)>, +); + +impl OnUnbalanced> + for ToParentTreasury +where + T: pallet_balances::Config + pallet_xcm::Config + frame_system::Config, + <::RuntimeOrigin as OriginTrait>::AccountId: From>, + [u8; 32]: From<::AccountId>, + TreasuryAccount: Get>, + PalletAccount: Get>, + BalanceOf: Into, +{ + fn on_unbalanced(amount: NegativeImbalance) { + let amount = match amount.drop_zero() { + Ok(..) => return, + Err(amount) => amount, + }; + let imbalance = amount.peek(); + let pallet_acc: AccountIdOf = PalletAccount::get(); + let treasury_acc: AccountIdOf = TreasuryAccount::get(); + + >::resolve_creating(&pallet_acc, amount); + + let result = >::teleport_assets( + <::RuntimeOrigin>::signed(pallet_acc.into()), + Box::new(Parent.into()), + Box::new( + Junction::AccountId32 { network: None, id: treasury_acc.into() } + .into_location() + .into(), + ), + Box::new((Parent, imbalance).into()), + 0, + ); + + if let Err(err) = result { + log::warn!("Failed to teleport slashed assets: {:?}", err); + } + } +} + +/// Proposal provider for alliance pallet. +/// Adapter from collective pallet to alliance proposal provider trait. +pub struct AllianceProposalProvider(PhantomData<(T, I)>); + +impl ProposalProvider, HashOf, ProposalOf> + for AllianceProposalProvider +where + T: pallet_collective::Config + frame_system::Config, + I: 'static, +{ + fn propose_proposal( + who: AccountIdOf, + threshold: u32, + proposal: Box>, + length_bound: u32, + ) -> Result<(u32, u32), DispatchError> { + pallet_collective::Pallet::::do_propose_proposed( + who, + threshold, + proposal, + length_bound, + ) + } + + fn vote_proposal( + who: AccountIdOf, + proposal: HashOf, + index: ProposalIndex, + approve: bool, + ) -> Result { + pallet_collective::Pallet::::do_vote(who, proposal, index, approve) + } + + fn close_proposal( + proposal_hash: HashOf, + proposal_index: ProposalIndex, + proposal_weight_bound: Weight, + length_bound: u32, + ) -> DispatchResultWithPostInfo { + pallet_collective::Pallet::::do_close( + proposal_hash, + proposal_index, + proposal_weight_bound, + length_bound, + ) + } + + fn proposal_of(proposal_hash: HashOf) -> Option> { + pallet_collective::Pallet::::proposal_of(proposal_hash) + } +} + +/// Used to compare the privilege of an origin inside the scheduler. +pub struct EqualOrGreatestRootCmp; + +impl PrivilegeCmp for EqualOrGreatestRootCmp { + fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option { + if left == right { + return Some(Ordering::Equal) + } + match (left, right) { + // Root is greater than anything. + (OriginCaller::system(frame_system::RawOrigin::Root), _) => Some(Ordering::Greater), + _ => None, + } + } +} + +#[cfg(feature = "runtime-benchmarks")] +pub mod benchmarks { + use super::*; + use crate::ParachainSystem; + use cumulus_primitives_core::{ChannelStatus, GetChannelInfo}; + use frame_support::traits::{ + fungible, + tokens::{Pay, PaymentStatus}, + }; + use pallet_ranked_collective::Rank; + use parachains_common::{AccountId, Balance}; + use sp_runtime::traits::Convert; + + /// Rank to salary conversion helper type. + pub struct RankToSalary(PhantomData); + impl Convert for RankToSalary + where + Fungible: fungible::Inspect, + { + fn convert(r: Rank) -> Balance { + Balance::from(r).saturating_mul(Fungible::minimum_balance()) + } + } + + /// Trait for setting up any prerequisites for successful execution of benchmarks. + pub trait EnsureSuccessful { + fn ensure_successful(); + } + + /// Implementation of the [`EnsureSuccessful`] trait which opens an HRMP channel between + /// the Collectives and a parachain with a given ID. + pub struct OpenHrmpChannel(PhantomData); + impl> EnsureSuccessful for OpenHrmpChannel { + fn ensure_successful() { + if let ChannelStatus::Closed = ParachainSystem::get_channel_status(I::get().into()) { + ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(I::get().into()) + } + } + } + + /// Type that wraps a type implementing the [`Pay`] trait to decorate its + /// [`Pay::ensure_successful`] function with a provided implementation of the + /// [`EnsureSuccessful`] trait. + pub struct PayWithEnsure(PhantomData<(O, E)>); + impl Pay for PayWithEnsure + where + O: Pay, + E: EnsureSuccessful, + { + type AssetKind = O::AssetKind; + type Balance = O::Balance; + type Beneficiary = O::Beneficiary; + type Error = O::Error; + type Id = O::Id; + + fn pay( + who: &Self::Beneficiary, + asset_kind: Self::AssetKind, + amount: Self::Balance, + ) -> Result { + O::pay(who, asset_kind, amount) + } + fn check_payment(id: Self::Id) -> PaymentStatus { + O::check_payment(id) + } + fn ensure_successful( + who: &Self::Beneficiary, + asset_kind: Self::AssetKind, + amount: Self::Balance, + ) { + E::ensure_successful(); + O::ensure_successful(who, asset_kind, amount) + } + fn ensure_concluded(id: Self::Id) { + O::ensure_concluded(id) + } + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/lib.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/lib.rs new file mode 100644 index 00000000000..a548a2c4865 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/lib.rs @@ -0,0 +1,1031 @@ +// 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. + +//! # Collectives Parachain +//! +//! This parachain is for collectives that serve the Polkadot network. +//! Each collective is defined by a specialized (possibly instanced) pallet. +//! +//! ### Governance +//! +//! As a system parachain, Collectives defers its governance (namely, its `Root` origin), to +//! its Relay Chain parent, Polkadot. +//! +//! ### Collator Selection +//! +//! Collectives uses `pallet-collator-selection`, a simple first-come-first-served registration +//! system where collators can reserve a small bond to join the block producer set. There is no +//! slashing. Collective members are generally expected to run collators. + +#![cfg_attr(not(feature = "std"), no_std)] +#![recursion_limit = "256"] + +// Make the WASM binary available. +#[cfg(feature = "std")] +include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); + +pub mod ambassador; +pub mod impls; +mod weights; +pub mod xcm_config; +// Fellowship configurations. +pub mod fellowship; +pub use ambassador::pallet_ambassador_origins; + +use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use fellowship::{ + migration::import_kusama_fellowship, pallet_fellowship_origins, Fellows, + FellowshipCollectiveInstance, +}; +use impls::{AllianceProposalProvider, EqualOrGreatestRootCmp, ToParentTreasury}; +use sp_api::impl_runtime_apis; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; +use sp_runtime::{ + create_runtime_str, generic, impl_opaque_keys, + traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT}, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, Perbill, +}; + +use sp_std::prelude::*; +#[cfg(feature = "std")] +use sp_version::NativeVersion; +use sp_version::RuntimeVersion; + +use codec::{Decode, Encode, MaxEncodedLen}; +use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; +use frame_support::{ + construct_runtime, + dispatch::DispatchClass, + genesis_builder_helper::{build_config, create_default_config}, + parameter_types, + traits::{ + fungible::HoldConsideration, ConstBool, ConstU16, ConstU32, ConstU64, ConstU8, + EitherOfDiverse, InstanceFilter, LinearStoragePrice, TransformOrigin, + }, + weights::{ConstantMultiplier, Weight}, + PalletId, +}; +use frame_system::{ + limits::{BlockLength, BlockWeights}, + EnsureRoot, +}; +pub use parachains_common as common; +use parachains_common::{ + impls::DealWithFees, + message_queue::*, + polkadot::{account::*, consensus::*, currency::*, fee::WeightToFee}, + AccountId, AuraId, Balance, BlockNumber, Hash, Header, Nonce, Signature, + AVERAGE_ON_INITIALIZE_RATIO, DAYS, HOURS, MAXIMUM_BLOCK_WEIGHT, MINUTES, NORMAL_DISPATCH_RATIO, + SLOT_DURATION, +}; +use sp_runtime::RuntimeDebug; +use xcm_config::{GovernanceLocation, XcmOriginToTransactDispatchOrigin}; + +#[cfg(any(feature = "std", test))] +pub use sp_runtime::BuildStorage; + +// Polkadot imports +use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; +use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; +use xcm::latest::{prelude::*, BodyId}; + +use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; + +impl_opaque_keys! { + pub struct SessionKeys { + pub aura: Aura, + } +} + +#[sp_version::runtime_version] +pub const VERSION: RuntimeVersion = RuntimeVersion { + spec_name: create_runtime_str!("collectives"), + impl_name: create_runtime_str!("collectives"), + authoring_version: 1, + spec_version: 10000, + impl_version: 0, + apis: RUNTIME_API_VERSIONS, + transaction_version: 5, + state_version: 0, +}; + +/// The version information used to identify this runtime when compiled natively. +#[cfg(feature = "std")] +pub fn native_version() -> NativeVersion { + NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } +} + +/// Privileged origin that represents Root or more than two thirds of the Alliance. +pub type RootOrAllianceTwoThirdsMajority = EitherOfDiverse< + EnsureRoot, + pallet_collective::EnsureProportionMoreThan, +>; + +parameter_types! { + pub const Version: RuntimeVersion = VERSION; + pub RuntimeBlockLength: BlockLength = + BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() + .base_block(BlockExecutionWeight::get()) + .for_class(DispatchClass::all(), |weights| { + weights.base_extrinsic = ExtrinsicBaseWeight::get(); + }) + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Operational transactions have some extra reserved space, so that they + // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); +} + +// Configure FRAME pallets to include in runtime. +impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = RuntimeBlockWeights; + type BlockLength = RuntimeBlockLength; + type AccountId = AccountId; + type RuntimeCall = RuntimeCall; + type Lookup = AccountIdLookup; + type Nonce = Nonce; + type Hash = Hash; + type Hashing = BlakeTwo256; + type Block = Block; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type BlockHashCount = BlockHashCount; + type DbWeight = RocksDbWeight; + type Version = Version; + type PalletInfo = PalletInfo; + type OnNewAccount = (); + type OnKilledAccount = (); + type AccountData = pallet_balances::AccountData; + type SystemWeightInfo = weights::frame_system::WeightInfo; + type SS58Prefix = ConstU16<0>; + type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + +impl pallet_timestamp::Config for Runtime { + /// A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = Aura; + type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>; + type WeightInfo = weights::pallet_timestamp::WeightInfo; +} + +impl pallet_authorship::Config for Runtime { + type FindAuthor = pallet_session::FindAccountFromAuthorIndex; + type EventHandler = (CollatorSelection,); +} + +parameter_types! { + pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT; +} + +impl pallet_balances::Config for Runtime { + type MaxLocks = ConstU32<50>; + /// The type for recording an account's balance. + type Balance = Balance; + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = weights::pallet_balances::WeightInfo; + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; + type FreezeIdentifier = (); + type MaxHolds = ConstU32<1>; + type MaxFreezes = ConstU32<0>; +} + +parameter_types! { + /// Relay Chain `TransactionByteFee` / 10 + pub const TransactionByteFee: Balance = MILLICENTS; +} + +impl pallet_transaction_payment::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type OnChargeTransaction = + pallet_transaction_payment::CurrencyAdapter>; + type WeightToFee = WeightToFee; + type LengthToFee = ConstantMultiplier; + type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; + type OperationalFeeMultiplier = ConstU8<5>; +} + +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); + // Additional storage item size of 32 bytes. + pub const DepositFactor: Balance = deposit(0, 32); +} + +impl pallet_multisig::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type Currency = Balances; + type DepositBase = DepositBase; + type DepositFactor = DepositFactor; + type MaxSignatories = ConstU32<100>; + type WeightInfo = weights::pallet_multisig::WeightInfo; +} + +impl pallet_utility::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type PalletsOrigin = OriginCaller; + type WeightInfo = weights::pallet_utility::WeightInfo; +} + +parameter_types! { + // One storage item; key size 32, value size 8; . + pub const ProxyDepositBase: Balance = deposit(1, 40); + // Additional storage item size of 33 bytes. + pub const ProxyDepositFactor: Balance = deposit(0, 33); + // One storage item; key size 32, value size 16 + pub const AnnouncementDepositBase: Balance = deposit(1, 48); + pub const AnnouncementDepositFactor: Balance = deposit(0, 66); +} + +/// The type used to represent the kinds of proxying allowed. +#[derive( + Copy, + Clone, + Eq, + PartialEq, + Ord, + PartialOrd, + Encode, + Decode, + RuntimeDebug, + MaxEncodedLen, + scale_info::TypeInfo, +)] +pub enum ProxyType { + /// Fully permissioned proxy. Can execute any call on behalf of _proxied_. + Any, + /// Can execute any call that does not transfer funds. + NonTransfer, + /// Proxy with the ability to reject time-delay proxy announcements. + CancelProxy, + /// Collator selection proxy. Can execute calls related to collator selection mechanism. + Collator, + /// Alliance proxy. Allows calls related to the Alliance. + Alliance, + /// Fellowship proxy. Allows calls related to the Fellowship. + Fellowship, + /// Ambassador proxy. Allows calls related to the Ambassador Program. + Ambassador, +} +impl Default for ProxyType { + fn default() -> Self { + Self::Any + } +} +impl InstanceFilter for ProxyType { + fn filter(&self, c: &RuntimeCall) -> bool { + match self { + ProxyType::Any => true, + ProxyType::NonTransfer => !matches!(c, RuntimeCall::Balances { .. }), + ProxyType::CancelProxy => matches!( + c, + RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }) | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + ProxyType::Collator => matches!( + c, + RuntimeCall::CollatorSelection { .. } | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + ProxyType::Alliance => matches!( + c, + RuntimeCall::AllianceMotion { .. } | + RuntimeCall::Alliance { .. } | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + ProxyType::Fellowship => matches!( + c, + RuntimeCall::FellowshipCollective { .. } | + RuntimeCall::FellowshipReferenda { .. } | + RuntimeCall::FellowshipCore { .. } | + RuntimeCall::FellowshipSalary { .. } | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + ProxyType::Ambassador => matches!( + c, + RuntimeCall::AmbassadorCollective { .. } | + RuntimeCall::AmbassadorReferenda { .. } | + RuntimeCall::AmbassadorContent { .. } | + RuntimeCall::AmbassadorCore { .. } | + RuntimeCall::AmbassadorSalary { .. } | + RuntimeCall::Utility { .. } | + RuntimeCall::Multisig { .. } + ), + } + } + fn is_superset(&self, o: &Self) -> bool { + match (self, o) { + (x, y) if x == y => true, + (ProxyType::Any, _) => true, + (_, ProxyType::Any) => false, + (ProxyType::NonTransfer, _) => true, + _ => false, + } + } +} + +impl pallet_proxy::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type Currency = Balances; + type ProxyType = ProxyType; + type ProxyDepositBase = ProxyDepositBase; + type ProxyDepositFactor = ProxyDepositFactor; + type MaxProxies = ConstU32<32>; + type WeightInfo = weights::pallet_proxy::WeightInfo; + type MaxPending = ConstU32<32>; + type CallHasher = BlakeTwo256; + type AnnouncementDepositBase = AnnouncementDepositBase; + type AnnouncementDepositFactor = AnnouncementDepositFactor; +} + +parameter_types! { + pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); + pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); +} + +impl cumulus_pallet_parachain_system::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type OnSystemEvent = (); + type SelfParaId = parachain_info::Pallet; + type DmpQueue = frame_support::traits::EnqueueWithOrigin; + type ReservedDmpWeight = ReservedDmpWeight; + type OutboundXcmpMessageSource = XcmpQueue; + type XcmpMessageHandler = XcmpQueue; + type ReservedXcmpWeight = ReservedXcmpWeight; + type CheckAssociatedRelayNumber = RelayNumberStrictlyIncreases; + type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook< + Runtime, + RELAY_CHAIN_SLOT_DURATION_MILLIS, + BLOCK_PROCESSING_VELOCITY, + UNINCLUDED_SEGMENT_CAPACITY, + >; +} + +impl parachain_info::Config for Runtime {} + +parameter_types! { + pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block; +} + +impl pallet_message_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type WeightInfo = weights::pallet_message_queue::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor< + cumulus_primitives_core::AggregateMessageOrigin, + >; + #[cfg(not(feature = "runtime-benchmarks"))] + type MessageProcessor = xcm_builder::ProcessXcmMessage< + AggregateMessageOrigin, + xcm_executor::XcmExecutor, + RuntimeCall, + >; + type Size = u32; + // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin: + type QueueChangeHandler = NarrowOriginToSibling; + type QueuePausedQuery = NarrowOriginToSibling; + type HeapSize = sp_core::ConstU32<{ 64 * 1024 }>; + type MaxStale = sp_core::ConstU32<8>; + type ServiceWeight = MessageQueueServiceWeight; +} + +impl cumulus_pallet_aura_ext::Config for Runtime {} + +parameter_types! { + /// The asset ID for the asset that we use to pay for message delivery fees. + pub FeeAssetId: AssetId = Concrete(xcm_config::DotLocation::get()); + /// The base fee for the message delivery fees. + pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); +} + +pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice< + FeeAssetId, + BaseDeliveryFee, + TransactionByteFee, + XcmpQueue, +>; + +impl cumulus_pallet_xcmp_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type ChannelInfo = ParachainSystem; + type VersionWrapper = PolkadotXcm; + // Enqueue XCMP messages from siblings for later processing. + type XcmpQueue = TransformOrigin; + type MaxInboundSuspended = sp_core::ConstU32<1_000>; + type ControllerOrigin = EitherOfDiverse, Fellows>; + type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; + type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; + type PriceForSiblingDelivery = + polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; +} + +parameter_types! { + pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent; +} + +impl cumulus_pallet_dmp_queue::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_dmp_queue::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type DmpSink = frame_support::traits::EnqueueWithOrigin; +} + +pub const PERIOD: u32 = 6 * HOURS; +pub const OFFSET: u32 = 0; + +impl pallet_session::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type ValidatorId = ::AccountId; + // we don't have stash and controller, thus we don't need the convert as well. + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ShouldEndSession = pallet_session::PeriodicSessions, ConstU32>; + type NextSessionRotation = pallet_session::PeriodicSessions, ConstU32>; + type SessionManager = CollatorSelection; + // Essentially just Aura, but let's be pedantic. + type SessionHandler = ::KeyTypeIdProviders; + type Keys = SessionKeys; + type WeightInfo = weights::pallet_session::WeightInfo; +} + +impl pallet_aura::Config for Runtime { + type AuthorityId = AuraId; + type DisabledValidators = (); + type MaxAuthorities = ConstU32<100_000>; + type AllowMultipleBlocksPerSlot = ConstBool; + #[cfg(feature = "experimental")] + type SlotDuration = pallet_aura::MinimumPeriodTimesTwo; +} + +parameter_types! { + pub const PotId: PalletId = PalletId(*b"PotStake"); + pub const SessionLength: BlockNumber = 6 * HOURS; + // `StakingAdmin` pluralistic body. + pub const StakingAdminBodyId: BodyId = BodyId::Defense; +} + +/// We allow root and the `StakingAdmin` to execute privileged collator selection operations. +pub type CollatorSelectionUpdateOrigin = EitherOfDiverse< + EnsureRoot, + EnsureXcm>, +>; + +impl pallet_collator_selection::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type UpdateOrigin = CollatorSelectionUpdateOrigin; + type PotId = PotId; + type MaxCandidates = ConstU32<100>; + type MinEligibleCollators = ConstU32<4>; + type MaxInvulnerables = ConstU32<20>; + // should be a multiple of session or things will get inconsistent + type KickThreshold = ConstU32; + type ValidatorId = ::AccountId; + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ValidatorRegistration = Session; + type WeightInfo = weights::pallet_collator_selection::WeightInfo; +} + +pub const ALLIANCE_MOTION_DURATION: BlockNumber = 5 * DAYS; + +parameter_types! { + pub const AllianceMotionDuration: BlockNumber = ALLIANCE_MOTION_DURATION; + pub MaxProposalWeight: Weight = Perbill::from_percent(50) * RuntimeBlockWeights::get().max_block; +} +pub const ALLIANCE_MAX_PROPOSALS: u32 = 100; +pub const ALLIANCE_MAX_MEMBERS: u32 = 100; + +type AllianceCollective = pallet_collective::Instance1; +impl pallet_collective::Config for Runtime { + type RuntimeOrigin = RuntimeOrigin; + type Proposal = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type MotionDuration = AllianceMotionDuration; + type MaxProposals = ConstU32; + type MaxMembers = ConstU32; + type DefaultVote = pallet_collective::MoreThanMajorityThenPrimeDefaultVote; + type SetMembersOrigin = EnsureRoot; + type WeightInfo = weights::pallet_collective::WeightInfo; + type MaxProposalWeight = MaxProposalWeight; +} + +pub const MAX_FELLOWS: u32 = ALLIANCE_MAX_MEMBERS; +pub const MAX_ALLIES: u32 = 100; + +parameter_types! { + pub const AllyDeposit: Balance = 1_000 * UNITS; // 1,000 DOT bond to join as an Ally + // The Alliance pallet account, used as a temporary place to deposit a slashed imbalance + // before the teleport to the Treasury. + pub AlliancePalletAccount: AccountId = ALLIANCE_PALLET_ID.into_account_truncating(); + pub PolkadotTreasuryAccount: AccountId = POLKADOT_TREASURY_PALLET_ID.into_account_truncating(); + // The number of blocks a member must wait between giving a retirement notice and retiring. + // Supposed to be greater than time required to `kick_member` with alliance motion. + pub const AllianceRetirementPeriod: BlockNumber = (90 * DAYS) + ALLIANCE_MOTION_DURATION; +} + +impl pallet_alliance::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type Proposal = RuntimeCall; + type AdminOrigin = RootOrAllianceTwoThirdsMajority; + type MembershipManager = RootOrAllianceTwoThirdsMajority; + type AnnouncementOrigin = RootOrAllianceTwoThirdsMajority; + type Currency = Balances; + type Slashed = ToParentTreasury; + type InitializeMembers = AllianceMotion; + type MembershipChanged = AllianceMotion; + type RetirementPeriod = AllianceRetirementPeriod; + type IdentityVerifier = (); // Don't block accounts on identity criteria + type ProposalProvider = AllianceProposalProvider; + type MaxProposals = ConstU32; + type MaxFellows = ConstU32; + type MaxAllies = ConstU32; + type MaxUnscrupulousItems = ConstU32<100>; + type MaxWebsiteUrlLength = ConstU32<255>; + type MaxAnnouncementsCount = ConstU32<100>; + type MaxMembersCount = ConstU32; + type AllyDeposit = AllyDeposit; + type WeightInfo = weights::pallet_alliance::WeightInfo; +} + +parameter_types! { + pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block; +} + +#[cfg(not(feature = "runtime-benchmarks"))] +parameter_types! { + pub const MaxScheduledPerBlock: u32 = 50; +} + +#[cfg(feature = "runtime-benchmarks")] +parameter_types! { + pub const MaxScheduledPerBlock: u32 = 200; +} + +impl pallet_scheduler::Config for Runtime { + type RuntimeOrigin = RuntimeOrigin; + type RuntimeEvent = RuntimeEvent; + type PalletsOrigin = OriginCaller; + type RuntimeCall = RuntimeCall; + type MaximumWeight = MaximumSchedulerWeight; + type ScheduleOrigin = EnsureRoot; + type MaxScheduledPerBlock = MaxScheduledPerBlock; + type WeightInfo = weights::pallet_scheduler::WeightInfo; + type OriginPrivilegeCmp = EqualOrGreatestRootCmp; + type Preimages = Preimage; +} + +parameter_types! { + pub const PreimageBaseDeposit: Balance = deposit(2, 64); + pub const PreimageByteDeposit: Balance = deposit(0, 1); + pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage); +} + +impl pallet_preimage::Config for Runtime { + type WeightInfo = weights::pallet_preimage::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type ManagerOrigin = EnsureRoot; + type Consideration = HoldConsideration< + AccountId, + Balances, + PreimageHoldReason, + LinearStoragePrice, + >; +} + +// Create the runtime by composing the FRAME pallets that were previously configured. +construct_runtime!( + pub enum Runtime + { + // System support stuff. + System: frame_system::{Pallet, Call, Config, Storage, Event} = 0, + ParachainSystem: cumulus_pallet_parachain_system::{ + Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned, + } = 1, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2, + ParachainInfo: parachain_info::{Pallet, Storage, Config} = 3, + + // Monetary stuff. + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event} = 10, + TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 11, + + // Collator support. the order of these 5 are important and shall not change. + Authorship: pallet_authorship::{Pallet, Storage} = 20, + CollatorSelection: pallet_collator_selection::{Pallet, Call, Storage, Event, Config} = 21, + Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 22, + Aura: pallet_aura::{Pallet, Storage, Config} = 23, + AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config} = 24, + + // XCM helpers. + XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, + PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 31, + CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, + DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, + MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event} = 34, + + // Handy utilities. + Utility: pallet_utility::{Pallet, Call, Event} = 40, + Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 41, + Proxy: pallet_proxy::{Pallet, Call, Storage, Event} = 42, + Preimage: pallet_preimage::{Pallet, Call, Storage, Event, HoldReason} = 43, + Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event} = 44, + + // The main stage. + + // The Alliance. + Alliance: pallet_alliance::{Pallet, Call, Storage, Event, Config} = 50, + AllianceMotion: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config} = 51, + + // The Fellowship. + // pub type FellowshipCollectiveInstance = pallet_ranked_collective::Instance1; + FellowshipCollective: pallet_ranked_collective::::{Pallet, Call, Storage, Event} = 60, + // pub type FellowshipReferendaInstance = pallet_referenda::Instance1; + FellowshipReferenda: pallet_referenda::::{Pallet, Call, Storage, Event} = 61, + FellowshipOrigins: pallet_fellowship_origins::{Origin} = 62, + // pub type FellowshipCoreInstance = pallet_core_fellowship::Instance1; + FellowshipCore: pallet_core_fellowship::::{Pallet, Call, Storage, Event} = 63, + // pub type FellowshipSalaryInstance = pallet_salary::Instance1; + FellowshipSalary: pallet_salary::::{Pallet, Call, Storage, Event} = 64, + + // Ambassador Program. + AmbassadorCollective: pallet_ranked_collective::::{Pallet, Call, Storage, Event} = 70, + AmbassadorReferenda: pallet_referenda::::{Pallet, Call, Storage, Event} = 71, + AmbassadorOrigins: pallet_ambassador_origins::{Origin} = 72, + AmbassadorCore: pallet_core_fellowship::::{Pallet, Call, Storage, Event} = 73, + AmbassadorSalary: pallet_salary::::{Pallet, Call, Storage, Event} = 74, + AmbassadorContent: pallet_collective_content::::{Pallet, Call, Storage, Event} = 75, + } +); + +/// The address format for describing accounts. +pub type Address = sp_runtime::MultiAddress; +/// Block type as expected by this runtime. +pub type Block = generic::Block; +/// A Block signed with a Justification +pub type SignedBlock = generic::SignedBlock; +/// BlockId type as expected by this runtime. +pub type BlockId = generic::BlockId; +/// The extension to the basic transaction logic. +pub type TxExtension = ( + frame_system::CheckNonZeroSender, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, +); +/// Unchecked extrinsic type as expected by this runtime. +pub type UncheckedExtrinsic = + generic::UncheckedExtrinsic; +/// All migrations executed on runtime upgrade as a nested tuple of types implementing +/// `OnRuntimeUpgrade`. Included migrations must be idempotent. +type Migrations = ( + // v9420 + import_kusama_fellowship::Migration, + // unreleased + pallet_collator_selection::migration::v1::MigrateToV1, +); + +/// Executive: handles dispatch to the various modules. +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + Migrations, +>; + +#[cfg(feature = "runtime-benchmarks")] +mod benches { + frame_benchmarking::define_benchmarks!( + [frame_system, SystemBench::] + [pallet_balances, Balances] + [pallet_message_queue, MessageQueue] + [pallet_multisig, Multisig] + [pallet_proxy, Proxy] + [pallet_session, SessionBench::] + [pallet_utility, Utility] + [pallet_timestamp, Timestamp] + [pallet_collator_selection, CollatorSelection] + [cumulus_pallet_parachain_system, ParachainSystem] + [cumulus_pallet_xcmp_queue, XcmpQueue] + [cumulus_pallet_dmp_queue, DmpQueue] + [pallet_alliance, Alliance] + [pallet_collective, AllianceMotion] + [pallet_xcm, PalletXcmExtrinsicsBenchmark::] + [pallet_preimage, Preimage] + [pallet_scheduler, Scheduler] + [pallet_referenda, FellowshipReferenda] + [pallet_ranked_collective, FellowshipCollective] + [pallet_core_fellowship, FellowshipCore] + [pallet_salary, FellowshipSalary] + [pallet_referenda, AmbassadorReferenda] + [pallet_ranked_collective, AmbassadorCollective] + [pallet_collective_content, AmbassadorContent] + [pallet_core_fellowship, AmbassadorCore] + [pallet_salary, AmbassadorSalary] + ); +} + +impl_runtime_apis! { + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + + fn authorities() -> Vec { + Aura::authorities().into_inner() + } + } + + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + + fn metadata_at_version(version: u32) -> Option { + Runtime::metadata_at_version(version) + } + + fn metadata_versions() -> sp_std::vec::Vec { + Runtime::metadata_versions() + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi + for Runtime + { + fn query_call_info( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::RuntimeDispatchInfo { + TransactionPayment::query_call_info(call, len) + } + fn query_call_fee_details( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_call_fee_details(call, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { + ParachainSystem::collect_collation_info(header) + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { + let weight = Executive::try_runtime_upgrade(checks).unwrap(); + (weight, RuntimeBlockWeights::get().max_block) + } + + fn execute_block( + block: Block, + state_root_check: bool, + signature_check: bool, + select: frame_try_runtime::TryStateSelect, + ) -> Weight { + // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to + // have a backtrace here. + Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap() + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; + + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsWithSystem::storage_info(); + (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; + use sp_storage::TrackedStorageKey; + + use frame_system_benchmarking::Pallet as SystemBench; + impl frame_system_benchmarking::Config for Runtime { + fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); + Ok(()) + } + + fn verify_set_code() { + System::assert_last_event(cumulus_pallet_parachain_system::Event::::ValidationFunctionStored.into()); + } + } + + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + impl cumulus_pallet_session_benchmarking::Config for Runtime {} + + use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; + impl pallet_xcm::benchmarking::Config for Runtime { + fn reachable_dest() -> Option { + Some(Parent.into()) + } + + fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + // Relay/native token can be teleported between Collectives and Relay. + Some(( + MultiAsset { + fun: Fungible(EXISTENTIAL_DEPOSIT), + id: Concrete(Parent.into()) + }.into(), + Parent.into(), + )) + } + + fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { + // Reserve transfers are disabled on Collectives. + None + } + } + + let whitelist: Vec = vec![ + // Block Number + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(), + // Total Issuance + hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(), + // Execution Phase + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(), + // Event Count + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(), + // System Events + hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(), + ]; + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + add_benchmarks!(params, batches); + + if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } + Ok(batches) + } + } + + impl sp_genesis_builder::GenesisBuilder for Runtime { + fn create_default_config() -> Vec { + create_default_config::() + } + + fn build_config(config: Vec) -> sp_genesis_builder::Result { + build_config::(config) + } + } +} + +cumulus_pallet_parachain_system::register_validate_block! { + Runtime = Runtime, + BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/block_weights.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/block_weights.rs new file mode 100644 index 00000000000..e7fdb2aae2a --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/block_weights.rs @@ -0,0 +1,53 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; + + parameter_types! { + /// Importing a block with 0 Extrinsics. + pub const BlockExecutionWeight: Weight = + Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(5_000_000), 0); + } + + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; + + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::BlockExecutionWeight::get(); + + // At least 100 µs. + assert!( + w.ref_time() >= 100u64 * constants::WEIGHT_REF_TIME_PER_MICROS, + "Weight should be at least 100 µs." + ); + // At most 50 ms. + assert!( + w.ref_time() <= 50u64 * constants::WEIGHT_REF_TIME_PER_MILLIS, + "Weight should be at most 50 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_dmp_queue.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_dmp_queue.rs new file mode 100644 index 00000000000..cc41dcd6cbb --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_dmp_queue.rs @@ -0,0 +1,131 @@ +// 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 . + +//! Autogenerated weights for `cumulus_pallet_dmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-10-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=cumulus_pallet_dmp_queue +// --chain=asset-hub-kusama-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_dmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_dmp_queue::WeightInfo for WeightInfo { + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65696` + // Estimated: `69161` + // Minimum execution time: 124_651_000 picoseconds. + Weight::from_parts(127_857_000, 0) + .saturating_add(Weight::from_parts(0, 69161)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65659` + // Estimated: `69124` + // Minimum execution time: 65_684_000 picoseconds. + Weight::from_parts(68_039_000, 0) + .saturating_add(Weight::from_parts(0, 69124)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_overweight_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65726` + // Estimated: `69191` + // Minimum execution time: 117_657_000 picoseconds. + Weight::from_parts(122_035_000, 0) + .saturating_add(Weight::from_parts(0, 69191)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + fn on_idle_overweight_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65689` + // Estimated: `69154` + // Minimum execution time: 59_799_000 picoseconds. + Weight::from_parts(61_354_000, 0) + .saturating_add(Weight::from_parts(0, 69154)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_parachain_system.rs new file mode 100644 index 00000000000..0b7a2fc21cd --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_parachain_system.rs @@ -0,0 +1,80 @@ +// 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. + +//! Autogenerated weights for `cumulus_pallet_parachain_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-03-28, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `i9`, CPU: `13th Gen Intel(R) Core(TM) i9-13900K` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("collectives-polkadot-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --chain +// collectives-polkadot-dev +// --pallet +// cumulus_pallet_parachain_system +// --extrinsic +// * +// --execution +// wasm +// --wasm-execution +// compiled +// --output +// parachains/runtimes/collectives/collectives-polkadot/src/weights +// --steps +// 50 +// --repeat +// 20 + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_parachain_system`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_parachain_system::WeightInfo for WeightInfo { + /// Storage: ParachainSystem LastDmqMqcHead (r:1 w:1) + /// Proof Skipped: ParachainSystem LastDmqMqcHead (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem ReservedDmpWeightOverride (r:1 w:0) + /// Proof Skipped: ParachainSystem ReservedDmpWeightOverride (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: ParachainSystem ProcessedDownwardMessages (r:0 w:1) + /// Proof Skipped: ParachainSystem ProcessedDownwardMessages (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: MessageQueue Pages (r:0 w:16) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + /// The range of component `n` is `[0, 1000]`. + fn enqueue_inbound_downward_messages(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `48` + // Estimated: `8121` + // Minimum execution time: 1_988_000 picoseconds. + Weight::from_parts(2_039_000, 0) + .saturating_add(Weight::from_parts(0, 8121)) + // Standard Error: 30_660 + .saturating_add(Weight::from_parts(24_419_204, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs new file mode 100644 index 00000000000..e68c075bffc --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs @@ -0,0 +1,148 @@ +// 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. + +//! Autogenerated weights for `cumulus_pallet_xcmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-09-15, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `Olivers-MacBook-Pro.local`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --pallet +// cumulus-pallet-xcmp-queue +// --chain +// collectives-polkadot-dev +// --output +// cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/cumulus_pallet_xcmp_queue.rs +// --extrinsic +// + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_xcmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_xcmp_queue::WeightInfo for WeightInfo { + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:1) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn set_config_with_u32() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `1627` + // Minimum execution time: 5_000_000 picoseconds. + Weight::from_parts(6_000_000, 0) + .saturating_add(Weight::from_parts(0, 1627)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:0) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn enqueue_xcmp_message() -> Weight { + // Proof Size summary in bytes: + // Measured: `148` + // Estimated: `3517` + // Minimum execution time: 14_000_000 picoseconds. + Weight::from_parts(14_000_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn suspend_channel() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `1627` + // Minimum execution time: 3_000_000 picoseconds. + Weight::from_parts(3_000_000, 0) + .saturating_add(Weight::from_parts(0, 1627)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn resume_channel() -> Weight { + // Proof Size summary in bytes: + // Measured: `177` + // Estimated: `1662` + // Minimum execution time: 4_000_000 picoseconds. + Weight::from_parts(5_000_000, 0) + .saturating_add(Weight::from_parts(0, 1662)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn take_first_concatenated_xcm() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 44_000_000 picoseconds. + Weight::from_parts(45_000_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Storage: `XcmpQueue::InboundXcmpMessages` (r:1 w:1) + /// Proof: `XcmpQueue::InboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `XcmpQueue::QueueConfig` (r:1 w:0) + /// Proof: `XcmpQueue::QueueConfig` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65777` + // Estimated: `69242` + // Minimum execution time: 60_000_000 picoseconds. + Weight::from_parts(63_000_000, 0) + .saturating_add(Weight::from_parts(0, 69242)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + /// Proof: UNKNOWN KEY `0x7b3237373ffdfeb1cab4222e3b520d6b345d8e88afa015075c945637c07e8f20` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65776` + // Estimated: `69241` + // Minimum execution time: 41_000_000 picoseconds. + Weight::from_parts(43_000_000, 0) + .saturating_add(Weight::from_parts(0, 69241)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/extrinsic_weights.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/extrinsic_weights.rs new file mode 100644 index 00000000000..1a4adb968bb --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/extrinsic_weights.rs @@ -0,0 +1,53 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, Weight}, + }; + + parameter_types! { + /// Executing a NO-OP `System::remarks` Extrinsic. + pub const ExtrinsicBaseWeight: Weight = + Weight::from_parts(constants::WEIGHT_REF_TIME_PER_NANOS.saturating_mul(125_000), 0); + } + + #[cfg(test)] + mod test_weights { + use frame_support::weights::constants; + + /// Checks that the weight exists and is sane. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + let w = super::constants::ExtrinsicBaseWeight::get(); + + // At least 10 µs. + assert!( + w.ref_time() >= 10u64 * constants::WEIGHT_REF_TIME_PER_MICROS, + "Weight should be at least 10 µs." + ); + // At most 1 ms. + assert!( + w.ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/frame_system.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/frame_system.rs new file mode 100644 index 00000000000..b6f1dc8dc08 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/frame_system.rs @@ -0,0 +1,154 @@ +// 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. + +//! Autogenerated weights for `frame_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=frame_system +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `frame_system`. +pub struct WeightInfo(PhantomData); +impl frame_system::WeightInfo for WeightInfo { + /// The range of component `b` is `[0, 3932160]`. + fn remark(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_926_000 picoseconds. + Weight::from_parts(1_929_666, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 0 + .saturating_add(Weight::from_parts(387, 0).saturating_mul(b.into())) + } + /// The range of component `b` is `[0, 3932160]`. + fn remark_with_event(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_221_000 picoseconds. + Weight::from_parts(34_449_539, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 7 + .saturating_add(Weight::from_parts(1_706, 0).saturating_mul(b.into())) + } + /// Storage: `System::Digest` (r:1 w:1) + /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) + /// Proof: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) + fn set_heap_pages() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `1485` + // Minimum execution time: 3_681_000 picoseconds. + Weight::from_parts(3_857_000, 0) + .saturating_add(Weight::from_parts(0, 1485)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ParachainSystem::ValidationData` (r:1 w:0) + /// Proof: `ParachainSystem::ValidationData` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpgradeRestrictionSignal` (r:1 w:0) + /// Proof: `ParachainSystem::UpgradeRestrictionSignal` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingValidationCode` (r:1 w:1) + /// Proof: `ParachainSystem::PendingValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::NewValidationCode` (r:0 w:1) + /// Proof: `ParachainSystem::NewValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::DidSetValidationCode` (r:0 w:1) + /// Proof: `ParachainSystem::DidSetValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn set_code() -> Weight { + // Proof Size summary in bytes: + // Measured: `156` + // Estimated: `1641` + // Minimum execution time: 101_899_621_000 picoseconds. + Weight::from_parts(106_377_672_000, 0) + .saturating_add(Weight::from_parts(0, 1641)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `i` is `[0, 1000]`. + fn set_storage(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_039_000 picoseconds. + Weight::from_parts(2_094_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 2_124 + .saturating_add(Weight::from_parts(754_465, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `i` is `[0, 1000]`. + fn kill_storage(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_103_000 picoseconds. + Weight::from_parts(2_182_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_031 + .saturating_add(Weight::from_parts(570_563, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `p` is `[0, 1000]`. + fn kill_prefix(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `82 + p * (69 ±0)` + // Estimated: `78 + p * (70 ±0)` + // Minimum execution time: 3_728_000 picoseconds. + Weight::from_parts(3_836_000, 0) + .saturating_add(Weight::from_parts(0, 78)) + // Standard Error: 1_802 + .saturating_add(Weight::from_parts(1_199_345, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) + .saturating_add(Weight::from_parts(0, 70).saturating_mul(p.into())) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/mod.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/mod.rs new file mode 100644 index 00000000000..1d877fdbd2b --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/mod.rs @@ -0,0 +1,50 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod block_weights; +pub mod cumulus_pallet_dmp_queue; +pub mod cumulus_pallet_parachain_system; +pub mod cumulus_pallet_xcmp_queue; +pub mod extrinsic_weights; +pub mod frame_system; +pub mod pallet_alliance; +pub mod pallet_balances; +pub mod pallet_collator_selection; +pub mod pallet_collective; +pub mod pallet_collective_content; +pub mod pallet_core_fellowship_ambassador_core; +pub mod pallet_core_fellowship_fellowship_core; +pub mod pallet_message_queue; +pub mod pallet_multisig; +pub mod pallet_preimage; +pub mod pallet_proxy; +pub mod pallet_ranked_collective_ambassador_collective; +pub mod pallet_ranked_collective_fellowship_collective; +pub mod pallet_referenda_ambassador_referenda; +pub mod pallet_referenda_fellowship_referenda; +pub mod pallet_salary_ambassador_salary; +pub mod pallet_salary_fellowship_salary; +pub mod pallet_scheduler; +pub mod pallet_session; +pub mod pallet_timestamp; +pub mod pallet_utility; +pub mod pallet_xcm; +pub mod paritydb_weights; +pub mod rocksdb_weights; + +pub use block_weights::constants::BlockExecutionWeight; +pub use extrinsic_weights::constants::ExtrinsicBaseWeight; +pub use paritydb_weights::constants::ParityDbWeight; +pub use rocksdb_weights::constants::RocksDbWeight; diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_alliance.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_alliance.rs new file mode 100644 index 00000000000..d8ede609a67 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_alliance.rs @@ -0,0 +1,494 @@ +// 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. + +//! Autogenerated weights for `pallet_alliance` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_alliance +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_alliance`. +pub struct WeightInfo(PhantomData); +impl pallet_alliance::WeightInfo for WeightInfo { + /// Storage: `Alliance::Members` (r:1 w:0) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::ProposalOf` (r:1 w:1) + /// Proof: `AllianceMotion::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:1) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalCount` (r:1 w:1) + /// Proof: `AllianceMotion::ProposalCount` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Voting` (r:0 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `b` is `[1, 1024]`. + /// The range of component `m` is `[2, 100]`. + /// The range of component `p` is `[1, 100]`. + fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `439 + m * (32 ±0) + p * (36 ±0)` + // Estimated: `6676 + m * (32 ±0) + p * (36 ±0)` + // Minimum execution time: 32_783_000 picoseconds. + Weight::from_parts(32_174_037, 0) + .saturating_add(Weight::from_parts(0, 6676)) + // Standard Error: 198 + .saturating_add(Weight::from_parts(1_220, 0).saturating_mul(b.into())) + // Standard Error: 2_074 + .saturating_add(Weight::from_parts(40_945, 0).saturating_mul(m.into())) + // Standard Error: 2_048 + .saturating_add(Weight::from_parts(181_087, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 36).saturating_mul(p.into())) + } + /// Storage: `Alliance::Members` (r:1 w:0) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::Voting` (r:1 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `m` is `[5, 100]`. + fn vote(m: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `868 + m * (64 ±0)` + // Estimated: `6676 + m * (64 ±0)` + // Minimum execution time: 28_520_000 picoseconds. + Weight::from_parts(29_661_024, 0) + .saturating_add(Weight::from_parts(0, 6676)) + // Standard Error: 2_336 + .saturating_add(Weight::from_parts(89_873, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) + } + /// Storage: `Alliance::Members` (r:1 w:0) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::Voting` (r:1 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Members` (r:1 w:0) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:1) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalOf` (r:0 w:1) + /// Proof: `AllianceMotion::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `m` is `[4, 100]`. + /// The range of component `p` is `[1, 100]`. + fn close_early_disapproved(m: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `312 + m * (96 ±0) + p * (36 ±0)` + // Estimated: `6676 + m * (97 ±0) + p * (36 ±0)` + // Minimum execution time: 39_353_000 picoseconds. + Weight::from_parts(33_028_008, 0) + .saturating_add(Weight::from_parts(0, 6676)) + // Standard Error: 2_137 + .saturating_add(Weight::from_parts(90_946, 0).saturating_mul(m.into())) + // Standard Error: 2_084 + .saturating_add(Weight::from_parts(175_827, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 97).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 36).saturating_mul(p.into())) + } + /// Storage: `Alliance::Members` (r:1 w:0) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::Voting` (r:1 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Members` (r:1 w:0) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalOf` (r:1 w:1) + /// Proof: `AllianceMotion::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:1) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// The range of component `b` is `[1, 1024]`. + /// The range of component `m` is `[4, 100]`. + /// The range of component `p` is `[1, 100]`. + fn close_early_approved(_b: u32, m: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `762 + m * (96 ±0) + p * (41 ±0)` + // Estimated: `6676 + m * (97 ±0) + p * (40 ±0)` + // Minimum execution time: 52_835_000 picoseconds. + Weight::from_parts(45_963_292, 0) + .saturating_add(Weight::from_parts(0, 6676)) + // Standard Error: 3_189 + .saturating_add(Weight::from_parts(111_627, 0).saturating_mul(m.into())) + // Standard Error: 3_109 + .saturating_add(Weight::from_parts(207_923, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 97).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 40).saturating_mul(p.into())) + } + /// Storage: `Alliance::Members` (r:1 w:0) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::Voting` (r:1 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Members` (r:1 w:0) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Prime` (r:1 w:0) + /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalOf` (r:1 w:1) + /// Proof: `AllianceMotion::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:1) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `Alliance::Rule` (r:0 w:1) + /// Proof: `Alliance::Rule` (`max_values`: Some(1), `max_size`: Some(87), added: 582, mode: `MaxEncodedLen`) + /// The range of component `m` is `[2, 100]`. + /// The range of component `p` is `[1, 100]`. + fn close_disapproved(m: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `518 + m * (96 ±0) + p * (41 ±0)` + // Estimated: `6676 + m * (109 ±0) + p * (43 ±0)` + // Minimum execution time: 49_980_000 picoseconds. + Weight::from_parts(48_110_301, 0) + .saturating_add(Weight::from_parts(0, 6676)) + // Standard Error: 5_057 + .saturating_add(Weight::from_parts(169_065, 0).saturating_mul(m.into())) + // Standard Error: 4_995 + .saturating_add(Weight::from_parts(201_349, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(4)) + .saturating_add(Weight::from_parts(0, 109).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 43).saturating_mul(p.into())) + } + /// Storage: `Alliance::Members` (r:1 w:0) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::Voting` (r:1 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Members` (r:1 w:0) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Prime` (r:1 w:0) + /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:1) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalOf` (r:0 w:1) + /// Proof: `AllianceMotion::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `b` is `[1, 1024]`. + /// The range of component `m` is `[5, 100]`. + /// The range of component `p` is `[1, 100]`. + fn close_approved(_b: u32, m: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `417 + m * (96 ±0) + p * (36 ±0)` + // Estimated: `6676 + m * (96 ±0) + p * (36 ±0)` + // Minimum execution time: 40_646_000 picoseconds. + Weight::from_parts(36_865_909, 0) + .saturating_add(Weight::from_parts(0, 6676)) + // Standard Error: 2_136 + .saturating_add(Weight::from_parts(74_341, 0).saturating_mul(m.into())) + // Standard Error: 2_059 + .saturating_add(Weight::from_parts(170_035, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 96).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 36).saturating_mul(p.into())) + } + /// Storage: `Alliance::Members` (r:2 w:2) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::Members` (r:1 w:1) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// The range of component `m` is `[1, 100]`. + /// The range of component `z` is `[0, 100]`. + fn init_members(m: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `12` + // Estimated: `12362` + // Minimum execution time: 29_710_000 picoseconds. + Weight::from_parts(17_762_170, 0) + .saturating_add(Weight::from_parts(0, 12362)) + // Standard Error: 1_652 + .saturating_add(Weight::from_parts(156_967, 0).saturating_mul(m.into())) + // Standard Error: 1_632 + .saturating_add(Weight::from_parts(130_352, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Alliance::Members` (r:2 w:2) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:0) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `Alliance::DepositOf` (r:200 w:50) + /// Proof: `Alliance::DepositOf` (`max_values`: None, `max_size`: Some(64), added: 2539, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:50 w:50) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::Members` (r:0 w:1) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Prime` (r:0 w:1) + /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// The range of component `x` is `[1, 100]`. + /// The range of component `y` is `[0, 100]`. + /// The range of component `z` is `[0, 50]`. + fn disband(x: u32, y: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + x * (52 ±0) + y * (53 ±0) + z * (250 ±0)` + // Estimated: `12362 + x * (2539 ±0) + y * (2539 ±0) + z * (2603 ±1)` + // Minimum execution time: 294_258_000 picoseconds. + Weight::from_parts(295_116_000, 0) + .saturating_add(Weight::from_parts(0, 12362)) + // Standard Error: 23_663 + .saturating_add(Weight::from_parts(553_978, 0).saturating_mul(x.into())) + // Standard Error: 23_549 + .saturating_add(Weight::from_parts(567_024, 0).saturating_mul(y.into())) + // Standard Error: 47_055 + .saturating_add(Weight::from_parts(15_439_056, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(x.into()))) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(y.into()))) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(z.into()))) + .saturating_add(T::DbWeight::get().writes(4)) + .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(z.into()))) + .saturating_add(Weight::from_parts(0, 2539).saturating_mul(x.into())) + .saturating_add(Weight::from_parts(0, 2539).saturating_mul(y.into())) + .saturating_add(Weight::from_parts(0, 2603).saturating_mul(z.into())) + } + /// Storage: `Alliance::Rule` (r:0 w:1) + /// Proof: `Alliance::Rule` (`max_values`: Some(1), `max_size`: Some(87), added: 582, mode: `MaxEncodedLen`) + fn set_rule() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 8_538_000 picoseconds. + Weight::from_parts(8_752_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Alliance::Announcements` (r:1 w:1) + /// Proof: `Alliance::Announcements` (`max_values`: Some(1), `max_size`: Some(8702), added: 9197, mode: `MaxEncodedLen`) + fn announce() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `10187` + // Minimum execution time: 11_213_000 picoseconds. + Weight::from_parts(11_792_000, 0) + .saturating_add(Weight::from_parts(0, 10187)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Alliance::Announcements` (r:1 w:1) + /// Proof: `Alliance::Announcements` (`max_values`: Some(1), `max_size`: Some(8702), added: 9197, mode: `MaxEncodedLen`) + fn remove_announcement() -> Weight { + // Proof Size summary in bytes: + // Measured: `149` + // Estimated: `10187` + // Minimum execution time: 12_477_000 picoseconds. + Weight::from_parts(12_942_000, 0) + .saturating_add(Weight::from_parts(0, 10187)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Alliance::Members` (r:3 w:1) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `Alliance::UnscrupulousAccounts` (r:1 w:0) + /// Proof: `Alliance::UnscrupulousAccounts` (`max_values`: Some(1), `max_size`: Some(3202), added: 3697, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Alliance::DepositOf` (r:0 w:1) + /// Proof: `Alliance::DepositOf` (`max_values`: None, `max_size`: Some(64), added: 2539, mode: `MaxEncodedLen`) + fn join_alliance() -> Weight { + // Proof Size summary in bytes: + // Measured: `294` + // Estimated: `18048` + // Minimum execution time: 41_517_000 picoseconds. + Weight::from_parts(42_433_000, 0) + .saturating_add(Weight::from_parts(0, 18048)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Alliance::Members` (r:3 w:1) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `Alliance::UnscrupulousAccounts` (r:1 w:0) + /// Proof: `Alliance::UnscrupulousAccounts` (`max_values`: Some(1), `max_size`: Some(3202), added: 3697, mode: `MaxEncodedLen`) + fn nominate_ally() -> Weight { + // Proof Size summary in bytes: + // Measured: `193` + // Estimated: `18048` + // Minimum execution time: 25_950_000 picoseconds. + Weight::from_parts(26_631_000, 0) + .saturating_add(Weight::from_parts(0, 18048)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Alliance::Members` (r:2 w:2) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:0) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Members` (r:0 w:1) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Prime` (r:0 w:1) + /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn elevate_ally() -> Weight { + // Proof Size summary in bytes: + // Measured: `236` + // Estimated: `12362` + // Minimum execution time: 24_470_000 picoseconds. + Weight::from_parts(25_222_000, 0) + .saturating_add(Weight::from_parts(0, 12362)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Alliance::Members` (r:4 w:2) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:0) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Members` (r:0 w:1) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Prime` (r:0 w:1) + /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `Alliance::RetiringMembers` (r:0 w:1) + /// Proof: `Alliance::RetiringMembers` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + fn give_retirement_notice() -> Weight { + // Proof Size summary in bytes: + // Measured: `236` + // Estimated: `23734` + // Minimum execution time: 31_519_000 picoseconds. + Weight::from_parts(32_827_000, 0) + .saturating_add(Weight::from_parts(0, 23734)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `Alliance::RetiringMembers` (r:1 w:1) + /// Proof: `Alliance::RetiringMembers` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `Alliance::Members` (r:1 w:1) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `Alliance::DepositOf` (r:1 w:1) + /// Proof: `Alliance::DepositOf` (`max_values`: None, `max_size`: Some(64), added: 2539, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn retire() -> Weight { + // Proof Size summary in bytes: + // Measured: `517` + // Estimated: `6676` + // Minimum execution time: 38_799_000 picoseconds. + Weight::from_parts(39_634_000, 0) + .saturating_add(Weight::from_parts(0, 6676)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `Alliance::Members` (r:3 w:1) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:0) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `Alliance::DepositOf` (r:1 w:1) + /// Proof: `Alliance::DepositOf` (`max_values`: None, `max_size`: Some(64), added: 2539, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Members` (r:0 w:1) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Prime` (r:0 w:1) + /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn kick_member() -> Weight { + // Proof Size summary in bytes: + // Measured: `643` + // Estimated: `18048` + // Minimum execution time: 137_442_000 picoseconds. + Weight::from_parts(142_142_000, 0) + .saturating_add(Weight::from_parts(0, 18048)) + .saturating_add(T::DbWeight::get().reads(13)) + .saturating_add(T::DbWeight::get().writes(8)) + } + /// Storage: `Alliance::UnscrupulousAccounts` (r:1 w:1) + /// Proof: `Alliance::UnscrupulousAccounts` (`max_values`: Some(1), `max_size`: Some(3202), added: 3697, mode: `MaxEncodedLen`) + /// Storage: `Alliance::UnscrupulousWebsites` (r:1 w:1) + /// Proof: `Alliance::UnscrupulousWebsites` (`max_values`: Some(1), `max_size`: Some(25702), added: 26197, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 100]`. + /// The range of component `l` is `[0, 255]`. + fn add_unscrupulous_items(n: u32, l: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `27187` + // Minimum execution time: 7_189_000 picoseconds. + Weight::from_parts(7_387_000, 0) + .saturating_add(Weight::from_parts(0, 27187)) + // Standard Error: 3_417 + .saturating_add(Weight::from_parts(1_581_413, 0).saturating_mul(n.into())) + // Standard Error: 1_338 + .saturating_add(Weight::from_parts(67_739, 0).saturating_mul(l.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Alliance::UnscrupulousAccounts` (r:1 w:1) + /// Proof: `Alliance::UnscrupulousAccounts` (`max_values`: Some(1), `max_size`: Some(3202), added: 3697, mode: `MaxEncodedLen`) + /// Storage: `Alliance::UnscrupulousWebsites` (r:1 w:1) + /// Proof: `Alliance::UnscrupulousWebsites` (`max_values`: Some(1), `max_size`: Some(25702), added: 26197, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 100]`. + /// The range of component `l` is `[0, 255]`. + fn remove_unscrupulous_items(n: u32, l: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + l * (100 ±0) + n * (289 ±0)` + // Estimated: `27187` + // Minimum execution time: 7_201_000 picoseconds. + Weight::from_parts(7_325_000, 0) + .saturating_add(Weight::from_parts(0, 27187)) + // Standard Error: 183_302 + .saturating_add(Weight::from_parts(16_886_382, 0).saturating_mul(n.into())) + // Standard Error: 71_789 + .saturating_add(Weight::from_parts(352_937, 0).saturating_mul(l.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Alliance::Members` (r:3 w:2) + /// Proof: `Alliance::Members` (`max_values`: None, `max_size`: Some(3211), added: 5686, mode: `MaxEncodedLen`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:0) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Members` (r:0 w:1) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Prime` (r:0 w:1) + /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn abdicate_fellow_status() -> Weight { + // Proof Size summary in bytes: + // Measured: `236` + // Estimated: `18048` + // Minimum execution time: 29_653_000 picoseconds. + Weight::from_parts(30_365_000, 0) + .saturating_add(Weight::from_parts(0, 18048)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_balances.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_balances.rs new file mode 100644 index 00000000000..6c1cf072257 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_balances.rs @@ -0,0 +1,152 @@ +// 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. + +//! Autogenerated weights for `pallet_balances` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_balances +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_balances`. +pub struct WeightInfo(PhantomData); +impl pallet_balances::WeightInfo for WeightInfo { + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_allow_death() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 55_696_000 picoseconds. + Weight::from_parts(56_582_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_keep_alive() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 40_885_000 picoseconds. + Weight::from_parts(41_993_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_set_balance_creating() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `3593` + // Minimum execution time: 14_565_000 picoseconds. + Weight::from_parts(15_080_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_set_balance_killing() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `3593` + // Minimum execution time: 22_158_000 picoseconds. + Weight::from_parts(22_715_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_transfer() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `6196` + // Minimum execution time: 57_957_000 picoseconds. + Weight::from_parts(58_618_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn transfer_all() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `3593` + // Minimum execution time: 52_018_000 picoseconds. + Weight::from_parts(52_795_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + fn force_unreserve() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `3593` + // Minimum execution time: 17_469_000 picoseconds. + Weight::from_parts(18_030_000, 0) + .saturating_add(Weight::from_parts(0, 3593)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `System::Account` (r:999 w:999) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `u` is `[1, 1000]`. + fn upgrade_accounts(u: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + u * (136 ±0)` + // Estimated: `990 + u * (2603 ±0)` + // Minimum execution time: 17_223_000 picoseconds. + Weight::from_parts(17_587_000, 0) + .saturating_add(Weight::from_parts(0, 990)) + // Standard Error: 16_201 + .saturating_add(Weight::from_parts(15_360_967, 0).saturating_mul(u.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(u.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(u.into()))) + .saturating_add(Weight::from_parts(0, 2603).saturating_mul(u.into())) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_collator_selection.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_collator_selection.rs new file mode 100644 index 00000000000..03f3ff602a5 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_collator_selection.rs @@ -0,0 +1,246 @@ +// 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. + +//! Autogenerated weights for `pallet_collator_selection` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_collator_selection +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_collator_selection`. +pub struct WeightInfo(PhantomData); +impl pallet_collator_selection::WeightInfo for WeightInfo { + /// Storage: `Session::NextKeys` (r:20 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::Invulnerables` (r:0 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// The range of component `b` is `[1, 20]`. + fn set_invulnerables(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `163 + b * (79 ±0)` + // Estimated: `1154 + b * (2555 ±0)` + // Minimum execution time: 14_616_000 picoseconds. + Weight::from_parts(12_150_410, 0) + .saturating_add(Weight::from_parts(0, 1154)) + // Standard Error: 6_270 + .saturating_add(Weight::from_parts(3_256_932, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(b.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(Weight::from_parts(0, 2555).saturating_mul(b.into())) + } + /// Storage: `Session::NextKeys` (r:1 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `b` is `[1, 19]`. + /// The range of component `c` is `[1, 99]`. + fn add_invulnerable(b: u32, c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `756 + b * (32 ±0) + c * (53 ±0)` + // Estimated: `6287 + b * (37 ±0) + c * (53 ±0)` + // Minimum execution time: 48_450_000 picoseconds. + Weight::from_parts(51_166_679, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_588 + .saturating_add(Weight::from_parts(167_219, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 37).saturating_mul(b.into())) + .saturating_add(Weight::from_parts(0, 53).saturating_mul(c.into())) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:0) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:1) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// The range of component `b` is `[5, 20]`. + fn remove_invulnerable(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `119 + b * (32 ±0)` + // Estimated: `6287` + // Minimum execution time: 15_830_000 picoseconds. + Weight::from_parts(15_792_847, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 5_343 + .saturating_add(Weight::from_parts(167_955, 0).saturating_mul(b.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::DesiredCandidates` (r:0 w:1) + /// Proof: `CollatorSelection::DesiredCandidates` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn set_desired_candidates() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_424_000 picoseconds. + Weight::from_parts(7_767_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::CandidacyBond` (r:0 w:1) + /// Proof: `CollatorSelection::CandidacyBond` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + fn set_candidacy_bond(_c: u32, _k: u32) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_388_000 picoseconds. + Weight::from_parts(7_677_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::DesiredCandidates` (r:1 w:0) + /// Proof: `CollatorSelection::DesiredCandidates` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `Session::NextKeys` (r:1 w:0) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `CollatorSelection::CandidacyBond` (r:1 w:0) + /// Proof: `CollatorSelection::CandidacyBond` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// The range of component `c` is `[1, 99]`. + fn register_as_candidate(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `736 + c * (52 ±0)` + // Estimated: `6287 + c * (54 ±0)` + // Minimum execution time: 41_241_000 picoseconds. + Weight::from_parts(46_090_319, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_918 + .saturating_add(Weight::from_parts(161_140, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(2)) + .saturating_add(Weight::from_parts(0, 54).saturating_mul(c.into())) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:1) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// The range of component `c` is `[4, 100]`. + fn leave_intent(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 34_221_000 picoseconds. + Weight::from_parts(36_183_872, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_766 + .saturating_add(Weight::from_parts(168_742, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + fn update_bond(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 34_814_000 picoseconds. + Weight::from_parts(36_371_520, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_391 + .saturating_add(Weight::from_parts(201_700, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + fn take_candidate_slot(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `306 + c * (50 ±0)` + // Estimated: `6287` + // Minimum execution time: 34_814_000 picoseconds. + Weight::from_parts(36_371_520, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 2_391 + .saturating_add(Weight::from_parts(201_700, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `System::BlockWeight` (r:1 w:1) + /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:0 w:1) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + fn note_author() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `6196` + // Minimum execution time: 43_910_000 picoseconds. + Weight::from_parts(44_796_000, 0) + .saturating_add(Weight::from_parts(0, 6196)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `CollatorSelection::Candidates` (r:1 w:0) + /// Proof: `CollatorSelection::Candidates` (`max_values`: Some(1), `max_size`: Some(4802), added: 5297, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::LastAuthoredBlock` (r:100 w:0) + /// Proof: `CollatorSelection::LastAuthoredBlock` (`max_values`: None, `max_size`: Some(44), added: 2519, mode: `MaxEncodedLen`) + /// Storage: `CollatorSelection::Invulnerables` (r:1 w:0) + /// Proof: `CollatorSelection::Invulnerables` (`max_values`: Some(1), `max_size`: Some(641), added: 1136, mode: `MaxEncodedLen`) + /// Storage: `System::BlockWeight` (r:1 w:1) + /// Proof: `System::BlockWeight` (`max_values`: Some(1), `max_size`: Some(48), added: 543, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:97 w:97) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `r` is `[1, 100]`. + /// The range of component `c` is `[1, 100]`. + fn new_session(r: u32, c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `2243 + c * (97 ±0) + r * (112 ±0)` + // Estimated: `6287 + c * (2519 ±0) + r * (2603 ±0)` + // Minimum execution time: 17_092_000 picoseconds. + Weight::from_parts(17_635_000, 0) + .saturating_add(Weight::from_parts(0, 6287)) + // Standard Error: 351_635 + .saturating_add(Weight::from_parts(15_162_192, 0).saturating_mul(c.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(c.into()))) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) + .saturating_add(Weight::from_parts(0, 2519).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(0, 2603).saturating_mul(r.into())) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_collective.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_collective.rs new file mode 100644 index 00000000000..9133baa6120 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_collective.rs @@ -0,0 +1,304 @@ +// 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. + +//! Autogenerated weights for `pallet_collective` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_collective +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_collective`. +pub struct WeightInfo(PhantomData); +impl pallet_collective::WeightInfo for WeightInfo { + /// Storage: `AllianceMotion::Members` (r:1 w:1) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:0) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Voting` (r:100 w:100) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Prime` (r:0 w:1) + /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// The range of component `m` is `[0, 100]`. + /// The range of component `n` is `[0, 100]`. + /// The range of component `p` is `[0, 100]`. + fn set_members(m: u32, _n: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0 + m * (3232 ±0) + p * (3190 ±0)` + // Estimated: `15691 + m * (1967 ±23) + p * (4332 ±23)` + // Minimum execution time: 16_410_000 picoseconds. + Weight::from_parts(16_816_000, 0) + .saturating_add(Weight::from_parts(0, 15691)) + // Standard Error: 59_812 + .saturating_add(Weight::from_parts(4_516_537, 0).saturating_mul(m.into())) + // Standard Error: 59_812 + .saturating_add(Weight::from_parts(7_992_168, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) + .saturating_add(T::DbWeight::get().writes(2)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) + .saturating_add(Weight::from_parts(0, 1967).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 4332).saturating_mul(p.into())) + } + /// Storage: `AllianceMotion::Members` (r:1 w:0) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// The range of component `b` is `[2, 1024]`. + /// The range of component `m` is `[1, 100]`. + fn execute(b: u32, m: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `32 + m * (32 ±0)` + // Estimated: `1518 + m * (32 ±0)` + // Minimum execution time: 14_418_000 picoseconds. + Weight::from_parts(13_588_617, 0) + .saturating_add(Weight::from_parts(0, 1518)) + // Standard Error: 21 + .saturating_add(Weight::from_parts(1_711, 0).saturating_mul(b.into())) + // Standard Error: 223 + .saturating_add(Weight::from_parts(13_836, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) + } + /// Storage: `AllianceMotion::Members` (r:1 w:0) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalOf` (r:1 w:0) + /// Proof: `AllianceMotion::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `b` is `[2, 1024]`. + /// The range of component `m` is `[1, 100]`. + fn propose_execute(b: u32, m: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `32 + m * (32 ±0)` + // Estimated: `3498 + m * (32 ±0)` + // Minimum execution time: 17_174_000 picoseconds. + Weight::from_parts(16_192_764, 0) + .saturating_add(Weight::from_parts(0, 3498)) + // Standard Error: 27 + .saturating_add(Weight::from_parts(1_672, 0).saturating_mul(b.into())) + // Standard Error: 280 + .saturating_add(Weight::from_parts(24_343, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(Weight::from_parts(0, 32).saturating_mul(m.into())) + } + /// Storage: `AllianceMotion::Members` (r:1 w:0) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalOf` (r:1 w:1) + /// Proof: `AllianceMotion::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:1) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalCount` (r:1 w:1) + /// Proof: `AllianceMotion::ProposalCount` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Voting` (r:0 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `b` is `[2, 1024]`. + /// The range of component `m` is `[2, 100]`. + /// The range of component `p` is `[1, 100]`. + fn propose_proposed(b: u32, m: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `322 + m * (32 ±0) + p * (36 ±0)` + // Estimated: `3714 + m * (33 ±0) + p * (36 ±0)` + // Minimum execution time: 23_970_000 picoseconds. + Weight::from_parts(23_004_052, 0) + .saturating_add(Weight::from_parts(0, 3714)) + // Standard Error: 123 + .saturating_add(Weight::from_parts(2_728, 0).saturating_mul(b.into())) + // Standard Error: 1_291 + .saturating_add(Weight::from_parts(32_731, 0).saturating_mul(m.into())) + // Standard Error: 1_275 + .saturating_add(Weight::from_parts(199_537, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + .saturating_add(Weight::from_parts(0, 33).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 36).saturating_mul(p.into())) + } + /// Storage: `AllianceMotion::Members` (r:1 w:0) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Voting` (r:1 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `m` is `[5, 100]`. + fn vote(m: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `771 + m * (64 ±0)` + // Estimated: `4235 + m * (64 ±0)` + // Minimum execution time: 25_843_000 picoseconds. + Weight::from_parts(26_092_578, 0) + .saturating_add(Weight::from_parts(0, 4235)) + // Standard Error: 1_785 + .saturating_add(Weight::from_parts(67_298, 0).saturating_mul(m.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(Weight::from_parts(0, 64).saturating_mul(m.into())) + } + /// Storage: `AllianceMotion::Voting` (r:1 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Members` (r:1 w:0) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:1) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalOf` (r:0 w:1) + /// Proof: `AllianceMotion::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `m` is `[4, 100]`. + /// The range of component `p` is `[1, 100]`. + fn close_early_disapproved(m: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `360 + m * (64 ±0) + p * (36 ±0)` + // Estimated: `3805 + m * (65 ±0) + p * (36 ±0)` + // Minimum execution time: 27_543_000 picoseconds. + Weight::from_parts(26_505_473, 0) + .saturating_add(Weight::from_parts(0, 3805)) + // Standard Error: 1_054 + .saturating_add(Weight::from_parts(35_295, 0).saturating_mul(m.into())) + // Standard Error: 1_028 + .saturating_add(Weight::from_parts(190_508, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 65).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 36).saturating_mul(p.into())) + } + /// Storage: `AllianceMotion::Voting` (r:1 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Members` (r:1 w:0) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalOf` (r:1 w:1) + /// Proof: `AllianceMotion::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:1) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// The range of component `b` is `[2, 1024]`. + /// The range of component `m` is `[4, 100]`. + /// The range of component `p` is `[1, 100]`. + fn close_early_approved(b: u32, m: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `662 + b * (1 ±0) + m * (64 ±0) + p * (40 ±0)` + // Estimated: `3979 + b * (1 ±0) + m * (66 ±0) + p * (40 ±0)` + // Minimum execution time: 40_375_000 picoseconds. + Weight::from_parts(34_081_294, 0) + .saturating_add(Weight::from_parts(0, 3979)) + // Standard Error: 196 + .saturating_add(Weight::from_parts(3_796, 0).saturating_mul(b.into())) + // Standard Error: 2_072 + .saturating_add(Weight::from_parts(50_954, 0).saturating_mul(m.into())) + // Standard Error: 2_020 + .saturating_add(Weight::from_parts(246_000, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(b.into())) + .saturating_add(Weight::from_parts(0, 66).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 40).saturating_mul(p.into())) + } + /// Storage: `AllianceMotion::Voting` (r:1 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Members` (r:1 w:0) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Prime` (r:1 w:0) + /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:1) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalOf` (r:0 w:1) + /// Proof: `AllianceMotion::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `m` is `[4, 100]`. + /// The range of component `p` is `[1, 100]`. + fn close_disapproved(m: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `458 + m * (48 ±0) + p * (36 ±0)` + // Estimated: `3898 + m * (49 ±0) + p * (36 ±0)` + // Minimum execution time: 28_793_000 picoseconds. + Weight::from_parts(29_656_832, 0) + .saturating_add(Weight::from_parts(0, 3898)) + // Standard Error: 1_214 + .saturating_add(Weight::from_parts(22_148, 0).saturating_mul(m.into())) + // Standard Error: 1_184 + .saturating_add(Weight::from_parts(189_860, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 49).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 36).saturating_mul(p.into())) + } + /// Storage: `AllianceMotion::Voting` (r:1 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Members` (r:1 w:0) + /// Proof: `AllianceMotion::Members` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Prime` (r:1 w:0) + /// Proof: `AllianceMotion::Prime` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalOf` (r:1 w:1) + /// Proof: `AllianceMotion::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Proposals` (r:1 w:1) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// The range of component `b` is `[2, 1024]`. + /// The range of component `m` is `[4, 100]`. + /// The range of component `p` is `[1, 100]`. + fn close_approved(b: u32, m: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `682 + b * (1 ±0) + m * (64 ±0) + p * (40 ±0)` + // Estimated: `3999 + b * (1 ±0) + m * (66 ±0) + p * (40 ±0)` + // Minimum execution time: 40_887_000 picoseconds. + Weight::from_parts(39_529_567, 0) + .saturating_add(Weight::from_parts(0, 3999)) + // Standard Error: 191 + .saturating_add(Weight::from_parts(2_802, 0).saturating_mul(b.into())) + // Standard Error: 2_021 + .saturating_add(Weight::from_parts(35_956, 0).saturating_mul(m.into())) + // Standard Error: 1_970 + .saturating_add(Weight::from_parts(235_154, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(b.into())) + .saturating_add(Weight::from_parts(0, 66).saturating_mul(m.into())) + .saturating_add(Weight::from_parts(0, 40).saturating_mul(p.into())) + } + /// Storage: `AllianceMotion::Proposals` (r:1 w:1) + /// Proof: `AllianceMotion::Proposals` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::Voting` (r:0 w:1) + /// Proof: `AllianceMotion::Voting` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `AllianceMotion::ProposalOf` (r:0 w:1) + /// Proof: `AllianceMotion::ProposalOf` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `p` is `[1, 100]`. + fn disapprove_proposal(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `189 + p * (32 ±0)` + // Estimated: `1674 + p * (32 ±0)` + // Minimum execution time: 14_040_000 picoseconds. + Weight::from_parts(15_075_964, 0) + .saturating_add(Weight::from_parts(0, 1674)) + // Standard Error: 854 + .saturating_add(Weight::from_parts(159_597, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(Weight::from_parts(0, 32).saturating_mul(p.into())) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_collective_content.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_collective_content.rs new file mode 100644 index 00000000000..6be94db22db --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_collective_content.rs @@ -0,0 +1,93 @@ +// 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. + +//! Autogenerated weights for `pallet_collective_content` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-08-18, STEPS: `10`, REPEAT: `3`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `cob`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/debug/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --steps=10 +// --repeat=3 +// --pallet=pallet_collective_content +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_collective_content`. +pub struct WeightInfo(PhantomData); +impl pallet_collective_content::WeightInfo for WeightInfo { + /// Storage: `AmbassadorContent::Charter` (r:0 w:1) + /// Proof: `AmbassadorContent::Charter` (`max_values`: Some(1), `max_size`: Some(70), added: 565, mode: `MaxEncodedLen`) + fn set_charter() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 99_000_000 picoseconds. + Weight::from_parts(99_000_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `AmbassadorCollective::Members` (r:1 w:0) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorContent::AnnouncementsCount` (r:1 w:1) + /// Proof: `AmbassadorContent::AnnouncementsCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorContent::NextAnnouncementExpireAt` (r:1 w:1) + /// Proof: `AmbassadorContent::NextAnnouncementExpireAt` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorContent::Announcements` (r:0 w:1) + /// Proof: `AmbassadorContent::Announcements` (`max_values`: None, `max_size`: Some(90), added: 2565, mode: `MaxEncodedLen`) + fn announce() -> Weight { + // Proof Size summary in bytes: + // Measured: `285` + // Estimated: `3507` + // Minimum execution time: 273_000_000 picoseconds. + Weight::from_parts(278_000_000, 0) + .saturating_add(Weight::from_parts(0, 3507)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `AmbassadorCollective::Members` (r:1 w:0) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorContent::Announcements` (r:1 w:1) + /// Proof: `AmbassadorContent::Announcements` (`max_values`: None, `max_size`: Some(90), added: 2565, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorContent::AnnouncementsCount` (r:1 w:1) + /// Proof: `AmbassadorContent::AnnouncementsCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn remove_announcement() -> Weight { + // Proof Size summary in bytes: + // Measured: `450` + // Estimated: `3555` + // Minimum execution time: 326_000_000 picoseconds. + Weight::from_parts(338_000_000, 0) + .saturating_add(Weight::from_parts(0, 3555)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_core_fellowship_ambassador_core.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_core_fellowship_ambassador_core.rs new file mode 100644 index 00000000000..f40940a8b25 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_core_fellowship_ambassador_core.rs @@ -0,0 +1,223 @@ +// Copyright 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 . + +//! Autogenerated weights for `pallet_core_fellowship` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-08-11, STEPS: `2`, REPEAT: `2`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `cob`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/release/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_core_fellowship +// --extrinsic=* +// --steps=2 +// --repeat=2 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_core_fellowship`. +pub struct WeightInfo(PhantomData); +impl pallet_core_fellowship::WeightInfo for WeightInfo { + /// Storage: `AmbassadorCore::Params` (r:0 w:1) + /// Proof: `AmbassadorCore::Params` (`max_values`: Some(1), `max_size`: Some(364), added: 859, mode: `MaxEncodedLen`) + fn set_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) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCore::Params` (r:1 w:0) + /// Proof: `AmbassadorCore::Params` (`max_values`: Some(1), `max_size`: Some(364), added: 859, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:1) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IdToIndex` (r:1 w:0) + /// Proof: `AmbassadorCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCore::MemberEvidence` (r:1 w:1) + /// Proof: `AmbassadorCore::MemberEvidence` (`max_values`: None, `max_size`: Some(65581), added: 68056, mode: `MaxEncodedLen`) + fn bump_offboard() -> Weight { + // Proof Size summary in bytes: + // Measured: `66011` + // Estimated: `69046` + // Minimum execution time: 96_000_000 picoseconds. + Weight::from_parts(111_000_000, 0) + .saturating_add(Weight::from_parts(0, 69046)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// 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) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCore::Params` (r:1 w:0) + /// Proof: `AmbassadorCore::Params` (`max_values`: Some(1), `max_size`: Some(364), added: 859, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:1) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IdToIndex` (r:1 w:0) + /// Proof: `AmbassadorCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCore::MemberEvidence` (r:1 w:1) + /// Proof: `AmbassadorCore::MemberEvidence` (`max_values`: None, `max_size`: Some(65581), added: 68056, mode: `MaxEncodedLen`) + fn bump_demote() -> Weight { + // Proof Size summary in bytes: + // Measured: `66121` + // Estimated: `69046` + // Minimum execution time: 99_000_000 picoseconds. + Weight::from_parts(116_000_000, 0) + .saturating_add(Weight::from_parts(0, 69046)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// 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) + /// Proof: `AmbassadorCore::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + fn set_active() -> Weight { + // Proof Size summary in bytes: + // Measured: `360` + // Estimated: `3514` + // Minimum execution time: 21_000_000 picoseconds. + Weight::from_parts(22_000_000, 0) + .saturating_add(Weight::from_parts(0, 3514)) + .saturating_add(T::DbWeight::get().reads(2)) + .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) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:1) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IndexToId` (r:0 w:1) + /// Proof: `AmbassadorCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IdToIndex` (r:0 w:1) + /// Proof: `AmbassadorCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + fn induct() -> Weight { + // Proof Size summary in bytes: + // Measured: `118` + // Estimated: `3514` + // Minimum execution time: 36_000_000 picoseconds. + Weight::from_parts(36_000_000, 0) + .saturating_add(Weight::from_parts(0, 3514)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `AmbassadorCollective::Members` (r:1 w:1) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCore::Member` (r:1 w:1) + /// Proof: `AmbassadorCore::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCore::Params` (r:1 w:0) + /// Proof: `AmbassadorCore::Params` (`max_values`: Some(1), `max_size`: Some(364), added: 859, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:1) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCore::MemberEvidence` (r:1 w:1) + /// Proof: `AmbassadorCore::MemberEvidence` (`max_values`: None, `max_size`: Some(65581), added: 68056, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IndexToId` (r:0 w:1) + /// Proof: `AmbassadorCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IdToIndex` (r:0 w:1) + /// Proof: `AmbassadorCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + fn promote() -> Weight { + // Proof Size summary in bytes: + // Measured: `65989` + // Estimated: `69046` + // Minimum execution time: 95_000_000 picoseconds. + Weight::from_parts(110_000_000, 0) + .saturating_add(Weight::from_parts(0, 69046)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// 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) + /// Proof: `AmbassadorCore::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCore::MemberEvidence` (r:0 w:1) + /// Proof: `AmbassadorCore::MemberEvidence` (`max_values`: None, `max_size`: Some(65581), added: 68056, mode: `MaxEncodedLen`) + fn offboard() -> Weight { + // Proof Size summary in bytes: + // Measured: `331` + // Estimated: `3514` + // Minimum execution time: 21_000_000 picoseconds. + Weight::from_parts(22_000_000, 0) + .saturating_add(Weight::from_parts(0, 3514)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// 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:0) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + fn import() -> Weight { + // Proof Size summary in bytes: + // Measured: `285` + // Estimated: `3514` + // Minimum execution time: 20_000_000 picoseconds. + Weight::from_parts(21_000_000, 0) + .saturating_add(Weight::from_parts(0, 3514)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// 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) + /// Proof: `AmbassadorCore::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCore::MemberEvidence` (r:1 w:1) + /// Proof: `AmbassadorCore::MemberEvidence` (`max_values`: None, `max_size`: Some(65581), added: 68056, mode: `MaxEncodedLen`) + fn approve() -> Weight { + // Proof Size summary in bytes: + // Measured: `65967` + // Estimated: `69046` + // Minimum execution time: 78_000_000 picoseconds. + Weight::from_parts(104_000_000, 0) + .saturating_add(Weight::from_parts(0, 69046)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `AmbassadorCore::Member` (r:1 w:0) + /// Proof: `AmbassadorCore::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCore::MemberEvidence` (r:1 w:1) + /// Proof: `AmbassadorCore::MemberEvidence` (`max_values`: None, `max_size`: Some(65581), added: 68056, mode: `MaxEncodedLen`) + fn submit_evidence() -> Weight { + // Proof Size summary in bytes: + // Measured: `151` + // Estimated: `69046` + // Minimum execution time: 43_000_000 picoseconds. + Weight::from_parts(44_000_000, 0) + .saturating_add(Weight::from_parts(0, 69046)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_core_fellowship_fellowship_core.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_core_fellowship_fellowship_core.rs new file mode 100644 index 00000000000..471ee82ead7 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_core_fellowship_fellowship_core.rs @@ -0,0 +1,222 @@ +// 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. + +//! Autogenerated weights for `pallet_core_fellowship` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-08-11, STEPS: `2`, REPEAT: `2`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `cob`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/release/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_core_fellowship +// --extrinsic=* +// --steps=2 +// --repeat=2 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_core_fellowship`. +pub struct WeightInfo(PhantomData); +impl pallet_core_fellowship::WeightInfo for WeightInfo { + /// Storage: `FellowshipCore::Params` (r:0 w:1) + /// Proof: `FellowshipCore::Params` (`max_values`: Some(1), `max_size`: Some(364), added: 859, mode: `MaxEncodedLen`) + fn set_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) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCore::Params` (r:1 w:0) + /// Proof: `FellowshipCore::Params` (`max_values`: Some(1), `max_size`: Some(364), added: 859, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:1) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IdToIndex` (r:1 w:0) + /// Proof: `FellowshipCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCore::MemberEvidence` (r:1 w:1) + /// Proof: `FellowshipCore::MemberEvidence` (`max_values`: None, `max_size`: Some(65581), added: 68056, mode: `MaxEncodedLen`) + fn bump_offboard() -> Weight { + // Proof Size summary in bytes: + // Measured: `66144` + // Estimated: `69046` + // Minimum execution time: 109_000_000 picoseconds. + Weight::from_parts(125_000_000, 0) + .saturating_add(Weight::from_parts(0, 69046)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// 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) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCore::Params` (r:1 w:0) + /// Proof: `FellowshipCore::Params` (`max_values`: Some(1), `max_size`: Some(364), added: 859, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:1) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IdToIndex` (r:1 w:0) + /// Proof: `FellowshipCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCore::MemberEvidence` (r:1 w:1) + /// Proof: `FellowshipCore::MemberEvidence` (`max_values`: None, `max_size`: Some(65581), added: 68056, mode: `MaxEncodedLen`) + fn bump_demote() -> Weight { + // Proof Size summary in bytes: + // Measured: `66254` + // Estimated: `69046` + // Minimum execution time: 112_000_000 picoseconds. + Weight::from_parts(114_000_000, 0) + .saturating_add(Weight::from_parts(0, 69046)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// 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) + /// Proof: `FellowshipCore::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + fn set_active() -> Weight { + // Proof Size summary in bytes: + // Measured: `493` + // Estimated: `3514` + // Minimum execution time: 22_000_000 picoseconds. + Weight::from_parts(27_000_000, 0) + .saturating_add(Weight::from_parts(0, 3514)) + .saturating_add(T::DbWeight::get().reads(2)) + .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) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:1) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IndexToId` (r:0 w:1) + /// Proof: `FellowshipCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IdToIndex` (r:0 w:1) + /// Proof: `FellowshipCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + fn induct() -> Weight { + // Proof Size summary in bytes: + // Measured: `251` + // Estimated: `3514` + // Minimum execution time: 35_000_000 picoseconds. + Weight::from_parts(36_000_000, 0) + .saturating_add(Weight::from_parts(0, 3514)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `FellowshipCollective::Members` (r:1 w:1) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCore::Member` (r:1 w:1) + /// Proof: `FellowshipCore::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCore::Params` (r:1 w:0) + /// Proof: `FellowshipCore::Params` (`max_values`: Some(1), `max_size`: Some(364), added: 859, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:1) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCore::MemberEvidence` (r:1 w:1) + /// Proof: `FellowshipCore::MemberEvidence` (`max_values`: None, `max_size`: Some(65581), added: 68056, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IndexToId` (r:0 w:1) + /// Proof: `FellowshipCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IdToIndex` (r:0 w:1) + /// Proof: `FellowshipCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + fn promote() -> Weight { + // Proof Size summary in bytes: + // Measured: `66122` + // Estimated: `69046` + // Minimum execution time: 97_000_000 picoseconds. + Weight::from_parts(129_000_000, 0) + .saturating_add(Weight::from_parts(0, 69046)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// 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) + /// Proof: `FellowshipCore::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCore::MemberEvidence` (r:0 w:1) + /// Proof: `FellowshipCore::MemberEvidence` (`max_values`: None, `max_size`: Some(65581), added: 68056, mode: `MaxEncodedLen`) + fn offboard() -> Weight { + // Proof Size summary in bytes: + // Measured: `464` + // Estimated: `3514` + // Minimum execution time: 22_000_000 picoseconds. + Weight::from_parts(22_000_000, 0) + .saturating_add(Weight::from_parts(0, 3514)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// 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:0) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + fn import() -> Weight { + // Proof Size summary in bytes: + // Measured: `418` + // Estimated: `3514` + // Minimum execution time: 20_000_000 picoseconds. + Weight::from_parts(24_000_000, 0) + .saturating_add(Weight::from_parts(0, 3514)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// 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) + /// Proof: `FellowshipCore::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCore::MemberEvidence` (r:1 w:1) + /// Proof: `FellowshipCore::MemberEvidence` (`max_values`: None, `max_size`: Some(65581), added: 68056, mode: `MaxEncodedLen`) + fn approve() -> Weight { + // Proof Size summary in bytes: + // Measured: `66100` + // Estimated: `69046` + // Minimum execution time: 89_000_000 picoseconds. + Weight::from_parts(119_000_000, 0) + .saturating_add(Weight::from_parts(0, 69046)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `FellowshipCore::Member` (r:1 w:0) + /// Proof: `FellowshipCore::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCore::MemberEvidence` (r:1 w:1) + /// Proof: `FellowshipCore::MemberEvidence` (`max_values`: None, `max_size`: Some(65581), added: 68056, mode: `MaxEncodedLen`) + fn submit_evidence() -> Weight { + // Proof Size summary in bytes: + // Measured: `184` + // Estimated: `69046` + // Minimum execution time: 43_000_000 picoseconds. + Weight::from_parts(52_000_000, 0) + .saturating_add(Weight::from_parts(0, 69046)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_message_queue.rs new file mode 100644 index 00000000000..4bd71c4e7d4 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_message_queue.rs @@ -0,0 +1,179 @@ +// 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. + +//! Autogenerated weights for `pallet_message_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-03-24, STEPS: `2`, REPEAT: `1`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `i9`, CPU: `13th Gen Intel(R) Core(TM) i9-13900K` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("collectives-polkadot-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --chain +// collectives-polkadot-dev +// --pallet +// pallet_message_queue +// --extrinsic +// * +// --execution +// wasm +// --wasm-execution +// compiled +// --output +// parachains/runtimes/collectives/collectives-polkadot/src/weights + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `pallet_message_queue`. +pub struct WeightInfo(PhantomData); +impl pallet_message_queue::WeightInfo for WeightInfo { + /// Storage: MessageQueue ServiceHead (r:1 w:0) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: MessageQueue BookStateFor (r:2 w:2) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn ready_ring_knit() -> Weight { + // Proof Size summary in bytes: + // Measured: `189` + // Estimated: `7534` + // Minimum execution time: 11_440_000 picoseconds. + Weight::from_parts(11_440_000, 0) + .saturating_add(Weight::from_parts(0, 7534)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:2 w:2) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + fn ready_ring_unknit() -> Weight { + // Proof Size summary in bytes: + // Measured: `184` + // Estimated: `7534` + // Minimum execution time: 11_077_000 picoseconds. + Weight::from_parts(11_077_000, 0) + .saturating_add(Weight::from_parts(0, 7534)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn service_queue_base() -> Weight { + // Proof Size summary in bytes: + // Measured: `6` + // Estimated: `3517` + // Minimum execution time: 3_977_000 picoseconds. + Weight::from_parts(3_977_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn service_page_base_completion() -> Weight { + // Proof Size summary in bytes: + // Measured: `72` + // Estimated: `69050` + // Minimum execution time: 4_831_000 picoseconds. + Weight::from_parts(4_831_000, 0) + .saturating_add(Weight::from_parts(0, 69050)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn service_page_base_no_completion() -> Weight { + // Proof Size summary in bytes: + // Measured: `72` + // Estimated: `69050` + // Minimum execution time: 5_192_000 picoseconds. + Weight::from_parts(5_192_000, 0) + .saturating_add(Weight::from_parts(0, 69050)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn service_page_item() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 58_750_000 picoseconds. + Weight::from_parts(58_750_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: MessageQueue BookStateFor (r:1 w:0) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn bump_service_head() -> Weight { + // Proof Size summary in bytes: + // Measured: `99` + // Estimated: `5007` + // Minimum execution time: 5_107_000 picoseconds. + Weight::from_parts(5_107_000, 0) + .saturating_add(Weight::from_parts(0, 5007)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn reap_page() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 46_814_000 picoseconds. + Weight::from_parts(46_814_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn execute_overweight_page_removed() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 52_510_000 picoseconds. + Weight::from_parts(52_510_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn execute_overweight_page_updated() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 71_930_000 picoseconds. + Weight::from_parts(71_930_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_multisig.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_multisig.rs new file mode 100644 index 00000000000..a7827b72009 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_multisig.rs @@ -0,0 +1,164 @@ +// 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. + +//! Autogenerated weights for `pallet_multisig` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_multisig +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_multisig`. +pub struct WeightInfo(PhantomData); +impl pallet_multisig::WeightInfo for WeightInfo { + /// The range of component `z` is `[0, 10000]`. + fn as_multi_threshold_1(z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 13_288_000 picoseconds. + Weight::from_parts(14_235_741, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 5 + .saturating_add(Weight::from_parts(500, 0).saturating_mul(z.into())) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_create(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `328 + s * (2 ±0)` + // Estimated: `6811` + // Minimum execution time: 44_865_000 picoseconds. + Weight::from_parts(33_468_056, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_513 + .saturating_add(Weight::from_parts(130_544, 0).saturating_mul(s.into())) + // Standard Error: 14 + .saturating_add(Weight::from_parts(1_422, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[3, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_approve(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `348` + // Estimated: `6811` + // Minimum execution time: 29_284_000 picoseconds. + Weight::from_parts(18_708_967, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 916 + .saturating_add(Weight::from_parts(119_202, 0).saturating_mul(s.into())) + // Standard Error: 8 + .saturating_add(Weight::from_parts(1_447, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + /// The range of component `z` is `[0, 10000]`. + fn as_multi_complete(s: u32, z: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `451 + s * (33 ±0)` + // Estimated: `6811` + // Minimum execution time: 49_462_000 picoseconds. + Weight::from_parts(34_470_286, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_738 + .saturating_add(Weight::from_parts(178_227, 0).saturating_mul(s.into())) + // Standard Error: 17 + .saturating_add(Weight::from_parts(1_644, 0).saturating_mul(z.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_create(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `329 + s * (2 ±0)` + // Estimated: `6811` + // Minimum execution time: 30_749_000 picoseconds. + Weight::from_parts(31_841_438, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 1_033 + .saturating_add(Weight::from_parts(123_126, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn approve_as_multi_approve(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `348` + // Estimated: `6811` + // Minimum execution time: 17_436_000 picoseconds. + Weight::from_parts(18_036_002, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 829 + .saturating_add(Weight::from_parts(109_450, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Multisig::Multisigs` (r:1 w:1) + /// Proof: `Multisig::Multisigs` (`max_values`: None, `max_size`: Some(3346), added: 5821, mode: `MaxEncodedLen`) + /// The range of component `s` is `[2, 100]`. + fn cancel_as_multi(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `520 + s * (1 ±0)` + // Estimated: `6811` + // Minimum execution time: 31_532_000 picoseconds. + Weight::from_parts(32_818_015, 0) + .saturating_add(Weight::from_parts(0, 6811)) + // Standard Error: 977 + .saturating_add(Weight::from_parts(123_121, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_preimage.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_preimage.rs new file mode 100644 index 00000000000..9b45c875818 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_preimage.rs @@ -0,0 +1,232 @@ +// 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. + +//! Autogenerated weights for `pallet_preimage` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_preimage +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_preimage`. +pub struct WeightInfo(PhantomData); +impl pallet_preimage::WeightInfo for WeightInfo { + fn ensure_updated(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `193 + n * (91 ±0)` + // Estimated: `3593 + n * (2566 ±0)` + // Minimum execution time: 2_000_000 picoseconds. + Weight::from_parts(2_000_000, 3593) + // Standard Error: 13_720 + .saturating_add(Weight::from_parts(17_309_199, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(1_u64)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().writes(1_u64)) + .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(n.into()))) + .saturating_add(Weight::from_parts(0, 2566).saturating_mul(n.into())) + } + + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + /// Storage: `Preimage::PreimageFor` (r:0 w:1) + /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) + /// The range of component `s` is `[0, 4194304]`. + fn note_preimage(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `177` + // Estimated: `3556` + // Minimum execution time: 29_323_000 picoseconds. + Weight::from_parts(29_793_000, 0) + .saturating_add(Weight::from_parts(0, 3556)) + // Standard Error: 5 + .saturating_add(Weight::from_parts(2_504, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + /// Storage: `Preimage::PreimageFor` (r:0 w:1) + /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) + /// The range of component `s` is `[0, 4194304]`. + fn note_requested_preimage(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `140` + // Estimated: `3556` + // Minimum execution time: 15_581_000 picoseconds. + Weight::from_parts(15_659_000, 0) + .saturating_add(Weight::from_parts(0, 3556)) + // Standard Error: 4 + .saturating_add(Weight::from_parts(2_500, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + /// Storage: `Preimage::PreimageFor` (r:0 w:1) + /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) + /// The range of component `s` is `[0, 4194304]`. + fn note_no_deposit_preimage(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `140` + // Estimated: `3556` + // Minimum execution time: 15_028_000 picoseconds. + Weight::from_parts(15_150_000, 0) + .saturating_add(Weight::from_parts(0, 3556)) + // Standard Error: 6 + .saturating_add(Weight::from_parts(2_560, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + /// Storage: `Preimage::PreimageFor` (r:0 w:1) + /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) + fn unnote_preimage() -> Weight { + // Proof Size summary in bytes: + // Measured: `323` + // Estimated: `3556` + // Minimum execution time: 55_113_000 picoseconds. + Weight::from_parts(59_127_000, 0) + .saturating_add(Weight::from_parts(0, 3556)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + /// Storage: `Preimage::PreimageFor` (r:0 w:1) + /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) + fn unnote_no_deposit_preimage() -> Weight { + // Proof Size summary in bytes: + // Measured: `178` + // Estimated: `3556` + // Minimum execution time: 38_033_000 picoseconds. + Weight::from_parts(41_203_000, 0) + .saturating_add(Weight::from_parts(0, 3556)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + fn request_preimage() -> Weight { + // Proof Size summary in bytes: + // Measured: `222` + // Estimated: `3556` + // Minimum execution time: 31_482_000 picoseconds. + Weight::from_parts(34_726_000, 0) + .saturating_add(Weight::from_parts(0, 3556)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + fn request_no_deposit_preimage() -> Weight { + // Proof Size summary in bytes: + // Measured: `178` + // Estimated: `3556` + // Minimum execution time: 20_724_000 picoseconds. + Weight::from_parts(22_928_000, 0) + .saturating_add(Weight::from_parts(0, 3556)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + fn request_unnoted_preimage() -> Weight { + // Proof Size summary in bytes: + // Measured: `76` + // Estimated: `3556` + // Minimum execution time: 27_015_000 picoseconds. + Weight::from_parts(29_240_000, 0) + .saturating_add(Weight::from_parts(0, 3556)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + fn request_requested_preimage() -> Weight { + // Proof Size summary in bytes: + // Measured: `140` + // Estimated: `3556` + // Minimum execution time: 10_712_000 picoseconds. + Weight::from_parts(11_317_000, 0) + .saturating_add(Weight::from_parts(0, 3556)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + /// Storage: `Preimage::PreimageFor` (r:0 w:1) + /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `MaxEncodedLen`) + fn unrequest_preimage() -> Weight { + // Proof Size summary in bytes: + // Measured: `178` + // Estimated: `3556` + // Minimum execution time: 34_528_000 picoseconds. + Weight::from_parts(35_982_000, 0) + .saturating_add(Weight::from_parts(0, 3556)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + fn unrequest_unnoted_preimage() -> Weight { + // Proof Size summary in bytes: + // Measured: `140` + // Estimated: `3556` + // Minimum execution time: 11_059_000 picoseconds. + Weight::from_parts(12_458_000, 0) + .saturating_add(Weight::from_parts(0, 3556)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + fn unrequest_multi_referenced_preimage() -> Weight { + // Proof Size summary in bytes: + // Measured: `140` + // Estimated: `3556` + // Minimum execution time: 11_502_000 picoseconds. + Weight::from_parts(12_180_000, 0) + .saturating_add(Weight::from_parts(0, 3556)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_proxy.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_proxy.rs new file mode 100644 index 00000000000..59d9f912bf1 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_proxy.rs @@ -0,0 +1,225 @@ +// 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. + +//! Autogenerated weights for `pallet_proxy` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_proxy +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_proxy`. +pub struct WeightInfo(PhantomData); +impl pallet_proxy::WeightInfo for WeightInfo { + /// Storage: `Proxy::Proxies` (r:1 w:0) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn proxy(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `127 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 15_597_000 picoseconds. + Weight::from_parts(16_231_993, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 1_665 + .saturating_add(Weight::from_parts(29_818, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:0) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// Storage: `Proxy::Announcements` (r:1 w:1) + /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 31]`. + /// The range of component `p` is `[1, 31]`. + fn proxy_announced(a: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `454 + a * (68 ±0) + p * (37 ±0)` + // Estimated: `5698` + // Minimum execution time: 36_685_000 picoseconds. + Weight::from_parts(36_376_358, 0) + .saturating_add(Weight::from_parts(0, 5698)) + // Standard Error: 3_003 + .saturating_add(Weight::from_parts(133_776, 0).saturating_mul(a.into())) + // Standard Error: 3_103 + .saturating_add(Weight::from_parts(60_315, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Proxy::Announcements` (r:1 w:1) + /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 31]`. + /// The range of component `p` is `[1, 31]`. + fn remove_announcement(a: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `369 + a * (68 ±0)` + // Estimated: `5698` + // Minimum execution time: 23_835_000 picoseconds. + Weight::from_parts(24_154_219, 0) + .saturating_add(Weight::from_parts(0, 5698)) + // Standard Error: 1_580 + .saturating_add(Weight::from_parts(125_884, 0).saturating_mul(a.into())) + // Standard Error: 1_632 + .saturating_add(Weight::from_parts(21_563, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Proxy::Announcements` (r:1 w:1) + /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 31]`. + /// The range of component `p` is `[1, 31]`. + fn reject_announcement(a: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `369 + a * (68 ±0)` + // Estimated: `5698` + // Minimum execution time: 23_997_000 picoseconds. + Weight::from_parts(24_301_638, 0) + .saturating_add(Weight::from_parts(0, 5698)) + // Standard Error: 1_658 + .saturating_add(Weight::from_parts(133_005, 0).saturating_mul(a.into())) + // Standard Error: 1_713 + .saturating_add(Weight::from_parts(20_237, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Proxy::Proxies` (r:1 w:0) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// Storage: `Proxy::Announcements` (r:1 w:1) + /// Proof: `Proxy::Announcements` (`max_values`: None, `max_size`: Some(2233), added: 4708, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// The range of component `a` is `[0, 31]`. + /// The range of component `p` is `[1, 31]`. + fn announce(a: u32, p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `386 + a * (68 ±0) + p * (37 ±0)` + // Estimated: `5698` + // Minimum execution time: 33_604_000 picoseconds. + Weight::from_parts(33_322_880, 0) + .saturating_add(Weight::from_parts(0, 5698)) + // Standard Error: 1_840 + .saturating_add(Weight::from_parts(114_037, 0).saturating_mul(a.into())) + // Standard Error: 1_901 + .saturating_add(Weight::from_parts(45_629, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn add_proxy(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `127 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 24_634_000 picoseconds. + Weight::from_parts(25_509_118, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 2_278 + .saturating_add(Weight::from_parts(38_401, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn remove_proxy(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `127 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 24_855_000 picoseconds. + Weight::from_parts(25_753_505, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 1_819 + .saturating_add(Weight::from_parts(44_357, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn remove_proxies(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `127 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 22_211_000 picoseconds. + Weight::from_parts(23_094_124, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 2_597 + .saturating_add(Weight::from_parts(36_725, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[1, 31]`. + fn create_pure(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `139` + // Estimated: `4706` + // Minimum execution time: 26_764_000 picoseconds. + Weight::from_parts(27_667_535, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 1_111 + .saturating_add(Weight::from_parts(3_422, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Proxy::Proxies` (r:1 w:1) + /// Proof: `Proxy::Proxies` (`max_values`: None, `max_size`: Some(1241), added: 3716, mode: `MaxEncodedLen`) + /// The range of component `p` is `[0, 30]`. + fn kill_pure(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `164 + p * (37 ±0)` + // Estimated: `4706` + // Minimum execution time: 22_632_000 picoseconds. + Weight::from_parts(23_678_772, 0) + .saturating_add(Weight::from_parts(0, 4706)) + // Standard Error: 2_136 + .saturating_add(Weight::from_parts(26_492, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_ranked_collective_ambassador_collective.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_ranked_collective_ambassador_collective.rs new file mode 100644 index 00000000000..a6372c4b89d --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_ranked_collective_ambassador_collective.rs @@ -0,0 +1,177 @@ +// Copyright 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 . + +//! Autogenerated weights for `pallet_ranked_collective` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-08-11, STEPS: `2`, REPEAT: `2`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `cob`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/release/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_ranked_collective +// --extrinsic=* +// --steps=2 +// --repeat=2 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_ranked_collective`. +pub struct WeightInfo(PhantomData); +impl pallet_ranked_collective::WeightInfo for WeightInfo { + /// Storage: `AmbassadorCollective::Members` (r:1 w:1) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:1) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IndexToId` (r:0 w:1) + /// Proof: `AmbassadorCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IdToIndex` (r:0 w:1) + /// Proof: `AmbassadorCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + fn add_member() -> Weight { + // Proof Size summary in bytes: + // Measured: `42` + // Estimated: `3507` + // Minimum execution time: 21_000_000 picoseconds. + Weight::from_parts(23_000_000, 0) + .saturating_add(Weight::from_parts(0, 3507)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `AmbassadorCollective::Members` (r:1 w:1) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:11 w:11) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IdToIndex` (r:11 w:11) + /// Proof: `AmbassadorCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IndexToId` (r:11 w:11) + /// Proof: `AmbassadorCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// The range of component `r` is `[0, 10]`. + /// The range of component `r` is `[0, 10]`. + fn remove_member(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `508 + r * (281 ±0)` + // Estimated: `3519 + r * (2529 ±0)` + // Minimum execution time: 34_000_000 picoseconds. + Weight::from_parts(36_500_000, 0) + .saturating_add(Weight::from_parts(0, 3519)) + // Standard Error: 158_113 + .saturating_add(Weight::from_parts(16_000_000, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(r.into()))) + .saturating_add(T::DbWeight::get().writes(4)) + .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(r.into()))) + .saturating_add(Weight::from_parts(0, 2529).saturating_mul(r.into())) + } + /// Storage: `AmbassadorCollective::Members` (r:1 w:1) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:1) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IndexToId` (r:0 w:1) + /// Proof: `AmbassadorCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IdToIndex` (r:0 w:1) + /// Proof: `AmbassadorCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// The range of component `r` is `[0, 10]`. + /// The range of component `r` is `[0, 10]`. + fn promote_member(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `210 + r * (17 ±0)` + // Estimated: `3507` + // Minimum execution time: 25_000_000 picoseconds. + Weight::from_parts(26_000_000, 0) + .saturating_add(Weight::from_parts(0, 3507)) + // Standard Error: 180_277 + .saturating_add(Weight::from_parts(650_000, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `AmbassadorCollective::Members` (r:1 w:1) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:1) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IdToIndex` (r:1 w:1) + /// Proof: `AmbassadorCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::IndexToId` (r:1 w:1) + /// Proof: `AmbassadorCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// The range of component `r` is `[0, 10]`. + /// The range of component `r` is `[0, 10]`. + fn demote_member(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `508 + r * (71 ±0)` + // Estimated: `3519` + // Minimum execution time: 34_000_000 picoseconds. + Weight::from_parts(36_500_000, 0) + .saturating_add(Weight::from_parts(0, 3519)) + // Standard Error: 335_410 + .saturating_add(Weight::from_parts(550_000, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `AmbassadorCollective::Members` (r:1 w:0) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::Voting` (r:1 w:1) + /// Proof: `AmbassadorCollective::Voting` (`max_values`: None, `max_size`: Some(65), added: 2540, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn vote() -> Weight { + // Proof Size summary in bytes: + // Measured: `566` + // Estimated: `317568` + // Minimum execution time: 57_000_000 picoseconds. + Weight::from_parts(60_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:0) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::VotingCleanup` (r:1 w:0) + /// Proof: `AmbassadorCollective::VotingCleanup` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::Voting` (r:100 w:100) + /// Proof: `AmbassadorCollective::Voting` (`max_values`: None, `max_size`: Some(65), added: 2540, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 100]`. + /// The range of component `n` is `[0, 100]`. + fn cleanup_poll(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `209 + n * (52 ±0)` + // Estimated: `4365 + n * (2550 ±0)` + // Minimum execution time: 18_000_000 picoseconds. + Weight::from_parts(18_500_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + // Standard Error: 11_180 + .saturating_add(Weight::from_parts(1_335_000, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) + .saturating_add(Weight::from_parts(0, 2550).saturating_mul(n.into())) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_ranked_collective_fellowship_collective.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_ranked_collective_fellowship_collective.rs new file mode 100644 index 00000000000..9c773c56ac3 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_ranked_collective_fellowship_collective.rs @@ -0,0 +1,176 @@ +// 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. + +//! Autogenerated weights for `pallet_ranked_collective` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-08-11, STEPS: `2`, REPEAT: `2`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `cob`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/release/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_ranked_collective +// --extrinsic=* +// --steps=2 +// --repeat=2 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_ranked_collective`. +pub struct WeightInfo(PhantomData); +impl pallet_ranked_collective::WeightInfo for WeightInfo { + /// Storage: `FellowshipCollective::Members` (r:1 w:1) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:1) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IndexToId` (r:0 w:1) + /// Proof: `FellowshipCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IdToIndex` (r:0 w:1) + /// Proof: `FellowshipCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + fn add_member() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `3507` + // Minimum execution time: 21_000_000 picoseconds. + Weight::from_parts(22_000_000, 0) + .saturating_add(Weight::from_parts(0, 3507)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `FellowshipCollective::Members` (r:1 w:1) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:11 w:11) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IdToIndex` (r:11 w:11) + /// Proof: `FellowshipCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IndexToId` (r:11 w:11) + /// Proof: `FellowshipCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// The range of component `r` is `[0, 10]`. + /// The range of component `r` is `[0, 10]`. + fn remove_member(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `608 + r * (281 ±0)` + // Estimated: `3519 + r * (2529 ±0)` + // Minimum execution time: 35_000_000 picoseconds. + Weight::from_parts(36_500_000, 0) + .saturating_add(Weight::from_parts(0, 3519)) + // Standard Error: 254_950 + .saturating_add(Weight::from_parts(15_900_000, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(r.into()))) + .saturating_add(T::DbWeight::get().writes(4)) + .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(r.into()))) + .saturating_add(Weight::from_parts(0, 2529).saturating_mul(r.into())) + } + /// Storage: `FellowshipCollective::Members` (r:1 w:1) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:1) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IndexToId` (r:0 w:1) + /// Proof: `FellowshipCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IdToIndex` (r:0 w:1) + /// Proof: `FellowshipCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// The range of component `r` is `[0, 10]`. + /// The range of component `r` is `[0, 10]`. + fn promote_member(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `310 + r * (17 ±0)` + // Estimated: `3507` + // Minimum execution time: 25_000_000 picoseconds. + Weight::from_parts(25_500_000, 0) + .saturating_add(Weight::from_parts(0, 3507)) + // Standard Error: 70_710 + .saturating_add(Weight::from_parts(400_000, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `FellowshipCollective::Members` (r:1 w:1) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:1) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IdToIndex` (r:1 w:1) + /// Proof: `FellowshipCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::IndexToId` (r:1 w:1) + /// Proof: `FellowshipCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// The range of component `r` is `[0, 10]`. + /// The range of component `r` is `[0, 10]`. + fn demote_member(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `608 + r * (71 ±0)` + // Estimated: `3519` + // Minimum execution time: 35_000_000 picoseconds. + Weight::from_parts(37_500_000, 0) + .saturating_add(Weight::from_parts(0, 3519)) + // Standard Error: 150_000 + .saturating_add(Weight::from_parts(350_000, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `FellowshipCollective::Members` (r:1 w:0) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::Voting` (r:1 w:1) + /// Proof: `FellowshipCollective::Voting` (`max_values`: None, `max_size`: Some(65), added: 2540, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn vote() -> Weight { + // Proof Size summary in bytes: + // Measured: `700` + // Estimated: `317568` + // Minimum execution time: 57_000_000 picoseconds. + Weight::from_parts(57_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:0) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::VotingCleanup` (r:1 w:0) + /// Proof: `FellowshipCollective::VotingCleanup` (`max_values`: None, `max_size`: Some(114), added: 2589, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::Voting` (r:100 w:100) + /// Proof: `FellowshipCollective::Voting` (`max_values`: None, `max_size`: Some(65), added: 2540, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 100]`. + /// The range of component `n` is `[0, 100]`. + fn cleanup_poll(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `343 + n * (52 ±0)` + // Estimated: `4365 + n * (2550 ±0)` + // Minimum execution time: 18_000_000 picoseconds. + Weight::from_parts(19_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + // Standard Error: 25_000 + .saturating_add(Weight::from_parts(1_395_000, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) + .saturating_add(Weight::from_parts(0, 2550).saturating_mul(n.into())) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_referenda_ambassador_referenda.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_referenda_ambassador_referenda.rs new file mode 100644 index 00000000000..fdc451c5d31 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_referenda_ambassador_referenda.rs @@ -0,0 +1,536 @@ +// Copyright 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 . + +//! Autogenerated weights for `pallet_referenda` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-08-11, STEPS: `2`, REPEAT: `2`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `cob`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/release/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_referenda +// --extrinsic=* +// --steps=2 +// --repeat=2 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_referenda`. +pub struct WeightInfo(PhantomData); +impl pallet_referenda::WeightInfo for WeightInfo { + /// Storage: `AmbassadorCollective::Members` (r:1 w:0) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::ReferendumCount` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:0 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + fn submit() -> Weight { + // Proof Size summary in bytes: + // Measured: `255` + // Estimated: `159279` + // Minimum execution time: 32_000_000 picoseconds. + Weight::from_parts(34_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn place_decision_deposit_preparing() -> Weight { + // Proof Size summary in bytes: + // Measured: `366` + // Estimated: `317568` + // Minimum execution time: 63_000_000 picoseconds. + Weight::from_parts(68_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::DecidingCount` (r:1 w:0) + /// Proof: `AmbassadorReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::TrackQueue` (r:1 w:1) + /// Proof: `AmbassadorReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(171), added: 2646, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn place_decision_deposit_queued() -> Weight { + // Proof Size summary in bytes: + // Measured: `1165` + // Estimated: `159279` + // Minimum execution time: 97_000_000 picoseconds. + Weight::from_parts(123_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::DecidingCount` (r:1 w:0) + /// Proof: `AmbassadorReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::TrackQueue` (r:1 w:1) + /// Proof: `AmbassadorReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(171), added: 2646, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn place_decision_deposit_not_queued() -> Weight { + // Proof Size summary in bytes: + // Measured: `1173` + // Estimated: `159279` + // Minimum execution time: 104_000_000 picoseconds. + Weight::from_parts(111_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::DecidingCount` (r:1 w:1) + /// Proof: `AmbassadorReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:0) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn place_decision_deposit_passing() -> Weight { + // Proof Size summary in bytes: + // Measured: `702` + // Estimated: `317568` + // Minimum execution time: 140_000_000 picoseconds. + Weight::from_parts(150_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::DecidingCount` (r:1 w:1) + /// Proof: `AmbassadorReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:0) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn place_decision_deposit_failing() -> Weight { + // Proof Size summary in bytes: + // Measured: `601` + // Estimated: `317568` + // Minimum execution time: 81_000_000 picoseconds. + Weight::from_parts(82_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + fn refund_decision_deposit() -> Weight { + // Proof Size summary in bytes: + // Measured: `317` + // Estimated: `4365` + // Minimum execution time: 38_000_000 picoseconds. + Weight::from_parts(38_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + fn refund_submission_deposit() -> Weight { + // Proof Size summary in bytes: + // Measured: `167` + // Estimated: `4365` + // Minimum execution time: 17_000_000 picoseconds. + Weight::from_parts(18_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn cancel() -> Weight { + // Proof Size summary in bytes: + // Measured: `311` + // Estimated: `317568` + // Minimum execution time: 44_000_000 picoseconds. + Weight::from_parts(45_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `AmbassadorReferenda::MetadataOf` (r:1 w:0) + /// Proof: `AmbassadorReferenda::MetadataOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + fn kill() -> Weight { + // Proof Size summary in bytes: + // Measured: `626` + // Estimated: `317568` + // Minimum execution time: 183_000_000 picoseconds. + Weight::from_parts(187_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(11)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// Storage: `AmbassadorReferenda::TrackQueue` (r:1 w:0) + /// Proof: `AmbassadorReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(171), added: 2646, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::DecidingCount` (r:1 w:1) + /// Proof: `AmbassadorReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + fn one_fewer_deciding_queue_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `140` + // Estimated: `3636` + // Minimum execution time: 12_000_000 picoseconds. + Weight::from_parts(12_000_000, 0) + .saturating_add(Weight::from_parts(0, 3636)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `AmbassadorReferenda::TrackQueue` (r:1 w:1) + /// Proof: `AmbassadorReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(171), added: 2646, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:0) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn one_fewer_deciding_failing() -> Weight { + // Proof Size summary in bytes: + // Measured: `1412` + // Estimated: `159279` + // Minimum execution time: 88_000_000 picoseconds. + Weight::from_parts(97_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `AmbassadorReferenda::TrackQueue` (r:1 w:1) + /// Proof: `AmbassadorReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(171), added: 2646, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:0) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn one_fewer_deciding_passing() -> Weight { + // Proof Size summary in bytes: + // Measured: `1412` + // Estimated: `159279` + // Minimum execution time: 87_000_000 picoseconds. + Weight::from_parts(92_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:0) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::TrackQueue` (r:1 w:1) + /// Proof: `AmbassadorReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(171), added: 2646, mode: `MaxEncodedLen`) + fn nudge_referendum_requeued_insertion() -> Weight { + // Proof Size summary in bytes: + // Measured: `935` + // Estimated: `4365` + // Minimum execution time: 43_000_000 picoseconds. + Weight::from_parts(46_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:0) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::TrackQueue` (r:1 w:1) + /// Proof: `AmbassadorReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(171), added: 2646, mode: `MaxEncodedLen`) + fn nudge_referendum_requeued_slide() -> Weight { + // Proof Size summary in bytes: + // Measured: `935` + // Estimated: `4365` + // Minimum execution time: 39_000_000 picoseconds. + Weight::from_parts(43_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::DecidingCount` (r:1 w:0) + /// Proof: `AmbassadorReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::TrackQueue` (r:1 w:1) + /// Proof: `AmbassadorReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(171), added: 2646, mode: `MaxEncodedLen`) + fn nudge_referendum_queued() -> Weight { + // Proof Size summary in bytes: + // Measured: `951` + // Estimated: `4365` + // Minimum execution time: 48_000_000 picoseconds. + Weight::from_parts(50_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::DecidingCount` (r:1 w:0) + /// Proof: `AmbassadorReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::TrackQueue` (r:1 w:1) + /// Proof: `AmbassadorReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(171), added: 2646, mode: `MaxEncodedLen`) + fn nudge_referendum_not_queued() -> Weight { + // Proof Size summary in bytes: + // Measured: `959` + // Estimated: `4365` + // Minimum execution time: 42_000_000 picoseconds. + Weight::from_parts(48_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_no_deposit() -> Weight { + // Proof Size summary in bytes: + // Measured: `263` + // Estimated: `159279` + // Minimum execution time: 28_000_000 picoseconds. + Weight::from_parts(30_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_preparing() -> Weight { + // Proof Size summary in bytes: + // Measured: `311` + // Estimated: `159279` + // Minimum execution time: 26_000_000 picoseconds. + Weight::from_parts(28_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + fn nudge_referendum_timed_out() -> Weight { + // Proof Size summary in bytes: + // Measured: `208` + // Estimated: `4365` + // Minimum execution time: 19_000_000 picoseconds. + Weight::from_parts(20_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::DecidingCount` (r:1 w:1) + /// Proof: `AmbassadorReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:0) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_begin_deciding_failing() -> Weight { + // Proof Size summary in bytes: + // Measured: `546` + // Estimated: `159279` + // Minimum execution time: 42_000_000 picoseconds. + Weight::from_parts(46_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::DecidingCount` (r:1 w:1) + /// Proof: `AmbassadorReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:0) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_begin_deciding_passing() -> Weight { + // Proof Size summary in bytes: + // Measured: `647` + // Estimated: `159279` + // Minimum execution time: 87_000_000 picoseconds. + Weight::from_parts(93_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:0) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_begin_confirming() -> Weight { + // Proof Size summary in bytes: + // Measured: `700` + // Estimated: `159279` + // Minimum execution time: 100_000_000 picoseconds. + Weight::from_parts(120_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:0) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_end_confirming() -> Weight { + // Proof Size summary in bytes: + // Measured: `683` + // Estimated: `159279` + // Minimum execution time: 90_000_000 picoseconds. + Weight::from_parts(100_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:0) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_continue_not_confirming() -> Weight { + // Proof Size summary in bytes: + // Measured: `700` + // Estimated: `159279` + // Minimum execution time: 77_000_000 picoseconds. + Weight::from_parts(82_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:0) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_continue_confirming() -> Weight { + // Proof Size summary in bytes: + // Measured: `704` + // Estimated: `159279` + // Minimum execution time: 68_000_000 picoseconds. + Weight::from_parts(77_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:0) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Lookup` (r:1 w:1) + /// Proof: `Scheduler::Lookup` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + fn nudge_referendum_approved() -> Weight { + // Proof Size summary in bytes: + // Measured: `704` + // Estimated: `317568` + // Minimum execution time: 99_000_000 picoseconds. + Weight::from_parts(104_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::MemberCount` (r:1 w:0) + /// Proof: `AmbassadorCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_rejected() -> Weight { + // Proof Size summary in bytes: + // Measured: `700` + // Estimated: `159279` + // Minimum execution time: 87_000_000 picoseconds. + Weight::from_parts(100_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:0) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `Preimage::StatusFor` (r:1 w:0) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::MetadataOf` (r:0 w:1) + /// Proof: `AmbassadorReferenda::MetadataOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + fn set_some_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `419` + // Estimated: `4365` + // Minimum execution time: 23_000_000 picoseconds. + Weight::from_parts(25_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `AmbassadorReferenda::ReferendumInfoFor` (r:1 w:0) + /// Proof: `AmbassadorReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorReferenda::MetadataOf` (r:1 w:1) + /// Proof: `AmbassadorReferenda::MetadataOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + fn clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `285` + // Estimated: `4365` + // Minimum execution time: 20_000_000 picoseconds. + Weight::from_parts(21_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_referenda_fellowship_referenda.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_referenda_fellowship_referenda.rs new file mode 100644 index 00000000000..63f68833795 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_referenda_fellowship_referenda.rs @@ -0,0 +1,535 @@ +// 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. + +//! Autogenerated weights for `pallet_referenda` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-08-11, STEPS: `2`, REPEAT: `2`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `cob`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/release/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_referenda +// --extrinsic=* +// --steps=2 +// --repeat=2 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_referenda`. +pub struct WeightInfo(PhantomData); +impl pallet_referenda::WeightInfo for WeightInfo { + /// Storage: `FellowshipCollective::Members` (r:1 w:0) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::ReferendumCount` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:0 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + fn submit() -> Weight { + // Proof Size summary in bytes: + // Measured: `389` + // Estimated: `159279` + // Minimum execution time: 34_000_000 picoseconds. + Weight::from_parts(36_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn place_decision_deposit_preparing() -> Weight { + // Proof Size summary in bytes: + // Measured: `400` + // Estimated: `317568` + // Minimum execution time: 64_000_000 picoseconds. + Weight::from_parts(67_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::DecidingCount` (r:1 w:0) + /// Proof: `FellowshipReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::TrackQueue` (r:1 w:1) + /// Proof: `FellowshipReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(812), added: 3287, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn place_decision_deposit_queued() -> Weight { + // Proof Size summary in bytes: + // Measured: `2038` + // Estimated: `159279` + // Minimum execution time: 99_000_000 picoseconds. + Weight::from_parts(109_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::DecidingCount` (r:1 w:0) + /// Proof: `FellowshipReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::TrackQueue` (r:1 w:1) + /// Proof: `FellowshipReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(812), added: 3287, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn place_decision_deposit_not_queued() -> Weight { + // Proof Size summary in bytes: + // Measured: `2079` + // Estimated: `159279` + // Minimum execution time: 101_000_000 picoseconds. + Weight::from_parts(111_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::DecidingCount` (r:1 w:1) + /// Proof: `FellowshipReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:0) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn place_decision_deposit_passing() -> Weight { + // Proof Size summary in bytes: + // Measured: `836` + // Estimated: `317568` + // Minimum execution time: 135_000_000 picoseconds. + Weight::from_parts(153_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::DecidingCount` (r:1 w:1) + /// Proof: `FellowshipReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:0) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn place_decision_deposit_failing() -> Weight { + // Proof Size summary in bytes: + // Measured: `735` + // Estimated: `317568` + // Minimum execution time: 78_000_000 picoseconds. + Weight::from_parts(82_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + fn refund_decision_deposit() -> Weight { + // Proof Size summary in bytes: + // Measured: `351` + // Estimated: `4365` + // Minimum execution time: 38_000_000 picoseconds. + Weight::from_parts(39_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + fn refund_submission_deposit() -> Weight { + // Proof Size summary in bytes: + // Measured: `201` + // Estimated: `4365` + // Minimum execution time: 18_000_000 picoseconds. + Weight::from_parts(19_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn cancel() -> Weight { + // Proof Size summary in bytes: + // Measured: `345` + // Estimated: `317568` + // Minimum execution time: 45_000_000 picoseconds. + Weight::from_parts(46_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:1 w:1) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `FellowshipReferenda::MetadataOf` (r:1 w:0) + /// Proof: `FellowshipReferenda::MetadataOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + fn kill() -> Weight { + // Proof Size summary in bytes: + // Measured: `587` + // Estimated: `317568` + // Minimum execution time: 185_000_000 picoseconds. + Weight::from_parts(196_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(11)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// Storage: `FellowshipReferenda::TrackQueue` (r:1 w:0) + /// Proof: `FellowshipReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(812), added: 3287, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::DecidingCount` (r:1 w:1) + /// Proof: `FellowshipReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + fn one_fewer_deciding_queue_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `174` + // Estimated: `4277` + // Minimum execution time: 12_000_000 picoseconds. + Weight::from_parts(15_000_000, 0) + .saturating_add(Weight::from_parts(0, 4277)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `FellowshipReferenda::TrackQueue` (r:1 w:1) + /// Proof: `FellowshipReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(812), added: 3287, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:0) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn one_fewer_deciding_failing() -> Weight { + // Proof Size summary in bytes: + // Measured: `2452` + // Estimated: `159279` + // Minimum execution time: 82_000_000 picoseconds. + Weight::from_parts(90_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `FellowshipReferenda::TrackQueue` (r:1 w:1) + /// Proof: `FellowshipReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(812), added: 3287, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:0) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn one_fewer_deciding_passing() -> Weight { + // Proof Size summary in bytes: + // Measured: `2452` + // Estimated: `159279` + // Minimum execution time: 91_000_000 picoseconds. + Weight::from_parts(99_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:0) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::TrackQueue` (r:1 w:1) + /// Proof: `FellowshipReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(812), added: 3287, mode: `MaxEncodedLen`) + fn nudge_referendum_requeued_insertion() -> Weight { + // Proof Size summary in bytes: + // Measured: `1841` + // Estimated: `4365` + // Minimum execution time: 41_000_000 picoseconds. + Weight::from_parts(44_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:0) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::TrackQueue` (r:1 w:1) + /// Proof: `FellowshipReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(812), added: 3287, mode: `MaxEncodedLen`) + fn nudge_referendum_requeued_slide() -> Weight { + // Proof Size summary in bytes: + // Measured: `1808` + // Estimated: `4365` + // Minimum execution time: 46_000_000 picoseconds. + Weight::from_parts(55_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::DecidingCount` (r:1 w:0) + /// Proof: `FellowshipReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::TrackQueue` (r:1 w:1) + /// Proof: `FellowshipReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(812), added: 3287, mode: `MaxEncodedLen`) + fn nudge_referendum_queued() -> Weight { + // Proof Size summary in bytes: + // Measured: `1824` + // Estimated: `4365` + // Minimum execution time: 49_000_000 picoseconds. + Weight::from_parts(53_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::DecidingCount` (r:1 w:0) + /// Proof: `FellowshipReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::TrackQueue` (r:1 w:1) + /// Proof: `FellowshipReferenda::TrackQueue` (`max_values`: None, `max_size`: Some(812), added: 3287, mode: `MaxEncodedLen`) + fn nudge_referendum_not_queued() -> Weight { + // Proof Size summary in bytes: + // Measured: `1865` + // Estimated: `4365` + // Minimum execution time: 51_000_000 picoseconds. + Weight::from_parts(54_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_no_deposit() -> Weight { + // Proof Size summary in bytes: + // Measured: `297` + // Estimated: `159279` + // Minimum execution time: 28_000_000 picoseconds. + Weight::from_parts(30_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_preparing() -> Weight { + // Proof Size summary in bytes: + // Measured: `345` + // Estimated: `159279` + // Minimum execution time: 28_000_000 picoseconds. + Weight::from_parts(29_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + fn nudge_referendum_timed_out() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `4365` + // Minimum execution time: 20_000_000 picoseconds. + Weight::from_parts(21_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::DecidingCount` (r:1 w:1) + /// Proof: `FellowshipReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:0) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_begin_deciding_failing() -> Weight { + // Proof Size summary in bytes: + // Measured: `680` + // Estimated: `159279` + // Minimum execution time: 42_000_000 picoseconds. + Weight::from_parts(47_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::DecidingCount` (r:1 w:1) + /// Proof: `FellowshipReferenda::DecidingCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:0) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_begin_deciding_passing() -> Weight { + // Proof Size summary in bytes: + // Measured: `781` + // Estimated: `159279` + // Minimum execution time: 90_000_000 picoseconds. + Weight::from_parts(95_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:0) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_begin_confirming() -> Weight { + // Proof Size summary in bytes: + // Measured: `834` + // Estimated: `159279` + // Minimum execution time: 84_000_000 picoseconds. + Weight::from_parts(93_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:0) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_end_confirming() -> Weight { + // Proof Size summary in bytes: + // Measured: `817` + // Estimated: `159279` + // Minimum execution time: 88_000_000 picoseconds. + Weight::from_parts(98_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:0) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_continue_not_confirming() -> Weight { + // Proof Size summary in bytes: + // Measured: `834` + // Estimated: `159279` + // Minimum execution time: 81_000_000 picoseconds. + Weight::from_parts(93_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:0) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_continue_confirming() -> Weight { + // Proof Size summary in bytes: + // Measured: `838` + // Estimated: `159279` + // Minimum execution time: 74_000_000 picoseconds. + Weight::from_parts(77_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:0) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:2 w:2) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Lookup` (r:1 w:1) + /// Proof: `Scheduler::Lookup` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + fn nudge_referendum_approved() -> Weight { + // Proof Size summary in bytes: + // Measured: `838` + // Estimated: `317568` + // Minimum execution time: 105_000_000 picoseconds. + Weight::from_parts(123_000_000, 0) + .saturating_add(Weight::from_parts(0, 317568)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:1) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::MemberCount` (r:1 w:0) + /// Proof: `FellowshipCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + fn nudge_referendum_rejected() -> Weight { + // Proof Size summary in bytes: + // Measured: `834` + // Estimated: `159279` + // Minimum execution time: 90_000_000 picoseconds. + Weight::from_parts(100_000_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:0) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `Preimage::StatusFor` (r:1 w:0) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::MetadataOf` (r:0 w:1) + /// Proof: `FellowshipReferenda::MetadataOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + fn set_some_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `453` + // Estimated: `4365` + // Minimum execution time: 24_000_000 picoseconds. + Weight::from_parts(24_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `FellowshipReferenda::ReferendumInfoFor` (r:1 w:0) + /// Proof: `FellowshipReferenda::ReferendumInfoFor` (`max_values`: None, `max_size`: Some(900), added: 3375, mode: `MaxEncodedLen`) + /// Storage: `FellowshipReferenda::MetadataOf` (r:1 w:1) + /// Proof: `FellowshipReferenda::MetadataOf` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + fn clear_metadata() -> Weight { + // Proof Size summary in bytes: + // Measured: `319` + // Estimated: `4365` + // Minimum execution time: 21_000_000 picoseconds. + Weight::from_parts(23_000_000, 0) + .saturating_add(Weight::from_parts(0, 4365)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_salary_ambassador_salary.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_salary_ambassador_salary.rs new file mode 100644 index 00000000000..0522420f2f5 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_salary_ambassador_salary.rs @@ -0,0 +1,190 @@ +// Copyright 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 . + +//! Autogenerated weights for `pallet_salary` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-08-11, STEPS: `2`, REPEAT: `2`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `cob`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/release/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_salary +// --extrinsic=* +// --steps=2 +// --repeat=2 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_salary`. +pub struct WeightInfo(PhantomData); +impl pallet_salary::WeightInfo for WeightInfo { + /// Storage: `AmbassadorSalary::Status` (r:1 w:1) + /// Proof: `AmbassadorSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + fn init() -> Weight { + // Proof Size summary in bytes: + // Measured: `109` + // Estimated: `1541` + // Minimum execution time: 12_000_000 picoseconds. + Weight::from_parts(14_000_000, 0) + .saturating_add(Weight::from_parts(0, 1541)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `AmbassadorSalary::Status` (r:1 w:1) + /// Proof: `AmbassadorSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + fn bump() -> Weight { + // Proof Size summary in bytes: + // Measured: `191` + // Estimated: `1541` + // Minimum execution time: 15_000_000 picoseconds. + Weight::from_parts(16_000_000, 0) + .saturating_add(Weight::from_parts(0, 1541)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `AmbassadorSalary::Status` (r:1 w:0) + /// Proof: `AmbassadorSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::Members` (r:1 w:0) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorSalary::Claimant` (r:1 w:1) + /// Proof: `AmbassadorSalary::Claimant` (`max_values`: None, `max_size`: Some(86), added: 2561, mode: `MaxEncodedLen`) + fn induct() -> Weight { + // Proof Size summary in bytes: + // Measured: `400` + // Estimated: `3551` + // Minimum execution time: 23_000_000 picoseconds. + Weight::from_parts(23_000_000, 0) + .saturating_add(Weight::from_parts(0, 3551)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `AmbassadorCollective::Members` (r:1 w:0) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorSalary::Status` (r:1 w:1) + /// Proof: `AmbassadorSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorSalary::Claimant` (r:1 w:1) + /// Proof: `AmbassadorSalary::Claimant` (`max_values`: None, `max_size`: Some(86), added: 2561, mode: `MaxEncodedLen`) + fn register() -> Weight { + // Proof Size summary in bytes: + // Measured: `467` + // Estimated: `3551` + // Minimum execution time: 27_000_000 picoseconds. + Weight::from_parts(28_000_000, 0) + .saturating_add(Weight::from_parts(0, 3551)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `AmbassadorSalary::Status` (r:1 w:1) + /// Proof: `AmbassadorSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorSalary::Claimant` (r:1 w:1) + /// Proof: `AmbassadorSalary::Claimant` (`max_values`: None, `max_size`: Some(86), added: 2561, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::Members` (r:1 w:0) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::RelevantMessagingState` (r:1 w:0) + /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) + /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn payout() -> Weight { + // Proof Size summary in bytes: + // Measured: `879` + // Estimated: `4344` + // Minimum execution time: 68_000_000 picoseconds. + Weight::from_parts(72_000_000, 0) + .saturating_add(Weight::from_parts(0, 4344)) + .saturating_add(T::DbWeight::get().reads(10)) + .saturating_add(T::DbWeight::get().writes(7)) + } + /// Storage: `AmbassadorSalary::Status` (r:1 w:1) + /// Proof: `AmbassadorSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorSalary::Claimant` (r:1 w:1) + /// Proof: `AmbassadorSalary::Claimant` (`max_values`: None, `max_size`: Some(86), added: 2561, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorCollective::Members` (r:1 w:0) + /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::RelevantMessagingState` (r:1 w:0) + /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) + /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn payout_other() -> Weight { + // Proof Size summary in bytes: + // Measured: `879` + // Estimated: `4344` + // Minimum execution time: 69_000_000 picoseconds. + Weight::from_parts(70_000_000, 0) + .saturating_add(Weight::from_parts(0, 4344)) + .saturating_add(T::DbWeight::get().reads(10)) + .saturating_add(T::DbWeight::get().writes(7)) + } + /// Storage: `AmbassadorSalary::Status` (r:1 w:1) + /// Proof: `AmbassadorSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + /// Storage: `AmbassadorSalary::Claimant` (r:1 w:1) + /// Proof: `AmbassadorSalary::Claimant` (`max_values`: None, `max_size`: Some(86), added: 2561, mode: `MaxEncodedLen`) + /// Storage: `PolkadotXcm::Queries` (r:1 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn check_payment() -> Weight { + // Proof Size summary in bytes: + // Measured: `479` + // Estimated: `3944` + // Minimum execution time: 27_000_000 picoseconds. + Weight::from_parts(28_000_000, 0) + .saturating_add(Weight::from_parts(0, 3944)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_salary_fellowship_salary.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_salary_fellowship_salary.rs new file mode 100644 index 00000000000..37680b4e5df --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_salary_fellowship_salary.rs @@ -0,0 +1,189 @@ +// 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. + +//! Autogenerated weights for `pallet_salary` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-08-11, STEPS: `2`, REPEAT: `2`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `cob`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/release/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_salary +// --extrinsic=* +// --steps=2 +// --repeat=2 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_salary`. +pub struct WeightInfo(PhantomData); +impl pallet_salary::WeightInfo for WeightInfo { + /// Storage: `FellowshipSalary::Status` (r:1 w:1) + /// Proof: `FellowshipSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + fn init() -> Weight { + // Proof Size summary in bytes: + // Measured: `142` + // Estimated: `1541` + // Minimum execution time: 13_000_000 picoseconds. + Weight::from_parts(17_000_000, 0) + .saturating_add(Weight::from_parts(0, 1541)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `FellowshipSalary::Status` (r:1 w:1) + /// Proof: `FellowshipSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + fn bump() -> Weight { + // Proof Size summary in bytes: + // Measured: `224` + // Estimated: `1541` + // Minimum execution time: 15_000_000 picoseconds. + Weight::from_parts(18_000_000, 0) + .saturating_add(Weight::from_parts(0, 1541)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `FellowshipSalary::Status` (r:1 w:0) + /// Proof: `FellowshipSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::Members` (r:1 w:0) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `FellowshipSalary::Claimant` (r:1 w:1) + /// Proof: `FellowshipSalary::Claimant` (`max_values`: None, `max_size`: Some(86), added: 2561, mode: `MaxEncodedLen`) + fn induct() -> Weight { + // Proof Size summary in bytes: + // Measured: `395` + // Estimated: `3551` + // Minimum execution time: 22_000_000 picoseconds. + Weight::from_parts(25_000_000, 0) + .saturating_add(Weight::from_parts(0, 3551)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `FellowshipCollective::Members` (r:1 w:0) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `FellowshipSalary::Status` (r:1 w:1) + /// Proof: `FellowshipSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + /// Storage: `FellowshipSalary::Claimant` (r:1 w:1) + /// Proof: `FellowshipSalary::Claimant` (`max_values`: None, `max_size`: Some(86), added: 2561, mode: `MaxEncodedLen`) + fn register() -> Weight { + // Proof Size summary in bytes: + // Measured: `462` + // Estimated: `3551` + // Minimum execution time: 26_000_000 picoseconds. + Weight::from_parts(29_000_000, 0) + .saturating_add(Weight::from_parts(0, 3551)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `FellowshipSalary::Status` (r:1 w:1) + /// Proof: `FellowshipSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + /// Storage: `FellowshipSalary::Claimant` (r:1 w:1) + /// Proof: `FellowshipSalary::Claimant` (`max_values`: None, `max_size`: Some(86), added: 2561, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::Members` (r:1 w:0) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::RelevantMessagingState` (r:1 w:0) + /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) + /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn payout() -> Weight { + // Proof Size summary in bytes: + // Measured: `774` + // Estimated: `4239` + // Minimum execution time: 67_000_000 picoseconds. + Weight::from_parts(74_000_000, 0) + .saturating_add(Weight::from_parts(0, 4239)) + .saturating_add(T::DbWeight::get().reads(10)) + .saturating_add(T::DbWeight::get().writes(7)) + } + /// Storage: `FellowshipSalary::Status` (r:1 w:1) + /// Proof: `FellowshipSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + /// Storage: `FellowshipSalary::Claimant` (r:1 w:1) + /// Proof: `FellowshipSalary::Claimant` (`max_values`: None, `max_size`: Some(86), added: 2561, mode: `MaxEncodedLen`) + /// Storage: `FellowshipCollective::Members` (r:1 w:0) + /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::RelevantMessagingState` (r:1 w:0) + /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) + /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn payout_other() -> Weight { + // Proof Size summary in bytes: + // Measured: `774` + // Estimated: `4239` + // Minimum execution time: 66_000_000 picoseconds. + Weight::from_parts(71_000_000, 0) + .saturating_add(Weight::from_parts(0, 4239)) + .saturating_add(T::DbWeight::get().reads(10)) + .saturating_add(T::DbWeight::get().writes(7)) + } + /// Storage: `FellowshipSalary::Status` (r:1 w:1) + /// Proof: `FellowshipSalary::Status` (`max_values`: Some(1), `max_size`: Some(56), added: 551, mode: `MaxEncodedLen`) + /// Storage: `FellowshipSalary::Claimant` (r:1 w:1) + /// Proof: `FellowshipSalary::Claimant` (`max_values`: None, `max_size`: Some(86), added: 2561, mode: `MaxEncodedLen`) + /// Storage: `PolkadotXcm::Queries` (r:1 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn check_payment() -> Weight { + // Proof Size summary in bytes: + // Measured: `512` + // Estimated: `3977` + // Minimum execution time: 26_000_000 picoseconds. + Weight::from_parts(27_000_000, 0) + .saturating_add(Weight::from_parts(0, 3977)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_scheduler.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_scheduler.rs new file mode 100644 index 00000000000..cf5610df665 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_scheduler.rs @@ -0,0 +1,206 @@ +// 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. + +//! Autogenerated weights for `pallet_scheduler` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_scheduler +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_scheduler`. +pub struct WeightInfo(PhantomData); +impl pallet_scheduler::WeightInfo for WeightInfo { + /// Storage: `Scheduler::IncompleteSince` (r:1 w:1) + /// Proof: `Scheduler::IncompleteSince` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn service_agendas_base() -> Weight { + // Proof Size summary in bytes: + // Measured: `31` + // Estimated: `1489` + // Minimum execution time: 3_441_000 picoseconds. + Weight::from_parts(3_604_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + /// The range of component `s` is `[0, 200]`. + fn service_agenda_base(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `77 + s * (177 ±0)` + // Estimated: `159279` + // Minimum execution time: 2_879_000 picoseconds. + Weight::from_parts(2_963_000, 0) + .saturating_add(Weight::from_parts(0, 159279)) + // Standard Error: 3_764 + .saturating_add(Weight::from_parts(909_557, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn service_task_base() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 5_172_000 picoseconds. + Weight::from_parts(5_294_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: `Preimage::PreimageFor` (r:1 w:1) + /// Proof: `Preimage::PreimageFor` (`max_values`: None, `max_size`: Some(4194344), added: 4196819, mode: `Measured`) + /// Storage: `Preimage::StatusFor` (r:1 w:1) + /// Proof: `Preimage::StatusFor` (`max_values`: None, `max_size`: Some(91), added: 2566, mode: `MaxEncodedLen`) + /// The range of component `s` is `[128, 4194304]`. + fn service_task_fetched(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `213 + s * (1 ±0)` + // Estimated: `3678 + s * (1 ±0)` + // Minimum execution time: 19_704_000 picoseconds. + Weight::from_parts(19_903_000, 0) + .saturating_add(Weight::from_parts(0, 3678)) + // Standard Error: 5 + .saturating_add(Weight::from_parts(1_394, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + .saturating_add(Weight::from_parts(0, 1).saturating_mul(s.into())) + } + /// Storage: `Scheduler::Lookup` (r:0 w:1) + /// Proof: `Scheduler::Lookup` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + fn service_task_named() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_359_000 picoseconds. + Weight::from_parts(6_599_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn service_task_periodic() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 5_217_000 picoseconds. + Weight::from_parts(5_333_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + fn execute_dispatch_signed() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_406_000 picoseconds. + Weight::from_parts(2_541_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + fn execute_dispatch_unsigned() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_370_000 picoseconds. + Weight::from_parts(2_561_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + /// The range of component `s` is `[0, 199]`. + fn schedule(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `77 + s * (177 ±0)` + // Estimated: `159279` + // Minimum execution time: 11_784_000 picoseconds. + Weight::from_parts(5_574_404, 0) + .saturating_add(Weight::from_parts(0, 159279)) + // Standard Error: 7_217 + .saturating_add(Weight::from_parts(1_035_248, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Lookup` (r:0 w:1) + /// Proof: `Scheduler::Lookup` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// The range of component `s` is `[1, 200]`. + fn cancel(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `77 + s * (177 ±0)` + // Estimated: `159279` + // Minimum execution time: 16_373_000 picoseconds. + Weight::from_parts(3_088_135, 0) + .saturating_add(Weight::from_parts(0, 159279)) + // Standard Error: 7_095 + .saturating_add(Weight::from_parts(1_745_270, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Scheduler::Lookup` (r:1 w:1) + /// Proof: `Scheduler::Lookup` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + /// The range of component `s` is `[0, 199]`. + fn schedule_named(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `468 + s * (179 ±0)` + // Estimated: `159279` + // Minimum execution time: 14_822_000 picoseconds. + Weight::from_parts(9_591_402, 0) + .saturating_add(Weight::from_parts(0, 159279)) + // Standard Error: 7_151 + .saturating_add(Weight::from_parts(1_058_408, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Scheduler::Lookup` (r:1 w:1) + /// Proof: `Scheduler::Lookup` (`max_values`: None, `max_size`: Some(48), added: 2523, mode: `MaxEncodedLen`) + /// Storage: `Scheduler::Agenda` (r:1 w:1) + /// Proof: `Scheduler::Agenda` (`max_values`: None, `max_size`: Some(155814), added: 158289, mode: `MaxEncodedLen`) + /// The range of component `s` is `[1, 200]`. + fn cancel_named(s: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `509 + s * (179 ±0)` + // Estimated: `159279` + // Minimum execution time: 18_541_000 picoseconds. + Weight::from_parts(6_522_239, 0) + .saturating_add(Weight::from_parts(0, 159279)) + // Standard Error: 8_349 + .saturating_add(Weight::from_parts(1_760_431, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_session.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_session.rs new file mode 100644 index 00000000000..2ac0804df89 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_session.rs @@ -0,0 +1,80 @@ +// 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. + +//! Autogenerated weights for `pallet_session` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_session +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_session`. +pub struct WeightInfo(PhantomData); +impl pallet_session::WeightInfo for WeightInfo { + /// Storage: `Session::NextKeys` (r:1 w:1) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Session::KeyOwner` (r:1 w:1) + /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn set_keys() -> Weight { + // Proof Size summary in bytes: + // Measured: `270` + // Estimated: `3735` + // Minimum execution time: 16_663_000 picoseconds. + Weight::from_parts(17_246_000, 0) + .saturating_add(Weight::from_parts(0, 3735)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `Session::NextKeys` (r:1 w:1) + /// Proof: `Session::NextKeys` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `Session::KeyOwner` (r:0 w:1) + /// Proof: `Session::KeyOwner` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn purge_keys() -> Weight { + // Proof Size summary in bytes: + // Measured: `242` + // Estimated: `3707` + // Minimum execution time: 11_850_000 picoseconds. + Weight::from_parts(12_204_000, 0) + .saturating_add(Weight::from_parts(0, 3707)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_timestamp.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_timestamp.rs new file mode 100644 index 00000000000..ca06f43f92e --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_timestamp.rs @@ -0,0 +1,74 @@ +// 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. + +//! Autogenerated weights for `pallet_timestamp` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_timestamp +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_timestamp`. +pub struct WeightInfo(PhantomData); +impl pallet_timestamp::WeightInfo for WeightInfo { + /// Storage: `Timestamp::Now` (r:1 w:1) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `Aura::CurrentSlot` (r:1 w:0) + /// Proof: `Aura::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + fn set() -> Weight { + // Proof Size summary in bytes: + // Measured: `49` + // Estimated: `1493` + // Minimum execution time: 7_863_000 picoseconds. + Weight::from_parts(8_183_000, 0) + .saturating_add(Weight::from_parts(0, 1493)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn on_finalize() -> Weight { + // Proof Size summary in bytes: + // Measured: `57` + // Estimated: `0` + // Minimum execution time: 3_460_000 picoseconds. + Weight::from_parts(3_577_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_utility.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_utility.rs new file mode 100644 index 00000000000..c60a79d91da --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_utility.rs @@ -0,0 +1,101 @@ +// 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. + +//! Autogenerated weights for `pallet_utility` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=collectives-polkadot-dev +// --wasm-execution=compiled +// --pallet=pallet_utility +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_utility`. +pub struct WeightInfo(PhantomData); +impl pallet_utility::WeightInfo for WeightInfo { + /// The range of component `c` is `[0, 1000]`. + fn batch(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_650_000 picoseconds. + Weight::from_parts(7_474_437, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_625 + .saturating_add(Weight::from_parts(4_996_146, 0).saturating_mul(c.into())) + } + fn as_derivative() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_612_000 picoseconds. + Weight::from_parts(4_774_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// The range of component `c` is `[0, 1000]`. + fn batch_all(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_744_000 picoseconds. + Weight::from_parts(10_889_913, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_281 + .saturating_add(Weight::from_parts(5_218_293, 0).saturating_mul(c.into())) + } + fn dispatch_as() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 8_673_000 picoseconds. + Weight::from_parts(8_980_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// The range of component `c` is `[0, 1000]`. + fn force_batch(c: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_744_000 picoseconds. + Weight::from_parts(7_801_721, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_395 + .saturating_add(Weight::from_parts(5_000_971, 0).saturating_mul(c.into())) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_xcm.rs new file mode 100644 index 00000000000..57e50284147 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/pallet_xcm.rs @@ -0,0 +1,323 @@ +// 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 . + +//! Autogenerated weights for `pallet_xcm` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-11-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-polkadot-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=pallet_xcm +// --chain=collectives-polkadot-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_xcm`. +pub struct WeightInfo(PhantomData); +impl pallet_xcm::WeightInfo for WeightInfo { + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn send() -> Weight { + // Proof Size summary in bytes: + // Measured: `145` + // Estimated: `3610` + // Minimum execution time: 25_050_000 picoseconds. + Weight::from_parts(26_382_000, 0) + .saturating_add(Weight::from_parts(0, 3610)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + fn teleport_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `69` + // Estimated: `1489` + // Minimum execution time: 21_625_000 picoseconds. + Weight::from_parts(22_076_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + .saturating_add(T::DbWeight::get().reads(1)) + } + /// Storage: `Benchmark::Override` (r:0 w:0) + /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn reserve_transfer_assets() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 18_446_744_073_709_551_000 picoseconds. + Weight::from_parts(18_446_744_073_709_551_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: `Benchmark::Override` (r:0 w:0) + /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn execute() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 18_446_744_073_709_551_000 picoseconds. + Weight::from_parts(18_446_744_073_709_551_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: `PolkadotXcm::SupportedVersion` (r:0 w:1) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_xcm_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 7_076_000 picoseconds. + Weight::from_parts(7_378_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:0 w:1) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn force_default_xcm_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_327_000 picoseconds. + Weight::from_parts(2_454_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_subscribe_version_notify() -> Weight { + // Proof Size summary in bytes: + // Measured: `145` + // Estimated: `3610` + // Minimum execution time: 29_080_000 picoseconds. + Weight::from_parts(29_886_000, 0) + .saturating_add(Weight::from_parts(0, 3610)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn force_unsubscribe_version_notify() -> Weight { + // Proof Size summary in bytes: + // Measured: `363` + // Estimated: `3828` + // Minimum execution time: 30_746_000 picoseconds. + Weight::from_parts(31_631_000, 0) + .saturating_add(Weight::from_parts(0, 3828)) + .saturating_add(T::DbWeight::get().reads(7)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PolkadotXcm::XcmExecutionSuspended` (r:0 w:1) + /// Proof: `PolkadotXcm::XcmExecutionSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn force_suspension() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_208_000 picoseconds. + Weight::from_parts(2_341_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `PolkadotXcm::SupportedVersion` (r:4 w:2) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_supported_version() -> Weight { + // Proof Size summary in bytes: + // Measured: `162` + // Estimated: `11052` + // Minimum execution time: 16_239_000 picoseconds. + Weight::from_parts(16_881_000, 0) + .saturating_add(Weight::from_parts(0, 11052)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifiers` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifiers` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_version_notifiers() -> Weight { + // Proof Size summary in bytes: + // Measured: `166` + // Estimated: `11056` + // Minimum execution time: 16_711_000 picoseconds. + Weight::from_parts(16_944_000, 0) + .saturating_add(Weight::from_parts(0, 11056)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:5 w:0) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn already_notified_target() -> Weight { + // Proof Size summary in bytes: + // Measured: `173` + // Estimated: `13538` + // Minimum execution time: 18_142_000 picoseconds. + Weight::from_parts(18_470_000, 0) + .saturating_add(Weight::from_parts(0, 13538)) + .saturating_add(T::DbWeight::get().reads(5)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:2 w:1) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn notify_current_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `212` + // Estimated: `6152` + // Minimum execution time: 27_687_000 picoseconds. + Weight::from_parts(28_250_000, 0) + .saturating_add(Weight::from_parts(0, 6152)) + .saturating_add(T::DbWeight::get().reads(8)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:3 w:0) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn notify_target_migration_fail() -> Weight { + // Proof Size summary in bytes: + // Measured: `206` + // Estimated: `8621` + // Minimum execution time: 9_675_000 picoseconds. + Weight::from_parts(9_992_000, 0) + .saturating_add(Weight::from_parts(0, 8621)) + .saturating_add(T::DbWeight::get().reads(3)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn migrate_version_notify_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `173` + // Estimated: `11063` + // Minimum execution time: 16_597_000 picoseconds. + Weight::from_parts(17_248_000, 0) + .saturating_add(Weight::from_parts(0, 11063)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::VersionNotifyTargets` (r:4 w:2) + /// Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) + /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) + /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) + /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) + /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn migrate_and_notify_old_targets() -> Weight { + // Proof Size summary in bytes: + // Measured: `215` + // Estimated: `11105` + // Minimum execution time: 34_649_000 picoseconds. + Weight::from_parts(35_475_000, 0) + .saturating_add(Weight::from_parts(0, 11105)) + .saturating_add(T::DbWeight::get().reads(10)) + .saturating_add(T::DbWeight::get().writes(4)) + } + /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) + /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `PolkadotXcm::Queries` (r:0 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn new_query() -> Weight { + // Proof Size summary in bytes: + // Measured: `103` + // Estimated: `1588` + // Minimum execution time: 4_619_000 picoseconds. + Weight::from_parts(4_756_000, 0) + .saturating_add(Weight::from_parts(0, 1588)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `PolkadotXcm::Queries` (r:1 w:1) + /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) + fn take_response() -> Weight { + // Proof Size summary in bytes: + // Measured: `7740` + // Estimated: `11205` + // Minimum execution time: 26_721_000 picoseconds. + Weight::from_parts(27_412_000, 0) + .saturating_add(Weight::from_parts(0, 11205)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/paritydb_weights.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/paritydb_weights.rs new file mode 100644 index 00000000000..25679703831 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/paritydb_weights.rs @@ -0,0 +1,63 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; + + parameter_types! { + /// `ParityDB` can be enabled with a feature flag, but is still experimental. These weights + /// are available for brave runtime engineers who may want to try this out as default. + pub const ParityDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 8_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + write: 50_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + }; + } + + #[cfg(test)] + mod test_db_weights { + use super::constants::ParityDbWeight as W; + use frame_support::weights::constants; + + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Write weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/rocksdb_weights.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/rocksdb_weights.rs new file mode 100644 index 00000000000..3dd817aa6f1 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/weights/rocksdb_weights.rs @@ -0,0 +1,63 @@ +// 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. + +pub mod constants { + use frame_support::{ + parameter_types, + weights::{constants, RuntimeDbWeight}, + }; + + parameter_types! { + /// By default, Substrate uses `RocksDB`, so this will be the weight used throughout + /// the runtime. + pub const RocksDbWeight: RuntimeDbWeight = RuntimeDbWeight { + read: 25_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + write: 100_000 * constants::WEIGHT_REF_TIME_PER_NANOS, + }; + } + + #[cfg(test)] + mod test_db_weights { + use super::constants::RocksDbWeight as W; + use frame_support::weights::constants; + + /// Checks that all weights exist and have sane values. + // NOTE: If this test fails but you are sure that the generated values are fine, + // you can delete it. + #[test] + fn sane() { + // At least 1 µs. + assert!( + W::get().reads(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Read weight should be at least 1 µs." + ); + assert!( + W::get().writes(1).ref_time() >= constants::WEIGHT_REF_TIME_PER_MICROS, + "Write weight should be at least 1 µs." + ); + // At most 1 ms. + assert!( + W::get().reads(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Read weight should be at most 1 ms." + ); + assert!( + W::get().writes(1).ref_time() <= constants::WEIGHT_REF_TIME_PER_MILLIS, + "Write weight should be at most 1 ms." + ); + } + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/xcm_config.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/xcm_config.rs new file mode 100644 index 00000000000..71845650bd6 --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/xcm_config.rs @@ -0,0 +1,331 @@ +// 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::{ + AccountId, AllPalletsWithSystem, Balances, BaseDeliveryFee, FeeAssetId, Fellows, ParachainInfo, + ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, + TransactionByteFee, WeightToFee, XcmpQueue, +}; +use frame_support::{ + match_types, parameter_types, + traits::{ConstU32, Contains, Everything, Nothing}, + weights::Weight, +}; +use frame_system::EnsureRoot; +use pallet_xcm::XcmPassthrough; +use parachains_common::{impls::ToStakingPot, xcm_config::ConcreteAssetFromSystem}; +use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; +use xcm::latest::prelude::*; +use xcm_builder::{ + AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, + AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, + DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FixedWeightBounds, IsConcrete, + LocatableAssetId, OriginToPluralityVoice, ParentAsSuperuser, ParentIsPreset, + RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WithComputedOrigin, WithUniqueTopic, +}; +use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; + +const FELLOWSHIP_ADMIN_INDEX: u32 = 1; + +parameter_types! { + pub const DotLocation: MultiLocation = MultiLocation::parent(); + pub const RelayNetwork: Option = Some(NetworkId::Polkadot); + pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into(); + pub UniversalLocation: InteriorMultiLocation = + X2(GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())); + pub CheckingAccount: AccountId = PolkadotXcm::check_account(); + pub const GovernanceLocation: MultiLocation = MultiLocation::parent(); + pub const FellowshipAdminBodyId: BodyId = BodyId::Index(FELLOWSHIP_ADMIN_INDEX); + pub AssetHub: MultiLocation = (Parent, Parachain(1000)).into(); + pub AssetHubUsdtId: AssetId = (PalletInstance(50), GeneralIndex(1984)).into(); + pub UsdtAssetHub: LocatableAssetId = LocatableAssetId { + location: AssetHub::get(), + asset_id: AssetHubUsdtId::get(), + }; + pub DotAssetHub: LocatableAssetId = LocatableAssetId { + location: AssetHub::get(), + asset_id: DotLocation::get().into(), + }; +} + +/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used +/// when determining ownership of accounts for asset transacting and when attempting to use XCM +/// `Transact` in order to determine the dispatch Origin. +pub type LocationToAccountId = ( + // The parent (Relay-chain) origin converts to the parent `AccountId`. + ParentIsPreset, + // Sibling parachain origins convert to AccountId via the `ParaId::into`. + SiblingParachainConvertsVia, + // Straight up local `AccountId32` origins just alias directly to `AccountId`. + AccountId32Aliases, +); + +/// Means for transacting the native currency on this chain. +pub type CurrencyTransactor = CurrencyAdapter< + // Use this currency: + Balances, + // Use this currency when it is a fungible asset matching the given location or name: + IsConcrete, + // Convert an XCM MultiLocation into a local account id: + LocationToAccountId, + // Our chain's account ID type (we can't get away without mentioning it explicitly): + AccountId, + // We don't track any teleports of `Balances`. + (), +>; + +/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, +/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can +/// biases the kind of local `Origin` it will become. +pub type XcmOriginToTransactDispatchOrigin = ( + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, + // Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when + // recognised. + RelayChainAsNative, + // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when + // recognised. + SiblingParachainAsNative, + // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a + // transaction from the Root origin. + ParentAsSuperuser, + // Native signed account converter; this just converts an `AccountId32` origin into a normal + // `RuntimeOrigin::Signed` origin of the same 32-byte value. + SignedAccountId32AsNative, + // Xcm origins can be represented natively under the Xcm pallet's Xcm origin. + XcmPassthrough, +); + +parameter_types! { + /// The amount of weight an XCM operation takes. This is a safe overestimate. + pub const BaseXcmWeight: Weight = Weight::from_parts(1_000_000_000, 1024); + /// A temporary weight value for each XCM instruction. + /// NOTE: This should be removed after we account for PoV weights. + pub const TempFixedXcmWeight: Weight = Weight::from_parts(1_000_000_000, 0); + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; + // Fellows pluralistic body. + pub const FellowsBodyId: BodyId = BodyId::Technical; +} + +match_types! { + pub type ParentOrParentsPlurality: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(Plurality { .. }) } + }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; +} + +/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly +/// account for proof size weights. +/// +/// Calls that are allowed through this filter must: +/// 1. Have a fixed weight; +/// 2. Cannot lead to another call being made; +/// 3. Have a defined proof size weight, e.g. no unbounded vecs in call parameters. +pub struct SafeCallFilter; +impl Contains for SafeCallFilter { + fn contains(call: &RuntimeCall) -> bool { + #[cfg(feature = "runtime-benchmarks")] + { + if matches!(call, RuntimeCall::System(frame_system::Call::remark_with_event { .. })) { + return true + } + } + + matches!( + call, + RuntimeCall::System( + frame_system::Call::set_heap_pages { .. } | + frame_system::Call::set_code { .. } | + frame_system::Call::set_code_without_checks { .. } | + frame_system::Call::kill_prefix { .. }, + ) | RuntimeCall::ParachainSystem(..) | + RuntimeCall::Timestamp(..) | + RuntimeCall::Balances(..) | + RuntimeCall::CollatorSelection( + pallet_collator_selection::Call::set_desired_candidates { .. } | + pallet_collator_selection::Call::set_candidacy_bond { .. } | + pallet_collator_selection::Call::register_as_candidate { .. } | + pallet_collator_selection::Call::leave_intent { .. } | + pallet_collator_selection::Call::set_invulnerables { .. } | + pallet_collator_selection::Call::add_invulnerable { .. } | + pallet_collator_selection::Call::remove_invulnerable { .. }, + ) | RuntimeCall::Session(pallet_session::Call::purge_keys { .. }) | + RuntimeCall::PolkadotXcm(pallet_xcm::Call::force_xcm_version { .. }) | + RuntimeCall::XcmpQueue(..) | + RuntimeCall::MessageQueue(..) | + RuntimeCall::Alliance( + // `init_members` accepts unbounded vecs as arguments, + // but the call can be initiated only by root origin. + pallet_alliance::Call::init_members { .. } | + pallet_alliance::Call::vote { .. } | + pallet_alliance::Call::disband { .. } | + pallet_alliance::Call::set_rule { .. } | + pallet_alliance::Call::announce { .. } | + pallet_alliance::Call::remove_announcement { .. } | + pallet_alliance::Call::join_alliance { .. } | + pallet_alliance::Call::nominate_ally { .. } | + pallet_alliance::Call::elevate_ally { .. } | + pallet_alliance::Call::give_retirement_notice { .. } | + pallet_alliance::Call::retire { .. } | + pallet_alliance::Call::kick_member { .. } | + pallet_alliance::Call::close { .. } | + pallet_alliance::Call::abdicate_fellow_status { .. }, + ) | RuntimeCall::AllianceMotion( + pallet_collective::Call::vote { .. } | + pallet_collective::Call::disapprove_proposal { .. } | + pallet_collective::Call::close { .. }, + ) | RuntimeCall::FellowshipCollective( + pallet_ranked_collective::Call::add_member { .. } | + pallet_ranked_collective::Call::promote_member { .. } | + pallet_ranked_collective::Call::demote_member { .. } | + pallet_ranked_collective::Call::remove_member { .. }, + ) | RuntimeCall::FellowshipCore( + pallet_core_fellowship::Call::bump { .. } | + pallet_core_fellowship::Call::set_params { .. } | + pallet_core_fellowship::Call::set_active { .. } | + pallet_core_fellowship::Call::approve { .. } | + pallet_core_fellowship::Call::induct { .. } | + pallet_core_fellowship::Call::promote { .. } | + pallet_core_fellowship::Call::offboard { .. } | + pallet_core_fellowship::Call::submit_evidence { .. } | + pallet_core_fellowship::Call::import { .. }, + ) + ) + } +} + +pub type Barrier = TrailingSetTopicAsId< + DenyThenTry< + DenyReserveTransferToRelayChain, + ( + // Allow local users to buy weight credit. + TakeWeightCredit, + // Expected responses are OK. + AllowKnownQueryResponses, + // Allow XCMs with some computed origins to pass through. + WithComputedOrigin< + ( + // If the message is one that immediately attempts to pay for execution, then + // allow it. + AllowTopLevelPaidExecutionFrom, + // Parent and its pluralities (i.e. governance bodies) get free execution. + AllowExplicitUnpaidExecutionFrom, + // Subscriptions for version tracking are OK. + AllowSubscriptionsFrom, + ), + UniversalLocation, + ConstU32<8>, + >, + ), + >, +>; + +/// Cases where a remote origin is accepted as trusted Teleporter for a given asset: +/// - DOT with the parent Relay Chain and sibling parachains. +pub type TrustedTeleporters = ConcreteAssetFromSystem; + +pub struct XcmConfig; +impl xcm_executor::Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = XcmRouter; + type AssetTransactor = CurrencyTransactor; + type OriginConverter = XcmOriginToTransactDispatchOrigin; + // Collectives does not recognize a reserve location for any asset. Users must teleport DOT + // where allowed (e.g. with the Relay Chain). + type IsReserve = (); + type IsTeleporter = TrustedTeleporters; + type UniversalLocation = UniversalLocation; + type Barrier = Barrier; + type Weigher = FixedWeightBounds; + type Trader = + UsingComponents>; + type ResponseHandler = PolkadotXcm; + type AssetTrap = PolkadotXcm; + type AssetClaims = PolkadotXcm; + type SubscriptionService = PolkadotXcm; + type PalletInstancesInfo = AllPalletsWithSystem; + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type AssetLocker = (); + type AssetExchanger = (); + type FeeManager = (); + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = WithOriginFilter; + type SafeCallFilter = SafeCallFilter; + type Aliasers = Nothing; +} + +/// Converts a local signed origin into an XCM multilocation. +/// Forms the basis for local origins sending/executing XCMs. +pub type LocalOriginToLocation = SignedToAccountId32; + +pub type PriceForParentDelivery = + ExponentialPrice; + +/// The means for routing XCM messages which are not for local execution into the right message +/// queues. +pub type XcmRouter = WithUniqueTopic<( + // Two routers - use UMP to communicate with the relay chain: + cumulus_primitives_utility::ParentAsUmp, + // ..and XCMP to communicate with the sibling chains. + XcmpQueue, +)>; + +/// Type to convert the Fellows origin to a Plurality `MultiLocation` value. +pub type FellowsToPlurality = OriginToPluralityVoice; + +impl pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + // We only allow the Fellows to send messages. + type SendXcmOrigin = EnsureXcmOrigin; + type XcmRouter = XcmRouter; + // We support local origins dispatching XCM executions in principle... + type ExecuteXcmOrigin = EnsureXcmOrigin; + // ... but disallow generic XCM execution. As a result only teleports are allowed. + type XcmExecuteFilter = Nothing; + type XcmExecutor = XcmExecutor; + type XcmTeleportFilter = Everything; + type XcmReserveTransferFilter = Nothing; // This parachain is not meant as a reserve location. + type Weigher = FixedWeightBounds; + type UniversalLocation = UniversalLocation; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; + type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; + type Currency = Balances; + type CurrencyMatcher = (); + type TrustedLockers = (); + type SovereignAccountOf = LocationToAccountId; + type MaxLockers = ConstU32<8>; + type WeightInfo = crate::weights::pallet_xcm::WeightInfo; + type AdminOrigin = EnsureRoot; + type MaxRemoteLockConsumers = ConstU32<0>; + type RemoteLockConsumerIdentifier = (); +} + +impl cumulus_pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type XcmExecutor = XcmExecutor; +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml b/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml index dd526a9e044..79d6c697b5f 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml @@ -6,14 +6,16 @@ edition.workspace = true license = "Apache-2.0" description = "Westend Collectives Parachain Runtime" -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ + "derive", + "max-encoded-len", +] } hex-literal = { version = "0.4.1" } log = { version = "0.4.20", default-features = false } -scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } +scale-info = { version = "2.10.0", default-features = false, features = [ + "derive", +] } smallvec = "1.11.0" # Substrate @@ -24,7 +26,6 @@ frame-system = { path = "../../../../../substrate/frame/system", default-feature 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 } @@ -38,7 +39,6 @@ pallet-session = { path = "../../../../../substrate/frame/session", default-feat 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 } @@ -72,7 +72,10 @@ westend-runtime-constants = { path = "../../../../../polkadot/runtime/westend/co # 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, features = ["parameterized-consensus-hook"] } +cumulus-pallet-dmp-queue = { path = "../../../../pallets/dmp-queue", default-features = false } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = [ + "parameterized-consensus-hook", +] } 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 } @@ -82,6 +85,7 @@ pallet-collator-selection = { path = "../../../../pallets/collator-selection", d 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 } +testnets-common = { path = "../../../testnets-common", default-features = false } [build-dependencies] substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } @@ -90,8 +94,9 @@ substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", sp-io = { path = "../../../../../substrate/primitives/io", features = ["std"] } [features] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ + "cumulus-pallet-dmp-queue/runtime-benchmarks", "cumulus-pallet-parachain-system/runtime-benchmarks", "cumulus-pallet-session-benchmarking/runtime-benchmarks", "cumulus-pallet-xcmp-queue/runtime-benchmarks", @@ -102,7 +107,6 @@ runtime-benchmarks = [ "frame-system-benchmarking/runtime-benchmarks", "frame-system/runtime-benchmarks", "pallet-alliance/runtime-benchmarks", - "pallet-asset-rate/runtime-benchmarks", "pallet-balances/runtime-benchmarks", "pallet-collator-selection/runtime-benchmarks", "pallet-collective-content/runtime-benchmarks", @@ -117,18 +121,19 @@ runtime-benchmarks = [ "pallet-salary/runtime-benchmarks", "pallet-scheduler/runtime-benchmarks", "pallet-timestamp/runtime-benchmarks", - "pallet-treasury/runtime-benchmarks", "pallet-utility/runtime-benchmarks", "pallet-xcm/runtime-benchmarks", "parachains-common/runtime-benchmarks", "polkadot-parachain-primitives/runtime-benchmarks", "polkadot-runtime-common/runtime-benchmarks", "sp-runtime/runtime-benchmarks", + "testnets-common/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", ] try-runtime = [ "cumulus-pallet-aura-ext/try-runtime", + "cumulus-pallet-dmp-queue/try-runtime", "cumulus-pallet-parachain-system/try-runtime", "cumulus-pallet-xcm/try-runtime", "cumulus-pallet-xcmp-queue/try-runtime", @@ -137,7 +142,6 @@ try-runtime = [ "frame-system/try-runtime", "frame-try-runtime/try-runtime", "pallet-alliance/try-runtime", - "pallet-asset-rate/try-runtime", "pallet-aura/try-runtime", "pallet-authorship/try-runtime", "pallet-balances/try-runtime", @@ -156,7 +160,6 @@ try-runtime = [ "pallet-session/try-runtime", "pallet-timestamp/try-runtime", "pallet-transaction-payment/try-runtime", - "pallet-treasury/try-runtime", "pallet-utility/try-runtime", "pallet-xcm/try-runtime", "parachain-info/try-runtime", @@ -166,6 +169,7 @@ try-runtime = [ std = [ "codec/std", "cumulus-pallet-aura-ext/std", + "cumulus-pallet-dmp-queue/std", "cumulus-pallet-parachain-system/std", "cumulus-pallet-session-benchmarking/std", "cumulus-pallet-xcm/std", @@ -181,7 +185,6 @@ std = [ "frame-try-runtime?/std", "log/std", "pallet-alliance/std", - "pallet-asset-rate/std", "pallet-aura/std", "pallet-authorship/std", "pallet-balances/std", @@ -201,7 +204,6 @@ std = [ "pallet-timestamp/std", "pallet-transaction-payment-rpc-runtime-api/std", "pallet-transaction-payment/std", - "pallet-treasury/std", "pallet-utility/std", "pallet-xcm/std", "parachain-info/std", @@ -225,15 +227,16 @@ std = [ "sp-transaction-pool/std", "sp-version/std", "substrate-wasm-builder", + "testnets-common/std", "westend-runtime-constants/std", "xcm-builder/std", "xcm-executor/std", "xcm/std", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] # A feature that should be enabled when the runtime should be built for on-chain # deployment. This will disable stuff that shouldn't be part of the on-chain wasm # to make it smaller like logging for example. -on-chain-release-build = ["sp-api/disable-logging"] +on-chain-release-build = [ "sp-api/disable-logging" ] 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 3fd108c0a5c..b7412705dde 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs @@ -21,41 +21,28 @@ mod tracks; use crate::{ impls::ToParentTreasury, weights, - xcm_config::{FellowshipAdminBodyId, TreasurerBodyId, UsdtAssetHub}, - AccountId, AssetRate, Balance, Balances, FellowshipReferenda, GovernanceLocation, Preimage, - Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, Scheduler, WestendTreasuryAccount, DAYS, + xcm_config::{FellowshipAdminBodyId, UsdtAssetHub}, + AccountId, Balance, Balances, FellowshipReferenda, GovernanceLocation, Preimage, Runtime, + RuntimeCall, RuntimeEvent, RuntimeOrigin, Scheduler, WestendTreasuryAccount, DAYS, }; use frame_support::{ parameter_types, - traits::{ - EitherOf, EitherOfDiverse, MapSuccess, NeverEnsureOrigin, OriginTrait, TryWithMorphedArg, - }, - PalletId, + traits::{EitherOf, EitherOfDiverse, MapSuccess, OriginTrait, TryWithMorphedArg}, }; -use frame_system::{EnsureRoot, EnsureRootWithSuccess}; +use frame_system::EnsureRootWithSuccess; pub use origins::{ pallet_origins as pallet_fellowship_origins, Architects, EnsureCanPromoteTo, EnsureCanRetainAt, EnsureFellowship, Fellows, Masters, Members, ToVoice, }; use pallet_ranked_collective::EnsureOfRank; use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; -use parachains_common::westend::{account, currency::GRAND}; -use polkadot_runtime_common::impls::{ - LocatableAssetConverter, VersionedLocatableAsset, VersionedMultiLocationConverter, -}; -use sp_arithmetic::Permill; +use parachains_common::{polkadot::account, HOURS}; use sp_core::{ConstU128, ConstU32}; -use sp_runtime::traits::{ - AccountIdConversion, ConstU16, ConvertToValue, IdentityLookup, Replace, TakeFirst, -}; -use westend_runtime_constants::time::HOURS; -use xcm::prelude::*; +use sp_runtime::traits::{AccountIdConversion, ConstU16, ConvertToValue, Replace, TakeFirst}; use xcm_builder::{AliasesIntoAccountId32, PayOverXcm}; #[cfg(feature = "runtime-benchmarks")] use crate::impls::benchmarks::{OpenHrmpChannel, PayWithEnsure}; -#[cfg(feature = "runtime-benchmarks")] -use parachains_common::westend::currency::DOLLARS; /// The Fellowship members' ranks. pub mod ranks { @@ -204,6 +191,8 @@ impl pallet_core_fellowship::Config for Runtime { pub type FellowshipSalaryInstance = pallet_salary::Instance1; +use xcm::prelude::*; + parameter_types! { // The interior location on AssetHub for the paying account. This is the Fellowship Salary // pallet instance (which sits at index 64). This sovereign account will need funding. @@ -247,102 +236,3 @@ impl pallet_salary::Config for Runtime { // Total monthly salary budget. type Budget = ConstU128<{ 100_000 * USDT_UNITS }>; } - -parameter_types! { - pub const FellowshipTreasuryPalletId: PalletId = account::FELLOWSHIP_TREASURY_PALLET_ID; - pub const HundredPercent: Permill = Permill::from_percent(100); - pub const Burn: Permill = Permill::from_percent(0); - pub const MaxBalance: Balance = Balance::max_value(); - // The asset's interior location for the paying account. This is the Fellowship Treasury - // pallet instance (which sits at index 65). - pub FellowshipTreasuryInteriorLocation: InteriorMultiLocation = PalletInstance(65).into(); -} - -#[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, - crate::xcm_config::XcmRouter, - crate::PolkadotXcm, - ConstU32<{ 6 * HOURS }>, - VersionedMultiLocation, - VersionedLocatableAsset, - LocatableAssetConverter, - VersionedMultiLocationConverter, ->; - -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; - type RejectOrigin = EitherOfDiverse< - EnsureRoot, - EitherOfDiverse>, Fellows>, - >; - type RuntimeEvent = RuntimeEvent; - type SpendPeriod = ConstU32<{ 7 * DAYS }>; - type Burn = Burn; - type BurnDestination = (); - type SpendFunds = (); - type MaxApprovals = ConstU32<100>; - type SpendOrigin = EitherOf< - EitherOf< - EnsureRootWithSuccess, - MapSuccess< - EnsureXcm>, - Replace>, - >, - >, - EitherOf< - MapSuccess>>, - MapSuccess>>, - >, - >; - type AssetKind = VersionedLocatableAsset; - type Beneficiary = VersionedMultiLocation; - type BeneficiaryLookup = IdentityLookup; - #[cfg(not(feature = "runtime-benchmarks"))] - type Paymaster = FellowshipTreasuryPaymaster; - #[cfg(feature = "runtime-benchmarks")] - type Paymaster = PayWithEnsure>>; - type BalanceConverter = AssetRate; - type PayoutPeriod = ConstU32<{ 30 * DAYS }>; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::TreasuryArguments< - sp_core::ConstU8<1>, - ConstU32<1000>, - >; -} diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs index 7583c1ea5a7..d6bf8cf5a7e 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs @@ -51,7 +51,7 @@ use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, - traits::{AccountIdConversion, BlakeTwo256, Block as BlockT}, + traits::{AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, Perbill, }; @@ -64,7 +64,7 @@ use sp_version::RuntimeVersion; use codec::{Decode, Encode, MaxEncodedLen}; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, parameter_types, @@ -81,24 +81,20 @@ use frame_system::{ }; pub use parachains_common as common; use parachains_common::{ - impls::DealWithFees, - message_queue::*, - westend::{account::*, consensus::*, currency::*, fee::WeightToFee}, - AccountId, AuraId, Balance, BlockNumber, Hash, Header, Nonce, Signature, - AVERAGE_ON_INITIALIZE_RATIO, DAYS, HOURS, MAXIMUM_BLOCK_WEIGHT, MINUTES, NORMAL_DISPATCH_RATIO, - SLOT_DURATION, + impls::DealWithFees, message_queue::*, AccountId, AuraId, Balance, BlockNumber, Hash, Header, + Nonce, Signature, AVERAGE_ON_INITIALIZE_RATIO, DAYS, HOURS, MAXIMUM_BLOCK_WEIGHT, MINUTES, + NORMAL_DISPATCH_RATIO, SLOT_DURATION, }; use sp_runtime::RuntimeDebug; -use xcm_config::{GovernanceLocation, TreasurerBodyId, XcmOriginToTransactDispatchOrigin}; +use testnets_common::westend::{account::*, consensus::*, currency::*, fee::WeightToFee}; +use xcm_config::{GovernanceLocation, XcmOriginToTransactDispatchOrigin}; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; // Polkadot imports use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; -use polkadot_runtime_common::{ - impls::VersionedLocatableAsset, BlockHashCount, SlowAdjustingFeeUpdate, -}; +use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; use xcm::latest::{prelude::*, BodyId}; use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; @@ -114,7 +110,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_005_000, + spec_version: 1_003_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 5, @@ -158,18 +154,25 @@ parameter_types! { } // Configure FRAME pallets to include in runtime. -#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { + type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = RuntimeBlockWeights; type BlockLength = RuntimeBlockLength; type AccountId = AccountId; type RuntimeCall = RuntimeCall; + type Lookup = AccountIdLookup; type Nonce = Nonce; type Hash = Hash; + type Hashing = BlakeTwo256; type Block = Block; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; type BlockHashCount = BlockHashCount; type DbWeight = RocksDbWeight; type Version = Version; + type PalletInfo = PalletInfo; + type OnNewAccount = (); + type OnKilledAccount = (); type AccountData = pallet_balances::AccountData; type SystemWeightInfo = weights::frame_system::WeightInfo; type SS58Prefix = ConstU16<0>; @@ -327,7 +330,6 @@ impl InstanceFilter for ProxyType { RuntimeCall::FellowshipReferenda { .. } | RuntimeCall::FellowshipCore { .. } | RuntimeCall::FellowshipSalary { .. } | - RuntimeCall::FellowshipTreasury { .. } | RuntimeCall::Utility { .. } | RuntimeCall::Multisig { .. } ), @@ -454,6 +456,12 @@ parameter_types! { pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent; } +impl cumulus_pallet_dmp_queue::Config for Runtime { + type WeightInfo = weights::cumulus_pallet_dmp_queue::WeightInfo; + type RuntimeEvent = RuntimeEvent; + type DmpSink = frame_support::traits::EnqueueWithOrigin; +} + pub const PERIOD: u32 = 6 * HOURS; pub const OFFSET: u32 = 0; @@ -616,21 +624,6 @@ impl pallet_preimage::Config for Runtime { >; } -impl pallet_asset_rate::Config for Runtime { - type WeightInfo = weights::pallet_asset_rate::WeightInfo; - type RuntimeEvent = RuntimeEvent; - type CreateOrigin = EitherOfDiverse< - EnsureRoot, - EitherOfDiverse>, Fellows>, - >; - type RemoveOrigin = Self::CreateOrigin; - type UpdateOrigin = Self::CreateOrigin; - type Currency = Balances; - type AssetKind = VersionedLocatableAsset; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = polkadot_runtime_common::impls::benchmarks::AssetRateArguments; -} - // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( pub enum Runtime @@ -658,6 +651,7 @@ construct_runtime!( XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 31, CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, + DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 33, MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event} = 34, // Handy utilities. @@ -666,7 +660,6 @@ construct_runtime!( Proxy: pallet_proxy::{Pallet, Call, Storage, Event} = 42, Preimage: pallet_preimage::{Pallet, Call, Storage, Event, HoldReason} = 43, Scheduler: pallet_scheduler::{Pallet, Call, Storage, Event} = 44, - AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event} = 45, // The main stage. @@ -684,8 +677,6 @@ construct_runtime!( FellowshipCore: pallet_core_fellowship::::{Pallet, Call, Storage, Event} = 63, // pub type FellowshipSalaryInstance = pallet_salary::Instance1; FellowshipSalary: pallet_salary::::{Pallet, Call, Storage, Event} = 64, - // pub type FellowshipTreasuryInstance = pallet_treasury::Instance1; - FellowshipTreasury: pallet_treasury::::{Pallet, Call, Storage, Event} = 65, // Ambassador Program. AmbassadorCollective: pallet_ranked_collective::::{Pallet, Call, Storage, Event} = 70, @@ -723,8 +714,6 @@ pub type UncheckedExtrinsic = type Migrations = ( // unreleased pallet_collator_selection::migration::v1::MigrateToV1, - // unreleased - cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4, ); /// Executive: handles dispatch to the various modules. @@ -751,6 +740,7 @@ mod benches { [pallet_collator_selection, CollatorSelection] [cumulus_pallet_parachain_system, ParachainSystem] [cumulus_pallet_xcmp_queue, XcmpQueue] + [cumulus_pallet_dmp_queue, DmpQueue] [pallet_alliance, Alliance] [pallet_collective, AllianceMotion] [pallet_xcm, PalletXcmExtrinsicsBenchmark::] @@ -765,8 +755,6 @@ mod benches { [pallet_collective_content, AmbassadorContent] [pallet_core_fellowship, AmbassadorCore] [pallet_salary, AmbassadorSalary] - [pallet_treasury, FellowshipTreasury] - [pallet_asset_rate, AssetRate] ); } @@ -994,18 +982,6 @@ impl_runtime_apis! { // Reserve transfers are disabled on Collectives. None } - - fn set_up_complex_asset_transfer( - ) -> Option<(MultiAssets, u32, MultiLocation, Box)> { - // Collectives only supports teleports to system parachain. - // Relay/native token can be teleported between Collectives and Relay. - let native_location = Parent.into(); - let dest = Parent.into(); - pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::( - native_location, - dest - ) - } } let whitelist: Vec = vec![ diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/cumulus_pallet_dmp_queue.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/cumulus_pallet_dmp_queue.rs new file mode 100644 index 00000000000..cc41dcd6cbb --- /dev/null +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/cumulus_pallet_dmp_queue.rs @@ -0,0 +1,131 @@ +// 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 . + +//! Autogenerated weights for `cumulus_pallet_dmp_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-10-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/production/polkadot-parachain +// benchmark +// pallet +// --steps=50 +// --repeat=20 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --json-file=/builds/parity/mirrors/polkadot-sdk/.git/.artifacts/bench.json +// --pallet=cumulus_pallet_dmp_queue +// --chain=asset-hub-kusama-dev +// --header=./cumulus/file_header.txt +// --output=./cumulus/parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_dmp_queue`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_dmp_queue::WeightInfo for WeightInfo { + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65696` + // Estimated: `69161` + // Minimum execution time: 124_651_000 picoseconds. + Weight::from_parts(127_857_000, 0) + .saturating_add(Weight::from_parts(0, 69161)) + .saturating_add(T::DbWeight::get().reads(5)) + .saturating_add(T::DbWeight::get().writes(5)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca7d95d3e948effbeccff2de2c182672836` (r:1 w:1) + fn on_idle_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65659` + // Estimated: `69124` + // Minimum execution time: 65_684_000 picoseconds. + Weight::from_parts(68_039_000, 0) + .saturating_add(Weight::from_parts(0, 69124)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Storage: `MessageQueue::BookStateFor` (r:1 w:1) + /// Proof: `MessageQueue::BookStateFor` (`max_values`: None, `max_size`: Some(52), added: 2527, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::ServiceHead` (r:1 w:1) + /// Proof: `MessageQueue::ServiceHead` (`max_values`: Some(1), `max_size`: Some(5), added: 500, mode: `MaxEncodedLen`) + /// Storage: `MessageQueue::Pages` (r:0 w:1) + /// Proof: `MessageQueue::Pages` (`max_values`: None, `max_size`: Some(65585), added: 68060, mode: `MaxEncodedLen`) + fn on_idle_overweight_good_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65726` + // Estimated: `69191` + // Minimum execution time: 117_657_000 picoseconds. + Weight::from_parts(122_035_000, 0) + .saturating_add(Weight::from_parts(0, 69191)) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(6)) + } + /// Storage: `DmpQueue::MigrationStatus` (r:1 w:1) + /// Proof: `DmpQueue::MigrationStatus` (`max_values`: Some(1), `max_size`: Some(1028), added: 1523, mode: `MaxEncodedLen`) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca754904d6d8c6fe06c4e5965f9b8397421` (r:1 w:0) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca70f923ef3252d0166429d36d20ed665a8` (r:1 w:1) + /// Storage: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + /// Proof: UNKNOWN KEY `0xcd5c1f6df63bc97f4a8ce37f14a50ca772275f64c354954352b71eea39cfaca2` (r:1 w:1) + fn on_idle_overweight_large_msg() -> Weight { + // Proof Size summary in bytes: + // Measured: `65689` + // Estimated: `69154` + // Minimum execution time: 59_799_000 picoseconds. + Weight::from_parts(61_354_000, 0) + .saturating_add(Weight::from_parts(0, 69154)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } +} diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/mod.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/mod.rs index 77f76342a2e..1d877fdbd2b 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/mod.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/mod.rs @@ -14,12 +14,12 @@ // limitations under the License. pub mod block_weights; +pub mod cumulus_pallet_dmp_queue; pub mod cumulus_pallet_parachain_system; pub mod cumulus_pallet_xcmp_queue; pub mod extrinsic_weights; pub mod frame_system; pub mod pallet_alliance; -pub mod pallet_asset_rate; pub mod pallet_balances; pub mod pallet_collator_selection; pub mod pallet_collective; @@ -39,7 +39,6 @@ pub mod pallet_salary_fellowship_salary; pub mod pallet_scheduler; pub mod pallet_session; pub mod pallet_timestamp; -pub mod pallet_treasury; pub mod pallet_utility; pub mod pallet_xcm; pub mod paritydb_weights; diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_asset_rate.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_asset_rate.rs deleted file mode 100644 index 51b0580f857..00000000000 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_asset_rate.rs +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 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 . - -//! Autogenerated weights for `pallet_asset_rate` -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-11-28, STEPS: `2`, REPEAT: `2`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `cob`, CPU: `` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-westend-dev")`, DB CACHE: 1024 - -// Executed Command: -// ./target/debug/polkadot-parachain -// benchmark -// pallet -// --chain=collectives-westend-dev -// --steps=2 -// --repeat=2 -// --pallet=pallet-asset-rate -// --extrinsic=* -// --wasm-execution=compiled -// --heap-pages=4096 -// --output=./cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/ - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(missing_docs)] - -use frame_support::{traits::Get, weights::Weight}; -use core::marker::PhantomData; - -/// Weight functions for `pallet_asset_rate`. -pub struct WeightInfo(PhantomData); -impl pallet_asset_rate::WeightInfo for WeightInfo { - /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:1) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(1238), added: 3713, mode: `MaxEncodedLen`) - fn create() -> Weight { - // Proof Size summary in bytes: - // Measured: `6` - // Estimated: `4703` - // Minimum execution time: 102_000_000 picoseconds. - Weight::from_parts(112_000_000, 0) - .saturating_add(Weight::from_parts(0, 4703)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:1) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(1238), added: 3713, mode: `MaxEncodedLen`) - fn update() -> Weight { - // Proof Size summary in bytes: - // Measured: `74` - // Estimated: `4703` - // Minimum execution time: 101_000_000 picoseconds. - Weight::from_parts(105_000_000, 0) - .saturating_add(Weight::from_parts(0, 4703)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:1) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(1238), added: 3713, mode: `MaxEncodedLen`) - fn remove() -> Weight { - // Proof Size summary in bytes: - // Measured: `74` - // Estimated: `4703` - // Minimum execution time: 112_000_000 picoseconds. - Weight::from_parts(116_000_000, 0) - .saturating_add(Weight::from_parts(0, 4703)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(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 deleted file mode 100644 index 58540e646d8..00000000000 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_treasury.rs +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright 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 . - -//! Autogenerated weights for `pallet_treasury` -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-11-28, STEPS: `2`, REPEAT: `2`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `cob`, CPU: `` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-westend-dev")`, DB CACHE: 1024 - -// Executed Command: -// ./target/debug/polkadot-parachain -// benchmark -// pallet -// --chain=collectives-westend-dev -// --steps=2 -// --repeat=2 -// --pallet=pallet-treasury -// --extrinsic=* -// --wasm-execution=compiled -// --heap-pages=4096 -// --output=./cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/ - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(missing_docs)] - -use frame_support::{traits::Get, weights::Weight}; -use core::marker::PhantomData; - -/// Weight functions for `pallet_treasury`. -pub struct WeightInfo(PhantomData); -impl pallet_treasury::WeightInfo for WeightInfo { - /// Storage: `FellowshipTreasury::ProposalCount` (r:1 w:1) - /// Proof: `FellowshipTreasury::ProposalCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `FellowshipTreasury::Approvals` (r:1 w:1) - /// Proof: `FellowshipTreasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) - /// Storage: `FellowshipTreasury::Proposals` (r:0 w:1) - /// Proof: `FellowshipTreasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - fn spend_local() -> Weight { - // Proof Size summary in bytes: - // Measured: `42` - // Estimated: `1887` - // Minimum execution time: 117_000_000 picoseconds. - Weight::from_parts(126_000_000, 0) - .saturating_add(Weight::from_parts(0, 1887)) - .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 { - // Proof Size summary in bytes: - // Measured: `127` - // Estimated: `1887` - // Minimum execution time: 62_000_000 picoseconds. - Weight::from_parts(65_000_000, 0) - .saturating_add(Weight::from_parts(0, 1887)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `System::Account` (r:199 w:199) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `FellowshipTreasury::Deactivated` (r:1 w:1) - /// Proof: `FellowshipTreasury::Deactivated` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) - /// Storage: `Balances::InactiveIssuance` (r:1 w:1) - /// Proof: `Balances::InactiveIssuance` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) - /// Storage: `FellowshipTreasury::Approvals` (r:1 w:1) - /// Proof: `FellowshipTreasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) - /// Storage: `FellowshipTreasury::Proposals` (r:99 w:99) - /// Proof: `FellowshipTreasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// The range of component `p` is `[0, 99]`. - fn on_initialize_proposals(p: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `145 + p * (250 ±0)` - // Estimated: `256707 + p * (5206 ±0)` - // Minimum execution time: 218_000_000 picoseconds. - Weight::from_parts(221_000_000, 0) - .saturating_add(Weight::from_parts(0, 256707)) - // Standard Error: 154_515 - .saturating_add(Weight::from_parts(399_232_323, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().reads((3_u64).saturating_mul(p.into()))) - .saturating_add(T::DbWeight::get().writes(3)) - .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(p.into()))) - .saturating_add(Weight::from_parts(0, 5206).saturating_mul(p.into())) - } - /// Storage: `AssetRate::ConversionRateToNative` (r:1 w:0) - /// Proof: `AssetRate::ConversionRateToNative` (`max_values`: None, `max_size`: Some(1238), added: 3713, mode: `MaxEncodedLen`) - /// Storage: `FellowshipTreasury::SpendCount` (r:1 w:1) - /// Proof: `FellowshipTreasury::SpendCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `FellowshipTreasury::Spends` (r:0 w:1) - /// Proof: `FellowshipTreasury::Spends` (`max_values`: None, `max_size`: Some(1853), added: 4328, mode: `MaxEncodedLen`) - fn spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `118` - // Estimated: `4703` - // Minimum execution time: 163_000_000 picoseconds. - Weight::from_parts(171_000_000, 0) - .saturating_add(Weight::from_parts(0, 4703)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `FellowshipTreasury::Spends` (r:1 w:1) - /// Proof: `FellowshipTreasury::Spends` (`max_values`: None, `max_size`: Some(1853), added: 4328, mode: `MaxEncodedLen`) - /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) - /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `PolkadotXcm::QueryCounter` (r:1 w:1) - /// Proof: `PolkadotXcm::QueryCounter` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `XcmpQueue::DeliveryFeeFactor` (r:1 w:0) - /// Proof: `XcmpQueue::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::RelevantMessagingState` (r:1 w:0) - /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) - /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) - /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::Queries` (r:0 w:1) - /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) - fn payout() -> Weight { - // Proof Size summary in bytes: - // Measured: `629` - // Estimated: `5318` - // Minimum execution time: 472_000_000 picoseconds. - Weight::from_parts(492_000_000, 0) - .saturating_add(Weight::from_parts(0, 5318)) - .saturating_add(T::DbWeight::get().reads(9)) - .saturating_add(T::DbWeight::get().writes(6)) - } - /// Storage: `FellowshipTreasury::Spends` (r:1 w:1) - /// Proof: `FellowshipTreasury::Spends` (`max_values`: None, `max_size`: Some(1853), added: 4328, mode: `MaxEncodedLen`) - /// Storage: `PolkadotXcm::Queries` (r:1 w:1) - /// Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) - fn check_status() -> Weight { - // Proof Size summary in bytes: - // Measured: `383` - // Estimated: `5318` - // Minimum execution time: 211_000_000 picoseconds. - Weight::from_parts(215_000_000, 0) - .saturating_add(Weight::from_parts(0, 5318)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `FellowshipTreasury::Spends` (r:1 w:1) - /// Proof: `FellowshipTreasury::Spends` (`max_values`: None, `max_size`: Some(1853), added: 4328, mode: `MaxEncodedLen`) - fn void_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `179` - // Estimated: `5318` - // Minimum execution time: 124_000_000 picoseconds. - Weight::from_parts(126_000_000, 0) - .saturating_add(Weight::from_parts(0, 5318)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } -} diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_xcm.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_xcm.rs index 50dfbffde01..a3b42cb86c4 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_xcm.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_xcm.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_xcm` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-05, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-11-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-r43aesjn-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("collectives-westend-dev")`, DB CACHE: 1024 // Executed Command: @@ -64,37 +64,22 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 24_540_000 picoseconds. - Weight::from_parts(25_439_000, 0) + // Minimum execution time: 25_746_000 picoseconds. + Weight::from_parts(26_349_000, 0) .saturating_add(Weight::from_parts(0, 3610)) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) - /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) - /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) fn teleport_assets() -> Weight { // Proof Size summary in bytes: - // Measured: `214` - // Estimated: `3679` - // Minimum execution time: 86_614_000 picoseconds. - Weight::from_parts(88_884_000, 0) - .saturating_add(Weight::from_parts(0, 3679)) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(3)) + // Measured: `69` + // Estimated: `1489` + // Minimum execution time: 22_660_000 picoseconds. + Weight::from_parts(23_173_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + .saturating_add(T::DbWeight::get().reads(1)) } /// Storage: `Benchmark::Override` (r:0 w:0) /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -106,32 +91,6 @@ impl pallet_xcm::WeightInfo for WeightInfo { Weight::from_parts(18_446_744_073_709_551_000, 0) .saturating_add(Weight::from_parts(0, 0)) } - /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) - /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::UpwardDeliveryFeeFactor` (r:1 w:0) - /// Proof: `ParachainSystem::UpwardDeliveryFeeFactor` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SupportedVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) - /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) - /// Proof: `PolkadotXcm::SafeXcmVersion` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) - /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `ParachainSystem::PendingUpwardMessages` (r:1 w:1) - /// Proof: `ParachainSystem::PendingUpwardMessages` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - fn transfer_assets() -> Weight { - // Proof Size summary in bytes: - // Measured: `214` - // Estimated: `3679` - // Minimum execution time: 87_915_000 picoseconds. - Weight::from_parts(90_219_000, 0) - .saturating_add(Weight::from_parts(0, 3679)) - .saturating_add(T::DbWeight::get().reads(8)) - .saturating_add(T::DbWeight::get().writes(3)) - } /// Storage: `Benchmark::Override` (r:0 w:0) /// Proof: `Benchmark::Override` (`max_values`: None, `max_size`: None, mode: `Measured`) fn execute() -> Weight { @@ -148,8 +107,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 6_872_000 picoseconds. - Weight::from_parts(7_110_000, 0) + // Minimum execution time: 7_321_000 picoseconds. + Weight::from_parts(7_542_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -159,8 +118,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_009_000 picoseconds. - Weight::from_parts(2_163_000, 0) + // Minimum execution time: 2_232_000 picoseconds. + Weight::from_parts(2_395_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -186,8 +145,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `145` // Estimated: `3610` - // Minimum execution time: 28_858_000 picoseconds. - Weight::from_parts(29_355_000, 0) + // Minimum execution time: 29_006_000 picoseconds. + Weight::from_parts(29_777_000, 0) .saturating_add(Weight::from_parts(0, 3610)) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(5)) @@ -212,8 +171,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `363` // Estimated: `3828` - // Minimum execution time: 30_598_000 picoseconds. - Weight::from_parts(31_168_000, 0) + // Minimum execution time: 31_245_000 picoseconds. + Weight::from_parts(32_125_000, 0) .saturating_add(Weight::from_parts(0, 3828)) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(4)) @@ -224,8 +183,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_090_000 picoseconds. - Weight::from_parts(2_253_000, 0) + // Minimum execution time: 2_255_000 picoseconds. + Weight::from_parts(2_399_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -235,8 +194,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `162` // Estimated: `11052` - // Minimum execution time: 16_133_000 picoseconds. - Weight::from_parts(16_433_000, 0) + // Minimum execution time: 16_521_000 picoseconds. + Weight::from_parts(17_001_000, 0) .saturating_add(Weight::from_parts(0, 11052)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -247,8 +206,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `166` // Estimated: `11056` - // Minimum execution time: 16_012_000 picoseconds. - Weight::from_parts(16_449_000, 0) + // Minimum execution time: 16_486_000 picoseconds. + Weight::from_parts(16_729_000, 0) .saturating_add(Weight::from_parts(0, 11056)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -259,8 +218,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `173` // Estimated: `13538` - // Minimum execution time: 17_922_000 picoseconds. - Weight::from_parts(18_426_000, 0) + // Minimum execution time: 18_037_000 picoseconds. + Weight::from_parts(18_310_000, 0) .saturating_add(Weight::from_parts(0, 13538)) .saturating_add(T::DbWeight::get().reads(5)) } @@ -282,8 +241,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `212` // Estimated: `6152` - // Minimum execution time: 27_280_000 picoseconds. - Weight::from_parts(28_026_000, 0) + // Minimum execution time: 27_901_000 picoseconds. + Weight::from_parts(28_566_000, 0) .saturating_add(Weight::from_parts(0, 6152)) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(3)) @@ -294,8 +253,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `206` // Estimated: `8621` - // Minimum execution time: 9_387_000 picoseconds. - Weight::from_parts(9_644_000, 0) + // Minimum execution time: 9_299_000 picoseconds. + Weight::from_parts(9_547_000, 0) .saturating_add(Weight::from_parts(0, 8621)) .saturating_add(T::DbWeight::get().reads(3)) } @@ -305,8 +264,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `173` // Estimated: `11063` - // Minimum execution time: 16_649_000 picoseconds. - Weight::from_parts(17_025_000, 0) + // Minimum execution time: 16_768_000 picoseconds. + Weight::from_parts(17_215_000, 0) .saturating_add(Weight::from_parts(0, 11063)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) @@ -329,8 +288,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `215` // Estimated: `11105` - // Minimum execution time: 34_355_000 picoseconds. - Weight::from_parts(35_295_000, 0) + // Minimum execution time: 35_134_000 picoseconds. + Weight::from_parts(35_883_000, 0) .saturating_add(Weight::from_parts(0, 11105)) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) @@ -343,8 +302,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `103` // Estimated: `1588` - // Minimum execution time: 4_527_000 picoseconds. - Weight::from_parts(4_699_000, 0) + // Minimum execution time: 4_562_000 picoseconds. + Weight::from_parts(4_802_000, 0) .saturating_add(Weight::from_parts(0, 1588)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(2)) @@ -355,8 +314,8 @@ impl pallet_xcm::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `7740` // Estimated: `11205` - // Minimum execution time: 27_011_000 picoseconds. - Weight::from_parts(27_398_000, 0) + // Minimum execution time: 26_865_000 picoseconds. + Weight::from_parts(27_400_000, 0) .saturating_add(Weight::from_parts(0, 11205)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs index 1fde722e42e..cefc099c96f 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs @@ -27,29 +27,26 @@ use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; use parachains_common::{ impls::ToStakingPot, - xcm_config::{ - AllSiblingSystemParachains, ConcreteAssetFromSystem, ParentRelayOrSiblingParachains, - RelayOrOtherSystemParachains, - }, + xcm_config::{ConcreteAssetFromSystem, RelayOrOtherSystemParachains}, }; use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; -use westend_runtime_constants::xcm as xcm_constants; +use westend_runtime_constants::system_parachain; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, - AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, - DenyThenTry, EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocatableAssetId, - OriginToPluralityVoice, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, - UsingComponents, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, - XcmFeeToAccount, + AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, + DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FixedWeightBounds, IsConcrete, + LocatableAssetId, OriginToPluralityVoice, ParentAsSuperuser, ParentIsPreset, + RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WithComputedOrigin, WithUniqueTopic, + XcmFeeManagerFromComponents, XcmFeeToAccount, }; use xcm_executor::{traits::WithOriginFilter, XcmExecutor}; +const FELLOWSHIP_ADMIN_INDEX: u32 = 1; + parameter_types! { pub const WndLocation: MultiLocation = MultiLocation::parent(); pub const RelayNetwork: Option = Some(NetworkId::Westend); @@ -59,8 +56,7 @@ parameter_types! { pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(westend_runtime_constants::TREASURY_PALLET_ID)).into(); pub CheckingAccount: AccountId = PolkadotXcm::check_account(); pub const GovernanceLocation: MultiLocation = MultiLocation::parent(); - pub const FellowshipAdminBodyId: BodyId = BodyId::Index(xcm_constants::body::FELLOWSHIP_ADMIN_INDEX); - pub const TreasurerBodyId: BodyId = BodyId::Index(xcm_constants::body::TREASURER_INDEX); + pub const FellowshipAdminBodyId: BodyId = BodyId::Index(FELLOWSHIP_ADMIN_INDEX); pub AssetHub: MultiLocation = (Parent, Parachain(1000)).into(); pub AssetHubUsdtId: AssetId = (PalletInstance(50), GeneralIndex(1984)).into(); pub UsdtAssetHub: LocatableAssetId = LocatableAssetId { @@ -86,7 +82,6 @@ pub type LocationToAccountId = ( ); /// Means for transacting the native currency on this chain. -#[allow(deprecated)] pub type CurrencyTransactor = CurrencyAdapter< // Use this currency: Balances, @@ -141,6 +136,10 @@ match_types! { MultiLocation { parents: 1, interior: Here } | MultiLocation { parents: 1, interior: X1(Plurality { .. }) } }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; } /// A call filter for the XCM Transact instruction. This is a temporary measure until we properly @@ -242,7 +241,7 @@ pub type Barrier = TrailingSetTopicAsId< // Parent and its pluralities (i.e. governance bodies) get free execution. AllowExplicitUnpaidExecutionFrom, // Subscriptions for version tracking are OK. - AllowSubscriptionsFrom, + AllowSubscriptionsFrom, ), UniversalLocation, ConstU32<8>, @@ -251,13 +250,24 @@ pub type Barrier = TrailingSetTopicAsId< >, >; +match_types! { + pub type SystemParachains: impl Contains = { + MultiLocation { + parents: 1, + interior: X1(Parachain( + system_parachain::ASSET_HUB_ID | + system_parachain::BRIDGE_HUB_ID | + system_parachain::COLLECTIVES_ID + )), + } + }; +} + /// Locations that will not be charged fees in the executor, /// either execution or delivery. /// We only waive fees for system functions, which these locations represent. -pub type WaivedLocations = ( - RelayOrOtherSystemParachains, - Equals, -); +pub type WaivedLocations = + (RelayOrOtherSystemParachains, Equals); /// Cases where a remote origin is accepted as trusted Teleporter for a given asset: /// - DOT with the parent Relay Chain and sibling parachains. diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/Cargo.toml b/cumulus/parachains/runtimes/contracts/contracts-rococo/Cargo.toml index 54af73c3d03..eded360436b 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "Apache-2.0" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -23,38 +20,39 @@ scale-info = { version = "2.10.0", default-features = false, features = ["derive smallvec = "1.11.0" # 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-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-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} +pallet-contracts-primitives = { path = "../../../../../substrate/frame/contracts/primitives", default-features = false} # Polkadot pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } @@ -70,7 +68,7 @@ xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkad cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } cumulus-pallet-dmp-queue = { path = "../../../../pallets/dmp-queue", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } 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 } @@ -81,7 +79,7 @@ parachain-info = { package = "staging-parachain-info", path = "../../../pallets/ parachains-common = { path = "../../../common", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-pallet-aura-ext/std", @@ -104,6 +102,7 @@ std = [ "pallet-authorship/std", "pallet-balances/std", "pallet-collator-selection/std", + "pallet-contracts-primitives/std", "pallet-contracts/std", "pallet-insecure-randomness-collective-flip/std", "pallet-message-queue/std", @@ -199,9 +198,9 @@ try-runtime = [ "sp-runtime/try-runtime", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] # A feature that should be enabled when the runtime should be built for on-chain # deployment. This will disable stuff that shouldn't be part of the on-chain wasm # to make it smaller like logging for example. -on-chain-release-build = ["sp-api/disable-logging"] +on-chain-release-build = [ "sp-api/disable-logging" ] diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs index 45225510ea7..d5f9f2e4189 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs @@ -35,7 +35,7 @@ use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, - traits::Block as BlockT, + traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, Perbill, }; @@ -46,11 +46,11 @@ use sp_version::NativeVersion; use sp_version::RuntimeVersion; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, parameter_types, - traits::{ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8}, + traits::{ConstBool, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Everything}, weights::{ConstantMultiplier, Weight}, PalletId, }; @@ -100,11 +100,9 @@ pub type UncheckedExtrinsic = /// Migrations to apply on runtime upgrade. pub type Migrations = ( cumulus_pallet_parachain_system::migration::Migration, - cumulus_pallet_xcmp_queue::migration::v2::MigrationToV2, - cumulus_pallet_xcmp_queue::migration::v3::MigrationToV3, + cumulus_pallet_xcmp_queue::migration::MigrationToV3, pallet_contracts::Migration, // unreleased - cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4, ); type EventRecord = frame_system::EventRecord< @@ -133,7 +131,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_005_000, + spec_version: 10001, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 6, @@ -171,17 +169,25 @@ parameter_types! { } // Configure FRAME pallets to include in runtime. -#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { + type BaseCallFilter = Everything; type BlockWeights = RuntimeBlockWeights; type BlockLength = RuntimeBlockLength; type AccountId = AccountId; + type RuntimeCall = RuntimeCall; + type Lookup = AccountIdLookup; type Nonce = Nonce; type Hash = Hash; + type Hashing = BlakeTwo256; type Block = Block; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; type BlockHashCount = BlockHashCount; type DbWeight = RocksDbWeight; type Version = Version; + type PalletInfo = PalletInfo; + type OnNewAccount = (); + type OnKilledAccount = (); type AccountData = pallet_balances::AccountData; type SystemWeightInfo = frame_system::weights::SubstrateWeight; type SS58Prefix = ConstU16<42>; @@ -582,7 +588,7 @@ impl_runtime_apis! { gas_limit: Option, storage_deposit_limit: Option, input_data: Vec, - ) -> pallet_contracts::ContractExecResult { + ) -> pallet_contracts_primitives::ContractExecResult { let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block); Contracts::bare_call( origin, @@ -602,10 +608,10 @@ impl_runtime_apis! { value: Balance, gas_limit: Option, storage_deposit_limit: Option, - code: pallet_contracts::Code, + code: pallet_contracts_primitives::Code, data: Vec, salt: Vec, - ) -> pallet_contracts::ContractInstantiateResult { + ) -> pallet_contracts_primitives::ContractInstantiateResult { let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block); Contracts::bare_instantiate( origin, @@ -625,7 +631,7 @@ impl_runtime_apis! { code: Vec, storage_deposit_limit: Option, determinism: pallet_contracts::Determinism, - ) -> pallet_contracts::CodeUploadResult { + ) -> pallet_contracts_primitives::CodeUploadResult { Contracts::bare_upload_code( origin, code, @@ -637,7 +643,7 @@ impl_runtime_apis! { fn get_storage( address: AccountId, key: Vec, - ) -> pallet_contracts::GetStorageResult { + ) -> pallet_contracts_primitives::GetStorageResult { Contracts::get_storage(address, key) } } @@ -723,18 +729,6 @@ impl_runtime_apis! { // Reserve transfers are disabled on Contracts-System-Para. None } - - fn set_up_complex_asset_transfer( - ) -> Option<(MultiAssets, u32, MultiLocation, Box)> { - // Contracts-System-Para only supports teleports to system parachain. - // Relay/native token can be teleported between Contracts-System-Para and Relay. - let native_location = Parent.into(); - let dest = Parent.into(); - pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::( - native_location, - dest - ) - } } let whitelist: Vec = vec![ diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs index 569ca6e587c..2ac93aed3f8 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs @@ -27,26 +27,22 @@ use frame_support::{ use frame_system::EnsureRoot; use pallet_xcm::{EnsureXcm, IsMajorityOfBody, XcmPassthrough}; use parachains_common::{ - xcm_config::{ - AllSiblingSystemParachains, ConcreteAssetFromSystem, ParentRelayOrSiblingParachains, - RelayOrOtherSystemParachains, - }, + xcm_config::{ConcreteAssetFromSystem, RelayOrOtherSystemParachains}, TREASURY_PALLET_ID, }; use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::xcm_sender::ExponentialPrice; +use rococo_runtime_constants::system_parachain; use sp_runtime::traits::AccountIdConversion; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, - AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, - DenyThenTry, EnsureXcmOrigin, FixedWeightBounds, IsConcrete, NativeAsset, ParentAsSuperuser, - ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - TrailingSetTopicAsId, UsingComponents, WithComputedOrigin, WithUniqueTopic, - XcmFeeManagerFromComponents, XcmFeeToAccount, + AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, + DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FixedWeightBounds, IsConcrete, + NativeAsset, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, + WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, XcmFeeToAccount, }; use xcm_executor::XcmExecutor; @@ -79,7 +75,6 @@ pub type LocationToAccountId = ( ); /// Means for transacting the native currency on this chain. -#[allow(deprecated)] pub type CurrencyTransactor = CurrencyAdapter< // Use this currency: Balances, @@ -128,6 +123,10 @@ match_types! { MultiLocation { parents: 1, interior: Here } | MultiLocation { parents: 1, interior: X1(Plurality { .. }) } }; + pub type ParentOrSiblings: impl Contains = { + MultiLocation { parents: 1, interior: Here } | + MultiLocation { parents: 1, interior: X1(_) } + }; } pub type Barrier = TrailingSetTopicAsId< @@ -150,7 +149,7 @@ pub type Barrier = TrailingSetTopicAsId< Equals, )>, // Subscriptions for version tracking are OK. - AllowSubscriptionsFrom, + AllowSubscriptionsFrom, ), UniversalLocation, ConstU32<8>, @@ -159,13 +158,25 @@ pub type Barrier = TrailingSetTopicAsId< >, >; +match_types! { + pub type SystemParachains: impl Contains = { + MultiLocation { + parents: 1, + interior: X1(Parachain( + system_parachain::ASSET_HUB_ID | + system_parachain::BRIDGE_HUB_ID | + system_parachain::CONTRACTS_ID | + system_parachain::ENCOINTER_ID + )), + } + }; +} + /// Locations that will not be charged fees in the executor, /// either execution or delivery. /// We only waive fees for system functions, which these locations represent. -pub type WaivedLocations = ( - RelayOrOtherSystemParachains, - Equals, -); +pub type WaivedLocations = + (RelayOrOtherSystemParachains, Equals); pub type TrustedTeleporter = ConcreteAssetFromSystem; diff --git a/cumulus/parachains/runtimes/glutton/glutton-kusama/Cargo.toml b/cumulus/parachains/runtimes/glutton/glutton-kusama/Cargo.toml new file mode 100644 index 00000000000..7f5feb1c880 --- /dev/null +++ b/cumulus/parachains/runtimes/glutton/glutton-kusama/Cargo.toml @@ -0,0 +1,138 @@ +[package] +name = "glutton-runtime" +version = "1.0.0" +description = "Glutton parachain runtime." +authors.workspace = true +edition.workspace = true +license = "Apache-2.0" + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } + +# 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, optional = true} +pallet-sudo = { path = "../../../../../substrate/frame/sudo", default-features = false, optional = true} +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} + +# 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} + +# Cumulus +cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } +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 } + +[build-dependencies] +substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder" } + +[features] +default = [ "std" ] +runtime-benchmarks = [ + "cumulus-pallet-parachain-system/runtime-benchmarks", + "cumulus-primitives-core/runtime-benchmarks", + "frame-benchmarking/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "frame-system-benchmarking/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-glutton/runtime-benchmarks", + "pallet-message-queue/runtime-benchmarks", + "pallet-sudo/runtime-benchmarks", + "pallet-timestamp/runtime-benchmarks", + "parachains-common/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", + "xcm-executor/runtime-benchmarks", +] +std = [ + "codec/std", + "cumulus-pallet-aura-ext/std", + "cumulus-pallet-parachain-system/std", + "cumulus-pallet-xcm/std", + "cumulus-primitives-aura/std", + "cumulus-primitives-core/std", + "cumulus-primitives-timestamp/std", + "frame-benchmarking?/std", + "frame-executive/std", + "frame-support/std", + "frame-system-benchmarking?/std", + "frame-system-rpc-runtime-api/std", + "frame-system/std", + "frame-try-runtime?/std", + "pallet-aura/std", + "pallet-glutton/std", + "pallet-message-queue/std", + "pallet-sudo/std", + "pallet-timestamp/std", + "parachain-info/std", + "parachains-common/std", + "scale-info/std", + "sp-api/std", + "sp-block-builder/std", + "sp-consensus-aura/std", + "sp-core/std", + "sp-genesis-builder/std", + "sp-inherents/std", + "sp-offchain/std", + "sp-runtime/std", + "sp-session/std", + "sp-std/std", + "sp-storage/std", + "sp-transaction-pool/std", + "sp-version/std", + "xcm-builder/std", + "xcm-executor/std", + "xcm/std", +] +try-runtime = [ + "cumulus-pallet-aura-ext/try-runtime", + "cumulus-pallet-parachain-system/try-runtime", + "cumulus-pallet-xcm/try-runtime", + "frame-executive/try-runtime", + "frame-support/try-runtime", + "frame-system/try-runtime", + "frame-try-runtime/try-runtime", + "pallet-aura/try-runtime", + "pallet-glutton/try-runtime", + "pallet-message-queue/try-runtime", + "pallet-sudo/try-runtime", + "pallet-timestamp/try-runtime", + "parachain-info/try-runtime", + "sp-runtime/try-runtime", +] + +experimental = [ "pallet-aura/experimental" ] + +# A feature that should be enabled when the runtime should be built for on-chain +# deployment. This will disable stuff that shouldn't be part of the on-chain wasm +# to make it smaller like logging for example. +on-chain-release-build = [ "sp-api/disable-logging" ] diff --git a/substrate/frame/contracts/fixtures/contracts/dummy.rs b/cumulus/parachains/runtimes/glutton/glutton-kusama/build.rs similarity index 79% rename from substrate/frame/contracts/fixtures/contracts/dummy.rs rename to cumulus/parachains/runtimes/glutton/glutton-kusama/build.rs index 98b9d494bbc..1580e6f07be 100644 --- a/substrate/frame/contracts/fixtures/contracts/dummy.rs +++ b/cumulus/parachains/runtimes/glutton/glutton-kusama/build.rs @@ -1,5 +1,3 @@ -// This file is part of Substrate. - // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 @@ -14,13 +12,13 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -#![no_std] -#![no_main] - -extern crate common; -#[no_mangle] -pub extern "C" fn deploy() {} +use substrate_wasm_builder::WasmBuilder; -#[no_mangle] -pub extern "C" fn call() {} +fn main() { + WasmBuilder::new() + .with_current_project() + .export_heap_base() + .import_memory() + .build() +} diff --git a/cumulus/parachains/runtimes/glutton/glutton-kusama/src/lib.rs b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/lib.rs new file mode 100644 index 00000000000..0c294da4223 --- /dev/null +++ b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/lib.rs @@ -0,0 +1,528 @@ +// 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. + +//! # Glutton Runtime +//! +//! The purpose of the Glutton parachain is to do stress testing on the Kusama +//! network. +//! +//! There may be multiple instances of the Glutton parachain deployed and +//! connected to Kusama. +//! +//! These parachains are not holding any real value. Their purpose is to stress +//! test the network. +//! +//! ### Governance +//! +//! Glutton defers its governance (namely, its `Root` origin), to its Relay +//! Chain parent, Kusama. +//! +//! ### XCM +//! +//! Since the main goal of Glutton is solely stress testing, the parachain will +//! only be able receive XCM messages from Kusama via DMP. This way the Glutton +//! parachains will be able to listen for upgrades that are coming from the +//! Relay chain. + +#![cfg_attr(not(feature = "std"), no_std)] +#![recursion_limit = "256"] + +// Make the WASM binary available. +#[cfg(feature = "std")] +include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); + +pub mod weights; +pub mod xcm_config; + +use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; +use sp_api::impl_runtime_apis; +pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; +use sp_runtime::{ + create_runtime_str, generic, impl_opaque_keys, + traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, +}; +use sp_std::prelude::*; +#[cfg(feature = "std")] +use sp_version::NativeVersion; +use sp_version::RuntimeVersion; + +use cumulus_primitives_core::AggregateMessageOrigin; +pub use frame_support::{ + construct_runtime, + dispatch::DispatchClass, + genesis_builder_helper::{build_config, create_default_config}, + parameter_types, + traits::{ + ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, Everything, IsInVec, Randomness, + }, + weights::{ + constants::{ + BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND, + }, + IdentityFee, Weight, + }, + PalletId, StorageValue, +}; +use frame_system::{ + limits::{BlockLength, BlockWeights}, + EnsureRoot, +}; +use parachains_common::{AccountId, Signature}; +#[cfg(any(feature = "std", test))] +pub use sp_runtime::BuildStorage; +pub use sp_runtime::{Perbill, Permill}; + +impl_opaque_keys! { + pub struct SessionKeys { + pub aura: Aura, + } +} + +#[sp_version::runtime_version] +pub const VERSION: RuntimeVersion = RuntimeVersion { + spec_name: create_runtime_str!("glutton"), + impl_name: create_runtime_str!("glutton"), + authoring_version: 1, + spec_version: 10000, + impl_version: 0, + apis: RUNTIME_API_VERSIONS, + transaction_version: 1, + state_version: 1, +}; + +/// The version information used to identify this runtime when compiled natively. +#[cfg(feature = "std")] +pub fn native_version() -> NativeVersion { + NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } +} + +/// We assume that ~10% of the block weight is consumed by `on_initialize` handlers. +/// This is used to limit the maximal weight of a single extrinsic. +const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10); +/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used +/// by Operational extrinsics. +const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); +/// We allow for .5 seconds of compute with a 12 second average block time. +const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts( + WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), + cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64, +); + +/// Maximum number of blocks simultaneously accepted by the Runtime, not yet included +/// into the relay chain. +const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3; +/// How many parachain blocks are processed by the relay chain per parent. Limits the +/// number of blocks authored per slot. +const BLOCK_PROCESSING_VELOCITY: u32 = 2; +/// Relay chain slot duration, in milliseconds. +const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000; + +/// This determines the average expected block time that we are targeting. +/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`. +/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked +/// up by `pallet_aura` to implement `fn slot_duration()`. +/// +/// Change this to adjust the block time. +pub const MILLISECS_PER_BLOCK: u64 = 6000; +pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; + +parameter_types! { + pub const BlockHashCount: BlockNumber = 4096; + pub const Version: RuntimeVersion = VERSION; + pub RuntimeBlockLength: BlockLength = + BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() + .base_block(BlockExecutionWeight::get()) + .for_class(DispatchClass::all(), |weights| { + weights.base_extrinsic = ExtrinsicBaseWeight::get(); + }) + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Operational transactions have some extra reserved space, so that they + // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); + pub const SS58Prefix: u8 = 2; +} + +impl frame_system::Config for Runtime { + type AccountId = AccountId; + type RuntimeCall = RuntimeCall; + type Lookup = AccountIdLookup; + type Nonce = Nonce; + type Hash = Hash; + type Hashing = BlakeTwo256; + type Block = Block; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type BlockHashCount = BlockHashCount; + type Version = Version; + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = frame_support::traits::Everything; + type SystemWeightInfo = (); + type BlockWeights = RuntimeBlockWeights; + type BlockLength = RuntimeBlockLength; + type SS58Prefix = SS58Prefix; + type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + +parameter_types! { + // We do anything the parent chain tells us in this runtime. + pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(2); + pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent; +} + +type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook< + Runtime, + RELAY_CHAIN_SLOT_DURATION_MILLIS, + BLOCK_PROCESSING_VELOCITY, + UNINCLUDED_SEGMENT_CAPACITY, +>; + +impl cumulus_pallet_parachain_system::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type OnSystemEvent = (); + type SelfParaId = parachain_info::Pallet; + type DmpQueue = frame_support::traits::EnqueueWithOrigin; + type OutboundXcmpMessageSource = (); + type ReservedDmpWeight = ReservedDmpWeight; + type XcmpMessageHandler = (); + type ReservedXcmpWeight = (); + type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases; + type ConsensusHook = ConsensusHook; + type WeightInfo = weights::cumulus_pallet_parachain_system::WeightInfo; +} + +parameter_types! { + pub MessageQueueServiceWeight: Weight = Perbill::from_percent(80) * + RuntimeBlockWeights::get().max_block; +} + +impl pallet_message_queue::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type WeightInfo = weights::pallet_message_queue::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor< + cumulus_primitives_core::AggregateMessageOrigin, + >; + #[cfg(not(feature = "runtime-benchmarks"))] + type MessageProcessor = xcm_builder::ProcessXcmMessage< + AggregateMessageOrigin, + xcm_executor::XcmExecutor, + RuntimeCall, + >; + type Size = u32; + type QueueChangeHandler = (); + type QueuePausedQuery = (); // No XCMP queue pallet deployed. + type HeapSize = sp_core::ConstU32<{ 64 * 1024 }>; + type MaxStale = sp_core::ConstU32<8>; + type ServiceWeight = MessageQueueServiceWeight; +} + +impl parachain_info::Config for Runtime {} + +impl cumulus_pallet_aura_ext::Config for Runtime {} + +impl pallet_timestamp::Config for Runtime { + type Moment = u64; + type OnTimestampSet = Aura; + #[cfg(feature = "experimental")] + type MinimumPeriod = ConstU64<0>; + #[cfg(not(feature = "experimental"))] + type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>; + type WeightInfo = weights::pallet_timestamp::WeightInfo; +} + +impl pallet_aura::Config for Runtime { + type AuthorityId = AuraId; + type DisabledValidators = (); + type MaxAuthorities = ConstU32<100_000>; + type AllowMultipleBlocksPerSlot = ConstBool; + #[cfg(feature = "experimental")] + type SlotDuration = ConstU64; +} + +impl pallet_glutton::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type WeightInfo = weights::pallet_glutton::WeightInfo; + type AdminOrigin = EnsureRoot; +} + +impl pallet_sudo::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type WeightInfo = (); +} + +construct_runtime! { + pub enum Runtime + { + System: frame_system::{Pallet, Call, Storage, Config, Event} = 0, + ParachainSystem: cumulus_pallet_parachain_system::{ + Pallet, Call, Config, Storage, Inherent, Event, ValidateUnsigned, + } = 1, + ParachainInfo: parachain_info::{Pallet, Storage, Config} = 2, + Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 3, + + // DMP handler. + CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Storage, Event, Origin} = 10, + MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event} = 11, + + // The main stage. + Glutton: pallet_glutton::{Pallet, Call, Storage, Event, Config} = 20, + + // Collator support + Aura: pallet_aura::{Pallet, Storage, Config} = 30, + AuraExt: cumulus_pallet_aura_ext::{Pallet, Storage, Config} = 31, + + // Sudo. + Sudo: pallet_sudo::{Pallet, Call, Storage, Event, Config} = 255, + } +} + +/// Index of a transaction in the chain. +pub type Nonce = u32; +/// A hash of some data used by the chain. +pub type Hash = sp_core::H256; +/// An index to a block. +pub type BlockNumber = u32; +/// The address format for describing accounts. +pub type Address = sp_runtime::MultiAddress; +/// Block header type as expected by this runtime. +pub type Header = generic::Header; +/// Block type as expected by this runtime. +pub type Block = generic::Block; +/// A Block signed with a Justification +pub type SignedBlock = generic::SignedBlock; +/// BlockId type as expected by this runtime. +pub type BlockId = generic::BlockId; +/// The extension to the basic transaction logic. +pub type TxExtension = ( + pallet_sudo::CheckOnlySudoAccount, + frame_system::CheckNonZeroSender, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, +); +/// Unchecked extrinsic type as expected by this runtime. +pub type UncheckedExtrinsic = + generic::UncheckedExtrinsic; +/// Executive: handles dispatch to the various modules. +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, +>; + +#[cfg(feature = "runtime-benchmarks")] +#[macro_use] +extern crate frame_benchmarking; + +#[cfg(feature = "runtime-benchmarks")] +mod benches { + define_benchmarks!( + [frame_system, SystemBench::] + [pallet_glutton, Glutton] + ); +} + +impl_runtime_apis! { + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + + fn metadata_at_version(version: u32) -> Option { + Runtime::metadata_at_version(version) + } + + fn metadata_versions() -> sp_std::vec::Vec { + Runtime::metadata_versions() + } + } + + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + + fn authorities() -> Vec { + Aura::authorities().into_inner() + } + } + + impl cumulus_primitives_aura::AuraUnincludedSegmentApi for Runtime { + fn can_build_upon( + included_hash: ::Hash, + slot: cumulus_primitives_aura::Slot, + ) -> bool { + ConsensusHook::can_build_upon(included_hash, slot) + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic( + extrinsic: ::Extrinsic, + ) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents(block: Block, data: sp_inherents::InherentData) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { + ParachainSystem::collect_collation_info(header) + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { + System::account_nonce(account) + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsWithSystem::storage_info(); + + (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{Benchmarking, BenchmarkBatch, BenchmarkError}; + use sp_storage::TrackedStorageKey; + + use frame_system_benchmarking::Pallet as SystemBench; + impl frame_system_benchmarking::Config for Runtime { + fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); + Ok(()) + } + + fn verify_set_code() { + System::assert_last_event(cumulus_pallet_parachain_system::Event::::ValidationFunctionStored.into()); + } + } + + use frame_support::traits::WhitelistedStorageKeys; + let whitelist: Vec = AllPalletsWithSystem::whitelisted_storage_keys(); + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + add_benchmarks!(params, batches); + Ok(batches) + } + } + + impl sp_genesis_builder::GenesisBuilder for Runtime { + fn create_default_config() -> Vec { + create_default_config::() + } + + fn build_config(config: Vec) -> sp_genesis_builder::Result { + build_config::(config) + } + } +} + +cumulus_pallet_parachain_system::register_validate_block! { + Runtime = Runtime, + BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, +} diff --git a/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/cumulus_pallet_parachain_system.rs new file mode 100644 index 00000000000..f787aa32701 --- /dev/null +++ b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/cumulus_pallet_parachain_system.rs @@ -0,0 +1,80 @@ +// 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. + +//! Autogenerated weights for `cumulus_pallet_parachain_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-03-28, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `i9`, CPU: `13th Gen Intel(R) Core(TM) i9-13900K` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("statemint-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --chain +// statemint-dev +// --pallet +// cumulus_pallet_parachain_system +// --extrinsic +// * +// --execution +// wasm +// --wasm-execution +// compiled +// --output +// parachains/runtimes/assets/statemint/src/weights +// --steps +// 50 +// --repeat +// 20 + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `cumulus_pallet_parachain_system`. +pub struct WeightInfo(PhantomData); +impl cumulus_pallet_parachain_system::WeightInfo for WeightInfo { + /// Storage: ParachainSystem LastDmqMqcHead (r:1 w:1) + /// Proof Skipped: ParachainSystem LastDmqMqcHead (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: ParachainSystem ReservedDmpWeightOverride (r:1 w:0) + /// Proof Skipped: ParachainSystem ReservedDmpWeightOverride (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: ParachainSystem ProcessedDownwardMessages (r:0 w:1) + /// Proof Skipped: ParachainSystem ProcessedDownwardMessages (max_values: Some(1), max_size: None, mode: Measured) + /// Storage: MessageQueue Pages (r:0 w:16) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + /// The range of component `n` is `[0, 1000]`. + fn enqueue_inbound_downward_messages(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `12` + // Estimated: `8013` + // Minimum execution time: 1_660_000 picoseconds. + Weight::from_parts(1_720_000, 0) + .saturating_add(Weight::from_parts(0, 8013)) + // Standard Error: 28_418 + .saturating_add(Weight::from_parts(24_636_963, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(4)) + } +} diff --git a/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/frame_system.rs b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/frame_system.rs new file mode 100644 index 00000000000..cf7ef948fd6 --- /dev/null +++ b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/frame_system.rs @@ -0,0 +1,154 @@ +// 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. + +//! Autogenerated weights for `frame_system` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("glutton-kusama-dev-1300")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=glutton-kusama-dev-1300 +// --wasm-execution=compiled +// --pallet=frame_system +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/glutton/glutton-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `frame_system`. +pub struct WeightInfo(PhantomData); +impl frame_system::WeightInfo for WeightInfo { + /// The range of component `b` is `[0, 3932160]`. + fn remark(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_717_000 picoseconds. + Weight::from_parts(1_782_325, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 0 + .saturating_add(Weight::from_parts(387, 0).saturating_mul(b.into())) + } + /// The range of component `b` is `[0, 3932160]`. + fn remark_with_event(b: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_089_000 picoseconds. + Weight::from_parts(6_353_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 2 + .saturating_add(Weight::from_parts(1_788, 0).saturating_mul(b.into())) + } + /// Storage: `System::Digest` (r:1 w:1) + /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) + /// Proof: UNKNOWN KEY `0x3a686561707061676573` (r:0 w:1) + fn set_heap_pages() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `1485` + // Minimum execution time: 3_389_000 picoseconds. + Weight::from_parts(3_605_000, 0) + .saturating_add(Weight::from_parts(0, 1485)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: `ParachainSystem::ValidationData` (r:1 w:0) + /// Proof: `ParachainSystem::ValidationData` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::UpgradeRestrictionSignal` (r:1 w:0) + /// Proof: `ParachainSystem::UpgradeRestrictionSignal` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::PendingValidationCode` (r:1 w:1) + /// Proof: `ParachainSystem::PendingValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::HostConfiguration` (r:1 w:0) + /// Proof: `ParachainSystem::HostConfiguration` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::NewValidationCode` (r:0 w:1) + /// Proof: `ParachainSystem::NewValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `ParachainSystem::DidSetValidationCode` (r:0 w:1) + /// Proof: `ParachainSystem::DidSetValidationCode` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + fn set_code() -> Weight { + // Proof Size summary in bytes: + // Measured: `119` + // Estimated: `1604` + // Minimum execution time: 97_701_839_000 picoseconds. + Weight::from_parts(100_104_315_000, 0) + .saturating_add(Weight::from_parts(0, 1604)) + .saturating_add(T::DbWeight::get().reads(4)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `i` is `[0, 1000]`. + fn set_storage(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_638_000 picoseconds. + Weight::from_parts(1_726_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 1_886 + .saturating_add(Weight::from_parts(809_561, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `i` is `[0, 1000]`. + fn kill_storage(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_569_000 picoseconds. + Weight::from_parts(1_690_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 963 + .saturating_add(Weight::from_parts(580_145, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(i.into()))) + } + /// Storage: `Skipped::Metadata` (r:0 w:0) + /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// The range of component `p` is `[0, 1000]`. + fn kill_prefix(p: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `52 + p * (69 ±0)` + // Estimated: `46 + p * (70 ±0)` + // Minimum execution time: 3_039_000 picoseconds. + Weight::from_parts(3_090_000, 0) + .saturating_add(Weight::from_parts(0, 46)) + // Standard Error: 2_007 + .saturating_add(Weight::from_parts(1_269_045, 0).saturating_mul(p.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(p.into()))) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(p.into()))) + .saturating_add(Weight::from_parts(0, 70).saturating_mul(p.into())) + } +} diff --git a/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/mod.rs b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/mod.rs new file mode 100644 index 00000000000..47f9d1ee105 --- /dev/null +++ b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/mod.rs @@ -0,0 +1,19 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod cumulus_pallet_parachain_system; +pub mod pallet_glutton; +pub mod pallet_message_queue; +pub mod pallet_timestamp; diff --git a/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/pallet_glutton.rs b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/pallet_glutton.rs new file mode 100644 index 00000000000..e1b0c5bf232 --- /dev/null +++ b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/pallet_glutton.rs @@ -0,0 +1,179 @@ +// 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. + +//! Autogenerated weights for `pallet_glutton` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("glutton-kusama-dev-1300")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=glutton-kusama-dev-1300 +// --wasm-execution=compiled +// --pallet=pallet_glutton +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/glutton/glutton-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_glutton`. +pub struct WeightInfo(PhantomData); +impl pallet_glutton::WeightInfo for WeightInfo { + /// Storage: `Glutton::TrashDataCount` (r:1 w:1) + /// Proof: `Glutton::TrashDataCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Glutton::TrashData` (r:0 w:1000) + /// Proof: `Glutton::TrashData` (`max_values`: Some(65000), `max_size`: Some(1036), added: 3016, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 1000]`. + fn initialize_pallet_grow(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `87` + // Estimated: `1489` + // Minimum execution time: 8_925_000 picoseconds. + Weight::from_parts(9_186_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + // Standard Error: 3_091 + .saturating_add(Weight::from_parts(9_666_196, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) + } + /// Storage: `Glutton::TrashDataCount` (r:1 w:1) + /// Proof: `Glutton::TrashDataCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// Storage: `Glutton::TrashData` (r:0 w:1000) + /// Proof: `Glutton::TrashData` (`max_values`: Some(65000), `max_size`: Some(1036), added: 3016, mode: `MaxEncodedLen`) + /// The range of component `n` is `[0, 1000]`. + fn initialize_pallet_shrink(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `120` + // Estimated: `1489` + // Minimum execution time: 8_924_000 picoseconds. + Weight::from_parts(8_963_000, 0) + .saturating_add(Weight::from_parts(0, 1489)) + // Standard Error: 1_202 + .saturating_add(Weight::from_parts(1_139_080, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(n.into()))) + } + /// The range of component `i` is `[0, 100000]`. + fn waste_ref_time_iter(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 708_000 picoseconds. + Weight::from_parts(1_698_031, 0) + .saturating_add(Weight::from_parts(0, 0)) + // Standard Error: 12 + .saturating_add(Weight::from_parts(106_500, 0).saturating_mul(i.into())) + } + /// Storage: `Glutton::TrashData` (r:5000 w:0) + /// Proof: `Glutton::TrashData` (`max_values`: Some(65000), `max_size`: Some(1036), added: 3016, mode: `MaxEncodedLen`) + /// The range of component `i` is `[0, 5000]`. + fn waste_proof_size_some(i: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `119115 + i * (1022 ±0)` + // Estimated: `990 + i * (3016 ±0)` + // Minimum execution time: 698_000 picoseconds. + Weight::from_parts(970_000, 0) + .saturating_add(Weight::from_parts(0, 990)) + // Standard Error: 4_022 + .saturating_add(Weight::from_parts(6_320_519, 0).saturating_mul(i.into())) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(i.into()))) + .saturating_add(Weight::from_parts(0, 3016).saturating_mul(i.into())) + } + /// Storage: `Glutton::Storage` (r:1 w:0) + /// Proof: `Glutton::Storage` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `Glutton::Compute` (r:1 w:0) + /// Proof: `Glutton::Compute` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `Glutton::TrashData` (r:1737 w:0) + /// Proof: `Glutton::TrashData` (`max_values`: Some(65000), `max_size`: Some(1036), added: 3016, mode: `MaxEncodedLen`) + fn on_idle_high_proof_waste() -> Weight { + // Proof Size summary in bytes: + // Measured: `1900498` + // Estimated: `5239782` + // Minimum execution time: 100_079_897_000 picoseconds. + Weight::from_parts(100_515_306_000, 0) + .saturating_add(Weight::from_parts(0, 5239782)) + .saturating_add(T::DbWeight::get().reads(1739)) + } + /// Storage: `Glutton::Storage` (r:1 w:0) + /// Proof: `Glutton::Storage` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `Glutton::Compute` (r:1 w:0) + /// Proof: `Glutton::Compute` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `Glutton::TrashData` (r:5 w:0) + /// Proof: `Glutton::TrashData` (`max_values`: Some(65000), `max_size`: Some(1036), added: 3016, mode: `MaxEncodedLen`) + fn on_idle_low_proof_waste() -> Weight { + // Proof Size summary in bytes: + // Measured: `9548` + // Estimated: `16070` + // Minimum execution time: 100_237_009_000 picoseconds. + Weight::from_parts(100_472_213_000, 0) + .saturating_add(Weight::from_parts(0, 16070)) + .saturating_add(T::DbWeight::get().reads(7)) + } + /// Storage: `Glutton::Storage` (r:1 w:0) + /// Proof: `Glutton::Storage` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `Glutton::Compute` (r:1 w:0) + /// Proof: `Glutton::Compute` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + fn empty_on_idle() -> Weight { + // Proof Size summary in bytes: + // Measured: `87` + // Estimated: `1493` + // Minimum execution time: 5_120_000 picoseconds. + Weight::from_parts(5_262_000, 0) + .saturating_add(Weight::from_parts(0, 1493)) + .saturating_add(T::DbWeight::get().reads(2)) + } + /// Storage: `Glutton::Compute` (r:0 w:1) + /// Proof: `Glutton::Compute` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + fn set_compute() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 5_947_000 picoseconds. + Weight::from_parts(6_171_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: `Glutton::Storage` (r:0 w:1) + /// Proof: `Glutton::Storage` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + fn set_storage() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 5_964_000 picoseconds. + Weight::from_parts(6_166_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } +} diff --git a/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/pallet_message_queue.rs new file mode 100644 index 00000000000..a9f0cb07cfe --- /dev/null +++ b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/pallet_message_queue.rs @@ -0,0 +1,179 @@ +// 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. + +//! Autogenerated weights for `pallet_message_queue` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-03-24, STEPS: `2`, REPEAT: `1`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `i9`, CPU: `13th Gen Intel(R) Core(TM) i9-13900K` +//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("westmint-dev"), DB CACHE: 1024 + +// Executed Command: +// ./target/release/polkadot-parachain +// benchmark +// pallet +// --chain +// westmint-dev +// --pallet +// pallet_message_queue +// --extrinsic +// * +// --execution +// wasm +// --wasm-execution +// compiled +// --output +// parachains/runtimes/assets/westmint/src/weights + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] + +use frame_support::{traits::Get, weights::Weight}; +use sp_std::marker::PhantomData; + +/// Weight functions for `pallet_message_queue`. +pub struct WeightInfo(PhantomData); +impl pallet_message_queue::WeightInfo for WeightInfo { + /// Storage: MessageQueue ServiceHead (r:1 w:0) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: MessageQueue BookStateFor (r:2 w:2) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn ready_ring_knit() -> Weight { + // Proof Size summary in bytes: + // Measured: `189` + // Estimated: `7534` + // Minimum execution time: 12_192_000 picoseconds. + Weight::from_parts(12_192_000, 0) + .saturating_add(Weight::from_parts(0, 7534)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:2 w:2) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + fn ready_ring_unknit() -> Weight { + // Proof Size summary in bytes: + // Measured: `184` + // Estimated: `7534` + // Minimum execution time: 10_447_000 picoseconds. + Weight::from_parts(10_447_000, 0) + .saturating_add(Weight::from_parts(0, 7534)) + .saturating_add(T::DbWeight::get().reads(3)) + .saturating_add(T::DbWeight::get().writes(3)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn service_queue_base() -> Weight { + // Proof Size summary in bytes: + // Measured: `6` + // Estimated: `3517` + // Minimum execution time: 4_851_000 picoseconds. + Weight::from_parts(4_851_000, 0) + .saturating_add(Weight::from_parts(0, 3517)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn service_page_base_completion() -> Weight { + // Proof Size summary in bytes: + // Measured: `72` + // Estimated: `69050` + // Minimum execution time: 6_342_000 picoseconds. + Weight::from_parts(6_342_000, 0) + .saturating_add(Weight::from_parts(0, 69050)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn service_page_base_no_completion() -> Weight { + // Proof Size summary in bytes: + // Measured: `72` + // Estimated: `69050` + // Minimum execution time: 6_199_000 picoseconds. + Weight::from_parts(6_199_000, 0) + .saturating_add(Weight::from_parts(0, 69050)) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn service_page_item() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 58_612_000 picoseconds. + Weight::from_parts(58_612_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } + /// Storage: MessageQueue ServiceHead (r:1 w:1) + /// Proof: MessageQueue ServiceHead (max_values: Some(1), max_size: Some(5), added: 500, mode: MaxEncodedLen) + /// Storage: MessageQueue BookStateFor (r:1 w:0) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + fn bump_service_head() -> Weight { + // Proof Size summary in bytes: + // Measured: `99` + // Estimated: `5007` + // Minimum execution time: 7_296_000 picoseconds. + Weight::from_parts(7_296_000, 0) + .saturating_add(Weight::from_parts(0, 5007)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn reap_page() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 48_345_000 picoseconds. + Weight::from_parts(48_345_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn execute_overweight_page_removed() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 56_441_000 picoseconds. + Weight::from_parts(56_441_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } + /// Storage: MessageQueue BookStateFor (r:1 w:1) + /// Proof: MessageQueue BookStateFor (max_values: None, max_size: Some(52), added: 2527, mode: MaxEncodedLen) + /// Storage: MessageQueue Pages (r:1 w:1) + /// Proof: MessageQueue Pages (max_values: None, max_size: Some(65585), added: 68060, mode: MaxEncodedLen) + fn execute_overweight_page_updated() -> Weight { + // Proof Size summary in bytes: + // Measured: `65667` + // Estimated: `72567` + // Minimum execution time: 70_858_000 picoseconds. + Weight::from_parts(70_858_000, 0) + .saturating_add(Weight::from_parts(0, 72567)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(2)) + } +} diff --git a/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/pallet_timestamp.rs b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/pallet_timestamp.rs new file mode 100644 index 00000000000..8edae065f1b --- /dev/null +++ b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/weights/pallet_timestamp.rs @@ -0,0 +1,75 @@ +// Copyright 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 . + +//! Autogenerated weights for `pallet_timestamp` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev +//! DATE: 2023-07-31, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `runner-ynta1nyy-project-238-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! EXECUTION: ``, WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-kusama-dev")`, DB CACHE: 1024 + +// Executed Command: +// ./target/production/polkadot-parachain +// benchmark +// pallet +// --chain=asset-hub-kusama-dev +// --wasm-execution=compiled +// --pallet=pallet_timestamp +// --no-storage-info +// --no-median-slopes +// --no-min-squares +// --extrinsic=* +// --steps=50 +// --repeat=20 +// --json +// --header=./file_header.txt +// --output=./parachains/runtimes/assets/asset-hub-kusama/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_timestamp`. +pub struct WeightInfo(PhantomData); +impl pallet_timestamp::WeightInfo for WeightInfo { + /// Storage: `Timestamp::Now` (r:1 w:1) + /// Proof: `Timestamp::Now` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `Aura::CurrentSlot` (r:1 w:0) + /// Proof: `Aura::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + fn set() -> Weight { + // Proof Size summary in bytes: + // Measured: `86` + // Estimated: `1493` + // Minimum execution time: 9_313_000 picoseconds. + Weight::from_parts(9_775_000, 0) + .saturating_add(Weight::from_parts(0, 1493)) + .saturating_add(T::DbWeight::get().reads(2)) + .saturating_add(T::DbWeight::get().writes(1)) + } + fn on_finalize() -> Weight { + // Proof Size summary in bytes: + // Measured: `57` + // Estimated: `0` + // Minimum execution time: 3_322_000 picoseconds. + Weight::from_parts(3_577_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + } +} diff --git a/cumulus/parachains/runtimes/glutton/glutton-kusama/src/xcm_config.rs b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/xcm_config.rs new file mode 100644 index 00000000000..fb7b78b79d2 --- /dev/null +++ b/cumulus/parachains/runtimes/glutton/glutton-kusama/src/xcm_config.rs @@ -0,0 +1,92 @@ +// 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::{ + AccountId, AllPalletsWithSystem, ParachainInfo, Runtime, RuntimeCall, RuntimeEvent, + RuntimeOrigin, +}; +use frame_support::{ + match_types, parameter_types, + traits::{Everything, Nothing}, + weights::Weight, +}; +use xcm::latest::prelude::*; +use xcm_builder::{ + AllowExplicitUnpaidExecutionFrom, FixedWeightBounds, ParentAsSuperuser, ParentIsPreset, + SovereignSignedViaLocation, +}; + +parameter_types! { + pub const KusamaLocation: MultiLocation = MultiLocation::parent(); + pub const KusamaNetwork: Option = Some(NetworkId::Kusama); + pub UniversalLocation: InteriorMultiLocation = X1(Parachain(ParachainInfo::parachain_id().into())); +} + +/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance, +/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can +/// bias the kind of local `Origin` it will become. +pub type XcmOriginToTransactDispatchOrigin = ( + // Sovereign account converter; this attempts to derive an `AccountId` from the origin location + // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for + // foreign chains who want to have a local sovereign account on this chain which they control. + SovereignSignedViaLocation, RuntimeOrigin>, + // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a + // transaction from the Root origin. + ParentAsSuperuser, +); + +match_types! { + pub type JustTheParent: impl Contains = { MultiLocation { parents:1, interior: Here } }; +} + +parameter_types! { + // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate. + pub UnitWeightCost: Weight = Weight::from_parts(1_000_000_000, 64 * 1024); + pub const MaxInstructions: u32 = 100; + pub const MaxAssetsIntoHolding: u32 = 64; +} + +pub struct XcmConfig; +impl xcm_executor::Config for XcmConfig { + type RuntimeCall = RuntimeCall; + type XcmSender = (); // sending XCM not supported + type AssetTransactor = (); // balances not supported + type OriginConverter = XcmOriginToTransactDispatchOrigin; + type IsReserve = (); // balances not supported + type IsTeleporter = (); // balances not supported + type UniversalLocation = UniversalLocation; + type Barrier = AllowExplicitUnpaidExecutionFrom; + type Weigher = FixedWeightBounds; // balances not supported + type Trader = (); // balances not supported + type ResponseHandler = (); // Don't handle responses for now. + type AssetTrap = (); // don't trap for now + type AssetClaims = (); // don't claim for now + type SubscriptionService = (); // don't handle subscriptions for now + type PalletInstancesInfo = AllPalletsWithSystem; + type MaxAssetsIntoHolding = MaxAssetsIntoHolding; + type AssetLocker = (); + type AssetExchanger = (); + type FeeManager = (); + type MessageExporter = (); + type UniversalAliases = Nothing; + type CallDispatcher = RuntimeCall; + type SafeCallFilter = Everything; + type Aliasers = Nothing; +} + +impl cumulus_pallet_xcm::Config for Runtime { + type RuntimeEvent = RuntimeEvent; + type XcmExecutor = xcm_executor::XcmExecutor; +} diff --git a/cumulus/parachains/runtimes/glutton/glutton-westend/Cargo.toml b/cumulus/parachains/runtimes/glutton/glutton-westend/Cargo.toml index 831e3242766..a30cdf35769 100644 --- a/cumulus/parachains/runtimes/glutton/glutton-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/glutton/glutton-westend/Cargo.toml @@ -6,48 +6,45 @@ edition.workspace = true license = "Apache-2.0" description = "Glutton parachain runtime." -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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, optional = true } -pallet-sudo = { path = "../../../../../substrate/frame/sudo", default-features = false, optional = true } +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, optional = true} +pallet-sudo = { path = "../../../../../substrate/frame/sudo", default-features = false, optional = true} 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-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-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-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 } +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} # 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 = { 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} # Cumulus cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } 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 } @@ -59,7 +56,7 @@ parachains-common = { path = "../../../common", default-features = false } substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder" } [features] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ "cumulus-pallet-parachain-system/runtime-benchmarks", "cumulus-primitives-core/runtime-benchmarks", @@ -133,9 +130,9 @@ try-runtime = [ "sp-runtime/try-runtime", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] # A feature that should be enabled when the runtime should be built for on-chain # deployment. This will disable stuff that shouldn't be part of the on-chain wasm # to make it smaller like logging for example. -on-chain-release-build = ["sp-api/disable-logging"] +on-chain-release-build = [ "sp-api/disable-logging" ] diff --git a/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs b/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs index 3b5964f8828..212466f8312 100644 --- a/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs @@ -53,7 +53,7 @@ pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, - traits::{BlakeTwo256, Block as BlockT}, + traits::{AccountIdLookup, BlakeTwo256, Block as BlockT}, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, }; @@ -64,7 +64,7 @@ use sp_version::RuntimeVersion; use cumulus_primitives_core::AggregateMessageOrigin; pub use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, parameter_types, @@ -99,7 +99,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_005_000, + spec_version: 10000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -168,14 +168,25 @@ parameter_types! { pub const SS58Prefix: u8 = 42; } -#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type AccountId = AccountId; + type RuntimeCall = RuntimeCall; + type Lookup = AccountIdLookup; type Nonce = Nonce; type Hash = Hash; + type Hashing = BlakeTwo256; type Block = Block; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; type BlockHashCount = BlockHashCount; type Version = Version; + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = frame_support::traits::Everything; + type SystemWeightInfo = (); type BlockWeights = RuntimeBlockWeights; type BlockLength = RuntimeBlockLength; type SS58Prefix = SS58Prefix; diff --git a/cumulus/parachains/runtimes/starters/seedling/Cargo.toml b/cumulus/parachains/runtimes/starters/seedling/Cargo.toml index 37a3bb4ca26..65ca58ac8b3 100644 --- a/cumulus/parachains/runtimes/starters/seedling/Cargo.toml +++ b/cumulus/parachains/runtimes/starters/seedling/Cargo.toml @@ -6,37 +6,34 @@ authors.workspace = true edition.workspace = true license = "Apache-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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 } +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-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-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-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} # Cumulus cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } 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 } @@ -47,7 +44,7 @@ parachains-common = { path = "../../../common", default-features = false } substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-pallet-aura-ext/std", @@ -80,4 +77,4 @@ std = [ "substrate-wasm-builder", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] diff --git a/cumulus/parachains/runtimes/starters/seedling/src/lib.rs b/cumulus/parachains/runtimes/starters/seedling/src/lib.rs index fc59cd81edb..3d713da2afc 100644 --- a/cumulus/parachains/runtimes/starters/seedling/src/lib.rs +++ b/cumulus/parachains/runtimes/starters/seedling/src/lib.rs @@ -44,7 +44,7 @@ use sp_version::RuntimeVersion; // A few exports that help ease life for downstream crates. pub use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, parameter_types, @@ -75,7 +75,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("seedling"), impl_name: create_runtime_str!("seedling"), authoring_version: 1, - spec_version: 1, + spec_version: 10000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 2, @@ -134,8 +134,6 @@ parameter_types! { .build_or_panic(); pub const SS58Prefix: u8 = 42; } - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { /// The identifier used to distinguish between accounts. type AccountId = AccountId; diff --git a/cumulus/parachains/runtimes/starters/shell/Cargo.toml b/cumulus/parachains/runtimes/starters/shell/Cargo.toml index 3d7042ecd49..77449f977bb 100644 --- a/cumulus/parachains/runtimes/starters/shell/Cargo.toml +++ b/cumulus/parachains/runtimes/starters/shell/Cargo.toml @@ -6,42 +6,39 @@ authors.workspace = true edition.workspace = true license = "Apache-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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-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-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-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-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-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 } # 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 = { 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} # Cumulus cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } 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 } @@ -51,7 +48,7 @@ parachains-common = { path = "../../../common", default-features = false } substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-pallet-aura-ext/std", @@ -100,4 +97,4 @@ try-runtime = [ "sp-runtime/try-runtime", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] diff --git a/cumulus/parachains/runtimes/starters/shell/src/lib.rs b/cumulus/parachains/runtimes/starters/shell/src/lib.rs index 504c55a21eb..62c362aee53 100644 --- a/cumulus/parachains/runtimes/starters/shell/src/lib.rs +++ b/cumulus/parachains/runtimes/starters/shell/src/lib.rs @@ -56,7 +56,7 @@ use sp_version::RuntimeVersion; // A few exports that help ease life for downstream crates. pub use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, parameter_types, @@ -147,7 +147,6 @@ parameter_types! { pub const SS58Prefix: u8 = 42; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { /// The identifier used to distinguish between accounts. type AccountId = AccountId; diff --git a/cumulus/parachains/runtimes/test-utils/Cargo.toml b/cumulus/parachains/runtimes/test-utils/Cargo.toml index cd100c472ce..62bce02bd35 100644 --- a/cumulus/parachains/runtimes/test-utils/Cargo.toml +++ b/cumulus/parachains/runtimes/test-utils/Cargo.toml @@ -6,41 +6,38 @@ edition.workspace = true description = "Utils for Runtimes testing" license = "Apache-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive", "max-encoded-len"] } # 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-session = { path = "../../../../substrate/frame/session", 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 } +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-session = { path = "../../../../substrate/frame/session", 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 } +sp-core = { path = "../../../../substrate/primitives/core", default-features = false} # Cumulus -cumulus-pallet-parachain-system = { path = "../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } +cumulus-pallet-parachain-system = { path = "../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } 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 } -parachain-info = { package = "staging-parachain-info", path = "../../pallets/parachain-info", default-features = false } +parachain-info = {package = "staging-parachain-info", path = "../../pallets/parachain-info", default-features = false } assets-common = { path = "../assets/common", 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 } # 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 = { 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} [dev-dependencies] hex-literal = "0.4.1" @@ -49,7 +46,7 @@ hex-literal = "0.4.1" substrate-wasm-builder = { path = "../../../../substrate/utils/wasm-builder" } [features] -default = ["std"] +default = [ "std" ] std = [ "assets-common/std", "codec/std", diff --git a/cumulus/parachains/runtimes/test-utils/src/lib.rs b/cumulus/parachains/runtimes/test-utils/src/lib.rs index ca1e1633d4f..e2a6fb45aec 100644 --- a/cumulus/parachains/runtimes/test-utils/src/lib.rs +++ b/cumulus/parachains/runtimes/test-utils/src/lib.rs @@ -114,48 +114,35 @@ impl BasicParachainRuntime for T -where - T: frame_system::Config +// Basic builder based on balances, collators and pallet_sessopm +pub struct ExtBuilder< + Runtime: frame_system::Config + pallet_balances::Config + pallet_session::Config + pallet_xcm::Config - + parachain_info::Config - + pallet_collator_selection::Config - + cumulus_pallet_parachain_system::Config, - ValidatorIdOf: From>, -{ -} - -/// Basic builder based on balances, collators and pallet_session. -pub struct ExtBuilder { + + parachain_info::Config, +> { // endowed accounts with balances balances: Vec<(AccountIdOf, BalanceOf)>, // collators to test block prod collators: Vec>, // keys added to pallet session keys: Vec<(AccountIdOf, ValidatorIdOf, SessionKeysOf)>, - // safe XCM version for pallet_xcm + // safe xcm version for pallet_xcm safe_xcm_version: Option, // para id para_id: Option, _runtime: PhantomData, } -impl Default for ExtBuilder { +impl< + Runtime: frame_system::Config + + pallet_balances::Config + + pallet_session::Config + + pallet_xcm::Config + + parachain_info::Config, + > Default for ExtBuilder +{ fn default() -> ExtBuilder { ExtBuilder { balances: vec![], @@ -168,7 +155,14 @@ impl Default for ExtBuilder { } } -impl ExtBuilder { +impl< + Runtime: frame_system::Config + + pallet_balances::Config + + pallet_session::Config + + pallet_xcm::Config + + parachain_info::Config, + > ExtBuilder +{ pub fn with_balances( mut self, balances: Vec<(AccountIdOf, BalanceOf)>, @@ -204,7 +198,12 @@ impl ExtBuilder { self } - pub fn build(self) -> sp_io::TestExternalities { + pub fn build(self) -> sp_io::TestExternalities + where + Runtime: + pallet_collator_selection::Config + pallet_balances::Config + pallet_session::Config, + ValidatorIdOf: From>, + { let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); pallet_xcm::GenesisConfig:: { diff --git a/cumulus/parachains/runtimes/testing/penpal/Cargo.toml b/cumulus/parachains/runtimes/testing/penpal/Cargo.toml index 4e2d145feb4..fb66275b025 100644 --- a/cumulus/parachains/runtimes/testing/penpal/Cargo.toml +++ b/cumulus/parachains/runtimes/testing/penpal/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true edition.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -25,52 +22,52 @@ scale-info = { version = "2.10.0", default-features = false, features = ["derive smallvec = "1.11.0" # 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 } +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 } +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} # 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 } +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} # 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-dmp-queue = { path = "../../../../pallets/dmp-queue", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } +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 } @@ -80,7 +77,7 @@ parachain-info = { package = "staging-parachain-info", path = "../../../pallets/ parachains-common = { path = "../../../common", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-pallet-aura-ext/std", @@ -193,4 +190,4 @@ try-runtime = [ "sp-runtime/try-runtime", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] diff --git a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs index 6dc3a13ff16..825c7d916c7 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs @@ -35,7 +35,7 @@ pub mod xcm_config; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, pallet_prelude::Weight, @@ -230,7 +230,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("penpal-parachain"), impl_name: create_runtime_str!("penpal-parachain"), authoring_version: 1, - spec_version: 1, + spec_version: 10000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -323,7 +323,6 @@ parameter_types! { // Configure FRAME pallets to include in runtime. -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { /// The identifier used to distinguish between accounts. type AccountId = AccountId; diff --git a/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs b/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs index e4f0afc854b..74d9a0b071d 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs @@ -44,16 +44,15 @@ use polkadot_parachain_primitives::primitives::Sibling; use polkadot_runtime_common::impls::ToAuthor; use sp_runtime::traits::Zero; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, AsPrefixedGeneralIndex, - ConvertedConcreteId, DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, - FixedWeightBounds, FungiblesAdapter, IsConcrete, LocalMint, NativeAsset, ParentAsSuperuser, - ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - TrailingSetTopicAsId, UsingComponents, WithComputedOrigin, WithUniqueTopic, + ConvertedConcreteId, CurrencyAdapter, DenyReserveTransferToRelayChain, DenyThenTry, + EnsureXcmOrigin, FixedWeightBounds, FungiblesAdapter, IsConcrete, LocalMint, NativeAsset, + ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, + WithComputedOrigin, WithUniqueTopic, }; use xcm_executor::{traits::JustTry, XcmExecutor}; @@ -77,7 +76,6 @@ pub type LocationToAccountId = ( ); /// Means for transacting assets on this chain. -#[allow(deprecated)] pub type CurrencyTransactor = CurrencyAdapter< // Use this currency: Balances, @@ -96,24 +94,12 @@ pub type FungiblesTransactor = FungiblesAdapter< // Use this fungibles implementation: Assets, // Use this currency when it is a fungible asset matching the given location or name: - ( - ConvertedConcreteId< - AssetIdPalletAssets, - Balance, - AsPrefixedGeneralIndex, - JustTry, - >, - ConvertedConcreteId< - AssetIdPalletAssets, - Balance, - AsPrefixedGeneralIndex< - SystemAssetHubAssetsPalletLocation, - AssetIdPalletAssets, - JustTry, - >, - JustTry, - >, - ), + ConvertedConcreteId< + AssetIdPalletAssets, + Balance, + AsPrefixedGeneralIndex, + JustTry, + >, // Convert an XCM MultiLocation into a local account id: LocationToAccountId, // Our chain's account ID type (we can't get away without mentioning it explicitly): @@ -251,8 +237,6 @@ where } } -// This asset can be added to AH as ForeignAsset and teleported between Penpal and AH -pub const TELEPORTABLE_ASSET_ID: u32 = 2; parameter_types! { /// The location that this chain recognizes as the Relay network's Asset Hub. pub SystemAssetHubLocation: MultiLocation = MultiLocation::new(1, X1(Parachain(1000))); @@ -260,30 +244,11 @@ parameter_types! { // the Relay Chain's Asset Hub's Assets pallet index pub SystemAssetHubAssetsPalletLocation: MultiLocation = MultiLocation::new(1, X2(Parachain(1000), PalletInstance(50))); - pub AssetsPalletLocation: MultiLocation = - MultiLocation::new(0, X1(PalletInstance(50))); pub CheckingAccount: AccountId = PolkadotXcm::check_account(); - pub LocalTeleportableToAssetHub: MultiLocation = MultiLocation::new( - 0, - X2(PalletInstance(50), GeneralIndex(TELEPORTABLE_ASSET_ID.into())) - ); -} - -/// Accepts asset with ID `AssetLocation` and is coming from `Origin` chain. -pub struct AssetFromChain(PhantomData<(AssetLocation, Origin)>); -impl, Origin: Get> - ContainsPair for AssetFromChain -{ - fn contains(asset: &MultiAsset, origin: &MultiLocation) -> bool { - log::trace!(target: "xcm::contains", "AssetFromChain asset: {:?}, origin: {:?}", asset, origin); - *origin == Origin::get() && matches!(asset.id, Concrete(id) if id == AssetLocation::get()) - } } pub type Reserves = (NativeAsset, AssetsFrom, NativeAssetFrom); -pub type TrustedTeleporters = - (AssetFromChain,); pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { @@ -294,7 +259,7 @@ impl xcm_executor::Config for XcmConfig { type OriginConverter = XcmOriginToTransactDispatchOrigin; type IsReserve = Reserves; // no teleport trust established with other chains - type IsTeleporter = TrustedTeleporters; + type IsTeleporter = NativeAsset; type UniversalLocation = UniversalLocation; type Barrier = Barrier; type Weigher = FixedWeightBounds; diff --git a/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml b/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml index a23b7558bce..08fa8b69127 100644 --- a/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml +++ b/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml @@ -6,52 +6,49 @@ edition.workspace = true description = "Simple runtime used by the rococo parachain(s)" license = "Apache-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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 } +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 } +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} # 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 } +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 } # 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-dmp-queue = { path = "../../../../pallets/dmp-queue", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } +cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } 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 } @@ -65,7 +62,7 @@ parachain-info = { package = "staging-parachain-info", path = "../../../pallets/ substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-pallet-aura-ext/std", @@ -136,4 +133,4 @@ runtime-benchmarks = [ "xcm-executor/runtime-benchmarks", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] diff --git a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs index 81c73b9fc3f..17579758fb8 100644 --- a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs @@ -39,7 +39,7 @@ use sp_version::RuntimeVersion; // A few exports that help ease life for downstream crates. pub use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, match_types, parameter_types, @@ -83,14 +83,12 @@ use xcm_executor::traits::JustTry; use pallet_xcm::{EnsureXcm, IsMajorityOfBody, XcmPassthrough}; use polkadot_parachain_primitives::primitives::Sibling; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, - EnsureXcmOrigin, FixedWeightBounds, IsConcrete, NativeAsset, ParentAsSuperuser, ParentIsPreset, - RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - UsingComponents, + CurrencyAdapter, EnsureXcmOrigin, FixedWeightBounds, IsConcrete, NativeAsset, + ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, UsingComponents, }; use xcm_executor::XcmExecutor; @@ -108,7 +106,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_005_000, + spec_version: 10000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 6, @@ -186,7 +184,6 @@ parameter_types! { pub const SS58Prefix: u8 = 42; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { /// The identifier used to distinguish between accounts. type AccountId = AccountId; @@ -347,7 +344,6 @@ pub type LocationToAccountId = ( ); /// Means for transacting assets on this chain. -#[allow(deprecated)] pub type CurrencyTransactor = CurrencyAdapter< // Use this currency: Balances, diff --git a/cumulus/parachains/testnets-common/Cargo.toml b/cumulus/parachains/testnets-common/Cargo.toml new file mode 100644 index 00000000000..e39cf91d3ab --- /dev/null +++ b/cumulus/parachains/testnets-common/Cargo.toml @@ -0,0 +1,44 @@ +[package] +name = "testnets-common" +version = "1.0.0" +authors.workspace = true +edition.workspace = true +description = "Logic and configuration specific to testnet parachain runtimes" +license = "Apache-2.0" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +smallvec = "1.11.0" + +# Substrate +frame-support = { path = "../../../substrate/frame/support", default-features = false } +sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } + +# Polkadot +rococo-runtime-constants = { path = "../../../polkadot/runtime/rococo/constants", default-features = false} +westend-runtime-constants = { path = "../../../polkadot/runtime/westend/constants", default-features = false} +polkadot-core-primitives = { path = "../../../polkadot/core-primitives", default-features = false} + +# Cumulus + +[dev-dependencies] + +[build-dependencies] +substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder" } + +[features] +default = [ "std" ] +std = [ + "frame-support/std", + "polkadot-core-primitives/std", + "rococo-runtime-constants/std", + "sp-runtime/std", + "westend-runtime-constants/std", +] + +runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", +] diff --git a/cumulus/parachains/testnets-common/src/lib.rs b/cumulus/parachains/testnets-common/src/lib.rs new file mode 100644 index 00000000000..42d367bff27 --- /dev/null +++ b/cumulus/parachains/testnets-common/src/lib.rs @@ -0,0 +1,30 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![cfg_attr(not(feature = "std"), no_std)] + +/// Since the parachains-common package is now published to crates.io, SP runtimes for testnets +/// will be adapted to use this package, and their config removed from the published common +/// package. Only the configs specific to rococo, westend and wococo will be moved here, and the +/// truly common logic will still be sourced from the parachains-common package. +/// +/// In practice this just means that instead of using e.g. `[parachains_common::westend::*]`, now +/// the westend configs will be in `[testnets_common::westend::*]`. +/// +/// TODO: edit all runtimes to remove the testnet configs as part of PR #1737 +/// +pub mod rococo; +pub mod westend; +pub mod wococo; diff --git a/cumulus/parachains/testnets-common/src/rococo.rs b/cumulus/parachains/testnets-common/src/rococo.rs new file mode 100644 index 00000000000..6e31def4b55 --- /dev/null +++ b/cumulus/parachains/testnets-common/src/rococo.rs @@ -0,0 +1,119 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub mod currency { + use polkadot_core_primitives::Balance; + use rococo_runtime_constants as constants; + + /// The existential deposit. Set to 1/10 of its parent Relay Chain (v9010). + pub const EXISTENTIAL_DEPOSIT: Balance = constants::currency::EXISTENTIAL_DEPOSIT / 10; + + pub const UNITS: Balance = constants::currency::UNITS; + pub const CENTS: Balance = constants::currency::CENTS; + pub const MILLICENTS: Balance = constants::currency::MILLICENTS; + + pub const fn deposit(items: u32, bytes: u32) -> Balance { + // map to 1/100 of what the rococo relay chain charges + constants::currency::deposit(items, bytes) / 100 + } +} + +pub mod fee { + use frame_support::{ + pallet_prelude::Weight, + weights::{ + constants::ExtrinsicBaseWeight, FeePolynomial, WeightToFeeCoefficient, + WeightToFeeCoefficients, WeightToFeePolynomial, + }, + }; + use polkadot_core_primitives::Balance; + use smallvec::smallvec; + pub use sp_runtime::Perbill; + + /// The block saturation level. Fees will be updates based on this value. + pub const TARGET_BLOCK_FULLNESS: Perbill = Perbill::from_percent(25); + + /// Handles converting a weight scalar to a fee value, based on the scale and granularity of the + /// node's balance type. + /// + /// This should typically create a mapping between the following ranges: + /// - `[0, MAXIMUM_BLOCK_WEIGHT]` + /// - `[Balance::min, Balance::max]` + /// + /// Yet, it can be used for any other sort of change to weight-fee. Some examples being: + /// - Setting it to `0` will essentially disable the weight fee. + /// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged. + pub struct WeightToFee; + impl frame_support::weights::WeightToFee for WeightToFee { + type Balance = Balance; + + fn weight_to_fee(weight: &Weight) -> Self::Balance { + let time_poly: FeePolynomial = RefTimeToFee::polynomial().into(); + let proof_poly: FeePolynomial = ProofSizeToFee::polynomial().into(); + + // Take the maximum instead of the sum to charge by the more scarce resource. + time_poly.eval(weight.ref_time()).max(proof_poly.eval(weight.proof_size())) + } + } + + /// Maps the reference time component of `Weight` to a fee. + pub struct RefTimeToFee; + impl WeightToFeePolynomial for RefTimeToFee { + type Balance = Balance; + fn polynomial() -> WeightToFeeCoefficients { + // In Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1/10 CENT: + // The standard system parachain configuration is 1/10 of that, as in 1/100 CENT. + let p = super::currency::CENTS; + let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time()); + + smallvec![WeightToFeeCoefficient { + degree: 1, + negative: false, + coeff_frac: Perbill::from_rational(p % q, q), + coeff_integer: p / q, + }] + } + } + + /// Maps the proof size component of `Weight` to a fee. + pub struct ProofSizeToFee; + impl WeightToFeePolynomial for ProofSizeToFee { + type Balance = Balance; + fn polynomial() -> WeightToFeeCoefficients { + // Map 10kb proof to 1 CENT. + let p = super::currency::CENTS; + let q = 10_000; + + smallvec![WeightToFeeCoefficient { + degree: 1, + negative: false, + coeff_frac: Perbill::from_rational(p % q, q), + coeff_integer: p / q, + }] + } + } +} + +/// Consensus-related. +pub mod consensus { + /// Maximum number of blocks simultaneously accepted by the Runtime, not yet included + /// into the relay chain. + pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 1; + /// How many parachain blocks are processed by the relay chain per parent. Limits the + /// number of blocks authored per slot. + pub const BLOCK_PROCESSING_VELOCITY: u32 = 1; + /// Relay chain slot duration, in milliseconds. + pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000; +} diff --git a/cumulus/parachains/testnets-common/src/westend.rs b/cumulus/parachains/testnets-common/src/westend.rs new file mode 100644 index 00000000000..0ae21e23454 --- /dev/null +++ b/cumulus/parachains/testnets-common/src/westend.rs @@ -0,0 +1,140 @@ +// 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. + +/// Universally recognized accounts. +pub mod account { + use frame_support::PalletId; + + /// Westend treasury pallet id, used to convert into AccountId - in Westend as a destination for + /// slashed funds. + pub const WESTEND_TREASURY_PALLET_ID: PalletId = PalletId(*b"py/trsry"); + /// Alliance pallet ID - used as a temporary place to deposit a slashed imbalance before the + /// teleport to the Treasury. + pub const ALLIANCE_PALLET_ID: PalletId = PalletId(*b"py/allia"); + /// Referenda pallet ID - used as a temporary place to deposit a slashed imbalance before the + /// teleport to the Treasury. + pub const REFERENDA_PALLET_ID: PalletId = PalletId(*b"py/refer"); + /// Ambassador Referenda pallet ID - used as a temporary place to deposit a slashed imbalance + /// before the teleport to the Treasury. + pub const AMBASSADOR_REFERENDA_PALLET_ID: PalletId = PalletId(*b"py/amref"); +} + +pub mod currency { + use polkadot_core_primitives::Balance; + use westend_runtime_constants as constants; + + /// The existential deposit. Set to 1/10 of its parent Relay Chain. + pub const EXISTENTIAL_DEPOSIT: Balance = constants::currency::EXISTENTIAL_DEPOSIT / 10; + + pub const UNITS: Balance = constants::currency::UNITS; + pub const DOLLARS: Balance = UNITS; // 1_000_000_000_000 + pub const CENTS: Balance = constants::currency::CENTS; + pub const MILLICENTS: Balance = constants::currency::MILLICENTS; + pub const GRAND: Balance = constants::currency::GRAND; + + pub const fn deposit(items: u32, bytes: u32) -> Balance { + // 1/100 of Westend testnet + constants::currency::deposit(items, bytes) / 100 + } +} + +/// Fee-related. +pub mod fee { + use frame_support::{ + pallet_prelude::Weight, + weights::{ + constants::ExtrinsicBaseWeight, FeePolynomial, WeightToFeeCoefficient, + WeightToFeeCoefficients, WeightToFeePolynomial, + }, + }; + use polkadot_core_primitives::Balance; + use smallvec::smallvec; + pub use sp_runtime::Perbill; + + /// The block saturation level. Fees will be updated based on this value. + pub const TARGET_BLOCK_FULLNESS: Perbill = Perbill::from_percent(25); + + /// Handles converting a weight scalar to a fee value, based on the scale and granularity of the + /// node's balance type. + /// + /// This should typically create a mapping between the following ranges: + /// - [0, MAXIMUM_BLOCK_WEIGHT] + /// - [Balance::min, Balance::max] + /// + /// Yet, it can be used for any other sort of change to weight-fee. Some examples being: + /// - Setting it to `0` will essentially disable the weight fee. + /// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged. + pub struct WeightToFee; + impl frame_support::weights::WeightToFee for WeightToFee { + type Balance = Balance; + + fn weight_to_fee(weight: &Weight) -> Self::Balance { + let time_poly: FeePolynomial = RefTimeToFee::polynomial().into(); + let proof_poly: FeePolynomial = ProofSizeToFee::polynomial().into(); + + // Take the maximum instead of the sum to charge by the more scarce resource. + time_poly.eval(weight.ref_time()).max(proof_poly.eval(weight.proof_size())) + } + } + + /// Maps the reference time component of `Weight` to a fee. + pub struct RefTimeToFee; + impl WeightToFeePolynomial for RefTimeToFee { + type Balance = Balance; + fn polynomial() -> WeightToFeeCoefficients { + // In Westend, extrinsic base weight (smallest non-zero weight) is mapped to 1/10 CENT: + // The standard system parachain configuration is 1/10 of that, as in 1/100 CENT. + let p = super::currency::CENTS; + let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time()); + + smallvec![WeightToFeeCoefficient { + degree: 1, + negative: false, + coeff_frac: Perbill::from_rational(p % q, q), + coeff_integer: p / q, + }] + } + } + + /// Maps the proof size component of `Weight` to a fee. + pub struct ProofSizeToFee; + impl WeightToFeePolynomial for ProofSizeToFee { + type Balance = Balance; + fn polynomial() -> WeightToFeeCoefficients { + // Map 10kb proof to 1 CENT. + let p = super::currency::CENTS; + let q = 10_000; + + smallvec![WeightToFeeCoefficient { + degree: 1, + negative: false, + coeff_frac: Perbill::from_rational(p % q, q), + coeff_integer: p / q, + }] + } + } +} + +/// Consensus-related. +pub mod consensus { + /// Maximum number of blocks simultaneously accepted by the Runtime, not yet included into the + /// relay chain. + pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 1; + /// How many parachain blocks are processed by the relay chain per parent. Limits the number of + /// blocks authored per slot. + pub const BLOCK_PROCESSING_VELOCITY: u32 = 1; + /// Relay chain slot duration, in milliseconds. + pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000; +} diff --git a/substrate/frame/contracts/uapi/src/host/riscv32.rs b/cumulus/parachains/testnets-common/src/wococo.rs similarity index 77% rename from substrate/frame/contracts/uapi/src/host/riscv32.rs rename to cumulus/parachains/testnets-common/src/wococo.rs index f58b8831f06..5cd6121135a 100644 --- a/substrate/frame/contracts/uapi/src/host/riscv32.rs +++ b/cumulus/parachains/testnets-common/src/wococo.rs @@ -1,14 +1,17 @@ // 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 +// 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. -// TODO: bring up to date with wasm32.rs + +// re-export rococo +pub use crate::rococo::{consensus, currency, fee}; diff --git a/cumulus/polkadot-parachain/Cargo.toml b/cumulus/polkadot-parachain/Cargo.toml index b8c1508da09..e23a7aeb22b 100644 --- a/cumulus/polkadot-parachain/Cargo.toml +++ b/cumulus/polkadot-parachain/Cargo.toml @@ -1,39 +1,42 @@ [package] name = "polkadot-parachain-bin" -version = "1.5.0" +version = "1.1.0" authors.workspace = true build = "build.rs" edition.workspace = true description = "Runs a polkadot parachain node which could be a collator." license = "Apache-2.0" -[lints] -workspace = true - [[bin]] name = "polkadot-parachain" path = "src/main.rs" [dependencies] async-trait = "0.1.73" -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.0.0" } futures = "0.3.28" hex-literal = "0.4.1" log = "0.4.20" -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.108" # 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" } +glutton-runtime = { path = "../parachains/runtimes/glutton/glutton-kusama" } seedling-runtime = { path = "../parachains/runtimes/starters/seedling" } +asset-hub-polkadot-runtime = { path = "../parachains/runtimes/assets/asset-hub-polkadot" } +asset-hub-kusama-runtime = { path = "../parachains/runtimes/assets/asset-hub-kusama" } asset-hub-rococo-runtime = { path = "../parachains/runtimes/assets/asset-hub-rococo" } asset-hub-westend-runtime = { path = "../parachains/runtimes/assets/asset-hub-westend" } +collectives-polkadot-runtime = { path = "../parachains/runtimes/collectives/collectives-polkadot" } 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" } +bridge-hub-kusama-runtime = { path = "../parachains/runtimes/bridge-hubs/bridge-hub-kusama" } +bridge-hub-polkadot-runtime = { path = "../parachains/runtimes/bridge-hubs/bridge-hub-polkadot" } bridge-hub-westend-runtime = { path = "../parachains/runtimes/bridge-hubs/bridge-hub-westend" } penpal-runtime = { path = "../parachains/runtimes/testing/penpal" } jsonrpsee = { version = "0.16.2", features = ["server"] } @@ -42,7 +45,7 @@ parachains-common = { path = "../parachains/common" } # 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-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" } @@ -112,22 +115,28 @@ substrate-build-script-utils = { path = "../../substrate/utils/build-script-util assert_cmd = "2.0" nix = { version = "0.26.1", features = ["signal"] } tempfile = "3.8.0" -tokio = { version = "1.32.0", features = ["macros", "parking_lot", "time"] } +tokio = { version = "1.32.0", features = ["macros", "time", "parking_lot"] } wait-timeout = "0.2" [features] default = [] runtime-benchmarks = [ + "asset-hub-kusama-runtime/runtime-benchmarks", + "asset-hub-polkadot-runtime/runtime-benchmarks", "asset-hub-rococo-runtime/runtime-benchmarks", "asset-hub-westend-runtime/runtime-benchmarks", + "bridge-hub-kusama-runtime/runtime-benchmarks", + "bridge-hub-polkadot-runtime/runtime-benchmarks", "bridge-hub-rococo-runtime/runtime-benchmarks", "bridge-hub-westend-runtime/runtime-benchmarks", + "collectives-polkadot-runtime/runtime-benchmarks", "collectives-westend-runtime/runtime-benchmarks", "contracts-rococo-runtime/runtime-benchmarks", "cumulus-primitives-core/runtime-benchmarks", "frame-benchmarking-cli/runtime-benchmarks", "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", + "glutton-runtime/runtime-benchmarks", "glutton-westend-runtime/runtime-benchmarks", "parachains-common/runtime-benchmarks", "penpal-runtime/runtime-benchmarks", @@ -139,14 +148,20 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", ] try-runtime = [ + "asset-hub-kusama-runtime/try-runtime", + "asset-hub-polkadot-runtime/try-runtime", "asset-hub-rococo-runtime/try-runtime", "asset-hub-westend-runtime/try-runtime", + "bridge-hub-kusama-runtime/try-runtime", + "bridge-hub-polkadot-runtime/try-runtime", "bridge-hub-rococo-runtime/try-runtime", "bridge-hub-westend-runtime/try-runtime", + "collectives-polkadot-runtime/try-runtime", "collectives-westend-runtime/try-runtime", "contracts-rococo-runtime/try-runtime", "frame-support/try-runtime", "frame-try-runtime/try-runtime", + "glutton-runtime/try-runtime", "glutton-westend-runtime/try-runtime", "pallet-transaction-payment/try-runtime", "penpal-runtime/try-runtime", diff --git a/cumulus/polkadot-parachain/src/chain_spec/asset_hubs.rs b/cumulus/polkadot-parachain/src/chain_spec/asset_hubs.rs index f889e05a166..2988d6af0d1 100644 --- a/cumulus/polkadot-parachain/src/chain_spec/asset_hubs.rs +++ b/cumulus/polkadot-parachain/src/chain_spec/asset_hubs.rs @@ -20,15 +20,35 @@ use crate::chain_spec::{ }; use cumulus_primitives_core::ParaId; use hex_literal::hex; -use parachains_common::{AccountId, AuraId, Balance as AssetHubBalance}; +use parachains_common::{AccountId, AssetHubPolkadotAuraId, AuraId, Balance as AssetHubBalance}; use sc_service::ChainType; use sp_core::{crypto::UncheckedInto, sr25519}; +const ASSET_HUB_POLKADOT_ED: AssetHubBalance = + parachains_common::polkadot::currency::EXISTENTIAL_DEPOSIT; +const ASSET_HUB_KUSAMA_ED: AssetHubBalance = + parachains_common::kusama::currency::EXISTENTIAL_DEPOSIT; const ASSET_HUB_WESTEND_ED: AssetHubBalance = parachains_common::westend::currency::EXISTENTIAL_DEPOSIT; const ASSET_HUB_ROCOCO_ED: AssetHubBalance = parachains_common::westend::currency::EXISTENTIAL_DEPOSIT; +/// Generate the session keys from individual elements. +/// +/// The input must be a tuple of individual keys (a single arg for now since we have just one key). +pub fn asset_hub_polkadot_session_keys( + keys: AssetHubPolkadotAuraId, +) -> asset_hub_polkadot_runtime::SessionKeys { + asset_hub_polkadot_runtime::SessionKeys { aura: keys } +} + +/// Generate the session keys from individual elements. +/// +/// The input must be a tuple of individual keys (a single arg for now since we have just one key). +pub fn asset_hub_kusama_session_keys(keys: AuraId) -> asset_hub_kusama_runtime::SessionKeys { + asset_hub_kusama_runtime::SessionKeys { aura: keys } +} + /// Generate the session keys from individual elements. /// /// The input must be a tuple of individual keys (a single arg for now since we have just one key). @@ -43,6 +63,341 @@ pub fn asset_hub_westend_session_keys(keys: AuraId) -> asset_hub_westend_runtime asset_hub_westend_runtime::SessionKeys { aura: keys } } +pub fn asset_hub_polkadot_development_config() -> GenericChainSpec { + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("ss58Format".into(), 0.into()); + properties.insert("tokenSymbol".into(), "DOT".into()); + properties.insert("tokenDecimals".into(), 10.into()); + + GenericChainSpec::builder( + asset_hub_polkadot_runtime::WASM_BINARY + .expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: "polkadot-dev".into(), para_id: 1000 }, + ) + .with_name("Polkadot Asset Hub Development") + .with_id("asset-hub-polkadot-dev") + .with_chain_type(ChainType::Local) + .with_genesis_config_patch(asset_hub_polkadot_genesis( + // initial collators. + vec![( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed::("Alice"), + )], + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + ], + 1000.into(), + )) + .with_properties(properties) + .build() +} + +pub fn asset_hub_polkadot_local_config() -> GenericChainSpec { + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("ss58Format".into(), 0.into()); + properties.insert("tokenSymbol".into(), "DOT".into()); + properties.insert("tokenDecimals".into(), 10.into()); + + GenericChainSpec::builder( + asset_hub_polkadot_runtime::WASM_BINARY + .expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: "polkadot-local".into(), para_id: 1000 }, + ) + .with_name("Polkadot Asset Hub Local") + .with_id("asset-hub-polkadot-local") + .with_chain_type(ChainType::Local) + .with_genesis_config_patch(asset_hub_polkadot_genesis( + // initial collators. + vec![ + ( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed::("Alice"), + ), + ( + get_account_id_from_seed::("Bob"), + get_collator_keys_from_seed::("Bob"), + ), + ], + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Charlie"), + get_account_id_from_seed::("Dave"), + get_account_id_from_seed::("Eve"), + get_account_id_from_seed::("Ferdie"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + get_account_id_from_seed::("Charlie//stash"), + get_account_id_from_seed::("Dave//stash"), + get_account_id_from_seed::("Eve//stash"), + get_account_id_from_seed::("Ferdie//stash"), + ], + 1000.into(), + )) + .with_boot_nodes(Vec::new()) + .with_properties(properties) + .build() +} + +// Not used for syncing, but just to determine the genesis values set for the upgrade from shell. +pub fn asset_hub_polkadot_config() -> GenericChainSpec { + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("ss58Format".into(), 0.into()); + properties.insert("tokenSymbol".into(), "DOT".into()); + properties.insert("tokenDecimals".into(), 10.into()); + + GenericChainSpec::builder( + asset_hub_polkadot_runtime::WASM_BINARY + .expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: "polkadot".into(), para_id: 1000 }, + ) + .with_name("Polkadot Asset Hub") + .with_id("asset-hub-polkadot") + .with_chain_type(ChainType::Live) + .with_genesis_config_patch(asset_hub_polkadot_genesis( + // initial collators. + vec![ + ( + hex!("4c3d674d2a01060f0ded218e5dcc6f90c1726f43df79885eb3e22d97a20d5421").into(), + hex!("4c3d674d2a01060f0ded218e5dcc6f90c1726f43df79885eb3e22d97a20d5421") + .unchecked_into(), + ), + ( + hex!("c7d7d38d16bc23c6321152c50306212dc22c0efc04a2e52b5cccfc31ab3d7811").into(), + hex!("c7d7d38d16bc23c6321152c50306212dc22c0efc04a2e52b5cccfc31ab3d7811") + .unchecked_into(), + ), + ( + hex!("c5c07ba203d7375675f5c1ebe70f0a5bb729ae57b48bcc877fcc2ab21309b762").into(), + hex!("c5c07ba203d7375675f5c1ebe70f0a5bb729ae57b48bcc877fcc2ab21309b762") + .unchecked_into(), + ), + ( + hex!("0b2d0013fb974794bd7aa452465b567d48ef70373fe231a637c1fb7c547e85b3").into(), + hex!("0b2d0013fb974794bd7aa452465b567d48ef70373fe231a637c1fb7c547e85b3") + .unchecked_into(), + ), + ], + vec![], + 1000u32.into(), + )) + .with_boot_nodes(vec![ + "/ip4/34.65.251.121/tcp/30334/p2p/12D3KooWG3GrM6XKMM4gp3cvemdwUvu96ziYoJmqmetLZBXE8bSa" + .parse() + .unwrap(), + "/ip4/34.65.35.228/tcp/30334/p2p/12D3KooWMRyTLrCEPcAQD6c4EnudL3vVzg9zji3whvsMYPUYevpq" + .parse() + .unwrap(), + "/ip4/34.83.247.146/tcp/30334/p2p/12D3KooWE4jFh5FpJDkWVZhnWtFnbSqRhdjvC7Dp9b8b3FTuubQC" + .parse() + .unwrap(), + "/ip4/104.199.117.230/tcp/30334/p2p/12D3KooWG9R8pVXKumVo2rdkeVD4j5PVhRTqmYgLHY3a4yPYgLqM" + .parse() + .unwrap(), + ]) + .with_properties(properties) + .build() +} + +fn asset_hub_polkadot_genesis( + invulnerables: Vec<(AccountId, AssetHubPolkadotAuraId)>, + endowed_accounts: Vec, + id: ParaId, +) -> serde_json::Value { + serde_json::json!( { + "balances": { + "balances": endowed_accounts + .iter() + .cloned() + .map(|k| (k, ASSET_HUB_POLKADOT_ED * 4096)) + .collect::>(), + }, + "parachainInfo": { + "parachainId": id, + }, + "collatorSelection": { + "invulnerables": invulnerables.iter().cloned().map(|(acc, _)| acc).collect::>(), + "candidacyBond": ASSET_HUB_POLKADOT_ED * 16, + }, + "session": { + "keys": invulnerables + .into_iter() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + asset_hub_polkadot_session_keys(aura), // session keys + ) + }) + .collect::>(), + }, + "polkadotXcm": { + "safeXcmVersion": Some(SAFE_XCM_VERSION), + } + }) +} + +pub fn asset_hub_kusama_development_config() -> GenericChainSpec { + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("ss58Format".into(), 2.into()); + properties.insert("tokenSymbol".into(), "KSM".into()); + properties.insert("tokenDecimals".into(), 12.into()); + + GenericChainSpec::builder( + asset_hub_kusama_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: "kusama-dev".into(), para_id: 1000 }, + ) + .with_name("Kusama Asset Hub Development") + .with_id("asset-hub-kusama-dev") + .with_chain_type(ChainType::Local) + .with_genesis_config_patch(asset_hub_kusama_genesis( + // initial collators. + vec![( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed::("Alice"), + )], + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + ], + 1000.into(), + )) + .with_properties(properties) + .build() +} + +pub fn asset_hub_kusama_local_config() -> GenericChainSpec { + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("ss58Format".into(), 2.into()); + properties.insert("tokenSymbol".into(), "KSM".into()); + properties.insert("tokenDecimals".into(), 12.into()); + + GenericChainSpec::builder( + asset_hub_kusama_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: "kusama-local".into(), para_id: 1000 }, + ) + .with_name("Kusama Asset Hub Local") + .with_id("asset-hub-kusama-local") + .with_chain_type(ChainType::Local) + .with_genesis_config_patch(asset_hub_kusama_genesis( + // initial collators. + vec![ + ( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed::("Alice"), + ), + ( + get_account_id_from_seed::("Bob"), + get_collator_keys_from_seed::("Bob"), + ), + ], + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Charlie"), + get_account_id_from_seed::("Dave"), + get_account_id_from_seed::("Eve"), + get_account_id_from_seed::("Ferdie"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + get_account_id_from_seed::("Charlie//stash"), + get_account_id_from_seed::("Dave//stash"), + get_account_id_from_seed::("Eve//stash"), + get_account_id_from_seed::("Ferdie//stash"), + ], + 1000.into(), + )) + .with_properties(properties) + .build() +} + +pub fn asset_hub_kusama_config() -> GenericChainSpec { + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("ss58Format".into(), 2.into()); + properties.insert("tokenSymbol".into(), "KSM".into()); + properties.insert("tokenDecimals".into(), 12.into()); + + GenericChainSpec::builder( + asset_hub_kusama_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: "kusama".into(), para_id: 1000 }, + ) + .with_name("Kusama Asset Hub") + .with_id("asset-hub-kusama") + .with_chain_type(ChainType::Live) + .with_genesis_config_patch(asset_hub_kusama_genesis( + // initial collators. + vec![ + ( + hex!("50673d59020488a4ffc9d8c6de3062a65977046e6990915617f85fef6d349730").into(), + hex!("50673d59020488a4ffc9d8c6de3062a65977046e6990915617f85fef6d349730") + .unchecked_into(), + ), + ( + hex!("fe8102dbc244e7ea2babd9f53236d67403b046154370da5c3ea99def0bd0747a").into(), + hex!("fe8102dbc244e7ea2babd9f53236d67403b046154370da5c3ea99def0bd0747a") + .unchecked_into(), + ), + ( + hex!("38144b5398e5d0da5ec936a3af23f5a96e782f676ab19d45f29075ee92eca76a").into(), + hex!("38144b5398e5d0da5ec936a3af23f5a96e782f676ab19d45f29075ee92eca76a") + .unchecked_into(), + ), + ( + hex!("3253947640e309120ae70fa458dcacb915e2ddd78f930f52bd3679ec63fc4415").into(), + hex!("3253947640e309120ae70fa458dcacb915e2ddd78f930f52bd3679ec63fc4415") + .unchecked_into(), + ), + ], + Vec::new(), + 1000.into(), + )) + .with_properties(properties) + .build() +} + +fn asset_hub_kusama_genesis( + invulnerables: Vec<(AccountId, AuraId)>, + endowed_accounts: Vec, + id: ParaId, +) -> serde_json::Value { + serde_json::json!( { + "balances": { + "balances": endowed_accounts + .iter() + .cloned() + .map(|k| (k, ASSET_HUB_KUSAMA_ED * 524_288)) + .collect::>(), + }, + "parachainInfo": { + "parachainId": id, + }, + "collatorSelection": { + "invulnerables": invulnerables.iter().cloned().map(|(acc, _)| acc).collect::>(), + "candidacyBond": ASSET_HUB_KUSAMA_ED * 16, + }, + "session": { + "keys": invulnerables + .into_iter() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + asset_hub_kusama_session_keys(aura), // session keys + ) + }) + .collect::>(), + }, + "polkadotXcm": { + "safeXcmVersion": Some(SAFE_XCM_VERSION), + }, + }) +} + pub fn asset_hub_westend_development_config() -> GenericChainSpec { let mut properties = sc_chain_spec::Properties::new(); properties.insert("tokenSymbol".into(), "WND".into()); diff --git a/cumulus/polkadot-parachain/src/chain_spec/bridge_hubs.rs b/cumulus/polkadot-parachain/src/chain_spec/bridge_hubs.rs index 8dab692c1cd..377ceb20e1e 100644 --- a/cumulus/polkadot-parachain/src/chain_spec/bridge_hubs.rs +++ b/cumulus/polkadot-parachain/src/chain_spec/bridge_hubs.rs @@ -24,14 +24,21 @@ use std::str::FromStr; /// Collects all supported BridgeHub configurations #[derive(Debug, PartialEq)] pub enum BridgeHubRuntimeType { - Kusama, - Polkadot, - Rococo, RococoLocal, // used by benchmarks RococoDevelopment, + Kusama, + KusamaLocal, + // used by benchmarks + KusamaDevelopment, + + Polkadot, + PolkadotLocal, + // used by benchmarks + PolkadotDevelopment, + Westend, WestendLocal, // used by benchmarks @@ -44,7 +51,12 @@ impl FromStr for BridgeHubRuntimeType { fn from_str(value: &str) -> Result { match value { polkadot::BRIDGE_HUB_POLKADOT => Ok(BridgeHubRuntimeType::Polkadot), + polkadot::BRIDGE_HUB_POLKADOT_LOCAL => Ok(BridgeHubRuntimeType::PolkadotLocal), + polkadot::BRIDGE_HUB_POLKADOT_DEVELOPMENT => + Ok(BridgeHubRuntimeType::PolkadotDevelopment), kusama::BRIDGE_HUB_KUSAMA => Ok(BridgeHubRuntimeType::Kusama), + kusama::BRIDGE_HUB_KUSAMA_LOCAL => Ok(BridgeHubRuntimeType::KusamaLocal), + kusama::BRIDGE_HUB_KUSAMA_DEVELOPMENT => Ok(BridgeHubRuntimeType::KusamaDevelopment), westend::BRIDGE_HUB_WESTEND => Ok(BridgeHubRuntimeType::Westend), westend::BRIDGE_HUB_WESTEND_LOCAL => Ok(BridgeHubRuntimeType::WestendLocal), westend::BRIDGE_HUB_WESTEND_DEVELOPMENT => Ok(BridgeHubRuntimeType::WestendDevelopment), @@ -64,9 +76,33 @@ impl BridgeHubRuntimeType { BridgeHubRuntimeType::Polkadot => Ok(Box::new(GenericChainSpec::from_json_bytes( &include_bytes!("../../chain-specs/bridge-hub-polkadot.json")[..], )?)), + BridgeHubRuntimeType::PolkadotLocal => Ok(Box::new(polkadot::local_config( + polkadot::BRIDGE_HUB_POLKADOT_LOCAL, + "Polkadot BridgeHub Local", + "polkadot-local", + ParaId::new(1002), + ))), + BridgeHubRuntimeType::PolkadotDevelopment => Ok(Box::new(polkadot::local_config( + polkadot::BRIDGE_HUB_POLKADOT_DEVELOPMENT, + "Polkadot BridgeHub Development", + "polkadot-dev", + ParaId::new(1002), + ))), BridgeHubRuntimeType::Kusama => Ok(Box::new(GenericChainSpec::from_json_bytes( &include_bytes!("../../chain-specs/bridge-hub-kusama.json")[..], )?)), + BridgeHubRuntimeType::KusamaLocal => Ok(Box::new(kusama::local_config( + kusama::BRIDGE_HUB_KUSAMA_LOCAL, + "Kusama BridgeHub Local", + "kusama-local", + ParaId::new(1003), + ))), + BridgeHubRuntimeType::KusamaDevelopment => Ok(Box::new(kusama::local_config( + kusama::BRIDGE_HUB_KUSAMA_DEVELOPMENT, + "Kusama BridgeHub Development", + "kusama-dev", + ParaId::new(1003), + ))), BridgeHubRuntimeType::Westend => Ok(Box::new(GenericChainSpec::from_json_bytes( &include_bytes!("../../chain-specs/bridge-hub-westend.json")[..], )?)), @@ -237,7 +273,109 @@ pub mod rococo { /// Sub-module for Kusama setup pub mod kusama { + use super::{BridgeHubBalance, ParaId}; + use crate::chain_spec::{ + get_account_id_from_seed, get_collator_keys_from_seed, Extensions, GenericChainSpec, + SAFE_XCM_VERSION, + }; + use parachains_common::{AccountId, AuraId}; + use sc_chain_spec::ChainType; + use sp_core::sr25519; + pub(crate) const BRIDGE_HUB_KUSAMA: &str = "bridge-hub-kusama"; + pub(crate) const BRIDGE_HUB_KUSAMA_LOCAL: &str = "bridge-hub-kusama-local"; + pub(crate) const BRIDGE_HUB_KUSAMA_DEVELOPMENT: &str = "bridge-hub-kusama-dev"; + const BRIDGE_HUB_KUSAMA_ED: BridgeHubBalance = + parachains_common::kusama::currency::EXISTENTIAL_DEPOSIT; + + pub fn local_config( + id: &str, + chain_name: &str, + relay_chain: &str, + para_id: ParaId, + ) -> GenericChainSpec { + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("ss58Format".into(), 2.into()); + properties.insert("tokenSymbol".into(), "KSM".into()); + properties.insert("tokenDecimals".into(), 12.into()); + + GenericChainSpec::builder( + bridge_hub_kusama_runtime::WASM_BINARY + .expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: relay_chain.to_string(), para_id: para_id.into() }, + ) + .with_name(chain_name) + .with_id(super::ensure_id(id).expect("invalid id")) + .with_chain_type(ChainType::Local) + .with_genesis_config_patch(genesis( + // initial collators. + vec![ + ( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed::("Alice"), + ), + ( + get_account_id_from_seed::("Bob"), + get_collator_keys_from_seed::("Bob"), + ), + ], + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Charlie"), + get_account_id_from_seed::("Dave"), + get_account_id_from_seed::("Eve"), + get_account_id_from_seed::("Ferdie"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + get_account_id_from_seed::("Charlie//stash"), + get_account_id_from_seed::("Dave//stash"), + get_account_id_from_seed::("Eve//stash"), + get_account_id_from_seed::("Ferdie//stash"), + ], + para_id, + )) + .with_properties(properties) + .build() + } + + fn genesis( + invulnerables: Vec<(AccountId, AuraId)>, + endowed_accounts: Vec, + id: ParaId, + ) -> serde_json::Value { + serde_json::json!({ + "balances": { + "balances": endowed_accounts + .iter() + .cloned() + .map(|k| (k, BRIDGE_HUB_KUSAMA_ED * 524_288)) + .collect::>(), + }, + "parachainInfo": { + "parachainId": id, + }, + "collatorSelection": { + "invulnerables": invulnerables.iter().cloned().map(|(acc, _)| acc).collect::>(), + "candidacyBond": BRIDGE_HUB_KUSAMA_ED * 16, + }, + "session": { + "keys": invulnerables + .into_iter() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + bridge_hub_kusama_runtime::SessionKeys { aura }, // session keys + ) + }) + .collect::>(), + }, + "polkadotXcm": { + "safeXcmVersion": Some(SAFE_XCM_VERSION), + } + }) + } } /// Sub-module for Westend setup. @@ -353,5 +491,107 @@ pub mod westend { /// Sub-module for Polkadot setup pub mod polkadot { + use super::{BridgeHubBalance, ParaId}; + use crate::chain_spec::{ + get_account_id_from_seed, get_collator_keys_from_seed, Extensions, GenericChainSpec, + SAFE_XCM_VERSION, + }; + use parachains_common::{AccountId, AuraId}; + use sc_chain_spec::ChainType; + use sp_core::sr25519; + pub(crate) const BRIDGE_HUB_POLKADOT: &str = "bridge-hub-polkadot"; + pub(crate) const BRIDGE_HUB_POLKADOT_LOCAL: &str = "bridge-hub-polkadot-local"; + pub(crate) const BRIDGE_HUB_POLKADOT_DEVELOPMENT: &str = "bridge-hub-polkadot-dev"; + const BRIDGE_HUB_POLKADOT_ED: BridgeHubBalance = + parachains_common::polkadot::currency::EXISTENTIAL_DEPOSIT; + + pub fn local_config( + id: &str, + chain_name: &str, + relay_chain: &str, + para_id: ParaId, + ) -> GenericChainSpec { + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("ss58Format".into(), 0.into()); + properties.insert("tokenSymbol".into(), "DOT".into()); + properties.insert("tokenDecimals".into(), 10.into()); + + GenericChainSpec::builder( + bridge_hub_polkadot_runtime::WASM_BINARY + .expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: relay_chain.to_string(), para_id: para_id.into() }, + ) + .with_name(chain_name) + .with_id(super::ensure_id(id).expect("invalid id")) + .with_chain_type(ChainType::Local) + .with_genesis_config_patch(genesis( + // initial collators. + vec![ + ( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed::("Alice"), + ), + ( + get_account_id_from_seed::("Bob"), + get_collator_keys_from_seed::("Bob"), + ), + ], + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Charlie"), + get_account_id_from_seed::("Dave"), + get_account_id_from_seed::("Eve"), + get_account_id_from_seed::("Ferdie"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + get_account_id_from_seed::("Charlie//stash"), + get_account_id_from_seed::("Dave//stash"), + get_account_id_from_seed::("Eve//stash"), + get_account_id_from_seed::("Ferdie//stash"), + ], + para_id, + )) + .with_properties(properties) + .build() + } + + fn genesis( + invulnerables: Vec<(AccountId, AuraId)>, + endowed_accounts: Vec, + id: ParaId, + ) -> serde_json::Value { + serde_json::json!({ + "balances": { + "balances": endowed_accounts + .iter() + .cloned() + .map(|k| (k, BRIDGE_HUB_POLKADOT_ED * 4096)) + .collect::>(), + }, + "parachainInfo": { + "parachainId": id, + }, + "collatorSelection": { + "invulnerables": invulnerables.iter().cloned().map(|(acc, _)| acc).collect::>(), + "candidacyBond": BRIDGE_HUB_POLKADOT_ED * 16, + }, + "session": { + "keys": invulnerables + .into_iter() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + bridge_hub_polkadot_runtime::SessionKeys { aura }, // session keys + ) + }) + .collect::>(), + }, + "polkadotXcm": { + "safeXcmVersion": Some(SAFE_XCM_VERSION), + } + }) + } } diff --git a/cumulus/polkadot-parachain/src/chain_spec/collectives.rs b/cumulus/polkadot-parachain/src/chain_spec/collectives.rs index dd67bf975f7..ac75a40ebde 100644 --- a/cumulus/polkadot-parachain/src/chain_spec/collectives.rs +++ b/cumulus/polkadot-parachain/src/chain_spec/collectives.rs @@ -23,9 +23,143 @@ use parachains_common::{AccountId, AuraId, Balance as CollectivesBalance}; use sc_service::ChainType; use sp_core::sr25519; +const COLLECTIVES_POLKADOT_ED: CollectivesBalance = + parachains_common::polkadot::currency::EXISTENTIAL_DEPOSIT; const COLLECTIVES_WESTEND_ED: CollectivesBalance = parachains_common::westend::currency::EXISTENTIAL_DEPOSIT; +/// Generate the session keys from individual elements. +/// +/// The input must be a tuple of individual keys (a single arg for now since we have just one key). +pub fn collectives_polkadot_session_keys( + keys: AuraId, +) -> collectives_polkadot_runtime::SessionKeys { + collectives_polkadot_runtime::SessionKeys { aura: keys } +} + +pub fn collectives_polkadot_development_config() -> GenericChainSpec { + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("ss58Format".into(), 0.into()); + properties.insert("tokenSymbol".into(), "DOT".into()); + properties.insert("tokenDecimals".into(), 10.into()); + + GenericChainSpec::builder( + collectives_polkadot_runtime::WASM_BINARY + .expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: "polkadot-dev".into(), para_id: 1002 }, + ) + .with_name("Polkadot Collectives Development") + .with_id("collectives_polkadot_dev") + .with_chain_type(ChainType::Local) + .with_genesis_config_patch(collectives_polkadot_genesis( + // initial collators. + vec![( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed::("Alice"), + )], + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + ], + // 1002 avoids a potential collision with Kusama-1001 (Encointer) should there ever + // be a collective para on Kusama. + 1002.into(), + )) + .with_boot_nodes(Vec::new()) + .with_properties(properties) + .build() +} + +/// Collectives Polkadot Local Config. +pub fn collectives_polkadot_local_config() -> GenericChainSpec { + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("ss58Format".into(), 0.into()); + properties.insert("tokenSymbol".into(), "DOT".into()); + properties.insert("tokenDecimals".into(), 10.into()); + + GenericChainSpec::builder( + collectives_polkadot_runtime::WASM_BINARY + .expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: "polkadot-local".into(), para_id: 1002 }, + ) + .with_name("Polkadot Collectives Local") + .with_id("collectives_polkadot_local") + .with_chain_type(ChainType::Local) + .with_genesis_config_patch(collectives_polkadot_genesis( + // initial collators. + vec![ + ( + get_account_id_from_seed::("Alice"), + get_collator_keys_from_seed::("Alice"), + ), + ( + get_account_id_from_seed::("Bob"), + get_collator_keys_from_seed::("Bob"), + ), + ], + vec![ + get_account_id_from_seed::("Alice"), + get_account_id_from_seed::("Bob"), + get_account_id_from_seed::("Charlie"), + get_account_id_from_seed::("Dave"), + get_account_id_from_seed::("Eve"), + get_account_id_from_seed::("Ferdie"), + get_account_id_from_seed::("Alice//stash"), + get_account_id_from_seed::("Bob//stash"), + get_account_id_from_seed::("Charlie//stash"), + get_account_id_from_seed::("Dave//stash"), + get_account_id_from_seed::("Eve//stash"), + get_account_id_from_seed::("Ferdie//stash"), + ], + 1002.into(), + )) + .with_boot_nodes(Vec::new()) + .with_properties(properties) + .build() +} + +fn collectives_polkadot_genesis( + invulnerables: Vec<(AccountId, AuraId)>, + endowed_accounts: Vec, + id: ParaId, +) -> serde_json::Value { + serde_json::json!( { + "balances": { + "balances": endowed_accounts + .iter() + .cloned() + .map(|k| (k, COLLECTIVES_POLKADOT_ED * 4096)) + .collect::>(), + }, + "parachainInfo": { + "parachainId": id, + }, + "collatorSelection": { + "invulnerables": invulnerables.iter().cloned().map(|(acc, _)| acc).collect::>(), + "candidacyBond": COLLECTIVES_POLKADOT_ED * 16, + }, + "session": { + "keys": invulnerables + .into_iter() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + collectives_polkadot_session_keys(aura), // session keys + ) + }) + .collect::>(), + }, + // no need to pass anything to aura, in fact it will panic if we do. Session will take care + // of this. + "polkadotXcm": { + "safeXcmVersion": Some(SAFE_XCM_VERSION), + }, + }) +} + /// Generate the session keys from individual elements. /// /// The input must be a tuple of individual keys (a single arg for now since we have just one key). diff --git a/cumulus/polkadot-parachain/src/chain_spec/glutton.rs b/cumulus/polkadot-parachain/src/chain_spec/glutton.rs index 77a4123b13e..8eced8d8f81 100644 --- a/cumulus/polkadot-parachain/src/chain_spec/glutton.rs +++ b/cumulus/polkadot-parachain/src/chain_spec/glutton.rs @@ -22,6 +22,62 @@ use sp_core::sr25519; use super::get_collator_keys_from_seed; +pub fn glutton_development_config(para_id: ParaId) -> GenericChainSpec { + GenericChainSpec::builder( + glutton_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: "kusama-dev".into(), para_id: para_id.into() }, + ) + .with_name("Glutton Development") + .with_id("glutton_dev") + .with_chain_type(ChainType::Local) + .with_genesis_config_patch(glutton_genesis( + para_id, + vec![get_collator_keys_from_seed::("Alice")], + )) + .build() +} + +pub fn glutton_local_config(para_id: ParaId) -> GenericChainSpec { + GenericChainSpec::builder( + glutton_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: "kusama-local".into(), para_id: para_id.into() }, + ) + .with_name("Glutton Local") + .with_id("glutton_local") + .with_chain_type(ChainType::Local) + .with_genesis_config_patch(glutton_genesis( + para_id, + vec![ + get_collator_keys_from_seed::("Alice"), + get_collator_keys_from_seed::("Bob"), + ], + )) + .build() +} + +pub fn glutton_config(para_id: ParaId) -> GenericChainSpec { + let mut properties = sc_chain_spec::Properties::new(); + properties.insert("ss58Format".into(), 2.into()); + + GenericChainSpec::builder( + glutton_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"), + Extensions { relay_chain: "kusama".into(), para_id: para_id.into() }, + ) + .with_name(format!("Glutton {}", para_id).as_str()) + .with_id(format!("glutton-kusama-{}", para_id).as_str()) + .with_chain_type(ChainType::Live) + .with_genesis_config_patch(glutton_genesis( + para_id, + vec![ + get_collator_keys_from_seed::("Alice"), + get_collator_keys_from_seed::("Bob"), + ], + )) + .with_protocol_id(format!("glutton-kusama-{}", para_id).as_str()) + .with_properties(properties) + .build() +} + fn glutton_genesis(parachain_id: ParaId, collators: Vec) -> serde_json::Value { serde_json::json!( { "parachainInfo": { diff --git a/cumulus/polkadot-parachain/src/cli.rs b/cumulus/polkadot-parachain/src/cli.rs index fec6e144e40..63e4baf27ae 100644 --- a/cumulus/polkadot-parachain/src/cli.rs +++ b/cumulus/polkadot-parachain/src/cli.rs @@ -45,8 +45,7 @@ pub enum Subcommand { PurgeChain(cumulus_client_cli::PurgeChainCmd), /// Export the genesis state of the parachain. - #[command(alias = "export-genesis-state")] - ExportGenesisHead(cumulus_client_cli::ExportGenesisHeadCommand), + ExportGenesisState(cumulus_client_cli::ExportGenesisStateCommand), /// Export the genesis wasm of the parachain. ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand), diff --git a/cumulus/polkadot-parachain/src/command.rs b/cumulus/polkadot-parachain/src/command.rs index d1b020cc7c9..f966a5db8f3 100644 --- a/cumulus/polkadot-parachain/src/command.rs +++ b/cumulus/polkadot-parachain/src/command.rs @@ -144,11 +144,27 @@ fn load_spec(id: &str) -> std::result::Result, String> { "seedling" => Box::new(chain_spec::seedling::get_seedling_chain_spec()), // -- Asset Hub Polkadot + "asset-hub-polkadot-dev" | "statemint-dev" => + Box::new(chain_spec::asset_hubs::asset_hub_polkadot_development_config()), + "asset-hub-polkadot-local" | "statemint-local" => + Box::new(chain_spec::asset_hubs::asset_hub_polkadot_local_config()), + // the chain spec as used for generating the upgrade genesis values + "asset-hub-polkadot-genesis" | "statemint-genesis" => + Box::new(chain_spec::asset_hubs::asset_hub_polkadot_config()), + // the shell-based chain spec as used for syncing "asset-hub-polkadot" | "statemint" => Box::new(GenericChainSpec::from_json_bytes( &include_bytes!("../chain-specs/asset-hub-polkadot.json")[..], )?), // -- Asset Hub Kusama + "asset-hub-kusama-dev" | "statemine-dev" => + Box::new(chain_spec::asset_hubs::asset_hub_kusama_development_config()), + "asset-hub-kusama-local" | "statemine-local" => + Box::new(chain_spec::asset_hubs::asset_hub_kusama_local_config()), + // the chain spec as used for generating the upgrade genesis values + "asset-hub-kusama-genesis" | "statemine-genesis" => + Box::new(chain_spec::asset_hubs::asset_hub_kusama_config()), + // the shell-based chain spec as used for syncing "asset-hub-kusama" | "statemine" => Box::new(GenericChainSpec::from_json_bytes( &include_bytes!("../chain-specs/asset-hub-kusama.json")[..], )?), @@ -179,11 +195,13 @@ fn load_spec(id: &str) -> std::result::Result, String> { )?), // -- Polkadot Collectives + "collectives-polkadot-dev" => + Box::new(chain_spec::collectives::collectives_polkadot_development_config()), + "collectives-polkadot-local" => + Box::new(chain_spec::collectives::collectives_polkadot_local_config()), "collectives-polkadot" => Box::new(GenericChainSpec::from_json_bytes( &include_bytes!("../chain-specs/collectives-polkadot.json")[..], )?), - - // -- Westend Collectives "collectives-westend-dev" => Box::new(chain_spec::collectives::collectives_westend_development_config()), "collectives-westend-local" => @@ -211,14 +229,14 @@ fn load_spec(id: &str) -> std::result::Result, String> { .expect("invalid value") .load_config()?, - // -- Penpal - "penpal-rococo" => Box::new(chain_spec::penpal::get_penpal_chain_spec( + // -- Penpall + "penpal-kusama" => Box::new(chain_spec::penpal::get_penpal_chain_spec( para_id.expect("Must specify parachain id"), - "rococo-local", + "kusama-local", )), - "penpal-westend" => Box::new(chain_spec::penpal::get_penpal_chain_spec( + "penpal-polkadot" => Box::new(chain_spec::penpal::get_penpal_chain_spec( para_id.expect("Must specify parachain id"), - "westend-local", + "polkadot-local", )), // -- Glutton Westend @@ -233,6 +251,18 @@ fn load_spec(id: &str) -> std::result::Result, String> { para_id.expect("Must specify parachain id"), )), + // -- Glutton + "glutton-kusama-dev" => Box::new(chain_spec::glutton::glutton_development_config( + para_id.expect("Must specify parachain id"), + )), + "glutton-kusama-local" => Box::new(chain_spec::glutton::glutton_local_config( + para_id.expect("Must specify parachain id"), + )), + // the chain spec as used for generating the upgrade genesis values + "glutton-kusama-genesis" => Box::new(chain_spec::glutton::glutton_config( + para_id.expect("Must specify parachain id"), + )), + // -- Fallback (generic chainspec) "" => { log::warn!("No ChainSpec.id specified, so using default one, based on rococo-parachain runtime"); @@ -530,10 +560,10 @@ pub fn run() -> Result<()> { cmd.run(config, polkadot_config) }) }, - Some(Subcommand::ExportGenesisHead(cmd)) => { + Some(Subcommand::ExportGenesisState(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| { - construct_partials!(config, |partials| cmd.run(partials.client)) + construct_partials!(config, |partials| cmd.run(&*config.chain_spec, &*partials.client)) }) }, Some(Subcommand::ExportGenesisWasm(cmd)) => { @@ -730,14 +760,18 @@ pub fn run() -> Result<()> { .map(|r| r.0) .map_err(Into::into), Runtime::BridgeHub(bridge_hub_runtime_type) => match bridge_hub_runtime_type { - chain_spec::bridge_hubs::BridgeHubRuntimeType::Polkadot => +chain_spec::bridge_hubs::BridgeHubRuntimeType::Polkadot | + chain_spec::bridge_hubs::BridgeHubRuntimeType::PolkadotLocal | + chain_spec::bridge_hubs::BridgeHubRuntimeType::PolkadotDevelopment => crate::service::start_generic_aura_node::< RuntimeApi, AuraId, >(config, polkadot_config, collator_options, id, hwbench) .await .map(|r| r.0), - chain_spec::bridge_hubs::BridgeHubRuntimeType::Kusama => + chain_spec::bridge_hubs::BridgeHubRuntimeType::Kusama | + chain_spec::bridge_hubs::BridgeHubRuntimeType::KusamaLocal | + chain_spec::bridge_hubs::BridgeHubRuntimeType::KusamaDevelopment => crate::service::start_generic_aura_node::< RuntimeApi, AuraId, @@ -1018,6 +1052,12 @@ mod tests { ); assert_eq!(Runtime::Default, path.runtime()); + let path = store_configuration( + &temp_dir, + Box::new(crate::chain_spec::asset_hubs::asset_hub_kusama_local_config()), + ); + assert_eq!(Runtime::AssetHubKusama, path.runtime()); + let path = store_configuration( &temp_dir, Box::new(crate::chain_spec::contracts::contracts_rococo_local_config()), diff --git a/cumulus/polkadot-parachain/src/service.rs b/cumulus/polkadot-parachain/src/service.rs index 6280d86e9f9..b0fca518201 100644 --- a/cumulus/polkadot-parachain/src/service.rs +++ b/cumulus/polkadot-parachain/src/service.rs @@ -96,6 +96,36 @@ impl sc_executor::NativeExecutionDispatch for ShellRuntimeExecutor { } } +/// Native Asset Hub Polkadot (Statemint) executor instance. +pub struct AssetHubPolkadotRuntimeExecutor; + +impl sc_executor::NativeExecutionDispatch for AssetHubPolkadotRuntimeExecutor { + type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; + + fn dispatch(method: &str, data: &[u8]) -> Option> { + asset_hub_polkadot_runtime::api::dispatch(method, data) + } + + fn native_version() -> sc_executor::NativeVersion { + asset_hub_polkadot_runtime::native_version() + } +} + +/// Native Asset Hub Kusama (Statemine) executor instance. +pub struct AssetHubKusamaExecutor; + +impl sc_executor::NativeExecutionDispatch for AssetHubKusamaExecutor { + type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; + + fn dispatch(method: &str, data: &[u8]) -> Option> { + asset_hub_kusama_runtime::api::dispatch(method, data) + } + + fn native_version() -> sc_executor::NativeVersion { + asset_hub_kusama_runtime::native_version() + } +} + /// Native Asset Hub Westend (Westmint) executor instance. pub struct AssetHubWestendExecutor; @@ -111,6 +141,21 @@ impl sc_executor::NativeExecutionDispatch for AssetHubWestendExecutor { } } +/// Native Polkadot Collectives executor instance. +pub struct CollectivesPolkadotRuntimeExecutor; + +impl sc_executor::NativeExecutionDispatch for CollectivesPolkadotRuntimeExecutor { + type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; + + fn dispatch(method: &str, data: &[u8]) -> Option> { + collectives_polkadot_runtime::api::dispatch(method, data) + } + + fn native_version() -> sc_executor::NativeVersion { + collectives_polkadot_runtime::native_version() + } +} + /// Native Westend Collectives executor instance. pub struct CollectivesWestendRuntimeExecutor; @@ -126,6 +171,36 @@ impl sc_executor::NativeExecutionDispatch for CollectivesWestendRuntimeExecutor } } +/// Native BridgeHubPolkadot executor instance. +pub struct BridgeHubPolkadotRuntimeExecutor; + +impl sc_executor::NativeExecutionDispatch for BridgeHubPolkadotRuntimeExecutor { + type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; + + fn dispatch(method: &str, data: &[u8]) -> Option> { + bridge_hub_polkadot_runtime::api::dispatch(method, data) + } + + fn native_version() -> sc_executor::NativeVersion { + bridge_hub_polkadot_runtime::native_version() + } +} + +/// Native BridgeHubKusama executor instance. +pub struct BridgeHubKusamaRuntimeExecutor; + +impl sc_executor::NativeExecutionDispatch for BridgeHubKusamaRuntimeExecutor { + type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; + + fn dispatch(method: &str, data: &[u8]) -> Option> { + bridge_hub_kusama_runtime::api::dispatch(method, data) + } + + fn native_version() -> sc_executor::NativeVersion { + bridge_hub_kusama_runtime::native_version() + } +} + /// Native BridgeHubRococo executor instance. pub struct BridgeHubRococoRuntimeExecutor; @@ -171,6 +246,21 @@ impl sc_executor::NativeExecutionDispatch for GluttonWestendRuntimeExecutor { } } +/// Native Glutton executor instance. +pub struct GluttonRuntimeExecutor; + +impl sc_executor::NativeExecutionDispatch for GluttonRuntimeExecutor { + type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; + + fn dispatch(method: &str, data: &[u8]) -> Option> { + shell_runtime::api::dispatch(method, data) + } + + fn native_version() -> sc_executor::NativeVersion { + shell_runtime::native_version() + } +} + /// Starts a `ServiceBuilder` for a full service. /// /// Use this macro if you don't actually need the full service, but just the builder in order to diff --git a/cumulus/polkadot-parachain/tests/benchmark_storage_works.rs b/cumulus/polkadot-parachain/tests/benchmark_storage_works.rs index c554b5b3d6b..c2850b64e45 100644 --- a/cumulus/polkadot-parachain/tests/benchmark_storage_works.rs +++ b/cumulus/polkadot-parachain/tests/benchmark_storage_works.rs @@ -24,7 +24,7 @@ use std::{ use tempfile::tempdir; /// The runtimes that this command supports. -static RUNTIMES: [&str; 1] = ["asset-hub-westend"]; +static RUNTIMES: [&str; 3] = ["asset-hub-westend", "asset-hub-kusama", "asset-hub-polkadot"]; /// The `benchmark storage` command works for the dev runtimes. #[test] diff --git a/cumulus/primitives/aura/Cargo.toml b/cumulus/primitives/aura/Cargo.toml index 6d917eea270..19607eb7c18 100644 --- a/cumulus/primitives/aura/Cargo.toml +++ b/cumulus/primitives/aura/Cargo.toml @@ -6,24 +6,21 @@ edition.workspace = true license = "Apache-2.0" description = "Core primitives for Aura in Cumulus" -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive" ] } # 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 = { 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} # Polkadot -polkadot-core-primitives = { path = "../../../polkadot/core-primitives", default-features = false } -polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false } +polkadot-core-primitives = { path = "../../../polkadot/core-primitives", default-features = false} +polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "polkadot-core-primitives/std", diff --git a/cumulus/primitives/core/Cargo.toml b/cumulus/primitives/core/Cargo.toml index 98c3e8ab567..23839a10e46 100644 --- a/cumulus/primitives/core/Cargo.toml +++ b/cumulus/primitives/core/Cargo.toml @@ -6,27 +6,24 @@ edition.workspace = true license = "Apache-2.0" description = "Cumulus related core primitive types and traits" -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive" ] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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 = { 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} # 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 = { 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} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "polkadot-core-primitives/std", diff --git a/cumulus/primitives/parachain-inherent/Cargo.toml b/cumulus/primitives/parachain-inherent/Cargo.toml index bfb101a43f4..46b5da57f38 100644 --- a/cumulus/primitives/parachain-inherent/Cargo.toml +++ b/cumulus/primitives/parachain-inherent/Cargo.toml @@ -6,25 +6,22 @@ edition.workspace = true description = "Inherent that needs to be present in every parachain block. Contains messages and a relay chain storage-proof." license = "Apache-2.0" -[lints] -workspace = true - [dependencies] async-trait = { version = "0.1.73", optional = true } -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive" ] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } tracing = { version = "0.1.37", optional = true } # Substrate -sc-client-api = { path = "../../../substrate/client/api", optional = true } -sp-api = { path = "../../../substrate/primitives/api", optional = true } -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 } -sp-state-machine = { path = "../../../substrate/primitives/state-machine", optional = true } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../substrate/primitives/storage", optional = true } -sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } +sc-client-api = { path = "../../../substrate/client/api", optional = true} +sp-api = { path = "../../../substrate/primitives/api", optional = true} +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} +sp-state-machine = { path = "../../../substrate/primitives/state-machine", optional = true} +sp-std = { path = "../../../substrate/primitives/std", default-features = false} +sp-storage = { path = "../../../substrate/primitives/storage", optional = true} +sp-trie = { path = "../../../substrate/primitives/trie", default-features = false} # Cumulus cumulus-primitives-core = { path = "../core", default-features = false } @@ -32,7 +29,7 @@ cumulus-relay-chain-interface = { path = "../../client/relay-chain-interface", o cumulus-test-relay-sproof-builder = { path = "../../test/relay-sproof-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "async-trait", "codec/std", diff --git a/cumulus/primitives/proof-size-hostfunction/Cargo.toml b/cumulus/primitives/proof-size-hostfunction/Cargo.toml deleted file mode 100644 index 06797f86863..00000000000 --- a/cumulus/primitives/proof-size-hostfunction/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -[package] -name = "cumulus-primitives-proof-size-hostfunction" -version = "0.1.0" -authors.workspace = true -edition.workspace = true -description = "Hostfunction exposing storage proof size to the runtime." -license = "Apache-2.0" - -[lints] -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 } - -[dev-dependencies] -sp-state-machine = { path = "../../../substrate/primitives/state-machine" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-io = { path = "../../../substrate/primitives/io" } - -[features] -default = ["std"] -std = ["sp-externalities/std", "sp-runtime-interface/std", "sp-trie/std"] diff --git a/cumulus/primitives/proof-size-hostfunction/src/lib.rs b/cumulus/primitives/proof-size-hostfunction/src/lib.rs deleted file mode 100644 index 6da6235e585..00000000000 --- a/cumulus/primitives/proof-size-hostfunction/src/lib.rs +++ /dev/null @@ -1,107 +0,0 @@ -// 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. - -// 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 Cumulus. If not, see . - -//! Tools for reclaiming PoV weight in parachain runtimes. - -#![cfg_attr(not(feature = "std"), no_std)] - -use sp_externalities::ExternalitiesExt; - -use sp_runtime_interface::runtime_interface; - -#[cfg(feature = "std")] -use sp_trie::proof_size_extension::ProofSizeExt; - -pub const PROOF_RECORDING_DISABLED: u64 = u64::MAX; - -/// Interface that provides access to the current storage proof size. -/// -/// Should return the current storage proof size if [`ProofSizeExt`] is registered. Otherwise, needs -/// to return u64::MAX. -#[runtime_interface] -pub trait StorageProofSize { - /// Returns the current storage proof size. - fn storage_proof_size(&mut self) -> u64 { - self.extension::().map_or(u64::MAX, |e| e.storage_proof_size()) - } -} - -#[cfg(test)] -mod tests { - use sp_core::Blake2Hasher; - use sp_state_machine::TestExternalities; - use sp_trie::{ - proof_size_extension::ProofSizeExt, recorder::Recorder, LayoutV1, PrefixedMemoryDB, - TrieDBMutBuilder, TrieMut, - }; - - use crate::{storage_proof_size, PROOF_RECORDING_DISABLED}; - - const TEST_DATA: &[(&[u8], &[u8])] = &[(b"key1", &[1; 64]), (b"key2", &[2; 64])]; - - type TestLayout = LayoutV1; - - fn get_prepared_test_externalities() -> (TestExternalities, Recorder) - { - let mut db = PrefixedMemoryDB::default(); - let mut root = Default::default(); - - { - let mut trie = TrieDBMutBuilder::::new(&mut db, &mut root).build(); - for (k, v) in TEST_DATA { - trie.insert(k, v).expect("Inserts data"); - } - } - - let recorder: sp_trie::recorder::Recorder = Default::default(); - let trie_backend = sp_state_machine::TrieBackendBuilder::new(db, root) - .with_recorder(recorder.clone()) - .build(); - - let mut ext: TestExternalities = TestExternalities::default(); - ext.backend = trie_backend; - (ext, recorder) - } - - #[test] - fn host_function_returns_size_from_recorder() { - let (mut ext, recorder) = get_prepared_test_externalities(); - ext.register_extension(ProofSizeExt::new(recorder)); - - ext.execute_with(|| { - assert_eq!(storage_proof_size::storage_proof_size(), 0); - sp_io::storage::get(b"key1"); - assert_eq!(storage_proof_size::storage_proof_size(), 175); - sp_io::storage::get(b"key2"); - assert_eq!(storage_proof_size::storage_proof_size(), 275); - sp_io::storage::get(b"key2"); - assert_eq!(storage_proof_size::storage_proof_size(), 275); - }); - } - - #[test] - fn host_function_returns_max_without_extension() { - let (mut ext, _) = get_prepared_test_externalities(); - - ext.execute_with(|| { - assert_eq!(storage_proof_size::storage_proof_size(), PROOF_RECORDING_DISABLED); - sp_io::storage::get(b"key1"); - assert_eq!(storage_proof_size::storage_proof_size(), PROOF_RECORDING_DISABLED); - sp_io::storage::get(b"key2"); - assert_eq!(storage_proof_size::storage_proof_size(), PROOF_RECORDING_DISABLED); - }); - } -} diff --git a/cumulus/primitives/timestamp/Cargo.toml b/cumulus/primitives/timestamp/Cargo.toml index b07a907154d..a0fea51f8db 100644 --- a/cumulus/primitives/timestamp/Cargo.toml +++ b/cumulus/primitives/timestamp/Cargo.toml @@ -6,23 +6,20 @@ edition.workspace = true description = "Provides timestamp related functionality for parachains." license = "Apache-2.0" -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive" ] } futures = "0.3.28" # 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 = { 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} # Cumulus cumulus-primitives-core = { path = "../core", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-primitives-core/std", diff --git a/cumulus/primitives/utility/Cargo.toml b/cumulus/primitives/utility/Cargo.toml index 56b6b928417..45ce6701988 100644 --- a/cumulus/primitives/utility/Cargo.toml +++ b/cumulus/primitives/utility/Cargo.toml @@ -6,32 +6,29 @@ edition.workspace = true license = "Apache-2.0" description = "Helper datatypes for Cumulus" -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive" ] } log = { version = "0.4.20", default-features = false } # 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 } +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} # 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 } +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} pallet-xcm-benchmarks = { path = "../../../polkadot/xcm/pallet-xcm-benchmarks", default-features = false } # Cumulus cumulus-primitives-core = { path = "../core", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-primitives-core/std", diff --git a/cumulus/scripts/benchmarks.sh b/cumulus/scripts/benchmarks.sh index 58b8419bf4a..7da18d9440e 100755 --- a/cumulus/scripts/benchmarks.sh +++ b/cumulus/scripts/benchmarks.sh @@ -6,7 +6,16 @@ repeat=${3:-20} __dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +${__dir}/benchmarks-ci.sh collectives collectives-polkadot target/$target $steps $repeat ${__dir}/benchmarks-ci.sh collectives collectives-westend target/$target $steps $repeat + +${__dir}/benchmarks-ci.sh assets asset-hub-kusama target/$target $steps $repeat +${__dir}/benchmarks-ci.sh assets asset-hub-polkadot target/$target $steps $repeat ${__dir}/benchmarks-ci.sh assets asset-hub-westend target/$target $steps $repeat + +${__dir}/benchmarks-ci.sh bridge-hubs bridge-hub-polkadot target/$target $steps $repeat +${__dir}/benchmarks-ci.sh bridge-hubs bridge-hub-kusama target/$target $steps $repeat ${__dir}/benchmarks-ci.sh bridge-hubs bridge-hub-rococo target/$target $steps $repeat + +${__dir}/benchmarks-ci.sh glutton glutton-kusama target/$target $steps $repeat ${__dir}/benchmarks-ci.sh glutton glutton-westend target/$target $steps $repeat diff --git a/cumulus/scripts/bridges_common.sh b/cumulus/scripts/bridges_common.sh index 97ef8aa1259..8d64c5ede52 100755 --- a/cumulus/scripts/bridges_common.sh +++ b/cumulus/scripts/bridges_common.sh @@ -187,25 +187,23 @@ function open_hrmp_channels() { ${max_message_size} } -function force_xcm_version() { +function set_storage() { local relay_url=$1 local relay_chain_seed=$2 local runtime_para_id=$3 local runtime_para_endpoint=$4 - local dest=$5 - local xcm_version=$6 - echo " calling force_xcm_version:" + local items=$5 + echo " calling set_storage:" echo " relay_url: ${relay_url}" echo " relay_chain_seed: ${relay_chain_seed}" echo " runtime_para_id: ${runtime_para_id}" echo " runtime_para_endpoint: ${runtime_para_endpoint}" - echo " dest: ${dest}" - echo " xcm_version: ${xcm_version}" + echo " items: ${items}" echo " params:" - # 1. generate data for Transact (PolkadotXcm::force_xcm_version) + # 1. generate data for Transact (System::set_storage) local tmp_output_file=$(mktemp) - generate_hex_encoded_call_data "force-xcm-version" "${runtime_para_endpoint}" "${tmp_output_file}" "$dest" "$xcm_version" + generate_hex_encoded_call_data "set-storage" "${runtime_para_endpoint}" "${tmp_output_file}" "$items" local hex_encoded_data=$(cat $tmp_output_file) # 2. trigger governance call diff --git a/cumulus/scripts/bridges_rococo_westend.sh b/cumulus/scripts/bridges_rococo_westend.sh index 8bce141d39a..9b3bd350276 100755 --- a/cumulus/scripts/bridges_rococo_westend.sh +++ b/cumulus/scripts/bridges_rococo_westend.sh @@ -129,7 +129,6 @@ ON_BRIDGE_HUB_WESTEND_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhro_ThisChain="5EHnXa ON_BRIDGE_HUB_WESTEND_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhro_BridgedChain="5EHnXaT5BhiSGP5h9RgQci1txJ2BDbp7KBRE9k8xty3BMUSi" LANE_ID="00000002" -XCM_VERSION=3 function init_ro_wnd() { ensure_relayer @@ -216,14 +215,6 @@ case "$1" in "ws://127.0.0.1:9942" \ "//Alice" \ 1013 1000 4 524288 - # set XCM version of remote AssetHubWestend - force_xcm_version \ - "ws://127.0.0.1:9942" \ - "//Alice" \ - 1000 \ - "ws://127.0.0.1:9910" \ - "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Westend" }, { "Parachain": 1000 } ] } }')" \ - $XCM_VERSION ;; init-bridge-hub-rococo-local) ensure_polkadot_js_api @@ -245,14 +236,6 @@ case "$1" in "//Alice" \ "$ON_BRIDGE_HUB_ROCOCO_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhwd_BridgedChain" \ $((1000000000000 + 2000000000000)) - # set XCM version of remote BridgeHubWestend - force_xcm_version \ - "ws://127.0.0.1:9942" \ - "//Alice" \ - 1013 \ - "ws://127.0.0.1:8943" \ - "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Westend" }, { "Parachain": 1002 } ] } }')" \ - $XCM_VERSION ;; init-asset-hub-westend-local) ensure_polkadot_js_api @@ -281,14 +264,6 @@ case "$1" in "ws://127.0.0.1:9945" \ "//Alice" \ 1002 1000 4 524288 - # set XCM version of remote AssetHubRococo - force_xcm_version \ - "ws://127.0.0.1:9945" \ - "//Alice" \ - 1000 \ - "ws://127.0.0.1:9010" \ - "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Rococo" }, { "Parachain": 1000 } ] } }')" \ - $XCM_VERSION ;; init-bridge-hub-westend-local) # SA of sibling asset hub pays for the execution @@ -309,14 +284,6 @@ case "$1" in "//Alice" \ "$ON_BRIDGE_HUB_WESTEND_SOVEREIGN_ACCOUNT_FOR_LANE_00000002_bhro_BridgedChain" \ $((1000000000000000 + 2000000000000)) - # set XCM version of remote BridgeHubRococo - force_xcm_version \ - "ws://127.0.0.1:9945" \ - "//Alice" \ - 1002 \ - "ws://127.0.0.1:8945" \ - "$(jq --null-input '{ "parents": 2, "interior": { "X2": [ { "GlobalConsensus": "Rococo" }, { "Parachain": 1013 } ] } }')" \ - $XCM_VERSION ;; reserve-transfer-assets-from-asset-hub-rococo-local) ensure_polkadot_js_api diff --git a/cumulus/scripts/create_bridge_hub_kusama_spec.sh b/cumulus/scripts/create_bridge_hub_kusama_spec.sh new file mode 100755 index 00000000000..813921b079a --- /dev/null +++ b/cumulus/scripts/create_bridge_hub_kusama_spec.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash + +usage() { + echo Usage: + echo "$1 " + echo "$2 " + echo "e.g.: ./scripts/create_bridge_hub_kusama_spec.sh ./target/release/wbuild/bridge-hub-kusama-runtime/bridge_hub_kusama_runtime.compact.compressed.wasm 1002" + exit 1 +} + +if [ -z "$1" ]; then + usage +fi + +if [ -z "$2" ]; then + usage +fi + +set -e + +rt_path=$1 +para_id=$2 + +echo "Generating chain spec for runtime: $rt_path and para_id: $para_id" + +binary="./target/release/polkadot-parachain" + +# build the chain spec we'll manipulate +$binary build-spec --chain bridge-hub-kusama-dev > chain-spec-plain.json + +# convert runtime to hex +cat $rt_path | od -A n -v -t x1 | tr -d ' \n' > rt-hex.txt + +# replace the runtime in the spec with the given runtime and set some values to production +cat chain-spec-plain.json | jq --rawfile code rt-hex.txt '.genesis.runtime.system.code = ("0x" + $code)' \ + | jq '.name = "Kusama BridgeHub"' \ + | jq '.id = "bridge-hub-kusama"' \ + | jq '.chainType = "Live"' \ + | jq '.bootNodes = [ + "/dns/kusama-bridge-hub-collator-ew1-0.polkadot.io/tcp/30334/p2p/12D3KooWP2Gngt4tt2sz5BgDaAbMTxasPWk3V2Z99bQTmFcAorqa", + "/dns/kusama-bridge-hub-collator-ew1-1.polkadot.io/tcp/30334/p2p/12D3KooWMmL3FQuYmruBui1sbY4MwNmvicinrePi1Yq4QMRSYHoR", + "/dns/kusama-bridge-hub-collator-ue4-0.polkadot.io/tcp/30334/p2p/12D3KooWQpTocTck1tNBzMNTHJ3kSv4vzv8Yf9FpVkfGnungbez4", + "/dns/kusama-bridge-hub-collator-ue4-1.polkadot.io/tcp/30334/p2p/12D3KooWRgtJqKEaMi7hkU4VMiGhpHTJeL8N7JgL7d9gwooPv4eW", + + "/dns/kusama-bridge-hub-connect-ew1-0.polkadot.io/tcp/30334/p2p/12D3KooWPQQPivrqQ51kRTDc2R1mtqwKT4GGtk2rapkY4FrwHrEp", + "/dns/kusama-bridge-hub-connect-ew1-1.polkadot.io/tcp/30334/p2p/12D3KooWPcF9Yk4gYrMju9CyWCV69hAFXbYsnxCLogwLGu9QFTRn", + "/dns/kusama-bridge-hub-connect-ue4-0.polkadot.io/tcp/30334/p2p/12D3KooWMf1sVnJDTkKWtaThqvrgcSPLbfGXttSqbwhM2DJp9BUG", + "/dns/kusama-bridge-hub-connect-ue4-1.polkadot.io/tcp/30334/p2p/12D3KooWQaV7wMfNVKy2aMz4Lds3TTxgSDyZAUEnbAZMfD8rW3ow", + + "/dns/kusama-bridge-hub-connect-ew1-0.polkadot.io/tcp/443/wss/p2p/12D3KooWPQQPivrqQ51kRTDc2R1mtqwKT4GGtk2rapkY4FrwHrEp", + "/dns/kusama-bridge-hub-connect-ew1-1.polkadot.io/tcp/443/wss/p2p/12D3KooWPcF9Yk4gYrMju9CyWCV69hAFXbYsnxCLogwLGu9QFTRn", + "/dns/kusama-bridge-hub-connect-ue4-0.polkadot.io/tcp/443/wss/p2p/12D3KooWMf1sVnJDTkKWtaThqvrgcSPLbfGXttSqbwhM2DJp9BUG", + "/dns/kusama-bridge-hub-connect-ue4-1.polkadot.io/tcp/443/wss/p2p/12D3KooWQaV7wMfNVKy2aMz4Lds3TTxgSDyZAUEnbAZMfD8rW3ow" + + ]' \ + | jq '.relay_chain = "kusama"' \ + | jq --argjson para_id $para_id '.para_id = $para_id' \ + | jq --argjson para_id $para_id '.genesis.runtime.parachainInfo.parachainId = $para_id' \ + | jq '.genesis.runtime.balances.balances = []' \ + | jq '.genesis.runtime.collatorSelection.invulnerables = [ + "DQkekNBt8g6D7bPUEqhgfujADxzzfivr1qQZJkeGzAqnEzF", + "HbUc5qrLtKAZvasioiTSf1CunaN2SyEwvfsgMuYQjXA5sfk", + "JEe4NcVyuWFEwZe4WLfRtynDswyKgvLS8H8r4Wo9d3t61g1", + "FAe4DGhQHKTm35n5MgBFNBZvyEJcm7QAwgnVNQU8KXP2ixn" + ]' \ + | jq '.genesis.runtime.session.keys = [ + [ + "DQkekNBt8g6D7bPUEqhgfujADxzzfivr1qQZJkeGzAqnEzF", + "DQkekNBt8g6D7bPUEqhgfujADxzzfivr1qQZJkeGzAqnEzF", + { + "aura": "5E7AiV9ygGUcfdK3XVoJsew7fsu18uvKQHYhksE5PXDNfRL9" + } + ], + [ + "HbUc5qrLtKAZvasioiTSf1CunaN2SyEwvfsgMuYQjXA5sfk", + "HbUc5qrLtKAZvasioiTSf1CunaN2SyEwvfsgMuYQjXA5sfk", + { + "aura": "5CyXoMh8cA2MSk55JASpCfhCg44iSG5fBwmhvSfXUUS3uhPR" + } + ], + [ + "JEe4NcVyuWFEwZe4WLfRtynDswyKgvLS8H8r4Wo9d3t61g1", + "JEe4NcVyuWFEwZe4WLfRtynDswyKgvLS8H8r4Wo9d3t61g1", + { + "aura": "5Grj5pN52kKU61qK9qP5cf9ADuyowe2WVvYWxMNK1QqAM8qf" + } + ], + [ + "FAe4DGhQHKTm35n5MgBFNBZvyEJcm7QAwgnVNQU8KXP2ixn", + "FAe4DGhQHKTm35n5MgBFNBZvyEJcm7QAwgnVNQU8KXP2ixn", + { + "aura": "5EHTyftGjcHfe71VVuZqCeLbHNf4ptYzgdAMMyqpTNbs5Rrp" + } + ] + ]' \ + > edited-chain-spec-plain.json + +# build a raw spec +$binary build-spec --chain edited-chain-spec-plain.json --raw > chain-spec-raw.json +cp edited-chain-spec-plain.json bridge-hub-kusama-spec.json +cp chain-spec-raw.json ./parachains/chain-specs/bridge-hub-kusama.json +cp chain-spec-raw.json bridge-hub-kusama-spec-raw.json + +# build genesis data +$binary export-genesis-state --chain chain-spec-raw.json > bridge-hub-kusama-genesis-head-data + +# build genesis wasm +$binary export-genesis-wasm --chain chain-spec-raw.json > bridge-hub-kusama-wasm diff --git a/cumulus/scripts/create_bridge_hub_polkadot_spec.sh b/cumulus/scripts/create_bridge_hub_polkadot_spec.sh new file mode 100755 index 00000000000..49bc9cee692 --- /dev/null +++ b/cumulus/scripts/create_bridge_hub_polkadot_spec.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash + +usage() { + echo Usage: + echo "$1 " + echo "$2 " + echo "e.g.: ./scripts/create_bridge_hub_polkadot_spec.sh ./target/release/wbuild/bridge-hub-polkadot-runtime/bridge_hub_polkadot_runtime.compact.compressed.wasm 1002" + exit 1 +} + +if [ -z "$1" ]; then + usage +fi + +if [ -z "$2" ]; then + usage +fi + +set -e + +rt_path=$1 +para_id=$2 + +echo "Generating chain spec for runtime: $rt_path and para_id: $para_id" + +binary="./target/release/polkadot-parachain" + +# build the chain spec we'll manipulate +$binary build-spec --chain bridge-hub-polkadot-dev > chain-spec-plain.json + +# convert runtime to hex +cat $rt_path | od -A n -v -t x1 | tr -d ' \n' > rt-hex.txt + +# replace the runtime in the spec with the given runtime and set some values to production +cat chain-spec-plain.json | jq --rawfile code rt-hex.txt '.genesis.runtime.system.code = ("0x" + $code)' \ + | jq '.name = "Polkadot BridgeHub"' \ + | jq '.id = "bridge-hub-polkadot"' \ + | jq '.chainType = "Live"' \ + | jq '.bootNodes = [ + "/dns/polkadot-bridge-hub-connect-a-0.polkadot.io/tcp/30334/p2p/12D3KooWAVQMhkXmc5ueSYasdsRWQbKus2YGZ6HDZUB4ViJMCxXy", + "/dns/polkadot-bridge-hub-connect-a-1.polkadot.io/tcp/30334/p2p/12D3KooWG4ypDHLKGCv4BZ6PuaGUwQHKAH6p2D6arR2uQ1eiR1T3", + "/dns/polkadot-bridge-hub-connect-b-0.polkadot.io/tcp/30334/p2p/12D3KooWCwGKxjpJXnx1mwXKvaxGQm769EM3b6Pg5vbU33wbhsNw", + "/dns/polkadot-bridge-hub-connect-b-1.polkadot.io/tcp/30334/p2p/12D3KooWLiSEdhriJUPdZKFtAjZrQncxN2ssEoDKVrt5mGM4Qu4J", + + "/dns/polkadot-bridge-hub-connect-a-0.polkadot.io/tcp/443/wss/p2p/12D3KooWAVQMhkXmc5ueSYasdsRWQbKus2YGZ6HDZUB4ViJMCxXy", + "/dns/polkadot-bridge-hub-connect-a-1.polkadot.io/tcp/443/wss/p2p/12D3KooWG4ypDHLKGCv4BZ6PuaGUwQHKAH6p2D6arR2uQ1eiR1T3", + "/dns/polkadot-bridge-hub-connect-b-0.polkadot.io/tcp/443/wss/p2p/12D3KooWCwGKxjpJXnx1mwXKvaxGQm769EM3b6Pg5vbU33wbhsNw", + "/dns/polkadot-bridge-hub-connect-b-1.polkadot.io/tcp/443/wss/p2p/12D3KooWLiSEdhriJUPdZKFtAjZrQncxN2ssEoDKVrt5mGM4Qu4J" + ]' \ + | jq '.relay_chain = "polkadot"' \ + | jq --argjson para_id $para_id '.para_id = $para_id' \ + | jq --argjson para_id $para_id '.genesis.runtime.parachainInfo.parachainId = $para_id' \ + | jq '.genesis.runtime.balances.balances = []' \ + | jq '.genesis.runtime.collatorSelection.invulnerables = [ + "134AK3RiMA97Fx9dLj1CvuLJUa8Yo93EeLA1TkP6CCGnWMSd", + "15dU8Tt7kde2diuHzijGbKGPU5K8BPzrFJfYFozvrS1DdE21", + "1vXMKM8SctM28AQw1wSpd7p9yCUWn1uhbbKSVTuznsw8Q2x", + "15mCQcaj3QP1UdxBF82JRd9v3riZJcVNVEmx8xkFp7DSYR4Y" + ]' \ + | jq '.genesis.runtime.session.keys = [ + [ + "134AK3RiMA97Fx9dLj1CvuLJUa8Yo93EeLA1TkP6CCGnWMSd", + "134AK3RiMA97Fx9dLj1CvuLJUa8Yo93EeLA1TkP6CCGnWMSd", + { + "aura": "5EX6AnyuSPEFQ7HAPjRgzqk1sxgh8cyacGimwJ16y1nJ2w7g" + } + ], + [ + "15dU8Tt7kde2diuHzijGbKGPU5K8BPzrFJfYFozvrS1DdE21", + "15dU8Tt7kde2diuHzijGbKGPU5K8BPzrFJfYFozvrS1DdE21", + { + "aura": "5DZN8UhaJftvKhMMARmJBwrwzuEDpoUzzBvvWMbFXYsJ4CmK" + } + ], + [ + "1vXMKM8SctM28AQw1wSpd7p9yCUWn1uhbbKSVTuznsw8Q2x", + "1vXMKM8SctM28AQw1wSpd7p9yCUWn1uhbbKSVTuznsw8Q2x", + { + "aura": "5FKsn83rXQQiw7HwoeYoLMoYS5GP9YVNHZiCHwA4DSwDcPVa" + } + ], + [ + "15mCQcaj3QP1UdxBF82JRd9v3riZJcVNVEmx8xkFp7DSYR4Y", + "15mCQcaj3QP1UdxBF82JRd9v3riZJcVNVEmx8xkFp7DSYR4Y", + { + "aura": "5DCg19ckcJz4m52Th4o1LcSRK3H7NsUcQsRbu7pTDM3mZ26v" + } + ] + ]' \ + > edited-chain-spec-plain.json + +# build a raw spec +$binary build-spec --chain edited-chain-spec-plain.json --raw > chain-spec-raw.json +cp edited-chain-spec-plain.json bridge-hub-polkadot-spec.json +cp chain-spec-raw.json ./parachains/chain-specs/bridge-hub-polkadot.json +cp chain-spec-raw.json bridge-hub-polkadot-spec-raw.json + +# build genesis data +$binary export-genesis-state --chain chain-spec-raw.json > bridge-hub-polkadot-genesis-head-data + +# build genesis wasm +$binary export-genesis-wasm --chain chain-spec-raw.json > bridge-hub-polkadot-wasm + +# cleanup +rm -f rt-hex.txt +rm -f chain-spec-plain.json +rm -f chain-spec-raw.json +rm -f edited-chain-spec-plain.json diff --git a/cumulus/scripts/create_glutton_spec.sh b/cumulus/scripts/create_glutton_spec.sh index 78aafda3bd0..c5158392f52 100755 --- a/cumulus/scripts/create_glutton_spec.sh +++ b/cumulus/scripts/create_glutton_spec.sh @@ -55,7 +55,7 @@ for (( para_id=$from_para_id; para_id<=$to_para_id; para_id++ )); do fi # build the chain spec we'll manipulate - $binary_path build-spec --disable-default-bootnode --chain "glutton-westend-genesis-$para_id" > "$output_para_dir/plain-glutton-$relay_chain-$para_id-spec.json" + $binary_path build-spec --disable-default-bootnode --chain "glutton-kusama-genesis-$para_id" > "$output_para_dir/plain-glutton-$relay_chain-$para_id-spec.json" id="glutton-$relay_chain-$para_id" protocol_id="glutton-$relay_chain-$para_id" diff --git a/cumulus/scripts/generate_hex_encoded_call/index.js b/cumulus/scripts/generate_hex_encoded_call/index.js index 30f89d754ce..09f0e6aaf61 100644 --- a/cumulus/scripts/generate_hex_encoded_call/index.js +++ b/cumulus/scripts/generate_hex_encoded_call/index.js @@ -106,11 +106,11 @@ function forceCreateAsset(endpoint, outputFile, assetId, assetOwnerAccountId, is }); } -function forceXcmVersion(endpoint, outputFile, dest, xcm_version) { - console.log(`Generating forceXcmVersion from RPC endpoint: ${endpoint} to outputFile: ${outputFile}, dest: ${dest}, xcm_version: ${xcm_version}`); +function setStorage(endpoint, outputFile, items) { + console.log(`Generating setStorage from RPC endpoint: ${endpoint} to outputFile: ${outputFile}, items: ${items}`); connect(endpoint) .then((api) => { - const call = api.tx.polkadotXcm.forceXcmVersion(JSON.parse(dest), xcm_version); + const call = api.tx.system.setStorage(JSON.parse(items)); writeHexEncodedBytesToOutput(call.method, outputFile); exit(0); }) @@ -154,8 +154,8 @@ switch (type) { case 'force-create-asset': forceCreateAsset(rpcEnpoint, output, inputArgs[0], inputArgs[1], inputArgs[2], inputArgs[3]); break; - case 'force-xcm-version': - forceXcmVersion(rpcEnpoint, output, inputArgs[0], inputArgs[1]); + case 'set-storage': + setStorage(rpcEnpoint, output, inputArgs[0]); break; case 'check': console.log(`Checking nodejs installation, if you see this everything is ready!`); diff --git a/cumulus/scripts/parachains_integration_tests.sh b/cumulus/scripts/parachains_integration_tests.sh new file mode 100755 index 00000000000..2a06b930e22 --- /dev/null +++ b/cumulus/scripts/parachains_integration_tests.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash + +tests=( + asset-hub-kusama + asset-hub-polkadot +) + +rm -R logs &> /dev/null + +for t in ${tests[@]} +do + printf "\n🔍 Running $t tests...\n\n" + + mkdir -p logs/$t + + parachains-integration-tests \ + -m zombienet \ + -c ./parachains/integration-tests/$t/config.toml \ + -cl ./logs/$t/chains.log 2> /dev/null & + + parachains-integration-tests \ + -m test \ + -t ./parachains/integration-tests/$t \ + -tl ./logs/$t/tests.log & tests=$! + + wait $tests + + pkill -f polkadot + pkill -f parachain + + printf "\n🎉 $t integration tests finished! \n\n" +done diff --git a/cumulus/test/client/Cargo.toml b/cumulus/test/client/Cargo.toml index 7190172101c..b760b796ec9 100644 --- a/cumulus/test/client/Cargo.toml +++ b/cumulus/test/client/Cargo.toml @@ -5,11 +5,8 @@ authors.workspace = true edition.workspace = true publish = false -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive" ] } # Substrate sc-service = { path = "../../../substrate/client/service" } @@ -39,7 +36,6 @@ 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" } [features] diff --git a/cumulus/test/client/src/lib.rs b/cumulus/test/client/src/lib.rs index 62fc080bb15..87ddbf59015 100644 --- a/cumulus/test/client/src/lib.rs +++ b/cumulus/test/client/src/lib.rs @@ -44,8 +44,7 @@ mod local_executor { pub struct LocalExecutor; impl sc_executor::NativeExecutionDispatch for LocalExecutor { - type ExtendHostFunctions = - cumulus_primitives_proof_size_hostfunction::storage_proof_size::HostFunctions; + type ExtendHostFunctions = (); fn dispatch(method: &str, data: &[u8]) -> Option> { cumulus_test_runtime::api::dispatch(method, data) diff --git a/cumulus/test/relay-sproof-builder/Cargo.toml b/cumulus/test/relay-sproof-builder/Cargo.toml index 02a9750d78e..b24ac308495 100644 --- a/cumulus/test/relay-sproof-builder/Cargo.toml +++ b/cumulus/test/relay-sproof-builder/Cargo.toml @@ -6,26 +6,23 @@ edition.workspace = true license = "Apache-2.0" description = "Mocked relay state proof builder for testing Cumulus." -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive" ] } # 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 = { 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} # Polkadot -polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false } +polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false} # Cumulus cumulus-primitives-core = { path = "../../primitives/core", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-primitives-core/std", diff --git a/cumulus/test/runtime/Cargo.toml b/cumulus/test/runtime/Cargo.toml index 5902a62512b..3ea51c1973f 100644 --- a/cumulus/test/runtime/Cargo.toml +++ b/cumulus/test/runtime/Cargo.toml @@ -5,46 +5,43 @@ authors.workspace = true edition.workspace = true publish = false -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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 } +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-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 } -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-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-sudo = { path = "../../../substrate/frame/sudo", 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} +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-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} # Cumulus -cumulus-pallet-parachain-system = { path = "../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook"] } +cumulus-pallet-parachain-system = { path = "../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } cumulus-primitives-core = { path = "../../primitives/core", default-features = false } [build-dependencies] substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "cumulus-pallet-parachain-system/std", diff --git a/cumulus/test/runtime/src/lib.rs b/cumulus/test/runtime/src/lib.rs index 1c01d8360b7..13910e87e6c 100644 --- a/cumulus/test/runtime/src/lib.rs +++ b/cumulus/test/runtime/src/lib.rs @@ -29,7 +29,7 @@ pub mod wasm_spec_version_incremented { mod test_pallet; -use frame_support::{derive_impl, traits::OnRuntimeUpgrade}; +use frame_support::traits::OnRuntimeUpgrade; use sp_api::{decl_runtime_apis, impl_runtime_apis}; use sp_core::{ConstU32, OpaqueMetadata}; use sp_runtime::{ @@ -177,23 +177,36 @@ parameter_types! { pub const SS58Prefix: u8 = 42; } -#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { /// The identifier used to distinguish between accounts. type AccountId = AccountId; + /// The aggregated dispatch type that is available for extrinsics. + type RuntimeCall = RuntimeCall; /// The lookup mechanism to get account ID from whatever is passed in dispatchers. type Lookup = IdentityLookup; /// The index type for storing how many extrinsics an account has signed. type Nonce = Nonce; /// The type for hashing blocks and tries. type Hash = Hash; + /// The hashing algorithm used. + type Hashing = BlakeTwo256; /// The block type. type Block = Block; + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + /// The ubiquitous origin type. + type RuntimeOrigin = RuntimeOrigin; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). type BlockHashCount = BlockHashCount; /// Runtime version. type Version = Version; + type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type DbWeight = (); + type BaseCallFilter = frame_support::traits::Everything; + type SystemWeightInfo = (); type BlockWeights = RuntimeBlockWeights; type BlockLength = RuntimeBlockLength; type SS58Prefix = SS58Prefix; diff --git a/cumulus/test/service/Cargo.toml b/cumulus/test/service/Cargo.toml index c4e7f7401b0..ed8c8748cc8 100644 --- a/cumulus/test/service/Cargo.toml +++ b/cumulus/test/service/Cargo.toml @@ -5,21 +5,18 @@ authors.workspace = true edition.workspace = true publish = false -[lints] -workspace = true - [[bin]] name = "test-parachain" path = "src/main.rs" [dependencies] async-trait = "0.1.73" -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.0.0" } -criterion = { version = "0.5.1", features = ["async_tokio"] } +criterion = { version = "0.5.1", features = [ "async_tokio" ] } jsonrpsee = { version = "0.16.2", features = ["server"] } rand = "0.8.5" -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.108" tokio = { version = "1.32.0", features = ["macros"] } tracing = "0.1.37" @@ -47,7 +44,7 @@ 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-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" } @@ -80,7 +77,7 @@ 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, features = ["parameterized-consensus-hook"] } +cumulus-pallet-parachain-system = { path = "../../pallets/parachain-system", default-features = false, features = ["parameterized-consensus-hook",] } pallet-timestamp = { path = "../../../substrate/frame/timestamp" } [dev-dependencies] diff --git a/cumulus/test/service/benches/block_import.rs b/cumulus/test/service/benches/block_import.rs index 9d6485d74c5..254e03b9263 100644 --- a/cumulus/test/service/benches/block_import.rs +++ b/cumulus/test/service/benches/block_import.rs @@ -24,7 +24,7 @@ use core::time::Duration; use cumulus_primitives_core::ParaId; use sp_api::{Core, ProvideRuntimeApi}; -use sp_keyring::Sr25519Keyring::{Alice, Bob}; +use sp_keyring::Sr25519Keyring::Alice; use cumulus_test_service::bench_utils as utils; @@ -32,69 +32,51 @@ fn benchmark_block_import(c: &mut Criterion) { sp_tracing::try_init_simple(); let runtime = tokio::runtime::Runtime::new().expect("creating tokio runtime doesn't fail; qed"); - - let para_id = ParaId::from(cumulus_test_runtime::PARACHAIN_ID); + let para_id = ParaId::from(100); let tokio_handle = runtime.handle(); // Create enough accounts to fill the block with transactions. // Each account should only be included in one transfer. let (src_accounts, dst_accounts, account_ids) = utils::create_benchmark_accounts(); - for bench_parameters in &[(true, Alice), (false, Bob)] { - let node = runtime.block_on( - cumulus_test_service::TestNodeBuilder::new( - para_id, - tokio_handle.clone(), - bench_parameters.1, - ) + let alice = runtime.block_on( + cumulus_test_service::TestNodeBuilder::new(para_id, tokio_handle.clone(), Alice) // Preload all accounts with funds for the transfers - .endowed_accounts(account_ids.clone()) - .import_proof_recording(bench_parameters.0) + .endowed_accounts(account_ids) .build(), - ); - - let client = node.client; - let backend = node.backend; - - let (max_transfer_count, extrinsics) = - utils::create_benchmarking_transfer_extrinsics(&client, &src_accounts, &dst_accounts); - - let parent_hash = client.usage_info().chain.best_hash; - let mut block_builder = BlockBuilderBuilder::new(&*client) - .on_parent_block(parent_hash) - .fetch_parent_block_number(&*client) - .unwrap() - .build() - .unwrap(); - for extrinsic in extrinsics { - block_builder.push(extrinsic).unwrap(); - } - let benchmark_block = block_builder.build().unwrap(); - - let mut group = c.benchmark_group("Block import"); - group.sample_size(20); - group.measurement_time(Duration::from_secs(120)); - group.throughput(Throughput::Elements(max_transfer_count as u64)); - - group.bench_function( - format!( - "(transfers = {max_transfer_count}, proof_recording = {}) block import", - bench_parameters.0 - ), - |b| { - b.iter_batched( - || { - backend.reset_trie_cache(); - benchmark_block.block.clone() - }, - |block| { - client.runtime_api().execute_block(parent_hash, block).unwrap(); - }, - BatchSize::SmallInput, - ) - }, - ); + ); + + let client = alice.client; + + let (max_transfer_count, extrinsics) = + utils::create_benchmarking_transfer_extrinsics(&client, &src_accounts, &dst_accounts); + + let parent_hash = client.usage_info().chain.best_hash; + let mut block_builder = BlockBuilderBuilder::new(&*client) + .on_parent_block(parent_hash) + .fetch_parent_block_number(&*client) + .unwrap() + .build() + .unwrap(); + for extrinsic in extrinsics { + block_builder.push(extrinsic).unwrap(); } + let benchmark_block = block_builder.build().unwrap(); + + let mut group = c.benchmark_group("Block import"); + group.sample_size(20); + group.measurement_time(Duration::from_secs(120)); + group.throughput(Throughput::Elements(max_transfer_count as u64)); + + group.bench_function(format!("(transfers = {}) block import", max_transfer_count), |b| { + b.iter_batched( + || benchmark_block.block.clone(), + |block| { + client.runtime_api().execute_block(parent_hash, block).unwrap(); + }, + BatchSize::SmallInput, + ) + }); } criterion_group!(benches, benchmark_block_import); diff --git a/cumulus/test/service/benches/block_import_glutton.rs b/cumulus/test/service/benches/block_import_glutton.rs index 6295fd68286..aeaf0722e72 100644 --- a/cumulus/test/service/benches/block_import_glutton.rs +++ b/cumulus/test/service/benches/block_import_glutton.rs @@ -27,7 +27,7 @@ use core::time::Duration; use cumulus_primitives_core::ParaId; use sc_block_builder::BlockBuilderBuilder; -use sp_keyring::Sr25519Keyring::{Alice, Bob, Charlie, Ferdie}; +use sp_keyring::Sr25519Keyring::Alice; use cumulus_test_service::bench_utils as utils; @@ -38,29 +38,17 @@ fn benchmark_block_import(c: &mut Criterion) { let para_id = ParaId::from(100); let tokio_handle = runtime.handle(); - let mut initialize_glutton_pallet = true; - for (compute_ratio, storage_ratio, proof_on_import, keyring_identity) in &[ - (One::one(), Zero::zero(), true, Alice), - (One::one(), One::one(), true, Bob), - (One::one(), Zero::zero(), false, Charlie), - (One::one(), One::one(), false, Ferdie), - ] { - let node = runtime.block_on( - cumulus_test_service::TestNodeBuilder::new( - para_id, - tokio_handle.clone(), - *keyring_identity, - ) - .import_proof_recording(*proof_on_import) - .build(), - ); - let client = node.client; - let backend = node.backend; + let alice = runtime.block_on( + cumulus_test_service::TestNodeBuilder::new(para_id, tokio_handle.clone(), Alice).build(), + ); + let client = alice.client; - let mut group = c.benchmark_group("Block import"); - group.sample_size(20); - group.measurement_time(Duration::from_secs(120)); + let mut group = c.benchmark_group("Block import"); + group.sample_size(20); + group.measurement_time(Duration::from_secs(120)); + let mut initialize_glutton_pallet = true; + for (compute_ratio, storage_ratio) in &[(One::one(), Zero::zero()), (One::one(), One::one())] { let block = utils::set_glutton_parameters( &client, initialize_glutton_pallet, @@ -94,10 +82,7 @@ fn benchmark_block_import(c: &mut Criterion) { ), |b| { b.iter_batched( - || { - backend.reset_trie_cache(); - benchmark_block.block.clone() - }, + || benchmark_block.block.clone(), |block| { client.runtime_api().execute_block(parent_hash, block).unwrap(); }, diff --git a/cumulus/test/service/benches/validate_block.rs b/cumulus/test/service/benches/validate_block.rs index a614863803e..11a7c4376d4 100644 --- a/cumulus/test/service/benches/validate_block.rs +++ b/cumulus/test/service/benches/validate_block.rs @@ -18,9 +18,7 @@ use codec::{Decode, Encode}; use core::time::Duration; use criterion::{criterion_group, criterion_main, BatchSize, Criterion, Throughput}; -use cumulus_primitives_core::{ - relay_chain::AccountId, ParaId, PersistedValidationData, ValidationParams, -}; +use cumulus_primitives_core::{relay_chain::AccountId, PersistedValidationData, ValidationParams}; use cumulus_test_client::{ generate_extrinsic_with_pair, BuildParachainBlockData, InitBlockBuilder, TestClientBuilder, ValidationResult, @@ -85,7 +83,6 @@ fn benchmark_block_validation(c: &mut Criterion) { // Each account should only be included in one transfer. let (src_accounts, dst_accounts, account_ids) = utils::create_benchmark_accounts(); - let para_id = ParaId::from(cumulus_test_runtime::PARACHAIN_ID); let mut test_client_builder = TestClientBuilder::with_default_backend(); let genesis_init = test_client_builder.genesis_init_mut(); *genesis_init = cumulus_test_client::GenesisParameters { endowed_accounts: account_ids }; @@ -101,14 +98,7 @@ fn benchmark_block_validation(c: &mut Criterion) { ..Default::default() }; - let sproof_builder = RelayStateSproofBuilder { - included_para_head: Some(parent_header.clone().encode().into()), - para_id, - ..Default::default() - }; - - let mut block_builder = - client.init_block_builder(Some(validation_data), sproof_builder.clone()); + let mut block_builder = client.init_block_builder(Some(validation_data), Default::default()); for extrinsic in extrinsics { block_builder.push(extrinsic).unwrap(); } @@ -118,6 +108,7 @@ fn benchmark_block_validation(c: &mut Criterion) { let proof_size_in_kb = parachain_block.storage_proof().encode().len() as f64 / 1024f64; let runtime = utils::get_wasm_module(); + let sproof_builder: RelayStateSproofBuilder = Default::default(); let (relay_parent_storage_root, _) = sproof_builder.into_state_root_and_proof(); let encoded_params = ValidationParams { block_data: cumulus_test_client::BlockData(parachain_block.encode()), diff --git a/cumulus/test/service/src/bench_utils.rs b/cumulus/test/service/src/bench_utils.rs index 3331000b5f3..3c35b4dd228 100644 --- a/cumulus/test/service/src/bench_utils.rs +++ b/cumulus/test/service/src/bench_utils.rs @@ -81,13 +81,8 @@ pub fn extrinsic_set_time(client: &TestClient) -> OpaqueExtrinsic { pub fn extrinsic_set_validation_data( parent_header: cumulus_test_runtime::Header, ) -> OpaqueExtrinsic { + let sproof_builder = RelayStateSproofBuilder { para_id: 100.into(), ..Default::default() }; let parent_head = HeadData(parent_header.encode()); - let sproof_builder = RelayStateSproofBuilder { - para_id: cumulus_test_runtime::PARACHAIN_ID.into(), - included_para_head: parent_head.clone().into(), - ..Default::default() - }; - let (relay_parent_storage_root, relay_chain_state) = sproof_builder.into_state_root_and_proof(); let data = ParachainInherentData { validation_data: PersistedValidationData { diff --git a/cumulus/test/service/src/cli.rs b/cumulus/test/service/src/cli.rs index 3dc5b8e3101..ef1159a3c1f 100644 --- a/cumulus/test/service/src/cli.rs +++ b/cumulus/test/service/src/cli.rs @@ -16,7 +16,6 @@ use std::{net::SocketAddr, path::PathBuf}; -use cumulus_client_cli::{ExportGenesisHeadCommand, ExportGenesisWasmCommand}; use polkadot_service::{ChainSpec, ParaId, PrometheusConfig}; use sc_cli::{ CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams, NetworkParams, @@ -61,13 +60,45 @@ pub enum Subcommand { BuildSpec(sc_cli::BuildSpecCmd), /// Export the genesis state of the parachain. - #[command(alias = "export-genesis-state")] - ExportGenesisHead(ExportGenesisHeadCommand), + ExportGenesisState(ExportGenesisStateCommand), /// Export the genesis wasm of the parachain. ExportGenesisWasm(ExportGenesisWasmCommand), } +#[derive(Debug, clap::Parser)] +#[group(skip)] +pub struct ExportGenesisStateCommand { + #[arg(default_value_t = 2000u32)] + pub parachain_id: u32, + + #[command(flatten)] + pub base: cumulus_client_cli::ExportGenesisStateCommand, +} + +impl CliConfiguration for ExportGenesisStateCommand { + fn shared_params(&self) -> &SharedParams { + &self.base.shared_params + } +} + +/// Command for exporting the genesis wasm file. +#[derive(Debug, clap::Parser)] +#[group(skip)] +pub struct ExportGenesisWasmCommand { + #[arg(default_value_t = 2000u32)] + pub parachain_id: u32, + + #[command(flatten)] + pub base: cumulus_client_cli::ExportGenesisWasmCommand, +} + +impl CliConfiguration for ExportGenesisWasmCommand { + fn shared_params(&self) -> &SharedParams { + &self.base.shared_params + } +} + #[derive(Debug)] pub struct RelayChainCli { /// The actual relay chain cli object. diff --git a/cumulus/test/service/src/genesis.rs b/cumulus/test/service/src/genesis.rs index be4b0427b2e..d4a9a225626 100644 --- a/cumulus/test/service/src/genesis.rs +++ b/cumulus/test/service/src/genesis.rs @@ -15,50 +15,11 @@ // along with Cumulus. If not, see . use codec::Encode; +use cumulus_client_cli::generate_genesis_block; use cumulus_primitives_core::ParaId; use cumulus_test_runtime::Block; use polkadot_primitives::HeadData; -use sc_chain_spec::ChainSpec; -use sp_runtime::{ - traits::{Block as BlockT, Hash as HashT, Header as HeaderT, Zero}, - StateVersion, -}; - -/// Generate a simple test genesis block from a given ChainSpec. -pub fn generate_genesis_block( - chain_spec: &dyn ChainSpec, - genesis_state_version: StateVersion, -) -> Result { - let storage = chain_spec.build_storage()?; - - let child_roots = storage.children_default.iter().map(|(sk, child_content)| { - let state_root = <<::Header as HeaderT>::Hashing as HashT>::trie_root( - child_content.data.clone().into_iter().collect(), - genesis_state_version, - ); - (sk.clone(), state_root.encode()) - }); - let state_root = <<::Header as HeaderT>::Hashing as HashT>::trie_root( - storage.top.clone().into_iter().chain(child_roots).collect(), - genesis_state_version, - ); - - let extrinsics_root = <<::Header as HeaderT>::Hashing as HashT>::trie_root( - Vec::new(), - genesis_state_version, - ); - - Ok(Block::new( - <::Header as HeaderT>::new( - Zero::zero(), - extrinsics_root, - state_root, - Default::default(), - Default::default(), - ), - Default::default(), - )) -} +use sp_runtime::traits::Block as BlockT; /// Returns the initial head data for a parachain ID. pub fn initial_head_data(para_id: ParaId) -> HeadData { diff --git a/cumulus/test/service/src/lib.rs b/cumulus/test/service/src/lib.rs index 176a8d39867..a15331a8184 100644 --- a/cumulus/test/service/src/lib.rs +++ b/cumulus/test/service/src/lib.rs @@ -22,14 +22,11 @@ pub mod bench_utils; pub mod chain_spec; - -/// Utilities for creating test genesis block and head data -pub mod genesis; +mod genesis; use runtime::AccountId; use sc_executor::{HeapAllocStrategy, WasmExecutor, DEFAULT_HEAP_ALLOC_STRATEGY}; use std::{ - collections::HashSet, future::Future, net::{IpAddr, Ipv4Addr, SocketAddr}, time::Duration, @@ -60,7 +57,7 @@ use cumulus_test_runtime::{Hash, Header, NodeBlock as Block, RuntimeApi}; use frame_system_rpc_runtime_api::AccountNonceApi; use polkadot_node_subsystem::{errors::RecoveryError, messages::AvailabilityRecoveryMessage}; use polkadot_overseer::Handle as OverseerHandle; -use polkadot_primitives::{CandidateHash, CollatorPair, Hash as PHash, PersistedValidationData}; +use polkadot_primitives::{CollatorPair, Hash as PHash, PersistedValidationData}; use polkadot_service::ProvideRuntimeApi; use sc_consensus::ImportQueue; use sc_network::{ @@ -147,13 +144,12 @@ pub type TransactionPool = Arc>; pub struct FailingRecoveryHandle { overseer_handle: OverseerHandle, counter: u32, - failed_hashes: HashSet, } impl FailingRecoveryHandle { /// Create a new FailingRecoveryHandle pub fn new(overseer_handle: OverseerHandle) -> Self { - Self { overseer_handle, counter: 0, failed_hashes: Default::default() } + Self { overseer_handle, counter: 0 } } } @@ -164,15 +160,11 @@ impl RecoveryHandle for FailingRecoveryHandle { message: AvailabilityRecoveryMessage, origin: &'static str, ) { - let AvailabilityRecoveryMessage::RecoverAvailableData(ref receipt, _, _, _) = message; - let candidate_hash = receipt.hash(); - - // For every 3rd block we immediately signal unavailability to trigger - // a retry. The same candidate is never failed multiple times to ensure progress. - if self.counter % 3 == 0 && self.failed_hashes.insert(candidate_hash) { - tracing::info!(target: LOG_TARGET, ?candidate_hash, "Failing pov recovery."); - + // For every 5th block we immediately signal unavailability to trigger + // a retry. + if self.counter % 5 == 0 { let AvailabilityRecoveryMessage::RecoverAvailableData(_, _, _, back_sender) = message; + tracing::info!(target: LOG_TARGET, "Failing pov recovery."); back_sender .send(Err(RecoveryError::Unavailable)) .expect("Return channel should work here."); @@ -189,7 +181,6 @@ impl RecoveryHandle for FailingRecoveryHandle { /// be able to perform chain operations. pub fn new_partial( config: &mut Configuration, - enable_import_proof_record: bool, ) -> Result< PartialComponents< Client, @@ -217,12 +208,7 @@ pub fn new_partial( sc_executor::NativeElseWasmExecutor::::new_with_wasm_executor(wasm); let (client, backend, keystore_container, task_manager) = - sc_service::new_full_parts_record_import::( - config, - None, - executor, - enable_import_proof_record, - )?; + sc_service::new_full_parts::(config, None, executor)?; let client = Arc::new(client); let block_import = @@ -317,21 +303,19 @@ pub async fn start_node_impl( rpc_ext_builder: RB, consensus: Consensus, collator_options: CollatorOptions, - proof_recording_during_import: bool, ) -> sc_service::error::Result<( TaskManager, Arc, Arc>, RpcHandlers, TransactionPool, - Arc, )> where RB: Fn(Arc) -> Result, sc_service::Error> + Send + 'static, { let mut parachain_config = prepare_node_config(parachain_config); - let params = new_partial(&mut parachain_config, proof_recording_during_import)?; + let params = new_partial(&mut parachain_config)?; let transaction_pool = params.transaction_pool.clone(); let mut task_manager = params.task_manager; @@ -487,7 +471,7 @@ where start_network.start_network(); - Ok((task_manager, client, network, rpc_handlers, transaction_pool, backend)) + Ok((task_manager, client, network, rpc_handlers, transaction_pool)) } /// A Cumulus test node instance used for testing. @@ -505,8 +489,6 @@ pub struct TestNode { pub rpc_handlers: RpcHandlers, /// Node's transaction pool pub transaction_pool: TransactionPool, - /// Node's backend - pub backend: Arc, } #[allow(missing_docs)] @@ -532,7 +514,6 @@ pub struct TestNodeBuilder { consensus: Consensus, relay_chain_mode: RelayChainMode, endowed_accounts: Vec, - record_proof_during_import: bool, } impl TestNodeBuilder { @@ -557,7 +538,6 @@ impl TestNodeBuilder { consensus: Consensus::RelayChain, endowed_accounts: Default::default(), relay_chain_mode: RelayChainMode::Embedded, - record_proof_during_import: true, } } @@ -670,12 +650,6 @@ impl TestNodeBuilder { self } - /// Record proofs during import. - pub fn import_proof_recording(mut self, should_record_proof: bool) -> TestNodeBuilder { - self.record_proof_during_import = should_record_proof; - self - } - /// Build the [`TestNode`]. pub async fn build(self) -> TestNode { let parachain_config = node_config( @@ -704,26 +678,24 @@ impl TestNodeBuilder { format!("{} (relay chain)", relay_chain_config.network.node_name); let multiaddr = parachain_config.network.listen_addresses[0].clone(); - let (task_manager, client, network, rpc_handlers, transaction_pool, backend) = - start_node_impl( - parachain_config, - self.collator_key, - relay_chain_config, - self.para_id, - self.wrap_announce_block, - false, - |_| Ok(jsonrpsee::RpcModule::new(())), - self.consensus, - collator_options, - self.record_proof_during_import, - ) - .await - .expect("could not create Cumulus test service"); + let (task_manager, client, network, rpc_handlers, transaction_pool) = start_node_impl( + parachain_config, + self.collator_key, + relay_chain_config, + self.para_id, + self.wrap_announce_block, + false, + |_| Ok(jsonrpsee::RpcModule::new(())), + self.consensus, + collator_options, + ) + .await + .expect("could not create Cumulus test service"); let peer_id = network.local_peer_id(); let addr = MultiaddrWithPeerId { multiaddr, peer_id }; - TestNode { task_manager, client, network, addr, rpc_handlers, transaction_pool, backend } + TestNode { task_manager, client, network, addr, rpc_handlers, transaction_pool } } } diff --git a/cumulus/test/service/src/main.rs b/cumulus/test/service/src/main.rs index aace92ca965..16b68796bd3 100644 --- a/cumulus/test/service/src/main.rs +++ b/cumulus/test/service/src/main.rs @@ -16,14 +16,16 @@ mod cli; -use std::sync::Arc; +use std::{io::Write, sync::Arc}; use cli::{RelayChainCli, Subcommand, TestCollatorCli}; +use cumulus_client_cli::generate_genesis_block; use cumulus_primitives_core::{relay_chain::CollatorPair, ParaId}; -use cumulus_test_service::{new_partial, AnnounceBlockFn}; +use cumulus_test_service::AnnounceBlockFn; use polkadot_service::runtime_traits::AccountIdConversion; use sc_cli::{CliConfiguration, SubstrateCli}; -use sp_core::Pair; +use sp_core::{hexdisplay::HexDisplay, Encode, Pair}; +use sp_runtime::traits::Block; pub fn wrap_announce_block() -> Box AnnounceBlockFn> { tracing::info!("Block announcements disabled."); @@ -42,16 +44,38 @@ fn main() -> Result<(), sc_cli::Error> { runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) }, - Some(Subcommand::ExportGenesisHead(cmd)) => { - let runner = cli.create_runner(cmd)?; - runner.sync_run(|mut config| { - let partial = new_partial(&mut config, false)?; - cmd.run(partial.client) - }) + Some(Subcommand::ExportGenesisState(params)) => { + let mut builder = sc_cli::LoggerBuilder::new(""); + builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); + let _ = builder.init(); + + let spec = + cli.load_spec(¶ms.base.shared_params.chain.clone().unwrap_or_default())?; + let state_version = cumulus_test_service::runtime::VERSION.state_version(); + + let block: parachains_common::Block = generate_genesis_block(&*spec, state_version)?; + let raw_header = block.header().encode(); + let output_buf = if params.base.raw { + raw_header + } else { + format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes() + }; + + if let Some(output) = ¶ms.base.output { + std::fs::write(output, output_buf)?; + } else { + std::io::stdout().write_all(&output_buf)?; + } + + Ok(()) }, Some(Subcommand::ExportGenesisWasm(cmd)) => { let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run(&*config.chain_spec)) + runner.sync_run(|_config| { + let parachain_id = ParaId::from(cmd.parachain_id); + let spec = cumulus_test_service::get_chain_spec(Some(parachain_id)); + cmd.base.run(&spec) + }) }, None => { let log_filters = cli.run.normalize().log_filters(); @@ -104,7 +128,7 @@ fn main() -> Result<(), sc_cli::Error> { }) .unwrap_or(cumulus_test_service::Consensus::RelayChain); - let (mut task_manager, _, _, _, _, _) = tokio_runtime + let (mut task_manager, _, _, _, _) = tokio_runtime .block_on(cumulus_test_service::start_node_impl( config, collator_key, @@ -115,7 +139,6 @@ fn main() -> Result<(), sc_cli::Error> { |_| Ok(jsonrpsee::RpcModule::new(())), consensus, collator_options, - true, )) .expect("could not create Cumulus test service"); diff --git a/cumulus/xcm/xcm-emulator/Cargo.toml b/cumulus/xcm/xcm-emulator/Cargo.toml index 0f10221d600..2f851f1bcde 100644 --- a/cumulus/xcm/xcm-emulator/Cargo.toml +++ b/cumulus/xcm/xcm-emulator/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license = "Apache-2.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0" } paste = "1.0.14" diff --git a/cumulus/zombienet/examples/bridge_hub_kusama_local_network.toml b/cumulus/zombienet/examples/bridge_hub_kusama_local_network.toml new file mode 100644 index 00000000000..ae8ae07a75c --- /dev/null +++ b/cumulus/zombienet/examples/bridge_hub_kusama_local_network.toml @@ -0,0 +1,67 @@ +[relaychain] +default_command = "../polkadot/target/release/polkadot" +default_args = [ "-lparachain=debug" ] +chain = "kusama-local" + + [[relaychain.nodes]] + name = "alice" + validator = true + + [[relaychain.nodes]] + name = "bob" + validator = true + + [[relaychain.nodes]] + name = "charlie" + validator = true + + [[relaychain.nodes]] + name = "dave" + validator = true + +[[parachains]] +id = 1003 +chain = "bridge-hub-kusama-local" +cumulus_based = true + + # run alice as parachain collator + [[parachains.collators]] + name = "alice" + validator = true + command = "./target/release/polkadot-parachain" + args = ["-lparachain=debug"] + + # run bob as parachain collator + [[parachains.collators]] + name = "bob" + validator = true + command = "./target/release/polkadot-parachain" + args = ["-lparachain=debug"] + + # run charlie as parachain collator + [[parachains.collators]] + name = "charlie" + validator = true + command = "./target/release/polkadot-parachain" + args = ["-lparachain=debug"] + + # run dave as parachain collator + [[parachains.collators]] + name = "dave" + validator = true + command = "./target/release/polkadot-parachain" + args = ["-lparachain=debug"] + + # run eve as parachain collator + [[parachains.collators]] + name = "eve" + validator = true + command = "./target/release/polkadot-parachain" + args = ["-lparachain=debug"] + + # run ferdie as parachain collator + [[parachains.collators]] + name = "ferdie" + validator = true + command = "./target/release/polkadot-parachain" + args = ["-lparachain=debug"] diff --git a/cumulus/zombienet/examples/bridge_hub_polkadot_local_network.toml b/cumulus/zombienet/examples/bridge_hub_polkadot_local_network.toml new file mode 100644 index 00000000000..564fece7cae --- /dev/null +++ b/cumulus/zombienet/examples/bridge_hub_polkadot_local_network.toml @@ -0,0 +1,67 @@ +[relaychain] +default_command = "../polkadot/target/release/polkadot" +default_args = [ "-lparachain=debug" ] +chain = "polkadot-local" + + [[relaychain.nodes]] + name = "alice" + validator = true + + [[relaychain.nodes]] + name = "bob" + validator = true + + [[relaychain.nodes]] + name = "charlie" + validator = true + + [[relaychain.nodes]] + name = "dave" + validator = true + +[[parachains]] +id = 1003 +chain = "bridge-hub-polkadot-local" +cumulus_based = true + + # run alice as parachain collator + [[parachains.collators]] + name = "alice" + validator = true + command = "./target/release/polkadot-parachain" + args = ["-lparachain=debug"] + + # run bob as parachain collator + [[parachains.collators]] + name = "bob" + validator = true + command = "./target/release/polkadot-parachain" + args = ["-lparachain=debug"] + + # run charlie as parachain collator + [[parachains.collators]] + name = "charlie" + validator = true + command = "./target/release/polkadot-parachain" + args = ["-lparachain=debug"] + + # run dave as parachain collator + [[parachains.collators]] + name = "dave" + validator = true + command = "./target/release/polkadot-parachain" + args = ["-lparachain=debug"] + + # run eve as parachain collator + [[parachains.collators]] + name = "eve" + validator = true + command = "./target/release/polkadot-parachain" + args = ["-lparachain=debug"] + + # run ferdie as parachain collator + [[parachains.collators]] + name = "ferdie" + validator = true + command = "./target/release/polkadot-parachain" + args = ["-lparachain=debug"] diff --git a/cumulus/zombienet/examples/small_network.toml b/cumulus/zombienet/examples/small_network.toml index ab726571230..06ac0d0e5e7 100644 --- a/cumulus/zombienet/examples/small_network.toml +++ b/cumulus/zombienet/examples/small_network.toml @@ -14,7 +14,7 @@ chain = "rococo-local" [[parachains]] id = 2000 cumulus_based = true -chain = "asset-hub-rococo-local" +chain = "asset-hub-kusama-local" # run charlie as parachain collator [[parachains.collators]] diff --git a/cumulus/zombienet/examples/asset_hub_westend_local_network.toml b/cumulus/zombienet/examples/statemine_kusama_local_network.toml similarity index 71% rename from cumulus/zombienet/examples/asset_hub_westend_local_network.toml rename to cumulus/zombienet/examples/statemine_kusama_local_network.toml index 5b0ac1f17e8..1f3debfb9d2 100644 --- a/cumulus/zombienet/examples/asset_hub_westend_local_network.toml +++ b/cumulus/zombienet/examples/statemine_kusama_local_network.toml @@ -1,7 +1,7 @@ [relaychain] -default_command = "../../target/release/polkadot" +default_command = "../polkadot/target/release/polkadot" default_args = [ "-lparachain=debug" ] -chain = "westend-local" +chain = "kusama-local" [[relaychain.nodes]] name = "alice" @@ -21,47 +21,47 @@ chain = "westend-local" [[parachains]] id = 1000 -chain = "asset-hub-westend-local" +chain = "asset-hub-kusama-local" cumulus_based = true # run alice as parachain collator [[parachains.collators]] name = "alice" validator = true - command = "../../target/release/polkadot-parachain" + command = "./target/release/polkadot-parachain" args = ["-lparachain=debug"] # run bob as parachain collator [[parachains.collators]] name = "bob" validator = true - command = "../../target/release/polkadot-parachain" + command = "./target/release/polkadot-parachain" args = ["-lparachain=debug"] # run charlie as parachain collator [[parachains.collators]] name = "charlie" validator = true - command = "../../target/release/polkadot-parachain" + command = "./target/release/polkadot-parachain" args = ["-lparachain=debug"] # run dave as parachain collator [[parachains.collators]] name = "dave" validator = true - command = "../../target/release/polkadot-parachain" + command = "./target/release/polkadot-parachain" args = ["-lparachain=debug"] # run eve as parachain collator [[parachains.collators]] name = "eve" validator = true - command = "../../target/release/polkadot-parachain" + command = "./target/release/polkadot-parachain" args = ["-lparachain=debug"] # run ferdie as parachain collator [[parachains.collators]] name = "ferdie" validator = true - command = "../../target/release/polkadot-parachain" + command = "./target/release/polkadot-parachain" args = ["-lparachain=debug"] diff --git a/cumulus/zombienet/tests/0002-pov_recovery.toml b/cumulus/zombienet/tests/0002-pov_recovery.toml index fe42fd4b2f6..105e4a324f3 100644 --- a/cumulus/zombienet/tests/0002-pov_recovery.toml +++ b/cumulus/zombienet/tests/0002-pov_recovery.toml @@ -34,12 +34,13 @@ add_to_genesis = false args = ["--disable-block-announcements"] # run 'alice' as a parachain collator who does not produce blocks + # 'alice' is a bootnode for 'bob' and 'charlie' [[parachains.collators]] name = "alice" validator = true # collator image = "{{COL_IMAGE}}" command = "test-parachain" - args = ["-lparachain::availability=trace,sync=debug,parachain=debug,cumulus-pov-recovery=debug,cumulus-consensus=debug", "--use-null-consensus", "--disable-block-announcements", "--bootnodes {{'bob'|zombie('multiAddress')}}", "--in-peers 0", "--out-peers 0", "--", "--reserved-only", "--reserved-nodes {{'ferdie'|zombie('multiAddress')}}"] + args = ["-lparachain::availability=trace,sync=debug,parachain=debug,cumulus-pov-recovery=debug,cumulus-consensus=debug", "--use-null-consensus", "--disable-block-announcements", "--bootnodes {{'bob'|zombie('multiAddress')}}", "--", "--reserved-only", "--reserved-nodes {{'ferdie'|zombie('multiAddress')}}"] # run 'charlie' as a parachain full node [[parachains.collators]] @@ -47,7 +48,7 @@ add_to_genesis = false validator = false # full node image = "{{COL_IMAGE}}" command = "test-parachain" - args = ["-lparachain::availability=trace,sync=debug,parachain=debug,cumulus-pov-recovery=debug,cumulus-consensus=debug", "--disable-block-announcements", "--bootnodes {{'bob'|zombie('multiAddress')}}", "--in-peers 0", "--out-peers 0", "--", "--reserved-only", "--reserved-nodes {{'ferdie'|zombie('multiAddress')}}"] + args = ["-lparachain::availability=trace,sync=debug,parachain=debug,cumulus-pov-recovery=debug,cumulus-consensus=debug", "--disable-block-announcements", "--bootnodes {{'bob'|zombie('multiAddress')}}", "--in-peers 0", "--out-peers 0","--", "--reserved-only", "--reserved-nodes {{'ferdie'|zombie('multiAddress')}}"] # we fail recovery for 'eve' from time to time to test retries [[parachains.collators]] diff --git a/cumulus/zombienet/tests/0002-pov_recovery.zndsl b/cumulus/zombienet/tests/0002-pov_recovery.zndsl index b05285c87bf..7a93e2f3742 100644 --- a/cumulus/zombienet/tests/0002-pov_recovery.zndsl +++ b/cumulus/zombienet/tests/0002-pov_recovery.zndsl @@ -13,8 +13,7 @@ alice: reports block height is at least 20 within 600 seconds charlie: reports block height is at least 20 within 600 seconds one: reports block height is at least 20 within 800 seconds two: reports block height is at least 20 within 800 seconds -# Re-enable once we upgraded from smoldot 0.11.0 and https://github.com/paritytech/polkadot-sdk/pull/1631 is merged -# three: reports block height is at least 20 within 800 seconds +three: reports block height is at least 20 within 800 seconds eve: reports block height is at least 20 within 800 seconds one: count of log lines containing "Importing block retrieved using pov_recovery" is greater than 19 within 10 seconds diff --git a/docs/contributor/CODE_OF_CONDUCT.md b/docs/CODE_OF_CONDUCT.md similarity index 100% rename from docs/contributor/CODE_OF_CONDUCT.md rename to docs/CODE_OF_CONDUCT.md diff --git a/docs/contributor/CONTRIBUTING.md b/docs/CONTRIBUTING.md similarity index 90% rename from docs/contributor/CONTRIBUTING.md rename to docs/CONTRIBUTING.md index 96dc86e9780..1e05755a9b8 100644 --- a/docs/contributor/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -93,12 +93,22 @@ The reviewers are also responsible to check: All Pull Requests must contain proper title & description. -Some Pull Requests can be exempt of `prdoc` documentation, those must be labelled with +Some Pull Requests can be exempt of `prdoc` documentation, those +must be labelled with [`R0-silent`](https://github.com/paritytech/labels/blob/main/ruled_labels/specs_polkadot-sdk.yaml#L89-L91). Non "silent" PRs must come with documentation in the form of a `.prdoc` file. +A `.prdoc` documentation is made of a text file (YAML) named `/prdoc/pr_NNNN.prdoc` where `NNNN` is the PR number. +For convenience, those file can also contain a short description/title: `/prdoc/pr_NNNN_pr-foobar.prdoc`. -See more about `prdoc` [here](./prdoc.md) +The CI automation checks for the presence and validity of a `prdoc` in the `/prdoc` folder. +Those files need to comply with a specific [schema](https://github.com/paritytech/prdoc/blob/master/schema_user.json). It +is highly recommended to [make your editor aware](https://github.com/paritytech/prdoc#schemas) of the schema as it is +self-described and will assist you in writing correct content. + +This schema is also embedded in the +[prdoc](https://github.com/paritytech/prdoc) utility that can also be used to generate and check the validity of a +`prdoc` locally. ## Helping out @@ -143,18 +153,8 @@ Or if you have opened PR and you're member of `paritytech` - you can use command - `bot update-ui latest -v CMD_IMAGE=paritytech/ci-unified:bullseye-1.70.0-2023-05-23 --rust_version=1.70.0` - will run the tests for the specified rust version and specified image -## Feature Propagation - -We use [zepter](https://github.com/ggwpez/zepter) to enforce features are propagated between crates correctly. - ## Command Bot If you're member of **paritytech** org - you can use command-bot to run various of common commands in CI: Start with comment in PR: `bot help` to see the list of available commands. - - -## Deprecating code - -When deprecating and removing code you need to be mindful of how this could impact downstream developers. In order to -mitigate this impact, it is recommended to adhere to the steps outlined in the [Deprecation Checklist](./DEPRECATION_CHECKLIST.md). diff --git a/docs/contributor/DEPRECATION_CHECKLIST.md b/docs/DEPRECATION_CHECKLIST.md similarity index 90% rename from docs/contributor/DEPRECATION_CHECKLIST.md rename to docs/DEPRECATION_CHECKLIST.md index 687c0a7cd7d..fccf93d2273 100644 --- a/docs/contributor/DEPRECATION_CHECKLIST.md +++ b/docs/DEPRECATION_CHECKLIST.md @@ -1,7 +1,9 @@ # Deprecation Checklist -Polkadot SDK is under constant development and improvement, thus deprecation and removal of existing code happen often. -When creating a breaking change we need to be mindful that external builders could be impacted by this. +This deprecation checklist makes sense while we don’t use [SemVer](https://semver.org/). +After that, this document will most likely change. +As deprecation and removal of existing code can happen on any release, we need to be mindful that external builders +could be impacted by the changes we make. The deprecation checklist tries to mitigate this impact, while still keeping the developer experience, the DevEx, as smooth as possible. @@ -43,7 +45,7 @@ We also need [https://docs.substrate.io/](https://docs.substrate.io/) to be upda ## Announce the deprecation and removal -**At minimum they should be noted in the release log.** Please see how to document a PR [here](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md#documentation). +**At minimum they should be noted in the release log.** Please see how to document a PR [here](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CONTRIBUTING.md#documentation). There you can give instructions based on the audience and tell them what they need to do to upgrade the code. Some breaking changes have a bigger impact than others. When the impact is big the release note is not enough, though diff --git a/docs/contributor/DOCUMENTATION_GUIDELINES.md b/docs/DOCUMENTATION_GUIDELINES.md similarity index 99% rename from docs/contributor/DOCUMENTATION_GUIDELINES.md rename to docs/DOCUMENTATION_GUIDELINES.md index 96811a2772d..5d1164e8ca8 100644 --- a/docs/contributor/DOCUMENTATION_GUIDELINES.md +++ b/docs/DOCUMENTATION_GUIDELINES.md @@ -225,7 +225,7 @@ For the top-level pallet docs, consider the following template: //! //! ## Pallet API //! -//! //! //! See the [`pallet`] module for more information about the interfaces this pallet exposes, including its @@ -349,7 +349,3 @@ Consider the fact that, similar to dispatchables, these docs will be part of the and might be used by wallets and explorers. Specifically for `error`, explain why the error has happened, and what can be done in order to avoid it. - -## Documenting Changes/PR - -See [PRDoc](./prdoc.md). diff --git a/docs/contributor/PULL_REQUEST_TEMPLATE.md b/docs/PULL_REQUEST_TEMPLATE.md similarity index 96% rename from docs/contributor/PULL_REQUEST_TEMPLATE.md rename to docs/PULL_REQUEST_TEMPLATE.md index 79a036a235a..c93ac90c7e3 100644 --- a/docs/contributor/PULL_REQUEST_TEMPLATE.md +++ b/docs/PULL_REQUEST_TEMPLATE.md @@ -3,7 +3,7 @@ ✄ ----------------------------------------------------------------------------- Thank you for your Pull Request! 🙏 Please make sure it follows the contribution guidelines outlined in -[this document](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md) and fill +[this document](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CONTRIBUTING.md) and fill out the sections below. Once you're ready to submit your PR for review, please delete this section and leave only the text under the "Description" heading. diff --git a/docs/contributor/SECURITY.md b/docs/SECURITY.md similarity index 100% rename from docs/contributor/SECURITY.md rename to docs/SECURITY.md diff --git a/docs/contributor/STYLE_GUIDE.md b/docs/STYLE_GUIDE.md similarity index 83% rename from docs/contributor/STYLE_GUIDE.md rename to docs/STYLE_GUIDE.md index 3df65d9699a..1ae9bc5003f 100644 --- a/docs/contributor/STYLE_GUIDE.md +++ b/docs/STYLE_GUIDE.md @@ -2,11 +2,9 @@ title: Style Guide for Rust in the Polkadot-SDK --- -Where possible these styles are enforced by settings in `rustfmt.toml` so if you run `cargo +nightly fmt` +Where possible these styles are enforced by settings in `rustfmt.toml` so if you run `cargo fmt` then you will adhere to most of these style guidelines automatically. -To see exactly which nightly version is used, check our CI job logs. - # Formatting - Indent using tabs. @@ -152,13 +150,31 @@ let mut target_path = # Manifest Formatting -We use [taplo](https://taplo.tamasfe.dev/) to enforce consistent TOML formatting. +> **TLDR** +> You can use the CLI tool [Zepter](https://crates.io/crates/zepter) to +> format the files: `zepter format features --fix` (or `zepter f f -f`). -You can install it with `cargo install taplo-cli` and format your code with `taplo format --config .config/taplo.toml`. +Rust `Cargo.toml` files need to respect certain formatting rules. All entries +need to be alphabetically sorted. This makes it easier to read them and insert +new entries. The exhaustive list of rules is enforced by the CI. The general +format looks like this: -See the config file for the exact rules. +- The feature is written as a single line if it fits within 80 chars: -You may find useful +```toml +[features] +default = [ "std" ] +``` -- [Taplo VSCode extension](https://marketplace.visualstudio.com/items?itemName=tamasfe.even-better-toml) -- For NeoVim, [taplo is avaliable with Mason](https://github.com/williamboman/mason-lspconfig.nvim#available-lsp-servers) +- Otherwise the feature is broken down into multiple lines with one entry per + line. Each line is padded with one tab and no trailing spaces but a trailing + comma. + +```toml +[features] +default = [ + "loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong", + # Comments go here as well ;) + "std", +] +``` diff --git a/docs/contributor/container.md b/docs/container.md similarity index 100% rename from docs/contributor/container.md rename to docs/container.md diff --git a/docs/contributor/prdoc.md b/docs/contributor/prdoc.md deleted file mode 100644 index af0ede5107a..00000000000 --- a/docs/contributor/prdoc.md +++ /dev/null @@ -1,71 +0,0 @@ -# PRDoc - -## Intro - -With the merge of [PR #1946](https://github.com/paritytech/polkadot-sdk/pull/1946), a new method for -documenting changes has been introduced: `prdoc`. The [prdoc repository](https://github.com/paritytech/prdoc) -contains more documentation and tooling. - -The current document describes how to quickly get started authoring `PRDoc` files. - -## Requirements - -When creating a PR, the author needs to decides with the `R0` label whether the change (PR) should -appear in the release notes or not. - -Labelling a PR with `R0` means that no `PRDoc` is required. - -A PR without the `R0` label **does** require a valid `PRDoc` file to be introduced in the PR. - -## PRDoc how-to - -A `.prdoc` file is a YAML file with a defined structure (ie JSON Schema). - -For significant changes, a `.prdoc` file is mandatory and the file must meet the following -requirements: -- file named `pr_NNNN.prdoc` where `NNNN` is the PR number. - For convenience, those file can also contain a short description: `pr_NNNN_foobar.prdoc`. -- located under the [`prdoc` folder](https://github.com/paritytech/polkadot-sdk/tree/master/prdoc) of the repository -- compliant with the [JSON schema](https://json-schema.org/) defined in `prdoc/schema_user.json` - -Those requirements can be fulfilled manually without any tooling but a text editor. - -## Tooling - -Users might find the following helpers convenient: -- Setup VSCode to be aware of the prdoc schema: see [using VSCode](https://github.com/paritytech/prdoc#using-vscode) -- Using the `prdoc` cli to: - - generate a `PRDoc` file from a [template defined in the Polkadot SDK - repo](https://github.com/paritytech/polkadot-sdk/blob/master/prdoc/.template.prdoc) simply providing a PR number - - check the validity of one or more `PRDoc` files - -## `prdoc` cli usage - -The `prdoc` cli documentation can be found at https://github.com/paritytech/prdoc#prdoc - -tldr: -- `prdoc generate ` -- `prdoc check -n ` - -where is the PR number. - -## Pick an audience - -While describing a PR, the author needs to consider which audience(s) need to be addressed. -The list of valid audiences is described and documented in the JSON schema as follow: - -- `Node Dev`: Those who build around the client side code. Alternative client builders, SMOLDOT, those who consume RPCs. - These are people who are oblivious to the runtime changes. They only care about the meta-protocol, not the protocol - itself. - -- `Runtime Dev`: All of those who rely on the runtime. A parachain team that is using a pallet. A DApp that is using a - pallet. These are people who care about the protocol (WASM), not the meta-protocol (client). - -- `Node Operator`: Those who don't write any code and only run code. - -- `Runtime User`: Anyone using the runtime. This can be a token holder or a dev writing a front end for a chain. - -## Tips - -The PRDoc schema is defined in each repo and usually is quite restrictive. -You cannot simply add a new property to a `PRDoc` file unless the Schema allows it. diff --git a/docs/contributor/docker.md b/docs/docker.md similarity index 100% rename from docs/contributor/docker.md rename to docs/docker.md diff --git a/docs/contributor/markdown_linting.md b/docs/markdown_linting.md similarity index 100% rename from docs/contributor/markdown_linting.md rename to docs/markdown_linting.md diff --git a/docs/mermaid/IA.mmd b/docs/mermaid/IA.mmd deleted file mode 100644 index 93d3e92814c..00000000000 --- a/docs/mermaid/IA.mmd +++ /dev/null @@ -1,14 +0,0 @@ -flowchart - parity[paritytech.github.io] --> devhub[polkadot_sdk_docs] - - devhub --> polkadot_sdk - devhub --> reference_docs - devhub --> tutorial - - polkadot_sdk --> substrate - polkadot_sdk --> frame - polkadot_sdk --> cumulus - polkadot_sdk --> polkadot - polkadot_sdk --> xcm - - diff --git a/docs/mermaid/extrinsics.mmd b/docs/mermaid/extrinsics.mmd deleted file mode 100644 index 4afd4ab8f75..00000000000 --- a/docs/mermaid/extrinsics.mmd +++ /dev/null @@ -1,5 +0,0 @@ -flowchart TD - E(Extrinsic) ---> I(Inherent); - E --> T(Transaction) - T --> ST("Signed (aka. Transaction)") - T --> UT(Unsigned) diff --git a/docs/mermaid/polkadot_sdk_parachain.mmd b/docs/mermaid/polkadot_sdk_parachain.mmd deleted file mode 100644 index 3f38fce046c..00000000000 --- a/docs/mermaid/polkadot_sdk_parachain.mmd +++ /dev/null @@ -1,11 +0,0 @@ -flowchart LR - subgraph Parachain[A Polkadot Parachain] - ParachainNode[Parachain Node] - ParachainRuntime[Parachain Runtime] - end - - FRAME -.-> ParachainRuntime - Substrate[Substrate Node Libraries] -.-> ParachainNoe - - CumulusC[Cumulus Node Libraries] -.-> ParachainNode - CumulusR[Cumulus Runtime Libraries] -.-> ParachainRuntime diff --git a/docs/mermaid/polkadot_sdk_polkadot.mmd b/docs/mermaid/polkadot_sdk_polkadot.mmd deleted file mode 100644 index 3326cc59383..00000000000 --- a/docs/mermaid/polkadot_sdk_polkadot.mmd +++ /dev/null @@ -1,10 +0,0 @@ -flowchart LR - - subgraph Polkadot[The Polkadot Relay Chain] - PolkadotNode[Polkadot Node] - PolkadotRuntime[Polkadot Runtime] - end - - FRAME -.-> PolkadotRuntime - Substrate[Substrate Node Libraries] -.-> PolkadotNode - diff --git a/docs/mermaid/polkadot_sdk_substrate.mmd b/docs/mermaid/polkadot_sdk_substrate.mmd deleted file mode 100644 index dfaf20d241f..00000000000 --- a/docs/mermaid/polkadot_sdk_substrate.mmd +++ /dev/null @@ -1,8 +0,0 @@ -flowchart LR - subgraph SubstrateChain[A Substrate-based blockchain] - Node - Runtime - end - - FRAME -.-> Runtime - Substrate[Substrate Node Libraries] -.-> Node diff --git a/docs/mermaid/state.mmd b/docs/mermaid/state.mmd deleted file mode 100644 index c72ecbfd156..00000000000 --- a/docs/mermaid/state.mmd +++ /dev/null @@ -1,16 +0,0 @@ -flowchart TB - subgraph Node[Node's View Of The State 🙈] - direction LR - 0x1234 --> 0x2345 - 0x3456 --> 0x4567 - 0x5678 --> 0x6789 - :code --> code[wasm code] - end - - subgraph Runtime[Runtime's View Of The State 🙉] - direction LR - ab[alice's balance] --> abv[known value] - bb[bob's balance] --> bbv[known value] - cb[charlie's balance] --> cbv[known value] - c2[:code] --> c22[wasm code] - end diff --git a/docs/mermaid/stf.mmd b/docs/mermaid/stf.mmd deleted file mode 100644 index dd6c7c36de6..00000000000 --- a/docs/mermaid/stf.mmd +++ /dev/null @@ -1,21 +0,0 @@ -flowchart LR - %%{init: {'flowchart' : {'curve' : 'linear'}}}%% - subgraph BData[Blockchain Database] - direction LR - BN[Block N] -.-> BN1[Block N+1] - end - - subgraph SData[State Database] - direction LR - SN[State N] -.-> SN1[State N+1] -.-> SN2[State N+2] - end - - BN --> STFN[STF] - SN --> STFN[STF] - STFN[STF] --> SN1 - - BN1 --> STFN1[STF] - SN1 --> STFN1[STF] - STFN1[STF] --> SN2 - - diff --git a/docs/mermaid/stf_simple.mmd b/docs/mermaid/stf_simple.mmd deleted file mode 100644 index 5db20cf6156..00000000000 --- a/docs/mermaid/stf_simple.mmd +++ /dev/null @@ -1,4 +0,0 @@ -flowchart LR - B[Block] --> STF - S[State] --> STF - STF --> NS[New State] diff --git a/docs/mermaid/substrate_client_runtime.mmd b/docs/mermaid/substrate_client_runtime.mmd index caab2b62302..23c3f849224 100644 --- a/docs/mermaid/substrate_client_runtime.mmd +++ b/docs/mermaid/substrate_client_runtime.mmd @@ -1,12 +1,10 @@ graph TB subgraph Substrate direction LR - subgraph Node + subgraph Client end - subgraph Runtime end - - Node --runtime-api--> Runtime - Runtime --host-functions--> Node + Client --runtime-api--> Runtime + Runtime --host-functions--> Client end diff --git a/docs/mermaid/substrate_dev.mmd b/docs/mermaid/substrate_dev.mmd deleted file mode 100644 index fc331ce311f..00000000000 --- a/docs/mermaid/substrate_dev.mmd +++ /dev/null @@ -1,2 +0,0 @@ -flowchart LR - T[Using a Template] --> P[Writing Your Own FRAME-Based Pallet] --> C[Custom Node] diff --git a/docs/mermaid/substrate_simple.mmd b/docs/mermaid/substrate_simple.mmd index a752eaba625..475d8be5ef8 100644 --- a/docs/mermaid/substrate_simple.mmd +++ b/docs/mermaid/substrate_simple.mmd @@ -1,7 +1,7 @@ graph TB subgraph Substrate direction LR - subgraph Node + subgraph Client end subgraph Runtime end diff --git a/docs/mermaid/substrate_with_frame.mmd b/docs/mermaid/substrate_with_frame.mmd index 173c1757b95..12d072a3360 100644 --- a/docs/mermaid/substrate_with_frame.mmd +++ b/docs/mermaid/substrate_with_frame.mmd @@ -1,7 +1,7 @@ graph TB subgraph Substrate direction LR - subgraph Node + subgraph Client Database Networking Consensus @@ -15,6 +15,6 @@ subgraph Substrate Identity end end - Node --runtime-api--> Runtime - Runtime --host-functions--> Node + Client --runtime-api--> Runtime + Runtime --host-functions--> Client end diff --git a/docs/sdk/Cargo.toml b/docs/sdk/Cargo.toml deleted file mode 100644 index c58c3402f6a..00000000000 --- a/docs/sdk/Cargo.toml +++ /dev/null @@ -1,69 +0,0 @@ -[package] -name = "polkadot-sdk-docs" -description = "The one stop shop for developers of the polakdot-sdk" -license = "GPL-3.0-or-later WITH Classpath-exception-2.0" -homepage = "paritytech.github.io" -repository.workspace = true -authors.workspace = true -edition.workspace = true -# This crate is not publish-able to crates.io for now because of docify. -publish = false -version = "0.0.1" - -[lints] -workspace = true - -[dependencies] -# Needed for all FRAME-based code -parity-scale-codec = { version = "3.0.0", default-features = false } -scale-info = { version = "2.6.0", default-features = false } -frame = { path = "../../substrate/frame", features = ["experimental", "runtime"] } -pallet-examples = { path = "../../substrate/frame/examples" } -pallet-default-config-example = { path = "../../substrate/frame/examples/default-config" } - -# How we build docs in rust-docs -simple-mermaid = { git = "https://github.com/kianenigma/simple-mermaid.git", branch = "main" } -docify = "0.2.6" - -# Polkadot SDK deps, typically all should only be in scope such that we can link to their doc item. -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" } - -# Substrate -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" } -substrate-wasm-builder = { path = "../../substrate/utils/wasm-builder" } - -# Cumulus -cumulus-pallet-aura-ext = { path = "../../cumulus/pallets/aura-ext" } -cumulus-pallet-parachain-system = { path = "../../cumulus/pallets/parachain-system", features = [ - "parameterized-consensus-hook", -] } -parachain-info = { package = "staging-parachain-info", path = "../../cumulus/parachains/pallets/parachain-info" } -pallet-aura = { path = "../../substrate/frame/aura", default-features = false } -pallet-timestamp = { path = "../../substrate/frame/timestamp" } - -# 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" } - -[dev-dependencies] -parity-scale-codec = "3.6.5" -scale-info = "2.9.0" - -[features] -experimental = ["pallet-aura/experimental"] diff --git a/docs/sdk/headers/toc.html b/docs/sdk/headers/toc.html deleted file mode 100644 index a4a074cb4f3..00000000000 --- a/docs/sdk/headers/toc.html +++ /dev/null @@ -1,54 +0,0 @@ - - diff --git a/docs/sdk/src/guides/changing_consensus.rs b/docs/sdk/src/guides/changing_consensus.rs deleted file mode 100644 index 7ba742f1072..00000000000 --- a/docs/sdk/src/guides/changing_consensus.rs +++ /dev/null @@ -1 +0,0 @@ -//! # Changing Consensus diff --git a/docs/sdk/src/guides/cumulus_enabled_parachain.rs b/docs/sdk/src/guides/cumulus_enabled_parachain.rs deleted file mode 100644 index fafd97feb82..00000000000 --- a/docs/sdk/src/guides/cumulus_enabled_parachain.rs +++ /dev/null @@ -1 +0,0 @@ -//! # Cumulus Enabled Parachain diff --git a/docs/sdk/src/guides/mod.rs b/docs/sdk/src/guides/mod.rs deleted file mode 100644 index 3120f253310..00000000000 --- a/docs/sdk/src/guides/mod.rs +++ /dev/null @@ -1,25 +0,0 @@ -//! # 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. - -/// Write your first simple pallet, learning the most most basic features of FRAME along the way. -pub mod your_first_pallet; - -/// Writing your first real [runtime](`crate::reference_docs::wasm_meta_protocol`), and successfully -/// compiling it to [WASM](crate::polkadot_sdk::substrate#wasm-build). -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; - -/// 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; - -/// 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; diff --git a/docs/sdk/src/guides/xcm_enabled_parachain.rs b/docs/sdk/src/guides/xcm_enabled_parachain.rs deleted file mode 100644 index 4518cab9342..00000000000 --- a/docs/sdk/src/guides/xcm_enabled_parachain.rs +++ /dev/null @@ -1 +0,0 @@ -//! # XCM Enabled Parachain diff --git a/docs/sdk/src/guides/your_first_node.rs b/docs/sdk/src/guides/your_first_node.rs deleted file mode 100644 index d12349c9906..00000000000 --- a/docs/sdk/src/guides/your_first_node.rs +++ /dev/null @@ -1 +0,0 @@ -//! # Your first Node diff --git a/docs/sdk/src/guides/your_first_pallet/mod.rs b/docs/sdk/src/guides/your_first_pallet/mod.rs deleted file mode 100644 index c886bc9af84..00000000000 --- a/docs/sdk/src/guides/your_first_pallet/mod.rs +++ /dev/null @@ -1,754 +0,0 @@ -//! # Currency Pallet -//! -//! By the end of this guide, you will write a small FRAME pallet (see -//! [`crate::polkadot_sdk::frame_runtime`]) that is capable of handling a simple crypto-currency. -//! This pallet will: -//! -//! 1. Allow anyone to mint new tokens into accounts (which is obviously not a great idea for a real -//! system). -//! 2. Allow any user that owns tokens to transfer them to others. -//! 3. Track the total issuance of all tokens at all times. -//! -//! > This guide will build a currency pallet from scratch using only the lowest primitives of -//! > FRAME, and is mainly intended for education, not *applicability*. For example, almost all -//! > 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 -//! -//! The following FRAME topics are covered in this guide: -//! -//! - [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 -//! -//! You should have studied the following modules as a prelude to this guide: -//! -//! - [`crate::reference_docs::blockchain_state_machines`] -//! - [`crate::reference_docs::trait_based_programming`] -//! - [`crate::polkadot_sdk::frame_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. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", shell_pallet)] -//! -//! ### Storage -//! -//! First, we will need to create two onchain storage declarations. -//! -//! One should be a mapping from account-ids to a balance type, and one value that is the total -//! issuance. -//! -//! > For the rest of this guide, we will opt for a balance type of `u128`. For the sake of -//! > simplicity, we are hardcoding this type. In a real pallet is best practice to define it as a -//! > 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: -#![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`. -#![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 -//! details: -//! -//! - Where do `T::AccountId` and `T::RuntimeOrigin` come from? These are both defined in -//! [`frame::prelude::frame_system::Config`], therefore we can access them in `T`. -//! - What is `ensure_signed`, and what does it do with the aforementioned `T::RuntimeOrigin`? This -//! is outside the scope of this guide, and you can learn more about it in the origin reference -//! document ([`crate::reference_docs::frame_origin`]). For now, you should only know the -//! signature of the function: it takes a generic `T::RuntimeOrigin` and returns a -//! `Result`. So by the end of this function call, we know that this dispatchable -//! 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`]. -//! -//! - The return type of all dispatchable functions is [`frame::prelude::DispatchResult`]: -#![doc = docify::embed!("../../substrate/frame/support/src/dispatch.rs", DispatchResult)] -//! -//! Which is more or less a normal Rust `Result`, with a custom [`frame::prelude::DispatchError`] as -//! the `Err` variant. We won't cover this error in detail here, but importantly you should know -//! that there is an `impl From<&'static string> for DispatchError` provided (see -//! [here](`frame::prelude::DispatchError#impl-From<%26'static+str>-for-DispatchError`)). Therefore, -//! we can use basic string literals as our error type and `.into()` them into `DispatchError`. -//! -//! - 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`] -//! -//! ### Improving Errors -//! -//! How we handle error in the above snippets is fairly rudimentary. Let's look at how this can be -//! improved. First, we can use [`frame::prelude::ensure`] to express the error slightly better. -//! This macro will call `.into()` under the hood. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", transfer_better)] -//! -//! Moreover, you will learn in the [Safe Defensive Programming -//! section](crate::reference_docs::safe_defensive_programming) that it is always recommended to use -//! safe arithmetic operations in your runtime. By using [`frame::traits::CheckedSub`], we can not -//! only take a step in that direction, but also improve the error handing and make it slightly more -//! ergonomic. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", transfer_better_checked)] -//! -//! This is more or less all the logic that there is this basic currency pallet! -//! -//! ### Your First (Test) Runtime -//! -//! 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 -//! [`frame::prelude::frame_system`]. So we expect to see a runtime with two pallet, `frame_system` -//! and the one we just wrote. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", runtime)] -//! -//! > [`frame::pallet_macros::derive_impl`] is a FRAME feature that enables developers to have -//! > defaults for associated types. -//! -//! Recall that within our pallet, (almost) all blocks of code are generic over ``. And, -//! because `trait Config: frame_system::Config`, we can get access to all items in `Config` (or -//! `frame_system::Config`) using `T::NameOfItem`. This is all within the boundaries of how Rust -//! traits and generics work. If unfamiliar with this pattern, read -//! [`crate::reference_docs::trait_based_programming`] before going further. -//! -//! Crucially, a typical FRAME runtime contains a `struct Runtime`. The main role of this `struct` -//! is to implement the `trait Config` of all pallets. That is, anywhere within your pallet code -//! where you see `` (read: *"some type `T` that implements `Config`"*), in the runtime, -//! it can be replaced with ``, because `Runtime` implements `Config` of all pallets, as we -//! see above. -//! -//! Another way to think about this is that within a pallet, a lot of types are "unknown" and, we -//! only know that they will be provided at some later point. For example, when you write -//! `T::AccountId` (which is short for `::AccountId`) in your pallet, -//! you are in fact saying "*Some type `AccountId` that will be known later*". That "later" is in -//! fact when you specify these types when you implement all `Config` traits for `Runtime`. -//! -//! As you see above, `frame_system::Config` is setting the `AccountId` to `u64`. Of course, a real -//! runtime will not use this type, and instead reside to a proper type like a 32-byte standard -//! public key. This is a HUGE benefit that FRAME developers can tap into: through the framework -//! being so generic, different types can always be customized to simple things when needed. -//! -//! > Imagine how hard it would have been if all tests had to use a real 32-byte account id, as -//! > opposed to just a u64 number 🙈. -//! -//! ### Your First Test -//! -//! The above is all you need to execute the dispatchables of your pallet. The last thing you need -//! to learn is that all of your pallet testing code should be wrapped in -//! [`frame::testing_prelude::TestState`]. This is a type that provides access to an in-memory state -//! to be used in our tests. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", first_test)] -//! -//! In the first test, we simply assert that there is no total issuance, and no balance associated -//! with Alice's account. Then, we mint some balance into Alice's, and re-check. -//! -//! 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. -//! -//! ## Improving the Currency Pallet -//! -//! ### Better Test Setup -//! -//! Idiomatic FRAME pallets often use Builder pattern to define their initial state. -//! -//! > The Polkadot Blockchain Academy's Rust entrance exam has a -//! > [section](https://github.com/Polkadot-Blockchain-Academy/pba-qualifier-exam/blob/main/src/m_builder.rs) -//! > on this that you can use to learn the Builder Pattern. -//! -//! Let's see how we can implement a better test setup using this pattern. First, we define a -//! `struct StateBuilder`. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", StateBuilder)] -//! -//! This struct is meant to contain the same list of accounts and balances that we want to have at -//! the beginning of each block. We hardcoded this to `let accounts = vec![(ALICE, 100), (2, 100)];` -//! so far. Then, if desired, we attach a default value for this struct. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", default_state_builder)] -//! -//! Like any other builder pattern, we attach functions to the type to mutate its internal -//! properties. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", impl_state_builder_add)] -//! -//! Finally --the useful part-- we write our own custom `build_and_execute` function on -//! this type. This function will do multiple things: -//! -//! 1. It would consume `self` to produce our `TestState` based on the properties that we attached -//! to `self`. -//! 2. It would execute any test function that we pass in as closure. -//! 3. A nifty trick, this allows our test setup to have some code that is executed both before and -//! after each test. For example, in this test, we do some additional checking about the -//! correctness of the `TotalIssuance`. We leave it up to you as an exercise to learn why the -//! assertion should always hold, and how it is checked. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", impl_state_builder_build)] -//! -//! We can write tests that specifically check the initial state, and making sure our `StateBuilder` -//! is working exactly as intended. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", state_builder_works)] -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", state_builder_add_balance)] -//! -//! ### More Tests -//! -//! Now that we have a more ergonomic test setup, let's see how a well written test for transfer and -//! mint would look like. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", transfer_works)] -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", mint_works)] -//! -//! It is always a good idea to build a mental model where you write *at least* one test for each -//! "success path" of a dispatchable, and one test for each "failure path", such as: -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", transfer_from_non_existent_fails)] -//! -//! We leave it up to you to write a test that triggers the `InsufficientBalance` error. -//! -//! ### Event and Error -//! -//! Our pallet is mainly missing two parts that are common in most FRAME pallets: Events, and -//! Errors. First, let's understand what each is. -//! -//! - **Error**: The static string-based error scheme we used so far is good for readability, but it -//! has a few drawbacks. The biggest problem with strings are that they are not type safe, e.g. a -//! match statement cannot be exhaustive. These string literals will bloat the final wasm blob, -//! and are relatively heavy to transmit and encode/decode. Moreover, it is easy to mistype them -//! 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`]. -//! -//! - **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 -//! otherwise, the outside world does not have an easy access to the state changes. They should -//! represent what happened at the end of a dispatch operation. Therefore, the convention is to -//! 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 an extra `#[frame::event/error]` attribute -//! 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)]` 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: -//! From>`. Read: a `RuntimeEvent` exists, and it can be created from the local `enum -//! Event` of this pallet. This enables the pallet to convert its `Event` into `RuntimeEvent`, and -//! 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` is doing. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", config_v2)] -//! -//! > These `Runtime*` types are better explained in -//! > [`crate::reference_docs::frame_composite_enums`]. -//! -//! Then, we can rewrite the `transfer` dispatchable as such: -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", transfer_v2)] -//! -//! Then, notice how now we would need to provide this `type RuntimeEvent` in our test runtime -//! setup. -#![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", runtime_v2)] -//! -//! In this snippet, the actual `RuntimeEvent` type (right hand side of `type RuntimeEvent = -//! RuntimeEvent`) is generated by `construct_runtime`. An interesting way to inspect this type is -//! to see its definition in rust-docs: -//! [`crate::guides::your_first_pallet::pallet_v2::tests::runtime_v2::RuntimeEvent`]. -//! -//! -//! -//! ## What Next? -//! -//! The following topics where used in this guide, but not covered in depth. It is suggested to -//! study them subsequently: -//! -//! - [`crate::reference_docs::safe_defensive_programming`]. -//! - [`crate::reference_docs::frame_origin`]. -//! - [`crate::reference_docs::frame_composite_enums`]. -//! - The pallet we wrote in this guide was using `dev_mode`, learn more in -//! [`frame::pallet_macros::config`]. -//! - Learn more about the individual pallet items/macros, such as event and errors and call, in -//! [`frame::pallet_macros`]. - -#[docify::export] -#[frame::pallet(dev_mode)] -pub mod shell_pallet { - use frame::prelude::*; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); -} - -#[frame::pallet(dev_mode)] -pub mod pallet { - use frame::prelude::*; - - #[docify::export] - pub type Balance = u128; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); - - #[docify::export] - /// Single storage item, of type `Balance`. - #[pallet::storage] - pub type TotalIssuance = StorageValue<_, Balance>; - - #[docify::export] - /// A mapping from `T::AccountId` to `Balance` - #[pallet::storage] - pub type Balances = StorageMap<_, _, T::AccountId, Balance>; - - #[docify::export(impl_pallet)] - #[pallet::call] - impl Pallet { - /// An unsafe mint that can be called by anyone. Not a great idea. - pub fn mint_unsafe( - origin: T::RuntimeOrigin, - dest: T::AccountId, - amount: Balance, - ) -> DispatchResult { - // ensure that this is a signed account, but we don't really check `_anyone`. - let _anyone = ensure_signed(origin)?; - - // update the balances map. Notice how all `` remains as ``. - Balances::::mutate(dest, |b| *b = Some(b.unwrap_or(0) + amount)); - // update total issuance. - TotalIssuance::::mutate(|t| *t = Some(t.unwrap_or(0) + amount)); - - Ok(()) - } - - /// Transfer `amount` from `origin` to `dest`. - pub fn transfer( - origin: T::RuntimeOrigin, - dest: T::AccountId, - amount: Balance, - ) -> DispatchResult { - let sender = ensure_signed(origin)?; - - // ensure sender has enough balance, and if so, calculate what is left after `amount`. - let sender_balance = Balances::::get(&sender).ok_or("NonExistentAccount")?; - if sender_balance < amount { - return Err("InsufficientBalance".into()) - } - let reminder = sender_balance - amount; - - // update sender and dest balances. - Balances::::mutate(dest, |b| *b = Some(b.unwrap_or(0) + amount)); - Balances::::insert(&sender, reminder); - - Ok(()) - } - } - - #[allow(unused)] - impl Pallet { - #[docify::export] - pub fn transfer_better( - origin: T::RuntimeOrigin, - dest: T::AccountId, - amount: Balance, - ) -> DispatchResult { - let sender = ensure_signed(origin)?; - - let sender_balance = Balances::::get(&sender).ok_or("NonExistentAccount")?; - ensure!(sender_balance >= amount, "InsufficientBalance"); - let reminder = sender_balance - amount; - - // .. snip - Ok(()) - } - - #[docify::export] - /// Transfer `amount` from `origin` to `dest`. - pub fn transfer_better_checked( - origin: T::RuntimeOrigin, - dest: T::AccountId, - amount: Balance, - ) -> DispatchResult { - let sender = ensure_signed(origin)?; - - let sender_balance = Balances::::get(&sender).ok_or("NonExistentAccount")?; - let reminder = sender_balance.checked_sub(amount).ok_or("InsufficientBalance")?; - - // .. snip - Ok(()) - } - } - - #[cfg(any(test, doc))] - pub(crate) mod tests { - use crate::guides::your_first_pallet::pallet::*; - use frame::testing_prelude::*; - const ALICE: u64 = 1; - const BOB: u64 = 2; - const CHARLIE: u64 = 3; - - #[docify::export] - mod runtime { - use super::*; - // we need to reference our `mod pallet` as an identifier to pass to - // `construct_runtime`. - use crate::guides::your_first_pallet::pallet as pallet_currency; - - construct_runtime!( - pub struct Runtime { - // ---^^^^^^ This is where `struct Runtime` is defined. - System: frame_system, - Currency: pallet_currency, - } - ); - - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] - impl frame_system::Config for Runtime { - type Block = MockBlock; - // within pallet we just said `::AccountId`, now we - // finally specified it. - type AccountId = u64; - } - - // our simple pallet has nothing to be configured. - impl pallet_currency::Config for Runtime {} - } - - pub(crate) use runtime::*; - - #[allow(unused)] - #[docify::export] - fn new_test_state_basic() -> TestState { - let mut state = TestState::new_empty(); - let accounts = vec![(ALICE, 100), (BOB, 100)]; - state.execute_with(|| { - for (who, amount) in &accounts { - Balances::::insert(who, amount); - TotalIssuance::::mutate(|b| *b = Some(b.unwrap_or(0) + amount)); - } - }); - - state - } - - #[docify::export] - pub(crate) struct StateBuilder { - balances: Vec<(::AccountId, Balance)>, - } - - #[docify::export(default_state_builder)] - impl Default for StateBuilder { - fn default() -> Self { - Self { balances: vec![(ALICE, 100), (BOB, 100)] } - } - } - - #[docify::export(impl_state_builder_add)] - impl StateBuilder { - fn add_balance( - mut self, - who: ::AccountId, - amount: Balance, - ) -> Self { - self.balances.push((who, amount)); - self - } - } - - #[docify::export(impl_state_builder_build)] - impl StateBuilder { - pub(crate) fn build_and_execute(self, test: impl FnOnce() -> ()) { - let mut ext = TestState::new_empty(); - ext.execute_with(|| { - for (who, amount) in &self.balances { - Balances::::insert(who, amount); - TotalIssuance::::mutate(|b| *b = Some(b.unwrap_or(0) + amount)); - } - }); - - ext.execute_with(test); - - // assertions that must always hold - ext.execute_with(|| { - assert_eq!( - Balances::::iter().map(|(_, x)| x).sum::(), - TotalIssuance::::get().unwrap_or_default() - ); - }) - } - } - - #[docify::export] - #[test] - fn first_test() { - TestState::new_empty().execute_with(|| { - // We expect Alice's account to have no funds. - assert_eq!(Balances::::get(&ALICE), None); - assert_eq!(TotalIssuance::::get(), None); - - // mint some funds into Alice's account. - assert_ok!(Pallet::::mint_unsafe( - RuntimeOrigin::signed(ALICE), - ALICE, - 100 - )); - - // re-check the above - assert_eq!(Balances::::get(&ALICE), Some(100)); - assert_eq!(TotalIssuance::::get(), Some(100)); - }) - } - - #[docify::export] - #[test] - fn state_builder_works() { - StateBuilder::default().build_and_execute(|| { - assert_eq!(Balances::::get(&ALICE), Some(100)); - assert_eq!(Balances::::get(&BOB), Some(100)); - assert_eq!(Balances::::get(&CHARLIE), None); - assert_eq!(TotalIssuance::::get(), Some(200)); - }); - } - - #[docify::export] - #[test] - fn state_builder_add_balance() { - StateBuilder::default().add_balance(CHARLIE, 42).build_and_execute(|| { - assert_eq!(Balances::::get(&CHARLIE), Some(42)); - assert_eq!(TotalIssuance::::get(), Some(242)); - }) - } - - #[test] - #[should_panic] - fn state_builder_duplicate_genesis_fails() { - StateBuilder::default() - .add_balance(CHARLIE, 42) - .add_balance(CHARLIE, 43) - .build_and_execute(|| { - assert_eq!(Balances::::get(&CHARLIE), None); - assert_eq!(TotalIssuance::::get(), Some(242)); - }) - } - - #[docify::export] - #[test] - fn mint_works() { - StateBuilder::default().build_and_execute(|| { - // given the initial state, when: - assert_ok!(Pallet::::mint_unsafe(RuntimeOrigin::signed(ALICE), BOB, 100)); - - // then: - assert_eq!(Balances::::get(&BOB), Some(200)); - assert_eq!(TotalIssuance::::get(), Some(300)); - - // given: - assert_ok!(Pallet::::mint_unsafe( - RuntimeOrigin::signed(ALICE), - CHARLIE, - 100 - )); - - // then: - assert_eq!(Balances::::get(&CHARLIE), Some(100)); - assert_eq!(TotalIssuance::::get(), Some(400)); - }); - } - - #[docify::export] - #[test] - fn transfer_works() { - StateBuilder::default().build_and_execute(|| { - // given the the initial state, when: - assert_ok!(Pallet::::transfer(RuntimeOrigin::signed(ALICE), BOB, 50)); - - // then: - assert_eq!(Balances::::get(&ALICE), Some(50)); - assert_eq!(Balances::::get(&BOB), Some(150)); - assert_eq!(TotalIssuance::::get(), Some(200)); - - // when: - assert_ok!(Pallet::::transfer(RuntimeOrigin::signed(BOB), ALICE, 50)); - - // then: - assert_eq!(Balances::::get(&ALICE), Some(100)); - assert_eq!(Balances::::get(&BOB), Some(100)); - assert_eq!(TotalIssuance::::get(), Some(200)); - }); - } - - #[docify::export] - #[test] - fn transfer_from_non_existent_fails() { - StateBuilder::default().build_and_execute(|| { - // given the the initial state, when: - assert_err!( - Pallet::::transfer(RuntimeOrigin::signed(CHARLIE), ALICE, 10), - "NonExistentAccount" - ); - - // then nothing has changed. - assert_eq!(Balances::::get(&ALICE), Some(100)); - assert_eq!(Balances::::get(&BOB), Some(100)); - assert_eq!(Balances::::get(&CHARLIE), None); - assert_eq!(TotalIssuance::::get(), Some(200)); - }); - } - } -} - -#[frame::pallet(dev_mode)] -pub mod pallet_v2 { - use super::pallet::Balance; - use frame::prelude::*; - - #[docify::export(config_v2)] - #[pallet::config] - pub trait Config: frame_system::Config { - /// The overarching event type of the runtime. - type RuntimeEvent: From> - + IsType<::RuntimeEvent> - + TryInto>; - } - - #[pallet::pallet] - pub struct Pallet(_); - - #[pallet::storage] - pub type Balances = StorageMap<_, _, T::AccountId, Balance>; - - #[pallet::storage] - pub type TotalIssuance = StorageValue<_, Balance>; - - #[docify::export] - #[pallet::error] - pub enum Error { - /// Account does not exist. - NonExistentAccount, - /// Account does not have enough balance. - InsufficientBalance, - } - - #[docify::export] - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - /// A transfer succeeded. - Transferred { from: T::AccountId, to: T::AccountId, amount: Balance }, - } - - #[pallet::call] - impl Pallet { - #[docify::export(transfer_v2)] - pub fn transfer( - origin: T::RuntimeOrigin, - dest: T::AccountId, - amount: Balance, - ) -> DispatchResult { - let sender = ensure_signed(origin)?; - - // ensure sender has enough balance, and if so, calculate what is left after `amount`. - let sender_balance = - Balances::::get(&sender).ok_or(Error::::NonExistentAccount)?; - let reminder = - sender_balance.checked_sub(amount).ok_or(Error::::InsufficientBalance)?; - - Balances::::mutate(&dest, |b| *b = Some(b.unwrap_or(0) + amount)); - Balances::::insert(&sender, reminder); - - Self::deposit_event(Event::::Transferred { from: sender, to: dest, amount }); - - Ok(()) - } - } - - #[cfg(any(test, doc))] - pub mod tests { - use super::{super::pallet::tests::StateBuilder, *}; - use frame::testing_prelude::*; - const ALICE: u64 = 1; - const BOB: u64 = 2; - - #[docify::export] - pub mod runtime_v2 { - use super::*; - use crate::guides::your_first_pallet::pallet_v2 as pallet_currency; - - construct_runtime!( - pub struct Runtime { - System: frame_system, - Currency: pallet_currency, - } - ); - - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] - impl frame_system::Config for Runtime { - type Block = MockBlock; - type AccountId = u64; - } - - impl pallet_currency::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - } - } - - pub(crate) use runtime_v2::*; - - #[docify::export(transfer_works_v2)] - #[test] - fn transfer_works() { - StateBuilder::default().build_and_execute(|| { - // skip the genesis block, as events are not deposited there and we need them for - // the final assertion. - System::set_block_number(ALICE); - - // given the the initial state, when: - assert_ok!(Pallet::::transfer(RuntimeOrigin::signed(ALICE), BOB, 50)); - - // then: - assert_eq!(Balances::::get(&ALICE), Some(50)); - assert_eq!(Balances::::get(&BOB), Some(150)); - assert_eq!(TotalIssuance::::get(), Some(200)); - - // now we can also check that an event has been deposited: - assert_eq!( - System::read_events_for_pallet::>(), - vec![Event::Transferred { from: ALICE, to: BOB, amount: 50 }] - ); - }); - } - } -} diff --git a/docs/sdk/src/guides/your_first_pallet/with_event.rs b/docs/sdk/src/guides/your_first_pallet/with_event.rs deleted file mode 100644 index a65aac324f0..00000000000 --- a/docs/sdk/src/guides/your_first_pallet/with_event.rs +++ /dev/null @@ -1,101 +0,0 @@ -#[frame::pallet(dev_mode)] -pub mod pallet { - use frame::prelude::*; - - #[docify::export] - pub type Balance = u128; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); - - #[docify::export] - /// Single storage item, of type `Balance`. - #[pallet::storage] - pub type TotalIssuance = StorageValue<_, Balance>; - - #[docify::export] - /// A mapping from `T::AccountId` to `Balance` - #[pallet::storage] - pub type Balances = StorageMap<_, _, T::AccountId, Balance>; - - #[docify::export(impl_pallet)] - #[pallet::call] - impl Pallet { - /// An unsafe mint that can be called by anyone. Not a great idea. - pub fn mint_unsafe( - origin: T::RuntimeOrigin, - dest: T::AccountId, - amount: Balance, - ) -> DispatchResult { - // ensure that this is a signed account, but we don't really check `_anyone`. - let _anyone = ensure_signed(origin)?; - - // update the balances map. Notice how all `` remains as ``. - Balances::::mutate(dest, |b| *b = Some(b.unwrap_or(0) + amount)); - // update total issuance. - TotalIssuance::::mutate(|t| *t = Some(t.unwrap_or(0) + amount)); - - Ok(()) - } - - /// Transfer `amount` from `origin` to `dest`. - pub fn transfer( - origin: T::RuntimeOrigin, - dest: T::AccountId, - amount: Balance, - ) -> DispatchResult { - let sender = ensure_signed(origin)?; - - // ensure sender has enough balance, and if so, calculate what is left after `amount`. - let sender_balance = Balances::::get(&sender).ok_or("NonExistentAccount")?; - if sender_balance < amount { - return Err("NotEnoughBalance".into()) - } - let reminder = sender_balance - amount; - - // update sender and dest balances. - Balances::::mutate(dest, |b| *b = Some(b.unwrap_or(0) + amount)); - Balances::::insert(&sender, reminder); - - Ok(()) - } - } - - #[allow(unused)] - impl Pallet { - #[docify::export] - pub fn transfer_better( - origin: T::RuntimeOrigin, - dest: T::AccountId, - amount: Balance, - ) -> DispatchResult { - let sender = ensure_signed(origin)?; - - let sender_balance = Balances::::get(&sender).ok_or("NonExistentAccount")?; - ensure!(sender_balance >= amount, "NotEnoughBalance"); - let reminder = sender_balance - amount; - - // .. snip - Ok(()) - } - - #[docify::export] - /// Transfer `amount` from `origin` to `dest`. - pub fn transfer_better_checked( - origin: T::RuntimeOrigin, - dest: T::AccountId, - amount: Balance, - ) -> DispatchResult { - let sender = ensure_signed(origin)?; - - let sender_balance = Balances::::get(&sender).ok_or("NonExistentAccount")?; - let reminder = sender_balance.checked_sub(amount).ok_or("NotEnoughBalance")?; - - // .. snip - Ok(()) - } - } -} diff --git a/docs/sdk/src/guides/your_first_runtime.rs b/docs/sdk/src/guides/your_first_runtime.rs deleted file mode 100644 index 3e02ef1b1b2..00000000000 --- a/docs/sdk/src/guides/your_first_runtime.rs +++ /dev/null @@ -1 +0,0 @@ -//! # Your first Runtime diff --git a/docs/sdk/src/lib.rs b/docs/sdk/src/lib.rs deleted file mode 100644 index b0abb50b52d..00000000000 --- a/docs/sdk/src/lib.rs +++ /dev/null @@ -1,43 +0,0 @@ -//! # Polkadot SDK Docs -//! -//! The Polkadot SDK Developer Documentation. -//! -//! This crate is a *minimal*, but *always-accurate* source of information for those wishing to -//! build on the Polkadot SDK. -//! -//! > **Work in Progress**: This crate is under heavy development. Expect content to be moved and -//! > changed. Do not use links to this crate yet. See [`meta_contributing`] for more information. -//! -//! ## Getting Started -//! -//! We suggest the following reading sequence: -//! -//! - Start by learning about the the [`polkadot_sdk`], its structure and context. -//! - Then, head over the [`guides`]. This modules contains in-depth guides about the most important -//! user-journeys of the Polkadot SDK. -//! - Whilst reading the guides, you might find back-links to [`crate::reference_docs`]. -//! - Finally, is the parent website of this crate that contains the -//! list of further tools related to the Polkadot SDK. -//! -//! ## Information Architecture -//! -//! This section paints a picture over the high-level information architecture of this crate. -#![doc = simple_mermaid::mermaid!("../../mermaid/IA.mmd")] -#![allow(rustdoc::invalid_html_tags)] // TODO: remove later. https://github.com/paritytech/polkadot-sdk-docs/issues/65 -#![allow(rustdoc::bare_urls)] // TODO: remove later. https://github.com/paritytech/polkadot-sdk-docs/issues/65 -#![warn(rustdoc::broken_intra_doc_links)] -#![warn(rustdoc::private_intra_doc_links)] - -/// Meta information about this crate, how it is built, what principles dictates its evolution and -/// how one can contribute to it. -pub mod meta_contributing; - -/// In-depth guides about the most common components of the Polkadot SDK. They are slightly more -/// high level and broad than reference docs. -pub mod guides; -/// An introduction to the Polkadot SDK. Read this module to learn about the structure of the SDK, -/// the tools that are provided as a part of it, and to gain a high level understanding of each. -pub mod polkadot_sdk; -/// Reference documents covering in-depth topics across the Polkadot SDK. It is suggested to read -/// these on-demand, while you are going through the [`guides`] or other content. -pub mod reference_docs; diff --git a/docs/sdk/src/meta_contributing.rs b/docs/sdk/src/meta_contributing.rs deleted file mode 100644 index 0d3ecea4655..00000000000 --- a/docs/sdk/src/meta_contributing.rs +++ /dev/null @@ -1,146 +0,0 @@ -//! # Contribution -//! -//! The following sections cover more detailed information about this crate and how it should be -//! maintained. -//! -//! ## Why Rust Docs? -//! -//! We acknowledge that blockchain based systems, particularly a cutting-edge one like Polkadot SDK -//! is a software artifact that is complex, and rapidly evolving. This makes the task of documenting -//! it externally extremely difficult, especially with regards to making sure it is up-to-date. -//! -//! Consequently, we argue that the best hedge against this is to move as much of the documentation -//! near the source code as possible. This would further incentivize developers to keep the -//! documentation up-to-date, as the overhead is reduced by making sure everything is in one -//! repository, and everything being in `.rs` files. -//! -//! > This is not say that a more visually appealing version of this crate (for example as an -//! > `md-book`) cannot exist, but it would be outside the scope of this crate. -//! -//! Moreover, we acknowledge that a major pain point has been not only outdated *concepts*, but also -//! *outdated code*. For this, we commit to making sure no code-snippet in this crate is left as -//! `///ignore` or `///no_compile`, making sure all code snippets are self-contained, compile-able, -//! and correct at every single revision of the entire repository. -//! -//! > This also allows us to have a clear versioning on the entire content of this crate. For every -//! commit of the Polkadot SDK, there would be one version of this crate that is guaranteed to be -//! correct. -//! -//! > To achieve this, we often use [`docify`](https://github.com/sam0x17/docify), a nifty invention -//! > of `@sam0x17`. -//! -//! Also see: . -//! -//! ## Scope -//! -//! The above would NOT be attainable if we don't acknowledge that the scope of this crate MUST be -//! limited, or else its maintenance burden would be infeasible or not worthwhile. In short, future -//! maintainers should always strive to keep the content of this repository as minimal as possible. -//! Some of the following principles are specifically there to be the guidance for this. -//! -//! ## Principles -//! -//! The following guidelines are meant to be the guiding torch of those who contribute to this -//! crate. -//! -//! 1. 🔺 Ground Up: Information should be layed out in the most ground-up fashion. The lowest level -//! (i.e. "ground") is Rust-docs. The highest level (i.e. "up") is "outside of this crate". In -//! between lies [`reference_docs`] and [`guides`], from low to high. The point of this principle -//! is to document as much of the information as possible in the lower level media, as it is -//! easier to maintain and more reachable. Then, use excessive linking to back-link when writing -//! in a more high level. -//! -//! > A prime example of this, the details of the FRAME storage APIs should NOT be explained in a -//! > high level tutorial. They should be explained in the rust-doc of the corresponding type or -//! > macro. -//! -//! 2. 🧘 Less is More: For reasons mentioned [above](#crate::why-rust-docs), the more concise this -//! crate is, the better. -//! 3. √ Don’t Repeat Yourself – DRY: A summary of the above two points. Authors should always -//! strive to avoid any duplicate information. Every concept should ideally be documented in -//! *ONE* place and one place only. This makes the task of maintaining topics significantly -//! easier. -//! -//! > A prime example of this, the list of CLI arguments of a particular binary should not be -//! > documented in multiple places across this crate. It should be only be documented in the -//! > corresponding crate (e.g. `sc_cli`). -//! -//! > Moreover, this means that as a contributor, **it is your responsibility to have a grasp over -//! > what topics are already covered in this crate, and how you can build on top of the information -//! > that they already pose, rather than repeating yourself**. -//! -//! For more details about documenting guidelines, see: -//! -//! -//! #### Example: Explaining `#[pallet::call]` -//! -//!
-//! -//! Let's consider the seemingly simple example of explaining to someone dead-simple code of a FRAME -//! call and see how we can use the above principles. -//! -//! -//! -//! ``` -//! #[frame::pallet(dev_mode)] -//! pub mod pallet { -//! # use frame::prelude::*; -//! # #[pallet::config] -//! # pub trait Config: frame_system::Config {} -//! # #[pallet::pallet] -//! # pub struct Pallet(_); -//! #[pallet::call] -//! impl Pallet { -//! pub fn a_simple_call(origin: OriginFor, data: u32) -> DispatchResult { -//! ensure!(data > 10, "SomeStaticString"); -//! todo!(); -//! } -//! } -//! } -//! ``` -//! -//! * Before even getting started, what is with all of this ``? We link to -//! [`crate::reference_docs::trait_based_programming`]. -//! * First, the name. Why is this called `pallet::call`? This goes back to `enum Call`, which is -//! explained in [`crate::reference_docs::frame_composite_enums`]. Build on top of this! -//! * Then, what is `origin`? Just an account id? [`crate::reference_docs::frame_origin`]. -//! * Then, what is `DispatchResult`? Why is this called *dispatch*? Probably something that can be -//! explained in the documentation of [`frame::prelude::DispatchResult`]. -//! * Why is `"SomeStaticString"` a valid error? Because there is implementation for it that you can -//! see [here](frame::prelude::DispatchError#impl-From<%26'static+str>-for-DispatchError). -//! -//! -//! All of these are examples of underlying information that a contributor should: -//! -//! 1. Try and create and they are going along. -//! 2. Back-link to if they already exist. -//! -//! Of course, all of this is not set in stone as a either/or rule. Sometimes, it is necessary to -//! rephrase a concept in a new context. -//! -//!
-//! -//! ## `docs.substrate.io` -//! -//! This crate is meant to gradually replace `docs.substrate.io`. As any content is added here, the -//! corresponding counter-part should be marked as deprecated, as described -//! [here](https://github.com/paritytech/polkadot-sdk-docs/issues/26). -//! -//! ## `crates.io` and Publishing -//! -//! As it stands now, this crate cannot be published to crates.io because of its use of -//! [workspace-level `docify`](https://github.com/sam0x17/docify/issues/22). For now, we accept this -//! compromise, but in the long term, we should work towards finding a way to maintain different -//! revisions of this crate. -//! -//! ## How to Build -//! -//! To build this crate properly, with with right HTML headers injected, run: -//! -//! ```no_compile -//! RUSTDOCFLAGS="--html-in-header $(pwd)/docs/sdk/headers/toc.html" cargo doc -p polkadot-sdk-docs -//! ``` -//! -//! adding `--no-deps` would speed up the process while development. If even faster build time for -//! docs is needed, you can temporarily remove most of the substrate/cumulus dependencies that are -//! only used for linking purposes. diff --git a/docs/sdk/src/polkadot_sdk/cumulus.rs b/docs/sdk/src/polkadot_sdk/cumulus.rs deleted file mode 100644 index 07a48c92d80..00000000000 --- a/docs/sdk/src/polkadot_sdk/cumulus.rs +++ /dev/null @@ -1,130 +0,0 @@ -//! # Cumulus -//! -//! Substrate provides a framework ([FRAME]) through which a blockchain node and runtime can easily -//! be created. Cumulus aims to extend the same approach to creation of Polkadot parachains. -//! -//! > Cumulus clouds are shaped sort of like dots; together they form a system that is intricate, -//! > beautiful and functional. -//! -//! ## Example: Runtime -//! -//! A Cumulus-based runtime is fairly similar to other [FRAME]-based runtimes. Most notably, the -//! following changes are applied to a normal FRAME-based runtime to make it a Cumulus-based -//! runtime: -//! -//! #### Cumulus Pallets -//! -//! A parachain runtime should use a number of pallets that are provided by Cumulus and Substrate. -//! Notably: -//! -//! - [`frame-system`](frame::prelude::frame_system), like all FRAME-based runtimes. -//! - [`cumulus_pallet_parachain_system`] -//! - [`parachain_info`] -#![doc = docify::embed!("./src/polkadot_sdk/cumulus.rs", system_pallets)] -//! -//! Given that all Cumulus-based runtimes use a simple Aura-based consensus mechanism, the following -//! pallets also need to be added: -//! -//! - [`pallet_timestamp`] -//! - [`pallet_aura`] -//! - [`cumulus_pallet_aura_ext`] -#![doc = docify::embed!("./src/polkadot_sdk/cumulus.rs", consensus_pallets)] -//! -//! -//! Finally, a separate macro, similar to -//! [`impl_runtime_api`](frame::runtime::prelude::impl_runtime_apis), which creates the default set -//! of runtime APIs, will generate the parachain runtime's validation runtime API, also known as -//! parachain validation function (PVF). Without this API, the relay chain is unable to validate -//! blocks produced by our parachain. -#![doc = docify::embed!("./src/polkadot_sdk/cumulus.rs", validate_block)] -//! -//! --- -//! -//! [FRAME]: crate::polkadot_sdk::frame_runtime - -#![deny(rustdoc::broken_intra_doc_links)] -#![deny(rustdoc::private_intra_doc_links)] - -#[cfg(test)] -mod tests { - mod runtime { - pub use frame::{ - deps::sp_consensus_aura::sr25519::AuthorityId as AuraId, prelude::*, - runtime::prelude::*, testing_prelude::*, - }; - - #[docify::export(CR)] - construct_runtime!( - pub struct Runtime { - // system-level pallets. - System: frame_system, - Timestamp: pallet_timestamp, - ParachainSystem: cumulus_pallet_parachain_system, - ParachainInfo: parachain_info, - - // parachain consensus support -- mandatory. - Aura: pallet_aura, - AuraExt: cumulus_pallet_aura_ext, - } - ); - - #[docify::export] - mod system_pallets { - use super::*; - - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] - impl frame_system::Config for Runtime { - type Block = MockBlock; - type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; - } - - impl cumulus_pallet_parachain_system::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type OnSystemEvent = (); - type SelfParaId = parachain_info::Pallet; - type OutboundXcmpMessageSource = (); - type XcmpMessageHandler = (); - type ReservedDmpWeight = (); - type ReservedXcmpWeight = (); - type CheckAssociatedRelayNumber = - cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; - type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook< - Runtime, - 6000, // relay chain block time - 1, - 1, - >; - type WeightInfo = (); - type DmpQueue = frame::traits::EnqueueWithOrigin<(), sp_core::ConstU8<0>>; - } - - impl parachain_info::Config for Runtime {} - } - - #[docify::export] - mod consensus_pallets { - use super::*; - - impl pallet_aura::Config for Runtime { - type AuthorityId = AuraId; - type DisabledValidators = (); - type MaxAuthorities = ConstU32<100_000>; - type AllowMultipleBlocksPerSlot = ConstBool; - #[cfg(feature = "experimental")] - type SlotDuration = pallet_aura::MinimumPeriodTimesTwo; - } - - #[docify::export(timestamp)] - #[derive_impl(pallet_timestamp::config_preludes::TestDefaultConfig as pallet_timestamp::DefaultConfig)] - impl pallet_timestamp::Config for Runtime {} - - impl cumulus_pallet_aura_ext::Config for Runtime {} - } - - #[docify::export(validate_block)] - cumulus_pallet_parachain_system::register_validate_block! { - Runtime = Runtime, - BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, - } - } -} diff --git a/docs/sdk/src/polkadot_sdk/frame_runtime.rs b/docs/sdk/src/polkadot_sdk/frame_runtime.rs deleted file mode 100644 index 32dc2045e3a..00000000000 --- a/docs/sdk/src/polkadot_sdk/frame_runtime.rs +++ /dev/null @@ -1,179 +0,0 @@ -//! # FRAME -//! -//! ```no_compile -//! ______ ______ ________ ___ __ __ ______ -//! /_____/\ /_____/\ /_______/\ /__//_//_/\ /_____/\ -//! \::::_\/_\:::_ \ \ \::: _ \ \\::\| \| \ \\::::_\/_ -//! \:\/___/\\:(_) ) )_\::(_) \ \\:. \ \\:\/___/\ -//! \:::._\/ \: __ `\ \\:: __ \ \\:.\-/\ \ \\::___\/_ -//! \:\ \ \ \ `\ \ \\:.\ \ \ \\. \ \ \ \\:\____/\ -//! \_\/ \_\/ \_\/ \__\/\__\/ \__\/ \__\/ \_____\/ -//! ``` -//! -//! > **F**ramework for **R**untime **A**ggregation of **M**odularized **E**ntities: Substrate's -//! > State Transition Function (Runtime) Framework. -//! -//! ## Introduction -//! -//! As described in [`crate::reference_docs::wasm_meta_protocol`], at a high-level Substrate-based -//! blockchains are composed of two parts: -//! -//! 1. A *runtime* which represents the state transition function (i.e. "Business Logic") of a -//! blockchain, and is encoded as a WASM blob. -//! 2. A node whose primary purpose is to execute the given runtime. -#![doc = simple_mermaid::mermaid!("../../../mermaid/substrate_simple.mmd")] -//! -//! *FRAME is the Substrate's framework of choice to build a runtime.* -//! -//! FRAME is composed of two major components, **pallets** and a **runtime**. -//! -//! ## Pallets -//! -//! A pallet is a unit of encapsulated logic. It has a clearly defined responsibility and can be -//! linked to other pallets. In order to be reusable, pallets shipped with FRAME strive to only care -//! about its own responsibilities and make as few assumptions about the general runtime as -//! possible. A pallet is analogous to a _module_ in the runtime. -//! -//! A pallet is defined as a `mod pallet` wrapped by the [`frame::pallet`] macro. Within this macro, -//! pallet components/parts can be defined. Most notable of these parts are: -//! -//! - [Config](frame::pallet_macros::config), allowing a pallet to make itself configurable and -//! generic over types, values and such. -//! - [Storage](frame::pallet_macros::storage), allowing a pallet to define onchain storage. -//! - [Dispatchable function](frame::pallet_macros::call), allowing a pallet to define extrinsics -//! that are callable by end users, from the outer world. -//! - [Events](frame::pallet_macros::event), allowing a pallet to emit events. -//! - [Errors](frame::pallet_macros::error), allowing a pallet to emit well-formed errors. -//! -//! Some of these pallet components resemble the building blocks of a smart contract. While both -//! models are programming state transition functions of blockchains, there are crucial differences -//! between the two. See [`crate::reference_docs::runtime_vs_smart_contract`] for more. -//! -//! Most of these components are defined using macros, the full list of which can be found in -//! [`frame::pallet_macros`]. -//! -//! ### Example -//! -//! The following examples showcases a minimal pallet. -#![doc = docify::embed!("src/polkadot_sdk/frame_runtime.rs", pallet)] -//! -//! -//! A runtime is a collection of pallets that are amalgamated together. Each pallet typically has -//! some configurations (exposed as a `trait Config`) that needs to be *specified* in the runtime. -//! This is done with [`frame::runtime::prelude::construct_runtime`]. -//! -//! A (real) runtime that actually wishes to compile to WASM needs to also implement a set of -//! runtime-apis. These implementation can be specified using the -//! [`frame::runtime::prelude::impl_runtime_apis`] macro. -//! -//! ### Example -//! -//! The following example shows a (test) runtime that is composing the pallet demonstrated above, -//! next to the [`frame::prelude::frame_system`] pallet, into a runtime. -#![doc = docify::embed!("src/polkadot_sdk/frame_runtime.rs", runtime)] -//! -//! ## More Examples -//! -//! You can find more FRAME examples that revolve around specific features at [`pallet_examples`]. -//! -//! ## Alternatives 🌈 -//! -//! There is nothing in the Substrate's node side code-base that mandates the use of FRAME. While -//! FRAME makes it very simple to write Substrate-based runtimes, it is by no means intended to be -//! the only one. At the end of the day, any WASM blob that exposes the right set of runtime APIs is -//! a valid Runtime form the point of view of a Substrate client (see -//! [`crate::reference_docs::wasm_meta_protocol`]). Notable examples are: -//! -//! * writing a runtime in pure Rust, as done in [this template](https://github.com/JoshOrndorff/frameless-node-template). -//! * writing a runtime in AssemblyScript,as explored in [this project](https://github.com/LimeChain/subsembly). - -#[cfg(test)] -mod tests { - use frame::prelude::*; - - /// A FRAME based pallet. This `mod` is the entry point for everything else. All - /// `#[pallet::xxx]` macros must be defined in this `mod`. Although, frame also provides an - /// experimental feature to break these parts into different `mod`s. See [`pallet_examples`] for - /// more. - #[docify::export] - #[frame::pallet(dev_mode)] - pub mod pallet { - use super::*; - - /// The configuration trait of a pallet. Mandatory. Allows a pallet to receive types at a - /// later point from the runtime that wishes to contain it. It allows the pallet to be - /// parameterized over both types and values. - #[pallet::config] - pub trait Config: frame_system::Config { - /// A type that is not known now, but the runtime that will contain this pallet will - /// know it later, therefore we define it here as an associated type. - type RuntimeEvent: IsType<::RuntimeEvent> - + From>; - - /// A parameterize-able value that we receive later via the `Get<_>` trait. - type ValueParameter: Get; - - /// Similar to [`Config::ValueParameter`], but using `const`. Both are functionally - /// equal, but offer different tradeoffs. - const ANOTHER_VALUE_PARAMETER: u32; - } - - /// A mandatory struct in each pallet. All functions callable by external users (aka. - /// transactions) must be attached to this type (see [`frame::pallet_macros::call`]). For - /// convenience, internal (private) functions can also be attached to this type. - #[pallet::pallet] - pub struct Pallet(PhantomData); - - /// The events tha this pallet can emit. - #[pallet::event] - pub enum Event {} - - /// A storage item that this pallet contains. This will be part of the state root trie/root - /// of the blockchain. - #[pallet::storage] - pub type Value = StorageValue; - - /// All *dispatchable* call functions (aka. transactions) are attached to `Pallet` in a - /// `impl` block. - #[pallet::call] - impl Pallet { - /// This will be callable by external users, and has two u32s as a parameter. - pub fn some_dispatchable( - _origin: OriginFor, - _param: u32, - _other_para: u32, - ) -> DispatchResult { - Ok(()) - } - } - } - - /// A simple runtime that contains the above pallet and `frame_system`, the mandatory pallet of - /// all runtimes. This runtime is for testing, but it shares a lot of similarities with a *real* - /// runtime. - #[docify::export] - pub mod runtime { - use super::pallet as pallet_example; - use frame::{prelude::*, testing_prelude::*}; - - // The major macro that amalgamates pallets into `struct Runtime` - construct_runtime!( - pub struct Runtime { - System: frame_system, - Example: pallet_example, - } - ); - - // These `impl` blocks specify the parameters of each pallet's `trait Config`. - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] - impl frame_system::Config for Runtime { - type Block = MockBlock; - } - - impl pallet_example::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type ValueParameter = ConstU32<42>; - const ANOTHER_VALUE_PARAMETER: u32 = 42; - } - } -} diff --git a/docs/sdk/src/polkadot_sdk/mod.rs b/docs/sdk/src/polkadot_sdk/mod.rs deleted file mode 100644 index 124d391421b..00000000000 --- a/docs/sdk/src/polkadot_sdk/mod.rs +++ /dev/null @@ -1,134 +0,0 @@ -//! # Polkadot SDK -//! -//! [Polkadot SDK](https://github.com/paritytech/polkadot-sdk) provides the main resources needed to -//! start building on the [Polkadot network](https://polkadot.network), a scalable, multi-chain -//! blockchain platform that enables different blockchains to securely interoperate. -//! -//! [![StackExchange](https://img.shields.io/badge/StackExchange-Polkadot%20and%20Substrate-222222?logo=stackexchange)](https://substrate.stackexchange.com/) -//! -//! [![awesomeDot](https://img.shields.io/badge/polkadot-awesome-e6007a?logo=polkadot)](https://github.com/Awsmdot/awesome-dot) -//! [![wiki](https://img.shields.io/badge/polkadot-wiki-e6007a?logo=polkadot)](https://wiki.polkadot.network/) -//! [![forum](https://img.shields.io/badge/polkadot-forum-e6007a?logo=polkadot)](https://forum.polkadot.network/) -//! -//! [![RFCs](https://img.shields.io/badge/fellowship-RFCs-e6007a?logo=polkadot)](https://github.com/polkadot-fellows/rfcs) -//! [![Runtime](https://img.shields.io/badge/fellowship-runtimes-e6007a?logo=polkadot)](https://github.com/polkadot-fellows/runtimes) -//! [![Manifesto](https://img.shields.io/badge/fellowship-manifesto-e6007a?logo=polkadot)](https://github.com/polkadot-fellows/manifesto) -//! -//! ## Getting Started -//! -//! The primary way to get started with the Polkadot SDK is to start writing a FRAME-based runtime. -//! See: -//! -//! * [`polkadot`], to understand what is Polkadot as a development platform. -//! * [`substrate`], for an overview of what Substrate as the main blockchain framework of Polkadot -//! SDK. -//! * [`frame`], to learn about how to write blockchain applications aka. "App Chains". -//! * Continue with the [`polkadot_sdk_docs`'s "getting started"](crate#getting-started). -//! -//! ## Components -//! -//! #### Substrate -//! -//! [![Substrate-license](https://img.shields.io/badge/License-GPL3%2FApache2.0-blue)](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/LICENSE-APACHE2) -//! [![GitHub -//! Repo](https://img.shields.io/badge/github-substrate-2324CC85)](https://github.com/paritytech/polkadot-sdk/blob/master/substrate) -//! -//! [`substrate`] is the base blockchain framework used to power the Polkadot SDK. It is a full -//! toolkit to create sovereign blockchains, including but not limited to those who connect to -//! Polkadot as parachains. -//! -//! #### FRAME -//! -//! [![Substrate-license](https://img.shields.io/badge/License-Apache2.0-blue)](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/LICENSE-APACHE2) -//! [![GitHub -//! Repo](https://img.shields.io/badge/github-frame-2324CC85)](https://github.com/paritytech/polkadot-sdk/blob/master/substrate/frame) -//! -//! [`frame`] is the framework used to create Substrate-based application logic, aka. runtimes. -//! Learn more about the distinction of a runtime and node in -//! [`reference_docs::wasm_meta_protocol`]. -//! -//! #### Cumulus -//! -//! [![Cumulus-license](https://img.shields.io/badge/License-GPL3-blue)](https://github.com/paritytech/polkadot-sdk/blob/master/cumulus/LICENSE) -//! [![GitHub -//! Repo](https://img.shields.io/badge/github-cumulus-white)](https://github.com/paritytech/polkadot-sdk/blob/master/cumulus) -//! -//! [`cumulus`] transforms FRAME-based runtimes into Polkadot-compatible parachain runtimes, and -//! Substrate-based nodes into Polkadot/Parachain-compatible nodes. -//! -//! #### XCM -//! -//! [![XCM-license](https://img.shields.io/badge/License-GPL3-blue)](https://github.com/paritytech/polkadot-sdk/blob/master/polkadot/LICENSE) -//! [![GitHub -//! Repo](https://img.shields.io/badge/github-XCM-e6007a?logo=polkadot)](https://github.com/paritytech/polkadot-sdk/blob/master/polkadot/xcm) -//! -//! [`xcm`], short for "cross consensus message", is the primary format that is used for -//! communication between parachains, but is intended to be extensible to other use cases as well. -//! -//! #### Polkadot -//! -//! [![Polkadot-license](https://img.shields.io/badge/License-GPL3-blue)](https://github.com/paritytech/polkadot-sdk/blob/master/polkadot/LICENSE) -//! [![GitHub -//! Repo](https://img.shields.io/badge/github-polkadot-e6007a?logo=polkadot)](https://github.com/paritytech/polkadot-sdk/blob/master/polkadot) -//! -//! [`polkadot`] is an implementation of a Polkadot node in Rust, by `@paritytech`. The Polkadot -//! runtimes are located under the -//! [`polkadot-fellows/runtimes`](https://github.com/polkadot-fellows/runtimes) repository. -//! -//! ### Summary -//! -//! The following diagram summarizes how some of the components of Polkadot SDK work together: -#![doc = simple_mermaid::mermaid!("../../../mermaid/polkadot_sdk_substrate.mmd")] -//! -//! A Substrate-based chain is a blockchain composed of a runtime and a node. As noted above, the -//! runtime is the application logic of the blockchain, and the node is everything else. -//! See [`crate::reference_docs::wasm_meta_protocol`] for an in-depth explanation of this. The -//! former is built with [`frame`], and the latter is built with rest of Substrate. -//! -//! > You can think of a Substrate-based chain as a white-labeled blockchain. -#![doc = simple_mermaid::mermaid!("../../../mermaid/polkadot_sdk_polkadot.mmd")] -//! Polkadot is itself a Substrate-based chain, composed of the exact same two components. It has -//! specialized logic in both the node and the runtime side, but it is not "special" in any way. -//! -//! A parachain is a "special" Substrate-based chain, whereby both the node and the runtime -//! components have became "Polkadot-aware" using Cumulus. -#![doc = simple_mermaid::mermaid!("../../../mermaid/polkadot_sdk_parachain.mmd")] -//! -//! ## Notable Upstream Crates -//! -//! - [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec) -//! - [`parity-db`](https://github.com/paritytech/parity-db) -//! - [`trie`](https://github.com/paritytech/trie) -//! - [`parity-common`](https://github.com/paritytech/parity-common) -//! -//! ## Trophy Section: Notable Downstream Projects -//! -//! A list of projects and tools in the blockchain ecosystem that one way or another parts of the -//! Polkadot SDK: -//! -//! * [Polygon's spin-off, Avail](https://github.com/availproject/avail) -//! * [Cardano Partner Chains](https://iohk.io/en/blog/posts/2023/11/03/partner-chains-are-coming-to-cardano/) -//! * [Starknet's Madara Sequencer](https://github.com/keep-starknet-strange/madara) -//! -//! [`substrate`]: crate::polkadot_sdk::substrate -//! [`frame`]: crate::polkadot_sdk::frame_runtime -//! [`cumulus`]: crate::polkadot_sdk::cumulus -//! [`polkadot`]: crate::polkadot_sdk::polkadot -//! [`xcm`]: crate::polkadot_sdk::xcm - -/// Lean about Cumulus, the framework that transforms [`substrate`]-based chains into -/// [`polkadot`]-enabled parachains. -pub mod cumulus; -/// Learn about FRAME, the framework used to build Substrate runtimes. -pub mod frame_runtime; -/// Learn about Polkadot as a platform. -pub mod polkadot; -/// Learn about different ways through which smart contracts can be utilized on top of Substrate, -/// and in the Polkadot ecosystem. -pub mod smart_contracts; -/// Learn about Substrate, the main blockchain framework used in the Polkadot ecosystem. -pub mod substrate; -/// Index of all the templates that can act as first scaffold for a new project. -pub mod templates; -/// Learn about XCM, the de-facto communication language between different consensus systems. -pub mod xcm; diff --git a/docs/sdk/src/polkadot_sdk/polkadot.rs b/docs/sdk/src/polkadot_sdk/polkadot.rs deleted file mode 100644 index d157a660e56..00000000000 --- a/docs/sdk/src/polkadot_sdk/polkadot.rs +++ /dev/null @@ -1,87 +0,0 @@ -//! # Polkadot -//! -//! Implementation of the Polkadot node/host in Rust. -//! -//! ## Learn More and Get Involved -//! -//! - [Polkadot Forum](https://forum.polkadot.network/) -//! - [Polkadot Parachains](https://parachains.info/) -//! - [Polkadot (multi-chain) Explorer](https://subscan.io/) -//! - Polkadot Fellowship -//! - [Manifesto](https://github.com/polkadot-fellows/manifesto) -//! - [Runtimes](https://github.com/polkadot-fellows/runtimes) -//! - [RFCs](https://github.com/polkadot-fellows/rfcs) -//! - [Polkadot Specs](spec.polkadot.network) -//! - [The Polkadot Parachain Host Implementers' Guide](https://paritytech.github.io/polkadot-sdk/book/) -//! - [Whitepaper](https://www.polkadot.network/whitepaper/) -//! -//! ## Alternative Node Implementations 🌈 -//! -//! - [Smoldot](https://crates.io/crates/smoldot-light). Polkadot light node/client. -//! - [KAGOME](https://github.com/qdrvm/kagome). C++ implementation of the Polkadot host. -//! - [Gossamer](https://github.com/ChainSafe/gossamer). Golang implementation of the Polkadot host. -//! -//! ## Platform -//! -//! In this section, we examine what what platform Polkadot exactly provides to developers. -//! -//! ### Polkadot White Paper -//! -//! The original vision of Polkadot (everything in the whitepaper, which was eventually called -//! **Polkadot 1.0**) revolves around the following arguments: -//! -//! * Future is multi-chain, because we need different chains with different specialization to -//! achieve widespread goals. -//! * In other words, no single chain is good enough to achieve all goals. -//! * A multi-chain future will inadvertently suffer from fragmentation of economic security. -//! * This stake fragmentation will make communication over consensus system with varying security -//! levels inherently unsafe. -//! -//! Polkadot's answer to the above is: -//! -//! > The chains of the future must have a way to share their economic security, whilst maintaining -//! > their execution and governance sovereignty. These chains are called "Parachains". -//! -//! * Shared Security: The idea of shared economic security sits at the core of Polkadot. Polkadot -//! enables different parachains* to pool their economic security from Polkadot (i.e. "*Relay -//! Chain*"). -//! * (heterogenous) Sharded Execution: Yet, each parachain is free to have its own execution logic -//! (runtime), which also encompasses governance and sovereignty. Moreover, Polkadot ensures the -//! correct execution of all parachain, without having all of its validators re-execute all -//! parachain blocks. When seen from this perspective, the fact that Polkadot executes different -//! parachains means it is a platform that has fully delivered (the holy grail of) "Full Execution -//! Sharding". TODO: link to approval checking article. https://github.com/paritytech/polkadot-sdk-docs/issues/66 -//! * A framework to build blockchains: In order to materialize the ecosystem of parachains, an easy -//! blockchain framework must exist. This is [Substrate](crate::polkadot_sdk::substrate), -//! [FRAME](crate::polkadot_sdk::frame_runtime) and [Cumulus](crate::polkadot_sdk::cumulus). -//! * A communication language between blockchains: In order for these blockchains to communicate, -//! they need a shared language. [XCM](crate::polkadot_sdk::xcm) is one such language, and the one -//! that is most endorsed in the Polkadot ecosystem. -//! -//! > Note that the interoperability promised by Polkadot is unparalleled in that any two parachains -//! > connected to Polkadot have the same security and can have much better guarantees about the -//! > security of the recipient of any message. TODO: weakest link in bridges systems. https://github.com/paritytech/polkadot-sdk-docs/issues/66 -//! -//! Polkadot delivers the above vision, alongside a flexible means for parachains to schedule -//! themselves with the Relay Chain. To achieve this, Polkadot has been developed with an -//! architecture similar to that of a computer. Polkadot Relay Chain has a number of "cores". Each -//! core is (in simple terms) capable of progressing 1 parachain at a time. For example, a parachain -//! can schedule itself on a single core for 5 relay chain blocks. -//! -//! Within the scope of Polkadot 1.x, two main scheduling ways have been considered: -//! -//! * Long term Parachains, obtained through locking a sum of DOT in an auction system. -//! * on-demand Parachains, purchased through paying DOT to the relay-chain whenever needed. -//! -//! ### The Future -//! -//! After delivering Polkadot 1.x, the future of Polkadot as a protocol and platform is in the hands -//! of the community and the fellowship. This is happening most notable through the RFC process. -//! Some of the RFCs that do alter Polkadot as a platform and have already passed are as follows: -//! -//! - RFC#1: [Agile-coretime](https://github.com/polkadot-fellows/RFCs/blob/main/text/0001-agile-coretime.md): -//! Agile periodic-sale-based model for assigning Coretime on the Polkadot Ubiquitous Computer. -//! - RFC#5: [Coretime-interface](https://github.com/polkadot-fellows/RFCs/blob/main/text/0005-coretime-interface.md): -//! Interface for manipulating the usage of cores on the Polkadot Ubiquitous Computer. -// TODO: add more context and explanations about Polkadot as the Ubiquitous Computer and related -// tech. https://github.com/paritytech/polkadot-sdk-docs/issues/66 diff --git a/docs/sdk/src/polkadot_sdk/smart_contracts.rs b/docs/sdk/src/polkadot_sdk/smart_contracts.rs deleted file mode 100644 index a4916f9c921..00000000000 --- a/docs/sdk/src/polkadot_sdk/smart_contracts.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! # Smart Contracts -//! -//! TODO: @cmichi https://github.com/paritytech/polkadot-sdk-docs/issues/56 -//! -//! - WASM and EVM based, pallet-contracts and pallet-evm. -//! - single-daap-chain, transition from ink! to FRAME. -//! - Link to `use.ink` -//! - Link to [`crate::reference_docs::runtime_vs_smart_contract`]. -//! - https://use.ink/migrate-ink-contracts-to-polkadot-frame-parachain/ diff --git a/docs/sdk/src/polkadot_sdk/substrate.rs b/docs/sdk/src/polkadot_sdk/substrate.rs deleted file mode 100644 index fd172f71469..00000000000 --- a/docs/sdk/src/polkadot_sdk/substrate.rs +++ /dev/null @@ -1,151 +0,0 @@ -//! # Substrate -//! -//! Substrate is a Rust framework for building blockchains in a modular and extensible way. While in -//! itself un-opinionated, it is the main engine behind the Polkadot ecosystem. -//! -//! ## Overview, Philosophy -//! -//! Substrate approaches blockchain development with an acknowledgement of a few self-evident -//! truths: -//! -//! 1. Society and technology evolves. -//! 2. Humans are fallible. -//! -//! This, makes the task of designing a correct, safe and long-lasting blockchain system hard. -//! -//! Nonetheless, in strive towards achieve this goal, Substrate embraces the following: -//! -//! 1. Use of **Rust** as a modern and safe programming language, which limits human error through -//! various means, most notably memory and type safety. -//! 2. Substrate is written from the ground-up with a *generic, modular and extensible* design. This -//! ensures that software components can be easily swapped and upgraded. Examples of this is -//! multiple consensus mechanisms provided by Substrate, as listed below. -//! 3. Lastly, the final blockchain system created with the above properties needs to be -//! upgradeable. In order to achieve this, Substrate is designed as a meta-protocol, whereby the -//! application logic of the blockchain (called "Runtime") is encoded as a WASM blob, and is -//! stored in the state. The rest of the system (called "node") acts as the executor of the WASM -//! blob. -//! -//! In essence, the meta-protocol of all Substrate based chains is the "Runtime as WASM blob" -//! accord. This enables the Runtime to become inherently upgradeable, crucially without forks. The -//! upgrade is merely a matter of the WASM blob being changed in the state, which is, in principle, -//! same as updating an account's balance. Learn more about this in detail in -//! [`crate::reference_docs::wasm_meta_protocol`]. -//! -//! > A great analogy for substrate is the following: Substrate node is a gaming console, and a WASM -//! > runtime, possibly created with FRAME is the game being inserted into the console. -//! -//! [`frame`], Substrate's default runtime development library, takes the above safety practices -//! even further by embracing a declarative programming model whereby correctness is enhanced and -//! the system is highly configurable through parameterization. Learn more about this in -//! [`crate::reference_docs::trait_based_programming`]. -//! -//! ## How to Get Started -//! -//! Substrate offers different options at the spectrum of technical freedom <-> development ease. -//! -//! * The easiest way to use Substrate is to use one of the templates (some of which listed at -//! [`crate::polkadot_sdk::templates`]) and only tweak the parameters of the runtime or node. This -//! allows you to launch a blockchain in minutes, but is limited in technical freedom. -//! * Next, most developers wish to develop their custom runtime modules, for which the de-facto way -//! is [`frame`](crate::polkadot_sdk::frame_runtime). -//! * Finally, Substrate is highly configurable at the node side as well, but this is the most -//! technically demanding. -//! -//! > A notable Substrate-based blockchain that has built both custom FRAME pallets and custom -//! > node-side components is . -#![doc = simple_mermaid::mermaid!("../../../mermaid/substrate_dev.mmd")] -//! -//! ## Structure -//! -//! Substrate contains a large number of crates, therefore it is useful to have an overview of what -//! they are, and how they are organized. In broad terms, these crates are divided into three -//! categories: -//! -//! * `sc-*` (short for *Substrate-client*) crates, located under `./client` folder. These are all -//! the crates that lead to the node software. Notable examples [`sc_network`], various consensus -//! crates, RPC ([`sc_rpc_api`]) and database ([`sc_client_db`]), all of which are expected to -//! reside in the node side. -//! * `sp-*` (short for *substrate-primitives*) crates, located under `./primitives` folder. These -//! are crates that facilitate both the node and the runtime, but are not opinionated about what -//! framework is using for building the runtime. Notable examples are [`sp_api`] and [`sp_io`], -//! which form the communication bridge between the node and runtime. -//! * `pallet-*` and `frame-*` crates, located under `./frame` folder. These are the crates related -//! to FRAME. See [`frame`] for more information. -//! -//! ### WASM Build -//! -//! Many of the Substrate crates, such as entire `sp-*`, need to compile to both WASM (when a WASM -//! runtime is being generated) and native (for example, when testing). To achieve this, Substrate -//! follows the convention of the Rust community, and uses a `feature = "std"` to signify that a -//! crate is being built with the standard library, and is built for native. Otherwise, it is built -//! for `no_std`. -//! -//! This can be summarized in `#![cfg_attr(not(feature = "std"), no_std)]`, which you can often find -//! in any Substrate-based runtime. -//! -//! Substrate-based runtimes use [`substrate_wasm_builder`] in their `build.rs` to automatically -//! build their WASM files as a part of normal build command (e.g. `cargo build`). Once built, the -//! wasm file is placed in `./target/{debug|release}/wbuild/{runtime_name}.wasm`. -//! -//! ### Binaries -//! -//! Multiple binaries are shipped with substrate, the most important of which are located in the -//! [`./bin`](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/bin) folder. -//! -//! * [`node_cli`] is an extensive substrate node that contains the superset of all runtime and node -//! side features. The corresponding runtime, called [`kitchensink_runtime`] contains all of the -//! modules that are provided with `FRAME`. This node and runtime is only used for testing and -//! demonstration. -//! * [`chain_spec_builder`]: Utility to build more detailed chain-specs for the aforementioned -//! node. Other projects typically contain a `build-spec` subcommand that does the same. -//! * [`node_template`](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/bin/node-template): -//! a template node that contains a minimal set of features and can act as a starting point of a -//! project. -//! * [`subkey`]: Substrate's key management utility. -//! -//! ### Anatomy of a Binary Crate -//! -//! From the above, [`node_cli`]/[`kitchensink_runtime`] and `node-template` are essentially -//! blueprints of a Substrate-based project, as the name of the latter is implying. Each -//! Substrate-based project typically contains the following: -//! -//! * Under `./runtime`, a `./runtime/src/lib.rs` which is the top level runtime amalgamator file. -//! This file typically contains the [`frame::runtime::prelude::construct_runtime`] and -//! [`frame::runtime::prelude::impl_runtime_apis`] macro calls, which is the final definition of a -//! runtime. -//! -//! * Under `./node`, a `main.rs`, which is the starting point, and a `./service.rs`, which contains -//! all the node side components. Skimming this file yields an overview of the networking, -//! database, consensus and similar node side components. -//! -//! > The above two are conventions, not rules. -//! -//! > See for an update on how the node side -//! > components are being amalgamated. -//! -//! ## Parachain? -//! -//! As noted above, Substrate is the main engine behind the Polkadot ecosystem. One of the ways -//! through which Polkadot can be utilized is by building "parachains", blockchains that are -//! connected to Polkadot's shared security. -//! -//! To build a parachain, one could use [Cumulus](crate::polkadot_sdk::cumulus), the library on -//! top of Substrate, empowering any substrate-based chain to be a Polkadot parachain. -//! -//! ## Where To Go Next? -//! -//! Additional noteworthy crates within substrate: -//! -//! - RPC APIs of a Substrate node: [`sc_rpc_api`]/[`sc_rpc`] -//! - CLI Options of a Substrate node: [`sc_cli`] -//! - All of the consensus related crates provided by Substrate: -//! - [`sc_consensus_aura`] -//! - [`sc_consensus_babe`] -//! - [`sc_consensus_grandpa`] -//! - [`sc_consensus_beefy`] (TODO: @adrian, add some high level docs https://github.com/paritytech/polkadot-sdk-docs/issues/57) -//! - [`sc_consensus_manual_seal`] -//! - [`sc_consensus_pow`] - -#[doc(hidden)] -pub use crate::polkadot_sdk; diff --git a/docs/sdk/src/polkadot_sdk/templates.rs b/docs/sdk/src/polkadot_sdk/templates.rs deleted file mode 100644 index f60c75b8f21..00000000000 --- a/docs/sdk/src/polkadot_sdk/templates.rs +++ /dev/null @@ -1,45 +0,0 @@ -//! # Templates -//! -//! ### Internal -//! -//! The following templates are maintained as a part of the `polkadot-sdk` repository: -//! -//! - 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`]. -//! -//! ### External Templates -//! -//! Noteworthy templates outside of this repository. -//! -//! - [`extended-parachain-template`](https://github.com/paritytech/extended-parachain-template): A -//! parachain template that contains more built-in functionality such as assets and NFTs. -//! - [`frontier-parachain-template`](https://github.com/paritytech/frontier-parachain-template): A -//! parachain template for launching EVM-compatible parachains. -//! -//! [`substrate-node-template`]: https://github.com/paritytech/polkadot-sdk/blob/master/substrate/bin/node-template/ -//! [`substrate-minimal-template`]: https://github.com/paritytech/polkadot-sdk/blob/master/substrate/bin/minimal/ -//! [`cumulus-parachain-template`]: https://github.com/paritytech/polkadot-sdk/blob/master/cumulus/parachain-template/ - -// 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. diff --git a/docs/sdk/src/polkadot_sdk/xcm.rs b/docs/sdk/src/polkadot_sdk/xcm.rs deleted file mode 100644 index 0d600f751c8..00000000000 --- a/docs/sdk/src/polkadot_sdk/xcm.rs +++ /dev/null @@ -1,5 +0,0 @@ -//! # XCM -//! -//! @KiChjang @franciscoaguirre -//! TODO: RFCs, xcm-spec, the future of the repo, minimal example perhaps, forward to where actual -//! docs are hosted. https://github.com/paritytech/polkadot-sdk-docs/issues/58 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 e69de29bb2d..00000000000 diff --git a/docs/sdk/src/reference_docs/blockchain_state_machines.rs b/docs/sdk/src/reference_docs/blockchain_state_machines.rs deleted file mode 100644 index 0d1aefcc527..00000000000 --- a/docs/sdk/src/reference_docs/blockchain_state_machines.rs +++ /dev/null @@ -1,29 +0,0 @@ -//! # State Transition Function -//! -//! This document briefly explains how in the context of Substrate-based blockchains, we view the -//! blockchain as a **decentralized state transition function**. -//! -//! Recall that a blockchain's main purpose is to help a permissionless set of entities to agree on -//! a shared data-set, and how it evolves. This is called the **State**, also referred to as -//! "onchain" data, or *Storage* in the context of FRAME. The state is where the account balance of -//! each user is, for example, stored, and there is a canonical version of it that everyone agrees -//! upon. -//! -//! Then, recall that a typical blockchain system will alter its state through execution of blocks. -//! *The component that dictates how this state alteration can happen is called the state transition -//! function*. -#![doc = simple_mermaid::mermaid!("../../../mermaid/stf_simple.mmd")] -//! -//! In Substrate-based blockchains, the state transition function is called the *Runtime*. This is -//! explained further in [`crate::reference_docs::wasm_meta_protocol`]. -//! -//! With this in mind, we can paint a complete picture of a blockchain as a state machine: -#![doc = simple_mermaid::mermaid!("../../../mermaid/stf.mmd")] -//! -//! In essence, the state of the blockchain at block N is the outcome of applying the state -//! transition function to the the previous state, and the current block as input. This can be -//! mathematically represented as: -//! -//! ```math -//! STF = F(State_N, Block_N) -> State_{N+1} -//! ``` diff --git a/docs/sdk/src/reference_docs/chain_spec_genesis.rs b/docs/sdk/src/reference_docs/chain_spec_genesis.rs deleted file mode 100644 index 2ac51a91f2d..00000000000 --- a/docs/sdk/src/reference_docs/chain_spec_genesis.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! Chain spec and genesis build. -//! -//! What is chain-spec. -//! What is genesis state and how to build it. diff --git a/docs/sdk/src/reference_docs/cli.rs b/docs/sdk/src/reference_docs/cli.rs deleted file mode 100644 index 9274e86b04e..00000000000 --- a/docs/sdk/src/reference_docs/cli.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! # Command Line Arguments -//! -//! -//! Notes: -//! -//! - Command line arguments of a typical substrate based chain, and how to find and learn them. -//! - How to extend them with your custom stuff. 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 e639761ee97..00000000000 --- 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/extrinsic_encoding.rs b/docs/sdk/src/reference_docs/extrinsic_encoding.rs deleted file mode 100644 index dd50a0f47c6..00000000000 --- a/docs/sdk/src/reference_docs/extrinsic_encoding.rs +++ /dev/null @@ -1,294 +0,0 @@ -//! # Constructing and Signing Extrinsics -//! -//! Extrinsics are payloads that are stored in blocks which are responsible for altering the state -//! of a blockchain via the [_state transition -//! function_][crate::reference_docs::blockchain_state_machines]. -//! -//! Substrate is configurable enough that extrinsics can take any format. In practice, runtimes -//! tend to use our [`sp_runtime::generic::UncheckedExtrinsic`] type to represent extrinsics, -//! because it's generic enough to cater for most (if not all) use cases. In Polkadot, this is -//! configured [here](https://github.com/polkadot-fellows/runtimes/blob/94b2798b69ba6779764e20a50f056e48db78ebef/relay/polkadot/src/lib.rs#L1478) -//! at the time of writing. -//! -//! What follows is a description of how extrinsics based on this -//! [`sp_runtime::generic::UncheckedExtrinsic`] type are encoded into bytes. Specifically, we are -//! looking at how extrinsics with a format version of 4 are encoded. This version is itself a part -//! of the payload, and if it changes, it indicates that something about the encoding may have -//! changed. -//! -//! # Encoding an Extrinsic -//! -//! At a high level, all extrinsics compatible with [`sp_runtime::generic::UncheckedExtrinsic`] -//! are formed from concatenating some details together, as in the following pseudo-code: -//! -//! ```text -//! extrinsic_bytes = concat( -//! compact_encoded_length, -//! version_and_maybe_signature, -//! call_data -//! ) -//! ``` -//! -//! For clarity, the actual implementation in Substrate looks like this: -#![doc = docify::embed!("../../substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs", unchecked_extrinsic_encode_impl)] -//! -//! Let's look at how each of these details is constructed: -//! -//! ## compact_encoded_length -//! -//! This is a [SCALE compact encoded][frame::deps::codec::Compact] integer which is equal to the -//! length, in bytes, of the rest of the extrinsic details. -//! -//! To obtain this value, we must encode and concatenate together the rest of the extrinsic details -//! first, and then obtain the byte length of these. We can then compact encode that length, and -//! prepend it to the rest of the details. -//! -//! ## version_and_maybe_signature -//! -//! If the extrinsic is _unsigned_, then `version_and_maybe_signature` will be just one byte -//! denoting the _transaction protocol version_, which is 4 (or `0b0000_0100`). -//! -//! If the extrinsic is _signed_ (all extrinsics submitted from users must be signed), then -//! `version_and_maybe_signature` is obtained by concatenating some details together, ie: -//! -//! ```text -//! version_and_maybe_signature = concat( -//! version_and_signed, -//! from_address, -//! signature, -//! transaction_extensions_extra, -//! ) -//! ``` -//! -//! Each of the details to be concatenated together is explained below: -//! -//! ### version_and_signed -//! -//! This is one byte, equal to `0x84` or `0b1000_0100` (i.e. an upper 1 bit to denote that it is -//! signed, and then the transaction version, 4, in the lower bits). -//! -//! ### from_address -//! -//! This is the [SCALE encoded][frame::deps::codec] address of the sender of the extrinsic. The -//! address is the first generic parameter of [`sp_runtime::generic::UncheckedExtrinsic`], and so -//! can vary from chain to chain. -//! -//! The address type used on the Polkadot relay chain is [`sp_runtime::MultiAddress`], -//! where `AccountId32` is defined [here][`sp_core::crypto::AccountId32`]. When constructing a -//! signed extrinsic to be submitted to a Polkadot node, you'll always use the -//! [`sp_runtime::MultiAddress::Id`] variant to wrap your `AccountId32`. -//! -//! ### signature -//! -//! This is the [SCALE encoded][frame::deps::codec] signature. The signature type is configured via -//! the third generic parameter of [`sp_runtime::generic::UncheckedExtrinsic`], which determines the -//! shape of the signature and signing algorithm that should be used. -//! -//! The signature is obtained by signing the _signed payload_ bytes (see below on how this is -//! constructed) using the private key associated with the address and correct algorithm. -//! -//! The signature type used on the Polkadot relay chain is [`sp_runtime::MultiSignature`]; the -//! variants there are the types of signature that can be provided. -//! -//! ### transaction_extensions_extra -//! -//! This is the concatenation of the [SCALE encoded][frame::deps::codec] bytes representing each of -//! the [_transaction extensions_][sp_runtime::traits::TransactionExtension], and are configured by -//! the fourth generic parameter of [`sp_runtime::generic::UncheckedExtrinsic`]. Learn more about -//! transaction extensions [here][crate::reference_docs::transaction_extensions]. -//! -//! When it comes to constructing an extrinsic, each transaction extension has two things that we -//! are interested in here: -//! -//! - The actual SCALE encoding of the transaction extension type itself; this is what will form our -//! `transaction_extensions_extra` bytes. -//! - An `Implicit` type. This is SCALE encoded into the `transaction_extensions_implicit` data of -//! the _signed payload_ (see below). -//! -//! Either (or both) of these can encode to zero bytes. -//! -//! Each chain configures the set of transaction extensions that it uses in its runtime -//! configuration. At the time of writing, Polkadot configures them -//! [here](https://github.com/polkadot-fellows/runtimes/blob/1dc04eb954eadf8aadb5d83990b89662dbb5a074/relay/polkadot/src/lib.rs#L1432C25-L1432C25). -//! Some of the common transaction extensions are defined -//! [here][frame::deps::frame_system#transaction-extensions]. -//! -//! Information about exactly which transaction extensions are present on a chain and in what order -//! is also a part of the metadata for the chain. For V15 metadata, it can be -//! [found here][frame::deps::frame_support::__private::metadata::v15::ExtrinsicMetadata]. -//! -//! ## call_data -//! -//! This is the main payload of the extrinsic, which is used to determine how the chain's state is -//! altered. This is defined by the second generic parameter of -//! [`sp_runtime::generic::UncheckedExtrinsic`]. -//! -//! A call can be anything that implements [`Encode`][frame::deps::codec::Encode]. In FRAME-based -//! runtimes, a call is represented as an enum of enums, where the outer enum represents the FRAME -//! pallet being called, and the inner enum represents the call being made within that pallet, and -//! any arguments to it. Read more about the call enum -//! [here][crate::reference_docs::frame_composite_enums]. -//! -//! FRAME `Call` enums are automatically generated, and end up looking something like this: -#![doc = docify::embed!("./src/reference_docs/extrinsic_encoding.rs", call_data)] -//! -//! In pseudo-code, this `Call` enum encodes equivalently to: -//! -//! ```text -//! call_data = concat( -//! pallet_index, -//! call_index, -//! call_args -//! ) -//! ``` -//! -//! - `pallet_index` is a single byte denoting the index of the pallet that we are calling into, and -//! is what the tag of the outermost enum will encode to. -//! - `call_index` is a single byte denoting the index of the call that we are making the pallet, -//! and is what the tag of the inner enum will encode to. -//! - `call_args` are the SCALE encoded bytes for each of the arguments that the call expects, and -//! are typically provided as values to the inner enum. -//! -//! Information about the pallets that exist for a chain (including their indexes), the calls -//! available in each pallet (including their indexes), and the arguments required for each call -//! can be found in the metadata for the chain. For V15 metadata, this information -//! [is here][frame::deps::frame_support::__private::metadata::v15::PalletMetadata]. -//! -//! # The Signed Payload Format -//! -//! All extrinsics submitted to a node from the outside world (also known as _transactions_) need to -//! be _signed_. The data that needs to be signed for some extrinsic is called the _signed payload_, -//! and its shape is described by the following pseudo-code: -//! -//! ```text -//! signed_payload = concat( -//! call_data, -//! transaction_extensions_extra, -//! transaction_extensions_implicit, -//! ) -//! -//! if length(signed_payload) > 256 { -//! signed_payload = blake2_256(signed_payload) -//! } -//! ``` -//! -//! The bytes representing `call_data` and `transaction_extensions_extra` can be obtained as -//! descibed above. `transaction_extensions_implicit` is constructed by SCALE encoding the -//! ["implicit" data][sp_runtime::traits::TransactionExtensionBase::Implicit] for each -//! transaction extension that the chain is using, in order. -//! -//! Once we've concatenated those together, we hash the result if it's greater than 256 bytes in -//! length using a Blake2 256bit hasher. -//! -//! The [`sp_runtime::generic::SignedPayload`] type takes care of assembling the correct payload -//! for us, given `call_data` and a tuple of transaction extensions. -//! -//! # Example Encoding -//! -//! Using [`sp_runtime::generic::UncheckedExtrinsic`], we can construct and encode an extrinsic -//! as follows: -#![doc = docify::embed!("./src/reference_docs/extrinsic_encoding.rs", encoding_example)] - -#[docify::export] -pub mod call_data { - use parity_scale_codec::{Decode, Encode}; - use sp_runtime::{traits::Dispatchable, DispatchResultWithInfo}; - - // The outer enum composes calls within - // different pallets together. We have two - // pallets, "PalletA" and "PalletB". - #[derive(Encode, Decode, Clone)] - pub enum Call { - #[codec(index = 0)] - PalletA(PalletACall), - #[codec(index = 7)] - PalletB(PalletBCall), - } - - // An inner enum represents the calls within - // a specific pallet. "PalletA" has one call, - // "Foo". - #[derive(Encode, Decode, Clone)] - pub enum PalletACall { - #[codec(index = 0)] - Foo(String), - } - - #[derive(Encode, Decode, Clone)] - pub enum PalletBCall { - #[codec(index = 0)] - Bar(String), - } - - impl Dispatchable for Call { - type RuntimeOrigin = (); - type Config = (); - type Info = (); - type PostInfo = (); - fn dispatch(self, _origin: Self::RuntimeOrigin) -> DispatchResultWithInfo { - Ok(()) - } - } -} - -#[docify::export] -pub mod encoding_example { - use super::call_data::{Call, PalletACall}; - use crate::reference_docs::transaction_extensions::transaction_extensions_example; - use parity_scale_codec::Encode; - use sp_core::crypto::AccountId32; - use sp_keyring::sr25519::Keyring; - use sp_runtime::{ - generic::{SignedPayload, UncheckedExtrinsic}, - MultiAddress, MultiSignature, - }; - - // Define some transaction extensions to use. We'll use a couple of examples - // from the transaction extensions reference doc. - type TransactionExtensions = ( - transaction_extensions_example::AddToPayload, - transaction_extensions_example::AddToSignaturePayload, - ); - - // We'll use `UncheckedExtrinsic` to encode our extrinsic for us. We set - // the address and signature type to those used on Polkadot, use our custom - // `Call` type, and use our custom set of `TransactionExtensions`. - type Extrinsic = UncheckedExtrinsic< - MultiAddress, - Call, - MultiSignature, - TransactionExtensions, - >; - - pub fn encode_demo_extrinsic() -> Vec { - // The "from" address will be our Alice dev account. - let from_address = MultiAddress::::Id(Keyring::Alice.to_account_id()); - - // We provide some values for our expected transaction extensions. - let transaction_extensions = ( - transaction_extensions_example::AddToPayload(1), - transaction_extensions_example::AddToSignaturePayload, - ); - - // Construct our call data: - let call_data = Call::PalletA(PalletACall::Foo("Hello".to_string())); - - // The signed payload. This takes care of encoding the call_data, - // transaction_extensions_extra and transaction_extensions_implicit, and hashing - // the result if it's > 256 bytes: - let signed_payload = SignedPayload::new(call_data.clone(), transaction_extensions.clone()); - - // Sign the signed payload with our Alice dev account's private key, - // and wrap the signature into the expected type: - let signature = { - let sig = Keyring::Alice.sign(&signed_payload.encode()); - MultiSignature::Sr25519(sig) - }; - - // Now, we can build and encode our extrinsic: - let ext = Extrinsic::new_signed(call_data, from_address, signature, transaction_extensions); - - let encoded_ext = ext.encode(); - encoded_ext - } -} diff --git a/docs/sdk/src/reference_docs/fee_less_runtime.rs b/docs/sdk/src/reference_docs/fee_less_runtime.rs deleted file mode 100644 index 1213c262825..00000000000 --- a/docs/sdk/src/reference_docs/fee_less_runtime.rs +++ /dev/null @@ -1,12 +0,0 @@ -//! # Fee-Less Runtime -//! -//! -//! Notes: -//! -//! - An extension of [`runtime_vs_smart_contract`], showcasing the tools needed to build a safe -//! runtime that is fee-less. -//! - Would need to use unsigned origins, custom validate_unsigned, check the existence of some NFT -//! and some kind of rate limiting (eg. any account gets 5 free tx per day). -//! - The rule of thumb is that as long as the unsigned validate does one storage read, similar to -//! nonce, it is fine. -//! - This could possibly be a good guide/template, rather than a reference doc. diff --git a/docs/sdk/src/reference_docs/frame_benchmarking_weight.rs b/docs/sdk/src/reference_docs/frame_benchmarking_weight.rs deleted file mode 100644 index f65f4174ec6..00000000000 --- a/docs/sdk/src/reference_docs/frame_benchmarking_weight.rs +++ /dev/null @@ -1,23 +0,0 @@ -//! # FRAME Benchmarking and Weights. -//! -//! Notes: -//! -//! On Weight as a concept. -//! -//! - Why we need it. Super important. People hate this. We need to argue why it is worth it. -//! - Axis of weight: PoV + Time. -//! - pre dispatch weight vs. metering and post dispatch correction. -//! - mention that we will do this for PoV -//! - you can manually refund using `DispatchResultWithPostInfo`. -//! - Technically you can have weights with any benchmarking framework. You just need one number to -//! be computed pre-dispatch. But FRAME gives you a framework for this. -//! - improve documentation of `#[weight = ..]` and `#[pallet::weight(..)]`. All syntax variation -//! should be covered. -//! -//! on FRAME benchmarking machinery: -//! -//! - component analysis, why everything must be linear. -//! - how to write benchmarks, how you must think of worst case. -//! - how to run benchmarks. -//! -//! - https://www.shawntabrizi.com/substrate/substrate-storage-deep-dive/ diff --git a/docs/sdk/src/reference_docs/frame_composite_enums.rs b/docs/sdk/src/reference_docs/frame_composite_enums.rs deleted file mode 100644 index 6051cd53446..00000000000 --- a/docs/sdk/src/reference_docs/frame_composite_enums.rs +++ /dev/null @@ -1 +0,0 @@ -//! # FRAME Composite Enums diff --git a/docs/sdk/src/reference_docs/frame_currency.rs b/docs/sdk/src/reference_docs/frame_currency.rs deleted file mode 100644 index ba181373062..00000000000 --- a/docs/sdk/src/reference_docs/frame_currency.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! FRAME Currency Abstractions and Traits -//! -//! Notes: -//! -//! - History, `Currency` trait. -//! - `Hold` and `Freeze` with diagram. -//! - `HoldReason` and `FreezeReason` -//! - This footgun: https://github.com/paritytech/polkadot-sdk/pull/1900#discussion_r1363783609 diff --git a/docs/sdk/src/reference_docs/frame_origin.rs b/docs/sdk/src/reference_docs/frame_origin.rs deleted file mode 100644 index a4078377cd7..00000000000 --- a/docs/sdk/src/reference_docs/frame_origin.rs +++ /dev/null @@ -1,14 +0,0 @@ -//! # FRAME Origin -//! -//! Notes: -//! -//! - Def talk about account abstraction and how it is a solved issue in frame. See Gav's talk in -//! Protocol Berg 2023 -//! - system's raw origin, how it is amalgamated with other origins into one type -//! [`frame_composite_enums`] -//! - signed origin -//! - unsigned origin, link to [`fee_less_runtime`] -//! - Root origin, how no one can obtain it. -//! - Abstract origin: how FRAME allows you to express "origin is 2/3 of the this body or 1/2 of -//! that body or half of the token holders". -//! - `type CustomOrigin: EnsureOrigin<_>` in pallets. diff --git a/docs/sdk/src/reference_docs/frame_runtime_migration.rs b/docs/sdk/src/reference_docs/frame_runtime_migration.rs deleted file mode 100644 index 0616ccbb6f5..00000000000 --- a/docs/sdk/src/reference_docs/frame_runtime_migration.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! # Runtime Runtime Upgrade and Testing -//! -//! -//! Notes: -//! -//! - Flow of things, when does `on_runtime_upgrade` get called. Link to to `Hooks` and its diagram -//! as source of truth. -//! - Data migration and when it is needed. -//! - Look into the pba-lecture. diff --git a/docs/sdk/src/reference_docs/frame_system_accounts.rs b/docs/sdk/src/reference_docs/frame_system_accounts.rs deleted file mode 100644 index ae9d2c9e0cb..00000000000 --- a/docs/sdk/src/reference_docs/frame_system_accounts.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! # FRAME Accounts -//! -//! How `frame_system` handles accountIds. Nonce. Consumers and Providers, reference counting. - -// - poorly understood topics, needs one great article to rul them all. -// - https://github.com/paritytech/substrate/issues/14425 -// - https://github.com/paritytech/substrate/pull/12951 -// - https://substrate.stackexchange.com/questions/263/what-is-the-meaning-of-the-account-provider-sufficients-and-consumer diff --git a/docs/sdk/src/reference_docs/glossary.rs b/docs/sdk/src/reference_docs/glossary.rs deleted file mode 100644 index 56f5ef5aeb5..00000000000 --- a/docs/sdk/src/reference_docs/glossary.rs +++ /dev/null @@ -1,120 +0,0 @@ -//! # Glossary -//! -//! #### State -//! -//! The data around which the blockchain network wishes to come to consensus. Also -//! referred to as "onchain data", "onchain storage" or sometimes just "storage". In UTXO based -//! blockchains, is referred to as "ledger". -//! -//! **Synonyms**: Onchain data, Onchain storage, Storage, Ledger -//! -//! #### State Transition Function -//! -//! The WASM Blob that dictates how the blockchain should transition its state upon encountering new -//! blocks. -//! -//! #### Host -//! -//! The environment that hosts and executes the [state transition function's WASM -//! blob](#state-transition-function). -//! -//! #### Node -//! -//! The full software artifact that contains the [host](#host), but importantly also all the other -//! modules needed to be part of a blockchain network, such as peer-to-peer networking, database and -//! such. -//! -//! **Synonyms**: Client -//! -//! #### Light Node -//! -//! Same as [node](#nodes), but when capable of following the network only through listening to -//! block headers. Usually capable of running in more constrained environments, such as an embedded -//! device, phone, or a web browser. -//! -//! **Synonyms**: Light Client -//! -//! #### Offchain -//! -//! Refers to operations conducted outside the blockchain's consensus mechanism. They are essential -//! for enhancing scalability and efficiency, enabling activities like data fetching and computation -//! without bloating the blockchain state. -//! -//! #### Host Functions: -//! -//! Host functions are the node's API, these are functions provided by the runtime environment (the -//! [host](#host)) to the Wasm runtime. These functions allow the Wasm code to interact with and -//! perform operations on the [node](#node), like accessing the blockchain state. -//! -//! #### Runtime API: -//! -//! This is the API of the runtime, it acts as a communication bridge between the runtime and the -//! node, serving as the exposed interface that facilitates their interactions. -//! -//! #### Dispatchable: -//! -//! Dispatchables are [function objects](https://en.wikipedia.org/wiki/Function_object) that act as -//! the entry points in [FRAME](frame) pallets. They can be called by internal or external entities -//! to interact with the blockchain's state. They are a core aspect of the runtime logic, handling -//! transactions and other state-changing operations. -//! -//! **Synonyms**: Callable -//! -//! #### Extrinsic -//! -//! An extrinsic is a general term for a piece of data that is originated outside of the runtime, -//! included into a block and leads to some action. This includes user-initiated transactions as -//! well as inherents which are placed into the block by the block-builder. -//! -//! #### Pallet -//! -//! Similar to software modules in traditional programming, [FRAME](frame) pallets in Substrate are -//! modular components that encapsulate distinct functionalities or business logic. Just as -//! libraries or modules are used to build and extend the capabilities of a software application, -//! pallets are the foundational building blocks for constructing a blockchain's runtime with frame. -//! They enable the creation of customizable and upgradeable networks, offering a composable -//! framework for a Substrate-based blockchain. Each pallet can be thought of as a plug-and-play -//! module, enhancing the blockchain's functionality in a cohesive and integrated manner. -//! -//! #### Full Node -//! -//! It is a node that prunes historical states, keeping only recent finalized block states to reduce -//! storage needs. Full nodes provide current chain state access and allow direct submission and -//! validation of extrinsics, maintaining network decentralization. -//! -//! #### Archive Node -//! -//! An archive node is a specialized node that maintains a complete history of all block states and -//! transactions. Unlike a full node, it does not prune historical data, ensuring full access to the -//! entire blockchain history. This makes it essential for detailed blockchain analysis and -//! historical queries, but requires significantly more storage capacity. -//! -//! #### Validator -//! -//! A validator is a node that participates in the consensus mechanism of the network. -//! Its role includes block production, transaction validation, network integrity and security -//! maintenance. -//! -//! #### Collator -//! -//! A collator is a node that is responsible for producing candidate blocks for the validators. -//! Collators are similar to validators on any other blockchain but, they do not need to provide -//! security guarantees as the Relay Chain handles this. -//! -//! #### Parachain -//! -//! Short for "parallelized chain" a parachain is a specialized blockchain that runs in parallel to -//! the Relay Chain (Polkadot, Kusama, etc.), benefiting from the shared security and -//! interoperability features of it. -//! -//! **Synonyms**: AppChain -//! -//! #### PVF -//! The Parachain Validation Function (PVF) is the current runtime Wasm for a parachain that is -//! stored on the Relay chain. It is an essential component in the Polkadot ecosystem, encapsulating -//! the validation logic for each parachain. The PVF is executed by validators to verify the -//! correctness of parachain blocks. This is critical for ensuring that each block follows the logic -//! set by its respective parachain, thus maintaining the integrity and security of the entire -//! network. -//! -//! **Synonyms**: Parachain Validation Function 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 a6a0a828ef5..00000000000 --- 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 -//! https://docs.substrate.io/learn/light-clients-in-substrate-connect/ -//! https://github.com/substrate-developer-hub/substrate-front-end-template/pull/277 diff --git a/docs/sdk/src/reference_docs/metadata.rs b/docs/sdk/src/reference_docs/metadata.rs deleted file mode 100644 index 702c1c30fd9..00000000000 --- a/docs/sdk/src/reference_docs/metadata.rs +++ /dev/null @@ -1 +0,0 @@ -//! # Metadata diff --git a/docs/sdk/src/reference_docs/mod.rs b/docs/sdk/src/reference_docs/mod.rs deleted file mode 100644 index 732db2f758c..00000000000 --- a/docs/sdk/src/reference_docs/mod.rs +++ /dev/null @@ -1,99 +0,0 @@ -//! # Polkadot SDK Reference Docs. -//! -//! This is the entry point for all reference documents that enhance one's learning experience in -//! the Polkadot SDK. -//! -//! Note that this module also contains the [glossary](crate::reference_docs::glossary). -//! -//! ## What is a "reference document"? -//! -//! First, see [why we use rust-docs for everything](crate#why-rust-docs) and our documentation -//! [principles](crate#principles). We acknowledge that as much of the crucial information should be -//! embedded in the low level rust-docs. Then, high level scenarios should be covered in -//! [`crate::guides`]. Finally, we acknowledge that there is a category of information that is: -//! -//! 1. crucial to know. -//! 2. is too high level to be in the rust-doc of any one `type`, `trait` or `fn`. -//! 3. is too low level to be encompassed in a [`crate::guides`]. -//! -//! We call this class of documents "reference documents". Our goal should be to minimize the number -//! of "reference" docs, as they incur maintenance burden. - -/// Learn how Substrate and FRAME use traits and associated types to make modules generic in a -/// type-safe manner. -pub mod trait_based_programming; - -/// Learn about the way Substrate and FRAME view their blockchains as state machines. -pub mod blockchain_state_machines; - -/// The glossary. -pub mod glossary; - -/// Learn about the WASM meta-protocol of all Substrate-based chains. -pub mod wasm_meta_protocol; - -/// Learn about the differences between smart contracts and a FRAME-based runtime. They are both -/// "code stored onchain", but how do they differ? -pub mod runtime_vs_smart_contract; - -/// Learn about how extrinsics are encoded to be transmitted to a node and stored in blocks. -pub mod extrinsic_encoding; - -/// Learn about the transaction extensions that form a part of extrinsics. -// TODO: @jsdw https://github.com/paritytech/polkadot-sdk-docs/issues/42 -pub mod transaction_extensions; - -/// Learn about *"Origin"* A topic in FRAME that enables complex account abstractions to be built. -// TODO: @shawntabrizi https://github.com/paritytech/polkadot-sdk-docs/issues/43 -pub mod frame_origin; - -/// Learn about how to write safe and defensive code in your FRAME runtime. -// TODO: @CrackTheCode016 https://github.com/paritytech/polkadot-sdk-docs/issues/44 -pub mod safe_defensive_programming; - -/// Learn about composite enums in FRAME-based runtimes, such as "RuntimeEvent" and "RuntimeCall". -pub mod frame_composite_enums; - -/// Learn about how to make a pallet/runtime that is fee-less and instead uses another mechanism to -/// control usage and sybil attacks. -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 frame-system handles `account-ids`, nonces, consumers and providers. -pub mod frame_system_accounts; - -/// Learn about the currency-related abstractions provided in FRAME. -pub mod frame_currency; - -/// Learn about benchmarking and weight. -// TODO: @shawntabrizi @ggwpez https://github.com/paritytech/polkadot-sdk-docs/issues/50 -pub mod frame_benchmarking_weight; - -/// Learn about chain specification file and the genesis state of the blockchain. -// TODO: @michalkucharczyk https://github.com/paritytech/polkadot-sdk-docs/issues/51 -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 all the advance ways to test your coordinate a rutnime upgrade and data migration. -// TODO: @liamaharon https://github.com/paritytech/polkadot-sdk-docs/issues/55 -pub mod frame_runtime_migration; - -/// 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; diff --git a/docs/sdk/src/reference_docs/runtime_vs_smart_contract.rs b/docs/sdk/src/reference_docs/runtime_vs_smart_contract.rs deleted file mode 100644 index 7f96fa1800a..00000000000 --- a/docs/sdk/src/reference_docs/runtime_vs_smart_contract.rs +++ /dev/null @@ -1,6 +0,0 @@ -//! Runtime vs. Smart Contracts -//! -//! Notes: -//! -//! Why one can be weighed, and one MUST be metered. -//! https://forum.polkadot.network/t/where-contracts-fail-and-runtimes-chains-are-needed/4464/3 diff --git a/docs/sdk/src/reference_docs/safe_defensive_programming.rs b/docs/sdk/src/reference_docs/safe_defensive_programming.rs deleted file mode 100644 index 9d0f028e570..00000000000 --- a/docs/sdk/src/reference_docs/safe_defensive_programming.rs +++ /dev/null @@ -1 +0,0 @@ -//! diff --git a/docs/sdk/src/reference_docs/trait_based_programming.rs b/docs/sdk/src/reference_docs/trait_based_programming.rs deleted file mode 100644 index ace31388070..00000000000 --- a/docs/sdk/src/reference_docs/trait_based_programming.rs +++ /dev/null @@ -1,229 +0,0 @@ -//! # Trait-based Programming -//! -//! This document walks you over a peculiar way of using Rust's `trait` items. This pattern is -//! abundantly used within [`frame`] and is therefore paramount important for a smooth transition -//! into it. -//! -//! The rest of this document assumes familiarity with the -//! [Rust book's Advanced Traits](https://doc.rust-lang.org/book/ch19-03-advanced-traits.html) -//! section. -//! Moreover, we use the [`frame::traits::Get`]. -//! -//! First, imagine we are writing a FRAME pallet. We represent this pallet with a `struct Pallet`, -//! and this pallet wants to implement the functionalities of that pallet, for example a simple -//! `transfer` function. For the sake of education, we are interested in having a `MinTransfer` -//! amount, expressed as a [`frame::traits::Get`], which will dictate what is the minimum amount -//! that can be transferred. -//! -//! We can foremost write this as simple as the following snippet: -#![doc = docify::embed!("./src/reference_docs/trait_based_programming.rs", basic)] -//! -//! -//! In this example, we use arbitrary choices for `AccountId`, `Balance` and the `MinTransfer` type. -//! This works great for **one team's purposes** but we have to remember that Substrate and FRAME -//! are written as generic frameworks, intended to be highly configurable. -//! -//! In a broad sense, there are two avenues in exposing configurability: -//! -//! 1. For *values* that need to be generic, for example `MinTransfer`, we attach them to the -//! `Pallet` struct as fields: -//! -//! ``` -//! struct Pallet { -//! min_transfer: u128, -//! } -//! ``` -//! -//! 2. For *types* that need to be generic, we would have to use generic or associated types, such -//! as: -//! -//! ``` -//! struct Pallet { -//! min_transfer: u128, -//! _marker: std::marker::PhantomData, -//! } -//! ``` -//! -//! Substrate and FRAME, for various reasons (performance, correctness, type safety) has opted to -//! use *types* to declare both *values* and *types* as generic. This is the essence of why the -//! `Get` trait exists. -//! -//! This would bring us to the second iteration of the pallet, which would look like: -#![doc = docify::embed!("./src/reference_docs/trait_based_programming.rs", generic)] -//! -//! In this example, we managed to make all 3 of our types generic. Taking the example of the -//! `AccountId`, one should read the above as following: -//! -//! > The `Pallet` does not know what type `AccountId` concretely is, but it knows that it is -//! > something that adheres to being `From<[u8; 32]>`. -//! -//! This method would work, but it suffers from two downsides: -//! -//! 1. It is verbose, each `impl` block would have to reiterate all of the trait bounds. -//! 2. It cannot easily share/inherit generic types. Imagine multiple pallets wanting to be generic -//! over a single `AccountId`. There is no easy way to express that in this model. -//! -//! Finally, this brings us to using traits and associated types on traits to express the above. -//! Trait associated types have the benefit of: -//! -//! 1. Being less verbose, as in effect they can *group multiple `type`s together*. -//! 2. Can inherit from one another by declaring -//! [supertraits](https://doc.rust-lang.org/rust-by-example/trait/supertraits.html). -//! -//! > Interestingly, one downside of associated types is that declaring defaults on them is not -//! > stable yet. In the meantime, we have built our own custom mechanics around declaring defaults -//! for associated types, see [`pallet_default_config_example`]. -//! -//! The last iteration of our code would look like this: -#![doc = docify::embed!("./src/reference_docs/trait_based_programming.rs", trait_based)] -//! -//! Notice how instead of having multiple generics, everything is generic over a single ``, and all types are fetched through `T`, for example `T::AccountId`, `T::MinTransfer`. -//! -//! Finally, imagine all pallets wanting to be generic over `AccountId`. This can be achieved by -//! having individual `trait Configs` declare a shared `trait SystemConfig` as their -//! [supertrait](https://doc.rust-lang.org/rust-by-example/trait/supertraits.html). -#![doc = docify::embed!("./src/reference_docs/trait_based_programming.rs", with_system)] -//! In FRAME, this shared supertrait is [`frame::prelude::frame_system`]. -//! -//! Notice how this made no difference in the syntax of the rest of the code. `T::AccountId` is -//! still a valid type, since `T` implements `Config` and `Config` implies `SystemConfig`, which -//! has a `type AccountId`. -//! -//! Note, in some instances one would need to use what is known as the fully-qualified-syntax to -//! access a type to help the Rust compiler disambiguate. -#![doc = docify::embed!("./src/reference_docs/trait_based_programming.rs", fully_qualified)] -//! -//! This syntax can sometimes become more complicated when you are dealing with nested traits. -//! Consider the following example, in which we fetch the `type Balance` from another trait -//! `CurrencyTrait`. -#![doc = docify::embed!("./src/reference_docs/trait_based_programming.rs", fully_qualified_complicated)] -//! -//! Notice the final `type BalanceOf` and how it is defined. Using such aliases to shorten the -//! length of fully qualified syntax is a common pattern in FRAME. -//! -//! The above example is almost identical to the well-known (and somewhat notorious) `type -//! BalanceOf` that is often used in the context of [`frame::traits::fungible`]. -#![doc = docify::embed!("../../substrate/frame/fast-unstake/src/types.rs", BalanceOf)] -//! -//! ## Additional Resources -//! -//! - -//! - [Substrate Seminar - Traits and Generic Types](https://www.youtube.com/watch?v=6cp10jVWNl4) -//! - -#![allow(unused)] - -use frame::traits::Get; - -#[docify::export] -mod basic { - struct Pallet; - - type AccountId = frame::deps::sp_runtime::AccountId32; - type Balance = u128; - type MinTransfer = frame::traits::ConstU128<10>; - - impl Pallet { - fn transfer(_from: AccountId, _to: AccountId, _amount: Balance) { - todo!() - } - } -} - -#[docify::export] -mod generic { - use super::*; - - struct Pallet { - _marker: std::marker::PhantomData<(AccountId, Balance, MinTransfer)>, - } - - impl Pallet - where - Balance: frame::traits::AtLeast32BitUnsigned, - MinTransfer: frame::traits::Get, - AccountId: From<[u8; 32]>, - { - fn transfer(_from: AccountId, _to: AccountId, amount: Balance) { - assert!(amount >= MinTransfer::get()); - unimplemented!(); - } - } -} - -#[docify::export] -mod trait_based { - use super::*; - - trait Config { - type AccountId: From<[u8; 32]>; - type Balance: frame::traits::AtLeast32BitUnsigned; - type MinTransfer: frame::traits::Get; - } - - struct Pallet(std::marker::PhantomData); - impl Pallet { - fn transfer(_from: T::AccountId, _to: T::AccountId, amount: T::Balance) { - assert!(amount >= T::MinTransfer::get()); - unimplemented!(); - } - } -} - -#[docify::export] -mod with_system { - use super::*; - - pub trait SystemConfig { - type AccountId: From<[u8; 32]>; - } - - pub trait Config: SystemConfig { - type Balance: frame::traits::AtLeast32BitUnsigned; - type MinTransfer: frame::traits::Get; - } - - pub struct Pallet(std::marker::PhantomData); - impl Pallet { - fn transfer(_from: T::AccountId, _to: T::AccountId, amount: T::Balance) { - assert!(amount >= T::MinTransfer::get()); - unimplemented!(); - } - } -} - -#[docify::export] -mod fully_qualified { - use super::with_system::*; - - // Simple of using fully qualified syntax. - type AccountIdOf = ::AccountId; -} - -#[docify::export] -mod fully_qualified_complicated { - use super::with_system::*; - - trait CurrencyTrait { - type Balance: frame::traits::AtLeast32BitUnsigned; - fn more_stuff() {} - } - - trait Config: SystemConfig { - type Currency: CurrencyTrait; - } - - struct Pallet(std::marker::PhantomData); - impl Pallet { - fn transfer( - _from: T::AccountId, - _to: T::AccountId, - _amount: <::Currency as CurrencyTrait>::Balance, - ) { - unimplemented!(); - } - } - - /// A common pattern in FRAME. - type BalanceOf = <::Currency as CurrencyTrait>::Balance; -} diff --git a/docs/sdk/src/reference_docs/transaction_extensions.rs b/docs/sdk/src/reference_docs/transaction_extensions.rs deleted file mode 100644 index 4f96d665d9b..00000000000 --- a/docs/sdk/src/reference_docs/transaction_extensions.rs +++ /dev/null @@ -1,57 +0,0 @@ -//! Transaction extensions are, briefly, a means for different chains to extend the "basic" -//! extrinsic format with custom data that can be checked by the runtime. -//! -//! # Example -//! -//! Defining a couple of very simple transaction extensions looks like the following: -#![doc = docify::embed!("./src/reference_docs/transaction_extensions.rs", transaction_extensions_example)] - -#[docify::export] -pub mod transaction_extensions_example { - use parity_scale_codec::{Decode, Encode}; - use scale_info::TypeInfo; - use sp_runtime::{ - impl_tx_ext_default, - traits::{Dispatchable, TransactionExtension, TransactionExtensionBase}, - TransactionValidityError, - }; - - // This doesn't actually check anything, but simply allows - // some arbitrary `u32` to be added to the extrinsic payload - #[derive(Debug, Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] - pub struct AddToPayload(pub u32); - - impl TransactionExtensionBase for AddToPayload { - const IDENTIFIER: &'static str = "AddToPayload"; - type Implicit = (); - } - - impl TransactionExtension for AddToPayload { - type Pre = (); - type Val = (); - - impl_tx_ext_default!(Call; (); validate prepare); - } - - // This is the opposite; nothing will be added to the extrinsic payload, - // but the Implicit type (`1234u32`) will be added to the - // payload to be signed. - #[derive(Debug, Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] - pub struct AddToSignaturePayload; - - impl TransactionExtensionBase for AddToSignaturePayload { - const IDENTIFIER: &'static str = "AddToSignaturePayload"; - type Implicit = u32; - - fn implicit(&self) -> Result { - Ok(1234) - } - } - - impl TransactionExtension for AddToSignaturePayload { - type Pre = (); - type Val = (); - - impl_tx_ext_default!(Call; (); validate prepare); - } -} 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 4f4cda31094..00000000000 --- 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 deleted file mode 100644 index 37d1460f0e1..00000000000 --- a/docs/sdk/src/reference_docs/wasm_meta_protocol.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! # 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". -//! -//! 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. -//! -//! Moreover, the idea of "storing code in the state" is explored in the context of smart contracts -//! platforms, but has not been expanded further. -//! -//! Substrate mixes these two ideas together, and takes the novel approach of storing the -//! blockchain's main "state transition function" in the main blockchain state, in the same fashion -//! 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. -//! -//! > 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. -//! -//! 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 -//! most part) oblivious to the change that is happening. -//! -//! Therefore, the high-level architecture of a any Substrate-based chain can be demonstrated as -//! follows: -#![doc = simple_mermaid::mermaid!("../../../mermaid/substrate_simple.mmd")] -//! -//! The node and the runtime need to communicate. This is done through two concepts: -//! -//! 1. **Host functions**: a way for the (WASM) runtime to talk to the node. All host functions are -//! defined in [`sp_io`]. For example, [`sp_io::storage`] are the set of host functions that -//! allow the runtime to read and write data to the on-chain state. -//! 2. **Runtime APIs**: a way for the node to talk to the WASM runtime. Runtime APIs are defined -//! using macros and utilities in [`sp_api`]. For example, [`sp_api::Core`] is the most -//! fundamental runtime API that any blockchain must implement in order to be able to (re) -//! execute blocks. -#![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. -//! -//! 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. -//! -//! ## Node vs. Runtime -//! -//! A common question is: which components of the system end up being part of the node, and which -//! ones of the runtime? -//! -//! Recall from [`crate::reference_docs::blockchain_state_machines`] that the runtime is the state -//! transition function. Anything that needs to influence how your blockchain's state is updated, -//! should be a part of the runtime. For example, the logic around currency, governance, identity or -//! any other application-specific logic that has to do with the state is part of the runtime. -//! -//! Anything that does not have to do with the state-transition function and will only -//! facilitate/enable it is part of the node. For example, the database, networking, and even -//! consensus algorithm are all node-side components. -//! -//! > The consensus is to your runtime what HTTP is to a web-application. It is the underlying -//! > engine that enables trustless execution of the runtime in a distributed manner whilst -//! > maintaining a canonical outcome of that execution. -#![doc = simple_mermaid::mermaid!("../../../mermaid/substrate_with_frame.mmd")] -//! -//! ## State -//! -//! From the previous sections, we know that the a database component is part of the node, not the -//! runtime. We also hinted that a set of host functions ([`sp_io::storage`]) are how the runtime -//! issues commands to the node to read/write to the state. Let's dive deeper into this. -//! -//! The state of the blockchain, what we seek to come to consensus about, is indeed *kept* in the -//! node side. Nonetheless, the runtime is the only component that: -//! -//! 1. Can update the state. -//! 2. Can fully interpret the state. -//! -//! 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. -#![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 -//! (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. -//! -//! This opaque-ness is the fundamental reason why Substrate-based chains can fork-less-ly upgrade: -//! because the node side code is kept oblivious to all of the details of the state transition -//! function. Therefore, the state transition function can freely upgrade without the node needing -//! to know. -//! -//! ## Native Runtime -//! -//! TODO -//! -//! -//! ## Example: Block Execution. -//! -//! TODO diff --git a/polkadot/Cargo.toml b/polkadot/Cargo.toml index d769957490e..fb161848fb6 100644 --- a/polkadot/Cargo.toml +++ b/polkadot/Cargo.toml @@ -18,18 +18,15 @@ rust-version = "1.64.0" readme = "README.md" authors.workspace = true edition.workspace = true -version = "1.5.0" +version = "1.1.0" default-run = "polkadot" -[lints] -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"] } +tikv-jemallocator = { version = "0.5.0", optional = true, features = [ "unprefixed_malloc_on_supported_platforms" ] } # Crates in our workspace, defined as dependencies so we can pass them feature flags. -polkadot-cli = { path = "cli", features = ["rococo-native", "westend-native"] } +polkadot-cli = { path = "cli", features = [ "westend-native", "rococo-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" } @@ -39,7 +36,7 @@ polkadot-node-core-pvf-common = { path = "node/core/pvf/common" } polkadot-node-core-pvf-execute-worker = { path = "node/core/pvf/execute-worker" } [target.'cfg(target_os = "linux")'.dependencies] -tikv-jemallocator = { version = "0.5.0", features = ["unprefixed_malloc_on_supported_platforms"] } +tikv-jemallocator = { version = "0.5.0", features = [ "unprefixed_malloc_on_supported_platforms" ] } [dev-dependencies] assert_cmd = "2.0.4" @@ -56,22 +53,23 @@ substrate-build-script-utils = { path = "../substrate/utils/build-script-utils" maintenance = { status = "actively-developed" } [features] -runtime-benchmarks = ["polkadot-cli/runtime-benchmarks"] -try-runtime = ["polkadot-cli/try-runtime"] -fast-runtime = ["polkadot-cli/fast-runtime"] -runtime-metrics = ["polkadot-cli/runtime-metrics"] -pyroscope = ["polkadot-cli/pyroscope"] +runtime-benchmarks = [ "polkadot-cli/runtime-benchmarks" ] +try-runtime = [ "polkadot-cli/try-runtime" ] +fast-runtime = [ "polkadot-cli/fast-runtime" ] +runtime-metrics = [ "polkadot-cli/runtime-metrics" ] +pyroscope = [ "polkadot-cli/pyroscope" ] jemalloc-allocator = [ "dep:tikv-jemallocator", "polkadot-node-core-pvf-prepare-worker/jemalloc-allocator", "polkadot-node-core-pvf/jemalloc-allocator", "polkadot-overseer/jemalloc-allocator", ] +network-protocol-staging = [ "polkadot-cli/network-protocol-staging" ] # Enables timeout-based tests supposed to be run only in CI environment as they may be flaky # when run locally depending on system load -ci-only-tests = ["polkadot-node-core-pvf/ci-only-tests"] +ci-only-tests = [ "polkadot-node-core-pvf/ci-only-tests" ] # Configuration for building a .deb package - for use with `cargo-deb` [package.metadata.deb] @@ -91,12 +89,12 @@ assets = [ [ "target/release/polkadot-prepare-worker", "/usr/lib/polkadot/", - "755", + "755" ], [ "target/release/polkadot-execute-worker", "/usr/lib/polkadot/", - "755", + "755" ], [ "scripts/packaging/polkadot.service", diff --git a/polkadot/README.md b/polkadot/README.md index f27fc86df27..3c234bb8e3f 100644 --- a/polkadot/README.md +++ b/polkadot/README.md @@ -63,6 +63,7 @@ directory of the repo: ```bash git checkout +./scripts/init.sh cargo build --release ``` @@ -212,7 +213,7 @@ that we currently maintain. ### Using Docker -[Using Docker](../docs/contributor/docker.md) +[Using Docker](../docs/docker.md) ### Shell Completion @@ -222,11 +223,11 @@ that we currently maintain. ### Contributing Guidelines -[Contribution Guidelines](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md) +[Contribution Guidelines](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CONTRIBUTING.md) ### Contributor Code of Conduct -[Code of Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CODE_OF_CONDUCT.md) +[Code of Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CODE_OF_CONDUCT.md) ## License diff --git a/polkadot/cli/Cargo.toml b/polkadot/cli/Cargo.toml index ed90b2d58a4..0c2925c76e8 100644 --- a/polkadot/cli/Cargo.toml +++ b/polkadot/cli/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [package.metadata.wasm-pack.profile.release] # `wasm-opt` has some problems on Linux, see # https://github.com/rustwasm/wasm-pack/issues/781 etc. @@ -18,8 +15,7 @@ wasm-opt = false crate-type = ["cdylib", "rlib"] [dependencies] -cfg-if = "1.0" -clap = { version = "4.4.11", features = ["derive"], optional = true } +clap = { version = "4.4.6", features = ["derive"], optional = true } log = "0.4.17" thiserror = "1.0.48" futures = "0.3.21" @@ -47,8 +43,8 @@ sc-storage-monitor = { path = "../../substrate/client/storage-monitor" } substrate-build-script-utils = { path = "../../substrate/utils/build-script-utils" } [features] -default = ["cli", "db", "full-node"] -db = ["service/db"] +default = [ "cli", "db", "full-node" ] +db = [ "service/db" ] cli = [ "clap", "frame-benchmarking-cli", @@ -64,17 +60,19 @@ runtime-benchmarks = [ "sc-service?/runtime-benchmarks", "service/runtime-benchmarks", ] -full-node = ["service/full-node"] -try-runtime = ["service/try-runtime", "try-runtime-cli/try-runtime"] -fast-runtime = ["service/fast-runtime"] -pyroscope = ["pyro", "pyroscope_pprofrs"] +full-node = [ "service/full-node" ] +try-runtime = [ "service/try-runtime", "try-runtime-cli/try-runtime" ] +fast-runtime = [ "service/fast-runtime" ] +pyroscope = [ "pyro", "pyroscope_pprofrs" ] # Configure the native runtimes to use. -westend-native = ["service/westend-native"] -rococo-native = ["service/rococo-native"] +westend-native = [ "service/westend-native" ] +rococo-native = [ "service/rococo-native" ] -malus = ["full-node", "service/malus"] +malus = [ "full-node", "service/malus" ] runtime-metrics = [ "polkadot-node-metrics/runtime-metrics", "service/runtime-metrics", ] + +network-protocol-staging = [ "service/network-protocol-staging" ] diff --git a/polkadot/cli/src/cli.rs b/polkadot/cli/src/cli.rs index 30f35ebcb6f..e20e35c9103 100644 --- a/polkadot/cli/src/cli.rs +++ b/polkadot/cli/src/cli.rs @@ -82,22 +82,22 @@ pub struct RunCmd { #[arg(long = "force-rococo")] pub force_rococo: bool, + /// Setup a GRANDPA scheduled voting pause. + /// + /// This parameter takes two values, namely a block number and a delay (in blocks). + /// + /// After the given block number is finalized the GRANDPA voter will temporarily + /// stop voting for new blocks until the given delay has elapsed (i.e. until a + /// block at height `pause_block + delay` is imported). + #[arg(long = "grandpa-pause", num_args = 2)] + pub grandpa_pause: Vec, + /// Disable the BEEFY gadget. /// /// Currently enabled by default on 'Rococo', 'Wococo' and 'Versi'. #[arg(long)] pub no_beefy: bool, - /// Allows a validator to run insecurely outside of Secure Validator Mode. Security features - /// are still enabled on a best-effort basis, but missing features are no longer required. For - /// more information see . - #[arg(long = "insecure-validator-i-know-what-i-do", requires = "validator")] - pub insecure_validator: bool, - - /// Enable the block authoring backoff that is triggered when finality is lagging. - #[arg(long)] - pub force_authoring_backoff: bool, - /// Add the destination address to the 'Jaeger' agent. /// /// Must be valid socket address, of format `IP:Port` (commonly `127.0.0.1:6831`). diff --git a/polkadot/cli/src/command.rs b/polkadot/cli/src/command.rs index 018400fbcf8..2dcf5e0e8d7 100644 --- a/polkadot/cli/src/command.rs +++ b/polkadot/cli/src/command.rs @@ -215,6 +215,12 @@ where set_default_ss58_version(chain_spec); + let grandpa_pause = if cli.run.grandpa_pause.is_empty() { + None + } else { + Some((cli.run.grandpa_pause[0], cli.run.grandpa_pause[1])) + }; + if chain_spec.is_kusama() { info!("----------------------------"); info!("This chain is not in any way"); @@ -238,8 +244,6 @@ where let node_version = if cli.run.disable_worker_version_check { None } else { Some(NODE_VERSION.to_string()) }; - let secure_validator_mode = cli.run.base.validator && !cli.run.insecure_validator; - runner.run_node_until_exit(move |config| async move { let hwbench = (!cli.run.no_hardware_benchmarks) .then_some(config.database.path().map(|database_path| { @@ -253,12 +257,11 @@ where config, service::NewFullParams { is_parachain_node: service::IsParachainNode::No, + grandpa_pause, enable_beefy, - force_authoring_backoff: cli.run.force_authoring_backoff, jaeger_agent, telemetry_worker_handle: None, node_version, - secure_validator_mode, workers_path: cli.run.workers_path, workers_names: None, overseer_gen, diff --git a/polkadot/core-primitives/Cargo.toml b/polkadot/core-primitives/Cargo.toml index 32ee8d3ff3f..f843ec17943 100644 --- a/polkadot/core-primitives/Cargo.toml +++ b/polkadot/core-primitives/Cargo.toml @@ -6,18 +6,15 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -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.10.0", default-features = false, features = ["derive"] } -parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive"] } +parity-scale-codec = { version = "3.6.1", default-features = false, features = [ "derive" ] } [features] -default = ["std"] +default = [ "std" ] std = [ "parity-scale-codec/std", "scale-info/std", diff --git a/polkadot/doc/testing.md b/polkadot/doc/testing.md index 76703b1b439..1045303baf0 100644 --- a/polkadot/doc/testing.md +++ b/polkadot/doc/testing.md @@ -1,7 +1,6 @@ # Testing -Testing is an essential tool to assure correctness. This document describes how we test the Polkadot code, whether -locally, at scale, and/or automatically in CI. +Automated testing is an essential tool to assure correctness. ## Scopes @@ -9,57 +8,27 @@ The testing strategy for Polkadot is 4-fold: ### Unit testing (1) -Boring, small scale correctness tests of individual functions. It is usually -enough to run `cargo test` in the crate you are testing. - -For full coverage you may have to pass some additional features. For example: - -```sh -cargo test --features ci-only-tests -``` +Boring, small scale correctness tests of individual functions. ### Integration tests -There are the following variants of integration tests: +There are two variants of integration tests: #### Subsystem tests (2) One particular subsystem (subsystem under test) interacts with a mocked overseer that is made to assert incoming and -outgoing messages of the subsystem under test. See e.g. the `statement-distribution` tests. +outgoing messages of the subsystem under test. This is largely present today, but has some fragmentation in the evolved +integration test implementation. A `proc-macro`/`macro_rules` would allow for more consistent implementation and +structure. #### Behavior tests (3) -Launching small scale networks, with multiple adversarial nodes. This should include tests around the thresholds in -order to evaluate the error handling once certain assumed invariants fail. - -Currently, we commonly use **zombienet** to run mini test-networks, whether locally or in CI. To run on your machine: - -- First, make sure you have [zombienet][zombienet] installed. - -- Now, all the required binaries must be installed in your $PATH. You must run the following from the `polkadot/` -directory in order to test your changes. (Not `zombienet setup`, or you will get the released binaries without your -local changes!) +Launching small scale networks, with multiple adversarial nodes without any further tooling required. This should +include tests around the thresholds in order to evaluate the error handling once certain assumed invariants fail. -```sh -cargo install --path . --locked -``` - -- You will also need to install whatever binaries are required for your specific tests. For example, to install -`undying-collator`, from `polkadot/`, run: - -```sh -cargo install --path ./parachain/test-parachains/undying/collator --locked -``` +For this purpose based on `AllSubsystems` and `proc-macro` `AllSubsystemsGen`. -- Finally, run the zombienet test from the `polkadot` directory: - -```sh -RUST_LOG=parachain::pvf=trace zombienet --provider=native spawn zombienet_tests/functional/0001-parachains-pvf.toml -``` - -- You can pick a validator node like `alice` from the output and view its logs -(`tail -f `) or metrics. Make sure there is nothing funny in the logs -(try `grep WARN `). +This assumes a simplistic test runtime. #### Testing at scale (4) @@ -72,27 +41,13 @@ addition prometheus avoiding additional Polkadot source changes. _Behavior tests_ and _testing at scale_ have naturally soft boundary. The most significant difference is the presence of a real network and the number of nodes, since a single host often not capable to run multiple nodes at once. -## Observing Logs - -To verify expected behavior it's often useful to observe logs. To avoid too many -logs at once, you can run one test at a time: - -1. Add `sp_tracing::try_init_simple();` to the beginning of a test -2. Specify `RUST_LOG=::=trace` before the cargo command. - -For example: - -```sh -RUST_LOG=parachain::pvf=trace cargo test execute_can_run_serially -``` - -For more info on how our logs work, check [the docs][logs]. +--- ## Coverage Coverage gives a _hint_ of the actually covered source lines by tests and test applications. -The state of the art is currently tarpaulin which unfortunately yields a lot of false negatives. Lines that +The state of the art is currently [tarpaulin][tarpaulin] which unfortunately yields a lot of false negatives. Lines that are in fact covered, marked as uncovered due to a mere linebreak in a statement can cause these artifacts. This leads to lower coverage percentages than there actually is. @@ -147,7 +102,7 @@ Fuzzing is an approach to verify correctness against arbitrary or partially stru Currently implemented fuzzing targets: -- `erasure-coding` +* `erasure-coding` The tooling of choice here is `honggfuzz-rs` as it allows _fastest_ coverage according to "some paper" which is a positive feature when run as part of PRs. @@ -158,16 +113,16 @@ hence simply not feasible due to the amount of state that is required. Other candidates to implement fuzzing are: -- `rpc` -- ... +* `rpc` +* ... ## Performance metrics There are various ways of performance metrics. -- timing with `criterion` -- cache hits/misses w/ `iai` harness or `criterion-perf` -- `coz` a performance based compiler +* timing with `criterion` +* cache hits/misses w/ `iai` harness or `criterion-perf` +* `coz` a performance based compiler Most of them are standard tools to aid in the creation of statistical tests regarding change in time of certain unit tests. @@ -185,10 +140,10 @@ pursued at the current time. Requirements: -- spawn nodes with preconfigured behaviors -- allow multiple types of configuration to be specified -- allow extendability via external crates -- ... +* spawn nodes with preconfigured behaviors +* allow multiple types of configuration to be specified +* allow extendability via external crates +* ... --- @@ -296,7 +251,5 @@ behavior_testcase!{ } ``` -[zombienet]: https://github.com/paritytech/zombienet [Gurke]: https://github.com/paritytech/gurke [simnet]: https://github.com/paritytech/simnet_scripts -[logs]: https://github.com/paritytech/polkadot-sdk/blob/master/polkadot/node/gum/src/lib.rs diff --git a/polkadot/erasure-coding/Cargo.toml b/polkadot/erasure-coding/Cargo.toml index f174f8ad0cf..ccfe7f14eb4 100644 --- a/polkadot/erasure-coding/Cargo.toml +++ b/polkadot/erasure-coding/Cargo.toml @@ -6,14 +6,11 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] polkadot-primitives = { path = "../primitives" } polkadot-node-primitives = { package = "polkadot-node-primitives", path = "../node/primitives" } novelpoly = { package = "reed-solomon-novelpoly", version = "1.0.0" } -parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive", "std"] } +parity-scale-codec = { version = "3.6.1", default-features = false, features = ["std", "derive"] } sp-core = { path = "../../substrate/primitives/core" } sp-trie = { path = "../../substrate/primitives/trie" } thiserror = "1.0.48" diff --git a/polkadot/erasure-coding/fuzzer/Cargo.toml b/polkadot/erasure-coding/fuzzer/Cargo.toml index 4e5ef9d229d..862b148cc5b 100644 --- a/polkadot/erasure-coding/fuzzer/Cargo.toml +++ b/polkadot/erasure-coding/fuzzer/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true publish = false -[lints] -workspace = true - [dependencies] polkadot-erasure-coding = { path = ".." } honggfuzz = "0.5" diff --git a/polkadot/node/collation-generation/Cargo.toml b/polkadot/node/collation-generation/Cargo.toml index 366c08a6c67..c1848f47fc6 100644 --- a/polkadot/node/collation-generation/Cargo.toml +++ b/polkadot/node/collation-generation/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "Collator-side subsystem that handles incoming candidate submissions from the parachain." -[lints] -workspace = true - [dependencies] futures = "0.3.21" gum = { package = "tracing-gum", path = "../gum" } @@ -18,7 +15,7 @@ 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" } +sp-maybe-compressed-blob = { path = "../../../substrate/primitives/maybe-compressed-blob" } thiserror = "1.0.48" parity-scale-codec = { version = "3.6.1", default-features = false, features = ["bit-vec", "derive"] } diff --git a/polkadot/node/core/approval-voting/Cargo.toml b/polkadot/node/core/approval-voting/Cargo.toml index 61a1e84dd6f..59a6708f17e 100644 --- a/polkadot/node/core/approval-voting/Cargo.toml +++ b/polkadot/node/core/approval-voting/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "Approval Voting Subsystem of the Polkadot node" -[lints] -workspace = true - [dependencies] futures = "0.3.21" futures-timer = "3.0.2" @@ -42,8 +39,7 @@ rand = "0.8.5" [dev-dependencies] async-trait = "0.1.57" parking_lot = "0.12.0" -# rand_core should match schnorrkel -rand_core = "0.5.1" +rand_core = "0.5.1" # should match schnorrkel sp-keyring = { path = "../../../../substrate/primitives/keyring" } sp-keystore = { path = "../../../../substrate/primitives/keystore" } sp-core = { path = "../../../../substrate/primitives/core" } diff --git a/polkadot/node/core/approval-voting/src/approval_checking.rs b/polkadot/node/core/approval-voting/src/approval_checking.rs index 0aa6102fbd6..5d24ff16419 100644 --- a/polkadot/node/core/approval-voting/src/approval_checking.rs +++ b/polkadot/node/core/approval-voting/src/approval_checking.rs @@ -25,15 +25,6 @@ use crate::{ time::Tick, }; -/// Result of counting the necessary tranches needed for approving a block. -#[derive(Debug, PartialEq, Clone)] -pub struct TranchesToApproveResult { - /// The required tranches for approving this block - pub required_tranches: RequiredTranches, - /// The total number of no_shows at the moment we are doing the counting. - pub total_observed_no_shows: usize, -} - /// The required tranches of assignments needed to determine whether a candidate is approved. #[derive(Debug, PartialEq, Clone)] pub enum RequiredTranches { @@ -73,7 +64,7 @@ pub enum RequiredTranches { } /// The result of a check. -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, Copy)] pub enum Check { /// The candidate is unapproved. Unapproved, @@ -187,7 +178,6 @@ struct State { next_no_show: Option, /// The last tick at which a considered assignment was received. last_assignment_tick: Option, - total_observed_no_shows: usize, } impl State { @@ -197,53 +187,41 @@ impl State { needed_approvals: usize, n_validators: usize, no_show_duration: Tick, - ) -> TranchesToApproveResult { + ) -> RequiredTranches { let covering = if self.depth == 0 { 0 } else { self.covering }; if self.depth != 0 && self.assignments + covering + self.uncovered >= n_validators { - return TranchesToApproveResult { - required_tranches: RequiredTranches::All, - total_observed_no_shows: self.total_observed_no_shows, - } + return RequiredTranches::All } // If we have enough assignments and all no-shows are covered, we have reached the number // of tranches that we need to have. if self.assignments >= needed_approvals && (covering + self.uncovered) == 0 { - return TranchesToApproveResult { - required_tranches: RequiredTranches::Exact { - needed: tranche, - tolerated_missing: self.covered, - next_no_show: self.next_no_show, - last_assignment_tick: self.last_assignment_tick, - }, - total_observed_no_shows: self.total_observed_no_shows, + return RequiredTranches::Exact { + needed: tranche, + tolerated_missing: self.covered, + next_no_show: self.next_no_show, + last_assignment_tick: self.last_assignment_tick, } } // We're pending more assignments and should look at more tranches. let clock_drift = self.clock_drift(no_show_duration); if self.depth == 0 { - TranchesToApproveResult { - required_tranches: RequiredTranches::Pending { - considered: tranche, - next_no_show: self.next_no_show, - // during the initial assignment-gathering phase, we want to accept assignments - // from any tranche. Note that honest validators will still not broadcast their - // assignment until it is time to do so, regardless of this value. - maximum_broadcast: DelayTranche::max_value(), - clock_drift, - }, - total_observed_no_shows: self.total_observed_no_shows, + RequiredTranches::Pending { + considered: tranche, + next_no_show: self.next_no_show, + // during the initial assignment-gathering phase, we want to accept assignments + // from any tranche. Note that honest validators will still not broadcast their + // assignment until it is time to do so, regardless of this value. + maximum_broadcast: DelayTranche::max_value(), + clock_drift, } } else { - TranchesToApproveResult { - required_tranches: RequiredTranches::Pending { - considered: tranche, - next_no_show: self.next_no_show, - maximum_broadcast: tranche + (covering + self.uncovered) as DelayTranche, - clock_drift, - }, - total_observed_no_shows: self.total_observed_no_shows, + RequiredTranches::Pending { + considered: tranche, + next_no_show: self.next_no_show, + maximum_broadcast: tranche + (covering + self.uncovered) as DelayTranche, + clock_drift, } } } @@ -298,7 +276,6 @@ impl State { uncovered, next_no_show, last_assignment_tick, - total_observed_no_shows: self.total_observed_no_shows + new_no_shows, } } } @@ -395,7 +372,7 @@ pub fn tranches_to_approve( block_tick: Tick, no_show_duration: Tick, needed_approvals: usize, -) -> TranchesToApproveResult { +) -> RequiredTranches { let tick_now = tranche_now as Tick + block_tick; let n_validators = approval_entry.n_validators(); @@ -407,7 +384,6 @@ pub fn tranches_to_approve( uncovered: 0, next_no_show: None, last_assignment_tick: None, - total_observed_no_shows: 0, }; // The `ApprovalEntry` doesn't have any data for empty tranches. We still want to iterate over @@ -458,7 +434,7 @@ pub fn tranches_to_approve( let s = s.advance(n_assignments, no_shows, next_no_show, last_assignment_tick); let output = s.output(tranche, needed_approvals, n_validators, no_show_duration); - *state = match output.required_tranches { + *state = match output { RequiredTranches::Exact { .. } | RequiredTranches::All => { // Wipe the state clean so the next iteration of this closure will terminate // the iterator. This guarantees that we can call `last` further down to see @@ -488,17 +464,15 @@ mod tests { #[test] fn pending_is_not_approved() { - let candidate = CandidateEntry::from_v1( - approval_db::v1::CandidateEntry { - candidate: dummy_candidate_receipt(dummy_hash()), - session: 0, - block_assignments: BTreeMap::default(), - approvals: BitVec::default(), - }, - 0, - ); + let candidate = approval_db::v1::CandidateEntry { + candidate: dummy_candidate_receipt(dummy_hash()), + session: 0, + block_assignments: BTreeMap::default(), + approvals: BitVec::default(), + } + .into(); - let approval_entry = approval_db::v3::ApprovalEntry { + let approval_entry = approval_db::v2::ApprovalEntry { tranches: Vec::new(), assigned_validators: BitVec::default(), our_assignment: None, @@ -523,31 +497,29 @@ mod tests { #[test] fn exact_takes_only_assignments_up_to() { - let mut candidate: CandidateEntry = CandidateEntry::from_v1( - approval_db::v1::CandidateEntry { - candidate: dummy_candidate_receipt(dummy_hash()), - session: 0, - block_assignments: BTreeMap::default(), - approvals: bitvec![u8, BitOrderLsb0; 0; 10], - }, - 0, - ); + let mut candidate: CandidateEntry = approval_db::v1::CandidateEntry { + candidate: dummy_candidate_receipt(dummy_hash()), + session: 0, + block_assignments: BTreeMap::default(), + approvals: bitvec![u8, BitOrderLsb0; 0; 10], + } + .into(); for i in 0..3 { candidate.mark_approval(ValidatorIndex(i)); } - let approval_entry = approval_db::v3::ApprovalEntry { + let approval_entry = approval_db::v2::ApprovalEntry { tranches: vec![ - approval_db::v3::TrancheEntry { + approval_db::v2::TrancheEntry { tranche: 0, assignments: (0..2).map(|i| (ValidatorIndex(i), 0.into())).collect(), }, - approval_db::v3::TrancheEntry { + approval_db::v2::TrancheEntry { tranche: 1, assignments: (2..5).map(|i| (ValidatorIndex(i), 1.into())).collect(), }, - approval_db::v3::TrancheEntry { + approval_db::v2::TrancheEntry { tranche: 2, assignments: (5..10).map(|i| (ValidatorIndex(i), 0.into())).collect(), }, @@ -597,31 +569,29 @@ mod tests { #[test] fn one_honest_node_always_approves() { - let mut candidate: CandidateEntry = CandidateEntry::from_v1( - approval_db::v1::CandidateEntry { - candidate: dummy_candidate_receipt(dummy_hash()), - session: 0, - block_assignments: BTreeMap::default(), - approvals: bitvec![u8, BitOrderLsb0; 0; 10], - }, - 0, - ); + let mut candidate: CandidateEntry = approval_db::v1::CandidateEntry { + candidate: dummy_candidate_receipt(dummy_hash()), + session: 0, + block_assignments: BTreeMap::default(), + approvals: bitvec![u8, BitOrderLsb0; 0; 10], + } + .into(); for i in 0..3 { candidate.mark_approval(ValidatorIndex(i)); } - let approval_entry = approval_db::v3::ApprovalEntry { + let approval_entry = approval_db::v2::ApprovalEntry { tranches: vec![ - approval_db::v3::TrancheEntry { + approval_db::v2::TrancheEntry { tranche: 0, assignments: (0..4).map(|i| (ValidatorIndex(i), 0.into())).collect(), }, - approval_db::v3::TrancheEntry { + approval_db::v2::TrancheEntry { tranche: 1, assignments: (4..6).map(|i| (ValidatorIndex(i), 1.into())).collect(), }, - approval_db::v3::TrancheEntry { + approval_db::v2::TrancheEntry { tranche: 2, assignments: (6..10).map(|i| (ValidatorIndex(i), 0.into())).collect(), }, @@ -677,7 +647,7 @@ mod tests { let no_show_duration = 10; let needed_approvals = 4; - let mut approval_entry: ApprovalEntry = approval_db::v3::ApprovalEntry { + let mut approval_entry: ApprovalEntry = approval_db::v2::ApprovalEntry { tranches: Vec::new(), assigned_validators: bitvec![u8, BitOrderLsb0; 0; 5], our_assignment: None, @@ -705,8 +675,7 @@ mod tests { block_tick, no_show_duration, needed_approvals, - ) - .required_tranches, + ), RequiredTranches::Exact { needed: 1, tolerated_missing: 0, @@ -722,7 +691,7 @@ mod tests { let no_show_duration = 10; let needed_approvals = 4; - let mut approval_entry: ApprovalEntry = approval_db::v3::ApprovalEntry { + let mut approval_entry: ApprovalEntry = approval_db::v2::ApprovalEntry { tranches: Vec::new(), assigned_validators: bitvec![u8, BitOrderLsb0; 0; 10], our_assignment: None, @@ -746,8 +715,7 @@ mod tests { block_tick, no_show_duration, needed_approvals, - ) - .required_tranches, + ), RequiredTranches::Pending { considered: 2, next_no_show: Some(block_tick + no_show_duration), @@ -763,7 +731,7 @@ mod tests { let no_show_duration = 10; let needed_approvals = 4; - let mut approval_entry: ApprovalEntry = approval_db::v3::ApprovalEntry { + let mut approval_entry: ApprovalEntry = approval_db::v2::ApprovalEntry { tranches: Vec::new(), assigned_validators: bitvec![u8, BitOrderLsb0; 0; 10], our_assignment: None, @@ -791,8 +759,7 @@ mod tests { block_tick, no_show_duration, needed_approvals, - ) - .required_tranches, + ), RequiredTranches::Pending { considered: 11, next_no_show: None, @@ -809,7 +776,7 @@ mod tests { let needed_approvals = 4; let n_validators = 8; - let mut approval_entry: ApprovalEntry = approval_db::v3::ApprovalEntry { + let mut approval_entry: ApprovalEntry = approval_db::v2::ApprovalEntry { tranches: Vec::new(), assigned_validators: bitvec![u8, BitOrderLsb0; 0; n_validators], our_assignment: None, @@ -840,8 +807,7 @@ mod tests { block_tick, no_show_duration, needed_approvals, - ) - .required_tranches, + ), RequiredTranches::Pending { considered: 1, next_no_show: None, @@ -860,8 +826,7 @@ mod tests { block_tick, no_show_duration, needed_approvals, - ) - .required_tranches, + ), RequiredTranches::Pending { considered: 1, next_no_show: None, @@ -878,7 +843,7 @@ mod tests { let needed_approvals = 4; let n_validators = 8; - let mut approval_entry: ApprovalEntry = approval_db::v3::ApprovalEntry { + let mut approval_entry: ApprovalEntry = approval_db::v2::ApprovalEntry { tranches: Vec::new(), assigned_validators: bitvec![u8, BitOrderLsb0; 0; n_validators], our_assignment: None, @@ -914,8 +879,7 @@ mod tests { block_tick, no_show_duration, needed_approvals, - ) - .required_tranches, + ), RequiredTranches::Exact { needed: 1, tolerated_missing: 0, @@ -934,8 +898,7 @@ mod tests { block_tick, no_show_duration, needed_approvals, - ) - .required_tranches, + ), RequiredTranches::Exact { needed: 2, tolerated_missing: 1, @@ -954,8 +917,7 @@ mod tests { block_tick, no_show_duration, needed_approvals, - ) - .required_tranches, + ), RequiredTranches::Pending { considered: 2, next_no_show: None, @@ -972,7 +934,7 @@ mod tests { let needed_approvals = 4; let n_validators = 8; - let mut approval_entry: ApprovalEntry = approval_db::v3::ApprovalEntry { + let mut approval_entry: ApprovalEntry = approval_db::v2::ApprovalEntry { tranches: Vec::new(), assigned_validators: bitvec![u8, BitOrderLsb0; 0; n_validators], our_assignment: None, @@ -1008,8 +970,7 @@ mod tests { block_tick, no_show_duration, needed_approvals, - ) - .required_tranches, + ), RequiredTranches::Exact { needed: 2, tolerated_missing: 1, @@ -1031,8 +992,7 @@ mod tests { block_tick, no_show_duration, needed_approvals, - ) - .required_tranches, + ), RequiredTranches::Pending { considered: 2, next_no_show: None, @@ -1053,8 +1013,7 @@ mod tests { block_tick, no_show_duration, needed_approvals, - ) - .required_tranches, + ), RequiredTranches::Exact { needed: 3, tolerated_missing: 2, @@ -1070,24 +1029,22 @@ mod tests { let no_show_duration = 10; let needed_approvals = 3; - let mut candidate: CandidateEntry = CandidateEntry::from_v1( - approval_db::v1::CandidateEntry { - candidate: dummy_candidate_receipt(dummy_hash()), - session: 0, - block_assignments: BTreeMap::default(), - approvals: bitvec![u8, BitOrderLsb0; 0; 3], - }, - 0, - ); + let mut candidate: CandidateEntry = approval_db::v1::CandidateEntry { + candidate: dummy_candidate_receipt(dummy_hash()), + session: 0, + block_assignments: BTreeMap::default(), + approvals: bitvec![u8, BitOrderLsb0; 0; 3], + } + .into(); for i in 0..3 { candidate.mark_approval(ValidatorIndex(i)); } - let approval_entry = approval_db::v3::ApprovalEntry { + let approval_entry = approval_db::v2::ApprovalEntry { tranches: vec![ // Assignments with invalid validator indexes. - approval_db::v3::TrancheEntry { + approval_db::v2::TrancheEntry { tranche: 1, assignments: (2..5).map(|i| (ValidatorIndex(i), 1.into())).collect(), }, @@ -1111,8 +1068,7 @@ mod tests { block_tick, no_show_duration, needed_approvals, - ) - .required_tranches, + ), RequiredTranches::Pending { considered: 10, next_no_show: None, @@ -1138,7 +1094,7 @@ mod tests { ]; for test_tranche in test_tranches { - let mut approval_entry: ApprovalEntry = approval_db::v3::ApprovalEntry { + let mut approval_entry: ApprovalEntry = approval_db::v2::ApprovalEntry { tranches: Vec::new(), backing_group: GroupIndex(0), our_assignment: None, @@ -1389,11 +1345,10 @@ mod tests { uncovered: 0, next_no_show: None, last_assignment_tick: None, - total_observed_no_shows: 0, }; assert_eq!( - state.output(0, 10, 10, 20).required_tranches, + state.output(0, 10, 10, 20), RequiredTranches::Pending { considered: 0, next_no_show: None, @@ -1413,11 +1368,10 @@ mod tests { uncovered: 0, next_no_show: None, last_assignment_tick: None, - total_observed_no_shows: 0, }; assert_eq!( - state.output(0, 10, 10, 20).required_tranches, + state.output(0, 10, 10, 20), RequiredTranches::Exact { needed: 0, tolerated_missing: 0, diff --git a/polkadot/node/core/approval-voting/src/approval_db/common/migration_helpers.rs b/polkadot/node/core/approval-voting/src/approval_db/common/migration_helpers.rs deleted file mode 100644 index e21c53e4cac..00000000000 --- a/polkadot/node/core/approval-voting/src/approval_db/common/migration_helpers.rs +++ /dev/null @@ -1,39 +0,0 @@ -// 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 bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec}; - -use polkadot_node_primitives::approval::{ - v1::{AssignmentCert, AssignmentCertKind, VrfProof, VrfSignature, RELAY_VRF_MODULO_CONTEXT}, - v2::VrfPreOutput, -}; -pub fn make_bitvec(len: usize) -> BitVec { - bitvec::bitvec![u8, BitOrderLsb0; 0; len] -} - -pub fn dummy_assignment_cert(kind: AssignmentCertKind) -> AssignmentCert { - let ctx = schnorrkel::signing_context(RELAY_VRF_MODULO_CONTEXT); - let msg = b"test-garbage"; - let mut prng = rand_core::OsRng; - let keypair = schnorrkel::Keypair::generate_with(&mut prng); - let (inout, proof, _) = keypair.vrf_sign(ctx.bytes(msg)); - let out = inout.to_output(); - - AssignmentCert { - kind, - vrf: VrfSignature { pre_output: VrfPreOutput(out), proof: VrfProof(proof) }, - } -} diff --git a/polkadot/node/core/approval-voting/src/approval_db/common/mod.rs b/polkadot/node/core/approval-voting/src/approval_db/common/mod.rs deleted file mode 100644 index 249dcf912df..00000000000 --- a/polkadot/node/core/approval-voting/src/approval_db/common/mod.rs +++ /dev/null @@ -1,293 +0,0 @@ -// 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 . - -//! Common helper functions for all versions of approval-voting database. -use std::sync::Arc; - -use parity_scale_codec::{Decode, Encode}; -use polkadot_node_subsystem::{SubsystemError, SubsystemResult}; -use polkadot_node_subsystem_util::database::{DBTransaction, Database}; -use polkadot_primitives::{BlockNumber, CandidateHash, CandidateIndex, Hash}; - -use crate::{ - backend::{Backend, BackendWriteOp, V1ReadBackend, V2ReadBackend}, - persisted_entries, -}; - -use super::{ - v2::{load_block_entry_v1, load_candidate_entry_v1}, - v3::{load_block_entry_v2, load_candidate_entry_v2, BlockEntry, CandidateEntry}, -}; - -pub mod migration_helpers; - -const STORED_BLOCKS_KEY: &[u8] = b"Approvals_StoredBlocks"; - -/// A range from earliest..last block number stored within the DB. -#[derive(Encode, Decode, Debug, Clone, PartialEq)] -pub struct StoredBlockRange(pub BlockNumber, pub BlockNumber); -/// The database config. -#[derive(Debug, Clone, Copy)] -pub struct Config { - /// The column family in the database where data is stored. - pub col_approval_data: u32, -} - -/// `DbBackend` is a concrete implementation of the higher-level Backend trait -pub struct DbBackend { - inner: Arc, - config: Config, -} - -impl DbBackend { - /// Create a new [`DbBackend`] with the supplied key-value store and - /// config. - pub fn new(db: Arc, config: Config) -> Self { - DbBackend { inner: db, config } - } -} - -/// Errors while accessing things from the DB. -#[derive(Debug, derive_more::From, derive_more::Display)] -pub enum Error { - Io(std::io::Error), - InvalidDecoding(parity_scale_codec::Error), - InternalError(SubsystemError), -} - -impl std::error::Error for Error {} - -/// Result alias for DB errors. -pub type Result = std::result::Result; - -impl Backend for DbBackend { - fn load_block_entry( - &self, - block_hash: &Hash, - ) -> SubsystemResult> { - load_block_entry(&*self.inner, &self.config, block_hash).map(|e| e.map(Into::into)) - } - - fn load_candidate_entry( - &self, - candidate_hash: &CandidateHash, - ) -> SubsystemResult> { - load_candidate_entry(&*self.inner, &self.config, candidate_hash).map(|e| e.map(Into::into)) - } - - fn load_blocks_at_height(&self, block_height: &BlockNumber) -> SubsystemResult> { - load_blocks_at_height(&*self.inner, &self.config, block_height) - } - - fn load_all_blocks(&self) -> SubsystemResult> { - load_all_blocks(&*self.inner, &self.config) - } - - fn load_stored_blocks(&self) -> SubsystemResult> { - load_stored_blocks(&*self.inner, &self.config) - } - - /// Atomically write the list of operations, with later operations taking precedence over prior. - fn write(&mut self, ops: I) -> SubsystemResult<()> - where - I: IntoIterator, - { - let mut tx = DBTransaction::new(); - for op in ops { - match op { - BackendWriteOp::WriteStoredBlockRange(stored_block_range) => { - tx.put_vec( - self.config.col_approval_data, - &STORED_BLOCKS_KEY, - stored_block_range.encode(), - ); - }, - BackendWriteOp::DeleteStoredBlockRange => { - tx.delete(self.config.col_approval_data, &STORED_BLOCKS_KEY); - }, - BackendWriteOp::WriteBlocksAtHeight(h, blocks) => { - tx.put_vec( - self.config.col_approval_data, - &blocks_at_height_key(h), - blocks.encode(), - ); - }, - BackendWriteOp::DeleteBlocksAtHeight(h) => { - tx.delete(self.config.col_approval_data, &blocks_at_height_key(h)); - }, - BackendWriteOp::WriteBlockEntry(block_entry) => { - let block_entry: BlockEntry = block_entry.into(); - tx.put_vec( - self.config.col_approval_data, - &block_entry_key(&block_entry.block_hash), - block_entry.encode(), - ); - }, - BackendWriteOp::DeleteBlockEntry(hash) => { - tx.delete(self.config.col_approval_data, &block_entry_key(&hash)); - }, - BackendWriteOp::WriteCandidateEntry(candidate_entry) => { - let candidate_entry: CandidateEntry = candidate_entry.into(); - tx.put_vec( - self.config.col_approval_data, - &candidate_entry_key(&candidate_entry.candidate.hash()), - candidate_entry.encode(), - ); - }, - BackendWriteOp::DeleteCandidateEntry(candidate_hash) => { - tx.delete(self.config.col_approval_data, &candidate_entry_key(&candidate_hash)); - }, - } - } - - self.inner.write(tx).map_err(|e| e.into()) - } -} - -impl V1ReadBackend for DbBackend { - fn load_candidate_entry_v1( - &self, - candidate_hash: &CandidateHash, - candidate_index: CandidateIndex, - ) -> SubsystemResult> { - load_candidate_entry_v1(&*self.inner, &self.config, candidate_hash) - .map(|e| e.map(|e| persisted_entries::CandidateEntry::from_v1(e, candidate_index))) - } - - fn load_block_entry_v1( - &self, - block_hash: &Hash, - ) -> SubsystemResult> { - load_block_entry_v1(&*self.inner, &self.config, block_hash).map(|e| e.map(Into::into)) - } -} - -impl V2ReadBackend for DbBackend { - fn load_candidate_entry_v2( - &self, - candidate_hash: &CandidateHash, - candidate_index: CandidateIndex, - ) -> SubsystemResult> { - load_candidate_entry_v2(&*self.inner, &self.config, candidate_hash) - .map(|e| e.map(|e| persisted_entries::CandidateEntry::from_v2(e, candidate_index))) - } - - fn load_block_entry_v2( - &self, - block_hash: &Hash, - ) -> SubsystemResult> { - load_block_entry_v2(&*self.inner, &self.config, block_hash).map(|e| e.map(Into::into)) - } -} - -pub(crate) fn load_decode( - store: &dyn Database, - col_approval_data: u32, - key: &[u8], -) -> Result> { - match store.get(col_approval_data, key)? { - None => Ok(None), - Some(raw) => D::decode(&mut &raw[..]).map(Some).map_err(Into::into), - } -} - -/// The key a given block entry is stored under. -pub(crate) fn block_entry_key(block_hash: &Hash) -> [u8; 46] { - const BLOCK_ENTRY_PREFIX: [u8; 14] = *b"Approvals_blck"; - - let mut key = [0u8; 14 + 32]; - key[0..14].copy_from_slice(&BLOCK_ENTRY_PREFIX); - key[14..][..32].copy_from_slice(block_hash.as_ref()); - - key -} - -/// The key a given candidate entry is stored under. -pub(crate) fn candidate_entry_key(candidate_hash: &CandidateHash) -> [u8; 46] { - const CANDIDATE_ENTRY_PREFIX: [u8; 14] = *b"Approvals_cand"; - - let mut key = [0u8; 14 + 32]; - key[0..14].copy_from_slice(&CANDIDATE_ENTRY_PREFIX); - key[14..][..32].copy_from_slice(candidate_hash.0.as_ref()); - - key -} - -/// The key a set of block hashes corresponding to a block number is stored under. -pub(crate) fn blocks_at_height_key(block_number: BlockNumber) -> [u8; 16] { - const BLOCKS_AT_HEIGHT_PREFIX: [u8; 12] = *b"Approvals_at"; - - let mut key = [0u8; 12 + 4]; - key[0..12].copy_from_slice(&BLOCKS_AT_HEIGHT_PREFIX); - block_number.using_encoded(|s| key[12..16].copy_from_slice(s)); - - key -} - -/// Return all blocks which have entries in the DB, ascending, by height. -pub fn load_all_blocks(store: &dyn Database, config: &Config) -> SubsystemResult> { - let mut hashes = Vec::new(); - if let Some(stored_blocks) = load_stored_blocks(store, config)? { - for height in stored_blocks.0..stored_blocks.1 { - let blocks = load_blocks_at_height(store, config, &height)?; - hashes.extend(blocks); - } - } - - Ok(hashes) -} - -/// Load the stored-blocks key from the state. -pub fn load_stored_blocks( - store: &dyn Database, - config: &Config, -) -> SubsystemResult> { - load_decode(store, config.col_approval_data, STORED_BLOCKS_KEY) - .map_err(|e| SubsystemError::with_origin("approval-voting", e)) -} - -/// Load a blocks-at-height entry for a given block number. -pub fn load_blocks_at_height( - store: &dyn Database, - config: &Config, - block_number: &BlockNumber, -) -> SubsystemResult> { - load_decode(store, config.col_approval_data, &blocks_at_height_key(*block_number)) - .map(|x| x.unwrap_or_default()) - .map_err(|e| SubsystemError::with_origin("approval-voting", e)) -} - -/// Load a block entry from the aux store. -pub fn load_block_entry( - store: &dyn Database, - config: &Config, - block_hash: &Hash, -) -> SubsystemResult> { - load_decode(store, config.col_approval_data, &block_entry_key(block_hash)) - .map(|u: Option| u.map(|v| v.into())) - .map_err(|e| SubsystemError::with_origin("approval-voting", e)) -} - -/// Load a candidate entry from the aux store in current version format. -pub fn load_candidate_entry( - store: &dyn Database, - config: &Config, - candidate_hash: &CandidateHash, -) -> SubsystemResult> { - load_decode(store, config.col_approval_data, &candidate_entry_key(candidate_hash)) - .map(|u: Option| u.map(|v| v.into())) - .map_err(|e| SubsystemError::with_origin("approval-voting", e)) -} diff --git a/polkadot/node/core/approval-voting/src/approval_db/mod.rs b/polkadot/node/core/approval-voting/src/approval_db/mod.rs index 78942a507f4..20fb6aa82d8 100644 --- a/polkadot/node/core/approval-voting/src/approval_db/mod.rs +++ b/polkadot/node/core/approval-voting/src/approval_db/mod.rs @@ -30,7 +30,5 @@ //! In the future, we may use a temporary DB which doesn't need to be wiped, but for the //! time being we share the same DB with the rest of Substrate. -pub mod common; pub mod v1; pub mod v2; -pub mod v3; diff --git a/polkadot/node/core/approval-voting/src/approval_db/v1/tests.rs b/polkadot/node/core/approval-voting/src/approval_db/v1/tests.rs index b979cb7ef45..07d8242b772 100644 --- a/polkadot/node/core/approval-voting/src/approval_db/v1/tests.rs +++ b/polkadot/node/core/approval-voting/src/approval_db/v1/tests.rs @@ -40,6 +40,10 @@ fn make_db() -> (DbBackend, Arc) { (DbBackend::new(db_writer.clone(), TEST_CONFIG), db_writer) } +fn make_bitvec(len: usize) -> BitVec { + bitvec::bitvec![u8, BitOrderLsb0; 0; len] +} + fn make_block_entry( block_hash: Hash, parent_hash: Hash, diff --git a/polkadot/node/core/approval-voting/src/approval_db/v2/migration_helpers.rs b/polkadot/node/core/approval-voting/src/approval_db/v2/migration_helpers.rs index df6e4754dbd..74e997c7af8 100644 --- a/polkadot/node/core/approval-voting/src/approval_db/v2/migration_helpers.rs +++ b/polkadot/node/core/approval-voting/src/approval_db/v2/migration_helpers.rs @@ -16,19 +16,25 @@ //! Approval DB migration helpers. use super::*; -use crate::{ - approval_db::common::{ - migration_helpers::{dummy_assignment_cert, make_bitvec}, - Error, Result, StoredBlockRange, - }, - backend::Backend, +use crate::backend::Backend; +use polkadot_node_primitives::approval::v1::{ + AssignmentCert, AssignmentCertKind, VrfOutput, VrfProof, VrfSignature, RELAY_VRF_MODULO_CONTEXT, }; - -use polkadot_node_primitives::approval::v1::AssignmentCertKind; use polkadot_node_subsystem_util::database::Database; use sp_application_crypto::sp_core::H256; use std::{collections::HashSet, sync::Arc}; +fn dummy_assignment_cert(kind: AssignmentCertKind) -> AssignmentCert { + let ctx = schnorrkel::signing_context(RELAY_VRF_MODULO_CONTEXT); + let msg = b"test-garbage"; + let mut prng = rand_core::OsRng; + let keypair = schnorrkel::Keypair::generate_with(&mut prng); + let (inout, proof, _) = keypair.vrf_sign(ctx.bytes(msg)); + let out = inout.to_output(); + + AssignmentCert { kind, vrf: VrfSignature { output: VrfOutput(out), proof: VrfProof(proof) } } +} + fn make_block_entry_v1( block_hash: Hash, parent_hash: Hash, @@ -48,10 +54,14 @@ fn make_block_entry_v1( } } +fn make_bitvec(len: usize) -> BitVec { + bitvec::bitvec![u8, BitOrderLsb0; 0; len] +} + /// Migrates `OurAssignment`, `CandidateEntry` and `ApprovalEntry` to version 2. /// Returns on any error. /// Must only be used in parachains DB migration code - `polkadot-service` crate. -pub fn v1_to_latest(db: Arc, config: Config) -> Result<()> { +pub fn v1_to_v2(db: Arc, config: Config) -> Result<()> { let mut backend = crate::DbBackend::new(db, config); let all_blocks = backend .load_all_blocks() @@ -75,13 +85,11 @@ pub fn v1_to_latest(db: Arc, config: Config) -> Result<()> { let mut counter = 0; // Get all candidate entries, approval entries and convert each of them. for block in all_blocks { - for (candidate_index, (_core_index, candidate_hash)) in - block.candidates().iter().enumerate() - { + for (_core_index, candidate_hash) in block.candidates() { // Loading the candidate will also perform the conversion to the updated format and // return that represantation. if let Some(candidate_entry) = backend - .load_candidate_entry_v1(&candidate_hash, candidate_index as CandidateIndex) + .load_candidate_entry_v1(&candidate_hash) .map_err(|e| Error::InternalError(e))? { // Write the updated representation. @@ -101,8 +109,42 @@ pub fn v1_to_latest(db: Arc, config: Config) -> Result<()> { Ok(()) } +// Checks if the migration doesn't leave the DB in an unsane state. +// This function is to be used in tests. +pub fn v1_to_v2_sanity_check( + db: Arc, + config: Config, + expected_candidates: HashSet, +) -> Result<()> { + let backend = crate::DbBackend::new(db, config); + + let all_blocks = backend + .load_all_blocks() + .unwrap() + .iter() + .map(|block_hash| backend.load_block_entry(block_hash).unwrap().unwrap()) + .collect::>(); + + let mut candidates = HashSet::new(); + + // Iterate all blocks and approval entries. + for block in all_blocks { + for (_core_index, candidate_hash) in block.candidates() { + // Loading the candidate will also perform the conversion to the updated format and + // return that represantation. + if let Some(candidate_entry) = backend.load_candidate_entry(&candidate_hash).unwrap() { + candidates.insert(candidate_entry.candidate.hash()); + } + } + } + + assert_eq!(candidates, expected_candidates); + + Ok(()) +} + // Fills the db with dummy data in v1 scheme. -pub fn v1_fill_test_data( +pub fn v1_to_v2_fill_test_data( db: Arc, config: Config, dummy_candidate_create: F, diff --git a/polkadot/node/core/approval-voting/src/approval_db/v2/mod.rs b/polkadot/node/core/approval-voting/src/approval_db/v2/mod.rs index da42fc5be48..66df6ee8f65 100644 --- a/polkadot/node/core/approval-voting/src/approval_db/v2/mod.rs +++ b/polkadot/node/core/approval-voting/src/approval_db/v2/mod.rs @@ -21,23 +21,145 @@ use polkadot_node_primitives::approval::{v1::DelayTranche, v2::AssignmentCertV2} use polkadot_node_subsystem::{SubsystemError, SubsystemResult}; use polkadot_node_subsystem_util::database::{DBTransaction, Database}; use polkadot_primitives::{ - BlockNumber, CandidateHash, CandidateIndex, CandidateReceipt, CoreIndex, GroupIndex, Hash, - SessionIndex, ValidatorIndex, ValidatorSignature, + BlockNumber, CandidateHash, CandidateReceipt, CoreIndex, GroupIndex, Hash, SessionIndex, + ValidatorIndex, ValidatorSignature, }; use sp_consensus_slots::Slot; use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec}; -use std::collections::BTreeMap; +use std::{collections::BTreeMap, sync::Arc}; -use crate::backend::V1ReadBackend; +use crate::{ + backend::{Backend, BackendWriteOp, V1ReadBackend}, + persisted_entries, +}; -use super::common::{block_entry_key, candidate_entry_key, load_decode, Config}; +const STORED_BLOCKS_KEY: &[u8] = b"Approvals_StoredBlocks"; pub mod migration_helpers; #[cfg(test)] pub mod tests; +/// `DbBackend` is a concrete implementation of the higher-level Backend trait +pub struct DbBackend { + inner: Arc, + config: Config, +} + +impl DbBackend { + /// Create a new [`DbBackend`] with the supplied key-value store and + /// config. + pub fn new(db: Arc, config: Config) -> Self { + DbBackend { inner: db, config } + } +} + +impl V1ReadBackend for DbBackend { + fn load_candidate_entry_v1( + &self, + candidate_hash: &CandidateHash, + ) -> SubsystemResult> { + load_candidate_entry_v1(&*self.inner, &self.config, candidate_hash) + .map(|e| e.map(Into::into)) + } + + fn load_block_entry_v1( + &self, + block_hash: &Hash, + ) -> SubsystemResult> { + load_block_entry_v1(&*self.inner, &self.config, block_hash).map(|e| e.map(Into::into)) + } +} + +impl Backend for DbBackend { + fn load_block_entry( + &self, + block_hash: &Hash, + ) -> SubsystemResult> { + load_block_entry(&*self.inner, &self.config, block_hash).map(|e| e.map(Into::into)) + } + + fn load_candidate_entry( + &self, + candidate_hash: &CandidateHash, + ) -> SubsystemResult> { + load_candidate_entry(&*self.inner, &self.config, candidate_hash).map(|e| e.map(Into::into)) + } + + fn load_blocks_at_height(&self, block_height: &BlockNumber) -> SubsystemResult> { + load_blocks_at_height(&*self.inner, &self.config, block_height) + } + + fn load_all_blocks(&self) -> SubsystemResult> { + load_all_blocks(&*self.inner, &self.config) + } + + fn load_stored_blocks(&self) -> SubsystemResult> { + load_stored_blocks(&*self.inner, &self.config) + } + + /// Atomically write the list of operations, with later operations taking precedence over prior. + fn write(&mut self, ops: I) -> SubsystemResult<()> + where + I: IntoIterator, + { + let mut tx = DBTransaction::new(); + for op in ops { + match op { + BackendWriteOp::WriteStoredBlockRange(stored_block_range) => { + tx.put_vec( + self.config.col_approval_data, + &STORED_BLOCKS_KEY, + stored_block_range.encode(), + ); + }, + BackendWriteOp::DeleteStoredBlockRange => { + tx.delete(self.config.col_approval_data, &STORED_BLOCKS_KEY); + }, + BackendWriteOp::WriteBlocksAtHeight(h, blocks) => { + tx.put_vec( + self.config.col_approval_data, + &blocks_at_height_key(h), + blocks.encode(), + ); + }, + BackendWriteOp::DeleteBlocksAtHeight(h) => { + tx.delete(self.config.col_approval_data, &blocks_at_height_key(h)); + }, + BackendWriteOp::WriteBlockEntry(block_entry) => { + let block_entry: BlockEntry = block_entry.into(); + tx.put_vec( + self.config.col_approval_data, + &block_entry_key(&block_entry.block_hash), + block_entry.encode(), + ); + }, + BackendWriteOp::DeleteBlockEntry(hash) => { + tx.delete(self.config.col_approval_data, &block_entry_key(&hash)); + }, + BackendWriteOp::WriteCandidateEntry(candidate_entry) => { + let candidate_entry: CandidateEntry = candidate_entry.into(); + tx.put_vec( + self.config.col_approval_data, + &candidate_entry_key(&candidate_entry.candidate.hash()), + candidate_entry.encode(), + ); + }, + BackendWriteOp::DeleteCandidateEntry(candidate_hash) => { + tx.delete(self.config.col_approval_data, &candidate_entry_key(&candidate_hash)); + }, + } + } + + self.inner.write(tx).map_err(|e| e.into()) + } +} + +/// A range from earliest..last block number stored within the DB. +#[derive(Encode, Decode, Debug, Clone, PartialEq)] +pub struct StoredBlockRange(pub BlockNumber, pub BlockNumber); + // slot_duration * 2 + DelayTranche gives the number of delay tranches since the // unix epoch. #[derive(Encode, Decode, Clone, Copy, Debug, PartialEq)] @@ -46,6 +168,13 @@ pub struct Tick(u64); /// Convenience type definition pub type Bitfield = BitVec; +/// The database config. +#[derive(Debug, Clone, Copy)] +pub struct Config { + /// The column family in the database where data is stored. + pub col_approval_data: u32, +} + /// Details pertaining to our assignment on a block. #[derive(Encode, Decode, Debug, Clone, PartialEq)] pub struct OurAssignment { @@ -130,6 +259,118 @@ impl From for crate::Tick { } } +/// Errors while accessing things from the DB. +#[derive(Debug, derive_more::From, derive_more::Display)] +pub enum Error { + Io(std::io::Error), + InvalidDecoding(parity_scale_codec::Error), + InternalError(SubsystemError), +} + +impl std::error::Error for Error {} + +/// Result alias for DB errors. +pub type Result = std::result::Result; + +pub(crate) fn load_decode( + store: &dyn Database, + col_approval_data: u32, + key: &[u8], +) -> Result> { + match store.get(col_approval_data, key)? { + None => Ok(None), + Some(raw) => D::decode(&mut &raw[..]).map(Some).map_err(Into::into), + } +} + +/// The key a given block entry is stored under. +pub(crate) fn block_entry_key(block_hash: &Hash) -> [u8; 46] { + const BLOCK_ENTRY_PREFIX: [u8; 14] = *b"Approvals_blck"; + + let mut key = [0u8; 14 + 32]; + key[0..14].copy_from_slice(&BLOCK_ENTRY_PREFIX); + key[14..][..32].copy_from_slice(block_hash.as_ref()); + + key +} + +/// The key a given candidate entry is stored under. +pub(crate) fn candidate_entry_key(candidate_hash: &CandidateHash) -> [u8; 46] { + const CANDIDATE_ENTRY_PREFIX: [u8; 14] = *b"Approvals_cand"; + + let mut key = [0u8; 14 + 32]; + key[0..14].copy_from_slice(&CANDIDATE_ENTRY_PREFIX); + key[14..][..32].copy_from_slice(candidate_hash.0.as_ref()); + + key +} + +/// The key a set of block hashes corresponding to a block number is stored under. +pub(crate) fn blocks_at_height_key(block_number: BlockNumber) -> [u8; 16] { + const BLOCKS_AT_HEIGHT_PREFIX: [u8; 12] = *b"Approvals_at"; + + let mut key = [0u8; 12 + 4]; + key[0..12].copy_from_slice(&BLOCKS_AT_HEIGHT_PREFIX); + block_number.using_encoded(|s| key[12..16].copy_from_slice(s)); + + key +} + +/// Return all blocks which have entries in the DB, ascending, by height. +pub fn load_all_blocks(store: &dyn Database, config: &Config) -> SubsystemResult> { + let mut hashes = Vec::new(); + if let Some(stored_blocks) = load_stored_blocks(store, config)? { + for height in stored_blocks.0..stored_blocks.1 { + let blocks = load_blocks_at_height(store, config, &height)?; + hashes.extend(blocks); + } + } + + Ok(hashes) +} + +/// Load the stored-blocks key from the state. +pub fn load_stored_blocks( + store: &dyn Database, + config: &Config, +) -> SubsystemResult> { + load_decode(store, config.col_approval_data, STORED_BLOCKS_KEY) + .map_err(|e| SubsystemError::with_origin("approval-voting", e)) +} + +/// Load a blocks-at-height entry for a given block number. +pub fn load_blocks_at_height( + store: &dyn Database, + config: &Config, + block_number: &BlockNumber, +) -> SubsystemResult> { + load_decode(store, config.col_approval_data, &blocks_at_height_key(*block_number)) + .map(|x| x.unwrap_or_default()) + .map_err(|e| SubsystemError::with_origin("approval-voting", e)) +} + +/// Load a block entry from the aux store. +pub fn load_block_entry( + store: &dyn Database, + config: &Config, + block_hash: &Hash, +) -> SubsystemResult> { + load_decode(store, config.col_approval_data, &block_entry_key(block_hash)) + .map(|u: Option| u.map(|v| v.into())) + .map_err(|e| SubsystemError::with_origin("approval-voting", e)) +} + +/// Load a candidate entry from the aux store in current version format. +pub fn load_candidate_entry( + store: &dyn Database, + config: &Config, + candidate_hash: &CandidateHash, +) -> SubsystemResult> { + load_decode(store, config.col_approval_data, &candidate_entry_key(candidate_hash)) + .map(|u: Option| u.map(|v| v.into())) + .map_err(|e| SubsystemError::with_origin("approval-voting", e)) +} + /// Load a candidate entry from the aux store in v1 format. pub fn load_candidate_entry_v1( store: &dyn Database, diff --git a/polkadot/node/core/approval-voting/src/approval_db/v2/tests.rs b/polkadot/node/core/approval-voting/src/approval_db/v2/tests.rs index 6021b44c276..50a5a924ca8 100644 --- a/polkadot/node/core/approval-voting/src/approval_db/v2/tests.rs +++ b/polkadot/node/core/approval-voting/src/approval_db/v2/tests.rs @@ -16,22 +16,13 @@ //! Tests for the aux-schema of approval voting. +use super::{DbBackend, StoredBlockRange, *}; use crate::{ - approval_db::{ - common::{migration_helpers::make_bitvec, DbBackend, StoredBlockRange, *}, - v2::*, - v3::{load_block_entry_v2, load_candidate_entry_v2}, - }, backend::{Backend, OverlayedBackend}, ops::{add_block_entry, canonicalize, force_approve, NewCandidateInfo}, }; -use polkadot_primitives::{ - BlockNumber, CandidateHash, CandidateReceipt, CoreIndex, GroupIndex, Hash, -}; - use polkadot_node_subsystem_util::database::Database; use polkadot_primitives::Id as ParaId; -use sp_consensus_slots::Slot; use std::{collections::HashMap, sync::Arc}; use ::test_helpers::{dummy_candidate_receipt, dummy_candidate_receipt_bad_sig, dummy_hash}; @@ -69,6 +60,10 @@ fn make_block_entry( } } +fn make_bitvec(len: usize) -> BitVec { + bitvec::bitvec![u8, BitOrderLsb0; 0; len] +} + fn make_candidate(para_id: ParaId, relay_parent: Hash) -> CandidateReceipt { let mut c = dummy_candidate_receipt(dummy_hash()); @@ -115,10 +110,7 @@ fn read_write() { overlay_db.write_stored_block_range(range.clone()); overlay_db.write_blocks_at_height(1, at_height.clone()); overlay_db.write_block_entry(block_entry.clone().into()); - overlay_db.write_candidate_entry(crate::persisted_entries::CandidateEntry::from_v2( - candidate_entry.clone(), - 0, - )); + overlay_db.write_candidate_entry(candidate_entry.clone().into()); let write_ops = overlay_db.into_write_ops(); db.write(write_ops).unwrap(); @@ -126,11 +118,11 @@ fn read_write() { assert_eq!(load_stored_blocks(store.as_ref(), &TEST_CONFIG).unwrap(), Some(range)); assert_eq!(load_blocks_at_height(store.as_ref(), &TEST_CONFIG, &1).unwrap(), at_height); assert_eq!( - load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &hash_a).unwrap(), + load_block_entry(store.as_ref(), &TEST_CONFIG, &hash_a).unwrap(), Some(block_entry.into()) ); assert_eq!( - load_candidate_entry_v2(store.as_ref(), &TEST_CONFIG, &candidate_hash).unwrap(), + load_candidate_entry(store.as_ref(), &TEST_CONFIG, &candidate_hash).unwrap(), Some(candidate_entry.into()), ); @@ -142,8 +134,8 @@ fn read_write() { db.write(write_ops).unwrap(); assert!(load_blocks_at_height(store.as_ref(), &TEST_CONFIG, &1).unwrap().is_empty()); - assert!(load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &hash_a).unwrap().is_none()); - assert!(load_candidate_entry_v2(store.as_ref(), &TEST_CONFIG, &candidate_hash) + assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &hash_a).unwrap().is_none()); + assert!(load_candidate_entry(store.as_ref(), &TEST_CONFIG, &candidate_hash) .unwrap() .is_none()); } @@ -204,27 +196,25 @@ fn add_block_entry_works() { db.write(write_ops).unwrap(); assert_eq!( - load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &block_hash_a).unwrap(), + load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_a).unwrap(), Some(block_entry_a.into()) ); assert_eq!( - load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &block_hash_b).unwrap(), + load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_b).unwrap(), Some(block_entry_b.into()) ); - let candidate_entry_a = - load_candidate_entry_v2(store.as_ref(), &TEST_CONFIG, &candidate_hash_a) - .unwrap() - .unwrap(); + let candidate_entry_a = load_candidate_entry(store.as_ref(), &TEST_CONFIG, &candidate_hash_a) + .unwrap() + .unwrap(); assert_eq!( candidate_entry_a.block_assignments.keys().collect::>(), vec![&block_hash_a, &block_hash_b] ); - let candidate_entry_b = - load_candidate_entry_v2(store.as_ref(), &TEST_CONFIG, &candidate_hash_b) - .unwrap() - .unwrap(); + let candidate_entry_b = load_candidate_entry(store.as_ref(), &TEST_CONFIG, &candidate_hash_b) + .unwrap() + .unwrap(); assert_eq!(candidate_entry_b.block_assignments.keys().collect::>(), vec![&block_hash_b]); } @@ -253,11 +243,11 @@ fn add_block_entry_adds_child() { block_entry_a.children.push(block_hash_b); assert_eq!( - load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &block_hash_a).unwrap(), + load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_a).unwrap(), Some(block_entry_a.into()) ); assert_eq!( - load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &block_hash_b).unwrap(), + load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_b).unwrap(), Some(block_entry_b.into()) ); } @@ -375,15 +365,13 @@ fn canonicalize_works() { for (c_hash, in_blocks) in expected { let (entry, in_blocks) = match in_blocks { None => { - assert!(load_candidate_entry_v2(store.as_ref(), &TEST_CONFIG, &c_hash) + assert!(load_candidate_entry(store.as_ref(), &TEST_CONFIG, &c_hash) .unwrap() .is_none()); continue }, Some(i) => ( - load_candidate_entry_v2(store.as_ref(), &TEST_CONFIG, &c_hash) - .unwrap() - .unwrap(), + load_candidate_entry(store.as_ref(), &TEST_CONFIG, &c_hash).unwrap().unwrap(), i, ), }; @@ -400,13 +388,13 @@ fn canonicalize_works() { for (hash, with_candidates) in expected { let (entry, with_candidates) = match with_candidates { None => { - assert!(load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &hash) + assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &hash) .unwrap() .is_none()); continue }, Some(i) => - (load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &hash).unwrap().unwrap(), i), + (load_block_entry(store.as_ref(), &TEST_CONFIG, &hash).unwrap().unwrap(), i), }; assert_eq!(entry.candidates.len(), with_candidates.len()); @@ -522,22 +510,22 @@ fn force_approve_works() { let write_ops = overlay_db.into_write_ops(); db.write(write_ops).unwrap(); - assert!(load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &block_hash_a,) + assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_a,) .unwrap() .unwrap() .approved_bitfield .all()); - assert!(load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &block_hash_b,) + assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_b,) .unwrap() .unwrap() .approved_bitfield .all()); - assert!(load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &block_hash_c,) + assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_c,) .unwrap() .unwrap() .approved_bitfield .not_any()); - assert!(load_block_entry_v2(store.as_ref(), &TEST_CONFIG, &block_hash_d,) + assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_d,) .unwrap() .unwrap() .approved_bitfield diff --git a/polkadot/node/core/approval-voting/src/approval_db/v3/migration_helpers.rs b/polkadot/node/core/approval-voting/src/approval_db/v3/migration_helpers.rs deleted file mode 100644 index ad5e89ef3de..00000000000 --- a/polkadot/node/core/approval-voting/src/approval_db/v3/migration_helpers.rs +++ /dev/null @@ -1,237 +0,0 @@ -// 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 . - -//! Approval DB migration helpers. -use super::*; -use crate::{ - approval_db::common::{ - block_entry_key, candidate_entry_key, - migration_helpers::{dummy_assignment_cert, make_bitvec}, - Config, Error, Result, StoredBlockRange, - }, - backend::{Backend, V2ReadBackend}, -}; -use polkadot_node_primitives::approval::v1::AssignmentCertKind; -use polkadot_node_subsystem_util::database::Database; -use sp_application_crypto::sp_core::H256; -use std::{collections::HashSet, sync::Arc}; - -/// Migrates `BlockEntry`, `CandidateEntry`, `ApprovalEntry` and `OurApproval` to version 3. -/// Returns on any error. -/// Must only be used in parachains DB migration code - `polkadot-service` crate. -pub fn v2_to_latest(db: Arc, config: Config) -> Result<()> { - let mut backend = crate::DbBackend::new(db, config); - let all_blocks = backend - .load_all_blocks() - .map_err(|e| Error::InternalError(e))? - .iter() - .filter_map(|block_hash| { - backend - .load_block_entry_v2(block_hash) - .map_err(|e| Error::InternalError(e)) - .ok()? - }) - .collect::>(); - - gum::info!( - target: crate::LOG_TARGET, - "Migrating candidate entries on top of {} blocks", - all_blocks.len() - ); - - let mut overlay = crate::OverlayedBackend::new(&backend); - let mut counter = 0; - // Get all candidate entries, approval entries and convert each of them. - for block in all_blocks { - for (candidate_index, (_core_index, candidate_hash)) in - block.candidates().iter().enumerate() - { - // Loading the candidate will also perform the conversion to the updated format and - // return that represantation. - if let Some(candidate_entry) = backend - .load_candidate_entry_v2(&candidate_hash, candidate_index as CandidateIndex) - .map_err(|e| Error::InternalError(e))? - { - // Write the updated representation. - overlay.write_candidate_entry(candidate_entry); - counter += 1; - } - } - overlay.write_block_entry(block); - } - - gum::info!(target: crate::LOG_TARGET, "Migrated {} entries", counter); - - // Commit all changes to DB. - let write_ops = overlay.into_write_ops(); - backend.write(write_ops).unwrap(); - - Ok(()) -} - -// Checks if the migration doesn't leave the DB in an unsane state. -// This function is to be used in tests. -pub fn v1_to_latest_sanity_check( - db: Arc, - config: Config, - expected_candidates: HashSet, -) -> Result<()> { - let backend = crate::DbBackend::new(db, config); - - let all_blocks = backend - .load_all_blocks() - .unwrap() - .iter() - .map(|block_hash| backend.load_block_entry(block_hash).unwrap().unwrap()) - .collect::>(); - - let mut candidates = HashSet::new(); - - // Iterate all blocks and approval entries. - for block in all_blocks { - for (_core_index, candidate_hash) in block.candidates() { - // Loading the candidate will also perform the conversion to the updated format and - // return that represantation. - if let Some(candidate_entry) = backend.load_candidate_entry(&candidate_hash).unwrap() { - candidates.insert(candidate_entry.candidate.hash()); - } - } - } - - assert_eq!(candidates, expected_candidates); - - Ok(()) -} - -// Fills the db with dummy data in v2 scheme. -pub fn v2_fill_test_data( - db: Arc, - config: Config, - dummy_candidate_create: F, -) -> Result> -where - F: Fn(H256) -> CandidateReceipt, -{ - let mut backend = crate::DbBackend::new(db.clone(), config); - let mut overlay_db = crate::OverlayedBackend::new(&backend); - let mut expected_candidates = HashSet::new(); - - const RELAY_BLOCK_COUNT: u32 = 10; - - let range = StoredBlockRange(1, 11); - overlay_db.write_stored_block_range(range.clone()); - - for relay_number in 1..=RELAY_BLOCK_COUNT { - let relay_hash = Hash::repeat_byte(relay_number as u8); - let assignment_core_index = CoreIndex(relay_number); - let candidate = dummy_candidate_create(relay_hash); - let candidate_hash = candidate.hash(); - - let at_height = vec![relay_hash]; - - let block_entry = make_block_entry_v2( - relay_hash, - Default::default(), - relay_number, - vec![(assignment_core_index, candidate_hash)], - ); - - let dummy_assignment = crate::approval_db::v2::OurAssignment { - cert: dummy_assignment_cert(AssignmentCertKind::RelayVRFModulo { sample: 0 }).into(), - tranche: 0, - validator_index: ValidatorIndex(0), - triggered: false, - }; - - let candidate_entry = crate::approval_db::v2::CandidateEntry { - candidate, - session: 123, - block_assignments: vec![( - relay_hash, - crate::approval_db::v2::ApprovalEntry { - tranches: Vec::new(), - backing_group: GroupIndex(1), - our_assignment: Some(dummy_assignment), - our_approval_sig: None, - approved: false, - assigned_validators: make_bitvec(1), - }, - )] - .into_iter() - .collect(), - approvals: Default::default(), - }; - - overlay_db.write_blocks_at_height(relay_number, at_height.clone()); - expected_candidates.insert(candidate_entry.candidate.hash()); - - db.write(write_candidate_entry_v2(candidate_entry, config)).unwrap(); - db.write(write_block_entry_v2(block_entry, config)).unwrap(); - } - - let write_ops = overlay_db.into_write_ops(); - backend.write(write_ops).unwrap(); - - Ok(expected_candidates) -} - -fn make_block_entry_v2( - block_hash: Hash, - parent_hash: Hash, - block_number: BlockNumber, - candidates: Vec<(CoreIndex, CandidateHash)>, -) -> crate::approval_db::v2::BlockEntry { - crate::approval_db::v2::BlockEntry { - block_hash, - parent_hash, - block_number, - session: 1, - slot: Slot::from(1), - relay_vrf_story: [0u8; 32], - approved_bitfield: make_bitvec(candidates.len()), - distributed_assignments: make_bitvec(candidates.len()), - candidates, - children: Vec::new(), - } -} - -// Low level DB helper to write a candidate entry in v1 scheme. -fn write_candidate_entry_v2( - candidate_entry: crate::approval_db::v2::CandidateEntry, - config: Config, -) -> DBTransaction { - let mut tx = DBTransaction::new(); - tx.put_vec( - config.col_approval_data, - &candidate_entry_key(&candidate_entry.candidate.hash()), - candidate_entry.encode(), - ); - tx -} - -// Low level DB helper to write a block entry in v1 scheme. -fn write_block_entry_v2( - block_entry: crate::approval_db::v2::BlockEntry, - config: Config, -) -> DBTransaction { - let mut tx = DBTransaction::new(); - tx.put_vec( - config.col_approval_data, - &block_entry_key(&block_entry.block_hash), - block_entry.encode(), - ); - tx -} diff --git a/polkadot/node/core/approval-voting/src/approval_db/v3/mod.rs b/polkadot/node/core/approval-voting/src/approval_db/v3/mod.rs deleted file mode 100644 index 3e4f4302195..00000000000 --- a/polkadot/node/core/approval-voting/src/approval_db/v3/mod.rs +++ /dev/null @@ -1,137 +0,0 @@ -// 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 . - -//! Version 3 of the DB schema. -//! -//! Version 3 modifies the `our_approval` format of `ApprovalEntry` -//! and adds a new field `pending_signatures` for `BlockEntry` - -use parity_scale_codec::{Decode, Encode}; -use polkadot_node_primitives::approval::v2::CandidateBitfield; -use polkadot_node_subsystem::SubsystemResult; -use polkadot_node_subsystem_util::database::{DBTransaction, Database}; -use polkadot_overseer::SubsystemError; -use polkadot_primitives::{ - BlockNumber, CandidateHash, CandidateIndex, CandidateReceipt, CoreIndex, GroupIndex, Hash, - SessionIndex, ValidatorIndex, ValidatorSignature, -}; - -use sp_consensus_slots::Slot; - -use std::collections::BTreeMap; - -use super::common::{block_entry_key, candidate_entry_key, load_decode, Config}; - -/// Re-export this structs as v3 since they did not change between v2 and v3. -pub use super::v2::{Bitfield, OurAssignment, Tick, TrancheEntry}; - -pub mod migration_helpers; - -#[cfg(test)] -pub mod tests; - -/// Metadata about our approval signature -#[derive(Encode, Decode, Debug, Clone, PartialEq)] -pub struct OurApproval { - /// The signature for the candidates hashes pointed by indices. - pub signature: ValidatorSignature, - /// The indices of the candidates signed in this approval. - pub signed_candidates_indices: CandidateBitfield, -} - -/// Metadata regarding approval of a particular candidate within the context of some -/// particular block. -#[derive(Encode, Decode, Debug, Clone, PartialEq)] -pub struct ApprovalEntry { - pub tranches: Vec, - pub backing_group: GroupIndex, - pub our_assignment: Option, - pub our_approval_sig: Option, - // `n_validators` bits. - pub assigned_validators: Bitfield, - pub approved: bool, -} - -/// Metadata regarding approval of a particular candidate. -#[derive(Encode, Decode, Debug, Clone, PartialEq)] -pub struct CandidateEntry { - pub candidate: CandidateReceipt, - pub session: SessionIndex, - // Assignments are based on blocks, so we need to track assignments separately - // based on the block we are looking at. - pub block_assignments: BTreeMap, - pub approvals: Bitfield, -} - -/// Metadata regarding approval of a particular block, by way of approval of the -/// candidates contained within it. -#[derive(Encode, Decode, Debug, Clone, PartialEq)] -pub struct BlockEntry { - pub block_hash: Hash, - pub block_number: BlockNumber, - pub parent_hash: Hash, - pub session: SessionIndex, - pub slot: Slot, - /// Random bytes derived from the VRF submitted within the block by the block - /// author as a credential and used as input to approval assignment criteria. - pub relay_vrf_story: [u8; 32], - // The candidates included as-of this block and the index of the core they are - // leaving. Sorted ascending by core index. - pub candidates: Vec<(CoreIndex, CandidateHash)>, - // A bitfield where the i'th bit corresponds to the i'th candidate in `candidates`. - // The i'th bit is `true` iff the candidate has been approved in the context of this - // block. The block can be considered approved if the bitfield has all bits set to `true`. - pub approved_bitfield: Bitfield, - pub children: Vec, - // A list of candidates we have checked, but didn't not sign and - // advertise the vote yet. - pub candidates_pending_signature: BTreeMap, - // Assignments we already distributed. A 1 bit means the candidate index for which - // we already have sent out an assignment. We need this to avoid distributing - // multiple core assignments more than once. - pub distributed_assignments: Bitfield, -} - -#[derive(Encode, Decode, Debug, Clone, PartialEq)] -/// Context needed for creating an approval signature for a given candidate. -pub struct CandidateSigningContext { - /// The candidate hash, to be included in the signature. - pub candidate_hash: CandidateHash, - /// The latest tick we have to create and send the approval. - pub sign_no_later_than_tick: Tick, -} - -/// Load a candidate entry from the aux store in v2 format. -pub fn load_candidate_entry_v2( - store: &dyn Database, - config: &Config, - candidate_hash: &CandidateHash, -) -> SubsystemResult> { - load_decode(store, config.col_approval_data, &candidate_entry_key(candidate_hash)) - .map(|u: Option| u.map(|v| v.into())) - .map_err(|e| SubsystemError::with_origin("approval-voting", e)) -} - -/// Load a block entry from the aux store in v2 format. -pub fn load_block_entry_v2( - store: &dyn Database, - config: &Config, - block_hash: &Hash, -) -> SubsystemResult> { - load_decode(store, config.col_approval_data, &block_entry_key(block_hash)) - .map(|u: Option| u.map(|v| v.into())) - .map_err(|e| SubsystemError::with_origin("approval-voting", e)) -} diff --git a/polkadot/node/core/approval-voting/src/approval_db/v3/tests.rs b/polkadot/node/core/approval-voting/src/approval_db/v3/tests.rs deleted file mode 100644 index 08c65461bca..00000000000 --- a/polkadot/node/core/approval-voting/src/approval_db/v3/tests.rs +++ /dev/null @@ -1,575 +0,0 @@ -// 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 . - -//! Tests for the aux-schema of approval voting. - -use crate::{ - approval_db::{ - common::{migration_helpers::make_bitvec, DbBackend, StoredBlockRange, *}, - v3::*, - }, - backend::{Backend, OverlayedBackend}, - ops::{add_block_entry, canonicalize, force_approve, NewCandidateInfo}, -}; -use polkadot_primitives::{ - BlockNumber, CandidateHash, CandidateReceipt, CoreIndex, GroupIndex, Hash, -}; - -use polkadot_node_subsystem_util::database::Database; -use polkadot_primitives::Id as ParaId; -use sp_consensus_slots::Slot; -use std::{collections::HashMap, sync::Arc}; - -use ::test_helpers::{dummy_candidate_receipt, dummy_candidate_receipt_bad_sig, dummy_hash}; - -const DATA_COL: u32 = 0; - -const NUM_COLUMNS: u32 = 1; - -const TEST_CONFIG: Config = Config { col_approval_data: DATA_COL }; - -fn make_db() -> (DbBackend, Arc) { - let db = kvdb_memorydb::create(NUM_COLUMNS); - let db = polkadot_node_subsystem_util::database::kvdb_impl::DbAdapter::new(db, &[]); - let db_writer: Arc = Arc::new(db); - (DbBackend::new(db_writer.clone(), TEST_CONFIG), db_writer) -} - -fn make_block_entry( - block_hash: Hash, - parent_hash: Hash, - block_number: BlockNumber, - candidates: Vec<(CoreIndex, CandidateHash)>, -) -> BlockEntry { - BlockEntry { - block_hash, - parent_hash, - block_number, - session: 1, - slot: Slot::from(1), - relay_vrf_story: [0u8; 32], - approved_bitfield: make_bitvec(candidates.len()), - candidates, - children: Vec::new(), - candidates_pending_signature: Default::default(), - distributed_assignments: Default::default(), - } -} - -fn make_candidate(para_id: ParaId, relay_parent: Hash) -> CandidateReceipt { - let mut c = dummy_candidate_receipt(dummy_hash()); - - c.descriptor.para_id = para_id; - c.descriptor.relay_parent = relay_parent; - - c -} - -#[test] -fn read_write() { - let (mut db, store) = make_db(); - - let hash_a = Hash::repeat_byte(1); - let hash_b = Hash::repeat_byte(2); - let candidate_hash = dummy_candidate_receipt_bad_sig(dummy_hash(), None).hash(); - - let range = StoredBlockRange(10, 20); - let at_height = vec![hash_a, hash_b]; - - let block_entry = - make_block_entry(hash_a, Default::default(), 1, vec![(CoreIndex(0), candidate_hash)]); - - let candidate_entry = CandidateEntry { - candidate: dummy_candidate_receipt_bad_sig(dummy_hash(), None), - session: 5, - block_assignments: vec![( - hash_a, - ApprovalEntry { - tranches: Vec::new(), - backing_group: GroupIndex(1), - our_assignment: None, - our_approval_sig: None, - assigned_validators: Default::default(), - approved: false, - }, - )] - .into_iter() - .collect(), - approvals: Default::default(), - }; - - let mut overlay_db = OverlayedBackend::new(&db); - overlay_db.write_stored_block_range(range.clone()); - overlay_db.write_blocks_at_height(1, at_height.clone()); - overlay_db.write_block_entry(block_entry.clone().into()); - overlay_db.write_candidate_entry(candidate_entry.clone().into()); - - let write_ops = overlay_db.into_write_ops(); - db.write(write_ops).unwrap(); - - assert_eq!(load_stored_blocks(store.as_ref(), &TEST_CONFIG).unwrap(), Some(range)); - assert_eq!(load_blocks_at_height(store.as_ref(), &TEST_CONFIG, &1).unwrap(), at_height); - assert_eq!( - load_block_entry(store.as_ref(), &TEST_CONFIG, &hash_a).unwrap(), - Some(block_entry.into()) - ); - assert_eq!( - load_candidate_entry(store.as_ref(), &TEST_CONFIG, &candidate_hash).unwrap(), - Some(candidate_entry.into()), - ); - - let mut overlay_db = OverlayedBackend::new(&db); - overlay_db.delete_blocks_at_height(1); - overlay_db.delete_block_entry(&hash_a); - overlay_db.delete_candidate_entry(&candidate_hash); - let write_ops = overlay_db.into_write_ops(); - db.write(write_ops).unwrap(); - - assert!(load_blocks_at_height(store.as_ref(), &TEST_CONFIG, &1).unwrap().is_empty()); - assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &hash_a).unwrap().is_none()); - assert!(load_candidate_entry(store.as_ref(), &TEST_CONFIG, &candidate_hash) - .unwrap() - .is_none()); -} - -#[test] -fn add_block_entry_works() { - let (mut db, store) = make_db(); - - let parent_hash = Hash::repeat_byte(1); - let block_hash_a = Hash::repeat_byte(2); - let block_hash_b = Hash::repeat_byte(69); - - let candidate_receipt_a = make_candidate(ParaId::from(1_u32), parent_hash); - let candidate_receipt_b = make_candidate(ParaId::from(2_u32), parent_hash); - - let candidate_hash_a = candidate_receipt_a.hash(); - let candidate_hash_b = candidate_receipt_b.hash(); - - let block_number = 10; - - let block_entry_a = make_block_entry( - block_hash_a, - parent_hash, - block_number, - vec![(CoreIndex(0), candidate_hash_a)], - ); - - let block_entry_b = make_block_entry( - block_hash_b, - parent_hash, - block_number, - vec![(CoreIndex(0), candidate_hash_a), (CoreIndex(1), candidate_hash_b)], - ); - - let n_validators = 10; - - let mut new_candidate_info = HashMap::new(); - new_candidate_info - .insert(candidate_hash_a, NewCandidateInfo::new(candidate_receipt_a, GroupIndex(0), None)); - - let mut overlay_db = OverlayedBackend::new(&db); - add_block_entry(&mut overlay_db, block_entry_a.clone().into(), n_validators, |h| { - new_candidate_info.get(h).map(|x| x.clone()) - }) - .unwrap(); - let write_ops = overlay_db.into_write_ops(); - db.write(write_ops).unwrap(); - - new_candidate_info - .insert(candidate_hash_b, NewCandidateInfo::new(candidate_receipt_b, GroupIndex(1), None)); - - let mut overlay_db = OverlayedBackend::new(&db); - add_block_entry(&mut overlay_db, block_entry_b.clone().into(), n_validators, |h| { - new_candidate_info.get(h).map(|x| x.clone()) - }) - .unwrap(); - let write_ops = overlay_db.into_write_ops(); - db.write(write_ops).unwrap(); - - assert_eq!( - load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_a).unwrap(), - Some(block_entry_a.into()) - ); - assert_eq!( - load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_b).unwrap(), - Some(block_entry_b.into()) - ); - - let candidate_entry_a = load_candidate_entry(store.as_ref(), &TEST_CONFIG, &candidate_hash_a) - .unwrap() - .unwrap(); - assert_eq!( - candidate_entry_a.block_assignments.keys().collect::>(), - vec![&block_hash_a, &block_hash_b] - ); - - let candidate_entry_b = load_candidate_entry(store.as_ref(), &TEST_CONFIG, &candidate_hash_b) - .unwrap() - .unwrap(); - assert_eq!(candidate_entry_b.block_assignments.keys().collect::>(), vec![&block_hash_b]); -} - -#[test] -fn add_block_entry_adds_child() { - let (mut db, store) = make_db(); - - let parent_hash = Hash::repeat_byte(1); - let block_hash_a = Hash::repeat_byte(2); - let block_hash_b = Hash::repeat_byte(69); - - let mut block_entry_a = make_block_entry(block_hash_a, parent_hash, 1, Vec::new()); - - let block_entry_b = make_block_entry(block_hash_b, block_hash_a, 2, Vec::new()); - - let n_validators = 10; - - let mut overlay_db = OverlayedBackend::new(&db); - add_block_entry(&mut overlay_db, block_entry_a.clone().into(), n_validators, |_| None).unwrap(); - - add_block_entry(&mut overlay_db, block_entry_b.clone().into(), n_validators, |_| None).unwrap(); - - let write_ops = overlay_db.into_write_ops(); - db.write(write_ops).unwrap(); - - block_entry_a.children.push(block_hash_b); - - assert_eq!( - load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_a).unwrap(), - Some(block_entry_a.into()) - ); - assert_eq!( - load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_b).unwrap(), - Some(block_entry_b.into()) - ); -} - -#[test] -fn canonicalize_works() { - let (mut db, store) = make_db(); - - // -> B1 -> C1 -> D1 - // A -> B2 -> C2 -> D2 - // - // We'll canonicalize C1. Everytning except D1 should disappear. - // - // Candidates: - // Cand1 in B2 - // Cand2 in C2 - // Cand3 in C2 and D1 - // Cand4 in D1 - // Cand5 in D2 - // Only Cand3 and Cand4 should remain after canonicalize. - - let n_validators = 10; - - let mut overlay_db = OverlayedBackend::new(&db); - overlay_db.write_stored_block_range(StoredBlockRange(1, 5)); - let write_ops = overlay_db.into_write_ops(); - db.write(write_ops).unwrap(); - - let genesis = Hash::repeat_byte(0); - - let block_hash_a = Hash::repeat_byte(1); - let block_hash_b1 = Hash::repeat_byte(2); - let block_hash_b2 = Hash::repeat_byte(3); - let block_hash_c1 = Hash::repeat_byte(4); - let block_hash_c2 = Hash::repeat_byte(5); - let block_hash_d1 = Hash::repeat_byte(6); - let block_hash_d2 = Hash::repeat_byte(7); - - let candidate_receipt_genesis = make_candidate(ParaId::from(1_u32), genesis); - let candidate_receipt_a = make_candidate(ParaId::from(2_u32), block_hash_a); - let candidate_receipt_b = make_candidate(ParaId::from(3_u32), block_hash_a); - let candidate_receipt_b1 = make_candidate(ParaId::from(4_u32), block_hash_b1); - let candidate_receipt_c1 = make_candidate(ParaId::from(5_u32), block_hash_c1); - - let cand_hash_1 = candidate_receipt_genesis.hash(); - let cand_hash_2 = candidate_receipt_a.hash(); - let cand_hash_3 = candidate_receipt_b.hash(); - let cand_hash_4 = candidate_receipt_b1.hash(); - let cand_hash_5 = candidate_receipt_c1.hash(); - - let block_entry_a = make_block_entry(block_hash_a, genesis, 1, Vec::new()); - let block_entry_b1 = make_block_entry(block_hash_b1, block_hash_a, 2, Vec::new()); - let block_entry_b2 = - make_block_entry(block_hash_b2, block_hash_a, 2, vec![(CoreIndex(0), cand_hash_1)]); - let block_entry_c1 = make_block_entry(block_hash_c1, block_hash_b1, 3, Vec::new()); - let block_entry_c2 = make_block_entry( - block_hash_c2, - block_hash_b2, - 3, - vec![(CoreIndex(0), cand_hash_2), (CoreIndex(1), cand_hash_3)], - ); - let block_entry_d1 = make_block_entry( - block_hash_d1, - block_hash_c1, - 4, - vec![(CoreIndex(0), cand_hash_3), (CoreIndex(1), cand_hash_4)], - ); - let block_entry_d2 = - make_block_entry(block_hash_d2, block_hash_c2, 4, vec![(CoreIndex(0), cand_hash_5)]); - - let candidate_info = { - let mut candidate_info = HashMap::new(); - candidate_info.insert( - cand_hash_1, - NewCandidateInfo::new(candidate_receipt_genesis, GroupIndex(1), None), - ); - - candidate_info - .insert(cand_hash_2, NewCandidateInfo::new(candidate_receipt_a, GroupIndex(2), None)); - - candidate_info - .insert(cand_hash_3, NewCandidateInfo::new(candidate_receipt_b, GroupIndex(3), None)); - - candidate_info - .insert(cand_hash_4, NewCandidateInfo::new(candidate_receipt_b1, GroupIndex(4), None)); - - candidate_info - .insert(cand_hash_5, NewCandidateInfo::new(candidate_receipt_c1, GroupIndex(5), None)); - - candidate_info - }; - - // now insert all the blocks. - let blocks = vec![ - block_entry_a.clone(), - block_entry_b1.clone(), - block_entry_b2.clone(), - block_entry_c1.clone(), - block_entry_c2.clone(), - block_entry_d1.clone(), - block_entry_d2.clone(), - ]; - - let mut overlay_db = OverlayedBackend::new(&db); - for block_entry in blocks { - add_block_entry(&mut overlay_db, block_entry.into(), n_validators, |h| { - candidate_info.get(h).map(|x| x.clone()) - }) - .unwrap(); - } - let write_ops = overlay_db.into_write_ops(); - db.write(write_ops).unwrap(); - - let check_candidates_in_store = |expected: Vec<(CandidateHash, Option>)>| { - for (c_hash, in_blocks) in expected { - let (entry, in_blocks) = match in_blocks { - None => { - assert!(load_candidate_entry(store.as_ref(), &TEST_CONFIG, &c_hash) - .unwrap() - .is_none()); - continue - }, - Some(i) => ( - load_candidate_entry(store.as_ref(), &TEST_CONFIG, &c_hash).unwrap().unwrap(), - i, - ), - }; - - assert_eq!(entry.block_assignments.len(), in_blocks.len()); - - for x in in_blocks { - assert!(entry.block_assignments.contains_key(&x)); - } - } - }; - - let check_blocks_in_store = |expected: Vec<(Hash, Option>)>| { - for (hash, with_candidates) in expected { - let (entry, with_candidates) = match with_candidates { - None => { - assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &hash) - .unwrap() - .is_none()); - continue - }, - Some(i) => - (load_block_entry(store.as_ref(), &TEST_CONFIG, &hash).unwrap().unwrap(), i), - }; - - assert_eq!(entry.candidates.len(), with_candidates.len()); - - for x in with_candidates { - assert!(entry.candidates.iter().any(|(_, c)| c == &x)); - } - } - }; - - check_candidates_in_store(vec![ - (cand_hash_1, Some(vec![block_hash_b2])), - (cand_hash_2, Some(vec![block_hash_c2])), - (cand_hash_3, Some(vec![block_hash_c2, block_hash_d1])), - (cand_hash_4, Some(vec![block_hash_d1])), - (cand_hash_5, Some(vec![block_hash_d2])), - ]); - - check_blocks_in_store(vec![ - (block_hash_a, Some(vec![])), - (block_hash_b1, Some(vec![])), - (block_hash_b2, Some(vec![cand_hash_1])), - (block_hash_c1, Some(vec![])), - (block_hash_c2, Some(vec![cand_hash_2, cand_hash_3])), - (block_hash_d1, Some(vec![cand_hash_3, cand_hash_4])), - (block_hash_d2, Some(vec![cand_hash_5])), - ]); - - let mut overlay_db = OverlayedBackend::new(&db); - canonicalize(&mut overlay_db, 3, block_hash_c1).unwrap(); - let write_ops = overlay_db.into_write_ops(); - db.write(write_ops).unwrap(); - - assert_eq!( - load_stored_blocks(store.as_ref(), &TEST_CONFIG).unwrap().unwrap(), - StoredBlockRange(4, 5) - ); - - check_candidates_in_store(vec![ - (cand_hash_1, None), - (cand_hash_2, None), - (cand_hash_3, Some(vec![block_hash_d1])), - (cand_hash_4, Some(vec![block_hash_d1])), - (cand_hash_5, None), - ]); - - check_blocks_in_store(vec![ - (block_hash_a, None), - (block_hash_b1, None), - (block_hash_b2, None), - (block_hash_c1, None), - (block_hash_c2, None), - (block_hash_d1, Some(vec![cand_hash_3, cand_hash_4])), - (block_hash_d2, None), - ]); -} - -#[test] -fn force_approve_works() { - let (mut db, store) = make_db(); - let n_validators = 10; - - let mut overlay_db = OverlayedBackend::new(&db); - overlay_db.write_stored_block_range(StoredBlockRange(1, 4)); - let write_ops = overlay_db.into_write_ops(); - db.write(write_ops).unwrap(); - - let candidate_hash = CandidateHash(Hash::repeat_byte(42)); - let single_candidate_vec = vec![(CoreIndex(0), candidate_hash)]; - let candidate_info = { - let mut candidate_info = HashMap::new(); - candidate_info.insert( - candidate_hash, - NewCandidateInfo::new( - make_candidate(ParaId::from(1_u32), Default::default()), - GroupIndex(1), - None, - ), - ); - - candidate_info - }; - - let block_hash_a = Hash::repeat_byte(1); // 1 - let block_hash_b = Hash::repeat_byte(2); - let block_hash_c = Hash::repeat_byte(3); - let block_hash_d = Hash::repeat_byte(4); // 4 - - let block_entry_a = - make_block_entry(block_hash_a, Default::default(), 1, single_candidate_vec.clone()); - let block_entry_b = - make_block_entry(block_hash_b, block_hash_a, 2, single_candidate_vec.clone()); - let block_entry_c = - make_block_entry(block_hash_c, block_hash_b, 3, single_candidate_vec.clone()); - let block_entry_d = - make_block_entry(block_hash_d, block_hash_c, 4, single_candidate_vec.clone()); - - let blocks = vec![ - block_entry_a.clone(), - block_entry_b.clone(), - block_entry_c.clone(), - block_entry_d.clone(), - ]; - - let mut overlay_db = OverlayedBackend::new(&db); - for block_entry in blocks { - add_block_entry(&mut overlay_db, block_entry.into(), n_validators, |h| { - candidate_info.get(h).map(|x| x.clone()) - }) - .unwrap(); - } - let approved_hashes = force_approve(&mut overlay_db, block_hash_d, 2).unwrap(); - let write_ops = overlay_db.into_write_ops(); - db.write(write_ops).unwrap(); - - assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_a,) - .unwrap() - .unwrap() - .approved_bitfield - .all()); - assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_b,) - .unwrap() - .unwrap() - .approved_bitfield - .all()); - assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_c,) - .unwrap() - .unwrap() - .approved_bitfield - .not_any()); - assert!(load_block_entry(store.as_ref(), &TEST_CONFIG, &block_hash_d,) - .unwrap() - .unwrap() - .approved_bitfield - .not_any()); - assert_eq!(approved_hashes, vec![block_hash_b, block_hash_a]); -} - -#[test] -fn load_all_blocks_works() { - let (mut db, store) = make_db(); - - let parent_hash = Hash::repeat_byte(1); - let block_hash_a = Hash::repeat_byte(2); - let block_hash_b = Hash::repeat_byte(69); - let block_hash_c = Hash::repeat_byte(42); - - let block_number = 10; - - let block_entry_a = make_block_entry(block_hash_a, parent_hash, block_number, vec![]); - - let block_entry_b = make_block_entry(block_hash_b, parent_hash, block_number, vec![]); - - let block_entry_c = make_block_entry(block_hash_c, block_hash_a, block_number + 1, vec![]); - - let n_validators = 10; - - let mut overlay_db = OverlayedBackend::new(&db); - add_block_entry(&mut overlay_db, block_entry_a.clone().into(), n_validators, |_| None).unwrap(); - - // add C before B to test sorting. - add_block_entry(&mut overlay_db, block_entry_c.clone().into(), n_validators, |_| None).unwrap(); - - add_block_entry(&mut overlay_db, block_entry_b.clone().into(), n_validators, |_| None).unwrap(); - - let write_ops = overlay_db.into_write_ops(); - db.write(write_ops).unwrap(); - - assert_eq!( - load_all_blocks(store.as_ref(), &TEST_CONFIG).unwrap(), - vec![block_hash_a, block_hash_b, block_hash_c], - ) -} diff --git a/polkadot/node/core/approval-voting/src/backend.rs b/polkadot/node/core/approval-voting/src/backend.rs index 9ce25334c0f..d98f3c5fd20 100644 --- a/polkadot/node/core/approval-voting/src/backend.rs +++ b/polkadot/node/core/approval-voting/src/backend.rs @@ -22,12 +22,12 @@ //! before any commit to the underlying storage is made. use polkadot_node_subsystem::SubsystemResult; -use polkadot_primitives::{BlockNumber, CandidateHash, CandidateIndex, Hash}; +use polkadot_primitives::{BlockNumber, CandidateHash, Hash}; use std::collections::HashMap; use super::{ - approval_db::common::StoredBlockRange, + approval_db::v2::StoredBlockRange, persisted_entries::{BlockEntry, CandidateEntry}, }; @@ -72,26 +72,12 @@ pub trait V1ReadBackend: Backend { fn load_candidate_entry_v1( &self, candidate_hash: &CandidateHash, - candidate_index: CandidateIndex, ) -> SubsystemResult>; /// Load a block entry from the DB with scheme version 1. fn load_block_entry_v1(&self, block_hash: &Hash) -> SubsystemResult>; } -/// A read only backend to enable db migration from version 2 of DB. -pub trait V2ReadBackend: Backend { - /// Load a candidate entry from the DB with scheme version 1. - fn load_candidate_entry_v2( - &self, - candidate_hash: &CandidateHash, - candidate_index: CandidateIndex, - ) -> SubsystemResult>; - - /// Load a block entry from the DB with scheme version 1. - fn load_block_entry_v2(&self, block_hash: &Hash) -> SubsystemResult>; -} - // Status of block range in the `OverlayedBackend`. #[derive(PartialEq)] enum BlockRangeStatus { diff --git a/polkadot/node/core/approval-voting/src/criteria.rs b/polkadot/node/core/approval-voting/src/criteria.rs index b6ad1971ef6..2bb5a151fe2 100644 --- a/polkadot/node/core/approval-voting/src/criteria.rs +++ b/polkadot/node/core/approval-voting/src/criteria.rs @@ -21,9 +21,7 @@ use parity_scale_codec::{Decode, Encode}; use polkadot_node_primitives::approval::{ self as approval_types, v1::{AssignmentCert, AssignmentCertKind, DelayTranche, RelayVRFStory}, - v2::{ - AssignmentCertKindV2, AssignmentCertV2, CoreBitfield, VrfPreOutput, VrfProof, VrfSignature, - }, + v2::{AssignmentCertKindV2, AssignmentCertV2, CoreBitfield, VrfOutput, VrfProof, VrfSignature}, }; use polkadot_primitives::{ AssignmentId, AssignmentPair, CandidateHash, CoreIndex, GroupIndex, IndexedVec, SessionInfo, @@ -261,7 +259,6 @@ pub(crate) trait AssignmentCriteria { relay_vrf_story: RelayVRFStory, config: &Config, leaving_cores: Vec<(CandidateHash, CoreIndex, GroupIndex)>, - enable_v2_assignments: bool, ) -> HashMap; fn check_assignment_cert( @@ -285,9 +282,8 @@ impl AssignmentCriteria for RealAssignmentCriteria { relay_vrf_story: RelayVRFStory, config: &Config, leaving_cores: Vec<(CandidateHash, CoreIndex, GroupIndex)>, - enable_v2_assignments: bool, ) -> HashMap { - compute_assignments(keystore, relay_vrf_story, config, leaving_cores, enable_v2_assignments) + compute_assignments(keystore, relay_vrf_story, config, leaving_cores, false) } fn check_assignment_cert( @@ -463,7 +459,7 @@ fn compute_relay_vrf_modulo_assignments_v1( let cert = AssignmentCert { kind: AssignmentCertKind::RelayVRFModulo { sample: rvm_sample }, vrf: VrfSignature { - pre_output: VrfPreOutput(vrf_in_out.to_output()), + output: VrfOutput(vrf_in_out.to_output()), proof: VrfProof(vrf_proof), }, }; @@ -543,7 +539,7 @@ fn compute_relay_vrf_modulo_assignments_v2( core_bitfield: assignment_bitfield.clone(), }, vrf: VrfSignature { - pre_output: VrfPreOutput(vrf_in_out.to_output()), + output: VrfOutput(vrf_in_out.to_output()), proof: VrfProof(vrf_proof), }, }; @@ -578,7 +574,7 @@ fn compute_relay_vrf_delay_assignments( let cert = AssignmentCertV2 { kind: AssignmentCertKindV2::RelayVRFDelay { core_index: core }, vrf: VrfSignature { - pre_output: VrfPreOutput(vrf_in_out.to_output()), + output: VrfOutput(vrf_in_out.to_output()), proof: VrfProof(vrf_proof), }, }; @@ -693,7 +689,7 @@ pub(crate) fn check_assignment_cert( } } - let vrf_pre_output = &assignment.vrf.pre_output; + let vrf_output = &assignment.vrf.output; let vrf_proof = &assignment.vrf.proof; let first_claimed_core_index = claimed_core_indices.first_one().expect("Checked above; qed") as u32; @@ -708,7 +704,7 @@ pub(crate) fn check_assignment_cert( let (vrf_in_out, _) = public .vrf_verify_extra( relay_vrf_modulo_transcript_v2(relay_vrf_story), - &vrf_pre_output.0, + &vrf_output.0, &vrf_proof.0, assigned_cores_transcript(core_bitfield), ) @@ -757,7 +753,7 @@ pub(crate) fn check_assignment_cert( let (vrf_in_out, _) = public .vrf_verify_extra( relay_vrf_modulo_transcript_v1(relay_vrf_story, *sample), - &vrf_pre_output.0, + &vrf_output.0, &vrf_proof.0, assigned_core_transcript(CoreIndex(first_claimed_core_index)), ) @@ -795,7 +791,7 @@ pub(crate) fn check_assignment_cert( let (vrf_in_out, _) = public .vrf_verify( relay_vrf_delay_transcript(relay_vrf_story, *core_index), - &vrf_pre_output.0, + &vrf_output.0, &vrf_proof.0, ) .map_err(|_| InvalidAssignment(Reason::VRFDelayOutputMismatch))?; diff --git a/polkadot/node/core/approval-voting/src/import.rs b/polkadot/node/core/approval-voting/src/import.rs index 7a56e9fd112..d7667e8e405 100644 --- a/polkadot/node/core/approval-voting/src/import.rs +++ b/polkadot/node/core/approval-voting/src/import.rs @@ -45,8 +45,8 @@ use polkadot_node_subsystem::{ }; use polkadot_node_subsystem_util::{determine_new_blocks, runtime::RuntimeInfo}; use polkadot_primitives::{ - vstaging::node_features, BlockNumber, CandidateEvent, CandidateHash, CandidateReceipt, - ConsensusLog, CoreIndex, GroupIndex, Hash, Header, SessionIndex, + BlockNumber, CandidateEvent, CandidateHash, CandidateReceipt, ConsensusLog, CoreIndex, + GroupIndex, Hash, Header, SessionIndex, }; use sc_keystore::LocalKeystore; use sp_consensus_slots::Slot; @@ -56,11 +56,11 @@ use futures::{channel::oneshot, prelude::*}; use std::collections::HashMap; -use super::approval_db::v3; +use super::approval_db::v2; use crate::{ backend::{Backend, OverlayedBackend}, criteria::{AssignmentCriteria, OurAssignment}, - get_extended_session_info, get_session_info, + get_session_info, persisted_entries::CandidateEntry, time::{slot_number_to_tick, Tick}, }; @@ -214,21 +214,10 @@ async fn imported_block_info( } }; - let extended_session_info = - get_extended_session_info(env.runtime_info, ctx.sender(), block_hash, session_index).await; - let enable_v2_assignments = extended_session_info.map_or(false, |extended_session_info| { - *extended_session_info - .node_features - .get(node_features::FeatureIndex::EnableAssignmentsV2 as usize) - .as_deref() - .unwrap_or(&false) - }); - let session_info = get_session_info(env.runtime_info, ctx.sender(), block_hash, session_index) .await .ok_or(ImportedBlockInfoError::SessionInfoUnavailable)?; - gum::debug!(target: LOG_TARGET, ?enable_v2_assignments, "V2 assignments"); let (assignments, slot, relay_vrf_story) = { let unsafe_vrf = approval_types::v1::babe_unsafe_vrf_info(&block_header); @@ -250,7 +239,6 @@ async fn imported_block_info( .iter() .map(|(c_hash, _, core, group)| (*c_hash, *core, *group)) .collect(), - enable_v2_assignments, ); (assignments, slot, relay_vrf) @@ -512,7 +500,7 @@ pub(crate) async fn handle_new_head( ctx.send_message(ChainSelectionMessage::Approved(block_hash)).await; } - let block_entry = v3::BlockEntry { + let block_entry = v2::BlockEntry { block_hash, parent_hash: block_header.parent_hash, block_number: block_header.number, @@ -525,7 +513,6 @@ pub(crate) async fn handle_new_head( .collect(), approved_bitfield, children: Vec::new(), - candidates_pending_signature: Default::default(), distributed_assignments: Default::default(), }; @@ -605,10 +592,7 @@ pub(crate) async fn handle_new_head( #[cfg(test)] pub(crate) mod tests { use super::*; - use crate::{ - approval_db::common::{load_block_entry, DbBackend}, - RuntimeInfo, RuntimeInfoConfig, - }; + use crate::{approval_db::v2::DbBackend, RuntimeInfo, RuntimeInfoConfig}; use ::test_helpers::{dummy_candidate_receipt, dummy_hash}; use assert_matches::assert_matches; use polkadot_node_primitives::{ @@ -619,7 +603,6 @@ pub(crate) mod tests { use polkadot_node_subsystem_test_helpers::make_subsystem_context; use polkadot_node_subsystem_util::database::Database; use polkadot_primitives::{ - vstaging::{node_features::FeatureIndex, NodeFeatures}, ExecutorParams, Id as ParaId, IndexedVec, SessionInfo, ValidatorId, ValidatorIndex, }; pub(crate) use sp_consensus_babe::{ @@ -631,7 +614,7 @@ pub(crate) mod tests { pub(crate) use sp_runtime::{Digest, DigestItem}; use std::{pin::Pin, sync::Arc}; - use crate::{approval_db::common::Config as DatabaseConfig, criteria, BlockEntry}; + use crate::{approval_db::v2::Config as DatabaseConfig, criteria, BlockEntry}; const DATA_COL: u32 = 0; @@ -656,7 +639,7 @@ pub(crate) mod tests { keystore: Arc::new(LocalKeystore::in_memory()), slot_duration_millis: 6_000, clock: Box::new(MockClock::default()), - assignment_criteria: Box::new(MockAssignmentCriteria::default()), + assignment_criteria: Box::new(MockAssignmentCriteria), spans: HashMap::new(), } } @@ -671,10 +654,7 @@ pub(crate) mod tests { ) } - #[derive(Default)] - struct MockAssignmentCriteria { - enable_v2: bool, - } + struct MockAssignmentCriteria; impl AssignmentCriteria for MockAssignmentCriteria { fn compute_assignments( @@ -687,9 +667,7 @@ pub(crate) mod tests { polkadot_primitives::CoreIndex, polkadot_primitives::GroupIndex, )>, - enable_assignments_v2: bool, ) -> HashMap { - assert_eq!(enable_assignments_v2, self.enable_v2); HashMap::new() } @@ -733,164 +711,154 @@ pub(crate) mod tests { #[test] fn imported_block_info_is_good() { - for enable_v2 in [false, true] { - let pool = TaskExecutor::new(); - let (mut ctx, mut handle) = - make_subsystem_context::(pool.clone()); - - let session = 5; - let session_info = dummy_session_info(session); - - let slot = Slot::from(10); - let header = Header { - digest: { - let mut d = Digest::default(); - let vrf_signature = garbage_vrf_signature(); - d.push(DigestItem::babe_pre_digest(PreDigest::SecondaryVRF( - SecondaryVRFPreDigest { authority_index: 0, slot, vrf_signature }, - ))); - - d - }, - extrinsics_root: Default::default(), - number: 5, - state_root: Default::default(), - parent_hash: Default::default(), - }; + let pool = TaskExecutor::new(); + let (mut ctx, mut handle) = + make_subsystem_context::(pool.clone()); - let hash = header.hash(); - let make_candidate = |para_id| { - let mut r = dummy_candidate_receipt(dummy_hash()); - r.descriptor.para_id = para_id; - r.descriptor.relay_parent = hash; - r - }; - let candidates = vec![ - (make_candidate(1.into()), CoreIndex(0), GroupIndex(2)), - (make_candidate(2.into()), CoreIndex(1), GroupIndex(3)), - ]; + let session = 5; + let session_info = dummy_session_info(session); + + let slot = Slot::from(10); + + let header = Header { + digest: { + let mut d = Digest::default(); + let vrf_signature = garbage_vrf_signature(); + d.push(DigestItem::babe_pre_digest(PreDigest::SecondaryVRF( + SecondaryVRFPreDigest { authority_index: 0, slot, vrf_signature }, + ))); + + d + }, + extrinsics_root: Default::default(), + number: 5, + state_root: Default::default(), + parent_hash: Default::default(), + }; + + let hash = header.hash(); + let make_candidate = |para_id| { + let mut r = dummy_candidate_receipt(dummy_hash()); + r.descriptor.para_id = para_id; + r.descriptor.relay_parent = hash; + r + }; + let candidates = vec![ + (make_candidate(1.into()), CoreIndex(0), GroupIndex(2)), + (make_candidate(2.into()), CoreIndex(1), GroupIndex(3)), + ]; + + let inclusion_events = candidates + .iter() + .cloned() + .map(|(r, c, g)| CandidateEvent::CandidateIncluded(r, Vec::new().into(), c, g)) + .collect::>(); - let inclusion_events = candidates + let test_fut = { + let included_candidates = candidates .iter() - .cloned() - .map(|(r, c, g)| CandidateEvent::CandidateIncluded(r, Vec::new().into(), c, g)) + .map(|(r, c, g)| (r.hash(), r.clone(), *c, *g)) .collect::>(); - let test_fut = { - let included_candidates = candidates - .iter() - .map(|(r, c, g)| (r.hash(), r.clone(), *c, *g)) - .collect::>(); - - let mut runtime_info = RuntimeInfo::new_with_config(RuntimeInfoConfig { - keystore: None, - session_cache_lru_size: DISPUTE_WINDOW.get(), - }); - - let header = header.clone(); - Box::pin(async move { - let env = ImportedBlockInfoEnv { - runtime_info: &mut runtime_info, - assignment_criteria: &MockAssignmentCriteria { enable_v2 }, - keystore: &LocalKeystore::in_memory(), - }; + let mut runtime_info = RuntimeInfo::new_with_config(RuntimeInfoConfig { + keystore: None, + session_cache_lru_size: DISPUTE_WINDOW.get(), + }); - let info = - imported_block_info(&mut ctx, env, hash, &header, &Some(4)).await.unwrap(); + let header = header.clone(); + Box::pin(async move { + let env = ImportedBlockInfoEnv { + runtime_info: &mut runtime_info, + assignment_criteria: &MockAssignmentCriteria, + keystore: &LocalKeystore::in_memory(), + }; - assert_eq!(info.included_candidates, included_candidates); - assert_eq!(info.session_index, session); - assert!(info.assignments.is_empty()); - assert_eq!(info.n_validators, 0); - assert_eq!(info.slot, slot); - assert!(info.force_approve.is_none()); - }) - }; + let info = + imported_block_info(&mut ctx, env, hash, &header, &Some(4)).await.unwrap(); - let aux_fut = Box::pin(async move { - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - h, - RuntimeApiRequest::CandidateEvents(c_tx), - )) => { - assert_eq!(h, hash); - let _ = c_tx.send(Ok(inclusion_events)); - } - ); + assert_eq!(info.included_candidates, included_candidates); + assert_eq!(info.session_index, session); + assert!(info.assignments.is_empty()); + assert_eq!(info.n_validators, 0); + assert_eq!(info.slot, slot); + assert!(info.force_approve.is_none()); + }) + }; - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - h, - RuntimeApiRequest::SessionIndexForChild(c_tx), - )) => { - assert_eq!(h, header.parent_hash); - let _ = c_tx.send(Ok(session)); - } - ); + let aux_fut = Box::pin(async move { + assert_matches!( + handle.recv().await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + h, + RuntimeApiRequest::CandidateEvents(c_tx), + )) => { + assert_eq!(h, hash); + let _ = c_tx.send(Ok(inclusion_events)); + } + ); - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - h, - RuntimeApiRequest::CurrentBabeEpoch(c_tx), - )) => { - assert_eq!(h, hash); - let _ = c_tx.send(Ok(BabeEpoch { - epoch_index: session as _, - start_slot: Slot::from(0), - duration: 200, - authorities: vec![(Sr25519Keyring::Alice.public().into(), 1)], - randomness: [0u8; 32], - config: BabeEpochConfiguration { - c: (1, 4), - allowed_slots: AllowedSlots::PrimarySlots, - }, - })); - } - ); + assert_matches!( + handle.recv().await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + h, + RuntimeApiRequest::SessionIndexForChild(c_tx), + )) => { + assert_eq!(h, header.parent_hash); + let _ = c_tx.send(Ok(session)); + } + ); - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request( - req_block_hash, - RuntimeApiRequest::SessionInfo(idx, si_tx), - ) - ) => { - assert_eq!(session, idx); - assert_eq!(req_block_hash, hash); - si_tx.send(Ok(Some(session_info.clone()))).unwrap(); - } - ); + assert_matches!( + handle.recv().await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + h, + RuntimeApiRequest::CurrentBabeEpoch(c_tx), + )) => { + assert_eq!(h, hash); + let _ = c_tx.send(Ok(BabeEpoch { + epoch_index: session as _, + start_slot: Slot::from(0), + duration: 200, + authorities: vec![(Sr25519Keyring::Alice.public().into(), 1)], + randomness: [0u8; 32], + config: BabeEpochConfiguration { + c: (1, 4), + allowed_slots: AllowedSlots::PrimarySlots, + }, + })); + } + ); - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request( - req_block_hash, - RuntimeApiRequest::SessionExecutorParams(idx, si_tx), - ) - ) => { - assert_eq!(session, idx); - assert_eq!(req_block_hash, hash); - si_tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); - } - ); + assert_matches!( + handle.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request( + req_block_hash, + RuntimeApiRequest::SessionInfo(idx, si_tx), + ) + ) => { + assert_eq!(session, idx); + assert_eq!(req_block_hash, hash); + si_tx.send(Ok(Some(session_info.clone()))).unwrap(); + } + ); - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::repeat(enable_v2, FeatureIndex::EnableAssignmentsV2 as usize + 1))).unwrap(); - } - ); - }); + assert_matches!( + handle.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request( + req_block_hash, + RuntimeApiRequest::SessionExecutorParams(idx, si_tx), + ) + ) => { + assert_eq!(session, idx); + assert_eq!(req_block_hash, hash); + si_tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); + } + ); + }); - futures::executor::block_on(futures::future::join(test_fut, aux_fut)); - } + futures::executor::block_on(futures::future::join(test_fut, aux_fut)); } #[test] @@ -938,7 +906,7 @@ pub(crate) mod tests { Box::pin(async move { let env = ImportedBlockInfoEnv { runtime_info: &mut runtime_info, - assignment_criteria: &MockAssignmentCriteria::default(), + assignment_criteria: &MockAssignmentCriteria, keystore: &LocalKeystore::in_memory(), }; @@ -1019,15 +987,6 @@ pub(crate) mod tests { si_tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); } ); - - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); }); futures::executor::block_on(futures::future::join(test_fut, aux_fut)); @@ -1077,7 +1036,7 @@ pub(crate) mod tests { Box::pin(async move { let env = ImportedBlockInfoEnv { runtime_info: &mut runtime_info, - assignment_criteria: &MockAssignmentCriteria::default(), + assignment_criteria: &MockAssignmentCriteria, keystore: &LocalKeystore::in_memory(), }; @@ -1175,7 +1134,7 @@ pub(crate) mod tests { Box::pin(async move { let env = ImportedBlockInfoEnv { runtime_info: &mut runtime_info, - assignment_criteria: &MockAssignmentCriteria::default(), + assignment_criteria: &MockAssignmentCriteria, keystore: &LocalKeystore::in_memory(), }; @@ -1262,15 +1221,6 @@ pub(crate) mod tests { si_tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); } ); - - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); }); futures::executor::block_on(futures::future::join(test_fut, aux_fut)); @@ -1351,7 +1301,7 @@ pub(crate) mod tests { let (state, mut session_info_provider) = single_session_state(); overlay_db.write_block_entry( - v3::BlockEntry { + v2::BlockEntry { block_hash: parent_hash, parent_hash: Default::default(), block_number: 4, @@ -1361,7 +1311,6 @@ pub(crate) mod tests { candidates: Vec::new(), approved_bitfield: Default::default(), children: Vec::new(), - candidates_pending_signature: Default::default(), distributed_assignments: Default::default(), } .into(), @@ -1394,10 +1343,11 @@ pub(crate) mod tests { assert_eq!(candidates[1].1.approvals().len(), 6); // the first candidate should be insta-approved // the second should not - let entry: BlockEntry = load_block_entry(db_writer.as_ref(), &TEST_CONFIG, &hash) - .unwrap() - .unwrap() - .into(); + let entry: BlockEntry = + v2::load_block_entry(db_writer.as_ref(), &TEST_CONFIG, &hash) + .unwrap() + .unwrap() + .into(); assert!(entry.is_candidate_approved(&candidates[0].0)); assert!(!entry.is_candidate_approved(&candidates[1].0)); }) @@ -1488,15 +1438,6 @@ pub(crate) mod tests { } ); - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); - assert_matches!( handle.recv().await, AllMessages::ApprovalDistribution(ApprovalDistributionMessage::NewBlocks( diff --git a/polkadot/node/core/approval-voting/src/lib.rs b/polkadot/node/core/approval-voting/src/lib.rs index af76b576d7c..ef01727b7eb 100644 --- a/polkadot/node/core/approval-voting/src/lib.rs +++ b/polkadot/node/core/approval-voting/src/lib.rs @@ -21,15 +21,14 @@ //! of others. It uses this information to determine when candidates and blocks have //! been sufficiently approved to finalize. -use itertools::Itertools; use jaeger::{hash_to_trace_identifier, PerLeafSpan}; use polkadot_node_jaeger as jaeger; use polkadot_node_primitives::{ approval::{ - v1::{BlockApprovalMeta, DelayTranche}, + v1::{BlockApprovalMeta, DelayTranche, IndirectSignedApprovalVote}, v2::{ AssignmentCertKindV2, BitfieldError, CandidateBitfield, CoreBitfield, - IndirectAssignmentCertV2, IndirectSignedApprovalVoteV2, + IndirectAssignmentCertV2, }, }, ValidationResult, DISPUTE_WINDOW, @@ -54,10 +53,9 @@ use polkadot_node_subsystem_util::{ TimeoutExt, }; use polkadot_primitives::{ - vstaging::{ApprovalVoteMultipleCandidates, ApprovalVotingParams}, - BlockNumber, CandidateHash, CandidateIndex, CandidateReceipt, DisputeStatement, ExecutorParams, - GroupIndex, Hash, PvfExecKind, SessionIndex, SessionInfo, ValidDisputeStatementKind, - ValidatorId, ValidatorIndex, ValidatorPair, ValidatorSignature, + ApprovalVote, BlockNumber, CandidateHash, CandidateIndex, CandidateReceipt, DisputeStatement, + ExecutorParams, GroupIndex, Hash, PvfExecKind, SessionIndex, SessionInfo, + ValidDisputeStatementKind, ValidatorId, ValidatorIndex, ValidatorPair, ValidatorSignature, }; use sc_keystore::LocalKeystore; use sp_application_crypto::Pair; @@ -69,11 +67,9 @@ use futures::{ future::{BoxFuture, RemoteHandle}, prelude::*, stream::FuturesUnordered, - StreamExt, }; use std::{ - cmp::min, collections::{ btree_map::Entry as BTMEntry, hash_map::Entry as HMEntry, BTreeMap, HashMap, HashSet, }, @@ -87,7 +83,7 @@ use approval_checking::RequiredTranches; use bitvec::{order::Lsb0, vec::BitVec}; use criteria::{AssignmentCriteria, RealAssignmentCriteria}; use persisted_entries::{ApprovalEntry, BlockEntry, CandidateEntry}; -use time::{slot_number_to_tick, Clock, ClockExt, DelayedApprovalTimer, SystemClock, Tick}; +use time::{slot_number_to_tick, Clock, ClockExt, SystemClock, Tick}; mod approval_checking; pub mod approval_db; @@ -99,11 +95,9 @@ mod persisted_entries; mod time; use crate::{ - approval_checking::{Check, TranchesToApproveResult}, - approval_db::common::{Config as DatabaseConfig, DbBackend}, + approval_db::v2::{Config as DatabaseConfig, DbBackend}, backend::{Backend, OverlayedBackend}, criteria::InvalidAssignmentReason, - persisted_entries::OurApproval, }; #[cfg(test)] @@ -121,9 +115,6 @@ const TICK_TOO_FAR_IN_FUTURE: Tick = 20; // 10 seconds. const APPROVAL_DELAY: Tick = 2; pub(crate) const LOG_TARGET: &str = "parachain::approval-voting"; -// The max number of ticks we delay sending the approval after we are ready to issue the approval -const MAX_APPROVAL_COALESCE_WAIT_TICKS: Tick = 12; - /// Configuration for the approval voting subsystem #[derive(Debug, Clone)] pub struct Config { @@ -167,14 +158,7 @@ struct MetricsInner { assignments_produced: prometheus::Histogram, approvals_produced_total: prometheus::CounterVec, no_shows_total: prometheus::Counter, - // The difference from `no_shows_total` is that this counts all observed no-shows at any - // moment in time. While `no_shows_total` catches that the no-shows at the moment the candidate - // is approved, approvals might arrive late and `no_shows_total` wouldn't catch that number. - observed_no_shows: prometheus::Counter, - approved_by_one_third: prometheus::Counter, wakeups_triggered_total: prometheus::Counter, - coalesced_approvals_buckets: prometheus::Histogram, - coalesced_approvals_delay: prometheus::Histogram, candidate_approval_time_ticks: prometheus::Histogram, block_approval_time_ticks: prometheus::Histogram, time_db_transaction: prometheus::Histogram, @@ -200,22 +184,6 @@ impl Metrics { } } - fn on_approval_coalesce(&self, num_coalesced: u32) { - if let Some(metrics) = &self.0 { - // Count how many candidates we covered with this coalesced approvals, - // so that the heat-map really gives a good understanding of the scales. - for _ in 0..num_coalesced { - metrics.coalesced_approvals_buckets.observe(num_coalesced as f64) - } - } - } - - fn on_delayed_approval(&self, delayed_ticks: u64) { - if let Some(metrics) = &self.0 { - metrics.coalesced_approvals_delay.observe(delayed_ticks as f64) - } - } - fn on_approval_stale(&self) { if let Some(metrics) = &self.0 { metrics.approvals_produced_total.with_label_values(&["stale"]).inc() @@ -252,18 +220,6 @@ impl Metrics { } } - fn on_observed_no_shows(&self, n: usize) { - if let Some(metrics) = &self.0 { - metrics.observed_no_shows.inc_by(n as u64); - } - } - - fn on_approved_by_one_third(&self) { - if let Some(metrics) = &self.0 { - metrics.approved_by_one_third.inc(); - } - } - fn on_wakeup(&self) { if let Some(metrics) = &self.0 { metrics.wakeups_triggered_total.inc(); @@ -341,13 +297,6 @@ impl metrics::Metrics for Metrics { )?, registry, )?, - observed_no_shows: prometheus::register( - prometheus::Counter::new( - "polkadot_parachain_approvals_observed_no_shows_total", - "Number of observed no shows at any moment in time", - )?, - registry, - )?, wakeups_triggered_total: prometheus::register( prometheus::Counter::new( "polkadot_parachain_approvals_wakeups_total", @@ -364,31 +313,6 @@ impl metrics::Metrics for Metrics { )?, registry, )?, - coalesced_approvals_buckets: prometheus::register( - prometheus::Histogram::with_opts( - prometheus::HistogramOpts::new( - "polkadot_parachain_approvals_coalesced_approvals_buckets", - "Number of coalesced approvals.", - ).buckets(vec![1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]), - )?, - registry, - )?, - coalesced_approvals_delay: prometheus::register( - prometheus::Histogram::with_opts( - prometheus::HistogramOpts::new( - "polkadot_parachain_approvals_coalescing_delay", - "Number of ticks we delay the sending of a candidate approval", - ).buckets(vec![1.1, 2.1, 3.1, 4.1, 6.1, 8.1, 12.1, 20.1, 32.1]), - )?, - registry, - )?, - approved_by_one_third: prometheus::register( - prometheus::Counter::new( - "polkadot_parachain_approved_by_one_third", - "Number of candidates where more than one third had to vote ", - )?, - registry, - )?, block_approval_time_ticks: prometheus::register( prometheus::Histogram::with_opts( prometheus::HistogramOpts::new( @@ -459,8 +383,8 @@ impl ApprovalVotingSubsystem { /// The operation is not allowed for blocks older than the last finalized one. pub fn revert_to(&self, hash: Hash) -> Result<(), SubsystemError> { let config = - approval_db::common::Config { col_approval_data: self.db_config.col_approval_data }; - let mut backend = approval_db::common::DbBackend::new(self.db.clone(), config); + approval_db::v2::Config { col_approval_data: self.db_config.col_approval_data }; + let mut backend = approval_db::v2::DbBackend::new(self.db.clone(), config); let mut overlay = OverlayedBackend::new(&backend); ops::revert_to(&mut overlay, hash)?; @@ -635,7 +559,6 @@ struct ApprovalStatus { required_tranches: RequiredTranches, tranche_now: DelayTranche, block_tick: Tick, - last_no_shows: usize, } #[derive(Copy, Clone)] @@ -810,73 +733,22 @@ 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 status = ApprovalStatus { - required_tranches, - block_tick, + let required_tranches = approval_checking::tranches_to_approve( + approval_entry, + candidate_entry.approvals(), tranche_now, - last_no_shows: total_observed_no_shows, - }; + block_tick, + no_show_duration, + session_info.needed_approvals as _, + ); + + let status = ApprovalStatus { required_tranches, block_tick, tranche_now }; Some((approval_entry, status)) } else { None } } - - // Returns the approval voting params from the RuntimeApi. - #[overseer::contextbounds(ApprovalVoting, prefix = self::overseer)] - async fn get_approval_voting_params_or_default( - &self, - ctx: &mut Context, - session_index: SessionIndex, - block_hash: Hash, - ) -> Option { - let (s_tx, s_rx) = oneshot::channel(); - - ctx.send_message(RuntimeApiMessage::Request( - block_hash, - RuntimeApiRequest::ApprovalVotingParams(session_index, s_tx), - )) - .await; - - match s_rx.await { - Ok(Ok(params)) => { - gum::trace!( - target: LOG_TARGET, - approval_voting_params = ?params, - session = ?session_index, - "Using the following subsystem params" - ); - Some(params) - }, - Ok(Err(err)) => { - gum::debug!( - target: LOG_TARGET, - ?err, - "Could not request approval voting params from runtime" - ); - None - }, - Err(err) => { - gum::debug!( - target: LOG_TARGET, - ?err, - "Could not request approval voting params from runtime" - ); - None - }, - } - } } #[derive(Debug, Clone)] @@ -935,7 +807,6 @@ where }); let mut wakeups = Wakeups::default(); let mut currently_checking_set = CurrentlyCheckingSet::default(); - let mut delayed_approvals_timers = DelayedApprovalTimer::default(); let mut approvals_cache = LruMap::new(ByLength::new(APPROVAL_CACHE_SIZE)); let mut last_finalized_height: Option = { @@ -1014,49 +885,17 @@ where } actions - }, - (block_hash, validator_index) = delayed_approvals_timers.select_next_some() => { - gum::debug!( - target: LOG_TARGET, - ?block_hash, - ?validator_index, - "Sign approval for multiple candidates", - ); - - match maybe_create_signature( - &mut overlayed_db, - &mut session_info_provider, - &state, - &mut ctx, - block_hash, - validator_index, - &subsystem.metrics, - ).await { - Ok(Some(next_wakeup)) => { - delayed_approvals_timers.maybe_arm_timer(next_wakeup, state.clock.as_ref(), block_hash, validator_index); - }, - Ok(None) => {} - Err(err) => { - gum::error!( - target: LOG_TARGET, - ?err, - "Failed to create signature", - ); - } - } - vec![] } }; if handle_actions( &mut ctx, - &mut state, + &state, &mut overlayed_db, &mut session_info_provider, &subsystem.metrics, &mut wakeups, &mut currently_checking_set, - &mut delayed_approvals_timers, &mut approvals_cache, &mut subsystem.mode, actions, @@ -1098,13 +937,12 @@ where #[overseer::contextbounds(ApprovalVoting, prefix = self::overseer)] async fn handle_actions( ctx: &mut Context, - state: &mut State, + state: &State, overlayed_db: &mut OverlayedBackend<'_, impl Backend>, session_info_provider: &mut RuntimeInfo, metrics: &Metrics, wakeups: &mut Wakeups, currently_checking_set: &mut CurrentlyCheckingSet, - delayed_approvals_timers: &mut DelayedApprovalTimer, approvals_cache: &mut LruMap, mode: &mut Mode, actions: Vec, @@ -1135,7 +973,6 @@ async fn handle_actions( session_info_provider, metrics, candidate_hash, - delayed_approvals_timers, approval_request, ) .await? @@ -1238,11 +1075,7 @@ async fn handle_actions( Action::BecomeActive => { *mode = Mode::Active; - let messages = distribution_messages_for_activation( - overlayed_db, - state, - delayed_approvals_timers, - )?; + let messages = distribution_messages_for_activation(overlayed_db, state)?; ctx.send_messages(messages.into_iter()).await; }, @@ -1268,7 +1101,7 @@ fn cores_to_candidate_indices( .iter() .position(|(core_index, _)| core_index.0 == claimed_core_index as u32) { - candidate_indices.push(candidate_index as _); + candidate_indices.push(candidate_index as CandidateIndex); } } @@ -1301,7 +1134,6 @@ fn get_assignment_core_indices( fn distribution_messages_for_activation( db: &OverlayedBackend<'_, impl Backend>, state: &State, - delayed_approvals_timers: &mut DelayedApprovalTimer, ) -> SubsystemResult> { let all_blocks: Vec = db.load_all_blocks()?; @@ -1340,8 +1172,8 @@ fn distribution_messages_for_activation( slot: block_entry.slot(), session: block_entry.session(), }); - let mut signatures_queued = HashSet::new(); - for (_, candidate_hash) in block_entry.candidates() { + + for (i, (_, candidate_hash)) in block_entry.candidates().iter().enumerate() { let _candidate_span = distribution_message_span.child("candidate").with_candidate(*candidate_hash); let candidate_entry = match db.load_candidate_entry(&candidate_hash)? { @@ -1368,15 +1200,6 @@ fn distribution_messages_for_activation( &candidate_hash, &block_entry, ) { - if block_entry.has_candidates_pending_signature() { - delayed_approvals_timers.maybe_arm_timer( - state.clock.tick_now(), - state.clock.as_ref(), - block_entry.block_hash(), - assignment.validator_index(), - ) - } - match cores_to_candidate_indices( &claimed_core_indices, &block_entry, @@ -1444,19 +1267,15 @@ fn distribution_messages_for_activation( continue }, } - if signatures_queued - .insert(approval_sig.signed_candidates_indices.clone()) - { - messages.push(ApprovalDistributionMessage::DistributeApproval( - IndirectSignedApprovalVoteV2 { - block_hash, - candidate_indices: approval_sig - .signed_candidates_indices, - validator: assignment.validator_index(), - signature: approval_sig.signature, - }, - )) - }; + + messages.push(ApprovalDistributionMessage::DistributeApproval( + IndirectSignedApprovalVote { + block_hash, + candidate_index: i as _, + validator: assignment.validator_index(), + signature: approval_sig, + }, + )); } else { gum::warn!( target: LOG_TARGET, @@ -1662,7 +1481,7 @@ async fn get_approval_signatures_for_candidate( ctx: &mut Context, db: &OverlayedBackend<'_, impl Backend>, candidate_hash: CandidateHash, - tx: oneshot::Sender, ValidatorSignature)>>, + tx: oneshot::Sender>, ) -> SubsystemResult<()> { let send_votes = |votes| { if let Err(_) = tx.send(votes) { @@ -1688,11 +1507,6 @@ async fn get_approval_signatures_for_candidate( let relay_hashes = entry.block_assignments.keys(); let mut candidate_indices = HashSet::new(); - let mut candidate_indices_to_candidate_hashes: HashMap< - Hash, - HashMap, - > = HashMap::new(); - // Retrieve `CoreIndices`/`CandidateIndices` as required by approval-distribution: for hash in relay_hashes { let entry = match db.load_block_entry(hash)? { @@ -1710,11 +1524,8 @@ async fn get_approval_signatures_for_candidate( for (candidate_index, (_core_index, c_hash)) in entry.candidates().iter().enumerate() { if c_hash == &candidate_hash { candidate_indices.insert((*hash, candidate_index as u32)); + break } - candidate_indices_to_candidate_hashes - .entry(*hash) - .or_default() - .insert(candidate_index as _, *c_hash); } } @@ -1739,55 +1550,7 @@ async fn get_approval_signatures_for_candidate( target: LOG_TARGET, "Request for approval signatures got cancelled by `approval-distribution`." ), - Some(Ok(votes)) => { - let votes = votes - .into_iter() - .filter_map(|(validator_index, (hash, signed_candidates_indices, signature))| { - let candidates_hashes = candidate_indices_to_candidate_hashes.get(&hash); - - if candidates_hashes.is_none() { - gum::warn!( - target: LOG_TARGET, - ?hash, - "Possible bug! Could not find map of candidate_hashes for block hash received from approval-distribution" - ); - } - - let num_signed_candidates = signed_candidates_indices.len(); - - let signed_candidates_hashes: Vec = - signed_candidates_indices - .into_iter() - .filter_map(|candidate_index| { - candidates_hashes.and_then(|candidate_hashes| { - if let Some(candidate_hash) = - candidate_hashes.get(&candidate_index) - { - Some(*candidate_hash) - } else { - gum::warn!( - target: LOG_TARGET, - ?candidate_index, - "Possible bug! Could not find candidate hash for candidate_index coming from approval-distribution" - ); - None - } - }) - }) - .collect(); - if num_signed_candidates == signed_candidates_hashes.len() { - Some((validator_index, (signed_candidates_hashes, signature))) - } else { - gum::warn!( - target: LOG_TARGET, - "Possible bug! Could not find all hashes for candidates coming from approval-distribution" - ); - None - } - }) - .collect(); - send_votes(votes) - }, + Some(Ok(votes)) => send_votes(votes), } }; @@ -2421,7 +2184,7 @@ async fn check_and_import_approval( db: &mut OverlayedBackend<'_, impl Backend>, session_info_provider: &mut RuntimeInfo, metrics: &Metrics, - approval: IndirectSignedApprovalVoteV2, + approval: IndirectSignedApprovalVote, with_response: impl FnOnce(ApprovalCheckResult) -> T, ) -> SubsystemResult<(Vec, T)> where @@ -2433,12 +2196,13 @@ where return Ok((Vec::new(), t)) }}; } + let mut span = state .spans .get(&approval.block_hash) .map(|span| span.child("check-and-import-approval")) .unwrap_or_else(|| jaeger::Span::new(approval.block_hash, "check-and-import-approval")) - .with_string_fmt_debug_tag("candidate-index", approval.candidate_indices.clone()) + .with_uint_tag("candidate-index", approval.candidate_index as u64) .with_relay_parent(approval.block_hash) .with_stage(jaeger::Stage::ApprovalChecking); @@ -2451,171 +2215,113 @@ where }, }; - let approved_candidates_info: Result, ApprovalCheckError> = - approval - .candidate_indices - .iter_ones() - .map(|candidate_index| { - block_entry - .candidate(candidate_index) - .ok_or(ApprovalCheckError::InvalidCandidateIndex(candidate_index as _)) - .map(|candidate| (candidate_index as _, candidate.1)) - }) - .collect(); - - let approved_candidates_info = match approved_candidates_info { - Ok(approved_candidates_info) => approved_candidates_info, - Err(err) => { - respond_early!(ApprovalCheckResult::Bad(err)) + let session_info = match get_session_info( + session_info_provider, + sender, + approval.block_hash, + block_entry.session(), + ) + .await + { + Some(s) => s, + None => { + respond_early!(ApprovalCheckResult::Bad(ApprovalCheckError::UnknownSessionIndex( + block_entry.session() + ),)) }, }; - span.add_string_tag("candidate-hashes", format!("{:?}", approved_candidates_info)); + let approved_candidate_hash = match block_entry.candidate(approval.candidate_index as usize) { + Some((_, h)) => *h, + None => respond_early!(ApprovalCheckResult::Bad( + ApprovalCheckError::InvalidCandidateIndex(approval.candidate_index), + )), + }; + + span.add_string_tag("candidate-hash", format!("{:?}", approved_candidate_hash)); span.add_string_tag( - "traceIDs", - format!( - "{:?}", - approved_candidates_info - .iter() - .map(|(_, approved_candidate_hash)| hash_to_trace_identifier( - approved_candidate_hash.0 - )) - .collect_vec() - ), + "traceID", + format!("{:?}", hash_to_trace_identifier(approved_candidate_hash.0)), ); - { - let session_info = match get_session_info( - session_info_provider, - sender, - approval.block_hash, - block_entry.session(), - ) - .await - { - Some(s) => s, - None => { - respond_early!(ApprovalCheckResult::Bad(ApprovalCheckError::UnknownSessionIndex( - block_entry.session() - ),)) - }, - }; - - let pubkey = match session_info.validators.get(approval.validator) { - Some(k) => k, - None => respond_early!(ApprovalCheckResult::Bad( - ApprovalCheckError::InvalidValidatorIndex(approval.validator), - )), - }; - - gum::trace!( - target: LOG_TARGET, - "Received approval for num_candidates {:}", - approval.candidate_indices.count_ones() - ); - - let candidate_hashes: Vec = - approved_candidates_info.iter().map(|candidate| candidate.1).collect(); - // Signature check: - match DisputeStatement::Valid( - ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(candidate_hashes.clone()), - ) - .check_signature( - &pubkey, - if let Some(candidate_hash) = candidate_hashes.first() { - *candidate_hash - } else { - respond_early!(ApprovalCheckResult::Bad(ApprovalCheckError::InvalidValidatorIndex( - approval.validator - ),)) - }, - block_entry.session(), - &approval.signature, - ) { - Err(_) => { - gum::error!( - target: LOG_TARGET, - "Error while checking signature {:}", - approval.candidate_indices.count_ones() - ); - respond_early!(ApprovalCheckResult::Bad(ApprovalCheckError::InvalidSignature( - approval.validator - ),)) - }, - Ok(()) => {}, - }; - } - - let mut actions = Vec::new(); - for (approval_candidate_index, approved_candidate_hash) in approved_candidates_info { - let block_entry = match db.load_block_entry(&approval.block_hash)? { - Some(b) => b, - None => { - respond_early!(ApprovalCheckResult::Bad(ApprovalCheckError::UnknownBlock( - approval.block_hash - ),)) - }, - }; - - let candidate_entry = match db.load_candidate_entry(&approved_candidate_hash)? { - Some(c) => c, - None => { - respond_early!(ApprovalCheckResult::Bad(ApprovalCheckError::InvalidCandidate( - approval_candidate_index, - approved_candidate_hash - ),)) - }, - }; + let pubkey = match session_info.validators.get(approval.validator) { + Some(k) => k, + None => respond_early!(ApprovalCheckResult::Bad( + ApprovalCheckError::InvalidValidatorIndex(approval.validator), + )), + }; - // Don't accept approvals until assignment. - match candidate_entry.approval_entry(&approval.block_hash) { - None => { - respond_early!(ApprovalCheckResult::Bad(ApprovalCheckError::Internal( - approval.block_hash, - approved_candidate_hash - ),)) - }, - Some(e) if !e.is_assigned(approval.validator) => { - respond_early!(ApprovalCheckResult::Bad(ApprovalCheckError::NoAssignment( - approval.validator - ),)) - }, - _ => {}, - } + // Signature check: + match DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking).check_signature( + &pubkey, + approved_candidate_hash, + block_entry.session(), + &approval.signature, + ) { + Err(_) => respond_early!(ApprovalCheckResult::Bad(ApprovalCheckError::InvalidSignature( + approval.validator + ),)), + Ok(()) => {}, + }; - gum::debug!( - target: LOG_TARGET, - validator_index = approval.validator.0, - candidate_hash = ?approved_candidate_hash, - para_id = ?candidate_entry.candidate_receipt().descriptor.para_id, - "Importing approval vote", - ); + let candidate_entry = match db.load_candidate_entry(&approved_candidate_hash)? { + Some(c) => c, + None => { + respond_early!(ApprovalCheckResult::Bad(ApprovalCheckError::InvalidCandidate( + approval.candidate_index, + approved_candidate_hash + ),)) + }, + }; - let new_actions = advance_approval_state( - sender, - state, - db, - session_info_provider, - &metrics, - block_entry, - approved_candidate_hash, - candidate_entry, - ApprovalStateTransition::RemoteApproval(approval.validator), - ) - .await; - actions.extend(new_actions); + // Don't accept approvals until assignment. + match candidate_entry.approval_entry(&approval.block_hash) { + None => { + respond_early!(ApprovalCheckResult::Bad(ApprovalCheckError::Internal( + approval.block_hash, + approved_candidate_hash + ),)) + }, + Some(e) if !e.is_assigned(approval.validator) => { + respond_early!(ApprovalCheckResult::Bad(ApprovalCheckError::NoAssignment( + approval.validator + ),)) + }, + _ => {}, } // importing the approval can be heavy as it may trigger acceptance for a series of blocks. let t = with_response(ApprovalCheckResult::Accepted); + gum::trace!( + target: LOG_TARGET, + validator_index = approval.validator.0, + validator = ?pubkey, + candidate_hash = ?approved_candidate_hash, + para_id = ?candidate_entry.candidate_receipt().descriptor.para_id, + "Importing approval vote", + ); + + let actions = advance_approval_state( + sender, + state, + db, + session_info_provider, + &metrics, + block_entry, + approved_candidate_hash, + candidate_entry, + ApprovalStateTransition::RemoteApproval(approval.validator), + ) + .await; + Ok((actions, t)) } #[derive(Debug)] enum ApprovalStateTransition { RemoteApproval(ValidatorIndex), - LocalApproval(ValidatorIndex), + LocalApproval(ValidatorIndex, ValidatorSignature), WakeupProcessed, } @@ -2623,7 +2329,7 @@ impl ApprovalStateTransition { fn validator_index(&self) -> Option { match *self { ApprovalStateTransition::RemoteApproval(v) | - ApprovalStateTransition::LocalApproval(v) => Some(v), + ApprovalStateTransition::LocalApproval(v, _) => Some(v), ApprovalStateTransition::WakeupProcessed => None, } } @@ -2631,7 +2337,7 @@ impl ApprovalStateTransition { fn is_local_approval(&self) -> bool { match *self { ApprovalStateTransition::RemoteApproval(_) => false, - ApprovalStateTransition::LocalApproval(_) => true, + ApprovalStateTransition::LocalApproval(_, _) => true, ApprovalStateTransition::WakeupProcessed => false, } } @@ -2698,16 +2404,7 @@ where // assignment tick of `now - APPROVAL_DELAY` - that is, that // all counted assignments are at least `APPROVAL_DELAY` ticks old. let is_approved = check.is_approved(tick_now.saturating_sub(APPROVAL_DELAY)); - if status.last_no_shows != 0 { - metrics.on_observed_no_shows(status.last_no_shows); - gum::debug!( - target: LOG_TARGET, - ?candidate_hash, - ?block_hash, - last_no_shows = ?status.last_no_shows, - "Observed no_shows", - ); - } + if is_approved { gum::trace!( target: LOG_TARGET, @@ -2725,12 +2422,6 @@ where if no_shows != 0 { metrics.on_no_shows(no_shows); } - if check == Check::ApprovedOneThird { - // No-shows are not counted when more than one third of validators approve a - // candidate, so count candidates where more than one third of validators had to - // approve it, this is indicative of something breaking. - metrics.on_approved_by_one_third() - } metrics.on_candidate_approved(status.tranche_now as _); @@ -2739,10 +2430,6 @@ where actions.push(Action::NoteApprovedInChainSelection(block_hash)); } - db.write_block_entry(block_entry.into()); - } else if transition.is_local_approval() { - // Local approvals always update the block_entry, so we need to flush it to - // the database. db.write_block_entry(block_entry.into()); } @@ -2771,6 +2458,10 @@ where approval_entry.mark_approved(); } + if let ApprovalStateTransition::LocalApproval(_, ref sig) = transition { + approval_entry.import_approval_sig(sig.clone()); + } + actions.extend(schedule_wakeup_action( &approval_entry, block_hash, @@ -2908,7 +2599,7 @@ async fn process_wakeup( let should_trigger = should_trigger_assignment( &approval_entry, &candidate_entry, - tranches_to_approve.required_tranches, + tranches_to_approve, tranche_now, ); @@ -3233,12 +2924,11 @@ async fn launch_approval( #[overseer::contextbounds(ApprovalVoting, prefix = self::overseer)] async fn issue_approval( ctx: &mut Context, - state: &mut State, + state: &State, db: &mut OverlayedBackend<'_, impl Backend>, session_info_provider: &mut RuntimeInfo, metrics: &Metrics, candidate_hash: CandidateHash, - delayed_approvals_timers: &mut DelayedApprovalTimer, ApprovalVoteRequest { validator_index, block_hash }: ApprovalVoteRequest, ) -> SubsystemResult> { let mut issue_approval_span = state @@ -3252,7 +2942,7 @@ async fn issue_approval( .with_validator_index(validator_index) .with_stage(jaeger::Stage::ApprovalChecking); - let mut block_entry = match db.load_block_entry(&block_hash)? { + let block_entry = match db.load_block_entry(&block_hash)? { Some(b) => b, None => { // not a cause for alarm - just lost a race with pruning, most likely. @@ -3278,6 +2968,21 @@ async fn issue_approval( }; issue_approval_span.add_int_tag("candidate_index", candidate_index as i64); + let session_info = match get_session_info( + session_info_provider, + ctx.sender(), + block_entry.parent_hash(), + block_entry.session(), + ) + .await + { + Some(s) => s, + None => { + metrics.on_approval_error(); + return Ok(Vec::new()) + }, + }; + let candidate_hash = match block_entry.candidate(candidate_index as usize) { Some((_, h)) => *h, None => { @@ -3308,149 +3013,10 @@ async fn issue_approval( }, }; - let session_info = match get_session_info( - session_info_provider, - ctx.sender(), - block_entry.parent_hash(), - block_entry.session(), - ) - .await - { - Some(s) => s, - None => return Ok(Vec::new()), - }; - - if block_entry - .defer_candidate_signature( - candidate_index as _, - candidate_hash, - compute_delayed_approval_sending_tick( - state, - &block_entry, - &candidate_entry, - session_info, - &metrics, - ), - ) - .is_some() - { - gum::error!( - target: LOG_TARGET, - ?candidate_hash, - ?block_hash, - validator_index = validator_index.0, - "Possible bug, we shouldn't have to defer a candidate more than once", - ); - } - - gum::info!( - target: LOG_TARGET, - ?candidate_hash, - ?block_hash, - validator_index = validator_index.0, - "Ready to issue approval vote", - ); - - let actions = advance_approval_state( - ctx.sender(), - state, - db, - session_info_provider, - metrics, - block_entry, - candidate_hash, - candidate_entry, - ApprovalStateTransition::LocalApproval(validator_index as _), - ) - .await; - - if let Some(next_wakeup) = maybe_create_signature( - db, - session_info_provider, - state, - ctx, - block_hash, - validator_index, - metrics, - ) - .await? - { - delayed_approvals_timers.maybe_arm_timer( - next_wakeup, - state.clock.as_ref(), - block_hash, - validator_index, - ); - } - Ok(actions) -} - -// Create signature for the approved candidates pending signatures -#[overseer::contextbounds(ApprovalVoting, prefix = self::overseer)] -async fn maybe_create_signature( - db: &mut OverlayedBackend<'_, impl Backend>, - session_info_provider: &mut RuntimeInfo, - state: &State, - ctx: &mut Context, - block_hash: Hash, - validator_index: ValidatorIndex, - metrics: &Metrics, -) -> SubsystemResult> { - let mut block_entry = match db.load_block_entry(&block_hash)? { - Some(b) => b, - None => { - // not a cause for alarm - just lost a race with pruning, most likely. - metrics.on_approval_stale(); - gum::debug!( - target: LOG_TARGET, - "Could not find block that needs signature {:}", block_hash - ); - return Ok(None) - }, - }; - - let approval_params = state - .get_approval_voting_params_or_default(ctx, block_entry.session(), block_hash) - .await - .unwrap_or_default(); - - gum::trace!( - target: LOG_TARGET, - "Candidates pending signatures {:}", block_entry.num_candidates_pending_signature() - ); - let tick_now = state.clock.tick_now(); - - let (candidates_to_sign, sign_no_later_then) = block_entry - .get_candidates_that_need_signature(tick_now, approval_params.max_approval_coalesce_count); - - let (candidates_hashes, candidates_indices) = match candidates_to_sign { - Some(candidates_to_sign) => candidates_to_sign, - None => return Ok(sign_no_later_then), - }; - - let session_info = match get_session_info( - session_info_provider, - ctx.sender(), - block_entry.parent_hash(), - block_entry.session(), - ) - .await - { - Some(s) => s, - None => { - metrics.on_approval_error(); - gum::error!( - target: LOG_TARGET, - "Could not retrieve the session" - ); - return Ok(None) - }, - }; - let validator_pubkey = match session_info.validators.get(validator_index) { Some(p) => p, None => { - gum::error!( + gum::warn!( target: LOG_TARGET, "Validator index {} out of bounds in session {}", validator_index.0, @@ -3458,89 +3024,72 @@ async fn maybe_create_signature( ); metrics.on_approval_error(); - return Ok(None) + return Ok(Vec::new()) }, }; - let signature = match sign_approval( - &state.keystore, - &validator_pubkey, - &candidates_hashes, - block_entry.session(), - ) { + let session = block_entry.session(); + let sig = match sign_approval(&state.keystore, &validator_pubkey, candidate_hash, session) { Some(sig) => sig, None => { - gum::error!( + gum::warn!( target: LOG_TARGET, validator_index = ?validator_index, - session = ?block_entry.session(), + session, "Could not issue approval signature. Assignment key present but not validator key?", ); metrics.on_approval_error(); - return Ok(None) + return Ok(Vec::new()) }, }; - metrics.on_approval_coalesce(candidates_hashes.len() as u32); - - let candidate_entries = candidates_hashes - .iter() - .map(|candidate_hash| db.load_candidate_entry(candidate_hash)) - .collect::>>>()?; - for mut candidate_entry in candidate_entries { - let approval_entry = candidate_entry.as_mut().and_then(|candidate_entry| { - candidate_entry.approval_entry_mut(&block_entry.block_hash()) - }); + gum::trace!( + target: LOG_TARGET, + ?candidate_hash, + ?block_hash, + validator_index = validator_index.0, + "Issuing approval vote", + ); - match approval_entry { - Some(approval_entry) => approval_entry.import_approval_sig(OurApproval { - signature: signature.clone(), - signed_candidates_indices: candidates_indices.clone(), - }), - None => { - gum::error!( - target: LOG_TARGET, - candidate_entry = ?candidate_entry, - "Candidate scheduled for signing approval entry should not be None" - ); - }, - }; - candidate_entry.map(|candidate_entry| db.write_candidate_entry(candidate_entry)); - } + let actions = advance_approval_state( + ctx.sender(), + state, + db, + session_info_provider, + metrics, + block_entry, + candidate_hash, + candidate_entry, + ApprovalStateTransition::LocalApproval(validator_index as _, sig.clone()), + ) + .await; metrics.on_approval_produced(); + // dispatch to approval distribution. ctx.send_unbounded_message(ApprovalDistributionMessage::DistributeApproval( - IndirectSignedApprovalVoteV2 { - block_hash: block_entry.block_hash(), - candidate_indices: candidates_indices, + IndirectSignedApprovalVote { + block_hash, + candidate_index: candidate_index as _, validator: validator_index, - signature, + signature: sig, }, )); - gum::trace!( - target: LOG_TARGET, - ?block_hash, - signed_candidates = ?block_entry.num_candidates_pending_signature(), - "Issue approval votes", - ); - block_entry.issued_approval(); - db.write_block_entry(block_entry.into()); - Ok(None) + Ok(actions) } // Sign an approval vote. Fails if the key isn't present in the store. fn sign_approval( keystore: &LocalKeystore, public: &ValidatorId, - candidate_hashes: &[CandidateHash], + candidate_hash: CandidateHash, session_index: SessionIndex, ) -> Option { let key = keystore.key_pair::(public).ok().flatten()?; - let payload = ApprovalVoteMultipleCandidates(candidate_hashes).signing_payload(session_index); + let payload = ApprovalVote(candidate_hash).signing_payload(session_index); Some(key.sign(&payload[..])) } @@ -3570,38 +3119,3 @@ fn issue_local_invalid_statement( false, )); } - -// Computes what is the latest tick we can send an approval -fn compute_delayed_approval_sending_tick( - state: &State, - block_entry: &BlockEntry, - candidate_entry: &CandidateEntry, - session_info: &SessionInfo, - metrics: &Metrics, -) -> Tick { - let current_block_tick = slot_number_to_tick(state.slot_duration_millis, block_entry.slot()); - let assignment_tranche = candidate_entry - .approval_entry(&block_entry.block_hash()) - .and_then(|approval_entry| approval_entry.our_assignment()) - .map(|our_assignment| our_assignment.tranche()) - .unwrap_or_default(); - - let assignment_triggered_tick = current_block_tick + assignment_tranche as Tick; - - let no_show_duration_ticks = slot_number_to_tick( - state.slot_duration_millis, - Slot::from(u64::from(session_info.no_show_slots)), - ); - let tick_now = state.clock.tick_now(); - - let sign_no_later_than = min( - tick_now + MAX_APPROVAL_COALESCE_WAIT_TICKS as Tick, - // We don't want to accidentally cause no-shows, so if we are past - // the second half of the no show time, force the sending of the - // approval immediately. - assignment_triggered_tick + no_show_duration_ticks / 2, - ); - - metrics.on_delayed_approval(sign_no_later_than.checked_sub(tick_now).unwrap_or_default()); - sign_no_later_than -} diff --git a/polkadot/node/core/approval-voting/src/ops.rs b/polkadot/node/core/approval-voting/src/ops.rs index 2a8fdba5aa3..a6f0ecf9d1f 100644 --- a/polkadot/node/core/approval-voting/src/ops.rs +++ b/polkadot/node/core/approval-voting/src/ops.rs @@ -25,7 +25,7 @@ use polkadot_primitives::{BlockNumber, CandidateHash, CandidateReceipt, GroupInd use std::collections::{hash_map::Entry, BTreeMap, HashMap}; use super::{ - approval_db::{common::StoredBlockRange, v2::OurAssignment}, + approval_db::v2::{OurAssignment, StoredBlockRange}, backend::{Backend, OverlayedBackend}, persisted_entries::{ApprovalEntry, BlockEntry, CandidateEntry}, LOG_TARGET, diff --git a/polkadot/node/core/approval-voting/src/persisted_entries.rs b/polkadot/node/core/approval-voting/src/persisted_entries.rs index ef47bdb2213..9cfe1c4cf8d 100644 --- a/polkadot/node/core/approval-voting/src/persisted_entries.rs +++ b/polkadot/node/core/approval-voting/src/persisted_entries.rs @@ -20,14 +20,13 @@ //! Within that context, things are plain-old-data. Within this module, //! data and logic are intertwined. -use itertools::Itertools; use polkadot_node_primitives::approval::{ v1::{DelayTranche, RelayVRFStory}, v2::{AssignmentCertV2, CandidateBitfield}, }; use polkadot_primitives::{ - BlockNumber, CandidateHash, CandidateIndex, CandidateReceipt, CoreIndex, GroupIndex, Hash, - SessionIndex, ValidatorIndex, ValidatorSignature, + BlockNumber, CandidateHash, CandidateReceipt, CoreIndex, GroupIndex, Hash, SessionIndex, + ValidatorIndex, ValidatorSignature, }; use sp_consensus_slots::Slot; @@ -77,45 +76,6 @@ impl From for crate::approval_db::v2::TrancheEntry { } } -impl From for OurApproval { - fn from(approval: crate::approval_db::v3::OurApproval) -> Self { - Self { - signature: approval.signature, - signed_candidates_indices: approval.signed_candidates_indices, - } - } -} -impl From for crate::approval_db::v3::OurApproval { - fn from(approval: OurApproval) -> Self { - Self { - signature: approval.signature, - signed_candidates_indices: approval.signed_candidates_indices, - } - } -} - -/// Metadata about our approval signature -#[derive(Debug, Clone, PartialEq)] -pub struct OurApproval { - /// The signature for the candidates hashes pointed by indices. - pub signature: ValidatorSignature, - /// The indices of the candidates signed in this approval. - pub signed_candidates_indices: CandidateBitfield, -} - -impl OurApproval { - /// Converts a ValidatorSignature to an OurApproval. - /// It used in converting the database from v1 to latest. - pub fn from_v1(value: ValidatorSignature, candidate_index: CandidateIndex) -> Self { - Self { signature: value, signed_candidates_indices: candidate_index.into() } - } - - /// Converts a ValidatorSignature to an OurApproval. - /// It used in converting the database from v2 to latest. - pub fn from_v2(value: ValidatorSignature, candidate_index: CandidateIndex) -> Self { - Self::from_v1(value, candidate_index) - } -} /// Metadata regarding approval of a particular candidate within the context of some /// particular block. #[derive(Debug, Clone, PartialEq)] @@ -123,7 +83,7 @@ pub struct ApprovalEntry { tranches: Vec, backing_group: GroupIndex, our_assignment: Option, - our_approval_sig: Option, + our_approval_sig: Option, // `n_validators` bits. assigned_validators: Bitfield, approved: bool, @@ -135,7 +95,7 @@ impl ApprovalEntry { tranches: Vec, backing_group: GroupIndex, our_assignment: Option, - our_approval_sig: Option, + our_approval_sig: Option, // `n_validators` bits. assigned_validators: Bitfield, approved: bool, @@ -177,7 +137,7 @@ impl ApprovalEntry { } /// Import our local approval vote signature for this candidate. - pub fn import_approval_sig(&mut self, approval_sig: OurApproval) { + pub fn import_approval_sig(&mut self, approval_sig: ValidatorSignature) { self.our_approval_sig = Some(approval_sig); } @@ -264,7 +224,7 @@ impl ApprovalEntry { /// Get the assignment cert & approval signature. /// /// The approval signature will only be `Some` if the assignment is too. - pub fn local_statements(&self) -> (Option, Option) { + pub fn local_statements(&self) -> (Option, Option) { let approval_sig = self.our_approval_sig.clone(); if let Some(our_assignment) = self.our_assignment.as_ref().filter(|a| a.triggered()) { (Some(our_assignment.clone()), approval_sig) @@ -272,44 +232,10 @@ impl ApprovalEntry { (None, None) } } - - // Convert an ApprovalEntry from v1 version to latest version - pub fn from_v1( - value: crate::approval_db::v1::ApprovalEntry, - candidate_index: CandidateIndex, - ) -> Self { - ApprovalEntry { - tranches: value.tranches.into_iter().map(|tranche| tranche.into()).collect(), - backing_group: value.backing_group, - our_assignment: value.our_assignment.map(|assignment| assignment.into()), - our_approval_sig: value - .our_approval_sig - .map(|sig| OurApproval::from_v1(sig, candidate_index)), - assigned_validators: value.assignments, - approved: value.approved, - } - } - - // Convert an ApprovalEntry from v1 version to latest version - pub fn from_v2( - value: crate::approval_db::v2::ApprovalEntry, - candidate_index: CandidateIndex, - ) -> Self { - ApprovalEntry { - tranches: value.tranches.into_iter().map(|tranche| tranche.into()).collect(), - backing_group: value.backing_group, - our_assignment: value.our_assignment.map(|assignment| assignment.into()), - our_approval_sig: value - .our_approval_sig - .map(|sig| OurApproval::from_v2(sig, candidate_index)), - assigned_validators: value.assigned_validators, - approved: value.approved, - } - } } -impl From for ApprovalEntry { - fn from(entry: crate::approval_db::v3::ApprovalEntry) -> Self { +impl From for ApprovalEntry { + fn from(entry: crate::approval_db::v2::ApprovalEntry) -> Self { ApprovalEntry { tranches: entry.tranches.into_iter().map(Into::into).collect(), backing_group: entry.backing_group, @@ -321,7 +247,7 @@ impl From for ApprovalEntry { } } -impl From for crate::approval_db::v3::ApprovalEntry { +impl From for crate::approval_db::v2::ApprovalEntry { fn from(entry: ApprovalEntry) -> Self { Self { tranches: entry.tranches.into_iter().map(Into::into).collect(), @@ -377,44 +303,10 @@ impl CandidateEntry { pub fn approval_entry(&self, block_hash: &Hash) -> Option<&ApprovalEntry> { self.block_assignments.get(block_hash) } - - /// Convert a CandidateEntry from a v1 to its latest equivalent. - pub fn from_v1( - value: crate::approval_db::v1::CandidateEntry, - candidate_index: CandidateIndex, - ) -> Self { - Self { - approvals: value.approvals, - block_assignments: value - .block_assignments - .into_iter() - .map(|(h, ae)| (h, ApprovalEntry::from_v1(ae, candidate_index))) - .collect(), - candidate: value.candidate, - session: value.session, - } - } - - /// Convert a CandidateEntry from a v2 to its latest equivalent. - pub fn from_v2( - value: crate::approval_db::v2::CandidateEntry, - candidate_index: CandidateIndex, - ) -> Self { - Self { - approvals: value.approvals, - block_assignments: value - .block_assignments - .into_iter() - .map(|(h, ae)| (h, ApprovalEntry::from_v2(ae, candidate_index))) - .collect(), - candidate: value.candidate, - session: value.session, - } - } } -impl From for CandidateEntry { - fn from(entry: crate::approval_db::v3::CandidateEntry) -> Self { +impl From for CandidateEntry { + fn from(entry: crate::approval_db::v2::CandidateEntry) -> Self { CandidateEntry { candidate: entry.candidate, session: entry.session, @@ -428,7 +320,7 @@ impl From for CandidateEntry { } } -impl From for crate::approval_db::v3::CandidateEntry { +impl From for crate::approval_db::v2::CandidateEntry { fn from(entry: CandidateEntry) -> Self { Self { candidate: entry.candidate, @@ -461,21 +353,12 @@ pub struct BlockEntry { // block. The block can be considered approved if the bitfield has all bits set to `true`. pub approved_bitfield: Bitfield, pub children: Vec, - // A list of candidates we have checked, but didn't not sign and - // advertise the vote yet. - candidates_pending_signature: BTreeMap, // A list of assignments for which we already distributed the assignment. // We use this to ensure we don't distribute multiple core assignments twice as we track // individual wakeups for each core. distributed_assignments: Bitfield, } -#[derive(Debug, Clone, PartialEq)] -pub struct CandidateSigningContext { - pub candidate_hash: CandidateHash, - pub sign_no_later_than_tick: Tick, -} - impl BlockEntry { /// Mark a candidate as fully approved in the bitfield. pub fn mark_approved_by_hash(&mut self, candidate_hash: &CandidateHash) { @@ -564,97 +447,10 @@ impl BlockEntry { distributed } - - /// Defer signing and issuing an approval for a candidate no later than the specified tick - pub fn defer_candidate_signature( - &mut self, - candidate_index: CandidateIndex, - candidate_hash: CandidateHash, - sign_no_later_than_tick: Tick, - ) -> Option { - self.candidates_pending_signature.insert( - candidate_index, - CandidateSigningContext { candidate_hash, sign_no_later_than_tick }, - ) - } - - /// Returns the number of candidates waiting for an approval to be issued. - pub fn num_candidates_pending_signature(&self) -> usize { - self.candidates_pending_signature.len() - } - - /// Return if we have candidates waiting for signature to be issued - pub fn has_candidates_pending_signature(&self) -> bool { - !self.candidates_pending_signature.is_empty() - } - - /// Candidate hashes for candidates pending signatures - fn candidate_hashes_pending_signature(&self) -> Vec { - self.candidates_pending_signature - .values() - .map(|unsigned_approval| unsigned_approval.candidate_hash) - .collect() - } - - /// Candidate indices for candidates pending signature - fn candidate_indices_pending_signature(&self) -> Option { - self.candidates_pending_signature - .keys() - .map(|val| *val) - .collect_vec() - .try_into() - .ok() - } - - /// Returns a list of candidates hashes that need need signature created at the current tick: - /// This might happen in other of the two reasons: - /// 1. We queued more than max_approval_coalesce_count candidates. - /// 2. We have candidates that waiting in the queue past their `sign_no_later_than_tick` - /// - /// Additionally, we also return the first tick when we will have to create a signature, - /// so that the caller can arm the timer if it is not already armed. - pub fn get_candidates_that_need_signature( - &self, - tick_now: Tick, - max_approval_coalesce_count: u32, - ) -> (Option<(Vec, CandidateBitfield)>, Option) { - let sign_no_later_than_tick = self - .candidates_pending_signature - .values() - .min_by(|a, b| a.sign_no_later_than_tick.cmp(&b.sign_no_later_than_tick)) - .map(|val| val.sign_no_later_than_tick); - - if let Some(sign_no_later_than_tick) = sign_no_later_than_tick { - if sign_no_later_than_tick <= tick_now || - self.num_candidates_pending_signature() >= max_approval_coalesce_count as usize - { - ( - self.candidate_indices_pending_signature().and_then(|candidate_indices| { - Some((self.candidate_hashes_pending_signature(), candidate_indices)) - }), - Some(sign_no_later_than_tick), - ) - } else { - // We can still wait for other candidates to queue in, so just make sure - // we wake up at the tick we have to sign the longest waiting candidate. - (Default::default(), Some(sign_no_later_than_tick)) - } - } else { - // No cached candidates, nothing to do here, this just means the timer fired, - // but the signatures were already sent because we gathered more than - // max_approval_coalesce_count. - (Default::default(), sign_no_later_than_tick) - } - } - - /// Clears the candidates pending signature because the approval was issued. - pub fn issued_approval(&mut self) { - self.candidates_pending_signature.clear(); - } } -impl From for BlockEntry { - fn from(entry: crate::approval_db::v3::BlockEntry) -> Self { +impl From for BlockEntry { + fn from(entry: crate::approval_db::v2::BlockEntry) -> Self { BlockEntry { block_hash: entry.block_hash, parent_hash: entry.parent_hash, @@ -665,11 +461,6 @@ impl From for BlockEntry { candidates: entry.candidates, approved_bitfield: entry.approved_bitfield, children: entry.children, - candidates_pending_signature: entry - .candidates_pending_signature - .into_iter() - .map(|(candidate_index, signing_context)| (candidate_index, signing_context.into())) - .collect(), distributed_assignments: entry.distributed_assignments, } } @@ -688,30 +479,11 @@ impl From for BlockEntry { approved_bitfield: entry.approved_bitfield, children: entry.children, distributed_assignments: Default::default(), - candidates_pending_signature: Default::default(), } } } -impl From for BlockEntry { - fn from(entry: crate::approval_db::v2::BlockEntry) -> Self { - BlockEntry { - block_hash: entry.block_hash, - parent_hash: entry.parent_hash, - block_number: entry.block_number, - session: entry.session, - slot: entry.slot, - relay_vrf_story: RelayVRFStory(entry.relay_vrf_story), - candidates: entry.candidates, - approved_bitfield: entry.approved_bitfield, - children: entry.children, - distributed_assignments: entry.distributed_assignments, - candidates_pending_signature: Default::default(), - } - } -} - -impl From for crate::approval_db::v3::BlockEntry { +impl From for crate::approval_db::v2::BlockEntry { fn from(entry: BlockEntry) -> Self { Self { block_hash: entry.block_hash, @@ -723,30 +495,36 @@ impl From for crate::approval_db::v3::BlockEntry { candidates: entry.candidates, approved_bitfield: entry.approved_bitfield, children: entry.children, - candidates_pending_signature: entry - .candidates_pending_signature - .into_iter() - .map(|(candidate_index, signing_context)| (candidate_index, signing_context.into())) - .collect(), distributed_assignments: entry.distributed_assignments, } } } -impl From for CandidateSigningContext { - fn from(signing_context: crate::approval_db::v3::CandidateSigningContext) -> Self { +/// Migration helpers. +impl From for CandidateEntry { + fn from(value: crate::approval_db::v1::CandidateEntry) -> Self { Self { - candidate_hash: signing_context.candidate_hash, - sign_no_later_than_tick: signing_context.sign_no_later_than_tick.into(), + approvals: value.approvals, + block_assignments: value + .block_assignments + .into_iter() + .map(|(h, ae)| (h, ae.into())) + .collect(), + candidate: value.candidate, + session: value.session, } } } -impl From for crate::approval_db::v3::CandidateSigningContext { - fn from(signing_context: CandidateSigningContext) -> Self { - Self { - candidate_hash: signing_context.candidate_hash, - sign_no_later_than_tick: signing_context.sign_no_later_than_tick.into(), +impl From for ApprovalEntry { + fn from(value: crate::approval_db::v1::ApprovalEntry) -> Self { + ApprovalEntry { + tranches: value.tranches.into_iter().map(|tranche| tranche.into()).collect(), + backing_group: value.backing_group, + our_assignment: value.our_assignment.map(|assignment| assignment.into()), + our_approval_sig: value.our_approval_sig, + assigned_validators: value.assignments, + approved: value.approved, } } } diff --git a/polkadot/node/core/approval-voting/src/tests.rs b/polkadot/node/core/approval-voting/src/tests.rs index 498cf62bb30..11bcba9c388 100644 --- a/polkadot/node/core/approval-voting/src/tests.rs +++ b/polkadot/node/core/approval-voting/src/tests.rs @@ -20,7 +20,7 @@ use crate::backend::V1ReadBackend; use polkadot_node_primitives::{ approval::{ v1::{ - AssignmentCert, AssignmentCertKind, DelayTranche, VrfPreOutput, VrfProof, VrfSignature, + AssignmentCert, AssignmentCertKind, DelayTranche, VrfOutput, VrfProof, VrfSignature, RELAY_VRF_MODULO_CONTEXT, }, v2::{AssignmentCertKindV2, AssignmentCertV2}, @@ -37,8 +37,8 @@ use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_node_subsystem_util::TimeoutExt; use polkadot_overseer::HeadSupportsParachains; use polkadot_primitives::{ - vstaging::NodeFeatures, ApprovalVote, CandidateCommitments, CandidateEvent, CoreIndex, - GroupIndex, Header, Id as ParaId, IndexedVec, ValidationCode, ValidatorSignature, + CandidateCommitments, CandidateEvent, CoreIndex, GroupIndex, Header, Id as ParaId, IndexedVec, + ValidationCode, ValidatorSignature, }; use std::time::Duration; @@ -56,7 +56,7 @@ use std::{ }; use super::{ - approval_db::common::StoredBlockRange, + approval_db::v2::StoredBlockRange, backend::BackendWriteOp, import::tests::{ garbage_vrf_signature, AllowedSlots, BabeEpoch, BabeEpochConfiguration, @@ -116,7 +116,7 @@ fn make_sync_oracle(val: bool) -> (Box, TestSyncOracleHan #[cfg(test)] pub mod test_constants { - use crate::approval_db::common::Config as DatabaseConfig; + use crate::approval_db::v2::Config as DatabaseConfig; const DATA_COL: u32 = 0; pub(crate) const NUM_COLUMNS: u32 = 1; @@ -243,7 +243,6 @@ where polkadot_primitives::CoreIndex, polkadot_primitives::GroupIndex, )>, - _enable_assignments_v2: bool, ) -> HashMap { self.0() } @@ -281,7 +280,6 @@ impl V1ReadBackend for TestStoreInner { fn load_candidate_entry_v1( &self, candidate_hash: &CandidateHash, - _candidate_index: CandidateIndex, ) -> SubsystemResult> { self.load_candidate_entry(candidate_hash) } @@ -365,7 +363,6 @@ impl V1ReadBackend for TestStore { fn load_candidate_entry_v1( &self, candidate_hash: &CandidateHash, - _candidate_index: CandidateIndex, ) -> SubsystemResult> { self.load_candidate_entry(candidate_hash) } @@ -418,12 +415,9 @@ fn garbage_assignment_cert(kind: AssignmentCertKind) -> AssignmentCert { let mut prng = rand_core::OsRng; let keypair = schnorrkel::Keypair::generate_with(&mut prng); let (inout, proof, _) = keypair.vrf_sign(ctx.bytes(msg)); - let preout = inout.to_output(); + let out = inout.to_output(); - AssignmentCert { - kind, - vrf: VrfSignature { pre_output: VrfPreOutput(preout), proof: VrfProof(proof) }, - } + AssignmentCert { kind, vrf: VrfSignature { output: VrfOutput(out), proof: VrfProof(proof) } } } fn garbage_assignment_cert_v2(kind: AssignmentCertKindV2) -> AssignmentCertV2 { @@ -432,12 +426,9 @@ fn garbage_assignment_cert_v2(kind: AssignmentCertKindV2) -> AssignmentCertV2 { let mut prng = rand_core::OsRng; let keypair = schnorrkel::Keypair::generate_with(&mut prng); let (inout, proof, _) = keypair.vrf_sign(ctx.bytes(msg)); - let preout = inout.to_output(); + let out = inout.to_output(); - AssignmentCertV2 { - kind, - vrf: VrfSignature { pre_output: VrfPreOutput(preout), proof: VrfProof(proof) }, - } + AssignmentCertV2 { kind, vrf: VrfSignature { output: VrfOutput(out), proof: VrfProof(proof) } } } fn sign_approval( @@ -448,15 +439,6 @@ fn sign_approval( key.sign(&ApprovalVote(candidate_hash).signing_payload(session_index)).into() } -fn sign_approval_multiple_candidates( - key: Sr25519Keyring, - candidate_hashes: Vec, - session_index: SessionIndex, -) -> ValidatorSignature { - key.sign(&ApprovalVoteMultipleCandidates(&candidate_hashes).signing_payload(session_index)) - .into() -} - type VirtualOverseer = test_helpers::TestSubsystemContextHandle; #[derive(Default)] @@ -652,12 +634,7 @@ async fn check_and_import_approval( overseer, FromOrchestra::Communication { msg: ApprovalVotingMessage::CheckAndImportApproval( - IndirectSignedApprovalVoteV2 { - block_hash, - candidate_indices: candidate_index.into(), - validator, - signature, - }, + IndirectSignedApprovalVote { block_hash, candidate_index, validator, signature }, tx, ), }, @@ -1020,15 +997,6 @@ async fn import_block( si_tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); } ); - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); } assert_matches!( @@ -2030,91 +1998,6 @@ fn forkful_import_at_same_height_act_on_leaf() { }); } -#[test] -fn test_signing_a_single_candidate_is_backwards_compatible() { - let session_index = 1; - let block_hash = Hash::repeat_byte(0x01); - let candidate_descriptors = (1..10) - .into_iter() - .map(|val| make_candidate(ParaId::from(val as u32), &block_hash)) - .collect::>(); - - let candidate_hashes = candidate_descriptors - .iter() - .map(|candidate_descriptor| candidate_descriptor.hash()) - .collect_vec(); - - let first_descriptor = candidate_descriptors.first().unwrap(); - - let candidate_hash = first_descriptor.hash(); - - let sig_a = sign_approval(Sr25519Keyring::Alice, candidate_hash, session_index); - - let sig_b = sign_approval(Sr25519Keyring::Alice, candidate_hash, session_index); - - assert!(DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) - .check_signature( - &Sr25519Keyring::Alice.public().into(), - candidate_hash, - session_index, - &sig_a, - ) - .is_ok()); - - assert!(DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) - .check_signature( - &Sr25519Keyring::Alice.public().into(), - candidate_hash, - session_index, - &sig_b, - ) - .is_ok()); - - let sig_c = sign_approval_multiple_candidates( - Sr25519Keyring::Alice, - vec![candidate_hash], - session_index, - ); - - assert!(DisputeStatement::Valid( - ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(vec![candidate_hash]) - ) - .check_signature(&Sr25519Keyring::Alice.public().into(), candidate_hash, session_index, &sig_c,) - .is_ok()); - - assert!(DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) - .check_signature( - &Sr25519Keyring::Alice.public().into(), - candidate_hash, - session_index, - &sig_c, - ) - .is_ok()); - - assert!(DisputeStatement::Valid( - ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(vec![candidate_hash]) - ) - .check_signature(&Sr25519Keyring::Alice.public().into(), candidate_hash, session_index, &sig_a,) - .is_ok()); - - let sig_all = sign_approval_multiple_candidates( - Sr25519Keyring::Alice, - candidate_hashes.clone(), - session_index, - ); - - assert!(DisputeStatement::Valid( - ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(candidate_hashes.clone()) - ) - .check_signature( - &Sr25519Keyring::Alice.public().into(), - *candidate_hashes.first().expect("test"), - session_index, - &sig_all, - ) - .is_ok()); -} - #[test] fn import_checked_approval_updates_entries_and_schedules() { let config = HarnessConfig::default(); @@ -2831,29 +2714,11 @@ async fn handle_double_assignment_import( } ); - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request(_, RuntimeApiRequest::ApprovalVotingParams(_, sender))) => { - let _ = sender.send(Ok(ApprovalVotingParams { - max_approval_coalesce_count: 1, - })); - } - ); - assert_matches!( overseer_recv(virtual_overseer).await, AllMessages::ApprovalDistribution(ApprovalDistributionMessage::DistributeApproval(_)) ); - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request(_, RuntimeApiRequest::ApprovalVotingParams(_, sender))) => { - let _ = sender.send(Ok(ApprovalVotingParams { - max_approval_coalesce_count: 1, - })); - } - ); - assert_matches!( overseer_recv(virtual_overseer).await, AllMessages::ApprovalDistribution(ApprovalDistributionMessage::DistributeApproval(_)) @@ -3588,455 +3453,3 @@ fn waits_until_approving_assignments_are_old_enough() { virtual_overseer }); } - -#[test] -fn test_approval_is_sent_on_max_approval_coalesce_count() { - let assignment_criteria = Box::new(MockAssignmentCriteria( - || { - let mut assignments = HashMap::new(); - let _ = assignments.insert( - CoreIndex(0), - approval_db::v2::OurAssignment { - cert: garbage_assignment_cert(AssignmentCertKind::RelayVRFModulo { sample: 0 }) - .into(), - tranche: 0, - validator_index: ValidatorIndex(0), - triggered: false, - } - .into(), - ); - - let assignments_cert = - garbage_assignment_cert_v2(AssignmentCertKindV2::RelayVRFModuloCompact { - core_bitfield: vec![CoreIndex(0), CoreIndex(1), CoreIndex(2)] - .try_into() - .unwrap(), - }); - let _ = assignments.insert( - CoreIndex(0), - approval_db::v2::OurAssignment { - cert: assignments_cert.clone(), - tranche: 0, - validator_index: ValidatorIndex(0), - triggered: false, - } - .into(), - ); - - let _ = assignments.insert( - CoreIndex(1), - approval_db::v2::OurAssignment { - cert: assignments_cert.clone(), - tranche: 0, - validator_index: ValidatorIndex(0), - triggered: false, - } - .into(), - ); - assignments - }, - |_| Ok(0), - )); - - let config = HarnessConfigBuilder::default().assignment_criteria(assignment_criteria).build(); - let store = config.backend(); - - test_harness(config, |test_harness| async move { - let TestHarness { mut virtual_overseer, clock, sync_oracle_handle: _sync_oracle_handle } = - test_harness; - - assert_matches!( - overseer_recv(&mut virtual_overseer).await, - AllMessages::ChainApi(ChainApiMessage::FinalizedBlockNumber(rx)) => { - rx.send(Ok(0)).unwrap(); - } - ); - - let block_hash = Hash::repeat_byte(0x01); - - let candidate_commitments = CandidateCommitments::default(); - - let candidate_receipt1 = { - let mut receipt = dummy_candidate_receipt(block_hash); - receipt.descriptor.para_id = ParaId::from(1_u32); - receipt.commitments_hash = candidate_commitments.hash(); - receipt - }; - - let candidate_hash1 = candidate_receipt1.hash(); - - let candidate_receipt2 = { - let mut receipt = dummy_candidate_receipt(block_hash); - receipt.descriptor.para_id = ParaId::from(2_u32); - receipt.commitments_hash = candidate_commitments.hash(); - receipt - }; - - let slot = Slot::from(1); - let candidate_index1 = 0; - let candidate_index2 = 1; - - let validators = vec![ - Sr25519Keyring::Alice, - Sr25519Keyring::Bob, - Sr25519Keyring::Charlie, - Sr25519Keyring::Dave, - Sr25519Keyring::Eve, - ]; - let session_info = SessionInfo { - validator_groups: IndexedVec::>::from(vec![ - vec![ValidatorIndex(0), ValidatorIndex(1)], - vec![ValidatorIndex(2)], - vec![ValidatorIndex(3), ValidatorIndex(4)], - ]), - ..session_info(&validators) - }; - - let candidates = Some(vec![ - (candidate_receipt1.clone(), CoreIndex(0), GroupIndex(0)), - (candidate_receipt2.clone(), CoreIndex(1), GroupIndex(1)), - ]); - ChainBuilder::new() - .add_block( - block_hash, - ChainBuilder::GENESIS_HASH, - 1, - BlockConfig { - slot, - candidates: candidates.clone(), - session_info: Some(session_info.clone()), - }, - ) - .build(&mut virtual_overseer) - .await; - - assert!(!clock.inner.lock().current_wakeup_is(1)); - clock.inner.lock().wakeup_all(1); - - assert!(clock.inner.lock().current_wakeup_is(slot_to_tick(slot))); - clock.inner.lock().wakeup_all(slot_to_tick(slot)); - - futures_timer::Delay::new(Duration::from_millis(200)).await; - - clock.inner.lock().wakeup_all(slot_to_tick(slot + 2)); - - assert_eq!(clock.inner.lock().wakeups.len(), 0); - - futures_timer::Delay::new(Duration::from_millis(200)).await; - - let candidate_entry = store.load_candidate_entry(&candidate_hash1).unwrap().unwrap(); - let our_assignment = - candidate_entry.approval_entry(&block_hash).unwrap().our_assignment().unwrap(); - assert!(our_assignment.triggered()); - - handle_approval_on_max_coalesce_count( - &mut virtual_overseer, - vec![candidate_index1, candidate_index2], - ) - .await; - - virtual_overseer - }); -} - -async fn handle_approval_on_max_coalesce_count( - virtual_overseer: &mut VirtualOverseer, - candidate_indicies: Vec, -) { - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::ApprovalDistribution(ApprovalDistributionMessage::DistributeAssignment( - _, - c_indices, - )) => { - assert_eq!(TryInto::::try_into(candidate_indicies.clone()).unwrap(), c_indices); - } - ); - - for _ in &candidate_indicies { - recover_available_data(virtual_overseer).await; - fetch_validation_code(virtual_overseer).await; - } - - for _ in &candidate_indicies { - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::CandidateValidation(CandidateValidationMessage::ValidateFromExhaustive{exec_kind, response_sender, ..}) if exec_kind == PvfExecKind::Approval => { - response_sender.send(Ok(ValidationResult::Valid(Default::default(), Default::default()))) - .unwrap(); - } - ); - } - - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request(_, RuntimeApiRequest::ApprovalVotingParams(_, sender))) => { - let _ = sender.send(Ok(ApprovalVotingParams { - max_approval_coalesce_count: 2, - })); - } - ); - - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request(_, RuntimeApiRequest::ApprovalVotingParams(_, sender))) => { - let _ = sender.send(Ok(ApprovalVotingParams { - max_approval_coalesce_count: 2, - })); - } - ); - - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::ApprovalDistribution(ApprovalDistributionMessage::DistributeApproval(vote)) => { - assert_eq!(TryInto::::try_into(candidate_indicies).unwrap(), vote.candidate_indices); - } - ); - - // Assert that there are no more messages being sent by the subsystem - assert!(overseer_recv(virtual_overseer).timeout(TIMEOUT / 2).await.is_none()); -} - -async fn handle_approval_on_max_wait_time( - virtual_overseer: &mut VirtualOverseer, - candidate_indicies: Vec, - clock: Box, -) { - const TICK_NOW_BEGIN: u64 = 1; - const MAX_COALESCE_COUNT: u32 = 3; - - clock.inner.lock().set_tick(TICK_NOW_BEGIN); - - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::ApprovalDistribution(ApprovalDistributionMessage::DistributeAssignment( - _, - c_indices, - )) => { - assert_eq!(TryInto::::try_into(candidate_indicies.clone()).unwrap(), c_indices); - } - ); - - for _ in &candidate_indicies { - recover_available_data(virtual_overseer).await; - fetch_validation_code(virtual_overseer).await; - } - - for _ in &candidate_indicies { - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::CandidateValidation(CandidateValidationMessage::ValidateFromExhaustive{exec_kind, response_sender, ..}) if exec_kind == PvfExecKind::Approval => { - response_sender.send(Ok(ValidationResult::Valid(Default::default(), Default::default()))) - .unwrap(); - } - ); - } - - // First time we fetch the configuration when we are ready to approve the first candidate - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request(_, RuntimeApiRequest::ApprovalVotingParams(_, sender))) => { - let _ = sender.send(Ok(ApprovalVotingParams { - max_approval_coalesce_count: MAX_COALESCE_COUNT, - })); - } - ); - - // Second time we fetch the configuration when we are ready to approve the second candidate - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request(_, RuntimeApiRequest::ApprovalVotingParams(_, sender))) => { - let _ = sender.send(Ok(ApprovalVotingParams { - max_approval_coalesce_count: MAX_COALESCE_COUNT, - })); - } - ); - - assert!(overseer_recv(virtual_overseer).timeout(TIMEOUT / 2).await.is_none()); - - // Move the clock just before we should send the approval - clock - .inner - .lock() - .set_tick(MAX_APPROVAL_COALESCE_WAIT_TICKS as Tick + TICK_NOW_BEGIN - 1); - - assert!(overseer_recv(virtual_overseer).timeout(TIMEOUT / 2).await.is_none()); - - // Move the clock tick, so we can trigger a force sending of the approvals - clock - .inner - .lock() - .set_tick(MAX_APPROVAL_COALESCE_WAIT_TICKS as Tick + TICK_NOW_BEGIN); - - // Third time we fetch the configuration when timer expires and we are ready to sent the - // approval - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi(RuntimeApiMessage::Request(_, RuntimeApiRequest::ApprovalVotingParams(_, sender))) => { - let _ = sender.send(Ok(ApprovalVotingParams { - max_approval_coalesce_count: 3, - })); - } - ); - - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::ApprovalDistribution(ApprovalDistributionMessage::DistributeApproval(vote)) => { - assert_eq!(TryInto::::try_into(candidate_indicies).unwrap(), vote.candidate_indices); - } - ); - - // Assert that there are no more messages being sent by the subsystem - assert!(overseer_recv(virtual_overseer).timeout(TIMEOUT / 2).await.is_none()); -} - -#[test] -fn test_approval_is_sent_on_max_approval_coalesce_wait() { - let assignment_criteria = Box::new(MockAssignmentCriteria( - || { - let mut assignments = HashMap::new(); - let _ = assignments.insert( - CoreIndex(0), - approval_db::v2::OurAssignment { - cert: garbage_assignment_cert(AssignmentCertKind::RelayVRFModulo { sample: 0 }) - .into(), - tranche: 0, - validator_index: ValidatorIndex(0), - triggered: false, - } - .into(), - ); - - let assignments_cert = - garbage_assignment_cert_v2(AssignmentCertKindV2::RelayVRFModuloCompact { - core_bitfield: vec![CoreIndex(0), CoreIndex(1), CoreIndex(2)] - .try_into() - .unwrap(), - }); - let _ = assignments.insert( - CoreIndex(0), - approval_db::v2::OurAssignment { - cert: assignments_cert.clone(), - tranche: 0, - validator_index: ValidatorIndex(0), - triggered: false, - } - .into(), - ); - - let _ = assignments.insert( - CoreIndex(1), - approval_db::v2::OurAssignment { - cert: assignments_cert.clone(), - tranche: 0, - validator_index: ValidatorIndex(0), - triggered: false, - } - .into(), - ); - assignments - }, - |_| Ok(0), - )); - - let config = HarnessConfigBuilder::default().assignment_criteria(assignment_criteria).build(); - let store = config.backend(); - - test_harness(config, |test_harness| async move { - let TestHarness { mut virtual_overseer, clock, sync_oracle_handle: _sync_oracle_handle } = - test_harness; - - assert_matches!( - overseer_recv(&mut virtual_overseer).await, - AllMessages::ChainApi(ChainApiMessage::FinalizedBlockNumber(rx)) => { - rx.send(Ok(0)).unwrap(); - } - ); - - let block_hash = Hash::repeat_byte(0x01); - - let candidate_commitments = CandidateCommitments::default(); - - let candidate_receipt1 = { - let mut receipt = dummy_candidate_receipt(block_hash); - receipt.descriptor.para_id = ParaId::from(1_u32); - receipt.commitments_hash = candidate_commitments.hash(); - receipt - }; - - let candidate_hash1 = candidate_receipt1.hash(); - - let candidate_receipt2 = { - let mut receipt = dummy_candidate_receipt(block_hash); - receipt.descriptor.para_id = ParaId::from(2_u32); - receipt.commitments_hash = candidate_commitments.hash(); - receipt - }; - - let slot = Slot::from(1); - let candidate_index1 = 0; - let candidate_index2 = 1; - - let validators = vec![ - Sr25519Keyring::Alice, - Sr25519Keyring::Bob, - Sr25519Keyring::Charlie, - Sr25519Keyring::Dave, - Sr25519Keyring::Eve, - ]; - let session_info = SessionInfo { - validator_groups: IndexedVec::>::from(vec![ - vec![ValidatorIndex(0), ValidatorIndex(1)], - vec![ValidatorIndex(2)], - vec![ValidatorIndex(3), ValidatorIndex(4)], - ]), - ..session_info(&validators) - }; - - let candidates = Some(vec![ - (candidate_receipt1.clone(), CoreIndex(0), GroupIndex(0)), - (candidate_receipt2.clone(), CoreIndex(1), GroupIndex(1)), - ]); - ChainBuilder::new() - .add_block( - block_hash, - ChainBuilder::GENESIS_HASH, - 1, - BlockConfig { - slot, - candidates: candidates.clone(), - session_info: Some(session_info.clone()), - }, - ) - .build(&mut virtual_overseer) - .await; - - assert!(!clock.inner.lock().current_wakeup_is(1)); - clock.inner.lock().wakeup_all(1); - - assert!(clock.inner.lock().current_wakeup_is(slot_to_tick(slot))); - clock.inner.lock().wakeup_all(slot_to_tick(slot)); - - futures_timer::Delay::new(Duration::from_millis(200)).await; - - clock.inner.lock().wakeup_all(slot_to_tick(slot + 2)); - - assert_eq!(clock.inner.lock().wakeups.len(), 0); - - futures_timer::Delay::new(Duration::from_millis(200)).await; - - let candidate_entry = store.load_candidate_entry(&candidate_hash1).unwrap().unwrap(); - let our_assignment = - candidate_entry.approval_entry(&block_hash).unwrap().our_assignment().unwrap(); - assert!(our_assignment.triggered()); - - handle_approval_on_max_wait_time( - &mut virtual_overseer, - vec![candidate_index1, candidate_index2], - clock, - ) - .await; - - virtual_overseer - }); -} diff --git a/polkadot/node/core/approval-voting/src/time.rs b/polkadot/node/core/approval-voting/src/time.rs index 61091f3c34c..a45866402c8 100644 --- a/polkadot/node/core/approval-voting/src/time.rs +++ b/polkadot/node/core/approval-voting/src/time.rs @@ -16,23 +16,14 @@ //! Time utilities for approval voting. -use futures::{ - future::BoxFuture, - prelude::*, - stream::{FusedStream, FuturesUnordered}, - Stream, StreamExt, -}; - +use futures::prelude::*; use polkadot_node_primitives::approval::v1::DelayTranche; use sp_consensus_slots::Slot; use std::{ - collections::HashSet, pin::Pin, - task::Poll, time::{Duration, SystemTime}, }; -use polkadot_primitives::{Hash, ValidatorIndex}; const TICK_DURATION_MILLIS: u64 = 500; /// A base unit of time, starting from the Unix epoch, split into half-second intervals. @@ -97,157 +88,3 @@ pub(crate) fn slot_number_to_tick(slot_duration_millis: u64, slot: Slot) -> Tick let ticks_per_slot = slot_duration_millis / TICK_DURATION_MILLIS; u64::from(slot) * ticks_per_slot } - -/// A list of delayed futures that gets triggered when the waiting time has expired and it is -/// time to sign the candidate. -/// We have a timer per relay-chain block. -#[derive(Default)] -pub struct DelayedApprovalTimer { - timers: FuturesUnordered>, - blocks: HashSet, -} - -impl DelayedApprovalTimer { - /// Starts a single timer per block hash - /// - /// Guarantees that if a timer already exits for the give block hash, - /// no additional timer is started. - pub(crate) fn maybe_arm_timer( - &mut self, - wait_untill: Tick, - clock: &dyn Clock, - block_hash: Hash, - validator_index: ValidatorIndex, - ) { - if self.blocks.insert(block_hash) { - let clock_wait = clock.wait(wait_untill); - self.timers.push(Box::pin(async move { - clock_wait.await; - (block_hash, validator_index) - })); - } - } -} - -impl Stream for DelayedApprovalTimer { - type Item = (Hash, ValidatorIndex); - - fn poll_next( - mut self: std::pin::Pin<&mut Self>, - cx: &mut std::task::Context<'_>, - ) -> std::task::Poll> { - let poll_result = self.timers.poll_next_unpin(cx); - match poll_result { - Poll::Ready(Some(result)) => { - self.blocks.remove(&result.0); - Poll::Ready(Some(result)) - }, - _ => poll_result, - } - } -} - -impl FusedStream for DelayedApprovalTimer { - fn is_terminated(&self) -> bool { - self.timers.is_terminated() - } -} - -#[cfg(test)] -mod tests { - use std::time::Duration; - - use futures::{executor::block_on, FutureExt, StreamExt}; - use futures_timer::Delay; - use polkadot_primitives::{Hash, ValidatorIndex}; - - use crate::time::{Clock, SystemClock}; - - use super::DelayedApprovalTimer; - - #[test] - fn test_select_empty_timer() { - block_on(async move { - let mut timer = DelayedApprovalTimer::default(); - - for _ in 1..10 { - let result = futures::select!( - _ = timer.select_next_some() => { - 0 - } - // Only this arm should fire - _ = Delay::new(Duration::from_millis(100)).fuse() => { - 1 - } - ); - - assert_eq!(result, 1); - } - }); - } - - #[test] - fn test_timer_functionality() { - block_on(async move { - let mut timer = DelayedApprovalTimer::default(); - let test_hashes = - vec![Hash::repeat_byte(0x01), Hash::repeat_byte(0x02), Hash::repeat_byte(0x03)]; - for (index, hash) in test_hashes.iter().enumerate() { - timer.maybe_arm_timer( - SystemClock.tick_now() + index as u64, - &SystemClock, - *hash, - ValidatorIndex::from(2), - ); - timer.maybe_arm_timer( - SystemClock.tick_now() + index as u64, - &SystemClock, - *hash, - ValidatorIndex::from(2), - ); - } - let timeout_hash = Hash::repeat_byte(0x02); - for i in 0..test_hashes.len() * 2 { - let result = futures::select!( - (hash, _) = timer.select_next_some() => { - hash - } - // Timers should fire only once, so for the rest of the iterations we should timeout through here. - _ = Delay::new(Duration::from_secs(2)).fuse() => { - timeout_hash - } - ); - assert_eq!(test_hashes.get(i).cloned().unwrap_or(timeout_hash), result); - } - - // Now check timer can be restarted if already fired - for (index, hash) in test_hashes.iter().enumerate() { - timer.maybe_arm_timer( - SystemClock.tick_now() + index as u64, - &SystemClock, - *hash, - ValidatorIndex::from(2), - ); - timer.maybe_arm_timer( - SystemClock.tick_now() + index as u64, - &SystemClock, - *hash, - ValidatorIndex::from(2), - ); - } - - for i in 0..test_hashes.len() * 2 { - let result = futures::select!( - (hash, _) = timer.select_next_some() => { - hash - } - // Timers should fire only once, so for the rest of the iterations we should timeout through here. - _ = Delay::new(Duration::from_secs(2)).fuse() => { - timeout_hash - } - ); - assert_eq!(test_hashes.get(i).cloned().unwrap_or(timeout_hash), result); - } - }); - } -} diff --git a/polkadot/node/core/av-store/Cargo.toml b/polkadot/node/core/av-store/Cargo.toml index 4b2baf3fc55..3fa81d064a8 100644 --- a/polkadot/node/core/av-store/Cargo.toml +++ b/polkadot/node/core/av-store/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] futures = "0.3.21" futures-timer = "3.0.2" diff --git a/polkadot/node/core/backing/Cargo.toml b/polkadot/node/core/backing/Cargo.toml index 16ed11e7eec..7a6ce5de8cb 100644 --- a/polkadot/node/core/backing/Cargo.toml +++ b/polkadot/node/core/backing/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "The Candidate Backing Subsystem. Tracks parachain candidates that can be backed, as well as the issuance of statements about candidates." -[lints] -workspace = true - [dependencies] futures = "0.3.21" sp-keystore = { path = "../../../../substrate/primitives/keystore" } diff --git a/polkadot/node/core/bitfield-signing/Cargo.toml b/polkadot/node/core/bitfield-signing/Cargo.toml index 880273c0e7f..712a01b46b1 100644 --- a/polkadot/node/core/bitfield-signing/Cargo.toml +++ b/polkadot/node/core/bitfield-signing/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "Bitfield signing subsystem for the Polkadot node" -[lints] -workspace = true - [dependencies] futures = "0.3.21" gum = { package = "tracing-gum", path = "../../gum" } diff --git a/polkadot/node/core/candidate-validation/Cargo.toml b/polkadot/node/core/candidate-validation/Cargo.toml index 9ded9e58a16..a2e88778532 100644 --- a/polkadot/node/core/candidate-validation/Cargo.toml +++ b/polkadot/node/core/candidate-validation/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] async-trait = "0.1.57" futures = "0.3.21" diff --git a/polkadot/node/core/candidate-validation/src/lib.rs b/polkadot/node/core/candidate-validation/src/lib.rs index 18c27968915..4e02e3e9299 100644 --- a/polkadot/node/core/candidate-validation/src/lib.rs +++ b/polkadot/node/core/candidate-validation/src/lib.rs @@ -88,8 +88,6 @@ pub struct Config { pub artifacts_cache_path: PathBuf, /// The version of the node. `None` can be passed to skip the version check (only for tests). pub node_version: Option, - /// Whether the node is attempting to run as a secure validator. - pub secure_validator_mode: bool, /// Path to the preparation worker binary pub prep_worker_path: PathBuf, /// Path to the execution worker binary @@ -135,19 +133,12 @@ async fn run( mut ctx: Context, metrics: Metrics, pvf_metrics: polkadot_node_core_pvf::Metrics, - Config { - artifacts_cache_path, - node_version, - secure_validator_mode, - prep_worker_path, - exec_worker_path, - }: Config, + Config { artifacts_cache_path, node_version, prep_worker_path, exec_worker_path }: Config, ) -> SubsystemResult<()> { let (validation_host, task) = polkadot_node_core_pvf::start( polkadot_node_core_pvf::Config::new( artifacts_cache_path, node_version, - secure_validator_mode, prep_worker_path, exec_worker_path, ), diff --git a/polkadot/node/core/chain-api/Cargo.toml b/polkadot/node/core/chain-api/Cargo.toml index 32962c9bda4..fa824e78ffe 100644 --- a/polkadot/node/core/chain-api/Cargo.toml +++ b/polkadot/node/core/chain-api/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "The Chain API subsystem provides access to chain related utility functions like block number to hash conversions." -[lints] -workspace = true - [dependencies] futures = "0.3.21" gum = { package = "tracing-gum", path = "../../gum" } diff --git a/polkadot/node/core/chain-selection/Cargo.toml b/polkadot/node/core/chain-selection/Cargo.toml index 6056ddd41cd..7678379870e 100644 --- a/polkadot/node/core/chain-selection/Cargo.toml +++ b/polkadot/node/core/chain-selection/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] futures = "0.3.21" futures-timer = "3" diff --git a/polkadot/node/core/dispute-coordinator/Cargo.toml b/polkadot/node/core/dispute-coordinator/Cargo.toml index 8ec9bcbe070..e2086db708f 100644 --- a/polkadot/node/core/dispute-coordinator/Cargo.toml +++ b/polkadot/node/core/dispute-coordinator/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] futures = "0.3.21" gum = { package = "tracing-gum", path = "../../gum" } diff --git a/polkadot/node/core/dispute-coordinator/src/import.rs b/polkadot/node/core/dispute-coordinator/src/import.rs index 98c12bd509b..837ad7856e7 100644 --- a/polkadot/node/core/dispute-coordinator/src/import.rs +++ b/polkadot/node/core/dispute-coordinator/src/import.rs @@ -34,9 +34,9 @@ use polkadot_node_primitives::{ use polkadot_node_subsystem::overseer; use polkadot_node_subsystem_util::runtime::RuntimeInfo; use polkadot_primitives::{ - CandidateHash, CandidateReceipt, DisputeStatement, ExecutorParams, Hash, IndexedVec, - SessionIndex, SessionInfo, ValidDisputeStatementKind, ValidatorId, ValidatorIndex, - ValidatorPair, ValidatorSignature, + CandidateReceipt, DisputeStatement, ExecutorParams, Hash, IndexedVec, SessionIndex, + SessionInfo, ValidDisputeStatementKind, ValidatorId, ValidatorIndex, ValidatorPair, + ValidatorSignature, }; use sc_keystore::LocalKeystore; @@ -126,9 +126,7 @@ impl OwnVoteState { let our_valid_votes = controlled_indices .iter() .filter_map(|i| votes.valid.raw().get_key_value(i)) - .map(|(index, (kind, sig))| { - (*index, (DisputeStatement::Valid(kind.clone()), sig.clone())) - }); + .map(|(index, (kind, sig))| (*index, (DisputeStatement::Valid(*kind), sig.clone()))); let our_invalid_votes = controlled_indices .iter() .filter_map(|i| votes.invalid.get_key_value(i)) @@ -307,7 +305,7 @@ impl CandidateVoteState { DisputeStatement::Valid(valid_kind) => { let fresh = votes.valid.insert_vote( val_index, - valid_kind.clone(), + *valid_kind, statement.into_validator_signature(), ); if fresh { @@ -513,7 +511,7 @@ impl ImportResult { pub fn import_approval_votes( self, env: &CandidateEnvironment, - approval_votes: HashMap, ValidatorSignature)>, + approval_votes: HashMap, now: Timestamp, ) -> Self { let Self { @@ -527,33 +525,19 @@ impl ImportResult { let (mut votes, _) = new_state.into_old_state(); - for (index, (candidate_hashes, sig)) in approval_votes.into_iter() { + for (index, sig) in approval_votes.into_iter() { debug_assert!( { let pub_key = &env.session_info().validators.get(index).expect("indices are validated by approval-voting subsystem; qed"); + let candidate_hash = votes.candidate_receipt.hash(); let session_index = env.session_index(); - candidate_hashes.contains(&votes.candidate_receipt.hash()) && DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(candidate_hashes.clone())) - .check_signature(pub_key, *candidate_hashes.first().expect("Valid votes have at least one candidate; qed"), session_index, &sig) + DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) + .check_signature(pub_key, candidate_hash, session_index, &sig) .is_ok() }, "Signature check for imported approval votes failed! This is a serious bug. Session: {:?}, candidate hash: {:?}, validator index: {:?}", env.session_index(), votes.candidate_receipt.hash(), index ); - if votes.valid.insert_vote( - index, - // There is a hidden dependency here between approval-voting and this subsystem. - // We should be able to start emitting - // ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates only after: - // 1. Runtime have been upgraded to know about the new format. - // 2. All nodes have been upgraded to know about the new format. - // Once those two requirements have been met we should be able to increase - // max_approval_coalesce_count to values greater than 1. - if candidate_hashes.len() > 1 { - ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(candidate_hashes) - } else { - ValidDisputeStatementKind::ApprovalChecking - }, - sig, - ) { + if votes.valid.insert_vote(index, ValidDisputeStatementKind::ApprovalChecking, sig) { imported_valid_votes += 1; imported_approval_votes += 1; } diff --git a/polkadot/node/core/dispute-coordinator/src/initialized.rs b/polkadot/node/core/dispute-coordinator/src/initialized.rs index d9cd4e39d3c..e44530b3f1b 100644 --- a/polkadot/node/core/dispute-coordinator/src/initialized.rs +++ b/polkadot/node/core/dispute-coordinator/src/initialized.rs @@ -642,7 +642,7 @@ impl Initialized { }; debug_assert!( SignedDisputeStatement::new_checked( - DisputeStatement::Valid(valid_statement_kind.clone()), + DisputeStatement::Valid(valid_statement_kind), candidate_hash, session, validator_public.clone(), @@ -656,7 +656,7 @@ impl Initialized { ); let signed_dispute_statement = SignedDisputeStatement::new_unchecked_from_trusted_source( - DisputeStatement::Valid(valid_statement_kind.clone()), + DisputeStatement::Valid(valid_statement_kind), candidate_hash, session, validator_public, diff --git a/polkadot/node/core/dispute-coordinator/src/lib.rs b/polkadot/node/core/dispute-coordinator/src/lib.rs index 5067d3673da..e96fee81240 100644 --- a/polkadot/node/core/dispute-coordinator/src/lib.rs +++ b/polkadot/node/core/dispute-coordinator/src/lib.rs @@ -576,7 +576,7 @@ pub fn make_dispute_message( .next() .ok_or(DisputeMessageCreationError::NoOppositeVote)?; let other_vote = SignedDisputeStatement::new_checked( - DisputeStatement::Valid(statement_kind.clone()), + DisputeStatement::Valid(*statement_kind), *our_vote.candidate_hash(), our_vote.session_index(), validators diff --git a/polkadot/node/core/dispute-coordinator/src/tests.rs b/polkadot/node/core/dispute-coordinator/src/tests.rs index da449773fe8..9254c2a851c 100644 --- a/polkadot/node/core/dispute-coordinator/src/tests.rs +++ b/polkadot/node/core/dispute-coordinator/src/tests.rs @@ -61,11 +61,10 @@ use polkadot_node_subsystem_test_helpers::{ make_buffered_subsystem_context, mock::new_leaf, TestSubsystemContextHandle, }; use polkadot_primitives::{ - vstaging::NodeFeatures, ApprovalVote, BlockNumber, CandidateCommitments, CandidateEvent, - CandidateHash, CandidateReceipt, CoreIndex, DisputeStatement, ExecutorParams, GroupIndex, Hash, - HeadData, Header, IndexedVec, MultiDisputeStatementSet, ScrapedOnChainVotes, SessionIndex, - SessionInfo, SigningContext, ValidDisputeStatementKind, ValidatorId, ValidatorIndex, - ValidatorSignature, + ApprovalVote, BlockNumber, CandidateCommitments, CandidateEvent, CandidateHash, + CandidateReceipt, CoreIndex, DisputeStatement, ExecutorParams, GroupIndex, Hash, HeadData, + Header, IndexedVec, MultiDisputeStatementSet, ScrapedOnChainVotes, SessionIndex, SessionInfo, + SigningContext, ValidDisputeStatementKind, ValidatorId, ValidatorIndex, ValidatorSignature, }; use crate::{ @@ -353,15 +352,6 @@ impl TestState { let _ = tx.send(Ok(Some(ExecutorParams::default()))); } ); - - assert_matches!( - overseer_recv(virtual_overseer).await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); } } @@ -661,7 +651,7 @@ fn make_candidate_included_event(candidate_receipt: CandidateReceipt) -> Candida pub async fn handle_approval_vote_request( ctx_handle: &mut VirtualOverseer, expected_hash: &CandidateHash, - votes_to_send: HashMap, ValidatorSignature)>, + votes_to_send: HashMap, ) { assert_matches!( ctx_handle.recv().await, @@ -868,12 +858,9 @@ fn approval_vote_import_works() { .await; gum::trace!("After sending `ImportStatements`"); - let approval_votes = [( - ValidatorIndex(4), - (vec![candidate_receipt1.hash()], approval_vote.into_validator_signature()), - )] - .into_iter() - .collect(); + let approval_votes = [(ValidatorIndex(4), approval_vote.into_validator_signature())] + .into_iter() + .collect(); handle_approval_vote_request(&mut virtual_overseer, &candidate_hash1, approval_votes) .await; @@ -3505,14 +3492,6 @@ fn session_info_is_requested_only_once() { let _ = tx.send(Ok(Some(ExecutorParams::default()))); } ); - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); test_state }) }); @@ -3573,15 +3552,6 @@ fn session_info_big_jump_works() { let _ = tx.send(Ok(Some(ExecutorParams::default()))); } ); - - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); } test_state }) @@ -3642,14 +3612,6 @@ fn session_info_small_jump_works() { let _ = tx.send(Ok(Some(ExecutorParams::default()))); } ); - assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); } test_state }) diff --git a/polkadot/node/core/parachains-inherent/Cargo.toml b/polkadot/node/core/parachains-inherent/Cargo.toml index 8d84b586a30..c783f21e24d 100644 --- a/polkadot/node/core/parachains-inherent/Cargo.toml +++ b/polkadot/node/core/parachains-inherent/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "Parachains inherent data provider for Polkadot node" -[lints] -workspace = true - [dependencies] futures = "0.3.21" futures-timer = "3.0.2" diff --git a/polkadot/node/core/prospective-parachains/Cargo.toml b/polkadot/node/core/prospective-parachains/Cargo.toml index e6b6aa5e15d..9db1259e61d 100644 --- a/polkadot/node/core/prospective-parachains/Cargo.toml +++ b/polkadot/node/core/prospective-parachains/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "The Prospective Parachains subsystem. Tracks and handles prospective parachain fragments." -[lints] -workspace = true - [dependencies] futures = "0.3.19" gum = { package = "tracing-gum", path = "../../gum" } diff --git a/polkadot/node/core/prospective-parachains/src/tests.rs b/polkadot/node/core/prospective-parachains/src/tests.rs index 51a5ef622c0..d2cd23fe95f 100644 --- a/polkadot/node/core/prospective-parachains/src/tests.rs +++ b/polkadot/node/core/prospective-parachains/src/tests.rs @@ -101,9 +101,11 @@ fn test_harness>( let mut view = View::new(); let subsystem = async move { - match run_iteration(&mut context, &mut view, &Metrics(None)).await { - Ok(()) => {}, - Err(e) => panic!("{:?}", e), + loop { + match run_iteration(&mut context, &mut view, &Metrics(None)).await { + Ok(()) => break, + Err(e) => panic!("{:?}", e), + } } view diff --git a/polkadot/node/core/provisioner/Cargo.toml b/polkadot/node/core/provisioner/Cargo.toml index 2d18bd29c1c..13ecb356f2c 100644 --- a/polkadot/node/core/provisioner/Cargo.toml +++ b/polkadot/node/core/provisioner/Cargo.toml @@ -1,14 +1,11 @@ [package] name = "polkadot-node-core-provisioner" version = "1.0.0" -description = "Responsible for assembling a relay chain block from a set of available parachain candidates" +description="Responsible for assembling a relay chain block from a set of available parachain candidates" authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } futures = "0.3.21" diff --git a/polkadot/node/core/provisioner/src/disputes/prioritized_selection/mod.rs b/polkadot/node/core/provisioner/src/disputes/prioritized_selection/mod.rs index cb55ce39bc8..096b73d271a 100644 --- a/polkadot/node/core/provisioner/src/disputes/prioritized_selection/mod.rs +++ b/polkadot/node/core/provisioner/src/disputes/prioritized_selection/mod.rs @@ -221,7 +221,7 @@ where votes.valid.retain(|validator_idx, (statement_kind, _)| { is_vote_worth_to_keep( validator_idx, - DisputeStatement::Valid(statement_kind.clone()), + DisputeStatement::Valid(*statement_kind), &onchain_state, ) }); diff --git a/polkadot/node/core/pvf-checker/Cargo.toml b/polkadot/node/core/pvf-checker/Cargo.toml index 274d8ee43bf..0326a20e5a5 100644 --- a/polkadot/node/core/pvf-checker/Cargo.toml +++ b/polkadot/node/core/pvf-checker/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] futures = "0.3.21" thiserror = "1.0.48" diff --git a/polkadot/node/core/pvf/Cargo.toml b/polkadot/node/core/pvf/Cargo.toml index 2642377b6e6..05509a5f853 100644 --- a/polkadot/node/core/pvf/Cargo.toml +++ b/polkadot/node/core/pvf/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] always-assert = "0.1" blake3 = "1.5" @@ -22,7 +19,6 @@ pin-project = "1.0.9" rand = "0.8.5" slotmap = "1.0" tempfile = "3.3.0" -thiserror = "1.0.31" tokio = { version = "1.24.2", features = ["fs", "process"] } parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive"] } @@ -43,7 +39,7 @@ polkadot-node-core-pvf-execute-worker = { path = "execute-worker", optional = tr [dev-dependencies] assert_matches = "1.4.0" -criterion = { version = "0.4.0", default-features = false, features = ["async_tokio", "cargo_bench_support"] } +criterion = { version = "0.4.0", default-features = false, features = ["cargo_bench_support", "async_tokio"] } hex-literal = "0.4.1" polkadot-node-core-pvf-common = { path = "common", features = ["test-utils"] } @@ -66,7 +62,7 @@ harness = false [features] ci-only-tests = [] -jemalloc-allocator = ["polkadot-node-core-pvf-common/jemalloc-allocator"] +jemalloc-allocator = [ "polkadot-node-core-pvf-common/jemalloc-allocator" ] # This feature is used to export test code to other crates without putting it in the production build. test-utils = [ "polkadot-node-core-pvf-execute-worker", diff --git a/polkadot/node/core/pvf/README.md b/polkadot/node/core/pvf/README.md deleted file mode 100644 index 796e17c05fa..00000000000 --- a/polkadot/node/core/pvf/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# PVF Host - -This is the PVF host, responsible for responding to requests from Candidate -Validation and spawning worker tasks to fulfill those requests. - -See also: - -- for more information: [the Implementer's Guide][impl-guide] -- for an explanation of terminology: [the Glossary][glossary] - -## Running basic tests - -Running `cargo test` in the `pvf/` directory will run unit and integration -tests. - -**Note:** some tests run only under Linux, amd64, and/or with the -`ci-only-tests` feature enabled. - -See the general [Testing][testing] instructions for more information on -**running tests** and **observing logs**. - -## Running a test-network with zombienet - -Since this crate is consensus-critical, for major changes it is highly -recommended to run a test-network. See the "Behavior tests" section of the -[Testing][testing] docs for full instructions. - -To run the PVF-specific zombienet test: - -```sh -RUST_LOG=parachain::pvf=trace zombienet --provider=native spawn zombienet_tests/functional/0001-parachains-pvf.toml -``` - -## Testing on Linux - -Some of the PVF functionality, especially related to security, is Linux-only, -and some is amd64-only. If you touch anything security-related, make sure to -test on Linux amd64! If you're on a Mac, you can either run a VM or you can hire -a VPS and use the open-source tool [EternalTerminal][et] to connect to it.[^et] - -[^et]: Unlike ssh, ET preserves your session across disconnects, and unlike -another popular persistent shell, mosh, it allows scrollback. - -[impl-guide]: https://paritytech.github.io/polkadot-sdk/book/pvf-prechecking.html#summary -[glossary]: https://paritytech.github.io/polkadot-sdk/book/glossary.html -[testing]: https://github.com/paritytech/polkadot-sdk/blob/master/polkadot/doc/testing.md -[et]: https://github.com/MisterTea/EternalTerminal diff --git a/polkadot/node/core/pvf/benches/host_prepare_rococo_runtime.rs b/polkadot/node/core/pvf/benches/host_prepare_rococo_runtime.rs index 2aea21361a3..e625a2303b5 100644 --- a/polkadot/node/core/pvf/benches/host_prepare_rococo_runtime.rs +++ b/polkadot/node/core/pvf/benches/host_prepare_rococo_runtime.rs @@ -28,9 +28,6 @@ use tokio::{runtime::Handle, sync::Mutex}; const TEST_PREPARATION_TIMEOUT: Duration = Duration::from_secs(30); struct TestHost { - // Keep a reference to the tempdir otherwise it gets deleted on drop. - #[allow(dead_code)] - cache_dir: tempfile::TempDir, host: Mutex, } @@ -45,14 +42,13 @@ impl TestHost { let mut config = Config::new( cache_dir.path().to_owned(), None, - false, prepare_worker_path, execute_worker_path, ); f(&mut config); let (host, task) = start(config, Metrics::default()).await.unwrap(); let _ = handle.spawn(task); - Self { host: Mutex::new(host), cache_dir } + Self { host: Mutex::new(host) } } async fn precheck_pvf( diff --git a/polkadot/node/core/pvf/common/Cargo.toml b/polkadot/node/core/pvf/common/Cargo.toml index c5c09300e8a..bfe1be9156f 100644 --- a/polkadot/node/core/pvf/common/Cargo.toml +++ b/polkadot/node/core/pvf/common/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] cfg-if = "1.0" cpu-time = "1.0.0" diff --git a/polkadot/node/core/pvf/common/src/executor_interface.rs b/polkadot/node/core/pvf/common/src/executor_intf.rs similarity index 98% rename from polkadot/node/core/pvf/common/src/executor_interface.rs rename to polkadot/node/core/pvf/common/src/executor_intf.rs index e634940dbe6..4bafc3f4291 100644 --- a/polkadot/node/core/pvf/common/src/executor_interface.rs +++ b/polkadot/node/core/pvf/common/src/executor_intf.rs @@ -175,9 +175,11 @@ pub fn params_to_wasmtime_semantics(par: &ExecutorParams) -> Semantics { /// Runs the prevalidation on the given code. Returns a [`RuntimeBlob`] if it succeeds. pub fn prevalidate(code: &[u8]) -> Result { - // Construct the runtime blob and do some basic checks for consistency. let blob = RuntimeBlob::new(code)?; - // In the future this function should take care of any further prevalidation logic. + // It's assumed this function will take care of any prevalidation logic + // that needs to be done. + // + // Do nothing for now. Ok(blob) } diff --git a/polkadot/node/core/pvf/common/src/lib.rs b/polkadot/node/core/pvf/common/src/lib.rs index abebd06f71a..c041c60aaf9 100644 --- a/polkadot/node/core/pvf/common/src/lib.rs +++ b/polkadot/node/core/pvf/common/src/lib.rs @@ -18,7 +18,7 @@ pub mod error; pub mod execute; -pub mod executor_interface; +pub mod executor_intf; pub mod prepare; pub mod pvf; pub mod worker; @@ -33,7 +33,6 @@ const LOG_TARGET: &str = "parachain::pvf-common"; pub const RUNTIME_VERSION: &str = env!("SUBSTRATE_WASMTIME_VERSION"); -use parity_scale_codec::{Decode, Encode}; use std::{ io::{self, Read, Write}, mem, @@ -48,11 +47,8 @@ pub mod tests { } /// Status of security features on the current system. -#[derive(Debug, Clone, Default, PartialEq, Eq, Encode, Decode)] +#[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct SecurityStatus { - /// Whether Secure Validator Mode is enabled. This mode enforces that all required security - /// features are present. All features are enabled on a best-effort basis regardless. - pub secure_validator_mode: bool, /// Whether the landlock features we use are fully available on this system. pub can_enable_landlock: bool, /// Whether the seccomp features we use are fully available on this system. @@ -61,12 +57,6 @@ pub struct SecurityStatus { pub can_unshare_user_namespace_and_change_root: bool, } -/// A handshake with information for the worker. -#[derive(Debug, Encode, Decode)] -pub struct WorkerHandshake { - pub security_status: SecurityStatus, -} - /// Write some data prefixed by its length into `w`. Sync version of `framed_send` to avoid /// dependency on tokio. pub fn framed_send_blocking(w: &mut (impl Write + Unpin), buf: &[u8]) -> io::Result<()> { diff --git a/polkadot/node/core/pvf/common/src/worker/mod.rs b/polkadot/node/core/pvf/common/src/worker/mod.rs index 5e7deb5ca78..d4f9bbc27ea 100644 --- a/polkadot/node/core/pvf/common/src/worker/mod.rs +++ b/polkadot/node/core/pvf/common/src/worker/mod.rs @@ -18,10 +18,9 @@ pub mod security; -use crate::{framed_recv_blocking, WorkerHandshake, LOG_TARGET}; +use crate::{SecurityStatus, LOG_TARGET}; use cpu_time::ProcessTime; use futures::never::Never; -use parity_scale_codec::Decode; use std::{ any::Any, fmt, io, @@ -51,6 +50,8 @@ macro_rules! decl_worker_main { #[cfg(target_os = "linux")] use $crate::worker::security; + // TODO: Remove this dependency, and `pub use sp_tracing` in `lib.rs`. + // See . $crate::sp_tracing::try_init_simple(); let worker_pid = std::process::id(); @@ -78,26 +79,14 @@ macro_rules! decl_worker_main { "--check-can-enable-landlock" => { #[cfg(target_os = "linux")] - let status = if let Err(err) = security::landlock::check_is_fully_enabled() { - // Write the error to stderr, log it on the host-side. - eprintln!("{}", err); - -1 - } else { - 0 - }; + let status = if security::landlock::check_is_fully_enabled() { 0 } else { -1 }; #[cfg(not(target_os = "linux"))] let status = -1; std::process::exit(status) }, "--check-can-enable-seccomp" => { #[cfg(all(target_os = "linux", target_arch = "x86_64"))] - let status = if let Err(err) = security::seccomp::check_is_fully_enabled() { - // Write the error to stderr, log it on the host-side. - eprintln!("{}", err); - -1 - } else { - 0 - }; + let status = if security::seccomp::check_is_fully_enabled() { 0 } else { -1 }; #[cfg(not(all(target_os = "linux", target_arch = "x86_64")))] let status = -1; std::process::exit(status) @@ -106,9 +95,11 @@ macro_rules! decl_worker_main { #[cfg(target_os = "linux")] let cache_path_tempdir = std::path::Path::new(&args[2]); #[cfg(target_os = "linux")] - let status = if let Err(err) = - security::change_root::check_is_fully_enabled(&cache_path_tempdir) - { + let status = if let Err(err) = security::unshare_user_namespace_and_change_root( + $crate::worker::WorkerKind::CheckPivotRoot, + worker_pid, + &cache_path_tempdir, + ) { // Write the error to stderr, log it on the host-side. eprintln!("{}", err); -1 @@ -116,7 +107,11 @@ macro_rules! decl_worker_main { 0 }; #[cfg(not(target_os = "linux"))] - let status = -1; + let status = { + // Write the error to stderr, log it on the host-side. + eprintln!("not available on macos"); + -1 + }; std::process::exit(status) }, @@ -139,6 +134,9 @@ macro_rules! decl_worker_main { let mut socket_path = None; let mut worker_dir_path = None; let mut node_version = None; + let mut can_enable_landlock = false; + let mut can_enable_seccomp = false; + let mut can_unshare_user_namespace_and_change_root = false; let mut i = 2; while i < args.len() { @@ -155,6 +153,10 @@ macro_rules! decl_worker_main { node_version = Some(args[i + 1].as_str()); i += 1 }, + "--can-enable-landlock" => can_enable_landlock = true, + "--can-enable-seccomp" => can_enable_seccomp = true, + "--can-unshare-user-namespace-and-change-root" => + can_unshare_user_namespace_and_change_root = true, arg => panic!("Unexpected argument found: {}", arg), } i += 1; @@ -165,8 +167,19 @@ macro_rules! decl_worker_main { let socket_path = std::path::Path::new(socket_path).to_owned(); let worker_dir_path = std::path::Path::new(worker_dir_path).to_owned(); - - $entrypoint(socket_path, worker_dir_path, node_version, Some($worker_version)); + let security_status = $crate::SecurityStatus { + can_enable_landlock, + can_enable_seccomp, + can_unshare_user_namespace_and_change_root, + }; + + $entrypoint( + socket_path, + worker_dir_path, + node_version, + Some($worker_version), + security_status, + ); } }; } @@ -192,75 +205,73 @@ impl fmt::Display for WorkerKind { } } -// Some fields are only used for logging, and dead-code analysis ignores Debug. -#[allow(dead_code)] -#[derive(Debug)] -pub struct WorkerInfo { - pid: u32, - kind: WorkerKind, - version: Option, - worker_dir_path: PathBuf, -} - // NOTE: The worker version must be passed in so that we accurately get the version of the worker, // and not the version that this crate was compiled with. // // NOTE: This must not spawn any threads due to safety requirements in `event_loop` and to avoid -// errors in [`security::change_root::try_restrict`]. +// errors in [`security::unshare_user_namespace_and_change_root`]. // /// Initializes the worker process, then runs the given event loop, which spawns a new job process /// to securely handle each incoming request. pub fn run_worker( worker_kind: WorkerKind, socket_path: PathBuf, - worker_dir_path: PathBuf, + #[cfg_attr(not(target_os = "linux"), allow(unused_mut))] mut worker_dir_path: PathBuf, node_version: Option<&str>, worker_version: Option<&str>, + security_status: &SecurityStatus, mut event_loop: F, ) where F: FnMut(UnixStream, PathBuf) -> io::Result, { - #[cfg_attr(not(target_os = "linux"), allow(unused_mut))] - let mut worker_info = WorkerInfo { - pid: std::process::id(), - kind: worker_kind, - version: worker_version.map(|v| v.to_string()), - worker_dir_path, - }; + let worker_pid = std::process::id(); gum::debug!( target: LOG_TARGET, - ?worker_info, + %worker_pid, ?socket_path, + ?worker_dir_path, + ?security_status, "starting pvf worker ({})", - worker_info.kind + worker_kind ); // Check for a mismatch between the node and worker versions. - if let (Some(node_version), Some(worker_version)) = (node_version, &worker_info.version) { + if let (Some(node_version), Some(worker_version)) = (node_version, worker_version) { if node_version != worker_version { gum::error!( target: LOG_TARGET, - ?worker_info, + %worker_kind, + %worker_pid, %node_version, + %worker_version, "Node and worker version mismatch, node needs restarting, forcing shutdown", ); kill_parent_node_in_emergency(); - worker_shutdown(worker_info, "Version mismatch"); + worker_shutdown_message(worker_kind, worker_pid, "Version mismatch"); + return } } // Make sure that we can read the worker dir path, and log its contents. let entries = || -> Result, io::Error> { - std::fs::read_dir(&worker_info.worker_dir_path)? + std::fs::read_dir(&worker_dir_path)? .map(|res| res.map(|e| e.file_name())) .collect() }(); match entries { Ok(entries) => - gum::trace!(target: LOG_TARGET, ?worker_info, "content of worker dir: {:?}", entries), + gum::trace!(target: LOG_TARGET, %worker_pid, ?worker_dir_path, "content of worker dir: {:?}", entries), Err(err) => { - let err = format!("Could not read worker dir: {}", err.to_string()); - worker_shutdown_error(worker_info, &err); + gum::error!( + target: LOG_TARGET, + %worker_kind, + %worker_pid, + ?worker_dir_path, + "Could not read worker dir: {}", + err.to_string() + ); + worker_shutdown_message(worker_kind, worker_pid, &err.to_string()); + return }, } @@ -270,20 +281,23 @@ pub fn run_worker( let _ = std::fs::remove_file(&socket_path); Ok(stream) }(); - let mut stream = match stream { - Ok(ok) => ok, - Err(err) => worker_shutdown_error(worker_info, &err.to_string()), - }; - - let WorkerHandshake { security_status } = match recv_worker_handshake(&mut stream) { - Ok(ok) => ok, - Err(err) => worker_shutdown_error(worker_info, &err.to_string()), + let stream = match stream { + Ok(s) => s, + Err(err) => { + gum::error!( + target: LOG_TARGET, + %worker_kind, + %worker_pid, + "{}", + err + ); + worker_shutdown_message(worker_kind, worker_pid, &err.to_string()); + return + }, }; // Enable some security features. { - gum::trace!(target: LOG_TARGET, ?security_status, "Enabling security features"); - // Call based on whether we can change root. Error out if it should work but fails. // // NOTE: This should not be called in a multi-threaded context (i.e. inside the tokio @@ -292,29 +306,39 @@ pub fn run_worker( // > CLONE_NEWUSER requires that the calling process is not threaded. #[cfg(target_os = "linux")] if security_status.can_unshare_user_namespace_and_change_root { - if let Err(err) = security::change_root::enable_for_worker(&worker_info) { - // The filesystem may be in an inconsistent state, always bail out. - let err = format!("Could not change root to be the worker cache path: {}", err); - worker_shutdown_error(worker_info, &err); + if let Err(err) = security::unshare_user_namespace_and_change_root( + worker_kind, + worker_pid, + &worker_dir_path, + ) { + // The filesystem may be in an inconsistent state, bail out. + gum::error!( + target: LOG_TARGET, + %worker_kind, + %worker_pid, + ?worker_dir_path, + "Could not change root to be the worker cache path: {}", + err + ); + worker_shutdown_message(worker_kind, worker_pid, &err); + return } - worker_info.worker_dir_path = std::path::Path::new("/").to_owned(); + worker_dir_path = std::path::Path::new("/").to_owned(); } #[cfg(target_os = "linux")] if security_status.can_enable_landlock { - if let Err(err) = security::landlock::enable_for_worker(&worker_info) { - // We previously were able to enable, so this should never happen. Shutdown if - // running in secure mode. - let err = format!("could not fully enable landlock: {:?}", err); + let landlock_status = + security::landlock::enable_for_worker(worker_kind, worker_pid, &worker_dir_path); + if !matches!(landlock_status, Ok(landlock::RulesetStatus::FullyEnforced)) { + // We previously were able to enable, so this should never happen. gum::error!( target: LOG_TARGET, - ?worker_info, - "{}. This should not happen, please report an issue", - err + %worker_kind, + %worker_pid, + "could not fully enable landlock: {:?}. This should not happen, please report an issue", + landlock_status ); - if security_status.secure_validator_mode { - worker_shutdown(worker_info, &err); - } } } @@ -322,54 +346,48 @@ pub fn run_worker( // job to catch regressions. See . #[cfg(all(target_os = "linux", target_arch = "x86_64"))] if security_status.can_enable_seccomp { - if let Err(err) = security::seccomp::enable_for_worker(&worker_info) { - // We previously were able to enable, so this should never happen. Shutdown if - // running in secure mode. - let err = format!("could not fully enable seccomp: {:?}", err); + let seccomp_status = + security::seccomp::enable_for_worker(worker_kind, worker_pid, &worker_dir_path); + if !matches!(seccomp_status, Ok(())) { + // We previously were able to enable, so this should never happen. + // + // TODO: Make this a real error in secure-mode. See: + // gum::error!( target: LOG_TARGET, - ?worker_info, - "{}. This should not happen, please report an issue", - err + %worker_kind, + %worker_pid, + "could not fully enable seccomp: {:?}. This should not happen, please report an issue", + seccomp_status ); - if security_status.secure_validator_mode { - worker_shutdown(worker_info, &err); - } } } - if !security::check_env_vars_were_cleared(&worker_info) { + if !security::check_env_vars_were_cleared(worker_kind, worker_pid) { let err = "not all env vars were cleared when spawning the process"; gum::error!( target: LOG_TARGET, - ?worker_info, + %worker_kind, + %worker_pid, "{}", err ); - if security_status.secure_validator_mode { - worker_shutdown(worker_info, err); - } + worker_shutdown_message(worker_kind, worker_pid, err); + return } } // Run the main worker loop. - let err = event_loop(stream, worker_info.worker_dir_path.clone()) + let err = event_loop(stream, worker_dir_path) // It's never `Ok` because it's `Ok(Never)`. .unwrap_err(); - worker_shutdown(worker_info, &err.to_string()); -} - -/// Provide a consistent message on unexpected worker shutdown. -fn worker_shutdown(worker_info: WorkerInfo, err: &str) -> ! { - gum::warn!(target: LOG_TARGET, ?worker_info, "quitting pvf worker ({}): {}", worker_info.kind, err); - std::process::exit(1); + worker_shutdown_message(worker_kind, worker_pid, &err.to_string()); } -/// Provide a consistent error on unexpected worker shutdown. -fn worker_shutdown_error(worker_info: WorkerInfo, err: &str) -> ! { - gum::error!(target: LOG_TARGET, ?worker_info, "quitting pvf worker ({}): {}", worker_info.kind, err); - std::process::exit(1); +/// Provide a consistent message on worker shutdown. +fn worker_shutdown_message(worker_kind: WorkerKind, worker_pid: u32, err: &str) { + gum::debug!(target: LOG_TARGET, %worker_pid, "quitting pvf worker ({}): {}", worker_kind, err); } /// Loop that runs in the CPU time monitor thread on prepare and execute jobs. Continuously wakes up @@ -440,18 +458,6 @@ fn kill_parent_node_in_emergency() { } } -/// Receives a handshake with information for the worker. -fn recv_worker_handshake(stream: &mut UnixStream) -> io::Result { - let worker_handshake = framed_recv_blocking(stream)?; - let worker_handshake = WorkerHandshake::decode(&mut &worker_handshake[..]).map_err(|e| { - io::Error::new( - io::ErrorKind::Other, - format!("recv_worker_handshake: failed to decode WorkerHandshake: {}", e), - ) - })?; - Ok(worker_handshake) -} - /// Functionality related to threads spawned by the workers. /// /// The motivation for this module is to coordinate worker threads without using async Rust. diff --git a/polkadot/node/core/pvf/common/src/worker/security/change_root.rs b/polkadot/node/core/pvf/common/src/worker/security/change_root.rs deleted file mode 100644 index 375cc8ff6f2..00000000000 --- a/polkadot/node/core/pvf/common/src/worker/security/change_root.rs +++ /dev/null @@ -1,173 +0,0 @@ -// 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 . - -//! Functionality for securing workers by unsharing some namespaces from other processes and -//! changing the root. - -use crate::{ - worker::{WorkerInfo, WorkerKind}, - LOG_TARGET, -}; -use std::{env, ffi::CString, io, os::unix::ffi::OsStrExt, path::Path, ptr}; - -#[derive(thiserror::Error, Debug)] -pub enum Error { - #[error("{0}")] - OsErrWithContext(String), - #[error(transparent)] - Io(#[from] io::Error), - #[error("assertion failed: {0}")] - AssertionFailed(String), -} - -pub type Result = std::result::Result; - -/// Try to enable for the given kind of worker. -/// -/// NOTE: This should not be called in a multi-threaded context. `unshare(2)`: -/// "CLONE_NEWUSER requires that the calling process is not threaded." -pub fn enable_for_worker(worker_info: &WorkerInfo) -> Result<()> { - gum::trace!( - target: LOG_TARGET, - ?worker_info, - "enabling change-root", - ); - - try_restrict(worker_info) -} - -/// Runs a check for unshare-and-change-root and returns an error indicating whether it can be fully -/// enabled on the current Linux environment. -/// -/// NOTE: This should not be called in a multi-threaded context. `unshare(2)`: -/// "CLONE_NEWUSER requires that the calling process is not threaded." -#[cfg(target_os = "linux")] -pub fn check_is_fully_enabled(tempdir: &Path) -> Result<()> { - let worker_dir_path = tempdir.to_owned(); - try_restrict(&WorkerInfo { - pid: std::process::id(), - kind: WorkerKind::CheckPivotRoot, - version: None, - worker_dir_path, - }) -} - -/// Unshare the user namespace and change root to be the worker directory. -/// -/// NOTE: This should not be called in a multi-threaded context. `unshare(2)`: -/// "CLONE_NEWUSER requires that the calling process is not threaded." -#[cfg(target_os = "linux")] -fn try_restrict(worker_info: &WorkerInfo) -> Result<()> { - // TODO: Remove this once this is stable: https://github.com/rust-lang/rust/issues/105723 - macro_rules! cstr_ptr { - ($e:expr) => { - concat!($e, "\0").as_ptr().cast::() - }; - } - - gum::trace!( - target: LOG_TARGET, - ?worker_info, - "unsharing the user namespace and calling pivot_root", - ); - - let worker_dir_path_c = CString::new(worker_info.worker_dir_path.as_os_str().as_bytes()) - .expect("on unix; the path will never contain 0 bytes; qed"); - - // Wrapper around all the work to prevent repetitive error handling. - // - // # Errors - // - // It's the caller's responsibility to call `Error::last_os_error`. Note that that alone does - // not give the context of which call failed, so we return a &str error. - || -> std::result::Result<(), &'static str> { - // SAFETY: We pass null-terminated C strings and use the APIs as documented. In fact, steps - // (2) and (3) are adapted from the example in pivot_root(2), with the additional - // change described in the `pivot_root(".", ".")` section. - unsafe { - // 1. `unshare` the user and the mount namespaces. - if libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNS) < 0 { - return Err("unshare user and mount namespaces") - } - - // 2. Setup mounts. - // - // Ensure that new root and its parent mount don't have shared propagation (which would - // cause pivot_root() to return an error), and prevent propagation of mount events to - // the initial mount namespace. - if libc::mount( - ptr::null(), - cstr_ptr!("/"), - ptr::null(), - libc::MS_REC | libc::MS_PRIVATE, - ptr::null(), - ) < 0 - { - return Err("mount MS_PRIVATE") - } - // Ensure that the new root is a mount point. - let additional_flags = - if let WorkerKind::Execute | WorkerKind::CheckPivotRoot = worker_info.kind { - libc::MS_RDONLY - } else { - 0 - }; - if libc::mount( - worker_dir_path_c.as_ptr(), - worker_dir_path_c.as_ptr(), - ptr::null(), // ignored when MS_BIND is used - libc::MS_BIND | - libc::MS_REC | libc::MS_NOEXEC | - libc::MS_NODEV | libc::MS_NOSUID | - libc::MS_NOATIME | additional_flags, - ptr::null(), // ignored when MS_BIND is used - ) < 0 - { - return Err("mount MS_BIND") - } - - // 3. `pivot_root` to the artifact directory. - if libc::chdir(worker_dir_path_c.as_ptr()) < 0 { - return Err("chdir to worker dir path") - } - if libc::syscall(libc::SYS_pivot_root, cstr_ptr!("."), cstr_ptr!(".")) < 0 { - return Err("pivot_root") - } - if libc::umount2(cstr_ptr!("."), libc::MNT_DETACH) < 0 { - return Err("umount the old root mount point") - } - } - - Ok(()) - }() - .map_err(|err_ctx| { - let err = io::Error::last_os_error(); - Error::OsErrWithContext(format!("{}: {}", err_ctx, err)) - })?; - - // Do some assertions. - if env::current_dir()? != Path::new("/") { - return Err(Error::AssertionFailed("expected current dir after pivot_root to be `/`".into())) - } - env::set_current_dir("..")?; - if env::current_dir()? != Path::new("/") { - return Err(Error::AssertionFailed( - "expected not to be able to break out of new root by doing `..`".into(), - )) - } - - Ok(()) -} diff --git a/polkadot/node/core/pvf/common/src/worker/security/landlock.rs b/polkadot/node/core/pvf/common/src/worker/security/landlock.rs index 211d12c2e44..51500c733b8 100644 --- a/polkadot/node/core/pvf/common/src/worker/security/landlock.rs +++ b/polkadot/node/core/pvf/common/src/worker/security/landlock.rs @@ -28,7 +28,7 @@ pub use landlock::RulesetStatus; use crate::{ - worker::{stringify_panic_payload, WorkerInfo, WorkerKind}, + worker::{stringify_panic_payload, WorkerKind}, LOG_TARGET, }; use landlock::*; @@ -74,8 +74,6 @@ pub const LANDLOCK_ABI: ABI = ABI::V1; #[derive(thiserror::Error, Debug)] pub enum Error { - #[error("Could not fully enable: {0:?}")] - NotFullyEnabled(RulesetStatus), #[error("Invalid exception path: {0:?}")] InvalidExceptionPath(PathBuf), #[error(transparent)] @@ -87,13 +85,17 @@ pub enum Error { pub type Result = std::result::Result; /// Try to enable landlock for the given kind of worker. -pub fn enable_for_worker(worker_info: &WorkerInfo) -> Result<()> { - let exceptions: Vec<(PathBuf, BitFlags)> = match worker_info.kind { +pub fn enable_for_worker( + worker_kind: WorkerKind, + worker_pid: u32, + worker_dir_path: &Path, +) -> Result { + let exceptions: Vec<(PathBuf, BitFlags)> = match worker_kind { WorkerKind::Prepare => { - vec![(worker_info.worker_dir_path.to_owned(), AccessFs::WriteFile.into())] + vec![(worker_dir_path.to_owned(), AccessFs::WriteFile.into())] }, WorkerKind::Execute => { - vec![(worker_info.worker_dir_path.to_owned(), AccessFs::ReadFile.into())] + vec![(worker_dir_path.to_owned(), AccessFs::ReadFile.into())] }, WorkerKind::CheckPivotRoot => panic!("this should only be passed for checking pivot_root; qed"), @@ -101,7 +103,9 @@ pub fn enable_for_worker(worker_info: &WorkerInfo) -> Result<()> { gum::trace!( target: LOG_TARGET, - ?worker_info, + %worker_kind, + %worker_pid, + ?worker_dir_path, "enabling landlock with exceptions: {:?}", exceptions, ); @@ -110,14 +114,18 @@ pub fn enable_for_worker(worker_info: &WorkerInfo) -> Result<()> { } // TODO: -/// Runs a check for landlock in its own thread, and returns an error indicating whether the given -/// landlock ABI is fully enabled on the current Linux environment. -pub fn check_is_fully_enabled() -> Result<()> { - match std::thread::spawn(|| try_restrict(std::iter::empty::<(PathBuf, AccessFs)>())).join() { - Ok(Ok(())) => Ok(()), - Ok(Err(err)) => Err(err), - Err(err) => Err(Error::Panic(stringify_panic_payload(err))), - } +/// Runs a check for landlock and returns a single bool indicating whether the given landlock +/// ABI is fully enabled on the current Linux environment. +pub fn check_is_fully_enabled() -> bool { + let status_from_thread: Result = + match std::thread::spawn(|| try_restrict(std::iter::empty::<(PathBuf, AccessFs)>())).join() + { + Ok(Ok(status)) => Ok(status), + Ok(Err(ruleset_err)) => Err(ruleset_err.into()), + Err(err) => Err(Error::Panic(stringify_panic_payload(err))), + }; + + matches!(status_from_thread, Ok(RulesetStatus::FullyEnforced)) } /// Tries to restrict the current thread (should only be called in a process' main thread) with @@ -131,7 +139,7 @@ pub fn check_is_fully_enabled() -> Result<()> { /// # Returns /// /// The status of the restriction (whether it was fully, partially, or not-at-all enforced). -fn try_restrict(fs_exceptions: I) -> Result<()> +fn try_restrict(fs_exceptions: I) -> Result where I: IntoIterator, P: AsRef, @@ -148,13 +156,8 @@ where } ruleset = ruleset.add_rules(rules)?; } - let status = ruleset.restrict_self()?; - if !matches!(status.ruleset, RulesetStatus::FullyEnforced) { - return Err(Error::NotFullyEnabled(status.ruleset)) - } - - Ok(()) + Ok(status.ruleset) } #[cfg(test)] @@ -165,7 +168,7 @@ mod tests { #[test] fn restricted_thread_cannot_read_file() { // TODO: This would be nice: . - if check_is_fully_enabled().is_err() { + if !check_is_fully_enabled() { return } @@ -188,7 +191,7 @@ mod tests { // Apply Landlock with a read exception for only one of the files. let status = try_restrict(vec![(path1, AccessFs::ReadFile)]); - if !matches!(status, Ok(())) { + if !matches!(status, Ok(RulesetStatus::FullyEnforced)) { panic!( "Ruleset should be enforced since we checked if landlock is enabled: {:?}", status @@ -209,7 +212,7 @@ mod tests { // Apply Landlock for all files. let status = try_restrict(std::iter::empty::<(PathBuf, AccessFs)>()); - if !matches!(status, Ok(())) { + if !matches!(status, Ok(RulesetStatus::FullyEnforced)) { panic!( "Ruleset should be enforced since we checked if landlock is enabled: {:?}", status @@ -230,7 +233,7 @@ mod tests { #[test] fn restricted_thread_cannot_write_file() { // TODO: This would be nice: . - if check_is_fully_enabled().is_err() { + if !check_is_fully_enabled() { return } @@ -249,7 +252,7 @@ mod tests { // Apply Landlock with a write exception for only one of the files. let status = try_restrict(vec![(path1, AccessFs::WriteFile)]); - if !matches!(status, Ok(())) { + if !matches!(status, Ok(RulesetStatus::FullyEnforced)) { panic!( "Ruleset should be enforced since we checked if landlock is enabled: {:?}", status @@ -267,7 +270,7 @@ mod tests { // Apply Landlock for all files. let status = try_restrict(std::iter::empty::<(PathBuf, AccessFs)>()); - if !matches!(status, Ok(())) { + if !matches!(status, Ok(RulesetStatus::FullyEnforced)) { panic!( "Ruleset should be enforced since we checked if landlock is enabled: {:?}", status @@ -289,7 +292,7 @@ mod tests { #[test] fn restricted_thread_can_truncate_file() { // TODO: This would be nice: . - if check_is_fully_enabled().is_err() { + if !check_is_fully_enabled() { return } @@ -305,7 +308,7 @@ mod tests { // Apply Landlock with all exceptions under the current ABI. let status = try_restrict(vec![(path, AccessFs::from_all(LANDLOCK_ABI))]); - if !matches!(status, Ok(())) { + if !matches!(status, Ok(RulesetStatus::FullyEnforced)) { panic!( "Ruleset should be enforced since we checked if landlock is enabled: {:?}", status diff --git a/polkadot/node/core/pvf/common/src/worker/security/mod.rs b/polkadot/node/core/pvf/common/src/worker/security/mod.rs index ff4c712f6bd..9a38ed17277 100644 --- a/polkadot/node/core/pvf/common/src/worker/security/mod.rs +++ b/polkadot/node/core/pvf/common/src/worker/security/mod.rs @@ -27,21 +27,134 @@ //! - Restrict networking by blocking socket creation and io_uring. //! - Remove env vars -use crate::{worker::WorkerInfo, LOG_TARGET}; +use crate::{worker::WorkerKind, LOG_TARGET}; -#[cfg(target_os = "linux")] -pub mod change_root; #[cfg(target_os = "linux")] pub mod landlock; + #[cfg(all(target_os = "linux", target_arch = "x86_64"))] pub mod seccomp; +/// Unshare the user namespace and change root to be the artifact directory. +/// +/// NOTE: This should not be called in a multi-threaded context. `unshare(2)`: +/// "CLONE_NEWUSER requires that the calling process is not threaded." +#[cfg(target_os = "linux")] +pub fn unshare_user_namespace_and_change_root( + worker_kind: WorkerKind, + worker_pid: u32, + worker_dir_path: &std::path::Path, +) -> Result<(), String> { + use std::{env, ffi::CString, os::unix::ffi::OsStrExt, path::Path, ptr}; + + // TODO: Remove this once this is stable: https://github.com/rust-lang/rust/issues/105723 + macro_rules! cstr_ptr { + ($e:expr) => { + concat!($e, "\0").as_ptr().cast::() + }; + } + + gum::trace!( + target: LOG_TARGET, + %worker_kind, + %worker_pid, + ?worker_dir_path, + "unsharing the user namespace and calling pivot_root", + ); + + let worker_dir_path_c = CString::new(worker_dir_path.as_os_str().as_bytes()) + .expect("on unix; the path will never contain 0 bytes; qed"); + + // Wrapper around all the work to prevent repetitive error handling. + // + // # Errors + // + // It's the caller's responsibility to call `Error::last_os_error`. Note that that alone does + // not give the context of which call failed, so we return a &str error. + || -> Result<(), &'static str> { + // SAFETY: We pass null-terminated C strings and use the APIs as documented. In fact, steps + // (2) and (3) are adapted from the example in pivot_root(2), with the additional + // change described in the `pivot_root(".", ".")` section. + unsafe { + // 1. `unshare` the user and the mount namespaces. + if libc::unshare(libc::CLONE_NEWUSER | libc::CLONE_NEWNS) < 0 { + return Err("unshare user and mount namespaces") + } + + // 2. Setup mounts. + // + // Ensure that new root and its parent mount don't have shared propagation (which would + // cause pivot_root() to return an error), and prevent propagation of mount events to + // the initial mount namespace. + if libc::mount( + ptr::null(), + cstr_ptr!("/"), + ptr::null(), + libc::MS_REC | libc::MS_PRIVATE, + ptr::null(), + ) < 0 + { + return Err("mount MS_PRIVATE") + } + // Ensure that the new root is a mount point. + let additional_flags = + if let WorkerKind::Execute | WorkerKind::CheckPivotRoot = worker_kind { + libc::MS_RDONLY + } else { + 0 + }; + if libc::mount( + worker_dir_path_c.as_ptr(), + worker_dir_path_c.as_ptr(), + ptr::null(), // ignored when MS_BIND is used + libc::MS_BIND | + libc::MS_REC | libc::MS_NOEXEC | + libc::MS_NODEV | libc::MS_NOSUID | + libc::MS_NOATIME | additional_flags, + ptr::null(), // ignored when MS_BIND is used + ) < 0 + { + return Err("mount MS_BIND") + } + + // 3. `pivot_root` to the artifact directory. + if libc::chdir(worker_dir_path_c.as_ptr()) < 0 { + return Err("chdir to worker dir path") + } + if libc::syscall(libc::SYS_pivot_root, cstr_ptr!("."), cstr_ptr!(".")) < 0 { + return Err("pivot_root") + } + if libc::umount2(cstr_ptr!("."), libc::MNT_DETACH) < 0 { + return Err("umount the old root mount point") + } + } + + Ok(()) + }() + .map_err(|err_ctx| { + let err = std::io::Error::last_os_error(); + format!("{}: {}", err_ctx, err) + })?; + + // Do some assertions. + if env::current_dir().map_err(|err| err.to_string())? != Path::new("/") { + return Err("expected current dir after pivot_root to be `/`".into()) + } + env::set_current_dir("..").map_err(|err| err.to_string())?; + if env::current_dir().map_err(|err| err.to_string())? != Path::new("/") { + return Err("expected not to be able to break out of new root by doing `..`".into()) + } + + Ok(()) +} + /// Require env vars to have been removed when spawning the process, to prevent malicious code from /// accessing them. -pub fn check_env_vars_were_cleared(worker_info: &WorkerInfo) -> bool { +pub fn check_env_vars_were_cleared(worker_kind: WorkerKind, worker_pid: u32) -> bool { gum::trace!( target: LOG_TARGET, - ?worker_info, + %worker_kind, + %worker_pid, "clearing env vars in worker", ); @@ -49,8 +162,8 @@ pub fn check_env_vars_were_cleared(worker_info: &WorkerInfo) -> bool { for (key, value) in std::env::vars_os() { // TODO: *theoretically* the value (or mere presence) of `RUST_LOG` can be a source of - // randomness for malicious code. It should be removed in the job process, which does no - // logging. + // randomness for malicious code. In the future we can remove it also and log in the host; + // see . if key == "RUST_LOG" { continue } @@ -62,7 +175,8 @@ pub fn check_env_vars_were_cleared(worker_info: &WorkerInfo) -> bool { gum::error!( target: LOG_TARGET, - ?worker_info, + %worker_kind, + %worker_pid, ?key, ?value, "env var was present that should have been removed", diff --git a/polkadot/node/core/pvf/common/src/worker/security/seccomp.rs b/polkadot/node/core/pvf/common/src/worker/security/seccomp.rs index 4f270f75b34..c3822d3c4c6 100644 --- a/polkadot/node/core/pvf/common/src/worker/security/seccomp.rs +++ b/polkadot/node/core/pvf/common/src/worker/security/seccomp.rs @@ -72,11 +72,11 @@ //! candidate. use crate::{ - worker::{stringify_panic_payload, WorkerInfo}, + worker::{stringify_panic_payload, WorkerKind}, LOG_TARGET, }; use seccompiler::*; -use std::collections::BTreeMap; +use std::{collections::BTreeMap, path::Path}; /// The action to take on caught syscalls. #[cfg(not(test))] @@ -98,28 +98,36 @@ pub enum Error { pub type Result = std::result::Result; /// Try to enable seccomp for the given kind of worker. -pub fn enable_for_worker(worker_info: &WorkerInfo) -> Result<()> { +pub fn enable_for_worker( + worker_kind: WorkerKind, + worker_pid: u32, + worker_dir_path: &Path, +) -> Result<()> { gum::trace!( target: LOG_TARGET, - ?worker_info, + %worker_kind, + %worker_pid, + ?worker_dir_path, "enabling seccomp", ); try_restrict() } -/// Runs a check for seccomp in its own thread, and returns an error indicating whether seccomp with -/// our rules is fully enabled on the current Linux environment. -pub fn check_is_fully_enabled() -> Result<()> { - match std::thread::spawn(|| try_restrict()).join() { +/// Runs a check for seccomp and returns a single bool indicating whether seccomp with our rules is +/// fully enabled on the current Linux environment. +pub fn check_is_fully_enabled() -> bool { + let status_from_thread: Result<()> = match std::thread::spawn(|| try_restrict()).join() { Ok(Ok(())) => Ok(()), - Ok(Err(err)) => Err(err), + Ok(Err(err)) => Err(err.into()), Err(err) => Err(Error::Panic(stringify_panic_payload(err))), - } + }; + + matches!(status_from_thread, Ok(())) } /// Applies a `seccomp` filter to disable networking for the PVF threads. -fn try_restrict() -> Result<()> { +pub fn try_restrict() -> Result<()> { // Build a `seccomp` filter which by default allows all syscalls except those blocked in the // blacklist. let mut blacklisted_rules = BTreeMap::default(); @@ -161,7 +169,7 @@ mod tests { #[test] fn sandboxed_thread_cannot_use_sockets() { // TODO: This would be nice: . - if check_is_fully_enabled().is_err() { + if !check_is_fully_enabled() { return } diff --git a/polkadot/node/core/pvf/execute-worker/Cargo.toml b/polkadot/node/core/pvf/execute-worker/Cargo.toml index 97dde59ebc2..40e0ff4f0a1 100644 --- a/polkadot/node/core/pvf/execute-worker/Cargo.toml +++ b/polkadot/node/core/pvf/execute-worker/Cargo.toml @@ -6,14 +6,11 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] cpu-time = "1.0.0" gum = { package = "tracing-gum", path = "../../../gum" } os_pipe = "1.1.4" -nix = { version = "0.27.1", features = ["process", "resource"] } +nix = { version = "0.27.1", features = ["resource", "process"]} libc = "0.2.139" parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive"] } diff --git a/polkadot/node/core/pvf/execute-worker/src/lib.rs b/polkadot/node/core/pvf/execute-worker/src/lib.rs index b33a9d5069d..d82a8fca65d 100644 --- a/polkadot/node/core/pvf/execute-worker/src/lib.rs +++ b/polkadot/node/core/pvf/execute-worker/src/lib.rs @@ -16,7 +16,9 @@ //! Contains the logic for executing PVFs. Used by the polkadot-execute-worker binary. -pub use polkadot_node_core_pvf_common::{executor_interface::execute_artifact, worker_dir}; +pub use polkadot_node_core_pvf_common::{ + executor_intf::execute_artifact, worker_dir, SecurityStatus, +}; // NOTE: Initializing logging in e.g. tests will not have an effect in the workers, as they are // separate spawned processes. Run with e.g. `RUST_LOG=parachain::pvf-execute-worker=trace`. @@ -90,13 +92,12 @@ use std::{ /// The stack size for the execute thread. pub const EXECUTE_THREAD_STACK_SIZE: usize = 2 * 1024 * 1024 + DEFAULT_NATIVE_STACK_MAX as usize; -/// Receives a handshake with information specific to the execute worker. -fn recv_execute_handshake(stream: &mut UnixStream) -> io::Result { +fn recv_handshake(stream: &mut UnixStream) -> io::Result { let handshake_enc = framed_recv_blocking(stream)?; let handshake = Handshake::decode(&mut &handshake_enc[..]).map_err(|_| { io::Error::new( io::ErrorKind::Other, - "execute pvf recv_execute_handshake: failed to decode Handshake".to_owned(), + "execute pvf recv_handshake: failed to decode Handshake".to_owned(), ) })?; Ok(handshake) @@ -138,6 +139,7 @@ pub fn worker_entrypoint( worker_dir_path: PathBuf, node_version: Option<&str>, worker_version: Option<&str>, + security_status: SecurityStatus, ) { run_worker( WorkerKind::Execute, @@ -145,11 +147,12 @@ pub fn worker_entrypoint( worker_dir_path, node_version, worker_version, + &security_status, |mut stream, worker_dir_path| { let worker_pid = process::id(); let artifact_path = worker_dir::execute_artifact(&worker_dir_path); - let Handshake { executor_params } = recv_execute_handshake(&mut stream)?; + let Handshake { executor_params } = recv_handshake(&mut stream)?; loop { let (params, execution_timeout) = recv_request(&mut stream)?; @@ -233,7 +236,7 @@ fn validate_using_artifact( let descriptor_bytes = match unsafe { // SAFETY: this should be safe since the compiled artifact passed here comes from the // file created by the prepare workers. These files are obtained by calling - // [`executor_interface::prepare`]. + // [`executor_intf::prepare`]. execute_artifact(compiled_artifact_blob, executor_params, params) } { Err(err) => return JobResponse::format_invalid("execute", &err), diff --git a/polkadot/node/core/pvf/prepare-worker/Cargo.toml b/polkadot/node/core/pvf/prepare-worker/Cargo.toml index 81e887afe4d..005f2e93511 100644 --- a/polkadot/node/core/pvf/prepare-worker/Cargo.toml +++ b/polkadot/node/core/pvf/prepare-worker/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] blake3 = "1.5" cfg-if = "1.0" @@ -19,7 +16,7 @@ tracking-allocator = { package = "staging-tracking-allocator", path = "../../../ tikv-jemalloc-ctl = { version = "0.5.0", optional = true } tikv-jemallocator = { version = "0.5.0", optional = true } os_pipe = "1.1.4" -nix = { version = "0.27.1", features = ["process", "resource"] } +nix = { version = "0.27.1", features = ["resource", "process"]} parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive"] } diff --git a/polkadot/node/core/pvf/prepare-worker/benches/prepare_rococo_runtime.rs b/polkadot/node/core/pvf/prepare-worker/benches/prepare_rococo_runtime.rs index d531c90b64b..ba2568cd80c 100644 --- a/polkadot/node/core/pvf/prepare-worker/benches/prepare_rococo_runtime.rs +++ b/polkadot/node/core/pvf/prepare-worker/benches/prepare_rococo_runtime.rs @@ -16,7 +16,7 @@ use criterion::{criterion_group, criterion_main, Criterion, SamplingMode}; use polkadot_node_core_pvf_common::{ - executor_interface::{prepare, prevalidate}, + executor_intf::{prepare, prevalidate}, prepare::PrepareJobKind, pvf::PvfPrepData, }; diff --git a/polkadot/node/core/pvf/prepare-worker/src/lib.rs b/polkadot/node/core/pvf/prepare-worker/src/lib.rs index af5ac8c5974..499e87c6e20 100644 --- a/polkadot/node/core/pvf/prepare-worker/src/lib.rs +++ b/polkadot/node/core/pvf/prepare-worker/src/lib.rs @@ -18,7 +18,7 @@ mod memory_stats; -use polkadot_node_core_pvf_common::executor_interface::{prepare, prevalidate}; +use polkadot_node_core_pvf_common::executor_intf::{prepare, prevalidate}; // NOTE: Initializing logging in e.g. tests will not have an effect in the workers, as they are // separate spawned processes. Run with e.g. `RUST_LOG=parachain::pvf-prepare-worker=trace`. @@ -41,7 +41,7 @@ use os_pipe::{self, PipeReader, PipeWriter}; use parity_scale_codec::{Decode, Encode}; use polkadot_node_core_pvf_common::{ error::{PrepareError, PrepareWorkerResult}, - executor_interface::create_runtime_from_artifact_bytes, + executor_intf::create_runtime_from_artifact_bytes, framed_recv_blocking, framed_send_blocking, prepare::{MemoryStats, PrepareJobKind, PrepareStats, PrepareWorkerSuccess}, pvf::PvfPrepData, @@ -50,7 +50,7 @@ use polkadot_node_core_pvf_common::{ thread::{self, spawn_worker_thread, WaitOutcome}, WorkerKind, }, - worker_dir, ProcessTime, + worker_dir, ProcessTime, SecurityStatus, }; use polkadot_primitives::ExecutorParams; use std::{ @@ -193,6 +193,7 @@ pub fn worker_entrypoint( worker_dir_path: PathBuf, node_version: Option<&str>, worker_version: Option<&str>, + security_status: SecurityStatus, ) { run_worker( WorkerKind::Prepare, @@ -200,6 +201,7 @@ pub fn worker_entrypoint( worker_dir_path, node_version, worker_version, + &security_status, |mut stream, worker_dir_path| { let worker_pid = process::id(); let temp_artifact_dest = worker_dir::prepare_tmp_artifact(&worker_dir_path); diff --git a/polkadot/node/core/pvf/src/artifacts.rs b/polkadot/node/core/pvf/src/artifacts.rs index 17ce5b443e3..79b53467b4e 100644 --- a/polkadot/node/core/pvf/src/artifacts.rs +++ b/polkadot/node/core/pvf/src/artifacts.rs @@ -66,7 +66,6 @@ use polkadot_parachain_primitives::primitives::ValidationCodeHash; use polkadot_primitives::ExecutorParamsHash; use std::{ collections::HashMap, - io, path::{Path, PathBuf}, str::FromStr as _, time::{Duration, SystemTime}, @@ -201,20 +200,13 @@ impl Artifacts { /// Create an empty table and populate it with valid artifacts as [`ArtifactState::Prepared`], /// if any. The existing caches will be checked by their file name to determine whether they are /// valid, e.g., matching the current node version. The ones deemed invalid will be pruned. - /// - /// Create the cache directory on-disk if it doesn't exist. pub async fn new_and_prune(cache_path: &Path) -> Self { let mut artifacts = Self { inner: HashMap::new() }; - let _ = artifacts.insert_and_prune(cache_path).await.map_err(|err| { - gum::error!( - target: LOG_TARGET, - "could not initialize artifacts cache: {err}", - ) - }); + artifacts.insert_and_prune(cache_path).await; artifacts } - async fn insert_and_prune(&mut self, cache_path: &Path) -> Result<(), String> { + async fn insert_and_prune(&mut self, cache_path: &Path) { async fn is_corrupted(path: &Path) -> bool { let checksum = match tokio::fs::read(path).await { Ok(bytes) => blake3::hash(&bytes), @@ -244,16 +236,24 @@ impl Artifacts { artifacts: &mut Artifacts, entry: &tokio::fs::DirEntry, cache_path: &Path, - ) -> Result<(), String> { + ) { let file_type = entry.file_type().await; let file_name = entry.file_name(); match file_type { Ok(file_type) => if !file_type.is_file() { - return Ok(()) + return }, - Err(err) => return Err(format!("unable to get file type for {file_name:?}: {err}")), + Err(err) => { + gum::warn!( + target: LOG_TARGET, + ?err, + "unable to get file type for {:?}", + file_name, + ); + return + }, } if let Some(file_name) = file_name.to_str() { @@ -261,51 +261,63 @@ impl Artifacts { let path = cache_path.join(file_name); if id.is_none() || is_corrupted(&path).await { + gum::warn!( + target: LOG_TARGET, + "discarding invalid artifact {:?}", + &path, + ); let _ = tokio::fs::remove_file(&path).await; - return Err(format!("invalid artifact {path:?}, file deleted")) + return } - let id = id.expect("checked is_none() above; qed"); - gum::debug!( + if let Some(id) = id { + gum::debug!( + target: LOG_TARGET, + "reusing existing {:?} for node version v{}", + &path, + NODE_VERSION, + ); + artifacts.insert_prepared(id, path, SystemTime::now(), Default::default()); + } + } else { + gum::warn!( target: LOG_TARGET, - "reusing existing {:?} for node version v{}", - &path, - NODE_VERSION, + "non-Unicode file name {:?} found in {:?}", + file_name, + cache_path, ); - artifacts.insert_prepared(id, path, SystemTime::now(), Default::default()); - - Ok(()) - } else { - Err(format!("non-Unicode file name {file_name:?} found in {cache_path:?}")) } } // Make sure that the cache path directory and all its parents are created. - if let Err(err) = tokio::fs::create_dir_all(cache_path).await { - if err.kind() != io::ErrorKind::AlreadyExists { - return Err(format!("failed to create dir {cache_path:?}: {err}")) - } - } + let _ = tokio::fs::create_dir_all(cache_path).await; - let mut dir = tokio::fs::read_dir(cache_path) - .await - .map_err(|err| format!("failed to read dir {cache_path:?}: {err}"))?; + let mut dir = match tokio::fs::read_dir(cache_path).await { + Ok(dir) => dir, + Err(err) => { + gum::error!( + target: LOG_TARGET, + ?err, + "failed to read dir {:?}", + cache_path, + ); + return + }, + }; loop { match dir.next_entry().await { - Ok(Some(entry)) => - if let Err(err) = insert_or_prune(self, &entry, cache_path).await { - gum::warn!( - target: LOG_TARGET, - ?cache_path, - "could not insert entry {:?} into the artifact cache: {}", - entry, - err, - ) - }, - Ok(None) => return Ok(()), - Err(err) => - return Err(format!("error processing artifacts in {cache_path:?}: {err}")), + Ok(Some(entry)) => insert_or_prune(self, &entry, cache_path).await, + Ok(None) => break, + Err(err) => { + gum::warn!( + target: LOG_TARGET, + ?err, + "error processing artifacts in {:?}", + cache_path, + ); + break + }, } } } diff --git a/polkadot/node/core/pvf/src/execute/mod.rs b/polkadot/node/core/pvf/src/execute/mod.rs index c6d9cf90fa2..669b9dc04d7 100644 --- a/polkadot/node/core/pvf/src/execute/mod.rs +++ b/polkadot/node/core/pvf/src/execute/mod.rs @@ -21,6 +21,6 @@ //! `polkadot_node_core_pvf_worker::execute_worker_entrypoint`. mod queue; -mod worker_interface; +mod worker_intf; pub use queue::{start, PendingExecutionRequest, ToQueue}; diff --git a/polkadot/node/core/pvf/src/execute/queue.rs b/polkadot/node/core/pvf/src/execute/queue.rs index be607fe1c20..a0c24fd4432 100644 --- a/polkadot/node/core/pvf/src/execute/queue.rs +++ b/polkadot/node/core/pvf/src/execute/queue.rs @@ -16,12 +16,12 @@ //! A queue that handles requests for PVF execution. -use super::worker_interface::Outcome; +use super::worker_intf::Outcome; use crate::{ artifacts::{ArtifactId, ArtifactPathId}, host::ResultSender, metrics::Metrics, - worker_interface::{IdleWorker, WorkerHandle}, + worker_intf::{IdleWorker, WorkerHandle}, InvalidCandidate, PossiblyInvalidError, ValidationError, LOG_TARGET, }; use futures::{ @@ -448,7 +448,7 @@ async fn spawn_worker_task( use futures_timer::Delay; loop { - match super::worker_interface::spawn( + match super::worker_intf::spawn( &program_path, &cache_path, job.executor_params.clone(), @@ -500,7 +500,7 @@ fn assign(queue: &mut Queue, worker: Worker, job: ExecuteJob) { queue.mux.push( async move { let _timer = execution_timer; - let outcome = super::worker_interface::start_work( + let outcome = super::worker_intf::start_work( idle, job.artifact.clone(), job.exec_timeout, diff --git a/polkadot/node/core/pvf/src/execute/worker_interface.rs b/polkadot/node/core/pvf/src/execute/worker_intf.rs similarity index 96% rename from polkadot/node/core/pvf/src/execute/worker_interface.rs rename to polkadot/node/core/pvf/src/execute/worker_intf.rs index 9f7738f00e6..16a7c290b52 100644 --- a/polkadot/node/core/pvf/src/execute/worker_interface.rs +++ b/polkadot/node/core/pvf/src/execute/worker_intf.rs @@ -18,7 +18,7 @@ use crate::{ artifacts::ArtifactPathId, - worker_interface::{ + worker_intf::{ clear_worker_dir_path, framed_recv, framed_send, spawn_with_program_path, IdleWorker, SpawnErr, WorkerDir, WorkerHandle, JOB_TIMEOUT_WALL_CLOCK_FACTOR, }, @@ -62,16 +62,16 @@ pub async fn spawn( security_status, ) .await?; - send_execute_handshake(&mut idle_worker.stream, Handshake { executor_params }) + send_handshake(&mut idle_worker.stream, Handshake { executor_params }) .await .map_err(|error| { - let err = SpawnErr::Handshake { err: error.to_string() }; gum::warn!( target: LOG_TARGET, worker_pid = %idle_worker.pid, - %err + ?error, + "failed to send a handshake to the spawned worker", ); - err + SpawnErr::Handshake })?; Ok((idle_worker, worker_handle)) } @@ -286,8 +286,7 @@ where outcome } -/// Sends a handshake with information specific to the execute worker. -async fn send_execute_handshake(stream: &mut UnixStream, handshake: Handshake) -> io::Result<()> { +async fn send_handshake(stream: &mut UnixStream, handshake: Handshake) -> io::Result<()> { framed_send(stream, &handshake.encode()).await } diff --git a/polkadot/node/core/pvf/src/host.rs b/polkadot/node/core/pvf/src/host.rs index d17a4d918e0..be8f7aee778 100644 --- a/polkadot/node/core/pvf/src/host.rs +++ b/polkadot/node/core/pvf/src/host.rs @@ -36,7 +36,7 @@ use polkadot_node_core_pvf_common::{ prepare::PrepareSuccess, pvf::PvfPrepData, }; -use polkadot_node_subsystem::{SubsystemError, SubsystemResult}; +use polkadot_node_subsystem::SubsystemResult; use polkadot_parachain_primitives::primitives::ValidationResult; use std::{ collections::HashMap, @@ -156,8 +156,6 @@ pub struct Config { pub cache_path: PathBuf, /// The version of the node. `None` can be passed to skip the version check (only for tests). pub node_version: Option, - /// Whether the node is attempting to run as a secure validator. - pub secure_validator_mode: bool, /// The path to the program that can be used to spawn the prepare workers. pub prepare_worker_program_path: PathBuf, @@ -182,14 +180,12 @@ impl Config { pub fn new( cache_path: PathBuf, node_version: Option, - secure_validator_mode: bool, prepare_worker_program_path: PathBuf, execute_worker_program_path: PathBuf, ) -> Self { Self { cache_path, node_version, - secure_validator_mode, prepare_worker_program_path, prepare_worker_spawn_timeout: Duration::from_secs(3), @@ -217,15 +213,8 @@ pub async fn start( ) -> SubsystemResult<(ValidationHost, impl Future)> { gum::debug!(target: LOG_TARGET, ?config, "starting PVF validation host"); - // Make sure the cache is initialized before doing anything else. - let artifacts = Artifacts::new_and_prune(&config.cache_path).await; - - // Run checks for supported security features once per host startup. If some checks fail, warn - // if Secure Validator Mode is disabled and return an error otherwise. - let security_status = match security::check_security_status(&config).await { - Ok(ok) => ok, - Err(err) => return Err(SubsystemError::Context(err)), - }; + // Run checks for supported security features once per host startup. Warn here if not enabled. + let security_status = security::check_security_status(&config).await; let (to_host_tx, to_host_rx) = mpsc::channel(10); @@ -263,6 +252,8 @@ pub async fn start( let run_sweeper = sweeper_task(to_sweeper_rx); let run_host = async move { + let artifacts = Artifacts::new_and_prune(&config.cache_path).await; + run(Inner { cleanup_pulse_interval: Duration::from_secs(3600), artifact_ttl: Duration::from_secs(3600 * 24), diff --git a/polkadot/node/core/pvf/src/lib.rs b/polkadot/node/core/pvf/src/lib.rs index 79391630b2d..3306a2461c1 100644 --- a/polkadot/node/core/pvf/src/lib.rs +++ b/polkadot/node/core/pvf/src/lib.rs @@ -98,7 +98,7 @@ mod metrics; mod prepare; mod priority; mod security; -mod worker_interface; +mod worker_intf; #[cfg(feature = "test-utils")] pub mod testing; @@ -107,7 +107,7 @@ pub use error::{InvalidCandidate, PossiblyInvalidError, ValidationError}; pub use host::{start, Config, ValidationHost, EXECUTE_BINARY_NAME, PREPARE_BINARY_NAME}; pub use metrics::Metrics; pub use priority::Priority; -pub use worker_interface::{framed_recv, framed_send, JOB_TIMEOUT_WALL_CLOCK_FACTOR}; +pub use worker_intf::{framed_recv, framed_send, JOB_TIMEOUT_WALL_CLOCK_FACTOR}; // Re-export some common types. pub use polkadot_node_core_pvf_common::{ diff --git a/polkadot/node/core/pvf/src/prepare/mod.rs b/polkadot/node/core/pvf/src/prepare/mod.rs index eb88070c2ba..580f67f73fa 100644 --- a/polkadot/node/core/pvf/src/prepare/mod.rs +++ b/polkadot/node/core/pvf/src/prepare/mod.rs @@ -24,7 +24,7 @@ mod pool; mod queue; -mod worker_interface; +mod worker_intf; pub use pool::start as start_pool; pub use queue::{start as start_queue, FromQueue, ToQueue}; diff --git a/polkadot/node/core/pvf/src/prepare/pool.rs b/polkadot/node/core/pvf/src/prepare/pool.rs index 4e11f977c9e..4901be9fe1b 100644 --- a/polkadot/node/core/pvf/src/prepare/pool.rs +++ b/polkadot/node/core/pvf/src/prepare/pool.rs @@ -14,10 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use super::worker_interface::{self, Outcome}; +use super::worker_intf::{self, Outcome}; use crate::{ metrics::Metrics, - worker_interface::{IdleWorker, WorkerHandle}, + worker_intf::{IdleWorker, WorkerHandle}, LOG_TARGET, }; use always_assert::never; @@ -278,7 +278,7 @@ async fn spawn_worker_task( use futures_timer::Delay; loop { - match worker_interface::spawn( + match worker_intf::spawn( &program_path, &cache_path, spawn_timeout, @@ -306,7 +306,7 @@ async fn start_work_task( cache_path: PathBuf, _preparation_timer: Option, ) -> PoolEvent { - let outcome = worker_interface::start_work(&metrics, idle, pvf, cache_path).await; + let outcome = worker_intf::start_work(&metrics, idle, pvf, cache_path).await; PoolEvent::StartWork(worker, outcome) } diff --git a/polkadot/node/core/pvf/src/prepare/worker_interface.rs b/polkadot/node/core/pvf/src/prepare/worker_intf.rs similarity index 99% rename from polkadot/node/core/pvf/src/prepare/worker_interface.rs rename to polkadot/node/core/pvf/src/prepare/worker_intf.rs index 984a87ce5c9..a393e9baa9e 100644 --- a/polkadot/node/core/pvf/src/prepare/worker_interface.rs +++ b/polkadot/node/core/pvf/src/prepare/worker_intf.rs @@ -19,7 +19,7 @@ use crate::{ artifacts::ArtifactId, metrics::Metrics, - worker_interface::{ + worker_intf::{ clear_worker_dir_path, framed_recv, framed_send, spawn_with_program_path, IdleWorker, SpawnErr, WorkerDir, WorkerHandle, JOB_TIMEOUT_WALL_CLOCK_FACTOR, }, diff --git a/polkadot/node/core/pvf/src/security.rs b/polkadot/node/core/pvf/src/security.rs index 9d0d4cf49af..2fd3b53e96b 100644 --- a/polkadot/node/core/pvf/src/security.rs +++ b/polkadot/node/core/pvf/src/security.rs @@ -18,19 +18,18 @@ use crate::{Config, SecurityStatus, LOG_TARGET}; use futures::join; use std::{fmt, path::Path}; +const SECURE_MODE_ANNOUNCEMENT: &'static str = + "In the next release this will be a hard error by default. + \nMore information: https://wiki.polkadot.network/docs/maintain-guides-secure-validator#secure-validator-mode"; + /// Run checks for supported security features. /// /// # Returns /// /// Returns the set of security features that we were able to enable. If an error occurs while /// enabling a security feature we set the corresponding status to `false`. -/// -/// # Errors -/// -/// Returns an error only if we could not fully enforce the security level required by the current -/// configuration. -pub async fn check_security_status(config: &Config) -> Result { - let Config { prepare_worker_program_path, secure_validator_mode, cache_path, .. } = config; +pub async fn check_security_status(config: &Config) -> SecurityStatus { + let Config { prepare_worker_program_path, cache_path, .. } = config; let (landlock, seccomp, change_root) = join!( check_landlock(prepare_worker_program_path), @@ -38,81 +37,26 @@ pub async fn check_security_status(config: &Config) -> Result = [landlock, seccomp, change_root] + .into_iter() + .filter_map(|result| result.err()) + .collect(); + let err_occurred = print_secure_mode_message(errs); + if err_occurred { + gum::error!( target: LOG_TARGET, - "👮‍♀️ Running in Secure Validator Mode. \ - It is highly recommended that you operate according to our security guidelines. \ - \nMore information: https://wiki.polkadot.network/docs/maintain-guides-secure-validator#secure-validator-mode" + "{}", + SECURE_MODE_ANNOUNCEMENT, ); } - Ok(security_status) -} - -/// Contains the full security status including error states. -struct FullSecurityStatus { - partial: SecurityStatus, - errs: Vec, -} - -impl FullSecurityStatus { - fn new( - secure_validator_mode: bool, - landlock: SecureModeResult, - seccomp: SecureModeResult, - change_root: SecureModeResult, - ) -> Self { - Self { - partial: SecurityStatus { - secure_validator_mode, - can_enable_landlock: landlock.is_ok(), - can_enable_seccomp: seccomp.is_ok(), - can_unshare_user_namespace_and_change_root: change_root.is_ok(), - }, - errs: [landlock, seccomp, change_root] - .into_iter() - .filter_map(|result| result.err()) - .collect(), - } - } - - fn as_partial(&self) -> SecurityStatus { - self.partial.clone() - } - - fn err_occurred(&self) -> bool { - !self.errs.is_empty() - } - - fn all_errs_allowed(&self) -> bool { - !self.partial.secure_validator_mode || - self.errs.iter().all(|err| err.is_allowed_in_secure_mode(&self.partial)) - } - - fn errs_string(&self) -> String { - self.errs - .iter() - .map(|err| { - format!( - "\n - {}{}", - if err.is_allowed_in_secure_mode(&self.partial) { "Optional: " } else { "" }, - err - ) - }) - .collect() - } + security_status } type SecureModeResult = std::result::Result<(), SecureModeError>; @@ -127,17 +71,12 @@ enum SecureModeError { impl SecureModeError { /// Whether this error is allowed with Secure Validator Mode enabled. - fn is_allowed_in_secure_mode(&self, security_status: &SecurityStatus) -> bool { + fn is_allowed_in_secure_mode(&self) -> bool { use SecureModeError::*; match self { - // Landlock is present on relatively recent Linuxes. This is optional if the unshare - // capability is present, providing FS sandboxing a different way. - CannotEnableLandlock(_) => security_status.can_unshare_user_namespace_and_change_root, - // seccomp should be present on all modern Linuxes unless it's been disabled. + CannotEnableLandlock(_) => true, CannotEnableSeccomp(_) => false, - // Should always be present on modern Linuxes. If not, Landlock also provides FS - // sandboxing, so don't enforce this. - CannotUnshareUserNamespaceAndChangeRoot(_) => security_status.can_enable_landlock, + CannotUnshareUserNamespaceAndChangeRoot(_) => false, } } } @@ -153,8 +92,12 @@ impl fmt::Display for SecureModeError { } } -/// Print an error if Secure Validator Mode and some mandatory errors occurred, warn otherwise. -fn print_secure_mode_error_or_warning(security_status: &FullSecurityStatus) { +/// Errors if Secure Validator Mode and some mandatory errors occurred, warn otherwise. +/// +/// # Returns +/// +/// `true` if an error was printed, `false` otherwise. +fn print_secure_mode_message(errs: Vec) -> bool { // Trying to run securely and some mandatory errors occurred. const SECURE_MODE_ERROR: &'static str = "🚨 Your system cannot securely run a validator. \ \nRunning validation of malicious PVF code has a higher risk of compromising this machine."; @@ -162,31 +105,39 @@ fn print_secure_mode_error_or_warning(security_status: &FullSecurityStatus) { // securely. const SECURE_MODE_WARNING: &'static str = "🚨 Some security issues have been detected. \ \nRunning validation of malicious PVF code has a higher risk of compromising this machine."; - // Message to be printed only when running securely and mandatory errors occurred. - const IGNORE_SECURE_MODE_TIP: &'static str = - "\nYou can ignore this error with the `--insecure-validator-i-know-what-i-do` \ - command line argument if you understand and accept the risks of running insecurely. \ - With this flag, security features are enabled on a best-effort basis, but not mandatory. \ - \nMore information: https://wiki.polkadot.network/docs/maintain-guides-secure-validator#secure-validator-mode"; - let all_errs_allowed = security_status.all_errs_allowed(); - let errs_string = security_status.errs_string(); + if errs.is_empty() { + return false + } + + let errs_allowed = errs.iter().all(|err| err.is_allowed_in_secure_mode()); + let errs_string: String = errs + .iter() + .map(|err| { + format!( + "\n - {}{}", + if err.is_allowed_in_secure_mode() { "Optional: " } else { "" }, + err + ) + }) + .collect(); - if all_errs_allowed { + if errs_allowed { gum::warn!( target: LOG_TARGET, "{}{}", SECURE_MODE_WARNING, errs_string, ); + false } else { gum::error!( target: LOG_TARGET, - "{}{}{}", + "{}{}", SECURE_MODE_ERROR, errs_string, - IGNORE_SECURE_MODE_TIP ); + true } } @@ -347,53 +298,3 @@ async fn check_seccomp( } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_secure_mode_error_optionality() { - let err = SecureModeError::CannotEnableLandlock(String::new()); - assert!(err.is_allowed_in_secure_mode(&SecurityStatus { - secure_validator_mode: true, - can_enable_landlock: false, - can_enable_seccomp: false, - can_unshare_user_namespace_and_change_root: true - })); - assert!(!err.is_allowed_in_secure_mode(&SecurityStatus { - secure_validator_mode: true, - can_enable_landlock: false, - can_enable_seccomp: true, - can_unshare_user_namespace_and_change_root: false - })); - - let err = SecureModeError::CannotEnableSeccomp(String::new()); - assert!(!err.is_allowed_in_secure_mode(&SecurityStatus { - secure_validator_mode: true, - can_enable_landlock: false, - can_enable_seccomp: false, - can_unshare_user_namespace_and_change_root: true - })); - assert!(!err.is_allowed_in_secure_mode(&SecurityStatus { - secure_validator_mode: true, - can_enable_landlock: false, - can_enable_seccomp: true, - can_unshare_user_namespace_and_change_root: false - })); - - let err = SecureModeError::CannotUnshareUserNamespaceAndChangeRoot(String::new()); - assert!(err.is_allowed_in_secure_mode(&SecurityStatus { - secure_validator_mode: true, - can_enable_landlock: true, - can_enable_seccomp: false, - can_unshare_user_namespace_and_change_root: false - })); - assert!(!err.is_allowed_in_secure_mode(&SecurityStatus { - secure_validator_mode: true, - can_enable_landlock: false, - can_enable_seccomp: true, - can_unshare_user_namespace_and_change_root: false - })); - } -} diff --git a/polkadot/node/core/pvf/src/testing.rs b/polkadot/node/core/pvf/src/testing.rs index 60b0b4b8d3d..c7c885c4342 100644 --- a/polkadot/node/core/pvf/src/testing.rs +++ b/polkadot/node/core/pvf/src/testing.rs @@ -18,7 +18,7 @@ pub use crate::{ host::{EXECUTE_BINARY_NAME, PREPARE_BINARY_NAME}, - worker_interface::{spawn_with_program_path, SpawnErr}, + worker_intf::{spawn_with_program_path, SpawnErr}, }; use crate::get_worker_version; @@ -36,7 +36,7 @@ pub fn validate_candidate( code: &[u8], params: &[u8], ) -> Result, Box> { - use polkadot_node_core_pvf_common::executor_interface::{prepare, prevalidate}; + use polkadot_node_core_pvf_common::executor_intf::{prepare, prevalidate}; use polkadot_node_core_pvf_execute_worker::execute_artifact; let code = sp_maybe_compressed_blob::decompress(code, 10 * 1024 * 1024) diff --git a/polkadot/node/core/pvf/src/worker_interface.rs b/polkadot/node/core/pvf/src/worker_intf.rs similarity index 82% rename from polkadot/node/core/pvf/src/worker_interface.rs rename to polkadot/node/core/pvf/src/worker_intf.rs index c68ff92b06e..9d6907c1092 100644 --- a/polkadot/node/core/pvf/src/worker_interface.rs +++ b/polkadot/node/core/pvf/src/worker_intf.rs @@ -19,9 +19,8 @@ use crate::LOG_TARGET; use futures::FutureExt as _; use futures_timer::Delay; -use parity_scale_codec::Encode; use pin_project::pin_project; -use polkadot_node_core_pvf_common::{SecurityStatus, WorkerHandshake}; +use polkadot_node_core_pvf_common::SecurityStatus; use rand::Rng; use std::{ fmt, mem, @@ -69,54 +68,83 @@ pub async fn spawn_with_program_path( let program_path = program_path.into(); let worker_dir = WorkerDir::new(debug_id, cache_path).await?; let extra_args: Vec = extra_args.iter().map(|arg| arg.to_string()).collect(); - // Hack the borrow-checker. - let program_path_clone = program_path.clone(); - let worker_dir_clone = worker_dir.path().to_owned(); - let extra_args_clone = extra_args.clone(); with_transient_socket_path(debug_id, |socket_path| { let socket_path = socket_path.to_owned(); + let worker_dir_path = worker_dir.path().to_owned(); async move { - let listener = match UnixListener::bind(&socket_path) { - Ok(ok) => ok, - Err(err) => return Err(SpawnErr::Bind { socket_path, err: err.to_string() }), - }; - - let handle = - WorkerHandle::spawn(&program_path, &extra_args, &socket_path, &worker_dir.path()) - .map_err(|err| SpawnErr::ProcessSpawn { program_path, err: err.to_string() })?; + let listener = UnixListener::bind(&socket_path).map_err(|err| { + gum::warn!( + target: LOG_TARGET, + %debug_id, + ?program_path, + ?extra_args, + ?worker_dir, + ?socket_path, + "cannot bind unix socket: {:?}", + err, + ); + SpawnErr::Bind + })?; + + let handle = WorkerHandle::spawn( + &program_path, + &extra_args, + &socket_path, + &worker_dir_path, + security_status, + ) + .map_err(|err| { + gum::warn!( + target: LOG_TARGET, + %debug_id, + ?program_path, + ?extra_args, + ?worker_dir_path, + ?socket_path, + "cannot spawn a worker: {:?}", + err, + ); + SpawnErr::ProcessSpawn + })?; futures::select! { accept_result = listener.accept().fuse() => { - let (mut stream, _) = accept_result - .map_err(|err| SpawnErr::Accept { socket_path, err: err.to_string() })?; - send_worker_handshake(&mut stream, WorkerHandshake { security_status }) - .await - .map_err(|err| SpawnErr::Handshake { err: err.to_string() })?; + let (stream, _) = accept_result.map_err(|err| { + gum::warn!( + target: LOG_TARGET, + %debug_id, + ?program_path, + ?extra_args, + ?worker_dir_path, + ?socket_path, + "cannot accept a worker: {:?}", + err, + ); + SpawnErr::Accept + })?; Ok((IdleWorker { stream, pid: handle.id(), worker_dir }, handle)) } - _ = Delay::new(spawn_timeout).fuse() => Err(SpawnErr::AcceptTimeout{spawn_timeout}), + _ = Delay::new(spawn_timeout).fuse() => { + gum::warn!( + target: LOG_TARGET, + %debug_id, + ?program_path, + ?extra_args, + ?worker_dir_path, + ?socket_path, + ?spawn_timeout, + "spawning and connecting to socket timed out", + ); + Err(SpawnErr::AcceptTimeout) + } } } }) .await - .map_err(|err| { - gum::warn!( - target: LOG_TARGET, - %debug_id, - ?program_path_clone, - ?extra_args_clone, - ?worker_dir_clone, - "error spawning worker: {}", - err, - ); - err - }) } -/// A temporary, random, free path that is necessary only to establish socket communications. If a -/// directory exists at the path at the end of this function, it is removed then. async fn with_transient_socket_path(debug_id: &'static str, f: F) -> Result where F: FnOnce(&Path) -> Fut, @@ -186,26 +214,21 @@ pub struct IdleWorker { pub worker_dir: WorkerDir, } -/// This is publicly exposed only for integration tests. -/// /// An error happened during spawning a worker process. -#[derive(thiserror::Error, Clone, Debug)] -#[doc(hidden)] +#[derive(Clone, Debug)] pub enum SpawnErr { - #[error("cannot obtain a temporary path location")] + /// Cannot obtain a temporary path location. TmpPath, - #[error("cannot bind the socket to the given path {socket_path:?}: {err}")] - Bind { socket_path: PathBuf, err: String }, - #[error( - "an error happened during accepting a connection to the socket {socket_path:?}: {err}" - )] - Accept { socket_path: PathBuf, err: String }, - #[error("an error happened during spawning the process at path {program_path:?}: {err}")] - ProcessSpawn { program_path: PathBuf, err: String }, - #[error("the deadline {}ms allotted for the worker spawning and connecting to the socket has elapsed", .spawn_timeout.as_millis())] - AcceptTimeout { spawn_timeout: Duration }, - #[error("failed to send handshake after successful spawning was signaled: {err}")] - Handshake { err: String }, + /// Cannot bind the socket to the given path. + Bind, + /// An error happened during accepting a connection to the socket. + Accept, + /// An error happened during spawning the process. + ProcessSpawn, + /// The deadline allotted for the worker spawning and connecting to the socket has elapsed. + AcceptTimeout, + /// Failed to send handshake after successful spawning was signaled + Handshake, } /// This is a representation of a potentially running worker. Drop it and the process will be @@ -233,7 +256,22 @@ impl WorkerHandle { extra_args: &[String], socket_path: impl AsRef, worker_dir_path: impl AsRef, + security_status: SecurityStatus, ) -> io::Result { + let security_args = { + let mut args = vec![]; + if security_status.can_enable_landlock { + args.push("--can-enable-landlock".to_string()); + } + if security_status.can_enable_seccomp { + args.push("--can-enable-seccomp".to_string()); + } + if security_status.can_unshare_user_namespace_and_change_root { + args.push("--can-unshare-user-namespace-and-change-root".to_string()); + } + args + }; + // Clear all env vars from the spawned process. let mut command = process::Command::new(program.as_ref()); command.env_clear(); @@ -248,6 +286,7 @@ impl WorkerHandle { .arg(socket_path.as_ref().as_os_str()) .arg("--worker-dir-path") .arg(worker_dir_path.as_ref().as_os_str()) + .args(&security_args) .stdout(std::process::Stdio::piped()) .kill_on_drop(true) .spawn()?; @@ -347,14 +386,6 @@ pub async fn framed_recv(r: &mut (impl AsyncRead + Unpin)) -> io::Result Ok(buf) } -/// Sends a handshake with information for the worker. -async fn send_worker_handshake( - stream: &mut UnixStream, - handshake: WorkerHandshake, -) -> io::Result<()> { - framed_send(stream, &handshake.encode()).await -} - /// A temporary worker dir that contains only files needed by the worker. The worker will change its /// root (the `/` directory) to this directory; it should have access to no other paths on its /// filesystem. @@ -402,6 +433,8 @@ impl WorkerDir { // Not async since Rust has trouble with async recursion. There should be few files here anyway. // +// TODO: A lingering malicious job can still access future files in this dir. See +// for how to fully secure this. /// Clear the temporary worker dir without deleting it. Not deleting is important because the worker /// has mounted its own separate filesystem here. /// diff --git a/polkadot/node/core/pvf/tests/README.md b/polkadot/node/core/pvf/tests/README.md new file mode 100644 index 00000000000..27385e19025 --- /dev/null +++ b/polkadot/node/core/pvf/tests/README.md @@ -0,0 +1,9 @@ +# PVF host integration tests + +## Testing + +Before running these tests, make sure the worker binaries are built first. This can be done with: + +```sh +cargo build --bin polkadot-execute-worker --bin polkadot-prepare-worker +``` diff --git a/polkadot/node/core/pvf/tests/it/main.rs b/polkadot/node/core/pvf/tests/it/main.rs index 09f975b706d..bd6b04182fd 100644 --- a/polkadot/node/core/pvf/tests/it/main.rs +++ b/polkadot/node/core/pvf/tests/it/main.rs @@ -39,7 +39,6 @@ const TEST_EXECUTION_TIMEOUT: Duration = Duration::from_secs(6); const TEST_PREPARATION_TIMEOUT: Duration = Duration::from_secs(6); struct TestHost { - // Keep a reference to the tempdir as it gets deleted on drop. cache_dir: tempfile::TempDir, host: Mutex, } @@ -59,7 +58,6 @@ impl TestHost { let mut config = Config::new( cache_dir.path().to_owned(), None, - false, prepare_worker_path, execute_worker_path, ); @@ -417,49 +415,22 @@ async fn prepare_can_run_serially() { #[tokio::test] async fn all_security_features_work() { // Landlock is only available starting Linux 5.13, and we may be testing on an old kernel. - let can_enable_landlock = { - let sysinfo = sc_sysinfo::gather_sysinfo(); - // The version will look something like "5.15.0-87-generic". - let version = sysinfo.linux_kernel.unwrap(); - let version_split: Vec<&str> = version.split(".").collect(); - let major: u32 = version_split[0].parse().unwrap(); - let minor: u32 = version_split[1].parse().unwrap(); - if major >= 6 { - true - } else if major == 5 { - minor >= 13 - } else { - false - } - }; + let sysinfo = sc_sysinfo::gather_sysinfo(); + // The version will look something like "5.15.0-87-generic". + let version = sysinfo.linux_kernel.unwrap(); + let version_split: Vec<&str> = version.split(".").collect(); + let major: u32 = version_split[0].parse().unwrap(); + let minor: u32 = version_split[1].parse().unwrap(); + let can_enable_landlock = if major >= 6 { true } else { minor >= 13 }; let host = TestHost::new().await; assert_eq!( host.security_status().await, SecurityStatus { - secure_validator_mode: false, can_enable_landlock, can_enable_seccomp: true, can_unshare_user_namespace_and_change_root: true, } ); } - -// Regression test to make sure the unshare-pivot-root capability does not depend on the PVF -// artifacts cache existing. -#[cfg(all(feature = "ci-only-tests", target_os = "linux"))] -#[tokio::test] -async fn nonexistant_cache_dir() { - let host = TestHost::new_with_config(|cfg| { - cfg.cache_path = cfg.cache_path.join("nonexistant_cache_dir"); - }) - .await; - - assert!(host.security_status().await.can_unshare_user_namespace_and_change_root); - - let _stats = host - .precheck_pvf(::adder::wasm_binary_unwrap(), Default::default()) - .await - .unwrap(); -} diff --git a/polkadot/node/core/pvf/tests/it/worker_common.rs b/polkadot/node/core/pvf/tests/it/worker_common.rs index 2c24a15b682..4b736b08ba6 100644 --- a/polkadot/node/core/pvf/tests/it/worker_common.rs +++ b/polkadot/node/core/pvf/tests/it/worker_common.rs @@ -27,7 +27,6 @@ async fn spawn_immediate_exit() { // There's no explicit `exit` subcommand in the worker; it will panic on an unknown // subcommand anyway - let spawn_timeout = Duration::from_secs(2); let result = spawn_with_program_path( "integration-test", prepare_worker_path, @@ -37,28 +36,23 @@ async fn spawn_immediate_exit() { SecurityStatus::default(), ) .await; - assert!( - matches!(result, Err(SpawnErr::AcceptTimeout { spawn_timeout: s }) if s == spawn_timeout) - ); + assert!(matches!(result, Err(SpawnErr::AcceptTimeout))); } #[tokio::test] async fn spawn_timeout() { let (_, execute_worker_path) = build_workers_and_get_paths(); - let spawn_timeout = Duration::from_secs(2); let result = spawn_with_program_path( "integration-test", execute_worker_path, &env::temp_dir(), &["test-sleep"], - spawn_timeout, + Duration::from_secs(2), SecurityStatus::default(), ) .await; - assert!( - matches!(result, Err(SpawnErr::AcceptTimeout { spawn_timeout: s }) if s == spawn_timeout) - ); + assert!(matches!(result, Err(SpawnErr::AcceptTimeout))); } #[tokio::test] diff --git a/polkadot/node/core/runtime-api/Cargo.toml b/polkadot/node/core/runtime-api/Cargo.toml index 547431b45b2..f324f1e79c4 100644 --- a/polkadot/node/core/runtime-api/Cargo.toml +++ b/polkadot/node/core/runtime-api/Cargo.toml @@ -1,14 +1,11 @@ [package] name = "polkadot-node-core-runtime-api" version = "1.0.0" -description = "Wrapper around the parachain-related runtime APIs" +description="Wrapper around the parachain-related runtime APIs" authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] futures = "0.3.21" gum = { package = "tracing-gum", path = "../../gum" } diff --git a/polkadot/node/core/runtime-api/src/cache.rs b/polkadot/node/core/runtime-api/src/cache.rs index 5eca551db0a..8a7a3dc08b8 100644 --- a/polkadot/node/core/runtime-api/src/cache.rs +++ b/polkadot/node/core/runtime-api/src/cache.rs @@ -20,13 +20,12 @@ use schnellru::{ByLength, LruMap}; use sp_consensus_babe::Epoch; use polkadot_primitives::{ - async_backing, slashing, - vstaging::{self, ApprovalVotingParams}, - AuthorityDiscoveryId, BlockNumber, CandidateCommitments, CandidateEvent, CandidateHash, - CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, GroupRotationInfo, Hash, - Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, - PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, SessionIndex, SessionInfo, - ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, + async_backing, slashing, vstaging, AuthorityDiscoveryId, BlockNumber, CandidateCommitments, + CandidateEvent, CandidateHash, CommittedCandidateReceipt, CoreState, DisputeState, + ExecutorParams, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, + InboundHrmpMessage, OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, + ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidationCode, ValidationCodeHash, + ValidatorId, ValidatorIndex, ValidatorSignature, }; /// For consistency we have the same capacity for all caches. We use 128 as we'll only need that @@ -69,7 +68,6 @@ pub(crate) struct RequestResultCache { para_backing_state: LruMap<(Hash, ParaId), Option>, async_backing_params: LruMap, node_features: LruMap, - approval_voting_params: LruMap, } impl Default for RequestResultCache { @@ -100,7 +98,6 @@ impl Default for RequestResultCache { unapplied_slashes: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)), key_ownership_proof: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)), minimum_backing_votes: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)), - approval_voting_params: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)), disabled_validators: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)), para_backing_state: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)), async_backing_params: LruMap::new(ByLength::new(DEFAULT_CACHE_CAP)), @@ -510,21 +507,6 @@ impl RequestResultCache { ) { self.async_backing_params.insert(key, value); } - - pub(crate) fn approval_voting_params( - &mut self, - key: (Hash, SessionIndex), - ) -> Option<&ApprovalVotingParams> { - self.approval_voting_params.get(&key.1).map(|v| &*v) - } - - pub(crate) fn cache_approval_voting_params( - &mut self, - session_index: SessionIndex, - value: ApprovalVotingParams, - ) { - self.approval_voting_params.insert(session_index, value); - } } pub(crate) enum RequestResult { @@ -572,7 +554,6 @@ pub(crate) enum RequestResult { slashing::OpaqueKeyOwnershipProof, Option<()>, ), - ApprovalVotingParams(Hash, SessionIndex, ApprovalVotingParams), DisabledValidators(Hash, Vec), ParaBackingState(Hash, ParaId, Option), AsyncBackingParams(Hash, async_backing::AsyncBackingParams), diff --git a/polkadot/node/core/runtime-api/src/lib.rs b/polkadot/node/core/runtime-api/src/lib.rs index 4bedfd82734..8689355c413 100644 --- a/polkadot/node/core/runtime-api/src/lib.rs +++ b/polkadot/node/core/runtime-api/src/lib.rs @@ -165,8 +165,6 @@ where KeyOwnershipProof(relay_parent, validator_id, key_ownership_proof) => self .requests_cache .cache_key_ownership_proof((relay_parent, validator_id), key_ownership_proof), - RequestResult::ApprovalVotingParams(_relay_parent, session_index, params) => - self.requests_cache.cache_approval_voting_params(session_index, params), SubmitReportDisputeLost(_, _, _, _) => {}, DisabledValidators(relay_parent, disabled_validators) => self.requests_cache.cache_disabled_validators(relay_parent, disabled_validators), @@ -302,9 +300,6 @@ where Request::SubmitReportDisputeLost(dispute_proof, key_ownership_proof, sender) }, ), - Request::ApprovalVotingParams(session_index, sender) => - query!(approval_voting_params(session_index), sender) - .map(|sender| Request::ApprovalVotingParams(session_index, sender)), Request::DisabledValidators(sender) => query!(disabled_validators(), sender) .map(|sender| Request::DisabledValidators(sender)), Request::ParaBackingState(para, sender) => query!(para_backing_state(para), sender) @@ -576,14 +571,6 @@ where ver = Request::KEY_OWNERSHIP_PROOF_RUNTIME_REQUIREMENT, sender ), - Request::ApprovalVotingParams(session_index, sender) => { - query!( - ApprovalVotingParams, - approval_voting_params(session_index), - ver = Request::APPROVAL_VOTING_PARAMS_REQUIREMENT, - sender - ) - }, Request::SubmitReportDisputeLost(dispute_proof, key_ownership_proof, sender) => query!( SubmitReportDisputeLost, submit_report_dispute_lost(dispute_proof, key_ownership_proof), diff --git a/polkadot/node/core/runtime-api/src/tests.rs b/polkadot/node/core/runtime-api/src/tests.rs index f91723b3d39..b939bffb0e7 100644 --- a/polkadot/node/core/runtime-api/src/tests.rs +++ b/polkadot/node/core/runtime-api/src/tests.rs @@ -20,13 +20,12 @@ use polkadot_node_primitives::{BabeAllowedSlots, BabeEpoch, BabeEpochConfigurati use polkadot_node_subsystem::SpawnGlue; use polkadot_node_subsystem_test_helpers::make_subsystem_context; use polkadot_primitives::{ - async_backing, slashing, - vstaging::{ApprovalVotingParams, NodeFeatures}, - AuthorityDiscoveryId, BlockNumber, CandidateCommitments, CandidateEvent, CandidateHash, - CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, GroupRotationInfo, - Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, - PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, SessionIndex, SessionInfo, - Slot, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, + async_backing, slashing, vstaging::NodeFeatures, AuthorityDiscoveryId, BlockNumber, + CandidateCommitments, CandidateEvent, CandidateHash, CommittedCandidateReceipt, CoreState, + DisputeState, ExecutorParams, GroupRotationInfo, Id as ParaId, InboundDownwardMessage, + InboundHrmpMessage, OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, + ScrapedOnChainVotes, SessionIndex, SessionInfo, Slot, ValidationCode, ValidationCodeHash, + ValidatorId, ValidatorIndex, ValidatorSignature, }; use sp_api::ApiError; use sp_core::testing::TaskExecutor; @@ -243,15 +242,6 @@ impl RuntimeApiSubsystemClient for MockSubsystemClient { todo!("Not required for tests") } - /// Approval voting configuration parameters - async fn approval_voting_params( - &self, - _: Hash, - _: SessionIndex, - ) -> Result { - todo!("Not required for tests") - } - async fn current_epoch(&self, _: Hash) -> Result { Ok(self.babe_epoch.as_ref().unwrap().clone()) } diff --git a/polkadot/node/gum/Cargo.toml b/polkadot/node/gum/Cargo.toml index ccb21f64e63..acee9efd0e0 100644 --- a/polkadot/node/gum/Cargo.toml +++ b/polkadot/node/gum/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "Stick logs together with the TraceID as provided by tempo" -[lints] -workspace = true - [dependencies] coarsetime = "0.1.22" tracing = "0.1.35" diff --git a/polkadot/node/gum/proc-macro/Cargo.toml b/polkadot/node/gum/proc-macro/Cargo.toml index f7880bfd2f9..1ffaf6160ba 100644 --- a/polkadot/node/gum/proc-macro/Cargo.toml +++ b/polkadot/node/gum/proc-macro/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "Generate an overseer including builder pattern and message wrapper from a single annotated struct definition." -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -16,10 +13,10 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -syn = { version = "2.0.40", features = ["extra-traits", "full"] } +syn = { version = "2.0.38", features = ["full", "extra-traits"] } quote = "1.0.28" proc-macro2 = "1.0.56" -proc-macro-crate = "2.0.1" +proc-macro-crate = "1.1.3" expander = "2.0.0" [dev-dependencies] diff --git a/polkadot/node/jaeger/Cargo.toml b/polkadot/node/jaeger/Cargo.toml index 81947f4f6a4..fcfbbaec611 100644 --- a/polkadot/node/jaeger/Cargo.toml +++ b/polkadot/node/jaeger/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "Polkadot Jaeger primitives, but equally useful for Grafana/Tempo" -[lints] -workspace = true - [dependencies] mick-jaeger = "0.1.8" lazy_static = "1.4" diff --git a/polkadot/node/malus/Cargo.toml b/polkadot/node/malus/Cargo.toml index d0a9b65f720..f52f0cc0282 100644 --- a/polkadot/node/malus/Cargo.toml +++ b/polkadot/node/malus/Cargo.toml @@ -8,9 +8,6 @@ license.workspace = true readme = "README.md" publish = false -[lints] -workspace = true - [[bin]] name = "malus" path = "src/malus.rs" @@ -29,7 +26,7 @@ path = "../../src/bin/prepare-worker.rs" doc = false [dependencies] -polkadot-cli = { path = "../../cli", features = ["malus", "rococo-native", "westend-native"] } +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" } @@ -43,7 +40,7 @@ assert_matches = "1.5" async-trait = "0.1.57" sp-keystore = { path = "../../../substrate/primitives/keystore" } sp-core = { path = "../../../substrate/primitives/core" } -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } futures = "0.3.21" futures-timer = "3.0.2" gum = { package = "tracing-gum", path = "../gum" } @@ -65,4 +62,4 @@ substrate-build-script-utils = { path = "../../../substrate/utils/build-script-u [features] default = [] -fast-runtime = ["polkadot-cli/fast-runtime"] +fast-runtime = [ "polkadot-cli/fast-runtime" ] diff --git a/polkadot/node/malus/src/malus.rs b/polkadot/node/malus/src/malus.rs index b8a83e54d4f..69dd7c869fc 100644 --- a/polkadot/node/malus/src/malus.rs +++ b/polkadot/node/malus/src/malus.rs @@ -36,8 +36,6 @@ enum NemesisVariant { BackGarbageCandidate(BackGarbageCandidateOptions), /// Delayed disputing of ancestors that are perfectly fine. DisputeAncestor(DisputeAncestorOptions), - /// Delayed disputing of finalized candidates. - DisputeFinalizedCandidates(DisputeFinalizedCandidatesOptions), } #[derive(Debug, Parser)] @@ -82,15 +80,6 @@ impl MalusCli { finality_delay, )? }, - NemesisVariant::DisputeFinalizedCandidates(opts) => { - let DisputeFinalizedCandidatesOptions { dispute_offset, cli } = opts; - - polkadot_cli::run_node( - cli, - DisputeFinalizedCandidates { dispute_offset }, - finality_delay, - )? - }, } Ok(()) } @@ -195,39 +184,4 @@ mod tests { assert!(run.cli.run.base.bob); }); } - - #[test] - fn dispute_finalized_candidates_works() { - let cli = MalusCli::try_parse_from(IntoIterator::into_iter([ - "malus", - "dispute-finalized-candidates", - "--bob", - ])) - .unwrap(); - assert_matches::assert_matches!(cli, MalusCli { - variant: NemesisVariant::DisputeFinalizedCandidates(run), - .. - } => { - assert!(run.cli.run.base.bob); - }); - } - - #[test] - fn dispute_finalized_offset_value_works() { - let cli = MalusCli::try_parse_from(IntoIterator::into_iter([ - "malus", - "dispute-finalized-candidates", - "--dispute-offset", - "13", - "--bob", - ])) - .unwrap(); - assert_matches::assert_matches!(cli, MalusCli { - variant: NemesisVariant::DisputeFinalizedCandidates(opts), - .. - } => { - assert_eq!(opts.dispute_offset, 13); // This line checks that dispute_offset is correctly set to 13 - assert!(opts.cli.run.base.bob); - }); - } } diff --git a/polkadot/node/malus/src/variants/common.rs b/polkadot/node/malus/src/variants/common.rs index 92264cd653d..20b6654638e 100644 --- a/polkadot/node/malus/src/variants/common.rs +++ b/polkadot/node/malus/src/variants/common.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -//! Implements common code for nemesis. Currently, only `ReplaceValidationResult` +//! Implements common code for nemesis. Currently, only `FakeValidationResult` //! interceptor is implemented. use crate::{ interceptor::*, @@ -188,7 +188,7 @@ where let _candidate_descriptor = candidate_descriptor.clone(); let mut subsystem_sender = subsystem_sender.clone(); let (sender, receiver) = std::sync::mpsc::channel(); - self.spawner.spawn( + self.spawner.spawn_blocking( "malus-get-validation-data", Some("malus"), Box::pin(async move { diff --git a/polkadot/node/malus/src/variants/dispute_finalized_candidates.rs b/polkadot/node/malus/src/variants/dispute_finalized_candidates.rs deleted file mode 100644 index 113ab026879..00000000000 --- a/polkadot/node/malus/src/variants/dispute_finalized_candidates.rs +++ /dev/null @@ -1,265 +0,0 @@ -// 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 . - -//! A malicious node variant that attempts to dispute finalized candidates. -//! -//! This malus variant behaves honestly in backing and approval voting. -//! The maliciousness comes from emitting an extra dispute statement on top of the other ones. -//! -//! Some extra quirks which generally should be insignificant: -//! - The malus node will not dispute at session boundaries -//! - The malus node will not dispute blocks it backed itself -//! - Be cautious about the size of the network to make sure disputes are not auto-confirmed -//! (7 validators is the smallest network size as it needs [(7-1)//3]+1 = 3 votes to get -//! confirmed but it only gets 1 from backing and 1 from malus so 2 in total) -//! -//! -//! Attention: For usage with `zombienet` only! - -#![allow(missing_docs)] - -use futures::channel::oneshot; -use polkadot_cli::{ - prepared_overseer_builder, - service::{ - AuthorityDiscoveryApi, AuxStore, BabeApi, Block, Error, HeaderBackend, Overseer, - OverseerConnector, OverseerGen, OverseerGenArgs, OverseerHandle, ParachainHost, - ProvideRuntimeApi, - }, - Cli, -}; -use polkadot_node_subsystem::{messages::ApprovalVotingMessage, SpawnGlue}; -use polkadot_node_subsystem_types::{DefaultSubsystemClient, OverseerSignal}; -use polkadot_node_subsystem_util::request_candidate_events; -use polkadot_primitives::CandidateEvent; -use sp_core::traits::SpawnNamed; - -// Filter wrapping related types. -use crate::{interceptor::*, shared::MALUS}; - -use std::sync::Arc; - -/// Wraps around ApprovalVotingSubsystem and replaces it. -/// Listens to finalization messages and if possible triggers disputes for their ancestors. -#[derive(Clone)] -struct AncestorDisputer { - spawner: Spawner, //stores the actual ApprovalVotingSubsystem spawner - dispute_offset: u32, /* relative depth of the disputed block to the finalized block, - * 0=finalized, 1=parent of finalized etc */ -} - -impl MessageInterceptor for AncestorDisputer -where - Sender: overseer::ApprovalVotingSenderTrait + Clone + Send + 'static, - Spawner: overseer::gen::Spawner + Clone + 'static, -{ - type Message = ApprovalVotingMessage; - - /// Intercept incoming `OverseerSignal::BlockFinalized' and pass the rest as normal. - fn intercept_incoming( - &self, - subsystem_sender: &mut Sender, - msg: FromOrchestra, - ) -> Option> { - match msg { - FromOrchestra::Communication { msg } => Some(FromOrchestra::Communication { msg }), - FromOrchestra::Signal(OverseerSignal::BlockFinalized( - finalized_hash, - finalized_height, - )) => { - gum::debug!( - target: MALUS, - "😈 Block Finalization Interception! Block: {:?}", finalized_hash, - ); - - //Ensure that the chain is long enough for the target ancestor to exist - if finalized_height <= self.dispute_offset { - return Some(FromOrchestra::Signal(OverseerSignal::BlockFinalized( - finalized_hash, - finalized_height, - ))) - } - - let dispute_offset = self.dispute_offset; - let mut sender = subsystem_sender.clone(); - self.spawner.spawn( - "malus-dispute-finalized-block", - Some("malus"), - Box::pin(async move { - // Query chain for the block hash at the target depth - let (tx, rx) = oneshot::channel(); - sender - .send_message(ChainApiMessage::FinalizedBlockHash( - finalized_height - dispute_offset, - tx, - )) - .await; - let disputable_hash = match rx.await { - Ok(Ok(Some(hash))) => { - gum::debug!( - target: MALUS, - "😈 Time to search {:?}`th ancestor! Block: {:?}", dispute_offset, hash, - ); - hash - }, - _ => { - gum::debug!( - target: MALUS, - "😈 Seems the target is not yet finalized! Nothing to dispute." - ); - return // Early return from the async block - }, - }; - - // Fetch all candidate events for the target ancestor - let events = - request_candidate_events(disputable_hash, &mut sender).await.await; - let events = match events { - Ok(Ok(events)) => events, - Ok(Err(e)) => { - gum::error!( - target: MALUS, - "😈 Failed to fetch candidate events: {:?}", e - ); - return // Early return from the async block - }, - Err(e) => { - gum::error!( - target: MALUS, - "😈 Failed to fetch candidate events: {:?}", e - ); - return // Early return from the async block - }, - }; - - // Extract a token candidate from the events to use for disputing - let event = events.iter().find(|event| { - matches!(event, CandidateEvent::CandidateIncluded(_, _, _, _)) - }); - let candidate = match event { - Some(CandidateEvent::CandidateIncluded(candidate, _, _, _)) => - candidate, - _ => { - gum::error!( - target: MALUS, - "😈 No candidate included event found! Nothing to dispute." - ); - return // Early return from the async block - }, - }; - - // Extract the candidate hash from the candidate - let candidate_hash = candidate.hash(); - - // Fetch the session index for the candidate - let (tx, rx) = oneshot::channel(); - sender - .send_message(RuntimeApiMessage::Request( - disputable_hash, - RuntimeApiRequest::SessionIndexForChild(tx), - )) - .await; - let session_index = match rx.await { - Ok(Ok(session_index)) => session_index, - _ => { - gum::error!( - target: MALUS, - "😈 Failed to fetch session index for candidate." - ); - return // Early return from the async block - }, - }; - gum::info!( - target: MALUS, - "😈 Disputing candidate with hash: {:?} in session {:?}", candidate_hash, session_index, - ); - - // Start dispute - sender.send_unbounded_message( - DisputeCoordinatorMessage::IssueLocalStatement( - session_index, - candidate_hash, - candidate.clone(), - false, // indicates candidate is invalid -> dispute starts - ), - ); - }), - ); - - // Passthrough the finalization signal as usual (using it as hook only) - Some(FromOrchestra::Signal(OverseerSignal::BlockFinalized( - finalized_hash, - finalized_height, - ))) - }, - FromOrchestra::Signal(signal) => Some(FromOrchestra::Signal(signal)), - } - } -} - -//---------------------------------------------------------------------------------- - -#[derive(Debug, clap::Parser)] -#[clap(rename_all = "kebab-case")] -#[allow(missing_docs)] -pub struct DisputeFinalizedCandidatesOptions { - /// relative depth of the disputed block to the finalized block, 0=finalized, 1=parent of - /// finalized etc - #[clap(long, ignore_case = true, default_value_t = 2, value_parser = clap::value_parser!(u32).range(0..=50))] - pub dispute_offset: u32, - - #[clap(flatten)] - pub cli: Cli, -} - -/// DisputeFinalizedCandidates implementation wrapper which implements `OverseerGen` glue. -pub(crate) struct DisputeFinalizedCandidates { - /// relative depth of the disputed block to the finalized block, 0=finalized, 1=parent of - /// finalized etc - pub dispute_offset: u32, -} - -impl OverseerGen for DisputeFinalizedCandidates { - fn generate( - &self, - connector: OverseerConnector, - args: OverseerGenArgs<'_, Spawner, RuntimeClient>, - ) -> Result< - (Overseer, Arc>>, OverseerHandle), - Error, - > - where - RuntimeClient: 'static + ProvideRuntimeApi + HeaderBackend + AuxStore, - RuntimeClient::Api: ParachainHost + BabeApi + AuthorityDiscoveryApi, - Spawner: 'static + SpawnNamed + Clone + Unpin, - { - gum::info!( - target: MALUS, - "😈 Started Malus node that disputes finalized blocks after they are {:?} finalizations deep.", - &self.dispute_offset, - ); - - let ancestor_disputer = AncestorDisputer { - spawner: SpawnGlue(args.spawner.clone()), - dispute_offset: self.dispute_offset, - }; - - prepared_overseer_builder(args)? - .replace_approval_voting(move |cb| InterceptedSubsystem::new(cb, ancestor_disputer)) - .build_with_connector(connector) - .map_err(|e| e.into()) - } -} diff --git a/polkadot/node/malus/src/variants/mod.rs b/polkadot/node/malus/src/variants/mod.rs index bb4971c145c..3789f33ac98 100644 --- a/polkadot/node/malus/src/variants/mod.rs +++ b/polkadot/node/malus/src/variants/mod.rs @@ -18,13 +18,11 @@ mod back_garbage_candidate; mod common; -mod dispute_finalized_candidates; mod dispute_valid_candidates; mod suggest_garbage_candidate; pub(crate) use self::{ back_garbage_candidate::{BackGarbageCandidateOptions, BackGarbageCandidates}, - dispute_finalized_candidates::{DisputeFinalizedCandidates, DisputeFinalizedCandidatesOptions}, dispute_valid_candidates::{DisputeAncestorOptions, DisputeValidCandidates}, suggest_garbage_candidate::{SuggestGarbageCandidateOptions, SuggestGarbageCandidates}, }; diff --git a/polkadot/node/malus/src/variants/suggest_garbage_candidate.rs b/polkadot/node/malus/src/variants/suggest_garbage_candidate.rs index 817afb58437..cf0ff5f809d 100644 --- a/polkadot/node/malus/src/variants/suggest_garbage_candidate.rs +++ b/polkadot/node/malus/src/variants/suggest_garbage_candidate.rs @@ -113,7 +113,7 @@ where let (sender, receiver) = std::sync::mpsc::channel(); let mut new_sender = subsystem_sender.clone(); let _candidate = candidate.clone(); - self.spawner.spawn( + self.spawner.spawn_blocking( "malus-get-validation-data", Some("malus"), Box::pin(async move { diff --git a/polkadot/node/metrics/Cargo.toml b/polkadot/node/metrics/Cargo.toml index e9a4d463f4d..e13ae63199f 100644 --- a/polkadot/node/metrics/Cargo.toml +++ b/polkadot/node/metrics/Cargo.toml @@ -6,15 +6,12 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] futures = "0.3.21" futures-timer = "3.0.2" gum = { package = "tracing-gum", path = "../gum" } -metered = { package = "prioritized-metered-channel", version = "0.5.1", default-features = false, features = ["futures_channel"] } +metered = { package = "prioritized-metered-channel", version = "0.5.1", default-features = false, features=["futures_channel"] } # 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" } @@ -31,11 +28,11 @@ assert_cmd = "2.0.4" tempfile = "3.2.0" hyper = { version = "0.14.20", default-features = false, features = ["http1", "tcp"] } tokio = "1.24.2" -polkadot-test-service = { path = "../test/service", features = ["runtime-metrics"] } +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" } +prometheus-parse = {version = "0.2.2"} [features] default = [] diff --git a/polkadot/node/network/approval-distribution/Cargo.toml b/polkadot/node/network/approval-distribution/Cargo.toml index 7291c1309e1..f8a7cc15f87 100644 --- a/polkadot/node/network/approval-distribution/Cargo.toml +++ b/polkadot/node/network/approval-distribution/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] polkadot-node-metrics = { path = "../../metrics" } polkadot-node-network-protocol = { path = "../protocol" } @@ -34,8 +31,7 @@ polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } assert_matches = "1.4.0" schnorrkel = { version = "0.9.1", default-features = false } -# rand_core should match schnorrkel -rand_core = "0.5.1" +rand_core = "0.5.1" # should match schnorrkel rand_chacha = "0.3.1" env_logger = "0.9.0" log = "0.4.17" diff --git a/polkadot/node/network/approval-distribution/src/lib.rs b/polkadot/node/network/approval-distribution/src/lib.rs index d520febaef5..47482eef764 100644 --- a/polkadot/node/network/approval-distribution/src/lib.rs +++ b/polkadot/node/network/approval-distribution/src/lib.rs @@ -32,15 +32,14 @@ use polkadot_node_network_protocol::{ self as net_protocol, filter_by_peer_version, grid_topology::{RandomRouting, RequiredRouting, SessionGridTopologies, SessionGridTopology}, peer_set::MAX_NOTIFICATION_SIZE, - v1 as protocol_v1, v2 as protocol_v2, v3 as protocol_v3, PeerId, + v1 as protocol_v1, v2 as protocol_v2, vstaging as protocol_vstaging, PeerId, UnifiedReputationChange as Rep, Versioned, View, }; use polkadot_node_primitives::approval::{ - v1::{AssignmentCertKind, BlockApprovalMeta, IndirectAssignmentCert}, - v2::{ - AsBitIndex, AssignmentCertKindV2, CandidateBitfield, IndirectAssignmentCertV2, - IndirectSignedApprovalVoteV2, + v1::{ + AssignmentCertKind, BlockApprovalMeta, IndirectAssignmentCert, IndirectSignedApprovalVote, }, + v2::{AsBitIndex, AssignmentCertKindV2, CandidateBitfield, IndirectAssignmentCertV2}, }; use polkadot_node_subsystem::{ messages::{ @@ -114,14 +113,6 @@ struct ApprovalRouting { required_routing: RequiredRouting, local: bool, random_routing: RandomRouting, - peers_randomly_routed: Vec, -} - -impl ApprovalRouting { - fn mark_randomly_sent(&mut self, peer: PeerId) { - self.random_routing.inc_sent(); - self.peers_randomly_routed.push(peer); - } } // This struct is responsible for tracking the full state of an assignment and grid routing @@ -130,9 +121,9 @@ struct ApprovalEntry { // The assignment certificate. assignment: IndirectAssignmentCertV2, // The candidates claimed by the certificate. A mapping between bit index and candidate index. - assignment_claimed_candidates: CandidateBitfield, + candidates: CandidateBitfield, // The approval signatures for each `CandidateIndex` claimed by the assignment certificate. - approvals: HashMap, + approvals: HashMap, // The validator index of the assignment signer. validator_index: ValidatorIndex, // Information required for gossiping to other peers using the grid topology. @@ -145,8 +136,6 @@ enum ApprovalEntryError { CandidateIndexOutOfBounds, InvalidCandidateIndex, DuplicateApproval, - UnknownAssignment, - AssignmentsFollowedDifferentPaths(RequiredRouting, RequiredRouting), } impl ApprovalEntry { @@ -159,7 +148,7 @@ impl ApprovalEntry { validator_index: assignment.validator, assignment, approvals: HashMap::with_capacity(candidates.len()), - assignment_claimed_candidates: candidates, + candidates, routing_info, } } @@ -167,15 +156,23 @@ impl ApprovalEntry { // Create a `MessageSubject` to reference the assignment. pub fn create_assignment_knowledge(&self, block_hash: Hash) -> (MessageSubject, MessageKind) { ( - MessageSubject( - block_hash, - self.assignment_claimed_candidates.clone(), - self.validator_index, - ), + MessageSubject(block_hash, self.candidates.clone(), self.validator_index), MessageKind::Assignment, ) } + // Create a `MessageSubject` to reference the approval. + pub fn create_approval_knowledge( + &self, + block_hash: Hash, + candidate_index: CandidateIndex, + ) -> (MessageSubject, MessageKind) { + ( + MessageSubject(block_hash, candidate_index.into(), self.validator_index), + MessageKind::Approval, + ) + } + // Updates routing information and returns the previous information if any. pub fn routing_info_mut(&mut self) -> &mut ApprovalRouting { &mut self.routing_info @@ -191,21 +188,11 @@ impl ApprovalEntry { self.routing_info.required_routing = required_routing; } - // Tells if this entry assignment covers at least one candidate in the approval - pub fn includes_approval_candidates(&self, approval: &IndirectSignedApprovalVoteV2) -> bool { - for candidate_index in approval.candidate_indices.iter_ones() { - if self.assignment_claimed_candidates.bit_at((candidate_index).as_bit_index()) { - return true - } - } - return false - } - // Records a new approval. Returns error if the claimed candidate is not found or we already // have received the approval. pub fn note_approval( &mut self, - approval: IndirectSignedApprovalVoteV2, + approval: IndirectSignedApprovalVote, ) -> Result<(), ApprovalEntryError> { // First do some sanity checks: // - check validator index matches @@ -215,29 +202,37 @@ impl ApprovalEntry { return Err(ApprovalEntryError::InvalidValidatorIndex) } - // We need at least one of the candidates in the approval to be in this assignment - if !self.includes_approval_candidates(&approval) { + if self.candidates.len() <= approval.candidate_index as usize { + return Err(ApprovalEntryError::CandidateIndexOutOfBounds) + } + + if !self.candidates.bit_at(approval.candidate_index.as_bit_index()) { return Err(ApprovalEntryError::InvalidCandidateIndex) } - if self.approvals.contains_key(&approval.candidate_indices) { + if self.approvals.contains_key(&approval.candidate_index) { return Err(ApprovalEntryError::DuplicateApproval) } - self.approvals.insert(approval.candidate_indices.clone(), approval.clone()); + self.approvals.insert(approval.candidate_index, approval); Ok(()) } // Get the assignment certiticate and claimed candidates. pub fn assignment(&self) -> (IndirectAssignmentCertV2, CandidateBitfield) { - (self.assignment.clone(), self.assignment_claimed_candidates.clone()) + (self.assignment.clone(), self.candidates.clone()) } // Get all approvals for all candidates claimed by the assignment. - pub fn approvals(&self) -> Vec { + pub fn approvals(&self) -> Vec { self.approvals.values().cloned().collect::>() } + // Get the approval for a specific candidate index. + pub fn approval(&self, candidate_index: CandidateIndex) -> Option { + self.approvals.get(&candidate_index).cloned() + } + // Get validator index. pub fn validator_index(&self) -> ValidatorIndex { self.validator_index @@ -435,41 +430,6 @@ impl PeerKnowledge { fn contains(&self, message: &MessageSubject, kind: MessageKind) -> bool { self.sent.contains(message, kind) || self.received.contains(message, kind) } - - // Generate the knowledge keys for querying if all assignments of an approval are known - // by this peer. - fn generate_assignments_keys( - approval: &IndirectSignedApprovalVoteV2, - ) -> Vec<(MessageSubject, MessageKind)> { - approval - .candidate_indices - .iter_ones() - .map(|candidate_index| { - ( - MessageSubject( - approval.block_hash, - (candidate_index as CandidateIndex).into(), - approval.validator, - ), - MessageKind::Assignment, - ) - }) - .collect_vec() - } - - // Generate the knowledge keys for querying if an approval is known by peer. - fn generate_approval_key( - approval: &IndirectSignedApprovalVoteV2, - ) -> (MessageSubject, MessageKind) { - ( - MessageSubject( - approval.block_hash, - approval.candidate_indices.clone(), - approval.validator, - ), - MessageKind::Approval, - ) - } } /// Information about blocks in our current view as well as whether peers know of them. @@ -502,13 +462,13 @@ impl BlockEntry { // First map one entry per candidate to the same key we will use in `approval_entries`. // Key is (Validator_index, CandidateBitfield) that links the `ApprovalEntry` to the (K,V) // entry in `candidate_entry.messages`. - for claimed_candidate_index in entry.assignment_claimed_candidates.iter_ones() { + for claimed_candidate_index in entry.candidates.iter_ones() { match self.candidates.get_mut(claimed_candidate_index) { Some(candidate_entry) => { candidate_entry - .assignments + .messages .entry(entry.validator_index()) - .or_insert(entry.assignment_claimed_candidates.clone()); + .or_insert(entry.candidates.clone()); }, None => { // This should never happen, but if it happens, it means the subsystem is @@ -524,107 +484,50 @@ impl BlockEntry { } self.approval_entries - .entry((entry.validator_index, entry.assignment_claimed_candidates.clone())) + .entry((entry.validator_index, entry.candidates.clone())) .or_insert(entry) } - // Tels if all candidate_indices are valid candidates - pub fn contains_candidates(&self, candidate_indices: &CandidateBitfield) -> bool { - candidate_indices - .iter_ones() - .all(|candidate_index| self.candidates.get(candidate_index as usize).is_some()) - } - - // Saves the given approval in all ApprovalEntries that contain an assignment for any of the - // candidates in the approval. - // - // Returns the required routing needed for this approval and the lit of random peers the - // covering assignments were sent. - pub fn note_approval( + // Returns a mutable reference of `ApprovalEntry` for `candidate_index` from validator + // `validator_index`. + pub fn approval_entry( &mut self, - approval: IndirectSignedApprovalVoteV2, - ) -> Result<(RequiredRouting, HashSet), ApprovalEntryError> { - let mut required_routing = None; - let mut peers_randomly_routed_to = HashSet::new(); - - if self.candidates.len() < approval.candidate_indices.len() as usize { - return Err(ApprovalEntryError::CandidateIndexOutOfBounds) - } - - // First determine all assignments bitfields that might be covered by this approval - let covered_assignments_bitfields: HashSet = approval - .candidate_indices - .iter_ones() - .filter_map(|candidate_index| { - self.candidates.get_mut(candidate_index).map_or(None, |candidate_entry| { - candidate_entry.assignments.get(&approval.validator).cloned() - }) + candidate_index: CandidateIndex, + validator_index: ValidatorIndex, + ) -> Option<&mut ApprovalEntry> { + self.candidates + .get(candidate_index as usize) + .map_or(None, |candidate_entry| candidate_entry.messages.get(&validator_index)) + .map_or(None, |candidate_indices| { + self.approval_entries.get_mut(&(validator_index, candidate_indices.clone())) }) - .collect(); + } - // Mark the vote in all approval entries - for assignment_bitfield in covered_assignments_bitfields { - if let Some(approval_entry) = - self.approval_entries.get_mut(&(approval.validator, assignment_bitfield)) - { - approval_entry.note_approval(approval.clone())?; - peers_randomly_routed_to - .extend(approval_entry.routing_info().peers_randomly_routed.iter()); - - if let Some(required_routing) = required_routing { - if required_routing != approval_entry.routing_info().required_routing { - // This shouldn't happen since the required routing is computed based on the - // validator_index, so two assignments from the same validators will have - // the same required routing. - return Err(ApprovalEntryError::AssignmentsFollowedDifferentPaths( - required_routing, - approval_entry.routing_info().required_routing, - )) - } - } else { - required_routing = Some(approval_entry.routing_info().required_routing) + // Get all approval entries for a given candidate. + pub fn approval_entries(&self, candidate_index: CandidateIndex) -> Vec<&ApprovalEntry> { + // Get the keys for fetching `ApprovalEntry` from `self.approval_entries`, + let approval_entry_keys = self + .candidates + .get(candidate_index as usize) + .map(|candidate_entry| &candidate_entry.messages); + + if let Some(approval_entry_keys) = approval_entry_keys { + // Ensure no duplicates. + let approval_entry_keys = approval_entry_keys.iter().unique().collect::>(); + + let mut entries = Vec::new(); + for (validator_index, candidate_indices) in approval_entry_keys { + if let Some(entry) = + self.approval_entries.get(&(*validator_index, candidate_indices.clone())) + { + entries.push(entry); } } - } - - if let Some(required_routing) = required_routing { - Ok((required_routing, peers_randomly_routed_to)) + entries } else { - Err(ApprovalEntryError::UnknownAssignment) + vec![] } } - - /// Returns the list of approval votes covering this candidate - pub fn approval_votes( - &self, - candidate_index: CandidateIndex, - ) -> Vec { - let result: Option< - HashMap<(ValidatorIndex, CandidateBitfield), IndirectSignedApprovalVoteV2>, - > = self.candidates.get(candidate_index as usize).map(|candidate_entry| { - candidate_entry - .assignments - .iter() - .filter_map(|(validator, assignment_bitfield)| { - self.approval_entries.get(&(*validator, assignment_bitfield.clone())) - }) - .flat_map(|approval_entry| { - approval_entry - .approvals - .clone() - .into_iter() - .filter(|(approved_candidates, _)| { - approved_candidates.bit_at(candidate_index.as_bit_index()) - }) - .map(|(approved_candidates, vote)| { - ((approval_entry.validator_index, approved_candidates), vote) - }) - }) - .collect() - }); - - result.map(|result| result.into_values().collect_vec()).unwrap_or_default() - } } // Information about candidates in the context of a particular block they are included in. @@ -634,7 +537,7 @@ impl BlockEntry { struct CandidateEntry { // The value represents part of the lookup key in `approval_entries` to fetch the assignment // and existing votes. - assignments: HashMap, + messages: HashMap, } #[derive(Debug, Clone, PartialEq)] @@ -654,7 +557,7 @@ impl MessageSource { enum PendingMessage { Assignment(IndirectAssignmentCertV2, CandidateBitfield), - Approval(IndirectSignedApprovalVoteV2), + Approval(IndirectSignedApprovalVote), } #[overseer::contextbounds(ApprovalDistribution, prefix = self::overseer)] @@ -927,49 +830,6 @@ impl State { } } - // Entry point for processing an approval coming from a peer. - async fn process_incoming_approvals( - &mut self, - ctx: &mut Context, - metrics: &Metrics, - peer_id: PeerId, - approvals: Vec, - ) { - gum::trace!( - target: LOG_TARGET, - peer_id = %peer_id, - num = approvals.len(), - "Processing approvals from a peer", - ); - for approval_vote in approvals.into_iter() { - if let Some(pending) = self.pending_known.get_mut(&approval_vote.block_hash) { - let block_hash = approval_vote.block_hash; - let validator_index = approval_vote.validator; - - gum::trace!( - target: LOG_TARGET, - %peer_id, - ?block_hash, - ?validator_index, - "Pending assignment candidates {:?}", - approval_vote.candidate_indices, - ); - - pending.push((peer_id, PendingMessage::Approval(approval_vote))); - - continue - } - - self.import_and_circulate_approval( - ctx, - metrics, - MessageSource::Peer(peer_id), - approval_vote, - ) - .await; - } - } - async fn process_incoming_peer_message( &mut self, ctx: &mut Context, @@ -978,14 +838,16 @@ impl State { msg: Versioned< protocol_v1::ApprovalDistributionMessage, protocol_v2::ApprovalDistributionMessage, - protocol_v3::ApprovalDistributionMessage, + protocol_vstaging::ApprovalDistributionMessage, >, rng: &mut R, ) where R: CryptoRng + Rng, { match msg { - Versioned::V3(protocol_v3::ApprovalDistributionMessage::Assignments(assignments)) => { + Versioned::VStaging(protocol_vstaging::ApprovalDistributionMessage::Assignments( + assignments, + )) => { gum::trace!( target: LOG_TARGET, peer_id = %peer_id, @@ -1025,18 +887,45 @@ impl State { ) .await; }, - Versioned::V3(protocol_v3::ApprovalDistributionMessage::Approvals(approvals)) => { - self.process_incoming_approvals(ctx, metrics, peer_id, approvals).await; - }, + Versioned::VStaging(protocol_vstaging::ApprovalDistributionMessage::Approvals( + approvals, + )) | Versioned::V1(protocol_v1::ApprovalDistributionMessage::Approvals(approvals)) | Versioned::V2(protocol_v2::ApprovalDistributionMessage::Approvals(approvals)) => { - self.process_incoming_approvals( - ctx, - metrics, - peer_id, - approvals.into_iter().map(|approval| approval.into()).collect::>(), - ) - .await; + gum::trace!( + target: LOG_TARGET, + peer_id = %peer_id, + num = approvals.len(), + "Processing approvals from a peer", + ); + for approval_vote in approvals.into_iter() { + if let Some(pending) = self.pending_known.get_mut(&approval_vote.block_hash) { + let block_hash = approval_vote.block_hash; + let candidate_index = approval_vote.candidate_index; + let validator_index = approval_vote.validator; + + gum::trace!( + target: LOG_TARGET, + %peer_id, + ?block_hash, + ?candidate_index, + ?validator_index, + "Pending assignment", + ); + + pending.push((peer_id, PendingMessage::Approval(approval_vote))); + + continue + } + + self.import_and_circulate_approval( + ctx, + metrics, + MessageSource::Peer(peer_id), + approval_vote, + ) + .await; + } }, } } @@ -1182,11 +1071,8 @@ impl State { COST_UNEXPECTED_MESSAGE, ) .await; - gum::debug!(target: LOG_TARGET, "Received assignment for invalid block"); - metrics.on_assignment_recent_outdated(); } } - metrics.on_assignment_invalid_block(); return }, }; @@ -1219,7 +1105,6 @@ impl State { COST_DUPLICATE_MESSAGE, ) .await; - metrics.on_assignment_duplicate(); } else { gum::trace!( target: LOG_TARGET, @@ -1247,7 +1132,6 @@ impl State { COST_UNEXPECTED_MESSAGE, ) .await; - metrics.on_assignment_out_of_view(); }, } @@ -1264,7 +1148,6 @@ impl State { gum::trace!(target: LOG_TARGET, ?peer_id, ?message_subject, "Known assignment"); peer_knowledge.received.insert(message_subject, message_kind); } - metrics.on_assignment_good_known(); return } @@ -1321,8 +1204,6 @@ impl State { ?peer_id, "Got an `AcceptedDuplicate` assignment", ); - metrics.on_assignment_duplicatevoting(); - return }, AssignmentCheckResult::TooFarInFuture => { @@ -1339,8 +1220,6 @@ impl State { COST_ASSIGNMENT_TOO_FAR_IN_THE_FUTURE, ) .await; - metrics.on_assignment_far(); - return }, AssignmentCheckResult::Bad(error) => { @@ -1358,7 +1237,6 @@ impl State { COST_INVALID_MESSAGE, ) .await; - metrics.on_assignment_bad(); return }, } @@ -1397,12 +1275,7 @@ impl State { let approval_entry = entry.insert_approval_entry(ApprovalEntry::new( assignment.clone(), claimed_candidate_indices.clone(), - ApprovalRouting { - required_routing, - local, - random_routing: Default::default(), - peers_randomly_routed: Default::default(), - }, + ApprovalRouting { required_routing, local, random_routing: Default::default() }, )); // Dispatch the message to all peers in the routing set which @@ -1432,10 +1305,6 @@ impl State { continue } - if !topology.map(|topology| topology.is_validator(&peer)).unwrap_or(false) { - continue - } - // Note: at this point, we haven't received the message from any peers // other than the source peer, and we just got it, so we haven't sent it // to any peers either. @@ -1443,7 +1312,7 @@ impl State { approval_entry.routing_info().random_routing.sample(n_peers_total, rng); if route_random { - approval_entry.routing_info_mut().mark_randomly_sent(peer); + approval_entry.routing_info_mut().random_routing.inc_sent(); peers.push(peer); } } @@ -1477,94 +1346,12 @@ impl State { } } - // Checks if an approval can be processed. - // Returns true if we can continue with processing the approval and false otherwise. - async fn check_approval_can_be_processed( - ctx: &mut Context, - assignments_knowledge_key: &Vec<(MessageSubject, MessageKind)>, - approval_knowledge_key: &(MessageSubject, MessageKind), - entry: &mut BlockEntry, - reputation: &mut ReputationAggregator, - peer_id: PeerId, - metrics: &Metrics, - ) -> bool { - for message_subject in assignments_knowledge_key { - if !entry.knowledge.contains(&message_subject.0, message_subject.1) { - gum::trace!( - target: LOG_TARGET, - ?peer_id, - ?message_subject, - "Unknown approval assignment", - ); - modify_reputation(reputation, ctx.sender(), peer_id, COST_UNEXPECTED_MESSAGE).await; - metrics.on_approval_unknown_assignment(); - return false - } - } - - // check if our knowledge of the peer already contains this approval - match entry.known_by.entry(peer_id) { - hash_map::Entry::Occupied(mut knowledge) => { - let peer_knowledge = knowledge.get_mut(); - if peer_knowledge.contains(&approval_knowledge_key.0, approval_knowledge_key.1) { - if !peer_knowledge - .received - .insert(approval_knowledge_key.0.clone(), approval_knowledge_key.1) - { - gum::trace!( - target: LOG_TARGET, - ?peer_id, - ?approval_knowledge_key, - "Duplicate approval", - ); - - modify_reputation( - reputation, - ctx.sender(), - peer_id, - COST_DUPLICATE_MESSAGE, - ) - .await; - metrics.on_approval_duplicate(); - } - return false - } - }, - hash_map::Entry::Vacant(_) => { - gum::debug!( - target: LOG_TARGET, - ?peer_id, - ?approval_knowledge_key, - "Approval from a peer is out of view", - ); - modify_reputation(reputation, ctx.sender(), peer_id, COST_UNEXPECTED_MESSAGE).await; - metrics.on_approval_out_of_view(); - }, - } - - if entry.knowledge.contains(&approval_knowledge_key.0, approval_knowledge_key.1) { - if let Some(peer_knowledge) = entry.known_by.get_mut(&peer_id) { - peer_knowledge - .received - .insert(approval_knowledge_key.0.clone(), approval_knowledge_key.1); - } - - // We already processed this approval no need to continue. - gum::trace!(target: LOG_TARGET, ?peer_id, ?approval_knowledge_key, "Known approval"); - metrics.on_approval_good_known(); - modify_reputation(reputation, ctx.sender(), peer_id, BENEFIT_VALID_MESSAGE).await; - false - } else { - true - } - } - async fn import_and_circulate_approval( &mut self, ctx: &mut Context, metrics: &Metrics, source: MessageSource, - vote: IndirectSignedApprovalVoteV2, + vote: IndirectSignedApprovalVote, ) { let _span = self .spans @@ -1583,9 +1370,10 @@ impl State { let block_hash = vote.block_hash; let validator_index = vote.validator; - let candidate_indices = &vote.candidate_indices; + let candidate_index = vote.candidate_index; + let entry = match self.blocks.get_mut(&block_hash) { - Some(entry) if entry.contains_candidates(&vote.candidate_indices) => entry, + Some(entry) if entry.candidates.get(candidate_index as usize).is_some() => entry, _ => { if let Some(peer_id) = source.peer_id() { if !self.recent_outdated_blocks.is_recent_outdated(&block_hash) { @@ -1594,7 +1382,7 @@ impl State { ?peer_id, ?block_hash, ?validator_index, - ?candidate_indices, + ?candidate_index, "Approval from a peer is out of view", ); modify_reputation( @@ -1604,9 +1392,6 @@ impl State { COST_UNEXPECTED_MESSAGE, ) .await; - metrics.on_approval_invalid_block(); - } else { - metrics.on_approval_recent_outdated(); } } return @@ -1614,21 +1399,81 @@ impl State { }; // compute metadata on the assignment. - let assignments_knowledge_keys = PeerKnowledge::generate_assignments_keys(&vote); - let approval_knwowledge_key = PeerKnowledge::generate_approval_key(&vote); + let message_subject = MessageSubject(block_hash, candidate_index.into(), validator_index); + let message_kind = MessageKind::Approval; if let Some(peer_id) = source.peer_id() { - if !Self::check_approval_can_be_processed( - ctx, - &assignments_knowledge_keys, - &approval_knwowledge_key, - entry, - &mut self.reputation, - peer_id, - metrics, - ) - .await - { + if !entry.knowledge.contains(&message_subject, MessageKind::Assignment) { + gum::debug!( + target: LOG_TARGET, + ?peer_id, + ?message_subject, + "Unknown approval assignment", + ); + modify_reputation( + &mut self.reputation, + ctx.sender(), + peer_id, + COST_UNEXPECTED_MESSAGE, + ) + .await; + return + } + + // check if our knowledge of the peer already contains this approval + match entry.known_by.entry(peer_id) { + hash_map::Entry::Occupied(mut knowledge) => { + let peer_knowledge = knowledge.get_mut(); + if peer_knowledge.contains(&message_subject, message_kind) { + if !peer_knowledge.received.insert(message_subject.clone(), message_kind) { + gum::debug!( + target: LOG_TARGET, + ?peer_id, + ?message_subject, + "Duplicate approval", + ); + + modify_reputation( + &mut self.reputation, + ctx.sender(), + peer_id, + COST_DUPLICATE_MESSAGE, + ) + .await; + } + return + } + }, + hash_map::Entry::Vacant(_) => { + gum::debug!( + target: LOG_TARGET, + ?peer_id, + ?message_subject, + "Approval from a peer is out of view", + ); + modify_reputation( + &mut self.reputation, + ctx.sender(), + peer_id, + COST_UNEXPECTED_MESSAGE, + ) + .await; + }, + } + + // if the approval is known to be valid, reward the peer + if entry.knowledge.contains(&message_subject, message_kind) { + gum::trace!(target: LOG_TARGET, ?peer_id, ?message_subject, "Known approval"); + modify_reputation( + &mut self.reputation, + ctx.sender(), + peer_id, + BENEFIT_VALID_MESSAGE, + ) + .await; + if let Some(peer_knowledge) = entry.known_by.get_mut(&peer_id) { + peer_knowledge.received.insert(message_subject.clone(), message_kind); + } return } @@ -1650,8 +1495,8 @@ impl State { gum::trace!( target: LOG_TARGET, ?peer_id, + ?message_subject, ?result, - ?vote, "Checked approval", ); match result { @@ -1664,13 +1509,9 @@ impl State { ) .await; - entry - .knowledge - .insert(approval_knwowledge_key.0.clone(), approval_knwowledge_key.1); + entry.knowledge.insert(message_subject.clone(), message_kind); if let Some(peer_knowledge) = entry.known_by.get_mut(&peer_id) { - peer_knowledge - .received - .insert(approval_knwowledge_key.0.clone(), approval_knwowledge_key.1); + peer_knowledge.received.insert(message_subject.clone(), message_kind); } }, ApprovalCheckResult::Bad(error) => { @@ -1687,55 +1528,74 @@ impl State { %error, "Got a bad approval from peer", ); - metrics.on_approval_bad(); return }, } } else { - if !entry - .knowledge - .insert(approval_knwowledge_key.0.clone(), approval_knwowledge_key.1) - { - // if we already imported all approvals, there is no need to distribute it again + if !entry.knowledge.insert(message_subject.clone(), message_kind) { + // if we already imported an approval, there is no need to distribute it again gum::warn!( target: LOG_TARGET, + ?message_subject, "Importing locally an already known approval", ); return } else { gum::debug!( target: LOG_TARGET, + ?message_subject, "Importing locally a new approval", ); } } - let (required_routing, peers_randomly_routed_to) = match entry.note_approval(vote.clone()) { - Ok(required_routing) => required_routing, - Err(err) => { + let required_routing = match entry.approval_entry(candidate_index, validator_index) { + Some(approval_entry) => { + // Invariant: to our knowledge, none of the peers except for the `source` know about + // the approval. + metrics.on_approval_imported(); + + if let Err(err) = approval_entry.note_approval(vote.clone()) { + // this would indicate a bug in approval-voting: + // - validator index mismatch + // - candidate index mismatch + // - duplicate approval + gum::warn!( + target: LOG_TARGET, + hash = ?block_hash, + ?candidate_index, + ?validator_index, + ?err, + "Possible bug: Vote import failed", + ); + + return + } + + approval_entry.routing_info().required_routing + }, + None => { + let peer_id = source.peer_id(); + // This indicates a bug in approval-distribution, since we check the knowledge at + // the begining of the function. gum::warn!( target: LOG_TARGET, - hash = ?block_hash, - validator_index = ?vote.validator, - candidate_bitfield = ?vote.candidate_indices, - ?err, - "Possible bug: Vote import failed", + ?peer_id, + ?message_subject, + "Unknown approval assignment", ); - metrics.on_approval_bug(); + // No rep change as this is caused by an issue return }, }; - // Invariant: to our knowledge, none of the peers except for the `source` know about the - // approval. - metrics.on_approval_imported(); - // Dispatch a ApprovalDistributionV1Message::Approval(vote) // to all peers required by the topology, with the exception of the source peer. let topology = self.topologies.get_topology(entry.session); let source_peer = source.peer_id(); - let peer_filter = move |peer| { + let message_subject = &message_subject; + let peer_filter = move |peer, knowledge: &PeerKnowledge| { if Some(peer) == source_peer.as_ref() { return false } @@ -1751,13 +1611,13 @@ impl State { // 3. Any randomly selected peers have been sent the assignment already. let in_topology = topology .map_or(false, |t| t.local_grid_neighbors().route_to_peer(required_routing, peer)); - in_topology || peers_randomly_routed_to.contains(peer) + in_topology || knowledge.sent.contains(message_subject, MessageKind::Assignment) }; let peers = entry .known_by .iter() - .filter(|(p, _)| peer_filter(p)) + .filter(|(p, k)| peer_filter(p, k)) .filter_map(|(p, _)| self.peer_views.get(p).map(|entry| (*p, entry.version))) .collect::>(); @@ -1765,7 +1625,7 @@ impl State { for peer in peers.iter() { // we already filtered peers above, so this should always be Some if let Some(entry) = entry.known_by.get_mut(&peer.0) { - entry.sent.insert(approval_knwowledge_key.0.clone(), approval_knwowledge_key.1); + entry.sent.insert(message_subject.clone(), message_kind); } } @@ -1774,6 +1634,7 @@ impl State { gum::trace!( target: LOG_TARGET, ?block_hash, + ?candidate_index, local = source.peer_id().is_none(), num_peers = peers.len(), "Sending an approval to peers", @@ -1786,7 +1647,7 @@ impl State { fn get_approval_signatures( &mut self, indices: HashSet<(Hash, CandidateIndex)>, - ) -> HashMap, ValidatorSignature)> { + ) -> HashMap { let mut all_sigs = HashMap::new(); for (hash, index) in indices { let _span = self @@ -1809,20 +1670,11 @@ impl State { Some(e) => e, }; - let sigs = block_entry.approval_votes(index).into_iter().map(|approval| { - ( - approval.validator, - ( - hash, - approval - .candidate_indices - .iter_ones() - .map(|val| val as CandidateIndex) - .collect_vec(), - approval.signature, - ), - ) - }); + let sigs = block_entry + .approval_entries(index) + .into_iter() + .filter_map(|approval_entry| approval_entry.approval(index)) + .map(|approval| (approval.validator, approval.signature)); all_sigs.extend(sigs); } all_sigs @@ -1866,31 +1718,23 @@ impl State { let peer_knowledge = entry.known_by.entry(peer_id).or_default(); let topology = topologies.get_topology(entry.session); - // We want to iterate the `approval_entries` of the block entry as these contain - // all assignments that also link all approval votes. + // We want to iterate the `approval_entries` of the block entry as these contain all + // assignments that also link all approval votes. for approval_entry in entry.approval_entries.values_mut() { // Propagate the message to all peers in the required routing set OR // randomly sample peers. { let required_routing = approval_entry.routing_info().required_routing; - let routing_info = &mut approval_entry.routing_info_mut(); + let random_routing = &mut approval_entry.routing_info_mut().random_routing; let rng = &mut *rng; let mut peer_filter = move |peer_id| { let in_topology = topology.as_ref().map_or(false, |t| { t.local_grid_neighbors().route_to_peer(required_routing, peer_id) }); in_topology || { - if !topology - .map(|topology| topology.is_validator(peer_id)) - .unwrap_or(false) - { - return false - } - - let route_random = - routing_info.random_routing.sample(total_peers, rng); + let route_random = random_routing.sample(total_peers, rng); if route_random { - routing_info.mark_randomly_sent(*peer_id); + random_routing.inc_sent(); } route_random @@ -1907,8 +1751,7 @@ impl State { let (assignment_knowledge, message_kind) = approval_entry.create_assignment_knowledge(block); - // Only send stuff a peer doesn't know in the context of a relay chain - // block. + // Only send stuff a peer doesn't know in the context of a relay chain block. if !peer_knowledge.contains(&assignment_knowledge, message_kind) { peer_knowledge.sent.insert(assignment_knowledge, message_kind); assignments_to_send.push(assignment_message); @@ -1916,12 +1759,12 @@ impl State { // Filter approval votes. for approval_message in approval_messages { - let approval_knowledge = - PeerKnowledge::generate_approval_key(&approval_message); + let (approval_knowledge, message_kind) = approval_entry + .create_approval_knowledge(block, approval_message.candidate_index); - if !peer_knowledge.contains(&approval_knowledge.0, approval_knowledge.1) { + if !peer_knowledge.contains(&approval_knowledge, message_kind) { + peer_knowledge.sent.insert(approval_knowledge, message_kind); approvals_to_send.push(approval_message); - peer_knowledge.sent.insert(approval_knowledge.0, approval_knowledge.1); } } } @@ -2094,7 +1937,6 @@ impl State { // Punish the peer for the invalid message. modify_reputation(&mut self.reputation, sender, peer_id, COST_OVERSIZED_BITFIELD) .await; - gum::error!(target: LOG_TARGET, block_hash = ?cert.block_hash, ?candidate_index, validator_index = ?cert.validator, kind = ?cert.cert.kind, "Bad assignment v1"); } else { sanitized_assignments.push((cert.into(), candidate_index.into())) } @@ -2137,9 +1979,6 @@ impl State { // Punish the peer for the invalid message. modify_reputation(&mut self.reputation, sender, peer_id, COST_OVERSIZED_BITFIELD) .await; - for candidate_index in candidate_bitfield.iter_ones() { - gum::error!(target: LOG_TARGET, block_hash = ?cert.block_hash, ?candidate_index, validator_index = ?cert.validator, "Bad assignment v2"); - } } else { sanitized_assignments.push((cert, candidate_bitfield)) } @@ -2227,10 +2066,11 @@ async fn adjust_required_routing_and_propagate { gum::debug!( target: LOG_TARGET, - "Distributing our approval vote on candidate (block={}, index={:?})", + "Distributing our approval vote on candidate (block={}, index={})", vote.block_hash, - vote.candidate_indices, + vote.candidate_index, ); state @@ -2456,7 +2296,7 @@ pub const MAX_ASSIGNMENT_BATCH_SIZE: usize = ensure_size_not_zero( /// The maximum amount of approvals per batch is 33% of maximum allowed by protocol. pub const MAX_APPROVAL_BATCH_SIZE: usize = ensure_size_not_zero( - MAX_NOTIFICATION_SIZE as usize / std::mem::size_of::() / 3, + MAX_NOTIFICATION_SIZE as usize / std::mem::size_of::() / 3, ); // Low level helper for sending assignments. @@ -2466,12 +2306,12 @@ async fn send_assignments_batched_inner( peers: Vec, peer_version: ValidationVersion, ) { - if peer_version == ValidationVersion::V3 { + if peer_version == ValidationVersion::VStaging { sender .send_message(NetworkBridgeTxMessage::SendValidationMessage( peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Assignments( + Versioned::VStaging(protocol_vstaging::ValidationProtocol::ApprovalDistribution( + protocol_vstaging::ApprovalDistributionMessage::Assignments( batch.into_iter().collect(), ), )), @@ -2522,7 +2362,7 @@ pub(crate) async fn send_assignments_batched( ) { let v1_peers = filter_by_peer_version(peers, ValidationVersion::V1.into()); let v2_peers = filter_by_peer_version(peers, ValidationVersion::V2.into()); - let v3_peers = filter_by_peer_version(peers, ValidationVersion::V3.into()); + let vstaging_peers = filter_by_peer_version(peers, ValidationVersion::VStaging.into()); // V1 and V2 validation protocol do not have any changes with regard to // ApprovalDistributionMessage so they can be treated the same. @@ -2560,13 +2400,18 @@ pub(crate) async fn send_assignments_batched( } } - if !v3_peers.is_empty() { - let mut v3 = v2_assignments.into_iter().peekable(); + if !vstaging_peers.is_empty() { + let mut vstaging = v2_assignments.into_iter().peekable(); - while v3.peek().is_some() { - let batch = v3.by_ref().take(MAX_ASSIGNMENT_BATCH_SIZE).collect::>(); - send_assignments_batched_inner(sender, batch, v3_peers.clone(), ValidationVersion::V3) - .await; + while vstaging.peek().is_some() { + let batch = vstaging.by_ref().take(MAX_ASSIGNMENT_BATCH_SIZE).collect::>(); + send_assignments_batched_inner( + sender, + batch, + vstaging_peers.clone(), + ValidationVersion::VStaging, + ) + .await; } } } @@ -2574,20 +2419,15 @@ pub(crate) async fn send_assignments_batched( /// Send approvals while honoring the `max_notification_size` of the protocol and peer version. pub(crate) async fn send_approvals_batched( sender: &mut impl overseer::ApprovalDistributionSenderTrait, - approvals: impl IntoIterator + Clone, + approvals: impl IntoIterator + Clone, peers: &[(PeerId, ProtocolVersion)], ) { let v1_peers = filter_by_peer_version(peers, ValidationVersion::V1.into()); let v2_peers = filter_by_peer_version(peers, ValidationVersion::V2.into()); - let v3_peers = filter_by_peer_version(peers, ValidationVersion::V3.into()); + let vstaging_peers = filter_by_peer_version(peers, ValidationVersion::VStaging.into()); if !v1_peers.is_empty() || !v2_peers.is_empty() { - let mut batches = approvals - .clone() - .into_iter() - .filter(|approval| approval.candidate_indices.count_ones() == 1) - .filter_map(|val| val.try_into().ok()) - .peekable(); + let mut batches = approvals.clone().into_iter().peekable(); while batches.peek().is_some() { let batch: Vec<_> = batches.by_ref().take(MAX_APPROVAL_BATCH_SIZE).collect(); @@ -2616,7 +2456,7 @@ pub(crate) async fn send_approvals_batched( } } - if !v3_peers.is_empty() { + if !vstaging_peers.is_empty() { let mut batches = approvals.into_iter().peekable(); while batches.peek().is_some() { @@ -2624,10 +2464,12 @@ pub(crate) async fn send_approvals_batched( sender .send_message(NetworkBridgeTxMessage::SendValidationMessage( - v3_peers.clone(), - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Approvals(batch), - )), + vstaging_peers.clone(), + Versioned::VStaging( + protocol_vstaging::ValidationProtocol::ApprovalDistribution( + protocol_vstaging::ApprovalDistributionMessage::Approvals(batch), + ), + ), )) .await; } diff --git a/polkadot/node/network/approval-distribution/src/metrics.rs b/polkadot/node/network/approval-distribution/src/metrics.rs index 0642b1b2e0c..6864259e6fd 100644 --- a/polkadot/node/network/approval-distribution/src/metrics.rs +++ b/polkadot/node/network/approval-distribution/src/metrics.rs @@ -31,8 +31,6 @@ struct MetricsInner { time_unify_with_peer: prometheus::Histogram, time_import_pending_now_known: prometheus::Histogram, time_awaiting_approval_voting: prometheus::Histogram, - assignments_received_result: prometheus::CounterVec, - approvals_received_result: prometheus::CounterVec, } trait AsLabel { @@ -80,132 +78,6 @@ impl Metrics { .map(|metrics| metrics.time_import_pending_now_known.start_timer()) } - pub fn on_approval_already_known(&self) { - if let Some(metrics) = &self.0 { - metrics.approvals_received_result.with_label_values(&["known"]).inc() - } - } - - pub fn on_approval_entry_not_found(&self) { - if let Some(metrics) = &self.0 { - metrics.approvals_received_result.with_label_values(&["noapprovalentry"]).inc() - } - } - - pub fn on_approval_recent_outdated(&self) { - if let Some(metrics) = &self.0 { - metrics.approvals_received_result.with_label_values(&["outdated"]).inc() - } - } - - pub fn on_approval_invalid_block(&self) { - if let Some(metrics) = &self.0 { - metrics.approvals_received_result.with_label_values(&["invalidblock"]).inc() - } - } - - pub fn on_approval_unknown_assignment(&self) { - if let Some(metrics) = &self.0 { - metrics - .approvals_received_result - .with_label_values(&["unknownassignment"]) - .inc() - } - } - - pub fn on_approval_duplicate(&self) { - if let Some(metrics) = &self.0 { - metrics.approvals_received_result.with_label_values(&["duplicate"]).inc() - } - } - - pub fn on_approval_out_of_view(&self) { - if let Some(metrics) = &self.0 { - metrics.approvals_received_result.with_label_values(&["outofview"]).inc() - } - } - - pub fn on_approval_good_known(&self) { - if let Some(metrics) = &self.0 { - metrics.approvals_received_result.with_label_values(&["goodknown"]).inc() - } - } - - pub fn on_approval_bad(&self) { - if let Some(metrics) = &self.0 { - metrics.approvals_received_result.with_label_values(&["bad"]).inc() - } - } - - pub fn on_approval_unexpected(&self) { - if let Some(metrics) = &self.0 { - metrics.approvals_received_result.with_label_values(&["unexpected"]).inc() - } - } - - pub fn on_approval_bug(&self) { - if let Some(metrics) = &self.0 { - metrics.approvals_received_result.with_label_values(&["bug"]).inc() - } - } - - pub fn on_assignment_already_known(&self) { - if let Some(metrics) = &self.0 { - metrics.assignments_received_result.with_label_values(&["known"]).inc() - } - } - - pub fn on_assignment_recent_outdated(&self) { - if let Some(metrics) = &self.0 { - metrics.assignments_received_result.with_label_values(&["outdated"]).inc() - } - } - - pub fn on_assignment_invalid_block(&self) { - if let Some(metrics) = &self.0 { - metrics.assignments_received_result.with_label_values(&["invalidblock"]).inc() - } - } - - pub fn on_assignment_duplicate(&self) { - if let Some(metrics) = &self.0 { - metrics.assignments_received_result.with_label_values(&["duplicate"]).inc() - } - } - - pub fn on_assignment_out_of_view(&self) { - if let Some(metrics) = &self.0 { - metrics.assignments_received_result.with_label_values(&["outofview"]).inc() - } - } - - pub fn on_assignment_good_known(&self) { - if let Some(metrics) = &self.0 { - metrics.assignments_received_result.with_label_values(&["goodknown"]).inc() - } - } - - pub fn on_assignment_bad(&self) { - if let Some(metrics) = &self.0 { - metrics.assignments_received_result.with_label_values(&["bad"]).inc() - } - } - - pub fn on_assignment_duplicatevoting(&self) { - if let Some(metrics) = &self.0 { - metrics - .assignments_received_result - .with_label_values(&["duplicatevoting"]) - .inc() - } - } - - pub fn on_assignment_far(&self) { - if let Some(metrics) = &self.0 { - metrics.assignments_received_result.with_label_values(&["far"]).inc() - } - } - pub(crate) fn time_awaiting_approval_voting( &self, ) -> Option { @@ -295,26 +167,6 @@ impl MetricsTrait for Metrics { ).buckets(vec![0.0001, 0.0004, 0.0016, 0.0064, 0.0256, 0.1024, 0.4096, 1.6384, 3.2768, 4.9152, 6.5536,]))?, registry, )?, - assignments_received_result: prometheus::register( - prometheus::CounterVec::new( - prometheus::Opts::new( - "polkadot_parachain_assignments_received_result", - "Result of a processed assignement", - ), - &["status"] - )?, - registry, - )?, - approvals_received_result: prometheus::register( - prometheus::CounterVec::new( - prometheus::Opts::new( - "polkadot_parachain_approvals_received_result", - "Result of a processed approval", - ), - &["status"] - )?, - registry, - )?, }; Ok(Metrics(Some(metrics))) } diff --git a/polkadot/node/network/approval-distribution/src/tests.rs b/polkadot/node/network/approval-distribution/src/tests.rs index ad5d0bb0a9c..33c38c7c5df 100644 --- a/polkadot/node/network/approval-distribution/src/tests.rs +++ b/polkadot/node/network/approval-distribution/src/tests.rs @@ -25,8 +25,8 @@ use polkadot_node_network_protocol::{ }; use polkadot_node_primitives::approval::{ v1::{ - AssignmentCert, AssignmentCertKind, IndirectAssignmentCert, IndirectSignedApprovalVote, - VrfPreOutput, VrfProof, VrfSignature, + AssignmentCert, AssignmentCertKind, IndirectAssignmentCert, VrfOutput, VrfProof, + VrfSignature, }, v2::{ AssignmentCertKindV2, AssignmentCertV2, CoreBitfield, IndirectAssignmentCertV2, @@ -133,13 +133,14 @@ fn make_gossip_topology( all_peers: &[(PeerId, AuthorityDiscoveryId)], neighbors_x: &[usize], neighbors_y: &[usize], - local_index: usize, ) -> network_bridge_event::NewGossipTopology { // This builds a grid topology which is a square matrix. // The local validator occupies the top left-hand corner. // The X peers occupy the same row and the Y peers occupy // the same column. + let local_index = 1; + assert_eq!( neighbors_x.len(), neighbors_y.len(), @@ -276,16 +277,16 @@ async fn send_message_from_peer_v2( .await; } -async fn send_message_from_peer_v3( +async fn send_message_from_peer_vstaging( virtual_overseer: &mut VirtualOverseer, peer_id: &PeerId, - msg: protocol_v3::ApprovalDistributionMessage, + msg: protocol_vstaging::ApprovalDistributionMessage, ) { overseer_send( virtual_overseer, ApprovalDistributionMessage::NetworkBridgeUpdate(NetworkBridgeEvent::PeerMessage( *peer_id, - Versioned::V3(msg), + Versioned::VStaging(msg), )), ) .await; @@ -297,14 +298,14 @@ fn fake_assignment_cert(block_hash: Hash, validator: ValidatorIndex) -> Indirect let mut prng = rand_core::OsRng; let keypair = schnorrkel::Keypair::generate_with(&mut prng); let (inout, proof, _) = keypair.vrf_sign(ctx.bytes(msg)); - let preout = inout.to_output(); + let out = inout.to_output(); IndirectAssignmentCert { block_hash, validator, cert: AssignmentCert { kind: AssignmentCertKind::RelayVRFModulo { sample: 1 }, - vrf: VrfSignature { pre_output: VrfPreOutput(preout), proof: VrfProof(proof) }, + vrf: VrfSignature { output: VrfOutput(out), proof: VrfProof(proof) }, }, } } @@ -319,14 +320,14 @@ fn fake_assignment_cert_v2( let mut prng = rand_core::OsRng; let keypair = schnorrkel::Keypair::generate_with(&mut prng); let (inout, proof, _) = keypair.vrf_sign(ctx.bytes(msg)); - let preout = inout.to_output(); + let out = inout.to_output(); IndirectAssignmentCertV2 { block_hash, validator, cert: AssignmentCertV2 { kind: AssignmentCertKindV2::RelayVRFModuloCompact { core_bitfield }, - vrf: VrfSignature { pre_output: VrfPreOutput(preout), proof: VrfProof(proof) }, + vrf: VrfSignature { output: VrfOutput(out), proof: VrfProof(proof) }, }, } } @@ -379,11 +380,10 @@ fn state_with_reputation_delay() -> State { /// the new peer sends us the same assignment #[test] fn try_import_the_same_assignment() { - let peers = make_peers_and_authority_ids(15); - let peer_a = peers.get(0).unwrap().0; - let peer_b = peers.get(1).unwrap().0; - let peer_c = peers.get(2).unwrap().0; - let peer_d = peers.get(4).unwrap().0; + let peer_a = PeerId::random(); + let peer_b = PeerId::random(); + let peer_c = PeerId::random(); + let peer_d = PeerId::random(); let parent_hash = Hash::repeat_byte(0xFF); let hash = Hash::repeat_byte(0xAA); @@ -394,10 +394,6 @@ fn try_import_the_same_assignment() { setup_peer_with_view(overseer, &peer_b, view![hash], ValidationVersion::V1).await; setup_peer_with_view(overseer, &peer_c, view![hash], ValidationVersion::V1).await; - // Set up a gossip topology, where a, b, c and d are topology neighboors to the node under - // testing. - setup_gossip_topology(overseer, make_gossip_topology(1, &peers, &[0, 1], &[2, 4], 3)).await; - // new block `hash_a` with 1 candidates let meta = BlockApprovalMeta { hash, @@ -450,7 +446,7 @@ fn try_import_the_same_assignment() { ); // setup new peer with V2 - setup_peer_with_view(overseer, &peer_d, view![], ValidationVersion::V3).await; + setup_peer_with_view(overseer, &peer_d, view![], ValidationVersion::VStaging).await; // send the same assignment from peer_d let msg = protocol_v1::ApprovalDistributionMessage::Assignments(assignments); @@ -468,24 +464,19 @@ fn try_import_the_same_assignment() { /// cores. #[test] fn try_import_the_same_assignment_v2() { - let peers = make_peers_and_authority_ids(15); - let peer_a = peers.get(0).unwrap().0; - let peer_b = peers.get(1).unwrap().0; - let peer_c = peers.get(2).unwrap().0; - let peer_d = peers.get(4).unwrap().0; + let peer_a = PeerId::random(); + let peer_b = PeerId::random(); + let peer_c = PeerId::random(); + let peer_d = PeerId::random(); let parent_hash = Hash::repeat_byte(0xFF); let hash = Hash::repeat_byte(0xAA); let _ = test_harness(state_without_reputation_delay(), |mut virtual_overseer| async move { let overseer = &mut virtual_overseer; // setup peers - setup_peer_with_view(overseer, &peer_a, view![], ValidationVersion::V3).await; - setup_peer_with_view(overseer, &peer_b, view![hash], ValidationVersion::V3).await; - setup_peer_with_view(overseer, &peer_c, view![hash], ValidationVersion::V3).await; - - // Set up a gossip topology, where a, b, c and d are topology neighboors to the node under - // testing. - setup_gossip_topology(overseer, make_gossip_topology(1, &peers, &[0, 1], &[2, 4], 3)).await; + setup_peer_with_view(overseer, &peer_a, view![], ValidationVersion::VStaging).await; + setup_peer_with_view(overseer, &peer_b, view![hash], ValidationVersion::VStaging).await; + setup_peer_with_view(overseer, &peer_c, view![hash], ValidationVersion::VStaging).await; // new block `hash_a` with 1 candidates let meta = BlockApprovalMeta { @@ -512,8 +503,8 @@ fn try_import_the_same_assignment_v2() { let cert = fake_assignment_cert_v2(hash, validator_index, core_bitfield.clone()); let assignments = vec![(cert.clone(), cores.clone().try_into().unwrap())]; - let msg = protocol_v3::ApprovalDistributionMessage::Assignments(assignments.clone()); - send_message_from_peer_v3(overseer, &peer_a, msg).await; + let msg = protocol_vstaging::ApprovalDistributionMessage::Assignments(assignments.clone()); + send_message_from_peer_vstaging(overseer, &peer_a, msg).await; expect_reputation_change(overseer, &peer_a, COST_UNEXPECTED_MESSAGE).await; @@ -537,8 +528,8 @@ fn try_import_the_same_assignment_v2() { overseer_recv(overseer).await, AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Assignments(assignments) + Versioned::VStaging(protocol_vstaging::ValidationProtocol::ApprovalDistribution( + protocol_vstaging::ApprovalDistributionMessage::Assignments(assignments) )) )) => { assert_eq!(peers.len(), 2); @@ -547,11 +538,11 @@ fn try_import_the_same_assignment_v2() { ); // setup new peer - setup_peer_with_view(overseer, &peer_d, view![], ValidationVersion::V3).await; + setup_peer_with_view(overseer, &peer_d, view![], ValidationVersion::VStaging).await; // send the same assignment from peer_d - let msg = protocol_v3::ApprovalDistributionMessage::Assignments(assignments); - send_message_from_peer_v3(overseer, &peer_d, msg).await; + let msg = protocol_vstaging::ApprovalDistributionMessage::Assignments(assignments); + send_message_from_peer_vstaging(overseer, &peer_d, msg).await; expect_reputation_change(overseer, &peer_d, COST_UNEXPECTED_MESSAGE).await; expect_reputation_change(overseer, &peer_d, BENEFIT_VALID_MESSAGE).await; @@ -714,19 +705,14 @@ fn spam_attack_results_in_negative_reputation_change() { #[test] fn peer_sending_us_the_same_we_just_sent_them_is_ok() { let parent_hash = Hash::repeat_byte(0xFF); + let peer_a = PeerId::random(); let hash = Hash::repeat_byte(0xAA); - let peers = make_peers_and_authority_ids(8); - let peer_a = peers.first().unwrap().0; - let _ = test_harness(state_without_reputation_delay(), |mut virtual_overseer| async move { let overseer = &mut virtual_overseer; let peer = &peer_a; setup_peer_with_view(overseer, peer, view![], ValidationVersion::V1).await; - // Setup a topology where peer_a is neigboor to current node. - setup_gossip_topology(overseer, make_gossip_topology(1, &peers, &[0], &[2], 1)).await; - // new block `hash` with 1 candidates let meta = BlockApprovalMeta { hash, @@ -794,12 +780,10 @@ fn peer_sending_us_the_same_we_just_sent_them_is_ok() { } #[test] -fn import_approval_happy_path_v1_v2_peers() { - let peers = make_peers_and_authority_ids(15); - - let peer_a = peers.get(0).unwrap().0; - let peer_b = peers.get(1).unwrap().0; - let peer_c = peers.get(2).unwrap().0; +fn import_approval_happy_path() { + let peer_a = PeerId::random(); + let peer_b = PeerId::random(); + let peer_c = PeerId::random(); let parent_hash = Hash::repeat_byte(0xFF); let hash = Hash::repeat_byte(0xAA); @@ -807,7 +791,7 @@ fn import_approval_happy_path_v1_v2_peers() { let overseer = &mut virtual_overseer; // setup peers with V1 and V2 protocol versions setup_peer_with_view(overseer, &peer_a, view![], ValidationVersion::V1).await; - setup_peer_with_view(overseer, &peer_b, view![hash], ValidationVersion::V3).await; + setup_peer_with_view(overseer, &peer_b, view![hash], ValidationVersion::VStaging).await; setup_peer_with_view(overseer, &peer_c, view![hash], ValidationVersion::V1).await; // new block `hash_a` with 1 candidates @@ -822,9 +806,6 @@ fn import_approval_happy_path_v1_v2_peers() { let msg = ApprovalDistributionMessage::NewBlocks(vec![meta]); overseer_send(overseer, msg).await; - // Set up a gossip topology, where a, b, and c are topology neighboors to the node. - setup_gossip_topology(overseer, make_gossip_topology(1, &peers, &[0, 1], &[2, 4], 3)).await; - // import an assignment related to `hash` locally let validator_index = ValidatorIndex(0); let candidate_index = 0u32; @@ -857,8 +838,8 @@ fn import_approval_happy_path_v1_v2_peers() { overseer_recv(overseer).await, AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Assignments(assignments) + Versioned::VStaging(protocol_vstaging::ValidationProtocol::ApprovalDistribution( + protocol_vstaging::ApprovalDistributionMessage::Assignments(assignments) )) )) => { assert_eq!(peers.len(), 1); @@ -867,15 +848,14 @@ fn import_approval_happy_path_v1_v2_peers() { ); // send the an approval from peer_b - let approval = IndirectSignedApprovalVoteV2 { + let approval = IndirectSignedApprovalVote { block_hash: hash, - candidate_indices: candidate_index.into(), + candidate_index, validator: validator_index, signature: dummy_signature(), }; - let msg: protocol_v3::ApprovalDistributionMessage = - protocol_v3::ApprovalDistributionMessage::Approvals(vec![approval.clone()]); - send_message_from_peer_v3(overseer, &peer_b, msg).await; + let msg = protocol_v1::ApprovalDistributionMessage::Approvals(vec![approval.clone()]); + send_message_from_peer(overseer, &peer_b, msg).await; assert_matches!( overseer_recv(overseer).await, @@ -906,474 +886,6 @@ fn import_approval_happy_path_v1_v2_peers() { }); } -// Test a v2 approval that signs multiple candidate is correctly processed. -#[test] -fn import_approval_happy_path_v2() { - let peers = make_peers_and_authority_ids(15); - - let peer_a = peers.get(0).unwrap().0; - let peer_b = peers.get(1).unwrap().0; - let peer_c = peers.get(2).unwrap().0; - let parent_hash = Hash::repeat_byte(0xFF); - let hash = Hash::repeat_byte(0xAA); - - let _ = test_harness(state_without_reputation_delay(), |mut virtual_overseer| async move { - let overseer = &mut virtual_overseer; - // setup peers with V2 protocol versions - setup_peer_with_view(overseer, &peer_a, view![], ValidationVersion::V3).await; - setup_peer_with_view(overseer, &peer_b, view![hash], ValidationVersion::V3).await; - setup_peer_with_view(overseer, &peer_c, view![hash], ValidationVersion::V3).await; - - // new block `hash_a` with 1 candidates - let meta = BlockApprovalMeta { - hash, - parent_hash, - number: 1, - candidates: vec![Default::default(); 2], - slot: 1.into(), - session: 1, - }; - let msg = ApprovalDistributionMessage::NewBlocks(vec![meta]); - overseer_send(overseer, msg).await; - - // Set up a gossip topology, where a, b, and c are topology neighboors to the node. - setup_gossip_topology(overseer, make_gossip_topology(1, &peers, &[0, 1], &[2, 4], 3)).await; - - // import an assignment related to `hash` locally - let validator_index = ValidatorIndex(0); - let candidate_indices: CandidateBitfield = - vec![0 as CandidateIndex, 1 as CandidateIndex].try_into().unwrap(); - let candidate_bitfields = vec![CoreIndex(0), CoreIndex(1)].try_into().unwrap(); - let cert = fake_assignment_cert_v2(hash, validator_index, candidate_bitfields); - overseer_send( - overseer, - ApprovalDistributionMessage::DistributeAssignment( - cert.clone().into(), - candidate_indices.clone(), - ), - ) - .await; - - // 1 peer is v2 - assert_matches!( - overseer_recv(overseer).await, - AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( - peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Assignments(assignments) - )) - )) => { - assert_eq!(peers.len(), 2); - assert_eq!(assignments.len(), 1); - } - ); - - // send the an approval from peer_b - let approval = IndirectSignedApprovalVoteV2 { - block_hash: hash, - candidate_indices, - validator: validator_index, - signature: dummy_signature(), - }; - let msg = protocol_v3::ApprovalDistributionMessage::Approvals(vec![approval.clone()]); - send_message_from_peer_v3(overseer, &peer_b, msg).await; - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::ApprovalVoting(ApprovalVotingMessage::CheckAndImportApproval( - vote, - tx, - )) => { - assert_eq!(vote, approval); - tx.send(ApprovalCheckResult::Accepted).unwrap(); - } - ); - - expect_reputation_change(overseer, &peer_b, BENEFIT_VALID_MESSAGE_FIRST).await; - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( - peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Approvals(approvals) - )) - )) => { - assert_eq!(peers.len(), 1); - assert_eq!(approvals.len(), 1); - } - ); - virtual_overseer - }); -} - -// Tests that votes that cover multiple assignments candidates are correctly processed on importing -#[test] -fn multiple_assignments_covered_with_one_approval_vote() { - let peers = make_peers_and_authority_ids(15); - - let peer_a = peers.get(0).unwrap().0; - let peer_b = peers.get(1).unwrap().0; - let peer_c = peers.get(2).unwrap().0; - let peer_d = peers.get(4).unwrap().0; - let parent_hash = Hash::repeat_byte(0xFF); - let hash = Hash::repeat_byte(0xAA); - - let _ = test_harness(state_without_reputation_delay(), |mut virtual_overseer| async move { - let overseer = &mut virtual_overseer; - // setup peers with V2 protocol versions - setup_peer_with_view(overseer, &peer_a, view![hash], ValidationVersion::V3).await; - setup_peer_with_view(overseer, &peer_b, view![hash], ValidationVersion::V3).await; - setup_peer_with_view(overseer, &peer_c, view![hash], ValidationVersion::V3).await; - setup_peer_with_view(overseer, &peer_d, view![hash], ValidationVersion::V3).await; - - // new block `hash_a` with 1 candidates - let meta = BlockApprovalMeta { - hash, - parent_hash, - number: 1, - candidates: vec![Default::default(); 2], - slot: 1.into(), - session: 1, - }; - let msg = ApprovalDistributionMessage::NewBlocks(vec![meta]); - overseer_send(overseer, msg).await; - - // Set up a gossip topology, where a, b, and c, d are topology neighboors to the node. - setup_gossip_topology(overseer, make_gossip_topology(1, &peers, &[0, 1], &[2, 4], 3)).await; - - // import an assignment related to `hash` locally - let validator_index = ValidatorIndex(2); // peer_c is the originator - let candidate_indices: CandidateBitfield = - vec![0 as CandidateIndex, 1 as CandidateIndex].try_into().unwrap(); - - let core_bitfields = vec![CoreIndex(0)].try_into().unwrap(); - let cert = fake_assignment_cert_v2(hash, validator_index, core_bitfields); - - // send the candidate 0 assignment from peer_b - let assignment = IndirectAssignmentCertV2 { - block_hash: hash, - validator: validator_index, - cert: cert.cert, - }; - let msg = protocol_v3::ApprovalDistributionMessage::Assignments(vec![( - assignment, - (0 as CandidateIndex).into(), - )]); - send_message_from_peer_v3(overseer, &peer_d, msg).await; - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::ApprovalVoting(ApprovalVotingMessage::CheckAndImportAssignment( - _, _, - tx, - )) => { - tx.send(AssignmentCheckResult::Accepted).unwrap(); - } - ); - expect_reputation_change(overseer, &peer_d, BENEFIT_VALID_MESSAGE_FIRST).await; - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( - peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Assignments(assignments) - )) - )) => { - assert!(peers.len() >= 2); - assert!(peers.contains(&peer_a)); - assert!(peers.contains(&peer_b)); - assert_eq!(assignments.len(), 1); - } - ); - - let candidate_bitfields = vec![CoreIndex(1)].try_into().unwrap(); - let cert = fake_assignment_cert_v2(hash, validator_index, candidate_bitfields); - - // send the candidate 1 assignment from peer_c - let assignment = IndirectAssignmentCertV2 { - block_hash: hash, - validator: validator_index, - cert: cert.cert, - }; - let msg = protocol_v3::ApprovalDistributionMessage::Assignments(vec![( - assignment, - (1 as CandidateIndex).into(), - )]); - - send_message_from_peer_v3(overseer, &peer_c, msg).await; - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::ApprovalVoting(ApprovalVotingMessage::CheckAndImportAssignment( - _, _, - tx, - )) => { - tx.send(AssignmentCheckResult::Accepted).unwrap(); - } - ); - expect_reputation_change(overseer, &peer_c, BENEFIT_VALID_MESSAGE_FIRST).await; - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( - peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Assignments(assignments) - )) - )) => { - assert!(peers.len() >= 2); - assert!(peers.contains(&peer_b)); - assert!(peers.contains(&peer_a)); - assert_eq!(assignments.len(), 1); - } - ); - - // send an approval from peer_b - let approval = IndirectSignedApprovalVoteV2 { - block_hash: hash, - candidate_indices, - validator: validator_index, - signature: dummy_signature(), - }; - let msg = protocol_v3::ApprovalDistributionMessage::Approvals(vec![approval.clone()]); - send_message_from_peer_v3(overseer, &peer_d, msg).await; - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::ApprovalVoting(ApprovalVotingMessage::CheckAndImportApproval( - vote, - tx, - )) => { - assert_eq!(vote, approval); - tx.send(ApprovalCheckResult::Accepted).unwrap(); - } - ); - - expect_reputation_change(overseer, &peer_d, BENEFIT_VALID_MESSAGE_FIRST).await; - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( - peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Approvals(approvals) - )) - )) => { - assert!(peers.len() >= 2); - assert!(peers.contains(&peer_b)); - assert!(peers.contains(&peer_a)); - assert_eq!(approvals.len(), 1); - } - ); - for candidate_index in 0..1 { - let (tx_distribution, rx_distribution) = oneshot::channel(); - let mut candidates_requesting_signatures = HashSet::new(); - candidates_requesting_signatures.insert((hash, candidate_index)); - overseer_send( - overseer, - ApprovalDistributionMessage::GetApprovalSignatures( - candidates_requesting_signatures, - tx_distribution, - ), - ) - .await; - let signatures = rx_distribution.await.unwrap(); - - assert_eq!(signatures.len(), 1); - for (signing_validator, signature) in signatures { - assert_eq!(validator_index, signing_validator); - assert_eq!(signature.0, hash); - assert_eq!(signature.2, approval.signature); - assert_eq!(signature.1, vec![0, 1]); - } - } - virtual_overseer - }); -} - -// Tests that votes that cover multiple assignments candidates are correctly processed when unify -// with peer view -#[test] -fn unify_with_peer_multiple_assignments_covered_with_one_approval_vote() { - let peers = make_peers_and_authority_ids(15); - - let peer_a = peers.get(0).unwrap().0; - let peer_b = peers.get(1).unwrap().0; - let peer_d = peers.get(4).unwrap().0; - let parent_hash = Hash::repeat_byte(0xFF); - let hash = Hash::repeat_byte(0xAA); - - let _ = test_harness(state_without_reputation_delay(), |mut virtual_overseer| async move { - let overseer = &mut virtual_overseer; - setup_peer_with_view(overseer, &peer_d, view![hash], ValidationVersion::V3).await; - - // new block `hash_a` with 1 candidates - let meta = BlockApprovalMeta { - hash, - parent_hash, - number: 1, - candidates: vec![Default::default(); 2], - slot: 1.into(), - session: 1, - }; - let msg = ApprovalDistributionMessage::NewBlocks(vec![meta]); - overseer_send(overseer, msg).await; - - // Set up a gossip topology, where a, b, and c, d are topology neighboors to the node. - setup_gossip_topology(overseer, make_gossip_topology(1, &peers, &[0, 1], &[2, 4], 3)).await; - - // import an assignment related to `hash` locally - let validator_index = ValidatorIndex(2); // peer_c is the originator - let candidate_indices: CandidateBitfield = - vec![0 as CandidateIndex, 1 as CandidateIndex].try_into().unwrap(); - - let core_bitfields = vec![CoreIndex(0)].try_into().unwrap(); - let cert = fake_assignment_cert_v2(hash, validator_index, core_bitfields); - - // send the candidate 0 assignment from peer_b - let assignment = IndirectAssignmentCertV2 { - block_hash: hash, - validator: validator_index, - cert: cert.cert, - }; - let msg = protocol_v3::ApprovalDistributionMessage::Assignments(vec![( - assignment, - (0 as CandidateIndex).into(), - )]); - send_message_from_peer_v3(overseer, &peer_d, msg).await; - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::ApprovalVoting(ApprovalVotingMessage::CheckAndImportAssignment( - _, _, - tx, - )) => { - tx.send(AssignmentCheckResult::Accepted).unwrap(); - } - ); - expect_reputation_change(overseer, &peer_d, BENEFIT_VALID_MESSAGE_FIRST).await; - - let candidate_bitfields = vec![CoreIndex(1)].try_into().unwrap(); - let cert = fake_assignment_cert_v2(hash, validator_index, candidate_bitfields); - - // send the candidate 1 assignment from peer_c - let assignment = IndirectAssignmentCertV2 { - block_hash: hash, - validator: validator_index, - cert: cert.cert, - }; - let msg = protocol_v3::ApprovalDistributionMessage::Assignments(vec![( - assignment, - (1 as CandidateIndex).into(), - )]); - - send_message_from_peer_v3(overseer, &peer_d, msg).await; - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::ApprovalVoting(ApprovalVotingMessage::CheckAndImportAssignment( - _, _, - tx, - )) => { - tx.send(AssignmentCheckResult::Accepted).unwrap(); - } - ); - expect_reputation_change(overseer, &peer_d, BENEFIT_VALID_MESSAGE_FIRST).await; - - // send an approval from peer_b - let approval = IndirectSignedApprovalVoteV2 { - block_hash: hash, - candidate_indices, - validator: validator_index, - signature: dummy_signature(), - }; - let msg = protocol_v3::ApprovalDistributionMessage::Approvals(vec![approval.clone()]); - send_message_from_peer_v3(overseer, &peer_d, msg).await; - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::ApprovalVoting(ApprovalVotingMessage::CheckAndImportApproval( - vote, - tx, - )) => { - assert_eq!(vote, approval); - tx.send(ApprovalCheckResult::Accepted).unwrap(); - } - ); - - expect_reputation_change(overseer, &peer_d, BENEFIT_VALID_MESSAGE_FIRST).await; - - // setup peers with V2 protocol versions - setup_peer_with_view(overseer, &peer_a, view![hash], ValidationVersion::V3).await; - setup_peer_with_view(overseer, &peer_b, view![hash], ValidationVersion::V3).await; - let mut expected_peers_assignments = vec![peer_a, peer_b]; - let mut expected_peers_approvals = vec![peer_a, peer_b]; - assert_matches!( - overseer_recv(overseer).await, - AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( - peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Assignments(assignments) - )) - )) => { - assert!(peers.len() == 1); - assert!(expected_peers_assignments.contains(peers.first().unwrap())); - expected_peers_assignments.retain(|peer| peer != peers.first().unwrap()); - assert_eq!(assignments.len(), 2); - } - ); - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( - peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Approvals(approvals) - )) - )) => { - assert!(peers.len() == 1); - assert!(expected_peers_approvals.contains(peers.first().unwrap())); - expected_peers_approvals.retain(|peer| peer != peers.first().unwrap()); - assert_eq!(approvals.len(), 1); - } - ); - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( - peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Assignments(assignments) - )) - )) => { - assert!(peers.len() == 1); - assert!(expected_peers_assignments.contains(peers.first().unwrap())); - expected_peers_assignments.retain(|peer| peer != peers.first().unwrap()); - assert_eq!(assignments.len(), 2); - } - ); - - assert_matches!( - overseer_recv(overseer).await, - AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( - peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Approvals(approvals) - )) - )) => { - assert!(peers.len() == 1); - assert!(expected_peers_approvals.contains(peers.first().unwrap())); - expected_peers_approvals.retain(|peer| peer != peers.first().unwrap()); - assert_eq!(approvals.len(), 1); - } - ); - - virtual_overseer - }); -} - #[test] fn import_approval_bad() { let peer_a = PeerId::random(); @@ -1404,14 +916,14 @@ fn import_approval_bad() { let cert = fake_assignment_cert(hash, validator_index); // send the an approval from peer_b, we don't have an assignment yet - let approval = IndirectSignedApprovalVoteV2 { + let approval = IndirectSignedApprovalVote { block_hash: hash, - candidate_indices: candidate_index.into(), + candidate_index, validator: validator_index, signature: dummy_signature(), }; - let msg = protocol_v3::ApprovalDistributionMessage::Approvals(vec![approval.clone()]); - send_message_from_peer_v3(overseer, &peer_b, msg).await; + let msg = protocol_v1::ApprovalDistributionMessage::Approvals(vec![approval.clone()]); + send_message_from_peer(overseer, &peer_b, msg).await; expect_reputation_change(overseer, &peer_b, COST_UNEXPECTED_MESSAGE).await; @@ -1436,8 +948,8 @@ fn import_approval_bad() { expect_reputation_change(overseer, &peer_b, BENEFIT_VALID_MESSAGE_FIRST).await; // and try again - let msg = protocol_v3::ApprovalDistributionMessage::Approvals(vec![approval.clone()]); - send_message_from_peer_v3(overseer, &peer_b, msg).await; + let msg = protocol_v1::ApprovalDistributionMessage::Approvals(vec![approval.clone()]); + send_message_from_peer(overseer, &peer_b, msg).await; assert_matches!( overseer_recv(overseer).await, @@ -1536,8 +1048,7 @@ fn update_peer_view() { let hash_b = Hash::repeat_byte(0xBB); let hash_c = Hash::repeat_byte(0xCC); let hash_d = Hash::repeat_byte(0xDD); - let peers = make_peers_and_authority_ids(8); - let peer_a = peers.first().unwrap().0; + let peer_a = PeerId::random(); let peer = &peer_a; let state = test_harness(State::default(), |mut virtual_overseer| async move { @@ -1571,9 +1082,6 @@ fn update_peer_view() { let msg = ApprovalDistributionMessage::NewBlocks(vec![meta_a, meta_b, meta_c]); overseer_send(overseer, msg).await; - // Setup a topology where peer_a is neigboor to current node. - setup_gossip_topology(overseer, make_gossip_topology(1, &peers, &[0], &[2], 1)).await; - let cert_a = fake_assignment_cert(hash_a, ValidatorIndex(0)); let cert_b = fake_assignment_cert(hash_b, ValidatorIndex(0)); @@ -1756,14 +1264,14 @@ fn import_remotely_then_locally() { assert!(overseer.recv().timeout(TIMEOUT).await.is_none(), "no message should be sent"); // send the approval remotely - let approval = IndirectSignedApprovalVoteV2 { + let approval = IndirectSignedApprovalVote { block_hash: hash, - candidate_indices: candidate_index.into(), + candidate_index, validator: validator_index, signature: dummy_signature(), }; - let msg = protocol_v3::ApprovalDistributionMessage::Approvals(vec![approval.clone()]); - send_message_from_peer_v3(overseer, peer, msg).await; + let msg = protocol_v1::ApprovalDistributionMessage::Approvals(vec![approval.clone()]); + send_message_from_peer(overseer, peer, msg).await; assert_matches!( overseer_recv(overseer).await, @@ -1787,8 +1295,7 @@ fn import_remotely_then_locally() { #[test] fn sends_assignments_even_when_state_is_approved() { - let peers = make_peers_and_authority_ids(8); - let peer_a = peers.first().unwrap().0; + let peer_a = PeerId::random(); let parent_hash = Hash::repeat_byte(0xFF); let hash = Hash::repeat_byte(0xAA); let peer = &peer_a; @@ -1808,9 +1315,6 @@ fn sends_assignments_even_when_state_is_approved() { let msg = ApprovalDistributionMessage::NewBlocks(vec![meta]); overseer_send(overseer, msg).await; - // Setup a topology where peer_a is neigboor to current node. - setup_gossip_topology(overseer, make_gossip_topology(1, &peers, &[0], &[2], 1)).await; - let validator_index = ValidatorIndex(0); let candidate_index = 0u32; @@ -1832,11 +1336,8 @@ fn sends_assignments_even_when_state_is_approved() { ) .await; - overseer_send( - overseer, - ApprovalDistributionMessage::DistributeApproval(approval.clone().into()), - ) - .await; + overseer_send(overseer, ApprovalDistributionMessage::DistributeApproval(approval.clone())) + .await; // connect the peer. setup_peer_with_view(overseer, peer, view![hash], ValidationVersion::V1).await; @@ -1879,8 +1380,7 @@ fn sends_assignments_even_when_state_is_approved() { /// assignemnts. #[test] fn sends_assignments_even_when_state_is_approved_v2() { - let peers = make_peers_and_authority_ids(8); - let peer_a = peers.first().unwrap().0; + let peer_a = PeerId::random(); let parent_hash = Hash::repeat_byte(0xFF); let hash = Hash::repeat_byte(0xAA); let peer = &peer_a; @@ -1900,9 +1400,6 @@ fn sends_assignments_even_when_state_is_approved_v2() { let msg = ApprovalDistributionMessage::NewBlocks(vec![meta]); overseer_send(overseer, msg).await; - // Setup a topology where peer_a is neigboor to current node. - setup_gossip_topology(overseer, make_gossip_topology(1, &peers, &[0], &[2], 1)).await; - let validator_index = ValidatorIndex(0); let cores = vec![0, 1, 2, 3]; let candidate_bitfield: CandidateBitfield = cores.clone().try_into().unwrap(); @@ -1919,9 +1416,9 @@ fn sends_assignments_even_when_state_is_approved_v2() { // Assumes candidate index == core index. let approvals = cores .iter() - .map(|core| IndirectSignedApprovalVoteV2 { + .map(|core| IndirectSignedApprovalVote { block_hash: hash, - candidate_indices: (*core).into(), + candidate_index: *core, validator: validator_index, signature: dummy_signature(), }) @@ -1945,7 +1442,7 @@ fn sends_assignments_even_when_state_is_approved_v2() { } // connect the peer. - setup_peer_with_view(overseer, peer, view![hash], ValidationVersion::V3).await; + setup_peer_with_view(overseer, peer, view![hash], ValidationVersion::VStaging).await; let assignments = vec![(cert.clone(), candidate_bitfield.clone())]; @@ -1953,8 +1450,8 @@ fn sends_assignments_even_when_state_is_approved_v2() { overseer_recv(overseer).await, AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Assignments(sent_assignments) + Versioned::VStaging(protocol_vstaging::ValidationProtocol::ApprovalDistribution( + protocol_vstaging::ApprovalDistributionMessage::Assignments(sent_assignments) )) )) => { assert_eq!(peers, vec![*peer]); @@ -1966,14 +1463,14 @@ fn sends_assignments_even_when_state_is_approved_v2() { overseer_recv(overseer).await, AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( peers, - Versioned::V3(protocol_v3::ValidationProtocol::ApprovalDistribution( - protocol_v3::ApprovalDistributionMessage::Approvals(sent_approvals) + Versioned::VStaging(protocol_vstaging::ValidationProtocol::ApprovalDistribution( + protocol_vstaging::ApprovalDistributionMessage::Approvals(sent_approvals) )) )) => { // Construct a hashmaps of approvals for comparison. Approval distribution reorders messages because they are kept in a // hashmap as well. - let sent_approvals = sent_approvals.into_iter().map(|approval| (approval.candidate_indices.clone(), approval)).collect::>(); - let approvals = approvals.into_iter().map(|approval| (approval.candidate_indices.clone(), approval)).collect::>(); + let sent_approvals = sent_approvals.into_iter().map(|approval| (approval.candidate_index, approval)).collect::>(); + let approvals = approvals.into_iter().map(|approval| (approval.candidate_index, approval)).collect::>(); assert_eq!(peers, vec![*peer]); assert_eq!(sent_approvals, approvals); @@ -2083,19 +1580,13 @@ fn propagates_locally_generated_assignment_to_both_dimensions() { // Set up a gossip topology. setup_gossip_topology( overseer, - make_gossip_topology( - 1, - &peers, - &[0, 10, 20, 30, 40, 60, 70, 80], - &[50, 51, 52, 53, 54, 55, 56, 57], - 1, - ), + make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53]), ) .await; let expected_indices = [ // Both dimensions in the gossip topology - 0, 10, 20, 30, 40, 60, 70, 80, 50, 51, 52, 53, 54, 55, 56, 57, + 0, 10, 20, 30, 50, 51, 52, 53, ]; // new block `hash_a` with 1 candidates @@ -2132,11 +1623,8 @@ fn propagates_locally_generated_assignment_to_both_dimensions() { ) .await; - overseer_send( - overseer, - ApprovalDistributionMessage::DistributeApproval(approval.clone().into()), - ) - .await; + overseer_send(overseer, ApprovalDistributionMessage::DistributeApproval(approval.clone())) + .await; let assignments = vec![(cert.clone(), candidate_index)]; let approvals = vec![approval.clone()]; @@ -2200,7 +1688,7 @@ fn propagates_assignments_along_unshared_dimension() { // Set up a gossip topology. setup_gossip_topology( overseer, - make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53], 1), + make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53]), ) .await; @@ -2343,19 +1831,13 @@ fn propagates_to_required_after_connect() { // Set up a gossip topology. setup_gossip_topology( overseer, - make_gossip_topology( - 1, - &peers, - &[0, 10, 20, 30, 40, 60, 70, 80], - &[50, 51, 52, 53, 54, 55, 56, 57], - 1, - ), + make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53]), ) .await; let expected_indices = [ // Both dimensions in the gossip topology, minus omitted. - 20, 30, 40, 60, 70, 80, 52, 53, 54, 55, 56, 57, + 20, 30, 52, 53, ]; // new block `hash_a` with 1 candidates @@ -2392,11 +1874,8 @@ fn propagates_to_required_after_connect() { ) .await; - overseer_send( - overseer, - ApprovalDistributionMessage::DistributeApproval(approval.clone().into()), - ) - .await; + overseer_send(overseer, ApprovalDistributionMessage::DistributeApproval(approval.clone())) + .await; let assignments = vec![(cert.clone(), candidate_index)]; let approvals = vec![approval.clone()]; @@ -2523,21 +2002,53 @@ fn sends_to_more_peers_after_getting_topology() { ) .await; - overseer_send( - overseer, - ApprovalDistributionMessage::DistributeApproval(approval.clone().into()), - ) - .await; + overseer_send(overseer, ApprovalDistributionMessage::DistributeApproval(approval.clone())) + .await; let assignments = vec![(cert.clone(), candidate_index)]; let approvals = vec![approval.clone()]; - let expected_indices = vec![0, 10, 20, 30, 50, 51, 52, 53]; + let mut expected_indices = vec![0, 10, 20, 30, 50, 51, 52, 53]; + let assignment_sent_peers = assert_matches!( + overseer_recv(overseer).await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( + sent_peers, + Versioned::V1(protocol_v1::ValidationProtocol::ApprovalDistribution( + protocol_v1::ApprovalDistributionMessage::Assignments(sent_assignments) + )) + )) => { + // Only sends to random peers. + assert_eq!(sent_peers.len(), 4); + for peer in &sent_peers { + let i = peers.iter().position(|p| peer == &p.0).unwrap(); + // Random gossip before topology can send to topology-targeted peers. + // Remove them from the expected indices so we don't expect + // them to get the messages again after the assignment. + expected_indices.retain(|&i2| i2 != i); + } + assert_eq!(sent_assignments, assignments); + sent_peers + } + ); + + assert_matches!( + overseer_recv(overseer).await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( + sent_peers, + Versioned::V1(protocol_v1::ValidationProtocol::ApprovalDistribution( + protocol_v1::ApprovalDistributionMessage::Approvals(sent_approvals) + )) + )) => { + // Random sampling is reused from the assignment. + assert_eq!(sent_peers, assignment_sent_peers); + assert_eq!(sent_approvals, approvals); + } + ); // Set up a gossip topology. setup_gossip_topology( overseer, - make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53], 1), + make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53]), ) .await; @@ -2640,7 +2151,7 @@ fn originator_aggression_l1() { // Set up a gossip topology. setup_gossip_topology( overseer, - make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53], 1), + make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53]), ) .await; @@ -2653,11 +2164,8 @@ fn originator_aggression_l1() { ) .await; - overseer_send( - overseer, - ApprovalDistributionMessage::DistributeApproval(approval.clone().into()), - ) - .await; + overseer_send(overseer, ApprovalDistributionMessage::DistributeApproval(approval.clone())) + .await; let assignments = vec![(cert.clone(), candidate_index)]; let approvals = vec![approval.clone()]; @@ -2799,7 +2307,7 @@ fn non_originator_aggression_l1() { // Set up a gossip topology. setup_gossip_topology( overseer, - make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53], 1), + make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53]), ) .await; @@ -2904,7 +2412,7 @@ fn non_originator_aggression_l2() { // Set up a gossip topology. setup_gossip_topology( overseer, - make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53], 1), + make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53]), ) .await; @@ -3050,7 +2558,7 @@ fn resends_messages_periodically() { // Set up a gossip topology. setup_gossip_topology( overseer, - make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53], 1), + make_gossip_topology(1, &peers, &[0, 10, 20, 30], &[50, 51, 52, 53]), ) .await; @@ -3173,13 +2681,12 @@ fn resends_messages_periodically() { /// Tests that peers correctly receive versioned messages. #[test] fn import_versioned_approval() { - let peers = make_peers_and_authority_ids(15); - let peer_a = peers.get(0).unwrap().0; - let peer_b = peers.get(1).unwrap().0; - let peer_c = peers.get(2).unwrap().0; - + let peer_a = PeerId::random(); + let peer_b = PeerId::random(); + let peer_c = PeerId::random(); let parent_hash = Hash::repeat_byte(0xFF); let hash = Hash::repeat_byte(0xAA); + let state = state_without_reputation_delay(); let _ = test_harness(state, |mut virtual_overseer| async move { let overseer = &mut virtual_overseer; @@ -3188,10 +2695,6 @@ fn import_versioned_approval() { setup_peer_with_view(overseer, &peer_b, view![hash], ValidationVersion::V1).await; setup_peer_with_view(overseer, &peer_c, view![hash], ValidationVersion::V2).await; - // Set up a gossip topology, where a, b, c and d are topology neighboors to the node under - // testing. - setup_gossip_topology(overseer, make_gossip_topology(1, &peers, &[0, 1], &[2, 4], 3)).await; - // new block `hash_a` with 1 candidates let meta = BlockApprovalMeta { hash, @@ -3259,7 +2762,7 @@ fn import_versioned_approval() { vote, tx, )) => { - assert_eq!(vote, approval.into()); + assert_eq!(vote, approval); tx.send(ApprovalCheckResult::Accepted).unwrap(); } ); @@ -3279,7 +2782,6 @@ fn import_versioned_approval() { assert_eq!(approvals.len(), 1); } ); - assert_matches!( overseer_recv(overseer).await, AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( @@ -3319,9 +2821,9 @@ fn batch_test_round(message_count: usize) { .collect(); let approvals: Vec<_> = validators - .map(|index| IndirectSignedApprovalVoteV2 { + .map(|index| IndirectSignedApprovalVote { block_hash: Hash::zero(), - candidate_indices: 0u32.into(), + candidate_index: 0, validator: ValidatorIndex(index as u32), signature: dummy_signature(), }) @@ -3388,7 +2890,7 @@ fn batch_test_round(message_count: usize) { assert_eq!(peers.len(), 1); for (message_index, approval) in sent_approvals.iter().enumerate() { - assert_eq!(approval, &approvals[approval_index + message_index].clone().try_into().unwrap()); + assert_eq!(approval, &approvals[approval_index + message_index]); } } ); diff --git a/polkadot/node/network/availability-distribution/Cargo.toml b/polkadot/node/network/availability-distribution/Cargo.toml index 0d52c013a33..91ed1026e41 100644 --- a/polkadot/node/network/availability-distribution/Cargo.toml +++ b/polkadot/node/network/availability-distribution/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] futures = "0.3.21" gum = { package = "tracing-gum", path = "../../gum" } diff --git a/polkadot/node/network/availability-distribution/src/pov_requester/mod.rs b/polkadot/node/network/availability-distribution/src/pov_requester/mod.rs index 6f9ef9f6a9f..12a97a1fb5a 100644 --- a/polkadot/node/network/availability-distribution/src/pov_requester/mod.rs +++ b/polkadot/node/network/availability-distribution/src/pov_requester/mod.rs @@ -146,9 +146,7 @@ mod tests { AllMessages, AvailabilityDistributionMessage, RuntimeApiMessage, RuntimeApiRequest, }; use polkadot_node_subsystem_test_helpers as test_helpers; - use polkadot_primitives::{ - vstaging::NodeFeatures, CandidateHash, ExecutorParams, Hash, ValidatorIndex, - }; + use polkadot_primitives::{CandidateHash, ExecutorParams, Hash, ValidatorIndex}; use test_helpers::mock::make_ferdie_keystore; use super::*; @@ -216,12 +214,6 @@ mod tests { )) => { tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); }, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, - RuntimeApiRequest::NodeFeatures(_, si_tx), - )) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - }, AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendRequests( mut reqs, _, diff --git a/polkadot/node/network/availability-distribution/src/requester/tests.rs b/polkadot/node/network/availability-distribution/src/requester/tests.rs index 2f5d900b037..c4252b4e439 100644 --- a/polkadot/node/network/availability-distribution/src/requester/tests.rs +++ b/polkadot/node/network/availability-distribution/src/requester/tests.rs @@ -25,8 +25,8 @@ use polkadot_node_primitives::{BlockData, ErasureChunk, PoV}; use polkadot_node_subsystem_test_helpers::mock::new_leaf; use polkadot_node_subsystem_util::runtime::RuntimeInfo; use polkadot_primitives::{ - vstaging::NodeFeatures, BlockNumber, CoreState, ExecutorParams, GroupIndex, Hash, Id as ParaId, - ScheduledCore, SessionIndex, SessionInfo, + BlockNumber, CoreState, ExecutorParams, GroupIndex, Hash, Id as ParaId, ScheduledCore, + SessionIndex, SessionInfo, }; use sp_core::traits::SpawnNamed; @@ -125,10 +125,6 @@ fn spawn_virtual_overseer( tx.send(Ok(Some(ExecutorParams::default()))) .expect("Receiver should be alive."); }, - RuntimeApiRequest::NodeFeatures(_, tx) => { - tx.send(Ok(NodeFeatures::EMPTY)) - .expect("Receiver should be alive."); - }, RuntimeApiRequest::AvailabilityCores(tx) => { let para_id = ParaId::from(1_u32); let maybe_block_position = diff --git a/polkadot/node/network/availability-distribution/src/tests/state.rs b/polkadot/node/network/availability-distribution/src/tests/state.rs index e95c1c3a27c..101d917c0db 100644 --- a/polkadot/node/network/availability-distribution/src/tests/state.rs +++ b/polkadot/node/network/availability-distribution/src/tests/state.rs @@ -46,8 +46,8 @@ use polkadot_node_subsystem::{ }; use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_primitives::{ - vstaging::NodeFeatures, CandidateHash, CoreState, ExecutorParams, GroupIndex, Hash, - Id as ParaId, ScheduledCore, SessionInfo, ValidatorIndex, + CandidateHash, CoreState, ExecutorParams, GroupIndex, Hash, Id as ParaId, ScheduledCore, + SessionInfo, ValidatorIndex, }; use test_helpers::mock::{make_ferdie_keystore, new_leaf}; @@ -264,9 +264,6 @@ impl TestState { tx.send(Ok(Some(ExecutorParams::default()))) .expect("Receiver should be alive."); }, - RuntimeApiRequest::NodeFeatures(_, si_tx) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).expect("Receiver should be alive."); - }, RuntimeApiRequest::AvailabilityCores(tx) => { gum::trace!(target: LOG_TARGET, cores= ?self.cores[&hash], hash = ?hash, "Sending out cores for hash"); tx.send(Ok(self.cores[&hash].clone())) diff --git a/polkadot/node/network/availability-recovery/Cargo.toml b/polkadot/node/network/availability-recovery/Cargo.toml index 063d75275ca..6048e6323cb 100644 --- a/polkadot/node/network/availability-recovery/Cargo.toml +++ b/polkadot/node/network/availability-recovery/Cargo.toml @@ -6,12 +6,8 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] futures = "0.3.21" -tokio = "1.24.2" schnellru = "0.2.1" rand = "0.8.5" fatality = "0.0.6" @@ -41,6 +37,3 @@ sc-network = { path = "../../../../substrate/client/network" } polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } - -[features] -subsystem-benchmarks = [] diff --git a/polkadot/node/network/availability-recovery/src/lib.rs b/polkadot/node/network/availability-recovery/src/lib.rs index fb8064878f4..4a658449f09 100644 --- a/polkadot/node/network/availability-recovery/src/lib.rs +++ b/polkadot/node/network/availability-recovery/src/lib.rs @@ -65,7 +65,7 @@ mod error; mod futures_undead; mod metrics; mod task; -pub use metrics::Metrics; +use metrics::Metrics; #[cfg(test)] mod tests; @@ -603,8 +603,7 @@ impl AvailabilityRecoverySubsystem { } } - /// Starts the inner subsystem loop. - pub async fn run(self, mut ctx: Context) -> SubsystemResult<()> { + async fn run(self, mut ctx: Context) -> SubsystemResult<()> { let mut state = State::default(); let Self { mut req_receiver, @@ -682,7 +681,6 @@ impl AvailabilityRecoverySubsystem { &mut state, signal, ).await? { - gum::debug!(target: LOG_TARGET, "subsystem concluded"); return Ok(()); } FromOrchestra::Communication { msg } => { @@ -847,17 +845,12 @@ async fn erasure_task_thread( let _ = sender.send(maybe_data); }, None => { - gum::trace!( + gum::debug!( target: LOG_TARGET, "Erasure task channel closed. Node shutting down ?", ); break }, } - - // In benchmarks this is a very hot loop not yielding at all. - // To update CPU metrics for the task we need to yield. - #[cfg(feature = "subsystem-benchmarks")] - tokio::task::yield_now().await; } } diff --git a/polkadot/node/network/availability-recovery/src/metrics.rs b/polkadot/node/network/availability-recovery/src/metrics.rs index d82a8f9ae5f..aa721673950 100644 --- a/polkadot/node/network/availability-recovery/src/metrics.rs +++ b/polkadot/node/network/availability-recovery/src/metrics.rs @@ -29,10 +29,7 @@ struct MetricsInner { /// /// Gets incremented on each sent chunk requests. chunk_requests_issued: Counter, - /// Total number of bytes recovered - /// - /// Gets incremented on each succesful recovery - recovered_bytes_total: Counter, + /// A counter for finished chunk requests. /// /// Split by result: @@ -136,10 +133,9 @@ impl Metrics { } /// A full recovery succeeded. - pub fn on_recovery_succeeded(&self, bytes: usize) { + pub fn on_recovery_succeeded(&self) { if let Some(metrics) = &self.0 { - metrics.full_recoveries_finished.with_label_values(&["success"]).inc(); - metrics.recovered_bytes_total.inc_by(bytes as u64) + metrics.full_recoveries_finished.with_label_values(&["success"]).inc() } } @@ -175,13 +171,6 @@ impl metrics::Metrics for Metrics { )?, registry, )?, - recovered_bytes_total: prometheus::register( - Counter::new( - "polkadot_parachain_availability_recovery_bytes_total", - "Total number of bytes recovered", - )?, - registry, - )?, chunk_requests_finished: prometheus::register( CounterVec::new( Opts::new( diff --git a/polkadot/node/network/availability-recovery/src/task.rs b/polkadot/node/network/availability-recovery/src/task.rs index c300c221da5..f705d5c0e4c 100644 --- a/polkadot/node/network/availability-recovery/src/task.rs +++ b/polkadot/node/network/availability-recovery/src/task.rs @@ -23,7 +23,6 @@ use crate::{ PostRecoveryCheck, LOG_TARGET, }; use futures::{channel::oneshot, SinkExt}; -use parity_scale_codec::Encode; #[cfg(not(test))] use polkadot_node_network_protocol::request_response::CHUNK_REQUEST_TIMEOUT; use polkadot_node_network_protocol::request_response::{ @@ -433,7 +432,7 @@ where return Err(err) }, Ok(data) => { - self.params.metrics.on_recovery_succeeded(data.encoded_size()); + self.params.metrics.on_recovery_succeeded(); return Ok(data) }, } diff --git a/polkadot/node/network/availability-recovery/src/tests.rs b/polkadot/node/network/availability-recovery/src/tests.rs index 1cb52757bac..63ccf0e94f9 100644 --- a/polkadot/node/network/availability-recovery/src/tests.rs +++ b/polkadot/node/network/availability-recovery/src/tests.rs @@ -24,12 +24,12 @@ use parity_scale_codec::Encode; use polkadot_node_network_protocol::request_response::{ self as req_res, IncomingRequest, Recipient, ReqProtocolNames, Requests, }; -use polkadot_node_subsystem_test_helpers::derive_erasure_chunks_with_proofs_and_root; use super::*; use sc_network::{config::RequestResponseConfig, IfDisconnected, OutboundFailure, RequestFailure}; +use polkadot_erasure_coding::{branches, obtain_chunks_v1 as obtain_chunks}; use polkadot_node_primitives::{BlockData, PoV, Proof}; use polkadot_node_subsystem::messages::{ AllMessages, NetworkBridgeTxMessage, RuntimeApiMessage, RuntimeApiRequest, @@ -456,6 +456,33 @@ fn validator_authority_id(val_ids: &[Sr25519Keyring]) -> Vec), +) -> (Vec, Hash) { + let mut chunks: Vec> = obtain_chunks(n_validators, available_data).unwrap(); + + for (i, chunk) in chunks.iter_mut().enumerate() { + alter_chunk(i, chunk) + } + + // create proofs for each erasure chunk + let branches = branches(chunks.as_ref()); + + let root = branches.root(); + let erasure_chunks = branches + .enumerate() + .map(|(index, (proof, chunk))| ErasureChunk { + chunk: chunk.to_vec(), + index: ValidatorIndex(index as _), + proof: Proof::try_from(proof).unwrap(), + }) + .collect::>(); + + (erasure_chunks, root) +} + impl Default for TestState { fn default() -> Self { let validators = vec![ diff --git a/polkadot/node/network/bitfield-distribution/Cargo.toml b/polkadot/node/network/bitfield-distribution/Cargo.toml index 5c5bd875a96..0e61e9cf620 100644 --- a/polkadot/node/network/bitfield-distribution/Cargo.toml +++ b/polkadot/node/network/bitfield-distribution/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] always-assert = "0.1" futures = "0.3.21" diff --git a/polkadot/node/network/bitfield-distribution/src/lib.rs b/polkadot/node/network/bitfield-distribution/src/lib.rs index 76baf499cad..9cc79aee849 100644 --- a/polkadot/node/network/bitfield-distribution/src/lib.rs +++ b/polkadot/node/network/bitfield-distribution/src/lib.rs @@ -32,7 +32,7 @@ use polkadot_node_network_protocol::{ GridNeighbors, RandomRouting, RequiredRouting, SessionBoundGridTopologyStorage, }, peer_set::{ProtocolVersion, ValidationVersion}, - v1 as protocol_v1, v2 as protocol_v2, v3 as protocol_v3, OurView, PeerId, + v1 as protocol_v1, v2 as protocol_v2, vstaging as protocol_vstaging, OurView, PeerId, UnifiedReputationChange as Rep, Versioned, View, }; use polkadot_node_subsystem::{ @@ -102,8 +102,8 @@ impl BitfieldGossipMessage { self.relay_parent, self.signed_availability.into(), )), - Some(ValidationVersion::V3) => - Versioned::V3(protocol_v3::BitfieldDistributionMessage::Bitfield( + Some(ValidationVersion::VStaging) => + Versioned::VStaging(protocol_vstaging::BitfieldDistributionMessage::Bitfield( self.relay_parent, self.signed_availability.into(), )), @@ -503,8 +503,8 @@ async fn relay_message( let v2_interested_peers = filter_by_peer_version(&interested_peers, ValidationVersion::V2.into()); - let v3_interested_peers = - filter_by_peer_version(&interested_peers, ValidationVersion::V3.into()); + let vstaging_interested_peers = + filter_by_peer_version(&interested_peers, ValidationVersion::VStaging.into()); if !v1_interested_peers.is_empty() { ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage( @@ -522,10 +522,10 @@ async fn relay_message( .await } - if !v3_interested_peers.is_empty() { + if !vstaging_interested_peers.is_empty() { ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage( - v3_interested_peers, - message.into_validation_protocol(ValidationVersion::V3.into()), + vstaging_interested_peers, + message.into_validation_protocol(ValidationVersion::VStaging.into()), )) .await } @@ -551,7 +551,7 @@ async fn process_incoming_peer_message( relay_parent, bitfield, )) | - Versioned::V3(protocol_v3::BitfieldDistributionMessage::Bitfield( + Versioned::VStaging(protocol_vstaging::BitfieldDistributionMessage::Bitfield( relay_parent, bitfield, )) => (relay_parent, bitfield), diff --git a/polkadot/node/network/bridge/Cargo.toml b/polkadot/node/network/bridge/Cargo.toml index d6b9a0a5e76..6ae765c252f 100644 --- a/polkadot/node/network/bridge/Cargo.toml +++ b/polkadot/node/network/bridge/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] always-assert = "0.1" async-trait = "0.1.57" diff --git a/polkadot/node/network/bridge/src/lib.rs b/polkadot/node/network/bridge/src/lib.rs index ddce99d5c2a..46d4a00faac 100644 --- a/polkadot/node/network/bridge/src/lib.rs +++ b/polkadot/node/network/bridge/src/lib.rs @@ -83,7 +83,6 @@ pub(crate) enum WireMessage { ViewUpdate(View), } -#[derive(Debug)] pub(crate) struct PeerData { /// The Latest view sent by the peer. view: View, diff --git a/polkadot/node/network/bridge/src/network.rs b/polkadot/node/network/bridge/src/network.rs index 2fcf5cec489..c264c94cc19 100644 --- a/polkadot/node/network/bridge/src/network.rs +++ b/polkadot/node/network/bridge/src/network.rs @@ -14,26 +14,25 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use std::{ - collections::{HashMap, HashSet}, - sync::Arc, -}; +use std::{collections::HashSet, sync::Arc}; use async_trait::async_trait; -use parking_lot::Mutex; +use futures::{prelude::*, stream::BoxStream}; use parity_scale_codec::Encode; use sc_network::{ - config::parse_addr, multiaddr::Multiaddr, types::ProtocolName, IfDisconnected, MessageSink, - NetworkPeers, NetworkRequest, NetworkService, OutboundFailure, ReputationChange, - RequestFailure, + config::parse_addr, multiaddr::Multiaddr, types::ProtocolName, Event as NetworkEvent, + IfDisconnected, NetworkEventStream, NetworkNotification, NetworkPeers, NetworkRequest, + NetworkService, OutboundFailure, ReputationChange, RequestFailure, }; use polkadot_node_network_protocol::{ - peer_set::{CollationVersion, PeerSet, ProtocolVersion, ValidationVersion}, + peer_set::{ + CollationVersion, PeerSet, PeerSetProtocolNames, ProtocolVersion, ValidationVersion, + }, request_response::{OutgoingRequest, Recipient, ReqProtocolNames, Requests}, - v1 as protocol_v1, v2 as protocol_v2, v3 as protocol_v3, PeerId, + v1 as protocol_v1, v2 as protocol_v2, vstaging as protocol_vstaging, PeerId, }; use polkadot_primitives::{AuthorityDiscoveryId, Block, Hash}; @@ -45,94 +44,104 @@ const LOG_TARGET: &'static str = "parachain::network-bridge-net"; // Helper function to send a validation v1 message to a list of peers. // Messages are always sent via the main protocol, even legacy protocol messages. pub(crate) fn send_validation_message_v1( + net: &mut impl Network, peers: Vec, + peerset_protocol_names: &PeerSetProtocolNames, message: WireMessage, metrics: &Metrics, - notification_sinks: &Arc>>>, ) { gum::trace!(target: LOG_TARGET, ?peers, ?message, "Sending validation v1 message to peers",); send_message( + net, peers, PeerSet::Validation, ValidationVersion::V1.into(), + peerset_protocol_names, message, metrics, - notification_sinks, ); } -// Helper function to send a validation v3 message to a list of peers. +// Helper function to send a validation vstaging message to a list of peers. // Messages are always sent via the main protocol, even legacy protocol messages. -pub(crate) fn send_validation_message_v3( +pub(crate) fn send_validation_message_vstaging( + net: &mut impl Network, peers: Vec, - message: WireMessage, + peerset_protocol_names: &PeerSetProtocolNames, + message: WireMessage, metrics: &Metrics, - notification_sinks: &Arc>>>, ) { - gum::trace!(target: LOG_TARGET, ?peers, ?message, "Sending validation v3 message to peers",); + gum::trace!(target: LOG_TARGET, ?peers, ?message, "Sending validation vstaging message to peers",); send_message( + net, peers, PeerSet::Validation, - ValidationVersion::V3.into(), + ValidationVersion::VStaging.into(), + peerset_protocol_names, message, metrics, - notification_sinks, ); } // Helper function to send a validation v2 message to a list of peers. // Messages are always sent via the main protocol, even legacy protocol messages. pub(crate) fn send_validation_message_v2( + net: &mut impl Network, peers: Vec, + protocol_names: &PeerSetProtocolNames, message: WireMessage, metrics: &Metrics, - notification_sinks: &Arc>>>, ) { send_message( + net, peers, PeerSet::Validation, ValidationVersion::V2.into(), + protocol_names, message, metrics, - notification_sinks, ); } // Helper function to send a collation v1 message to a list of peers. // Messages are always sent via the main protocol, even legacy protocol messages. pub(crate) fn send_collation_message_v1( + net: &mut impl Network, peers: Vec, + peerset_protocol_names: &PeerSetProtocolNames, message: WireMessage, metrics: &Metrics, - notification_sinks: &Arc>>>, ) { send_message( + net, peers, PeerSet::Collation, CollationVersion::V1.into(), + peerset_protocol_names, message, metrics, - notification_sinks, ); } // Helper function to send a collation v2 message to a list of peers. // Messages are always sent via the main protocol, even legacy protocol messages. pub(crate) fn send_collation_message_v2( + net: &mut impl Network, peers: Vec, + peerset_protocol_names: &PeerSetProtocolNames, message: WireMessage, metrics: &Metrics, - notification_sinks: &Arc>>>, ) { send_message( + net, peers, PeerSet::Collation, CollationVersion::V2.into(), + peerset_protocol_names, message, metrics, - notification_sinks, ); } @@ -142,19 +151,19 @@ pub(crate) fn send_collation_message_v2( /// messages that are compatible with the passed peer set, as that is currently not enforced by /// this function. These are messages of type `WireMessage` parameterized on the matching type. fn send_message( + net: &mut impl Network, mut peers: Vec, peer_set: PeerSet, version: ProtocolVersion, + protocol_names: &PeerSetProtocolNames, message: M, metrics: &super::Metrics, - network_notification_sinks: &Arc>>>, ) where M: Encode + Clone, { if peers.is_empty() { return } - let message = { let encoded = message.encode(); metrics.on_notification_sent(peer_set, version, encoded.len(), peers.len()); @@ -162,13 +171,13 @@ fn send_message( encoded }; - let notification_sinks = network_notification_sinks.lock(); - + // optimization: generate the protocol name once. + let protocol_name = protocol_names.get_name(peer_set, version); gum::trace!( target: LOG_TARGET, ?peers, - ?peer_set, ?version, + ?protocol_name, ?message, "Sending message to peers", ); @@ -176,26 +185,29 @@ fn send_message( // optimization: avoid cloning the message for the last peer in the // list. The message payload can be quite large. If the underlying // network used `Bytes` this would not be necessary. - // - // peer may have gotten disconnect by the time `send_message()` is called - // at which point the the sink is not available. let last_peer = peers.pop(); + + // We always send messages on the "main" name even when a negotiated + // fallback is used. The libp2p implementation handles the fallback + // under the hood. + let protocol_name = protocol_names.get_main_name(peer_set); peers.into_iter().for_each(|peer| { - if let Some(sink) = notification_sinks.get(&(peer_set, peer)) { - sink.send_sync_notification(message.clone()); - } + net.write_notification(peer, protocol_name.clone(), message.clone()); }); - if let Some(peer) = last_peer { - if let Some(sink) = notification_sinks.get(&(peer_set, peer)) { - sink.send_sync_notification(message.clone()); - } + net.write_notification(peer, protocol_name, message); } } /// An abstraction over networking for the purposes of this subsystem. #[async_trait] pub trait Network: Clone + Send + 'static { + /// Get a stream of all events occurring on the network. This may include events unrelated + /// to the Polkadot protocol - the user of this function should filter only for events related + /// to the [`VALIDATION_PROTOCOL_NAME`](VALIDATION_PROTOCOL_NAME) + /// or [`COLLATION_PROTOCOL_NAME`](COLLATION_PROTOCOL_NAME) + fn event_stream(&mut self) -> BoxStream<'static, NetworkEvent>; + /// Ask the network to keep a substream open with these nodes and not disconnect from them /// until removed from the protocol's peer set. /// Note that `out_peers` setting has no effect on this. @@ -227,12 +239,16 @@ pub trait Network: Clone + Send + 'static { /// Disconnect a given peer from the protocol specified without harming reputation. fn disconnect_peer(&self, who: PeerId, protocol: ProtocolName); - /// Get peer role. - fn peer_role(&self, who: PeerId, handshake: Vec) -> Option; + /// Write a notification to a peer on the given protocol. + fn write_notification(&self, who: PeerId, protocol: ProtocolName, message: Vec); } #[async_trait] impl Network for Arc> { + fn event_stream(&mut self) -> BoxStream<'static, NetworkEvent> { + NetworkService::event_stream(self, "polkadot-network-bridge").boxed() + } + async fn set_reserved_peers( &mut self, protocol: ProtocolName, @@ -257,6 +273,10 @@ impl Network for Arc> { NetworkService::disconnect_peer(&**self, who, protocol); } + fn write_notification(&self, who: PeerId, protocol: ProtocolName, message: Vec) { + NetworkService::write_notification(&**self, who, protocol, message); + } + async fn start_request( &self, authority_discovery: &mut AD, @@ -328,10 +348,6 @@ impl Network for Arc> { if_disconnected, ); } - - fn peer_role(&self, who: PeerId, handshake: Vec) -> Option { - NetworkService::peer_role(self, who, handshake) - } } /// We assume one `peer_id` per `authority_id`. diff --git a/polkadot/node/network/bridge/src/rx/mod.rs b/polkadot/node/network/bridge/src/rx/mod.rs index 49d81aea76a..06be57ead00 100644 --- a/polkadot/node/network/bridge/src/rx/mod.rs +++ b/polkadot/node/network/bridge/src/rx/mod.rs @@ -20,14 +20,11 @@ use super::*; use always_assert::never; use bytes::Bytes; +use futures::stream::{BoxStream, StreamExt}; use net_protocol::filter_by_peer_version; use parity_scale_codec::{Decode, DecodeAll}; -use parking_lot::Mutex; -use sc_network::{ - service::traits::{NotificationEvent, ValidationResult}, - MessageSink, NotificationService, -}; +use sc_network::Event as NetworkEvent; use sp_consensus::SyncOracle; use polkadot_node_network_protocol::{ @@ -37,8 +34,8 @@ use polkadot_node_network_protocol::{ CollationVersion, PeerSet, PeerSetProtocolNames, PerPeerSet, ProtocolVersion, ValidationVersion, }, - v1 as protocol_v1, v2 as protocol_v2, v3 as protocol_v3, ObservedRole, OurView, PeerId, - UnifiedReputationChange as Rep, View, + v1 as protocol_v1, v2 as protocol_v2, vstaging as protocol_vstaging, ObservedRole, OurView, + PeerId, UnifiedReputationChange as Rep, View, }; use polkadot_node_subsystem::{ @@ -70,7 +67,7 @@ use super::validator_discovery; /// Defines the `Network` trait with an implementation for an `Arc`. use crate::network::{ send_collation_message_v1, send_collation_message_v2, send_validation_message_v1, - send_validation_message_v2, send_validation_message_v3, Network, + send_validation_message_v2, send_validation_message_vstaging, Network, }; use crate::{network::get_peer_id_by_authority_id, WireMessage}; @@ -91,9 +88,6 @@ pub struct NetworkBridgeRx { shared: Shared, metrics: Metrics, peerset_protocol_names: PeerSetProtocolNames, - validation_service: Box, - collation_service: Box, - notification_sinks: Arc>>>, } impl NetworkBridgeRx { @@ -108,18 +102,8 @@ impl NetworkBridgeRx { sync_oracle: Box, metrics: Metrics, peerset_protocol_names: PeerSetProtocolNames, - mut notification_services: HashMap>, - notification_sinks: Arc>>>, ) -> Self { let shared = Shared::default(); - - let validation_service = notification_services - .remove(&PeerSet::Validation) - .expect("validation protocol was enabled so `NotificationService` must exist; qed"); - let collation_service = notification_services - .remove(&PeerSet::Collation) - .expect("collation protocol was enabled so `NotificationService` must exist; qed"); - Self { network_service, authority_discovery_service, @@ -127,9 +111,6 @@ impl NetworkBridgeRx { shared, metrics, peerset_protocol_names, - validation_service, - collation_service, - notification_sinks, } } } @@ -140,562 +121,444 @@ where Net: Network + Sync, AD: validator_discovery::AuthorityDiscovery + Clone + Sync, { - fn start(self, ctx: Context) -> SpawnedSubsystem { + fn start(mut self, ctx: Context) -> SpawnedSubsystem { + // The stream of networking events has to be created at initialization, otherwise the + // networking might open connections before the stream of events has been grabbed. + let network_stream = self.network_service.event_stream(); + // Swallow error because failure is fatal to the node and we log with more precision // within `run_network`. - let future = run_network_in(self, ctx) + let future = run_network_in(self, ctx, network_stream) .map_err(|e| SubsystemError::with_origin("network-bridge", e)) .boxed(); SpawnedSubsystem { name: "network-bridge-rx-subsystem", future } } } -/// Handle notification event received over the validation protocol. -async fn handle_validation_message( - event: NotificationEvent, - network_service: &mut impl Network, - sender: &mut impl overseer::NetworkBridgeRxSenderTrait, - authority_discovery_service: &mut AD, - metrics: &Metrics, - shared: &Shared, - peerset_protocol_names: &PeerSetProtocolNames, - notification_service: &mut Box, - notification_sinks: &mut Arc>>>, -) where +async fn handle_network_messages( + mut sender: impl overseer::NetworkBridgeRxSenderTrait, + mut network_service: impl Network, + network_stream: BoxStream<'static, NetworkEvent>, + mut authority_discovery_service: AD, + metrics: Metrics, + shared: Shared, + peerset_protocol_names: PeerSetProtocolNames, +) -> Result<(), Error> +where AD: validator_discovery::AuthorityDiscovery + Send, { - match event { - NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx, .. } => { - // only accept peers whose role can be determined - let result = network_service - .peer_role(peer, handshake) - .map_or(ValidationResult::Reject, |_| ValidationResult::Accept); - let _ = result_tx.send(result); - }, - NotificationEvent::NotificationStreamOpened { - peer, - handshake, - negotiated_fallback, - .. - } => { - let role = match network_service.peer_role(peer, handshake) { - Some(role) => ObservedRole::from(role), - None => { - gum::debug!( - target: LOG_TARGET, - ?peer, - "Failed to determine peer role for validation protocol", - ); - return - }, - }; - - let (peer_set, version) = { - let (peer_set, version) = - (PeerSet::Validation, PeerSet::Validation.get_main_version()); - - if let Some(fallback) = negotiated_fallback { - match peerset_protocol_names.try_get_protocol(&fallback) { - None => { - gum::debug!( - target: LOG_TARGET, - fallback = &*fallback, - ?peer, - peerset = ?peer_set, - "Unknown fallback", - ); - - return - }, - Some((p2, v2)) => { - if p2 != peer_set { + let mut network_stream = network_stream.fuse(); + loop { + match network_stream.next().await { + None => return Err(Error::EventStreamConcluded), + Some(NetworkEvent::Dht(_)) => {}, + Some(NetworkEvent::NotificationStreamOpened { + remote: peer, + protocol, + role, + negotiated_fallback, + received_handshake: _, + }) => { + let role = ObservedRole::from(role); + let (peer_set, version) = { + let (peer_set, version) = + match peerset_protocol_names.try_get_protocol(&protocol) { + None => continue, + Some(p) => p, + }; + + if let Some(fallback) = negotiated_fallback { + match peerset_protocol_names.try_get_protocol(&fallback) { + None => { gum::debug!( target: LOG_TARGET, fallback = &*fallback, - fallback_peerset = ?p2, - peerset = ?peer_set, - "Fallback mismatched peer-set", + ?peer, + ?peer_set, + "Unknown fallback", ); - return - } - - (p2, v2) - }, + continue + }, + Some((p2, v2)) => { + if p2 != peer_set { + gum::debug!( + target: LOG_TARGET, + fallback = &*fallback, + fallback_peerset = ?p2, + protocol = &*protocol, + peerset = ?peer_set, + "Fallback mismatched peer-set", + ); + + continue + } + + (p2, v2) + }, + } + } else { + (peer_set, version) } - } else { - (peer_set, version) - } - }; - // store the notification sink to `notification_sinks` so both `NetworkBridgeRx` - // and `NetworkBridgeTx` can send messages to the peer. - match notification_service.message_sink(&peer) { - Some(sink) => { - notification_sinks.lock().insert((peer_set, peer), sink); - }, - None => { - gum::warn!( - target: LOG_TARGET, - peerset = ?peer_set, - version = %version, - ?peer, - ?role, - "Message sink not available for peer", - ); - return - }, - } + }; - gum::debug!( - target: LOG_TARGET, - action = "PeerConnected", - peer_set = ?peer_set, - version = %version, - peer = ?peer, - role = ?role - ); - - let local_view = { - let mut shared = shared.0.lock(); - let peer_map = &mut shared.validation_peers; - - match peer_map.entry(peer) { - hash_map::Entry::Occupied(_) => return, - hash_map::Entry::Vacant(vacant) => { - vacant.insert(PeerData { view: View::default(), version }); - }, - } + gum::debug!( + target: LOG_TARGET, + action = "PeerConnected", + peer_set = ?peer_set, + version = %version, + peer = ?peer, + role = ?role + ); - metrics.on_peer_connected(peer_set, version); - metrics.note_peer_count(peer_set, version, peer_map.len()); + let local_view = { + let mut shared = shared.0.lock(); + let peer_map = match peer_set { + PeerSet::Validation => &mut shared.validation_peers, + PeerSet::Collation => &mut shared.collation_peers, + }; - shared.local_view.clone().unwrap_or(View::default()) - }; + match peer_map.entry(peer) { + hash_map::Entry::Occupied(_) => continue, + hash_map::Entry::Vacant(vacant) => { + vacant.insert(PeerData { view: View::default(), version }); + }, + } - let maybe_authority = - authority_discovery_service.get_authority_ids_by_peer_id(peer).await; + metrics.on_peer_connected(peer_set, version); + metrics.note_peer_count(peer_set, version, peer_map.len()); - dispatch_validation_events_to_all( - vec![ - NetworkBridgeEvent::PeerConnected(peer, role, version, maybe_authority), - NetworkBridgeEvent::PeerViewChange(peer, View::default()), - ], - sender, - &metrics, - ) - .await; + shared.local_view.clone().unwrap_or(View::default()) + }; - match ValidationVersion::try_from(version) - .expect("try_get_protocol has already checked version is known; qed") - { - ValidationVersion::V1 => send_validation_message_v1( - vec![peer], - WireMessage::::ViewUpdate(local_view), - metrics, - notification_sinks, - ), - ValidationVersion::V3 => send_validation_message_v3( - vec![peer], - WireMessage::::ViewUpdate(local_view), - metrics, - notification_sinks, - ), - ValidationVersion::V2 => send_validation_message_v2( - vec![peer], - WireMessage::::ViewUpdate(local_view), - metrics, - notification_sinks, - ), - } - }, - NotificationEvent::NotificationStreamClosed { peer } => { - let (peer_set, version) = (PeerSet::Validation, PeerSet::Validation.get_main_version()); + let maybe_authority = + authority_discovery_service.get_authority_ids_by_peer_id(peer).await; + + match peer_set { + PeerSet::Validation => { + dispatch_validation_events_to_all( + vec![ + NetworkBridgeEvent::PeerConnected( + peer, + role, + version, + maybe_authority, + ), + NetworkBridgeEvent::PeerViewChange(peer, View::default()), + ], + &mut sender, + &metrics, + ) + .await; - gum::debug!( - target: LOG_TARGET, - action = "PeerDisconnected", - ?peer_set, - ?peer - ); - - let was_connected = { - let mut shared = shared.0.lock(); - let peer_map = &mut shared.validation_peers; - - let w = peer_map.remove(&peer).is_some(); - - metrics.on_peer_disconnected(peer_set, version); - metrics.note_peer_count(peer_set, version, peer_map.len()); - - w - }; - - notification_sinks.lock().remove(&(peer_set, peer)); - - if was_connected && version == peer_set.get_main_version() { - dispatch_validation_event_to_all( - NetworkBridgeEvent::PeerDisconnected(peer), - sender, - &metrics, - ) - .await; - } - }, - NotificationEvent::NotificationReceived { peer, notification } => { - let expected_versions = { - let mut versions = PerPeerSet::>::default(); - let shared = shared.0.lock(); - - if let Some(peer_data) = shared.validation_peers.get(&peer) { - versions[PeerSet::Validation] = Some(peer_data.version); - } + match ValidationVersion::try_from(version) + .expect("try_get_protocol has already checked version is known; qed") + { + ValidationVersion::V1 => send_validation_message_v1( + &mut network_service, + vec![peer], + &peerset_protocol_names, + WireMessage::::ViewUpdate( + local_view, + ), + &metrics, + ), + ValidationVersion::VStaging => send_validation_message_vstaging( + &mut network_service, + vec![peer], + &peerset_protocol_names, + WireMessage::::ViewUpdate( + local_view, + ), + &metrics, + ), + ValidationVersion::V2 => send_validation_message_v2( + &mut network_service, + vec![peer], + &peerset_protocol_names, + WireMessage::::ViewUpdate( + local_view, + ), + &metrics, + ), + } + }, + PeerSet::Collation => { + dispatch_collation_events_to_all( + vec![ + NetworkBridgeEvent::PeerConnected( + peer, + role, + version, + maybe_authority, + ), + NetworkBridgeEvent::PeerViewChange(peer, View::default()), + ], + &mut sender, + ) + .await; - versions - }; + match CollationVersion::try_from(version) + .expect("try_get_protocol has already checked version is known; qed") + { + CollationVersion::V1 => send_collation_message_v1( + &mut network_service, + vec![peer], + &peerset_protocol_names, + WireMessage::::ViewUpdate( + local_view, + ), + &metrics, + ), + CollationVersion::V2 => send_collation_message_v2( + &mut network_service, + vec![peer], + &peerset_protocol_names, + WireMessage::::ViewUpdate( + local_view, + ), + &metrics, + ), + } + }, + } + }, + Some(NetworkEvent::NotificationStreamClosed { remote: peer, protocol }) => { + let (peer_set, version) = match peerset_protocol_names.try_get_protocol(&protocol) { + None => continue, + Some(peer_set) => peer_set, + }; - gum::trace!( - target: LOG_TARGET, - action = "PeerMessage", - peerset = ?PeerSet::Validation, - ?peer, - ); - - let (events, reports) = if expected_versions[PeerSet::Validation] == - Some(ValidationVersion::V1.into()) - { - handle_peer_messages::( - peer, - PeerSet::Validation, - &mut shared.0.lock().validation_peers, - vec![notification.into()], - metrics, - ) - } else if expected_versions[PeerSet::Validation] == Some(ValidationVersion::V2.into()) { - handle_peer_messages::( - peer, - PeerSet::Validation, - &mut shared.0.lock().validation_peers, - vec![notification.into()], - metrics, - ) - } else if expected_versions[PeerSet::Validation] == Some(ValidationVersion::V3.into()) { - handle_peer_messages::( - peer, - PeerSet::Validation, - &mut shared.0.lock().validation_peers, - vec![notification.into()], - metrics, - ) - } else { - gum::warn!( + gum::debug!( target: LOG_TARGET, - version = ?expected_versions[PeerSet::Validation], - "Major logic bug. Peer somehow has unsupported validation protocol version." - ); - - never!( - "Only versions 1 and 2 are supported; peer set connection checked above; qed" + action = "PeerDisconnected", + peer_set = ?peer_set, + peer = ?peer ); - // If a peer somehow triggers this, we'll disconnect them - // eventually. - (Vec::new(), vec![UNCONNECTED_PEERSET_COST]) - }; - - for report in reports { - network_service.report_peer(peer, report.into()); - } + let was_connected = { + let mut shared = shared.0.lock(); + let peer_map = match peer_set { + PeerSet::Validation => &mut shared.validation_peers, + PeerSet::Collation => &mut shared.collation_peers, + }; - dispatch_validation_events_to_all(events, sender, &metrics).await; - }, - } -} + let w = peer_map.remove(&peer).is_some(); -/// Handle notification event received over the collation protocol. -async fn handle_collation_message( - event: NotificationEvent, - network_service: &mut impl Network, - sender: &mut impl overseer::NetworkBridgeRxSenderTrait, - authority_discovery_service: &mut AD, - metrics: &Metrics, - shared: &Shared, - peerset_protocol_names: &PeerSetProtocolNames, - notification_service: &mut Box, - notification_sinks: &mut Arc>>>, -) where - AD: validator_discovery::AuthorityDiscovery + Send, -{ - match event { - NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx, .. } => { - // only accept peers whose role can be determined - let result = network_service - .peer_role(peer, handshake) - .map_or(ValidationResult::Reject, |_| ValidationResult::Accept); - let _ = result_tx.send(result); - }, - NotificationEvent::NotificationStreamOpened { - peer, - handshake, - negotiated_fallback, - .. - } => { - let role = match network_service.peer_role(peer, handshake) { - Some(role) => ObservedRole::from(role), - None => { - gum::debug!( - target: LOG_TARGET, - ?peer, - "Failed to determine peer role for validation protocol", - ); - return - }, - }; - - let (peer_set, version) = { - let (peer_set, version) = - (PeerSet::Collation, PeerSet::Collation.get_main_version()); - - if let Some(fallback) = negotiated_fallback { - match peerset_protocol_names.try_get_protocol(&fallback) { - None => { - gum::debug!( - target: LOG_TARGET, - fallback = &*fallback, - ?peer, - ?peer_set, - "Unknown fallback", - ); - - return - }, - Some((p2, v2)) => { - if p2 != peer_set { - gum::debug!( - target: LOG_TARGET, - fallback = &*fallback, - fallback_peerset = ?p2, - peerset = ?peer_set, - "Fallback mismatched peer-set", - ); + metrics.on_peer_disconnected(peer_set, version); + metrics.note_peer_count(peer_set, version, peer_map.len()); - return - } + w + }; - (p2, v2) - }, + if was_connected && version == peer_set.get_main_version() { + match peer_set { + PeerSet::Validation => + dispatch_validation_event_to_all( + NetworkBridgeEvent::PeerDisconnected(peer), + &mut sender, + &metrics, + ) + .await, + PeerSet::Collation => + dispatch_collation_event_to_all( + NetworkBridgeEvent::PeerDisconnected(peer), + &mut sender, + ) + .await, } - } else { - (peer_set, version) } - }; - - // store the notification sink to `notification_sinks` so both `NetworkBridgeRx` - // and `NetworkBridgeTx` can send messages to the peer. - match notification_service.message_sink(&peer) { - Some(sink) => { - notification_sinks.lock().insert((peer_set, peer), sink); - }, - None => { - gum::warn!( - target: LOG_TARGET, - peer_set = ?peer_set, - version = %version, - peer = ?peer, - role = ?role, - "Message sink not available for peer", - ); - return - }, - } + }, + Some(NetworkEvent::NotificationsReceived { remote, messages }) => { + let expected_versions = { + let mut versions = PerPeerSet::>::default(); + let shared = shared.0.lock(); + if let Some(peer_data) = shared.validation_peers.get(&remote) { + versions[PeerSet::Validation] = Some(peer_data.version); + } - gum::debug!( - target: LOG_TARGET, - action = "PeerConnected", - peer_set = ?peer_set, - version = %version, - peer = ?peer, - role = ?role - ); - - let local_view = { - let mut shared = shared.0.lock(); - let peer_map = &mut shared.collation_peers; - - match peer_map.entry(peer) { - hash_map::Entry::Occupied(_) => return, - hash_map::Entry::Vacant(vacant) => { - vacant.insert(PeerData { view: View::default(), version }); - }, - } + if let Some(peer_data) = shared.collation_peers.get(&remote) { + versions[PeerSet::Collation] = Some(peer_data.version); + } - metrics.on_peer_connected(peer_set, version); - metrics.note_peer_count(peer_set, version, peer_map.len()); + versions + }; - shared.local_view.clone().unwrap_or(View::default()) - }; + // non-decoded, but version-checked validation messages. + let v_messages: Result, _> = messages + .iter() + .filter_map(|(protocol, msg_bytes)| { + // version doesn't matter because we always receive on the 'correct' + // protocol name, not the negotiated fallback. + let (peer_set, version) = + peerset_protocol_names.try_get_protocol(protocol)?; + gum::trace!( + target: LOG_TARGET, + ?peer_set, + ?protocol, + ?version, + "Received notification" + ); - let maybe_authority = - authority_discovery_service.get_authority_ids_by_peer_id(peer).await; + if peer_set == PeerSet::Validation { + if expected_versions[PeerSet::Validation].is_none() { + return Some(Err(UNCONNECTED_PEERSET_COST)) + } - dispatch_collation_events_to_all( - vec![ - NetworkBridgeEvent::PeerConnected(peer, role, version, maybe_authority), - NetworkBridgeEvent::PeerViewChange(peer, View::default()), - ], - sender, - ) - .await; + Some(Ok(msg_bytes.clone())) + } else { + None + } + }) + .collect(); - match CollationVersion::try_from(version) - .expect("try_get_protocol has already checked version is known; qed") - { - CollationVersion::V1 => send_collation_message_v1( - vec![peer], - WireMessage::::ViewUpdate(local_view), - metrics, - notification_sinks, - ), - CollationVersion::V2 => send_collation_message_v2( - vec![peer], - WireMessage::::ViewUpdate(local_view), - metrics, - notification_sinks, - ), - } - }, - NotificationEvent::NotificationStreamClosed { peer } => { - let (peer_set, version) = (PeerSet::Collation, PeerSet::Collation.get_main_version()); + let v_messages = match v_messages { + Err(rep) => { + gum::debug!(target: LOG_TARGET, action = "ReportPeer"); + network_service.report_peer(remote, rep.into()); - gum::debug!( - target: LOG_TARGET, - action = "PeerDisconnected", - ?peer_set, - ?peer - ); + continue + }, + Ok(v) => v, + }; - let was_connected = { - let mut shared = shared.0.lock(); - let peer_map = &mut shared.collation_peers; + // non-decoded, but version-checked collation messages. + let c_messages: Result, _> = messages + .iter() + .filter_map(|(protocol, msg_bytes)| { + // version doesn't matter because we always receive on the 'correct' + // protocol name, not the negotiated fallback. + let (peer_set, _version) = + peerset_protocol_names.try_get_protocol(protocol)?; + + if peer_set == PeerSet::Collation { + if expected_versions[PeerSet::Collation].is_none() { + return Some(Err(UNCONNECTED_PEERSET_COST)) + } - let w = peer_map.remove(&peer).is_some(); + Some(Ok(msg_bytes.clone())) + } else { + None + } + }) + .collect(); - metrics.on_peer_disconnected(peer_set, version); - metrics.note_peer_count(peer_set, version, peer_map.len()); + let c_messages = match c_messages { + Err(rep) => { + gum::debug!(target: LOG_TARGET, action = "ReportPeer"); + network_service.report_peer(remote, rep.into()); - w - }; + continue + }, + Ok(v) => v, + }; - notification_sinks.lock().remove(&(peer_set, peer)); + if v_messages.is_empty() && c_messages.is_empty() { + continue + } - if was_connected && version == peer_set.get_main_version() { - dispatch_collation_event_to_all(NetworkBridgeEvent::PeerDisconnected(peer), sender) - .await; - } - }, - NotificationEvent::NotificationReceived { peer, notification } => { - let expected_versions = { - let mut versions = PerPeerSet::>::default(); - let shared = shared.0.lock(); + gum::trace!( + target: LOG_TARGET, + action = "PeerMessages", + peer = ?remote, + num_validation_messages = %v_messages.len(), + num_collation_messages = %c_messages.len() + ); - if let Some(peer_data) = shared.collation_peers.get(&peer) { - versions[PeerSet::Collation] = Some(peer_data.version); - } + if !v_messages.is_empty() { + let (events, reports) = if expected_versions[PeerSet::Validation] == + Some(ValidationVersion::V1.into()) + { + handle_peer_messages::( + remote, + PeerSet::Validation, + &mut shared.0.lock().validation_peers, + v_messages, + &metrics, + ) + } else if expected_versions[PeerSet::Validation] == + Some(ValidationVersion::V2.into()) + { + handle_peer_messages::( + remote, + PeerSet::Validation, + &mut shared.0.lock().validation_peers, + v_messages, + &metrics, + ) + } else if expected_versions[PeerSet::Validation] == + Some(ValidationVersion::VStaging.into()) + { + handle_peer_messages::( + remote, + PeerSet::Validation, + &mut shared.0.lock().validation_peers, + v_messages, + &metrics, + ) + } else { + gum::warn!( + target: LOG_TARGET, + version = ?expected_versions[PeerSet::Validation], + "Major logic bug. Peer somehow has unsupported validation protocol version." + ); - versions - }; + never!("Only versions 1 and 2 are supported; peer set connection checked above; qed"); - gum::trace!( - target: LOG_TARGET, - action = "PeerMessage", - peerset = ?PeerSet::Collation, - ?peer, - ); - - let (events, reports) = - if expected_versions[PeerSet::Collation] == Some(CollationVersion::V1.into()) { - handle_peer_messages::( - peer, - PeerSet::Collation, - &mut shared.0.lock().collation_peers, - vec![notification.into()], - metrics, - ) - } else if expected_versions[PeerSet::Collation] == Some(CollationVersion::V2.into()) - { - handle_peer_messages::( - peer, - PeerSet::Collation, - &mut shared.0.lock().collation_peers, - vec![notification.into()], - metrics, - ) - } else { - gum::warn!( - target: LOG_TARGET, - version = ?expected_versions[PeerSet::Collation], - "Major logic bug. Peer somehow has unsupported collation protocol version." - ); + // If a peer somehow triggers this, we'll disconnect them + // eventually. + (Vec::new(), vec![UNCONNECTED_PEERSET_COST]) + }; - never!("Only versions 1 and 2 are supported; peer set connection checked above; qed"); + for report in reports { + network_service.report_peer(remote, report.into()); + } - // If a peer somehow triggers this, we'll disconnect them - // eventually. - (Vec::new(), vec![UNCONNECTED_PEERSET_COST]) - }; + dispatch_validation_events_to_all(events, &mut sender, &metrics).await; + } - for report in reports { - network_service.report_peer(peer, report.into()); - } + if !c_messages.is_empty() { + let (events, reports) = if expected_versions[PeerSet::Collation] == + Some(CollationVersion::V1.into()) + { + handle_peer_messages::( + remote, + PeerSet::Collation, + &mut shared.0.lock().collation_peers, + c_messages, + &metrics, + ) + } else if expected_versions[PeerSet::Collation] == + Some(CollationVersion::V2.into()) + { + handle_peer_messages::( + remote, + PeerSet::Collation, + &mut shared.0.lock().collation_peers, + c_messages, + &metrics, + ) + } else { + gum::warn!( + target: LOG_TARGET, + version = ?expected_versions[PeerSet::Collation], + "Major logic bug. Peer somehow has unsupported collation protocol version." + ); - dispatch_collation_events_to_all(events, sender).await; - }, - } -} + never!("Only versions 1 and 2 are supported; peer set connection checked above; qed"); -async fn handle_network_messages( - mut sender: impl overseer::NetworkBridgeRxSenderTrait, - mut network_service: impl Network, - mut authority_discovery_service: AD, - metrics: Metrics, - shared: Shared, - peerset_protocol_names: PeerSetProtocolNames, - mut validation_service: Box, - mut collation_service: Box, - mut notification_sinks: Arc>>>, -) -> Result<(), Error> -where - AD: validator_discovery::AuthorityDiscovery + Send, -{ - loop { - futures::select! { - event = validation_service.next_event().fuse() => match event { - Some(event) => handle_validation_message( - event, - &mut network_service, - &mut sender, - &mut authority_discovery_service, - &metrics, - &shared, - &peerset_protocol_names, - &mut validation_service, - &mut notification_sinks, - ).await, - None => return Err(Error::EventStreamConcluded), + // If a peer somehow triggers this, we'll disconnect them + // eventually. + (Vec::new(), vec![UNCONNECTED_PEERSET_COST]) + }; + + for report in reports { + network_service.report_peer(remote, report.into()); + } + + dispatch_collation_events_to_all(events, &mut sender).await; + } }, - event = collation_service.next_event().fuse() => match event { - Some(event) => handle_collation_message( - event, - &mut network_service, - &mut sender, - &mut authority_discovery_service, - &metrics, - &shared, - &peerset_protocol_names, - &mut collation_service, - &mut notification_sinks, - ).await, - None => return Err(Error::EventStreamConcluded), - } } } } @@ -730,15 +593,17 @@ where } #[overseer::contextbounds(NetworkBridgeRx, prefix = self::overseer)] -async fn run_incoming_orchestra_signals( +async fn run_incoming_orchestra_signals( mut ctx: Context, + mut network_service: N, mut authority_discovery_service: AD, shared: Shared, sync_oracle: Box, metrics: Metrics, - notification_sinks: Arc>>>, + peerset_protocol_names: PeerSetProtocolNames, ) -> Result<(), Error> where + N: Network, AD: validator_discovery::AuthorityDiscovery + Clone, { // This is kept sorted, descending, by block number. @@ -830,12 +695,13 @@ where mode = Mode::Active; update_our_view( + &mut network_service, &mut ctx, &live_heads, &shared, finalized_number, &metrics, - ¬ification_sinks, + &peerset_protocol_names, ); } } @@ -869,6 +735,7 @@ where async fn run_network_in( bridge: NetworkBridgeRx, mut ctx: Context, + network_stream: BoxStream<'static, NetworkEvent>, ) -> Result<(), Error> where N: Network, @@ -881,21 +748,16 @@ where sync_oracle, shared, peerset_protocol_names, - validation_service, - collation_service, - notification_sinks, } = bridge; let (task, network_event_handler) = handle_network_messages( ctx.sender().clone(), network_service.clone(), + network_stream, authority_discovery_service.clone(), metrics.clone(), shared.clone(), peerset_protocol_names.clone(), - validation_service, - collation_service, - notification_sinks.clone(), ) .remote_handle(); @@ -904,11 +766,12 @@ where let orchestra_signal_handler = run_incoming_orchestra_signals( ctx, + network_service, authority_discovery_service, shared, sync_oracle, metrics, - notification_sinks, + peerset_protocol_names, ); futures::pin_mut!(orchestra_signal_handler); @@ -928,14 +791,17 @@ fn construct_view( } #[overseer::contextbounds(NetworkBridgeRx, prefix = self::overseer)] -fn update_our_view( +fn update_our_view( + net: &mut Net, ctx: &mut Context, live_heads: &[ActivatedLeaf], shared: &Shared, finalized_number: BlockNumber, metrics: &Metrics, - notification_sinks: &Arc>>>, -) { + peerset_protocol_names: &PeerSetProtocolNames, +) where + Net: Network, +{ let new_view = construct_view(live_heads.iter().map(|v| v.hash), finalized_number); let (validation_peers, collation_peers) = { @@ -979,42 +845,47 @@ fn update_our_view( filter_by_peer_version(&validation_peers, ValidationVersion::V2.into()); let v2_collation_peers = filter_by_peer_version(&collation_peers, CollationVersion::V2.into()); - let v3_validation_peers = - filter_by_peer_version(&validation_peers, ValidationVersion::V3.into()); + let vstaging_validation_peers = + filter_by_peer_version(&validation_peers, ValidationVersion::VStaging.into()); send_validation_message_v1( + net, v1_validation_peers, + peerset_protocol_names, WireMessage::ViewUpdate(new_view.clone()), metrics, - notification_sinks, ); send_collation_message_v1( + net, v1_collation_peers, + peerset_protocol_names, WireMessage::ViewUpdate(new_view.clone()), metrics, - notification_sinks, ); send_validation_message_v2( + net, v2_validation_peers, + peerset_protocol_names, WireMessage::ViewUpdate(new_view.clone()), metrics, - notification_sinks, ); send_collation_message_v2( + net, v2_collation_peers, + peerset_protocol_names, WireMessage::ViewUpdate(new_view.clone()), metrics, - notification_sinks, ); - send_validation_message_v3( - v3_validation_peers, + send_validation_message_vstaging( + net, + vstaging_validation_peers, + peerset_protocol_names, WireMessage::ViewUpdate(new_view.clone()), metrics, - notification_sinks, ); let our_view = OurView::new( diff --git a/polkadot/node/network/bridge/src/rx/tests.rs b/polkadot/node/network/bridge/src/rx/tests.rs index 6847b8a7e24..f784e78a7f2 100644 --- a/polkadot/node/network/bridge/src/rx/tests.rs +++ b/polkadot/node/network/bridge/src/rx/tests.rs @@ -15,7 +15,7 @@ // along with Polkadot. If not, see . use super::*; -use futures::{channel::oneshot, executor}; +use futures::{channel::oneshot, executor, stream::BoxStream}; use overseer::jaeger; use polkadot_node_network_protocol::{self as net_protocol, OurView}; use polkadot_node_subsystem::messages::NetworkBridgeEvent; @@ -26,13 +26,10 @@ use parking_lot::Mutex; use std::{ collections::HashSet, sync::atomic::{AtomicBool, Ordering}, + task::Poll, }; -use sc_network::{ - service::traits::{Direction, MessageSink, NotificationService}, - IfDisconnected, Multiaddr, ObservedRole as SubstrateObservedRole, ProtocolName, - ReputationChange, Roles, -}; +use sc_network::{Event as NetworkEvent, IfDisconnected, ProtocolName, ReputationChange}; use polkadot_node_network_protocol::{ peer_set::PeerSetProtocolNames, @@ -50,8 +47,9 @@ use polkadot_node_subsystem_test_helpers::{ mock::new_leaf, SingleItemSink, SingleItemStream, TestSubsystemContextHandle, }; use polkadot_node_subsystem_util::metered; -use polkadot_primitives::{AuthorityDiscoveryId, Hash}; +use polkadot_primitives::{AuthorityDiscoveryId, CandidateHash, Hash}; +use sc_network::Multiaddr; use sp_keyring::Sr25519Keyring; use crate::{network::Network, validator_discovery::AuthorityDiscovery}; @@ -66,9 +64,10 @@ pub enum NetworkAction { WriteNotification(PeerId, PeerSet, Vec), } -// The subsystem's view of the network. +// The subsystem's view of the network - only supports a single call to `event_stream`. #[derive(Clone)] struct TestNetwork { + net_events: Arc>>>, action_tx: Arc>>, protocol_names: Arc, } @@ -80,42 +79,37 @@ struct TestAuthorityDiscovery; // of `NetworkAction`s. struct TestNetworkHandle { action_rx: metered::UnboundedMeteredReceiver, - validation_tx: SingleItemSink, - collation_tx: SingleItemSink, + net_tx: SingleItemSink, + protocol_names: PeerSetProtocolNames, } fn new_test_network( protocol_names: PeerSetProtocolNames, -) -> ( - TestNetwork, - TestNetworkHandle, - TestAuthorityDiscovery, - Box, - Box, -) { +) -> (TestNetwork, TestNetworkHandle, TestAuthorityDiscovery) { + let (net_tx, net_rx) = polkadot_node_subsystem_test_helpers::single_item_sink(); let (action_tx, action_rx) = metered::unbounded(); - let (validation_tx, validation_rx) = polkadot_node_subsystem_test_helpers::single_item_sink(); - let (collation_tx, collation_rx) = polkadot_node_subsystem_test_helpers::single_item_sink(); - let action_tx = Arc::new(Mutex::new(action_tx)); ( TestNetwork { - action_tx: action_tx.clone(), + net_events: Arc::new(Mutex::new(Some(net_rx))), + action_tx: Arc::new(Mutex::new(action_tx)), protocol_names: Arc::new(protocol_names.clone()), }, - TestNetworkHandle { action_rx, validation_tx, collation_tx }, + TestNetworkHandle { action_rx, net_tx, protocol_names }, TestAuthorityDiscovery, - Box::new(TestNotificationService::new( - PeerSet::Validation, - action_tx.clone(), - validation_rx, - )), - Box::new(TestNotificationService::new(PeerSet::Collation, action_tx, collation_rx)), ) } #[async_trait] impl Network for TestNetwork { + fn event_stream(&mut self) -> BoxStream<'static, NetworkEvent> { + self.net_events + .lock() + .take() + .expect("Subsystem made more than one call to `event_stream`") + .boxed() + } + async fn set_reserved_peers( &mut self, _protocol: ProtocolName, @@ -149,8 +143,7 @@ impl Network for TestNetwork { } fn disconnect_peer(&self, who: PeerId, protocol: ProtocolName) { - let (peer_set, version) = self.protocol_names.try_get_protocol(&protocol).unwrap(); - assert_eq!(version, peer_set.get_main_version()); + let (peer_set, _) = self.protocol_names.try_get_protocol(&protocol).unwrap(); self.action_tx .lock() @@ -158,10 +151,13 @@ impl Network for TestNetwork { .unwrap(); } - fn peer_role(&self, _peer_id: PeerId, handshake: Vec) -> Option { - Roles::decode_all(&mut &handshake[..]) - .ok() - .and_then(|role| Some(SubstrateObservedRole::from(role))) + fn write_notification(&self, who: PeerId, protocol: ProtocolName, message: Vec) { + let (peer_set, _) = self.protocol_names.try_get_protocol(&protocol).unwrap(); + + self.action_tx + .lock() + .unbounded_send(NetworkAction::WriteNotification(who, peer_set, message)) + .unwrap(); } } @@ -205,85 +201,35 @@ impl TestNetworkHandle { peer_set: PeerSet, role: ObservedRole, ) { - fn observed_role_to_handshake(role: &ObservedRole) -> Vec { - match role { - &ObservedRole::Light => Roles::LIGHT.encode(), - &ObservedRole::Authority => Roles::AUTHORITY.encode(), - &ObservedRole::Full => Roles::FULL.encode(), - } - } - - // because of how protocol negotiation works, if two peers support at least one common - // protocol, the protocol is negotiated over the main protocol (`ValidationVersion::V2`) but - // if either one of the peers used a fallback protocol for the negotiation (meaning they - // don't support the main protocol but some older version of it ), `negotiated_fallback` is - // set to that protocol. - let negotiated_fallback = match protocol_version { - ValidationVersion::V2 => None, - ValidationVersion::V1 => match peer_set { - PeerSet::Validation => Some(ProtocolName::from("/polkadot/validation/1")), - PeerSet::Collation => Some(ProtocolName::from("/polkadot/collation/1")), - }, - ValidationVersion::V3 => match peer_set { - PeerSet::Validation => Some(ProtocolName::from("/polkadot/validation/3")), - PeerSet::Collation => unreachable!(), - }, - }; - - match peer_set { - PeerSet::Validation => { - self.validation_tx - .send(NotificationEvent::NotificationStreamOpened { - peer, - direction: Direction::Inbound, - handshake: observed_role_to_handshake(&role), - negotiated_fallback, - }) - .await - .expect("subsystem concluded early"); - }, - PeerSet::Collation => { - self.collation_tx - .send(NotificationEvent::NotificationStreamOpened { - peer, - direction: Direction::Inbound, - handshake: observed_role_to_handshake(&role), - negotiated_fallback, - }) - .await - .expect("subsystem concluded early"); - }, - } + let protocol_version = ProtocolVersion::from(protocol_version); + self.send_network_event(NetworkEvent::NotificationStreamOpened { + remote: peer, + protocol: self.protocol_names.get_name(peer_set, protocol_version), + negotiated_fallback: None, + role: role.into(), + received_handshake: vec![], + }) + .await; } async fn disconnect_peer(&mut self, peer: PeerId, peer_set: PeerSet) { - match peer_set { - PeerSet::Validation => self - .validation_tx - .send(NotificationEvent::NotificationStreamClosed { peer }) - .await - .expect("subsystem concluded early"), - PeerSet::Collation => self - .collation_tx - .send(NotificationEvent::NotificationStreamClosed { peer }) - .await - .expect("subsystem concluded early"), - } + self.send_network_event(NetworkEvent::NotificationStreamClosed { + remote: peer, + protocol: self.protocol_names.get_main_name(peer_set), + }) + .await; } async fn peer_message(&mut self, peer: PeerId, peer_set: PeerSet, message: Vec) { - match peer_set { - PeerSet::Validation => self - .validation_tx - .send(NotificationEvent::NotificationReceived { peer, notification: message }) - .await - .expect("subsystem concluded early"), - PeerSet::Collation => self - .collation_tx - .send(NotificationEvent::NotificationReceived { peer, notification: message }) - .await - .expect("subsystem concluded early"), - } + self.send_network_event(NetworkEvent::NotificationsReceived { + remote: peer, + messages: vec![(self.protocol_names.get_main_name(peer_set), message.into())], + }) + .await; + } + + async fn send_network_event(&mut self, event: NetworkEvent) { + self.net_tx.send(event).await.expect("subsystem concluded early"); } } @@ -294,121 +240,6 @@ fn assert_network_actions_contains(actions: &[NetworkAction], action: &NetworkAc } } -struct TestNotificationService { - peer_set: PeerSet, - action_tx: Arc>>, - rx: SingleItemStream, -} - -impl std::fmt::Debug for TestNotificationService { - fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - Ok(()) - } -} - -impl TestNotificationService { - pub fn new( - peer_set: PeerSet, - action_tx: Arc>>, - rx: SingleItemStream, - ) -> Self { - Self { peer_set, action_tx, rx } - } -} - -struct TestMessageSink { - peer: PeerId, - peer_set: PeerSet, - action_tx: Arc>>, -} - -impl TestMessageSink { - fn new( - peer: PeerId, - peer_set: PeerSet, - action_tx: Arc>>, - ) -> TestMessageSink { - Self { peer, peer_set, action_tx } - } -} - -#[async_trait::async_trait] -impl MessageSink for TestMessageSink { - fn send_sync_notification(&self, notification: Vec) { - self.action_tx - .lock() - .unbounded_send(NetworkAction::WriteNotification( - self.peer, - self.peer_set, - notification, - )) - .unwrap(); - } - - async fn send_async_notification( - &self, - _notification: Vec, - ) -> Result<(), sc_network::error::Error> { - unimplemented!(); - } -} - -#[async_trait::async_trait] -impl NotificationService for TestNotificationService { - /// Instruct `Notifications` to open a new substream for `peer`. - async fn open_substream(&mut self, _peer: PeerId) -> Result<(), ()> { - unimplemented!(); - } - - /// Instruct `Notifications` to close substream for `peer`. - async fn close_substream(&mut self, _peer: PeerId) -> Result<(), ()> { - unimplemented!(); - } - - /// Send synchronous `notification` to `peer`. - fn send_sync_notification(&self, _peer: &PeerId, _notification: Vec) { - unimplemented!(); - } - - /// Send asynchronous `notification` to `peer`, allowing sender to exercise backpressure. - async fn send_async_notification( - &self, - _peer: &PeerId, - _notification: Vec, - ) -> Result<(), sc_network::error::Error> { - unimplemented!(); - } - - /// Set handshake for the notification protocol replacing the old handshake. - async fn set_handshake(&mut self, _handshake: Vec) -> Result<(), ()> { - unimplemented!(); - } - - fn try_set_handshake(&mut self, _handshake: Vec) -> Result<(), ()> { - unimplemented!(); - } - - /// Get next event from the `Notifications` event stream. - async fn next_event(&mut self) -> Option { - self.rx.next().await - } - - // Clone [`NotificationService`] - fn clone(&mut self) -> Result, ()> { - unimplemented!(); - } - - /// Get protocol name. - fn protocol(&self) -> &ProtocolName { - unimplemented!(); - } - - /// Get notification sink of the peer. - fn message_sink(&self, peer: &PeerId) -> Option> { - Some(Box::new(TestMessageSink::new(*peer, self.peer_set, self.action_tx.clone()))) - } -} - #[derive(Clone)] struct TestSyncOracle { is_major_syncing: Arc, @@ -504,11 +335,10 @@ fn test_harness>( let peerset_protocol_names = PeerSetProtocolNames::new(genesis_hash, fork_id); let pool = sp_core::testing::TaskExecutor::new(); - let (network, network_handle, discovery, validation_service, collation_service) = - new_test_network(peerset_protocol_names.clone()); + let (mut network, network_handle, discovery) = new_test_network(peerset_protocol_names.clone()); let (context, virtual_overseer) = polkadot_node_subsystem_test_helpers::make_subsystem_context(pool); - let notification_sinks = Arc::new(Mutex::new(HashMap::new())); + let network_stream = network.event_stream(); let shared = Shared::default(); let bridge = NetworkBridgeRx { @@ -518,12 +348,9 @@ fn test_harness>( sync_oracle, shared: shared.clone(), peerset_protocol_names, - validation_service, - collation_service, - notification_sinks, }; - let network_bridge = run_network_in(bridge, context) + let network_bridge = run_network_in(bridge, context, network_stream) .map_err(|_| panic!("subsystem execution failed")) .map(|_| ()); @@ -1115,6 +942,8 @@ fn relays_collation_protocol_messages() { .await; } + // peer A gets reported for sending a collation message. + let collator_protocol_message = protocol_v1::CollatorProtocolMessage::Declare( Sr25519Keyring::Alice.public().into(), Default::default(), @@ -1124,23 +953,19 @@ fn relays_collation_protocol_messages() { let message_v1 = protocol_v1::CollationProtocol::CollatorProtocol(collator_protocol_message.clone()); - // peer A gets reported for sending a collation message. - // NOTE: this is not possible since peer A cannot send - // a collation message if it has not opened a collation protocol - - // network_handle - // .peer_message( - // peer_a, - // PeerSet::Collation, - // WireMessage::ProtocolMessage(message_v1.clone()).encode(), - // ) - // .await; - - // let actions = network_handle.next_network_actions(3).await; - // assert_network_actions_contains( - // &actions, - // &NetworkAction::ReputationChange(peer_a, UNCONNECTED_PEERSET_COST.into()), - // ); + network_handle + .peer_message( + peer_a, + PeerSet::Collation, + WireMessage::ProtocolMessage(message_v1.clone()).encode(), + ) + .await; + + let actions = network_handle.next_network_actions(3).await; + assert_network_actions_contains( + &actions, + &NetworkAction::ReputationChange(peer_a, UNCONNECTED_PEERSET_COST.into()), + ); // peer B has the message relayed. @@ -1387,7 +1212,7 @@ fn our_view_updates_decreasing_order_and_limited_to_max() { fn network_protocol_versioning_view_update() { let (oracle, handle) = make_sync_oracle(false); test_harness(Box::new(oracle), |test_harness| async move { - let TestHarness { mut network_handle, mut virtual_overseer, shared } = test_harness; + let TestHarness { mut network_handle, mut virtual_overseer, .. } = test_harness; let peer_ids: Vec<_> = (0..4).map(|_| PeerId::random()).collect(); let peers = [ @@ -1406,22 +1231,12 @@ fn network_protocol_versioning_view_update() { handle.await_mode_switch().await; - let mut total_validation_peers = 0; - let mut total_collation_peers = 0; - for &(peer_id, peer_set, version) in &peers { network_handle .connect_peer(peer_id, version, peer_set, ObservedRole::Full) .await; - - match peer_set { - PeerSet::Validation => total_validation_peers += 1, - PeerSet::Collation => total_collation_peers += 1, - } } - await_peer_connections(&shared, total_validation_peers, total_collation_peers).await; - let view = view![head]; let actions = network_handle.next_network_actions(4).await; @@ -1433,8 +1248,8 @@ fn network_protocol_versioning_view_update() { ValidationVersion::V2 => WireMessage::::ViewUpdate(view.clone()) .encode(), - ValidationVersion::V3 => - WireMessage::::ViewUpdate(view.clone()) + ValidationVersion::VStaging => + WireMessage::::ViewUpdate(view.clone()) .encode(), }; assert_network_actions_contains( @@ -1449,19 +1264,15 @@ fn network_protocol_versioning_view_update() { #[test] fn network_protocol_versioning_subsystem_msg() { - use polkadot_primitives::CandidateHash; - use std::task::Poll; - let (oracle, _handle) = make_sync_oracle(false); test_harness(Box::new(oracle), |test_harness| async move { - let TestHarness { mut network_handle, mut virtual_overseer, shared } = test_harness; + let TestHarness { mut network_handle, mut virtual_overseer, .. } = test_harness; let peer = PeerId::random(); network_handle .connect_peer(peer, ValidationVersion::V2, PeerSet::Validation, ObservedRole::Full) .await; - await_peer_connections(&shared, 1, 0).await; // bridge will inform about all connected peers. { @@ -1469,7 +1280,7 @@ fn network_protocol_versioning_subsystem_msg() { NetworkBridgeEvent::PeerConnected( peer, ObservedRole::Full, - ValidationVersion::V3.into(), + ValidationVersion::V2.into(), None, ), &mut virtual_overseer, @@ -1484,9 +1295,9 @@ fn network_protocol_versioning_subsystem_msg() { } let approval_distribution_message = - protocol_v3::ApprovalDistributionMessage::Approvals(Vec::new()); + protocol_v2::ApprovalDistributionMessage::Approvals(Vec::new()); - let msg = protocol_v3::ValidationProtocol::ApprovalDistribution( + let msg = protocol_v2::ValidationProtocol::ApprovalDistribution( approval_distribution_message.clone(), ); @@ -1502,7 +1313,7 @@ fn network_protocol_versioning_subsystem_msg() { virtual_overseer.recv().await, AllMessages::ApprovalDistribution( ApprovalDistributionMessage::NetworkBridgeUpdate( - NetworkBridgeEvent::PeerMessage(p, Versioned::V3(m)) + NetworkBridgeEvent::PeerMessage(p, Versioned::V2(m)) ) ) => { assert_eq!(p, peer); @@ -1536,7 +1347,7 @@ fn network_protocol_versioning_subsystem_msg() { virtual_overseer.recv().await, AllMessages::StatementDistribution( StatementDistributionMessage::NetworkBridgeUpdate( - NetworkBridgeEvent::PeerMessage(p, Versioned::V3(m)) + NetworkBridgeEvent::PeerMessage(p, Versioned::V2(m)) ) ) => { assert_eq!(p, peer); diff --git a/polkadot/node/network/bridge/src/tx/mod.rs b/polkadot/node/network/bridge/src/tx/mod.rs index 22802608e1d..5f222ad59c7 100644 --- a/polkadot/node/network/bridge/src/tx/mod.rs +++ b/polkadot/node/network/bridge/src/tx/mod.rs @@ -32,7 +32,7 @@ use polkadot_node_subsystem::{ /// To be passed to [`FullNetworkConfiguration::add_notification_protocol`](). pub use polkadot_node_network_protocol::peer_set::{peer_sets_info, IsAuthority}; use polkadot_node_network_protocol::request_response::Requests; -use sc_network::{MessageSink, ReputationChange}; +use sc_network::ReputationChange; use crate::validator_discovery; @@ -41,7 +41,7 @@ use crate::validator_discovery; /// Defines the `Network` trait with an implementation for an `Arc`. use crate::network::{ send_collation_message_v1, send_collation_message_v2, send_validation_message_v1, - send_validation_message_v2, send_validation_message_v3, Network, + send_validation_message_v2, send_validation_message_vstaging, Network, }; use crate::metrics::Metrics; @@ -60,7 +60,6 @@ pub struct NetworkBridgeTx { metrics: Metrics, req_protocol_names: ReqProtocolNames, peerset_protocol_names: PeerSetProtocolNames, - notification_sinks: Arc>>>, } impl NetworkBridgeTx { @@ -75,7 +74,6 @@ impl NetworkBridgeTx { metrics: Metrics, req_protocol_names: ReqProtocolNames, peerset_protocol_names: PeerSetProtocolNames, - notification_sinks: Arc>>>, ) -> Self { Self { network_service, @@ -83,7 +81,6 @@ impl NetworkBridgeTx { metrics, req_protocol_names, peerset_protocol_names, - notification_sinks, } } } @@ -110,7 +107,6 @@ async fn handle_subsystem_messages( metrics: Metrics, req_protocol_names: ReqProtocolNames, peerset_protocol_names: PeerSetProtocolNames, - notification_sinks: Arc>>>, ) -> Result<(), Error> where N: Network, @@ -134,7 +130,6 @@ where &metrics, &req_protocol_names, &peerset_protocol_names, - ¬ification_sinks, ) .await; }, @@ -145,14 +140,13 @@ where #[overseer::contextbounds(NetworkBridgeTx, prefix = self::overseer)] async fn handle_incoming_subsystem_communication( _ctx: &mut Context, - network_service: N, + mut network_service: N, validator_discovery: &mut validator_discovery::Service, mut authority_discovery_service: AD, msg: NetworkBridgeTxMessage, metrics: &Metrics, req_protocol_names: &ReqProtocolNames, peerset_protocol_names: &PeerSetProtocolNames, - notification_sinks: &Arc>>>, ) -> (N, AD) where N: Network, @@ -200,22 +194,25 @@ where match msg { Versioned::V1(msg) => send_validation_message_v1( + &mut network_service, peers, + peerset_protocol_names, WireMessage::ProtocolMessage(msg), &metrics, - notification_sinks, ), - Versioned::V3(msg) => send_validation_message_v3( + Versioned::VStaging(msg) => send_validation_message_vstaging( + &mut network_service, peers, + peerset_protocol_names, WireMessage::ProtocolMessage(msg), &metrics, - notification_sinks, ), Versioned::V2(msg) => send_validation_message_v2( + &mut network_service, peers, + peerset_protocol_names, WireMessage::ProtocolMessage(msg), &metrics, - notification_sinks, ), } }, @@ -230,22 +227,25 @@ where for (peers, msg) in msgs { match msg { Versioned::V1(msg) => send_validation_message_v1( + &mut network_service, peers, + peerset_protocol_names, WireMessage::ProtocolMessage(msg), &metrics, - notification_sinks, ), - Versioned::V3(msg) => send_validation_message_v3( + Versioned::VStaging(msg) => send_validation_message_vstaging( + &mut network_service, peers, + peerset_protocol_names, WireMessage::ProtocolMessage(msg), &metrics, - notification_sinks, ), Versioned::V2(msg) => send_validation_message_v2( + &mut network_service, peers, + peerset_protocol_names, WireMessage::ProtocolMessage(msg), &metrics, - notification_sinks, ), } } @@ -259,16 +259,18 @@ where match msg { Versioned::V1(msg) => send_collation_message_v1( + &mut network_service, peers, + peerset_protocol_names, WireMessage::ProtocolMessage(msg), &metrics, - notification_sinks, ), - Versioned::V2(msg) | Versioned::V3(msg) => send_collation_message_v2( + Versioned::V2(msg) | Versioned::VStaging(msg) => send_collation_message_v2( + &mut network_service, peers, + peerset_protocol_names, WireMessage::ProtocolMessage(msg), &metrics, - notification_sinks, ), } }, @@ -282,16 +284,18 @@ where for (peers, msg) in msgs { match msg { Versioned::V1(msg) => send_collation_message_v1( + &mut network_service, peers, + peerset_protocol_names, WireMessage::ProtocolMessage(msg), &metrics, - notification_sinks, ), - Versioned::V2(msg) | Versioned::V3(msg) => send_collation_message_v2( + Versioned::V2(msg) | Versioned::VStaging(msg) => send_collation_message_v2( + &mut network_service, peers, + peerset_protocol_names, WireMessage::ProtocolMessage(msg), &metrics, - notification_sinks, ), } } @@ -385,7 +389,6 @@ where metrics, req_protocol_names, peerset_protocol_names, - notification_sinks, } = bridge; handle_subsystem_messages( @@ -395,7 +398,6 @@ where metrics, req_protocol_names, peerset_protocol_names, - notification_sinks, ) .await?; diff --git a/polkadot/node/network/bridge/src/tx/tests.rs b/polkadot/node/network/bridge/src/tx/tests.rs index c3cf0f322f6..1a2d9a7a424 100644 --- a/polkadot/node/network/bridge/src/tx/tests.rs +++ b/polkadot/node/network/bridge/src/tx/tests.rs @@ -15,18 +15,15 @@ // along with Polkadot. If not, see . use super::*; -use futures::executor; +use futures::{executor, stream::BoxStream}; use polkadot_node_subsystem_util::TimeoutExt; use async_trait::async_trait; use parking_lot::Mutex; use std::collections::HashSet; -use sc_network::{ - IfDisconnected, ObservedRole as SubstrateObservedRole, ProtocolName, ReputationChange, Roles, -}; +use sc_network::{Event as NetworkEvent, IfDisconnected, ProtocolName, ReputationChange}; -use parity_scale_codec::DecodeAll; use polkadot_node_network_protocol::{ peer_set::{PeerSetProtocolNames, ValidationVersion}, request_response::{outgoing::Requests, ReqProtocolNames}, @@ -54,9 +51,10 @@ pub enum NetworkAction { WriteNotification(PeerId, PeerSet, Vec), } -// The subsystem's view of the network. +// The subsystem's view of the network - only supports a single call to `event_stream`. #[derive(Clone)] struct TestNetwork { + net_events: Arc>>>, action_tx: Arc>>, peerset_protocol_names: Arc, } @@ -68,78 +66,37 @@ struct TestAuthorityDiscovery; // of `NetworkAction`s. struct TestNetworkHandle { action_rx: metered::UnboundedMeteredReceiver, - _peerset_protocol_names: PeerSetProtocolNames, - notification_sinks: Arc>>>, - action_tx: Arc>>, -} - -struct TestMessageSink { - peer: PeerId, - peer_set: PeerSet, - action_tx: Arc>>, -} - -impl TestMessageSink { - fn new( - peer: PeerId, - peer_set: PeerSet, - action_tx: Arc>>, - ) -> TestMessageSink { - Self { peer, peer_set, action_tx } - } -} - -#[async_trait::async_trait] -impl MessageSink for TestMessageSink { - fn send_sync_notification(&self, notification: Vec) { - self.action_tx - .lock() - .unbounded_send(NetworkAction::WriteNotification( - self.peer, - self.peer_set, - notification, - )) - .unwrap(); - } - - async fn send_async_notification( - &self, - _notification: Vec, - ) -> Result<(), sc_network::error::Error> { - unimplemented!(); - } + net_tx: metered::MeteredSender, + peerset_protocol_names: PeerSetProtocolNames, } fn new_test_network( peerset_protocol_names: PeerSetProtocolNames, -) -> ( - TestNetwork, - TestNetworkHandle, - TestAuthorityDiscovery, - Arc>>>, -) { +) -> (TestNetwork, TestNetworkHandle, TestAuthorityDiscovery) { + let (net_tx, net_rx) = metered::channel(10); let (action_tx, action_rx) = metered::unbounded(); - let notification_sinks = Arc::new(Mutex::new(HashMap::new())); - let action_tx = Arc::new(Mutex::new(action_tx)); ( TestNetwork { - action_tx: action_tx.clone(), + net_events: Arc::new(Mutex::new(Some(net_rx))), + action_tx: Arc::new(Mutex::new(action_tx)), peerset_protocol_names: Arc::new(peerset_protocol_names.clone()), }, - TestNetworkHandle { - action_rx, - _peerset_protocol_names: peerset_protocol_names, - action_tx, - notification_sinks: notification_sinks.clone(), - }, + TestNetworkHandle { action_rx, net_tx, peerset_protocol_names }, TestAuthorityDiscovery, - notification_sinks, ) } #[async_trait] impl Network for TestNetwork { + fn event_stream(&mut self) -> BoxStream<'static, NetworkEvent> { + self.net_events + .lock() + .take() + .expect("Subsystem made more than one call to `event_stream`") + .boxed() + } + async fn set_reserved_peers( &mut self, _protocol: ProtocolName, @@ -173,8 +130,7 @@ impl Network for TestNetwork { } fn disconnect_peer(&self, who: PeerId, protocol: ProtocolName) { - let (peer_set, version) = self.peerset_protocol_names.try_get_protocol(&protocol).unwrap(); - assert_eq!(version, peer_set.get_main_version()); + let (peer_set, _) = self.peerset_protocol_names.try_get_protocol(&protocol).unwrap(); self.action_tx .lock() @@ -182,10 +138,13 @@ impl Network for TestNetwork { .unwrap(); } - fn peer_role(&self, _peer_id: PeerId, handshake: Vec) -> Option { - Roles::decode_all(&mut &handshake[..]) - .ok() - .and_then(|role| Some(SubstrateObservedRole::from(role))) + fn write_notification(&self, who: PeerId, protocol: ProtocolName, message: Vec) { + let (peer_set, _) = self.peerset_protocol_names.try_get_protocol(&protocol).unwrap(); + + self.action_tx + .lock() + .unbounded_send(NetworkAction::WriteNotification(who, peer_set, message)) + .unwrap(); } } @@ -215,14 +174,23 @@ impl TestNetworkHandle { async fn connect_peer( &mut self, peer: PeerId, - _protocol_version: ValidationVersion, + protocol_version: ValidationVersion, peer_set: PeerSet, - _role: ObservedRole, + role: ObservedRole, ) { - self.notification_sinks.lock().insert( - (peer_set, peer), - Box::new(TestMessageSink::new(peer, peer_set, self.action_tx.clone())), - ); + let protocol_version = ProtocolVersion::from(protocol_version); + self.send_network_event(NetworkEvent::NotificationStreamOpened { + remote: peer, + protocol: self.peerset_protocol_names.get_name(peer_set, protocol_version), + negotiated_fallback: None, + role: role.into(), + received_handshake: vec![], + }) + .await; + } + + async fn send_network_event(&mut self, event: NetworkEvent) { + self.net_tx.send(event).await.expect("subsystem concluded early"); } } @@ -240,8 +208,7 @@ fn test_harness>(test: impl FnOnce(TestHarne let peerset_protocol_names = PeerSetProtocolNames::new(genesis_hash, fork_id); let pool = sp_core::testing::TaskExecutor::new(); - let (network, network_handle, discovery, network_notification_sinks) = - new_test_network(peerset_protocol_names.clone()); + let (network, network_handle, discovery) = new_test_network(peerset_protocol_names.clone()); let (context, virtual_overseer) = polkadot_node_subsystem_test_helpers::make_subsystem_context(pool); @@ -252,7 +219,6 @@ fn test_harness>(test: impl FnOnce(TestHarne Metrics(None), req_protocol_names, peerset_protocol_names, - network_notification_sinks, ); let network_bridge_out_fut = run_network_out(bridge_out, context) @@ -398,9 +364,9 @@ fn network_protocol_versioning_send() { approval_distribution_message.clone(), ); - // only `peer_ids[0]` opened the validation protocol v2 - // so only they will be sent a notification - let receivers = vec![peer_ids[0]]; + // Note that bridge doesn't ensure neither peer's protocol version + // or peer set match the message. + let receivers = vec![peer_ids[0], peer_ids[3]]; virtual_overseer .send(FromOrchestra::Communication { msg: NetworkBridgeTxMessage::SendValidationMessage( @@ -440,9 +406,7 @@ fn network_protocol_versioning_send() { let msg = protocol_v2::CollationProtocol::CollatorProtocol(collator_protocol_message.clone()); - // only `peer_ids[0]` opened the collation protocol v2 - // so only they will be sent a notification - let receivers = vec![peer_ids[1]]; + let receivers = vec![peer_ids[1], peer_ids[2]]; virtual_overseer .send(FromOrchestra::Communication { diff --git a/polkadot/node/network/bridge/src/validator_discovery.rs b/polkadot/node/network/bridge/src/validator_discovery.rs index b11af8a8a08..86e861fbc5b 100644 --- a/polkadot/node/network/bridge/src/validator_discovery.rs +++ b/polkadot/node/network/bridge/src/validator_discovery.rs @@ -169,12 +169,13 @@ mod tests { use crate::network::Network; use async_trait::async_trait; + use futures::stream::BoxStream; use polkadot_node_network_protocol::{ request_response::{outgoing::Requests, ReqProtocolNames}, PeerId, }; use polkadot_primitives::Hash; - use sc_network::{IfDisconnected, ProtocolName, ReputationChange}; + use sc_network::{Event as NetworkEvent, IfDisconnected, ProtocolName, ReputationChange}; use sp_keyring::Sr25519Keyring; use std::collections::{HashMap, HashSet}; @@ -223,6 +224,10 @@ mod tests { #[async_trait] impl Network for TestNetwork { + fn event_stream(&mut self) -> BoxStream<'static, NetworkEvent> { + panic!() + } + async fn set_reserved_peers( &mut self, _protocol: ProtocolName, @@ -258,11 +263,7 @@ mod tests { panic!() } - fn peer_role( - &self, - _peer_id: PeerId, - _handshake: Vec, - ) -> Option { + fn write_notification(&self, _: PeerId, _: ProtocolName, _: Vec) { panic!() } } diff --git a/polkadot/node/network/collator-protocol/Cargo.toml b/polkadot/node/network/collator-protocol/Cargo.toml index bcf4f74132f..367a97f35d9 100644 --- a/polkadot/node/network/collator-protocol/Cargo.toml +++ b/polkadot/node/network/collator-protocol/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] bitvec = { version = "1.0.1", default-features = false, features = ["alloc"] } futures = "0.3.21" 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 8fb0bb21544..b3a396e1be3 100644 --- a/polkadot/node/network/collator-protocol/src/collator_side/mod.rs +++ b/polkadot/node/network/collator-protocol/src/collator_side/mod.rs @@ -882,7 +882,7 @@ async fn handle_incoming_peer_message( match msg { Versioned::V1(V1::Declare(..)) | Versioned::V2(V2::Declare(..)) | - Versioned::V3(V2::Declare(..)) => { + Versioned::VStaging(V2::Declare(..)) => { gum::trace!( target: LOG_TARGET, ?origin, @@ -895,7 +895,7 @@ async fn handle_incoming_peer_message( }, Versioned::V1(V1::AdvertiseCollation(_)) | Versioned::V2(V2::AdvertiseCollation { .. }) | - Versioned::V3(V2::AdvertiseCollation { .. }) => { + Versioned::VStaging(V2::AdvertiseCollation { .. }) => { gum::trace!( target: LOG_TARGET, ?origin, @@ -911,7 +911,7 @@ async fn handle_incoming_peer_message( }, Versioned::V1(V1::CollationSeconded(relay_parent, statement)) | Versioned::V2(V2::CollationSeconded(relay_parent, statement)) | - Versioned::V3(V2::CollationSeconded(relay_parent, statement)) => { + Versioned::VStaging(V2::CollationSeconded(relay_parent, statement)) => { if !matches!(statement.unchecked_payload(), Statement::Seconded(_)) { gum::warn!( target: LOG_TARGET, 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 1b1194c7270..7dd2287dab6 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 @@ -45,9 +45,8 @@ 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::{ - vstaging::NodeFeatures, AuthorityDiscoveryId, CollatorPair, ExecutorParams, GroupIndex, - GroupRotationInfo, IndexedVec, ScheduledCore, SessionIndex, SessionInfo, ValidatorId, - ValidatorIndex, + AuthorityDiscoveryId, CollatorPair, ExecutorParams, GroupIndex, GroupRotationInfo, IndexedVec, + ScheduledCore, SessionIndex, SessionInfo, ValidatorId, ValidatorIndex, }; use polkadot_primitives_test_helpers::TestCandidateBuilder; use test_helpers::mock::new_leaf; @@ -407,12 +406,7 @@ async fn distribute_collation_with_receipt( tx.send(Ok(Some(ExecutorParams::default()))).unwrap(); }, - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, - RuntimeApiRequest::NodeFeatures(_, si_tx), - )) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - }, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( _relay_parent, RuntimeApiRequest::ValidatorGroups(tx), 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 48ad3c711a6..20b3b9ea1d2 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/mod.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/mod.rs @@ -777,7 +777,7 @@ async fn process_incoming_peer_message( match msg { Versioned::V1(V1::Declare(collator_id, para_id, signature)) | Versioned::V2(V2::Declare(collator_id, para_id, signature)) | - Versioned::V3(V2::Declare(collator_id, para_id, signature)) => { + Versioned::VStaging(V2::Declare(collator_id, para_id, signature)) => { if collator_peer_id(&state.peer_data, &collator_id).is_some() { modify_reputation( &mut state.reputation, @@ -894,7 +894,7 @@ async fn process_incoming_peer_message( candidate_hash, parent_head_data_hash, }) | - Versioned::V3(V2::AdvertiseCollation { + Versioned::VStaging(V2::AdvertiseCollation { relay_parent, candidate_hash, parent_head_data_hash, @@ -923,7 +923,7 @@ async fn process_incoming_peer_message( }, Versioned::V1(V1::CollationSeconded(..)) | Versioned::V2(V2::CollationSeconded(..)) | - Versioned::V3(V2::CollationSeconded(..)) => { + Versioned::VStaging(V2::CollationSeconded(..)) => { gum::warn!( target: LOG_TARGET, peer_id = ?origin, diff --git a/polkadot/node/network/dispute-distribution/Cargo.toml b/polkadot/node/network/dispute-distribution/Cargo.toml index 15a0edd3661..f4ea358c41b 100644 --- a/polkadot/node/network/dispute-distribution/Cargo.toml +++ b/polkadot/node/network/dispute-distribution/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] futures = "0.3.21" futures-timer = "3.0.2" diff --git a/polkadot/node/network/dispute-distribution/src/tests/mod.rs b/polkadot/node/network/dispute-distribution/src/tests/mod.rs index a3520bf35f8..96f045cbf76 100644 --- a/polkadot/node/network/dispute-distribution/src/tests/mod.rs +++ b/polkadot/node/network/dispute-distribution/src/tests/mod.rs @@ -57,8 +57,8 @@ use polkadot_node_subsystem_test_helpers::{ subsystem_test_harness, TestSubsystemContextHandle, }; use polkadot_primitives::{ - vstaging::NodeFeatures, AuthorityDiscoveryId, CandidateHash, CandidateReceipt, ExecutorParams, - Hash, SessionIndex, SessionInfo, + AuthorityDiscoveryId, CandidateHash, CandidateReceipt, ExecutorParams, Hash, SessionIndex, + SessionInfo, }; use self::mock::{ @@ -646,16 +646,6 @@ async fn nested_network_dispute_request<'a, F, O>( }, unexpected => panic!("Unexpected message {:?}", unexpected), } - - match handle.recv().await { - AllMessages::RuntimeApi(RuntimeApiMessage::Request( - _, - RuntimeApiRequest::NodeFeatures(_, si_tx), - )) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - }, - unexpected => panic!("Unexpected message {:?}", unexpected), - } } // Import should get initiated: @@ -783,14 +773,6 @@ async fn activate_leaf( tx.send(Ok(Some(ExecutorParams::default()))).expect("Receiver should stay alive."); } ); - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); } assert_matches!( diff --git a/polkadot/node/network/gossip-support/Cargo.toml b/polkadot/node/network/gossip-support/Cargo.toml index e4d6ac601c3..a9f68261add 100644 --- a/polkadot/node/network/gossip-support/Cargo.toml +++ b/polkadot/node/network/gossip-support/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto" } sp-keystore = { path = "../../../../substrate/primitives/keystore" } @@ -38,4 +35,3 @@ polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } assert_matches = "1.4.0" async-trait = "0.1.57" lazy_static = "1.4.0" -quickcheck = "1.0.3" diff --git a/polkadot/node/network/gossip-support/src/lib.rs b/polkadot/node/network/gossip-support/src/lib.rs index 22417795d5e..674c86e5ce2 100644 --- a/polkadot/node/network/gossip-support/src/lib.rs +++ b/polkadot/node/network/gossip-support/src/lib.rs @@ -32,7 +32,7 @@ use std::{ use futures::{channel::oneshot, select, FutureExt as _}; use futures_timer::Delay; -use rand::{Rng, SeedableRng}; +use rand::{seq::SliceRandom as _, SeedableRng}; use rand_chacha::ChaCha20Rng; use sc_network::{config::parse_addr, Multiaddr}; @@ -477,7 +477,7 @@ where match message { Versioned::V1(m) => match m {}, Versioned::V2(m) => match m {}, - Versioned::V3(m) => match m {}, + Versioned::VStaging(m) => match m {}, } }, } @@ -607,7 +607,7 @@ async fn update_gossip_topology( .map(|(i, a)| (a.clone(), ValidatorIndex(i as _))) .collect(); - fisher_yates_shuffle(&mut rng, &mut canonical_shuffling[..]); + canonical_shuffling.shuffle(&mut rng); for (i, (_, validator_index)) in canonical_shuffling.iter().enumerate() { shuffled_indices[validator_index.0 as usize] = i; } @@ -627,16 +627,6 @@ async fn update_gossip_topology( Ok(()) } -// Durstenfeld algorithm for the Fisher-Yates shuffle -// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm -fn fisher_yates_shuffle(rng: &mut R, items: &mut [T]) { - for i in (1..items.len()).rev() { - // invariant: elements with index > i have been locked in place. - let index = rng.gen_range(0u32..(i as u32 + 1)); - items.swap(i, index as usize); - } -} - #[overseer::subsystem(GossipSupport, error = SubsystemError, prefix = self::overseer)] impl GossipSupport where diff --git a/polkadot/node/network/gossip-support/src/tests.rs b/polkadot/node/network/gossip-support/src/tests.rs index e5ee101c31d..2e909bb0a67 100644 --- a/polkadot/node/network/gossip-support/src/tests.rs +++ b/polkadot/node/network/gossip-support/src/tests.rs @@ -22,8 +22,6 @@ use assert_matches::assert_matches; use async_trait::async_trait; use futures::{executor, future, Future}; use lazy_static::lazy_static; -use quickcheck::quickcheck; -use rand::seq::SliceRandom as _; use sc_network::multiaddr::Protocol; use sp_authority_discovery::AuthorityPair as AuthorityDiscoveryPair; @@ -712,23 +710,3 @@ fn issues_a_connection_request_when_last_request_was_mostly_unresolved() { assert_eq!(state.last_session_index, Some(1)); assert!(state.last_failure.is_none()); } - -// note: this test was added at a time where the default `rand::SliceRandom::shuffle` -// function was used to shuffle authorities for the topology and ensures backwards compatibility. -// -// in the same commit, an explicit fisher-yates implementation was added in place of the unspecified -// behavior of that function. If this test begins to fail at some point in the future, it can simply -// be removed as the desired behavior has been preserved. -quickcheck! { - fn rng_shuffle_equals_fisher_yates(x: Vec, seed_base: u8) -> bool { - let mut rng1: ChaCha20Rng = SeedableRng::from_seed([seed_base; 32]); - let mut rng2: ChaCha20Rng = SeedableRng::from_seed([seed_base; 32]); - - let mut data1 = x.clone(); - let mut data2 = x; - - data1.shuffle(&mut rng1); - crate::fisher_yates_shuffle(&mut rng2, &mut data2[..]); - data1 == data2 - } -} diff --git a/polkadot/node/network/protocol/Cargo.toml b/polkadot/node/network/protocol/Cargo.toml index 1aded1f3c07..c33b9eae325 100644 --- a/polkadot/node/network/protocol/Cargo.toml +++ b/polkadot/node/network/protocol/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "Primitives types for the Node-side" -[lints] -workspace = true - [dependencies] async-channel = "1.8.0" async-trait = "0.1.57" @@ -30,3 +27,6 @@ bitvec = "1" [dev-dependencies] rand_chacha = "0.3.1" + +[features] +network-protocol-staging = [] diff --git a/polkadot/node/network/protocol/src/grid_topology.rs b/polkadot/node/network/protocol/src/grid_topology.rs index 8bd9adbc17c..99dd513c4d7 100644 --- a/polkadot/node/network/protocol/src/grid_topology.rs +++ b/polkadot/node/network/protocol/src/grid_topology.rs @@ -73,20 +73,12 @@ pub struct SessionGridTopology { shuffled_indices: Vec, /// The canonical shuffling of validators for the session. canonical_shuffling: Vec, - /// The list of peer-ids in an efficient way to search. - peer_ids: HashSet, } impl SessionGridTopology { /// Create a new session grid topology. pub fn new(shuffled_indices: Vec, canonical_shuffling: Vec) -> Self { - let mut peer_ids = HashSet::new(); - for peer_info in canonical_shuffling.iter() { - for peer_id in peer_info.peer_ids.iter() { - peer_ids.insert(*peer_id); - } - } - SessionGridTopology { shuffled_indices, canonical_shuffling, peer_ids } + SessionGridTopology { shuffled_indices, canonical_shuffling } } /// Produces the outgoing routing logic for a particular peer. @@ -119,11 +111,6 @@ impl SessionGridTopology { Some(grid_subset) } - - /// Tells if a given peer id is validator in a session - pub fn is_validator(&self, peer: &PeerId) -> bool { - self.peer_ids.contains(peer) - } } struct MatrixNeighbors { @@ -286,11 +273,6 @@ impl SessionGridTopologyEntry { pub fn get(&self) -> &SessionGridTopology { &self.topology } - - /// Tells if a given peer id is validator in a session - pub fn is_validator(&self, peer: &PeerId) -> bool { - self.topology.is_validator(peer) - } } /// A set of topologies indexed by session @@ -365,7 +347,6 @@ impl Default for SessionBoundGridTopologyStorage { topology: SessionGridTopology { shuffled_indices: Vec::new(), canonical_shuffling: Vec::new(), - peer_ids: Default::default(), }, local_neighbors: GridNeighbors::empty(), }, diff --git a/polkadot/node/network/protocol/src/lib.rs b/polkadot/node/network/protocol/src/lib.rs index ae72230ee43..9aeeb98ea9d 100644 --- a/polkadot/node/network/protocol/src/lib.rs +++ b/polkadot/node/network/protocol/src/lib.rs @@ -253,29 +253,29 @@ impl View { /// A protocol-versioned type. #[derive(Debug, Clone, PartialEq, Eq)] -pub enum Versioned { +pub enum Versioned { /// V1 type. V1(V1), /// V2 type. V2(V2), - /// V3 type - V3(V3), + /// VStaging type + VStaging(VStaging), } -impl Versioned<&'_ V1, &'_ V2, &'_ V3> { +impl Versioned<&'_ V1, &'_ V2, &'_ VStaging> { /// Convert to a fully-owned version of the message. - pub fn clone_inner(&self) -> Versioned { + pub fn clone_inner(&self) -> Versioned { match *self { Versioned::V1(inner) => Versioned::V1(inner.clone()), Versioned::V2(inner) => Versioned::V2(inner.clone()), - Versioned::V3(inner) => Versioned::V3(inner.clone()), + Versioned::VStaging(inner) => Versioned::VStaging(inner.clone()), } } } /// All supported versions of the validation protocol message. pub type VersionedValidationProtocol = - Versioned; + Versioned; impl From for VersionedValidationProtocol { fn from(v1: v1::ValidationProtocol) -> Self { @@ -289,9 +289,9 @@ impl From for VersionedValidationProtocol { } } -impl From for VersionedValidationProtocol { - fn from(v3: v3::ValidationProtocol) -> Self { - VersionedValidationProtocol::V3(v3) +impl From for VersionedValidationProtocol { + fn from(vstaging: vstaging::ValidationProtocol) -> Self { + VersionedValidationProtocol::VStaging(vstaging) } } @@ -317,7 +317,7 @@ macro_rules! impl_versioned_full_protocol_from { match versioned_from { Versioned::V1(x) => Versioned::V1(x.into()), Versioned::V2(x) => Versioned::V2(x.into()), - Versioned::V3(x) => Versioned::V3(x.into()), + Versioned::VStaging(x) => Versioned::VStaging(x.into()), } } } @@ -331,7 +331,7 @@ macro_rules! impl_versioned_try_from { $out:ty, $v1_pat:pat => $v1_out:expr, $v2_pat:pat => $v2_out:expr, - $v3_pat:pat => $v3_out:expr + $vstaging_pat:pat => $vstaging_out:expr ) => { impl TryFrom<$from> for $out { type Error = crate::WrongVariant; @@ -341,7 +341,7 @@ macro_rules! impl_versioned_try_from { match x { Versioned::V1($v1_pat) => Ok(Versioned::V1($v1_out)), Versioned::V2($v2_pat) => Ok(Versioned::V2($v2_out)), - Versioned::V3($v3_pat) => Ok(Versioned::V3($v3_out)), + Versioned::VStaging($vstaging_pat) => Ok(Versioned::VStaging($vstaging_out)), _ => Err(crate::WrongVariant), } } @@ -355,7 +355,8 @@ macro_rules! impl_versioned_try_from { match x { Versioned::V1($v1_pat) => Ok(Versioned::V1($v1_out.clone())), Versioned::V2($v2_pat) => Ok(Versioned::V2($v2_out.clone())), - Versioned::V3($v3_pat) => Ok(Versioned::V3($v3_out.clone())), + Versioned::VStaging($vstaging_pat) => + Ok(Versioned::VStaging($vstaging_out.clone())), _ => Err(crate::WrongVariant), } } @@ -367,7 +368,7 @@ macro_rules! impl_versioned_try_from { pub type BitfieldDistributionMessage = Versioned< v1::BitfieldDistributionMessage, v2::BitfieldDistributionMessage, - v3::BitfieldDistributionMessage, + vstaging::BitfieldDistributionMessage, >; impl_versioned_full_protocol_from!( BitfieldDistributionMessage, @@ -379,14 +380,14 @@ impl_versioned_try_from!( BitfieldDistributionMessage, v1::ValidationProtocol::BitfieldDistribution(x) => x, v2::ValidationProtocol::BitfieldDistribution(x) => x, - v3::ValidationProtocol::BitfieldDistribution(x) => x + vstaging::ValidationProtocol::BitfieldDistribution(x) => x ); /// Version-annotated messages used by the statement distribution subsystem. pub type StatementDistributionMessage = Versioned< v1::StatementDistributionMessage, v2::StatementDistributionMessage, - v3::StatementDistributionMessage, + vstaging::StatementDistributionMessage, >; impl_versioned_full_protocol_from!( StatementDistributionMessage, @@ -398,14 +399,14 @@ impl_versioned_try_from!( StatementDistributionMessage, v1::ValidationProtocol::StatementDistribution(x) => x, v2::ValidationProtocol::StatementDistribution(x) => x, - v3::ValidationProtocol::StatementDistribution(x) => x + vstaging::ValidationProtocol::StatementDistribution(x) => x ); /// Version-annotated messages used by the approval distribution subsystem. pub type ApprovalDistributionMessage = Versioned< v1::ApprovalDistributionMessage, v2::ApprovalDistributionMessage, - v3::ApprovalDistributionMessage, + vstaging::ApprovalDistributionMessage, >; impl_versioned_full_protocol_from!( ApprovalDistributionMessage, @@ -417,7 +418,7 @@ impl_versioned_try_from!( ApprovalDistributionMessage, v1::ValidationProtocol::ApprovalDistribution(x) => x, v2::ValidationProtocol::ApprovalDistribution(x) => x, - v3::ValidationProtocol::ApprovalDistribution(x) => x + vstaging::ValidationProtocol::ApprovalDistribution(x) => x ); @@ -425,7 +426,7 @@ impl_versioned_try_from!( pub type GossipSupportNetworkMessage = Versioned< v1::GossipSupportNetworkMessage, v2::GossipSupportNetworkMessage, - v3::GossipSupportNetworkMessage, + vstaging::GossipSupportNetworkMessage, >; // This is a void enum placeholder, so never gets sent over the wire. @@ -870,17 +871,19 @@ pub mod v2 { } } -/// v3 network protocol types. -/// Purpose is for chaning ApprovalDistributionMessage to -/// include more than one assignment and approval in a message. -pub mod v3 { +/// vstaging network protocol types, intended to become v3. +/// Initial purpose is for chaning ApprovalDistributionMessage to +/// include more than one assignment in the message. +pub mod vstaging { use parity_scale_codec::{Decode, Encode}; - use polkadot_node_primitives::approval::v2::{ - CandidateBitfield, IndirectAssignmentCertV2, IndirectSignedApprovalVoteV2, + use polkadot_node_primitives::approval::{ + v1::IndirectSignedApprovalVote, + v2::{CandidateBitfield, IndirectAssignmentCertV2}, }; - /// This parts of the protocol did not change from v2, so just alias them in v3. + /// This parts of the protocol did not change from v2, so just alias them in vstaging, + /// no reason why they can't be change untill vstaging becomes v3 and is released. pub use super::v2::{ declare_signature_payload, BackedCandidateAcknowledgement, BackedCandidateManifest, BitfieldDistributionMessage, GossipSupportNetworkMessage, StatementDistributionMessage, @@ -900,7 +903,7 @@ pub mod v3 { Assignments(Vec<(IndirectAssignmentCertV2, CandidateBitfield)>), /// Approvals for candidates in some recent, unfinalized block. #[codec(index = 1)] - Approvals(Vec), + Approvals(Vec), } /// All network messages on the validation peer-set. diff --git a/polkadot/node/network/protocol/src/peer_set.rs b/polkadot/node/network/protocol/src/peer_set.rs index cb329607ad6..eb483dec970 100644 --- a/polkadot/node/network/protocol/src/peer_set.rs +++ b/polkadot/node/network/protocol/src/peer_set.rs @@ -21,7 +21,6 @@ use polkadot_primitives::Hash; use sc_network::{ config::{NonDefaultSetConfig, SetConfig}, types::ProtocolName, - NotificationService, }; use std::{ collections::{hash_map::Entry, HashMap}, @@ -69,59 +68,47 @@ impl PeerSet { self, is_authority: IsAuthority, peerset_protocol_names: &PeerSetProtocolNames, - ) -> (NonDefaultSetConfig, (PeerSet, Box)) { + ) -> NonDefaultSetConfig { // Networking layer relies on `get_main_name()` being the main name of the protocol // for peersets and connection management. let protocol = peerset_protocol_names.get_main_name(self); - let fallback_names = PeerSetProtocolNames::get_fallback_names( - self, - &peerset_protocol_names.genesis_hash, - peerset_protocol_names.fork_id.as_deref(), - ); + let fallback_names = PeerSetProtocolNames::get_fallback_names(self); let max_notification_size = self.get_max_notification_size(is_authority); match self { - PeerSet::Validation => { - let (config, notification_service) = NonDefaultSetConfig::new( - protocol, - fallback_names, - max_notification_size, - None, - SetConfig { - // we allow full nodes to connect to validators for gossip - // to ensure any `MIN_GOSSIP_PEERS` always include reserved peers - // we limit the amount of non-reserved slots to be less - // than `MIN_GOSSIP_PEERS` in total - in_peers: super::MIN_GOSSIP_PEERS as u32 / 2 - 1, - out_peers: super::MIN_GOSSIP_PEERS as u32 / 2 - 1, - reserved_nodes: Vec::new(), - non_reserved_mode: sc_network::config::NonReservedPeerMode::Accept, - }, - ); - - (config, (PeerSet::Validation, notification_service)) + PeerSet::Validation => NonDefaultSetConfig { + notifications_protocol: protocol, + fallback_names, + max_notification_size, + handshake: None, + set_config: SetConfig { + // we allow full nodes to connect to validators for gossip + // to ensure any `MIN_GOSSIP_PEERS` always include reserved peers + // we limit the amount of non-reserved slots to be less + // than `MIN_GOSSIP_PEERS` in total + in_peers: super::MIN_GOSSIP_PEERS as u32 / 2 - 1, + out_peers: super::MIN_GOSSIP_PEERS as u32 / 2 - 1, + reserved_nodes: Vec::new(), + non_reserved_mode: sc_network::config::NonReservedPeerMode::Accept, + }, }, - PeerSet::Collation => { - let (config, notification_service) = NonDefaultSetConfig::new( - protocol, - fallback_names, - max_notification_size, - None, - SetConfig { - // Non-authority nodes don't need to accept incoming connections on this - // peer set: - in_peers: if is_authority == IsAuthority::Yes { 100 } else { 0 }, - out_peers: 0, - reserved_nodes: Vec::new(), - non_reserved_mode: if is_authority == IsAuthority::Yes { - sc_network::config::NonReservedPeerMode::Accept - } else { - sc_network::config::NonReservedPeerMode::Deny - }, + PeerSet::Collation => NonDefaultSetConfig { + notifications_protocol: protocol, + fallback_names, + max_notification_size, + handshake: None, + set_config: SetConfig { + // Non-authority nodes don't need to accept incoming connections on this peer + // set: + in_peers: if is_authority == IsAuthority::Yes { 100 } else { 0 }, + out_peers: 0, + reserved_nodes: Vec::new(), + non_reserved_mode: if is_authority == IsAuthority::Yes { + sc_network::config::NonReservedPeerMode::Accept + } else { + sc_network::config::NonReservedPeerMode::Deny }, - ); - - (config, (PeerSet::Collation, notification_service)) + }, }, } } @@ -131,8 +118,15 @@ impl PeerSet { /// Networking layer relies on `get_main_version()` being the version /// of the main protocol name reported by [`PeerSetProtocolNames::get_main_name()`]. pub fn get_main_version(self) -> ProtocolVersion { + #[cfg(not(feature = "network-protocol-staging"))] match self { - PeerSet::Validation => ValidationVersion::V3.into(), + PeerSet::Validation => ValidationVersion::V2.into(), + PeerSet::Collation => CollationVersion::V2.into(), + } + + #[cfg(feature = "network-protocol-staging")] + match self { + PeerSet::Validation => ValidationVersion::VStaging.into(), PeerSet::Collation => CollationVersion::V2.into(), } } @@ -160,7 +154,7 @@ impl PeerSet { Some("validation/1") } else if version == ValidationVersion::V2.into() { Some("validation/2") - } else if version == ValidationVersion::V3.into() { + } else if version == ValidationVersion::VStaging.into() { Some("validation/3") } else { None @@ -210,7 +204,7 @@ impl IndexMut for PerPeerSet { pub fn peer_sets_info( is_authority: IsAuthority, peerset_protocol_names: &PeerSetProtocolNames, -) -> Vec<(NonDefaultSetConfig, (PeerSet, Box))> { +) -> Vec { PeerSet::iter() .map(|s| s.get_info(is_authority, &peerset_protocol_names)) .collect() @@ -233,10 +227,9 @@ pub enum ValidationVersion { V1 = 1, /// The second version. V2 = 2, - /// The third version where changes to ApprovalDistributionMessage had been made. - /// The changes are translatable to V2 format untill assignments v2 and approvals - /// coalescing is enabled through a runtime upgrade. - V3 = 3, + /// The staging version to gather changes + /// that before the release become v3. + VStaging = 3, } /// Supported collation protocol versions. Only versions defined here must be used in the codebase. @@ -293,12 +286,10 @@ impl From for ProtocolVersion { } /// On the wire protocol name to [`PeerSet`] mapping. -#[derive(Debug, Clone)] +#[derive(Clone)] pub struct PeerSetProtocolNames { protocols: HashMap, names: HashMap<(PeerSet, ProtocolVersion), ProtocolName>, - genesis_hash: Hash, - fork_id: Option, } impl PeerSetProtocolNames { @@ -333,7 +324,7 @@ impl PeerSetProtocolNames { } Self::register_legacy_protocol(&mut protocols, protocol); } - Self { protocols, names, genesis_hash, fork_id: fork_id.map(|fork_id| fork_id.into()) } + Self { protocols, names } } /// Helper function to register main protocol. @@ -437,30 +428,9 @@ impl PeerSetProtocolNames { } /// Get the protocol fallback names. Currently only holds the legacy name - /// for `LEGACY_PROTOCOL_VERSION` = 1 and v2 for validation. - fn get_fallback_names( - protocol: PeerSet, - genesis_hash: &Hash, - fork_id: Option<&str>, - ) -> Vec { - let mut fallbacks = vec![Self::get_legacy_name(protocol)]; - match protocol { - PeerSet::Validation => { - // Fallbacks are tried one by one, till one matches so push v2 at the top, so - // that it is used ahead of the legacy one(v1). - fallbacks.insert( - 0, - Self::generate_name( - genesis_hash, - fork_id, - protocol, - ValidationVersion::V2.into(), - ), - ) - }, - PeerSet::Collation => {}, - }; - fallbacks + /// for `LEGACY_PROTOCOL_VERSION` = 1. + fn get_fallback_names(protocol: PeerSet) -> Vec { + std::iter::once(Self::get_legacy_name(protocol)).collect() } } diff --git a/polkadot/node/network/protocol/src/request_response/mod.rs b/polkadot/node/network/protocol/src/request_response/mod.rs index 2df3021343d..96f7adeb29b 100644 --- a/polkadot/node/network/protocol/src/request_response/mod.rs +++ b/polkadot/node/network/protocol/src/request_response/mod.rs @@ -248,8 +248,8 @@ impl Protocol { name, fallback_names, max_request_size: 1_000, - // Responses are just confirmation, in essence not even a bit. So 100 seems - // plenty. + /// Responses are just confirmation, in essence not even a bit. So 100 seems + /// plenty. max_response_size: 100, request_timeout: DISPUTE_REQUEST_TIMEOUT, inbound_queue: tx, diff --git a/polkadot/node/network/statement-distribution/Cargo.toml b/polkadot/node/network/statement-distribution/Cargo.toml index 85d2c75aa79..bf516e7b7ba 100644 --- a/polkadot/node/network/statement-distribution/Cargo.toml +++ b/polkadot/node/network/statement-distribution/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] futures = "0.3.21" futures-timer = "3.0.2" @@ -19,6 +16,7 @@ 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-subsystem-types = { path = "../../subsystem-types" } polkadot-node-network-protocol = { path = "../protocol" } arrayvec = "0.7.4" indexmap = "1.9.1" diff --git a/polkadot/node/network/statement-distribution/src/legacy_v1/mod.rs b/polkadot/node/network/statement-distribution/src/legacy_v1/mod.rs index 93f97fe1dd6..d9866af1ee2 100644 --- a/polkadot/node/network/statement-distribution/src/legacy_v1/mod.rs +++ b/polkadot/node/network/statement-distribution/src/legacy_v1/mod.rs @@ -22,8 +22,8 @@ use polkadot_node_network_protocol::{ grid_topology::{GridNeighbors, RequiredRouting, SessionBoundGridTopologyStorage}, peer_set::{IsAuthority, PeerSet, ValidationVersion}, v1::{self as protocol_v1, StatementMetadata}, - v2 as protocol_v2, v3 as protocol_v3, IfDisconnected, PeerId, UnifiedReputationChange as Rep, - Versioned, View, + v2 as protocol_v2, vstaging as protocol_vstaging, IfDisconnected, PeerId, + UnifiedReputationChange as Rep, Versioned, View, }; use polkadot_node_primitives::{ SignedFullStatement, Statement, StatementWithPVD, UncheckedSignedFullStatement, @@ -1075,7 +1075,7 @@ async fn circulate_statement<'a, Context>( }) .partition::, _>(|(_, _, version)| match version { ValidationVersion::V1 => true, - ValidationVersion::V2 | ValidationVersion::V3 => false, + ValidationVersion::V2 | ValidationVersion::VStaging => false, }); // partition is handy here but not if we add more protocol versions let payload = v1_statement_message(relay_parent, stored.statement.clone(), metrics); @@ -1108,7 +1108,8 @@ async fn circulate_statement<'a, Context>( .collect(); let v2_peers_to_send = filter_by_peer_version(&peers_to_send, ValidationVersion::V2.into()); - let v3_to_send = filter_by_peer_version(&peers_to_send, ValidationVersion::V3.into()); + let vstaging_to_send = + filter_by_peer_version(&peers_to_send, ValidationVersion::VStaging.into()); if !v2_peers_to_send.is_empty() { gum::trace!( @@ -1125,17 +1126,17 @@ async fn circulate_statement<'a, Context>( .await; } - if !v3_to_send.is_empty() { + if !vstaging_to_send.is_empty() { gum::trace!( target: LOG_TARGET, - ?v3_to_send, + ?vstaging_to_send, ?relay_parent, statement = ?stored.statement, - "Sending statement to v3 peers", + "Sending statement to vstaging peers", ); ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage( - v3_to_send, - compatible_v1_message(ValidationVersion::V3, payload.clone()).into(), + vstaging_to_send, + compatible_v1_message(ValidationVersion::VStaging, payload.clone()).into(), )) .await; } @@ -1471,8 +1472,10 @@ async fn handle_incoming_message<'a, Context>( let message = match message { Versioned::V1(m) => m, Versioned::V2(protocol_v2::StatementDistributionMessage::V1Compatibility(m)) | - Versioned::V3(protocol_v3::StatementDistributionMessage::V1Compatibility(m)) => m, - Versioned::V2(_) | Versioned::V3(_) => { + Versioned::VStaging(protocol_vstaging::StatementDistributionMessage::V1Compatibility( + m, + )) => m, + Versioned::V2(_) | Versioned::VStaging(_) => { // The higher-level subsystem code is supposed to filter out // all non v1 messages. gum::debug!( @@ -2198,7 +2201,8 @@ fn compatible_v1_message( ValidationVersion::V1 => Versioned::V1(message), ValidationVersion::V2 => Versioned::V2(protocol_v2::StatementDistributionMessage::V1Compatibility(message)), - ValidationVersion::V3 => - Versioned::V3(protocol_v3::StatementDistributionMessage::V1Compatibility(message)), + ValidationVersion::VStaging => Versioned::VStaging( + protocol_vstaging::StatementDistributionMessage::V1Compatibility(message), + ), } } diff --git a/polkadot/node/network/statement-distribution/src/legacy_v1/tests.rs b/polkadot/node/network/statement-distribution/src/legacy_v1/tests.rs index 8ac9895ec5a..ca3038f9b3f 100644 --- a/polkadot/node/network/statement-distribution/src/legacy_v1/tests.rs +++ b/polkadot/node/network/statement-distribution/src/legacy_v1/tests.rs @@ -43,8 +43,8 @@ use polkadot_node_subsystem::{ }; use polkadot_node_subsystem_test_helpers::mock::{make_ferdie_keystore, new_leaf}; use polkadot_primitives::{ - vstaging::NodeFeatures, ExecutorParams, GroupIndex, Hash, HeadData, Id as ParaId, IndexedVec, - SessionInfo, ValidationCode, + ExecutorParams, GroupIndex, Hash, HeadData, Id as ParaId, IndexedVec, SessionInfo, + ValidationCode, }; use polkadot_primitives_test_helpers::{ dummy_committed_candidate_receipt, dummy_hash, AlwaysZeroRng, @@ -834,15 +834,6 @@ fn receiving_from_one_sends_to_another_and_to_candidate_backing() { } ); - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); - // notify of peers and view handle .send(FromOrchestra::Communication { @@ -1083,15 +1074,6 @@ fn receiving_large_statement_from_one_sends_to_another_and_to_candidate_backing( } ); - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); - // notify of peers and view handle .send(FromOrchestra::Communication { @@ -1622,15 +1604,6 @@ fn delay_reputation_changes() { } ); - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); - // notify of peers and view handle .send(FromOrchestra::Communication { @@ -2111,15 +2084,6 @@ fn share_prioritizes_backing_group() { } ); - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); - // notify of dummy peers and view for (peer, pair) in dummy_peers.clone().into_iter().zip(dummy_pairs) { handle @@ -2442,15 +2406,6 @@ fn peer_cant_flood_with_large_statements() { } ); - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); - // notify of peers and view handle .send(FromOrchestra::Communication { @@ -2676,14 +2631,6 @@ fn handle_multiple_seconded_statements() { } ); - assert_matches!( - handle.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(_, RuntimeApiRequest::NodeFeatures(_, si_tx), ) - ) => { - si_tx.send(Ok(NodeFeatures::EMPTY)).unwrap(); - } - ); // notify of peers and view for peer in all_peers.iter() { handle diff --git a/polkadot/node/network/statement-distribution/src/lib.rs b/polkadot/node/network/statement-distribution/src/lib.rs index a1ba1137b5a..0a80c1491a9 100644 --- a/polkadot/node/network/statement-distribution/src/lib.rs +++ b/polkadot/node/network/statement-distribution/src/lib.rs @@ -19,7 +19,7 @@ //! This is responsible for distributing signed statements about candidate //! validity among validators. -#![deny(unused_crate_dependencies)] +// #![deny(unused_crate_dependencies)] #![warn(missing_docs)] use error::{log_error, FatalResult}; @@ -27,7 +27,7 @@ use std::time::Duration; use polkadot_node_network_protocol::{ request_response::{v1 as request_v1, v2::AttestedCandidateRequest, IncomingRequestReceiver}, - v2 as protocol_v2, v3 as protocol_v3, Versioned, + v2 as protocol_v2, vstaging as protocol_vstaging, Versioned, }; use polkadot_node_primitives::StatementWithPVD; use polkadot_node_subsystem::{ @@ -400,11 +400,11 @@ impl StatementDistributionSubsystem { Versioned::V2( protocol_v2::StatementDistributionMessage::V1Compatibility(_), ) | - Versioned::V3( - protocol_v3::StatementDistributionMessage::V1Compatibility(_), + Versioned::VStaging( + protocol_vstaging::StatementDistributionMessage::V1Compatibility(_), ) => VersionTarget::Legacy, Versioned::V1(_) => VersionTarget::Legacy, - Versioned::V2(_) | Versioned::V3(_) => VersionTarget::Current, + Versioned::V2(_) | Versioned::VStaging(_) => VersionTarget::Current, }, _ => VersionTarget::Both, }; diff --git a/polkadot/node/network/statement-distribution/src/v2/mod.rs b/polkadot/node/network/statement-distribution/src/v2/mod.rs index 2f06d3685b8..406f1130590 100644 --- a/polkadot/node/network/statement-distribution/src/v2/mod.rs +++ b/polkadot/node/network/statement-distribution/src/v2/mod.rs @@ -29,7 +29,8 @@ use polkadot_node_network_protocol::{ MAX_PARALLEL_ATTESTED_CANDIDATE_REQUESTS, }, v2::{self as protocol_v2, StatementFilter}, - v3 as protocol_v3, IfDisconnected, PeerId, UnifiedReputationChange as Rep, Versioned, View, + vstaging as protocol_vstaging, IfDisconnected, PeerId, UnifiedReputationChange as Rep, + Versioned, View, }; use polkadot_node_primitives::{ SignedFullStatementWithPVD, StatementWithPVD as FullStatementWithPVD, @@ -365,7 +366,7 @@ pub(crate) async fn handle_network_update( gum::trace!(target: LOG_TARGET, ?peer_id, ?role, ?protocol_version, "Peer connected"); let versioned_protocol = if protocol_version != ValidationVersion::V2.into() && - protocol_version != ValidationVersion::V3.into() + protocol_version != ValidationVersion::VStaging.into() { return } else { @@ -431,28 +432,28 @@ pub(crate) async fn handle_network_update( net_protocol::StatementDistributionMessage::V2( protocol_v2::StatementDistributionMessage::V1Compatibility(_), ) | - net_protocol::StatementDistributionMessage::V3( - protocol_v3::StatementDistributionMessage::V1Compatibility(_), + net_protocol::StatementDistributionMessage::VStaging( + protocol_vstaging::StatementDistributionMessage::V1Compatibility(_), ) => return, net_protocol::StatementDistributionMessage::V2( protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement), ) | - net_protocol::StatementDistributionMessage::V3( - protocol_v3::StatementDistributionMessage::Statement(relay_parent, statement), + net_protocol::StatementDistributionMessage::VStaging( + protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, statement), ) => handle_incoming_statement(ctx, state, peer_id, relay_parent, statement, reputation) .await, net_protocol::StatementDistributionMessage::V2( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(inner), ) | - net_protocol::StatementDistributionMessage::V3( - protocol_v3::StatementDistributionMessage::BackedCandidateManifest(inner), + net_protocol::StatementDistributionMessage::VStaging( + protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest(inner), ) => handle_incoming_manifest(ctx, state, peer_id, inner, reputation).await, net_protocol::StatementDistributionMessage::V2( protocol_v2::StatementDistributionMessage::BackedCandidateKnown(inner), ) | - net_protocol::StatementDistributionMessage::V3( - protocol_v3::StatementDistributionMessage::BackedCandidateKnown(inner), + net_protocol::StatementDistributionMessage::VStaging( + protocol_vstaging::StatementDistributionMessage::BackedCandidateKnown(inner), ) => handle_incoming_acknowledgement(ctx, state, peer_id, inner, reputation).await, }, NetworkBridgeEvent::PeerViewChange(peer_id, view) => @@ -805,13 +806,13 @@ fn pending_statement_network_message( protocol_v2::StatementDistributionMessage::Statement(relay_parent, signed) }) .map(|msg| (vec![peer.0], Versioned::V2(msg).into())), - ValidationVersion::V3 => statement_store + ValidationVersion::VStaging => statement_store .validator_statement(originator, compact) .map(|s| s.as_unchecked().clone()) .map(|signed| { - protocol_v3::StatementDistributionMessage::Statement(relay_parent, signed) + protocol_vstaging::StatementDistributionMessage::Statement(relay_parent, signed) }) - .map(|msg| (vec![peer.0], Versioned::V3(msg).into())), + .map(|msg| (vec![peer.0], Versioned::VStaging(msg).into())), ValidationVersion::V1 => { gum::error!( target: LOG_TARGET, @@ -944,10 +945,10 @@ async fn send_pending_grid_messages( ) .into(), )), - ValidationVersion::V3 => messages.push(( + ValidationVersion::VStaging => messages.push(( vec![peer_id.0], - Versioned::V3( - protocol_v3::StatementDistributionMessage::BackedCandidateManifest( + Versioned::VStaging( + protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest( manifest, ), ) @@ -959,7 +960,7 @@ async fn send_pending_grid_messages( "Bug ValidationVersion::V1 should not be used in statement-distribution v2, legacy should have handled this" ); - }, + } }; }, grid::ManifestKind::Acknowledgement => { @@ -1307,8 +1308,8 @@ async fn circulate_statement( let statement_to_v2_peers = filter_by_peer_version(&statement_to_peers, ValidationVersion::V2.into()); - let statement_to_v3_peers = - filter_by_peer_version(&statement_to_peers, ValidationVersion::V3.into()); + let statement_to_vstaging_peers = + filter_by_peer_version(&statement_to_peers, ValidationVersion::VStaging.into()); // ship off the network messages to the network bridge. if !statement_to_v2_peers.is_empty() { @@ -1330,17 +1331,17 @@ async fn circulate_statement( .await; } - if !statement_to_v3_peers.is_empty() { + if !statement_to_vstaging_peers.is_empty() { gum::debug!( target: LOG_TARGET, ?compact_statement, n_peers = ?statement_to_peers.len(), - "Sending statement to v3 peers", + "Sending statement to vstaging peers", ); ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage( - statement_to_v3_peers, - Versioned::V3(protocol_v3::StatementDistributionMessage::Statement( + statement_to_vstaging_peers, + Versioned::VStaging(protocol_vstaging::StatementDistributionMessage::Statement( relay_parent, statement.as_unchecked().clone(), )) @@ -1886,7 +1887,8 @@ async fn provide_candidate_to_grid( } let manifest_peers_v2 = filter_by_peer_version(&manifest_peers, ValidationVersion::V2.into()); - let manifest_peers_v3 = filter_by_peer_version(&manifest_peers, ValidationVersion::V3.into()); + let manifest_peers_vstaging = + filter_by_peer_version(&manifest_peers, ValidationVersion::VStaging.into()); if !manifest_peers_v2.is_empty() { gum::debug!( target: LOG_TARGET, @@ -1906,27 +1908,27 @@ async fn provide_candidate_to_grid( .await; } - if !manifest_peers_v3.is_empty() { + if !manifest_peers_vstaging.is_empty() { gum::debug!( target: LOG_TARGET, ?candidate_hash, local_validator = ?per_session.local_validator, - n_peers = manifest_peers_v3.len(), - "Sending manifest to v3 peers" + n_peers = manifest_peers_vstaging.len(), + "Sending manifest to vstaging peers" ); ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage( - manifest_peers_v3, - Versioned::V3(protocol_v3::StatementDistributionMessage::BackedCandidateManifest( - manifest, - )) + manifest_peers_vstaging, + Versioned::VStaging( + protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest(manifest), + ) .into(), )) .await; } let ack_peers_v2 = filter_by_peer_version(&ack_peers, ValidationVersion::V2.into()); - let ack_peers_v3 = filter_by_peer_version(&ack_peers, ValidationVersion::V3.into()); + let ack_peers_vstaging = filter_by_peer_version(&ack_peers, ValidationVersion::VStaging.into()); if !ack_peers_v2.is_empty() { gum::debug!( target: LOG_TARGET, @@ -1946,20 +1948,22 @@ async fn provide_candidate_to_grid( .await; } - if !ack_peers_v3.is_empty() { + if !ack_peers_vstaging.is_empty() { gum::debug!( target: LOG_TARGET, ?candidate_hash, local_validator = ?per_session.local_validator, - n_peers = ack_peers_v3.len(), - "Sending acknowledgement to v3 peers" + n_peers = ack_peers_vstaging.len(), + "Sending acknowledgement to vstaging peers" ); ctx.send_message(NetworkBridgeTxMessage::SendValidationMessage( - ack_peers_v3, - Versioned::V3(protocol_v3::StatementDistributionMessage::BackedCandidateKnown( - acknowledgement, - )) + ack_peers_vstaging, + Versioned::VStaging( + protocol_vstaging::StatementDistributionMessage::BackedCandidateKnown( + acknowledgement, + ), + ) .into(), )) .await; @@ -2289,8 +2293,8 @@ fn post_acknowledgement_statement_messages( ) .into(), )), - ValidationVersion::V3 => messages.push(Versioned::V3( - protocol_v3::StatementDistributionMessage::Statement( + ValidationVersion::VStaging => messages.push(Versioned::VStaging( + protocol_vstaging::StatementDistributionMessage::Statement( relay_parent, statement.as_unchecked().clone(), ) @@ -2437,9 +2441,9 @@ fn acknowledgement_and_statement_messages( let mut messages = match peer.1 { ValidationVersion::V2 => vec![(vec![peer.0], msg_v2.into())], - ValidationVersion::V3 => vec![( + ValidationVersion::VStaging => vec![( vec![peer.0], - Versioned::V3(protocol_v2::StatementDistributionMessage::BackedCandidateKnown( + Versioned::VStaging(protocol_v2::StatementDistributionMessage::BackedCandidateKnown( acknowledgement, )) .into(), diff --git a/polkadot/node/network/statement-distribution/src/v2/tests/grid.rs b/polkadot/node/network/statement-distribution/src/v2/tests/grid.rs index aa1a473b833..9802db06082 100644 --- a/polkadot/node/network/statement-distribution/src/v2/tests/grid.rs +++ b/polkadot/node/network/statement-distribution/src/v2/tests/grid.rs @@ -44,8 +44,6 @@ fn backed_candidate_leads_to_advertisement() { let local_group_index = local_validator.group_index.unwrap(); let local_para = ParaId::from(local_group_index.0); - let other_group = next_group_index(local_group_index, validator_count, group_size); - let test_leaf = state.make_dummy_leaf(relay_parent); let (candidate, pvd) = make_candidate( @@ -58,12 +56,13 @@ fn backed_candidate_leads_to_advertisement() { ); let candidate_hash = candidate.hash(); - let local_group_validators = state.group_validators(local_group_index, true); - let other_group_validators = state.group_validators(other_group, true); - let v_a = local_group_validators[0]; - let v_b = local_group_validators[1]; - let v_c = other_group_validators[0]; - let v_d = other_group_validators[1]; + let other_group_validators = state.group_validators(local_group_index, true); + let target_group_validators = + state.group_validators((local_group_index.0 + 1).into(), true); + let v_a = other_group_validators[0]; + let v_b = other_group_validators[1]; + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; // peer A is in group, has relay parent in view. // peer B is in group, has no relay parent in view. @@ -275,12 +274,12 @@ fn received_advertisement_before_confirmation_leads_to_request() { ); let candidate_hash = candidate.hash(); - let local_group_validators = state.group_validators(local_group_index, true); - let other_group_validators = state.group_validators(other_group, true); - let v_a = local_group_validators[0]; - let v_b = local_group_validators[1]; - let v_c = other_group_validators[0]; - let v_d = other_group_validators[1]; + let other_group_validators = state.group_validators(local_group_index, true); + let target_group_validators = state.group_validators(other_group, true); + let v_a = other_group_validators[0]; + let v_b = other_group_validators[1]; + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; // peer A is in group, has relay parent in view. // peer B is in group, has no relay parent in view. @@ -430,33 +429,19 @@ fn received_advertisement_after_backing_leads_to_acknowledgement() { async_backing_params: None, }; + let relay_parent = Hash::repeat_byte(1); + let peer_c = PeerId::random(); + let peer_d = PeerId::random(); + let peer_e = PeerId::random(); + test_harness(config, |state, mut overseer| async move { - let peers_to_connect = [ - TestPeerToConnect { local: true, relay_parent_in_view: false }, - TestPeerToConnect { local: true, relay_parent_in_view: false }, - TestPeerToConnect { local: false, relay_parent_in_view: true }, - TestPeerToConnect { local: false, relay_parent_in_view: true }, - TestPeerToConnect { local: false, relay_parent_in_view: true }, - ]; + let local_validator = state.local.clone().unwrap(); + let local_group_index = local_validator.group_index.unwrap(); - let TestSetupInfo { - other_group, - other_para, - relay_parent, - test_leaf, - peers, - validators, - .. - } = setup_test_and_connect_peers( - &state, - &mut overseer, - validator_count, - group_size, - &peers_to_connect, - ) - .await; - let [_, _, peer_c, peer_d, _] = peers[..] else { panic!() }; - let [_, _, v_c, v_d, v_e] = validators[..] else { panic!() }; + let other_group = next_group_index(local_group_index, validator_count, group_size); + let other_para = ParaId::from(other_group.0); + + let test_leaf = state.make_dummy_leaf(relay_parent); let (candidate, pvd) = make_candidate( relay_parent, @@ -468,6 +453,52 @@ fn received_advertisement_after_backing_leads_to_acknowledgement() { ); let candidate_hash = candidate.hash(); + let target_group_validators = state.group_validators(other_group, true); + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; + let v_e = target_group_validators[2]; + + // Connect C, D, E + { + connect_peer( + &mut overseer, + peer_c.clone(), + Some(vec![state.discovery_id(v_c)].into_iter().collect()), + ) + .await; + + connect_peer( + &mut overseer, + peer_d.clone(), + Some(vec![state.discovery_id(v_d)].into_iter().collect()), + ) + .await; + + connect_peer( + &mut overseer, + peer_e.clone(), + Some(vec![state.discovery_id(v_e)].into_iter().collect()), + ) + .await; + + send_peer_view_change(&mut overseer, peer_c.clone(), view![relay_parent]).await; + send_peer_view_change(&mut overseer, peer_d.clone(), view![relay_parent]).await; + send_peer_view_change(&mut overseer, peer_e.clone(), view![relay_parent]).await; + } + + activate_leaf(&mut overseer, &test_leaf, &state, true).await; + + answer_expected_hypothetical_depth_request( + &mut overseer, + vec![], + Some(relay_parent), + false, + ) + .await; + + // Send gossip topology. + send_new_topology(&mut overseer, state.make_dummy_topology()).await; + let manifest = BackedCandidateManifest { relay_parent, candidate_hash, @@ -499,7 +530,14 @@ fn received_advertisement_after_backing_leads_to_acknowledgement() { // Receive an advertisement from C. { - send_manifest_from_peer(&mut overseer, peer_c, manifest.clone()).await; + send_peer_message( + &mut overseer, + peer_c.clone(), + protocol_v2::StatementDistributionMessage::BackedCandidateManifest( + manifest.clone(), + ), + ) + .await; // Should send a request to C. let statements = vec![ @@ -525,16 +563,37 @@ fn received_advertisement_after_backing_leads_to_acknowledgement() { ) .await; - assert_peer_reported!(&mut overseer, peer_c, BENEFIT_VALID_STATEMENT); - assert_peer_reported!(&mut overseer, peer_c, BENEFIT_VALID_STATEMENT); - assert_peer_reported!(&mut overseer, peer_c, BENEFIT_VALID_STATEMENT); - assert_peer_reported!(&mut overseer, peer_c, BENEFIT_VALID_RESPONSE); + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_c && r == BENEFIT_VALID_STATEMENT.into() + ); + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_c && r == BENEFIT_VALID_STATEMENT.into() + ); + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_c && r == BENEFIT_VALID_STATEMENT.into() + ); + + assert_matches!( + overseer.recv().await, + AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) + if p == peer_c && r == BENEFIT_VALID_RESPONSE.into() + ); answer_expected_hypothetical_depth_request(&mut overseer, vec![], None, false).await; } // Receive Backed message. - send_backed_message(&mut overseer, candidate_hash).await; + overseer + .send(FromOrchestra::Communication { + msg: StatementDistributionMessage::Backed(candidate_hash), + }) + .await; // Should send an acknowledgement back to C. { @@ -566,7 +625,14 @@ fn received_advertisement_after_backing_leads_to_acknowledgement() { // Receive a manifest about the same candidate from peer D. { - send_manifest_from_peer(&mut overseer, peer_d, manifest.clone()).await; + send_peer_message( + &mut overseer, + peer_d.clone(), + protocol_v2::StatementDistributionMessage::BackedCandidateManifest( + manifest.clone(), + ), + ) + .await; let expected_ack = BackedCandidateAcknowledgement { candidate_hash, @@ -599,360 +665,6 @@ fn received_advertisement_after_backing_leads_to_acknowledgement() { }); } -#[test] -fn receive_ack_for_unconfirmed_candidate() { - let validator_count = 6; - let group_size = 3; - let config = TestConfig { - validator_count, - group_size, - local_validator: LocalRole::Validator, - async_backing_params: None, - }; - - test_harness(config, |state, mut overseer| async move { - let peers_to_connect = [ - TestPeerToConnect { local: true, relay_parent_in_view: true }, - TestPeerToConnect { local: true, relay_parent_in_view: false }, - TestPeerToConnect { local: false, relay_parent_in_view: true }, - TestPeerToConnect { local: false, relay_parent_in_view: false }, - ]; - let TestSetupInfo { local_para, relay_parent, test_leaf, peers, .. } = - setup_test_and_connect_peers( - &state, - &mut overseer, - validator_count, - group_size, - &peers_to_connect, - ) - .await; - let [_, _, peer_c, _] = peers[..] else { panic!() }; - - let (candidate, _pvd) = make_candidate( - relay_parent, - 1, - local_para, - test_leaf.para_data(local_para).head_data.clone(), - vec![4, 5, 6].into(), - Hash::repeat_byte(42).into(), - ); - let candidate_hash = candidate.hash(); - - let ack = BackedCandidateAcknowledgement { - candidate_hash, - statement_knowledge: StatementFilter { - seconded_in_group: bitvec::bitvec![u8, Lsb0; 1, 1, 1], - validated_in_group: bitvec::bitvec![u8, Lsb0; 0, 0, 0], - }, - }; - - // Receive an acknowledgement from a peer before the candidate is confirmed. - send_ack_from_peer(&mut overseer, peer_c, ack.clone()).await; - assert_peer_reported!( - &mut overseer, - peer_c, - COST_UNEXPECTED_ACKNOWLEDGEMENT_UNKNOWN_CANDIDATE, - ); - - overseer - }); -} - -// Test receiving unexpected and expected acknowledgements for a locally confirmed candidate. -#[test] -fn received_acknowledgements_for_locally_confirmed() { - let validator_count = 6; - let group_size = 3; - let config = TestConfig { - validator_count, - group_size, - local_validator: LocalRole::Validator, - async_backing_params: None, - }; - - test_harness(config, |state, mut overseer| async move { - let peers_to_connect = [ - TestPeerToConnect { local: true, relay_parent_in_view: true }, - TestPeerToConnect { local: true, relay_parent_in_view: false }, - TestPeerToConnect { local: false, relay_parent_in_view: true }, - TestPeerToConnect { local: false, relay_parent_in_view: false }, - ]; - let TestSetupInfo { - local_validator, - local_group, - local_para, - relay_parent, - test_leaf, - peers, - validators, - .. - } = setup_test_and_connect_peers( - &state, - &mut overseer, - validator_count, - group_size, - &peers_to_connect, - ) - .await; - let [peer_a, peer_b, peer_c, peer_d] = peers[..] else { panic!() }; - let [_, v_b, _, _] = validators[..] else { panic!() }; - - let (candidate, pvd) = make_candidate( - relay_parent, - 1, - local_para, - test_leaf.para_data(local_para).head_data.clone(), - vec![4, 5, 6].into(), - Hash::repeat_byte(42).into(), - ); - let candidate_hash = candidate.hash(); - - let ack = BackedCandidateAcknowledgement { - candidate_hash, - statement_knowledge: StatementFilter { - seconded_in_group: bitvec::bitvec![u8, Lsb0; 1, 1, 1], - validated_in_group: bitvec::bitvec![u8, Lsb0; 0, 0, 0], - }, - }; - - // Confirm the candidate locally so that we don't send out requests. - { - let statement = state - .sign_full_statement( - local_validator.validator_index, - Statement::Seconded(candidate.clone()), - &SigningContext { parent_hash: relay_parent, session_index: 1 }, - pvd.clone(), - ) - .clone(); - - send_share_message(&mut overseer, relay_parent, statement).await; - - assert_matches!( - overseer.recv().await, - AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage(peers, _)) if peers == vec![peer_a] - ); - - answer_expected_hypothetical_depth_request(&mut overseer, vec![], None, false).await; - } - - // Receive an unexpected acknowledgement from peer D. - send_ack_from_peer(&mut overseer, peer_d, ack.clone()).await; - assert_peer_reported!(&mut overseer, peer_d, COST_UNEXPECTED_MANIFEST_DISALLOWED); - - // Send statement from peer B. - { - let statement = state - .sign_statement( - v_b, - CompactStatement::Seconded(candidate_hash), - &SigningContext { parent_hash: relay_parent, session_index: 1 }, - ) - .as_unchecked() - .clone(); - - send_peer_message( - &mut overseer, - peer_b.clone(), - protocol_v2::StatementDistributionMessage::Statement(relay_parent, statement), - ) - .await; - - assert_peer_reported!(&mut overseer, peer_b, BENEFIT_VALID_STATEMENT_FIRST); - - assert_matches!( - overseer.recv().await, - AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage(peers, _)) if peers == vec![peer_a] - ); - } - - // Send Backed notification. - { - send_backed_message(&mut overseer, candidate_hash).await; - - // We should send out a manifest. - assert_matches!( - overseer.recv().await, - AllMessages:: NetworkBridgeTx( - NetworkBridgeTxMessage::SendValidationMessage( - peers, - Versioned::V2( - protocol_v2::ValidationProtocol::StatementDistribution( - protocol_v2::StatementDistributionMessage::BackedCandidateManifest(manifest), - ), - ), - ) - ) => { - assert_eq!(peers, vec![peer_c]); - assert_eq!(manifest, BackedCandidateManifest { - relay_parent, - candidate_hash, - group_index: local_group, - para_id: local_para, - parent_head_data_hash: pvd.parent_head.hash(), - statement_knowledge: StatementFilter { - seconded_in_group: bitvec::bitvec![u8, Lsb0; 0, 1, 1], - validated_in_group: bitvec::bitvec![u8, Lsb0; 0, 0, 0], - }, - }); - } - ); - - answer_expected_hypothetical_depth_request(&mut overseer, vec![], None, false).await; - } - - // Receive an unexpected acknowledgement from peer D. - // - // It still shouldn't know this manifest. - send_ack_from_peer(&mut overseer, peer_d, ack.clone()).await; - assert_peer_reported!(&mut overseer, peer_d, COST_UNEXPECTED_MANIFEST_DISALLOWED); - - // Receive an acknowledgement from peer C. - // - // It's OK, we know they know it because we sent them a manifest. - send_ack_from_peer(&mut overseer, peer_c, ack.clone()).await; - - // What happens if we get another valid ack? - send_ack_from_peer(&mut overseer, peer_c, ack.clone()).await; - - overseer - }); -} - -// Test receiving unexpected acknowledgements for a candidate confirmed in a different group. -#[test] -fn received_acknowledgements_for_externally_confirmed() { - let validator_count = 6; - let group_size = 3; - let config = TestConfig { - validator_count, - group_size, - local_validator: LocalRole::Validator, - async_backing_params: None, - }; - - test_harness(config, |state, mut overseer| async move { - let peers_to_connect = [ - TestPeerToConnect { local: true, relay_parent_in_view: true }, - TestPeerToConnect { local: true, relay_parent_in_view: false }, - TestPeerToConnect { local: false, relay_parent_in_view: true }, - TestPeerToConnect { local: false, relay_parent_in_view: true }, - TestPeerToConnect { local: false, relay_parent_in_view: true }, - ]; - let TestSetupInfo { - other_group, - other_para, - relay_parent, - test_leaf, - peers, - validators, - .. - } = setup_test_and_connect_peers( - &state, - &mut overseer, - validator_count, - group_size, - &peers_to_connect, - ) - .await; - let [peer_a, _, peer_c, peer_d, _] = peers[..] else { panic!() }; - let [_, _, v_c, v_d, v_e] = validators[..] else { panic!() }; - - let (candidate, pvd) = make_candidate( - relay_parent, - 1, - other_para, - test_leaf.para_data(other_para).head_data.clone(), - vec![4, 5, 6].into(), - Hash::repeat_byte(42).into(), - ); - let candidate_hash = candidate.hash(); - - let manifest = BackedCandidateManifest { - relay_parent, - candidate_hash, - group_index: other_group, - para_id: other_para, - parent_head_data_hash: pvd.parent_head.hash(), - statement_knowledge: StatementFilter { - seconded_in_group: bitvec::bitvec![u8, Lsb0; 0, 1, 1], - validated_in_group: bitvec::bitvec![u8, Lsb0; 0, 0, 0], - }, - }; - - let statement_c = state - .sign_statement( - v_c, - CompactStatement::Seconded(candidate_hash), - &SigningContext { parent_hash: relay_parent, session_index: 1 }, - ) - .as_unchecked() - .clone(); - let statement_d = state - .sign_statement( - v_d, - CompactStatement::Seconded(candidate_hash), - &SigningContext { parent_hash: relay_parent, session_index: 1 }, - ) - .as_unchecked() - .clone(); - - // Receive an advertisement from C, confirming the candidate. - { - send_manifest_from_peer(&mut overseer, peer_c, manifest.clone()).await; - - // Should send a request to C. - let statements = vec![ - statement_c.clone(), - statement_d.clone(), - state - .sign_statement( - v_e, - CompactStatement::Seconded(candidate_hash), - &SigningContext { parent_hash: relay_parent, session_index: 1 }, - ) - .as_unchecked() - .clone(), - ]; - handle_sent_request( - &mut overseer, - peer_c, - candidate_hash, - StatementFilter::blank(group_size), - candidate.clone(), - pvd.clone(), - statements, - ) - .await; - - assert_peer_reported!(&mut overseer, peer_c, BENEFIT_VALID_STATEMENT); - assert_peer_reported!(&mut overseer, peer_c, BENEFIT_VALID_STATEMENT); - assert_peer_reported!(&mut overseer, peer_c, BENEFIT_VALID_STATEMENT); - assert_peer_reported!(&mut overseer, peer_c, BENEFIT_VALID_RESPONSE); - - answer_expected_hypothetical_depth_request(&mut overseer, vec![], None, false).await; - } - - let ack = BackedCandidateAcknowledgement { - candidate_hash, - statement_knowledge: StatementFilter { - seconded_in_group: bitvec::bitvec![u8, Lsb0; 1, 1, 1], - validated_in_group: bitvec::bitvec![u8, Lsb0; 0, 0, 0], - }, - }; - - // Receive an unexpected acknowledgement from peer D. - send_ack_from_peer(&mut overseer, peer_d, ack.clone()).await; - assert_peer_reported!(&mut overseer, peer_d, COST_UNEXPECTED_MANIFEST_PEER_UNKNOWN); - - // Receive an unexpected acknowledgement from peer A. - send_ack_from_peer(&mut overseer, peer_a, ack.clone()).await; - assert_peer_reported!(&mut overseer, peer_a, COST_UNEXPECTED_MANIFEST_DISALLOWED); - - overseer - }); -} - // Received advertisement after confirmation but before backing leads to nothing. #[test] fn received_advertisement_after_confirmation_before_backing() { @@ -989,10 +701,10 @@ fn received_advertisement_after_confirmation_before_backing() { ); let candidate_hash = candidate.hash(); - let other_group_validators = state.group_validators(other_group, true); - let v_c = other_group_validators[0]; - let v_d = other_group_validators[1]; - let v_e = other_group_validators[2]; + let target_group_validators = state.group_validators(other_group, true); + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; + let v_e = target_group_validators[2]; // Connect C, D, E { @@ -1175,10 +887,10 @@ fn additional_statements_are_shared_after_manifest_exchange() { ); let candidate_hash = candidate.hash(); - let other_group_validators = state.group_validators(other_group, true); - let v_c = other_group_validators[0]; - let v_d = other_group_validators[1]; - let v_e = other_group_validators[2]; + let target_group_validators = state.group_validators(other_group, true); + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; + let v_e = target_group_validators[2]; // Connect C, D, E { @@ -1471,12 +1183,13 @@ fn advertisement_sent_when_peer_enters_relay_parent_view() { ); let candidate_hash = candidate.hash(); - let local_group_validators = state.group_validators(local_group_index, true); - let other_group_validators = state.group_validators((local_group_index.0 + 1).into(), true); - let v_a = local_group_validators[0]; - let v_b = local_group_validators[1]; - let v_c = other_group_validators[0]; - let v_d = other_group_validators[1]; + let other_group_validators = state.group_validators(local_group_index, true); + let target_group_validators = + state.group_validators((local_group_index.0 + 1).into(), true); + let v_a = other_group_validators[0]; + let v_b = other_group_validators[1]; + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; // peer A is in group, has relay parent in view. // peer B is in group, has no relay parent in view. @@ -1693,12 +1406,13 @@ fn advertisement_not_re_sent_when_peer_re_enters_view() { ); let candidate_hash = candidate.hash(); - let local_group_validators = state.group_validators(local_group_index, true); - let other_group_validators = state.group_validators((local_group_index.0 + 1).into(), true); - let v_a = local_group_validators[0]; - let v_b = local_group_validators[1]; - let v_c = other_group_validators[0]; - let v_d = other_group_validators[1]; + let other_group_validators = state.group_validators(local_group_index, true); + let target_group_validators = + state.group_validators((local_group_index.0 + 1).into(), true); + let v_a = other_group_validators[0]; + let v_b = other_group_validators[1]; + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; // peer A is in group, has relay parent in view. // peer B is in group, has no relay parent in view. @@ -1916,10 +1630,10 @@ fn grid_statements_imported_to_backing() { ); let candidate_hash = candidate.hash(); - let other_group_validators = state.group_validators(other_group, true); - let v_c = other_group_validators[0]; - let v_d = other_group_validators[1]; - let v_e = other_group_validators[2]; + let target_group_validators = state.group_validators(other_group, true); + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; + let v_e = target_group_validators[2]; // Connect C, D, E { @@ -2121,12 +1835,12 @@ fn advertisements_rejected_from_incorrect_peers() { ); let candidate_hash = candidate.hash(); - let local_group_validators = state.group_validators(local_group_index, true); - let other_group_validators = state.group_validators(other_group, true); - let v_a = local_group_validators[0]; - let v_b = local_group_validators[1]; - let v_c = other_group_validators[0]; - let v_d = other_group_validators[1]; + let other_group_validators = state.group_validators(local_group_index, true); + let target_group_validators = state.group_validators(other_group, true); + let v_a = other_group_validators[0]; + let v_b = other_group_validators[1]; + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; // peer A is in group, has relay parent in view. // peer B is in group, has no relay parent in view. @@ -2265,9 +1979,9 @@ fn manifest_rejected_with_unknown_relay_parent() { ); let candidate_hash = candidate.hash(); - let other_group_validators = state.group_validators(other_group, true); - let v_c = other_group_validators[0]; - let v_d = other_group_validators[1]; + let target_group_validators = state.group_validators(other_group, true); + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; // peer C is not in group, has relay parent in view. // peer D is not in group, has no relay parent in view. @@ -2367,9 +2081,9 @@ fn manifest_rejected_when_not_a_validator() { ); let candidate_hash = candidate.hash(); - let other_group_validators = state.group_validators(other_group, true); - let v_c = other_group_validators[0]; - let v_d = other_group_validators[1]; + let target_group_validators = state.group_validators(other_group, true); + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; // peer C is not in group, has relay parent in view. // peer D is not in group, has no relay parent in view. @@ -2474,9 +2188,9 @@ fn manifest_rejected_when_group_does_not_match_para() { ); let candidate_hash = candidate.hash(); - let other_group_validators = state.group_validators(other_group, true); - let v_c = other_group_validators[0]; - let v_d = other_group_validators[1]; + let target_group_validators = state.group_validators(other_group, true); + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; // peer C is not in group, has relay parent in view. // peer D is not in group, has no relay parent in view. @@ -2580,10 +2294,10 @@ fn peer_reported_for_advertisement_conflicting_with_confirmed_candidate() { ); let candidate_hash = candidate.hash(); - let other_group_validators = state.group_validators(other_group, true); - let v_c = other_group_validators[0]; - let v_d = other_group_validators[1]; - let v_e = other_group_validators[2]; + let target_group_validators = state.group_validators(other_group, true); + let v_c = target_group_validators[0]; + let v_d = target_group_validators[1]; + let v_e = target_group_validators[2]; // Connect C, D, E { @@ -2830,7 +2544,7 @@ fn inactive_local_participates_in_grid() { send_peer_message( &mut overseer, peer_a.clone(), - protocol_v3::StatementDistributionMessage::BackedCandidateManifest(manifest), + protocol_vstaging::StatementDistributionMessage::BackedCandidateManifest(manifest), ) .await; diff --git a/polkadot/node/network/statement-distribution/src/v2/tests/mod.rs b/polkadot/node/network/statement-distribution/src/v2/tests/mod.rs index c34cf20d716..4e626977524 100644 --- a/polkadot/node/network/statement-distribution/src/v2/tests/mod.rs +++ b/polkadot/node/network/statement-distribution/src/v2/tests/mod.rs @@ -21,7 +21,6 @@ use crate::*; use polkadot_node_network_protocol::{ grid_topology::TopologyPeerInfo, request_response::{outgoing::Recipient, ReqProtocolNames}, - v2::{BackedCandidateAcknowledgement, BackedCandidateManifest}, view, ObservedRole, }; use polkadot_node_primitives::Statement; @@ -378,95 +377,6 @@ impl TestLeaf { } } -struct TestSetupInfo { - local_validator: TestLocalValidator, - local_group: GroupIndex, - local_para: ParaId, - other_group: GroupIndex, - other_para: ParaId, - relay_parent: Hash, - test_leaf: TestLeaf, - peers: Vec, - validators: Vec, -} - -struct TestPeerToConnect { - local: bool, - relay_parent_in_view: bool, -} - -// TODO: Generalize, use in more places. -/// Sets up some test info that is common to most tests, and connects the requested peers. -async fn setup_test_and_connect_peers( - state: &TestState, - overseer: &mut VirtualOverseer, - validator_count: usize, - group_size: usize, - peers_to_connect: &[TestPeerToConnect], -) -> TestSetupInfo { - let local_validator = state.local.clone().unwrap(); - let local_group = local_validator.group_index.unwrap(); - let local_para = ParaId::from(local_group.0); - - let other_group = next_group_index(local_group, validator_count, group_size); - let other_para = ParaId::from(other_group.0); - - let relay_parent = Hash::repeat_byte(1); - let test_leaf = state.make_dummy_leaf(relay_parent); - - // Because we are testing grid mod, the "target" group (the one we communicate with) is usually - // other_group, a non-local group. - // - // TODO: change based on `LocalRole`? - let local_group_validators = state.group_validators(local_group, true); - let other_group_validators = state.group_validators(other_group, true); - - let mut peers = vec![]; - let mut validators = vec![]; - let mut local_group_idx = 0; - let mut other_group_idx = 0; - for peer_to_connect in peers_to_connect { - let peer = PeerId::random(); - peers.push(peer); - - let v = if peer_to_connect.local { - let v = local_group_validators[local_group_idx]; - local_group_idx += 1; - v - } else { - let v = other_group_validators[other_group_idx]; - other_group_idx += 1; - v - }; - validators.push(v); - - connect_peer(overseer, peer, Some(vec![state.discovery_id(v)].into_iter().collect())).await; - - if peer_to_connect.relay_parent_in_view { - send_peer_view_change(overseer, peer.clone(), view![relay_parent]).await; - } - } - - activate_leaf(overseer, &test_leaf, &state, true).await; - - answer_expected_hypothetical_depth_request(overseer, vec![], Some(relay_parent), false).await; - - // Send gossip topology. - send_new_topology(overseer, state.make_dummy_topology()).await; - - TestSetupInfo { - local_validator, - local_group, - local_para, - other_group, - other_para, - test_leaf, - relay_parent, - peers, - validators, - } -} - async fn activate_leaf( virtual_overseer: &mut VirtualOverseer, leaf: &TestLeaf, @@ -637,66 +547,6 @@ async fn answer_expected_hypothetical_depth_request( ) } -#[macro_export] -macro_rules! assert_peer_reported { - ($virtual_overseer:expr, $peer_id:expr, $rep_change:expr $(,)*) => { - assert_matches!( - $virtual_overseer.recv().await, - AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::ReportPeer(ReportPeerMessage::Single(p, r))) - if p == $peer_id && r == $rep_change.into() - ); - } -} - -async fn send_share_message( - virtual_overseer: &mut VirtualOverseer, - relay_parent: Hash, - statement: SignedFullStatementWithPVD, -) { - virtual_overseer - .send(FromOrchestra::Communication { - msg: StatementDistributionMessage::Share(relay_parent, statement), - }) - .await; -} - -async fn send_backed_message( - virtual_overseer: &mut VirtualOverseer, - candidate_hash: CandidateHash, -) { - virtual_overseer - .send(FromOrchestra::Communication { - msg: StatementDistributionMessage::Backed(candidate_hash), - }) - .await; -} - -async fn send_manifest_from_peer( - virtual_overseer: &mut VirtualOverseer, - peer_id: PeerId, - manifest: BackedCandidateManifest, -) { - send_peer_message( - virtual_overseer, - peer_id, - protocol_v2::StatementDistributionMessage::BackedCandidateManifest(manifest), - ) - .await; -} - -async fn send_ack_from_peer( - virtual_overseer: &mut VirtualOverseer, - peer_id: PeerId, - ack: BackedCandidateAcknowledgement, -) { - send_peer_message( - virtual_overseer, - peer_id, - protocol_v2::StatementDistributionMessage::BackedCandidateKnown(ack), - ) - .await; -} - fn validator_pubkeys(val_ids: &[ValidatorPair]) -> IndexedVec { val_ids.iter().map(|v| v.public().into()).collect() } diff --git a/polkadot/node/overseer/Cargo.toml b/polkadot/node/overseer/Cargo.toml index ec1849404b0..ac1e4443f0c 100644 --- a/polkadot/node/overseer/Cargo.toml +++ b/polkadot/node/overseer/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "System overseer of the Polkadot node" -[lints] -workspace = true - [dependencies] client = { package = "sc-client-api", path = "../../../substrate/client/api" } sp-api = { path = "../../../substrate/primitives/api" } @@ -20,14 +17,14 @@ 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.3", default-features = false, features = ["futures_channel"] } +orchestra = { version = "0.3.3", default-features = false, features=["futures_channel"] } gum = { package = "tracing-gum", path = "../gum" } sp-core = { path = "../../../substrate/primitives/core" } async-trait = "0.1.57" tikv-jemalloc-ctl = { version = "0.5.0", optional = true } [dev-dependencies] -metered = { package = "prioritized-metered-channel", version = "0.5.1", default-features = false, features = ["futures_channel"] } +metered = { package = "prioritized-metered-channel", version = "0.5.1", default-features = false, features=["futures_channel"] } sp-core = { path = "../../../substrate/primitives/core" } futures = { version = "0.3.21", features = ["thread-pool"] } femme = "2.2.1" @@ -39,8 +36,8 @@ node-test-helpers = { package = "polkadot-node-subsystem-test-helpers", path = " tikv-jemalloc-ctl = "0.5.0" [features] -default = ["futures_channel"] -dotgraph = ["orchestra/dotgraph"] -expand = ["orchestra/expand"] -futures_channel = ["metered/futures_channel", "orchestra/futures_channel"] -jemalloc-allocator = ["dep:tikv-jemalloc-ctl"] +default = [ "futures_channel" ] +dotgraph = [ "orchestra/dotgraph" ] +expand = [ "orchestra/expand" ] +futures_channel = [ "metered/futures_channel", "orchestra/futures_channel" ] +jemalloc-allocator = [ "dep:tikv-jemalloc-ctl" ] diff --git a/polkadot/node/overseer/src/lib.rs b/polkadot/node/overseer/src/lib.rs index f4eddf1f41c..da99546a44f 100644 --- a/polkadot/node/overseer/src/lib.rs +++ b/polkadot/node/overseer/src/lib.rs @@ -276,7 +276,6 @@ impl From> for BlockInfo { /// An event from outside the overseer scope, such /// as the substrate framework or user interaction. -#[derive(Debug)] pub enum Event { /// A new block was imported. /// @@ -301,7 +300,6 @@ pub enum Event { } /// Some request from outer world. -#[derive(Debug)] pub enum ExternalRequest { /// Wait for the activation of a particular hash /// and be notified by means of the return channel. diff --git a/polkadot/node/primitives/Cargo.toml b/polkadot/node/primitives/Cargo.toml index 802a830f3ab..c39fd5947b0 100644 --- a/polkadot/node/primitives/Cargo.toml +++ b/polkadot/node/primitives/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] bounded-vec = "0.7" futures = "0.3.21" @@ -24,7 +21,7 @@ polkadot-parachain-primitives = { path = "../../parachain", default-features = f schnorrkel = "0.9.1" thiserror = "1.0.48" bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } [target.'cfg(not(target_os = "unknown"))'.dependencies] zstd = { version = "0.12.4", default-features = false } diff --git a/polkadot/node/primitives/src/approval.rs b/polkadot/node/primitives/src/approval.rs index f2a79e025af..e5ae24f7a51 100644 --- a/polkadot/node/primitives/src/approval.rs +++ b/polkadot/node/primitives/src/approval.rs @@ -20,7 +20,7 @@ pub mod v1 { use sp_consensus_babe as babe_primitives; pub use sp_consensus_babe::{ - Randomness, Slot, VrfPreOutput, VrfProof, VrfSignature, VrfTranscript, + Randomness, Slot, VrfOutput, VrfProof, VrfSignature, VrfTranscript, }; use parity_scale_codec::{Decode, Encode}; @@ -145,14 +145,14 @@ pub mod v1 { AuthorityOutOfBounds(usize), } - /// An unsafe VRF pre-output. Provide BABE Epoch info to create a `RelayVRFStory`. - pub struct UnsafeVRFPreOutput { - vrf_pre_output: VrfPreOutput, + /// An unsafe VRF output. Provide BABE Epoch info to create a `RelayVRFStory`. + pub struct UnsafeVRFOutput { + vrf_output: VrfOutput, slot: Slot, authority_index: u32, } - impl UnsafeVRFPreOutput { + impl UnsafeVRFOutput { /// Get the slot. pub fn slot(&self) -> Slot { self.slot @@ -177,7 +177,7 @@ pub mod v1 { sp_consensus_babe::make_vrf_transcript(randomness, self.slot, epoch_index); let inout = self - .vrf_pre_output + .vrf_output .0 .attach_input_hash(&pubkey, transcript.0) .map_err(ApprovalError::SchnorrkelSignature)?; @@ -190,7 +190,7 @@ pub mod v1 { /// This fails if either there is no BABE `PreRuntime` digest or /// the digest has type `SecondaryPlain`, which Substrate nodes do /// not produce or accept anymore. - pub fn babe_unsafe_vrf_info(header: &Header) -> Option { + pub fn babe_unsafe_vrf_info(header: &Header) -> Option { use babe_primitives::digests::CompatibleDigestItem; for digest in &header.digest.logs { @@ -198,8 +198,8 @@ pub mod v1 { let slot = pre.slot(); let authority_index = pre.authority_index(); - return pre.vrf_signature().map(|sig| UnsafeVRFPreOutput { - vrf_pre_output: sig.pre_output.clone(), + return pre.vrf_signature().map(|sig| UnsafeVRFOutput { + vrf_output: sig.output.clone(), slot, authority_index, }) @@ -214,14 +214,12 @@ pub mod v1 { pub mod v2 { use parity_scale_codec::{Decode, Encode}; pub use sp_consensus_babe::{ - Randomness, Slot, VrfPreOutput, VrfProof, VrfSignature, VrfTranscript, + Randomness, Slot, VrfOutput, VrfProof, VrfSignature, VrfTranscript, }; use std::ops::BitOr; use bitvec::{prelude::Lsb0, vec::BitVec}; - use polkadot_primitives::{ - CandidateIndex, CoreIndex, Hash, ValidatorIndex, ValidatorSignature, - }; + use polkadot_primitives::{CandidateIndex, CoreIndex, Hash, ValidatorIndex}; /// A static context associated with producing randomness for a core. pub const CORE_RANDOMNESS_CONTEXT: &[u8] = b"A&V CORE v2"; @@ -475,59 +473,6 @@ pub mod v2 { }) } } - - impl From for IndirectSignedApprovalVoteV2 { - fn from(value: super::v1::IndirectSignedApprovalVote) -> Self { - Self { - block_hash: value.block_hash, - validator: value.validator, - candidate_indices: value.candidate_index.into(), - signature: value.signature, - } - } - } - - /// Errors that can occur when trying to convert to/from approvals v1/v2 - #[derive(Debug)] - pub enum ApprovalConversionError { - /// More than one candidate was signed. - MoreThanOneCandidate(usize), - } - - impl TryFrom for super::v1::IndirectSignedApprovalVote { - type Error = ApprovalConversionError; - - fn try_from(value: IndirectSignedApprovalVoteV2) -> Result { - if value.candidate_indices.count_ones() != 1 { - return Err(ApprovalConversionError::MoreThanOneCandidate( - value.candidate_indices.count_ones(), - )) - } - Ok(Self { - block_hash: value.block_hash, - validator: value.validator, - candidate_index: value.candidate_indices.first_one().expect("Qed we checked above") - as u32, - signature: value.signature, - }) - } - } - - /// A signed approval vote which references the candidate indirectly via the block. - /// - /// In practice, we have a look-up from block hash and candidate index to candidate hash, - /// so this can be transformed into a `SignedApprovalVote`. - #[derive(Debug, Clone, Encode, Decode, PartialEq, Eq)] - pub struct IndirectSignedApprovalVoteV2 { - /// A block hash where the candidate appears. - pub block_hash: Hash, - /// The index of the candidate in the list of candidates fully included as-of the block. - pub candidate_indices: CandidateBitfield, - /// The validator index. - pub validator: ValidatorIndex, - /// The signature by the validator. - pub signature: ValidatorSignature, - } } #[cfg(test)] diff --git a/polkadot/node/primitives/src/disputes/message.rs b/polkadot/node/primitives/src/disputes/message.rs index 31fe73a7ba1..89d3ea6c0af 100644 --- a/polkadot/node/primitives/src/disputes/message.rs +++ b/polkadot/node/primitives/src/disputes/message.rs @@ -170,7 +170,7 @@ impl DisputeMessage { let valid_vote = ValidDisputeVote { validator_index: valid_index, signature: valid_statement.validator_signature().clone(), - kind: valid_kind.clone(), + kind: *valid_kind, }; let invalid_vote = InvalidDisputeVote { diff --git a/polkadot/node/primitives/src/disputes/mod.rs b/polkadot/node/primitives/src/disputes/mod.rs index 768b95f6553..500b705be95 100644 --- a/polkadot/node/primitives/src/disputes/mod.rs +++ b/polkadot/node/primitives/src/disputes/mod.rs @@ -46,15 +46,6 @@ pub struct SignedDisputeStatement { session_index: SessionIndex, } -/// Errors encountered while signing a dispute statement -#[derive(Debug)] -pub enum SignedDisputeStatementError { - /// Encountered a keystore error while signing - KeyStoreError(KeystoreError), - /// Could not generate signing payload - PayloadError, -} - /// Tracked votes on candidates, for the purposes of dispute resolution. #[derive(Debug, Clone)] pub struct CandidateVotes { @@ -116,9 +107,8 @@ impl ValidCandidateVotes { ValidDisputeStatementKind::BackingValid(_) | ValidDisputeStatementKind::BackingSeconded(_) => false, ValidDisputeStatementKind::Explicit | - ValidDisputeStatementKind::ApprovalChecking | - ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(_) => { - occupied.insert((kind.clone(), sig)); + ValidDisputeStatementKind::ApprovalChecking => { + occupied.insert((kind, sig)); kind != occupied.get().0 }, }, @@ -223,19 +213,16 @@ impl SignedDisputeStatement { candidate_hash: CandidateHash, session_index: SessionIndex, validator_public: ValidatorId, - ) -> Result, SignedDisputeStatementError> { + ) -> Result, KeystoreError> { let dispute_statement = if valid { DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) } else { DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) }; - let data = dispute_statement - .payload_data(candidate_hash, session_index) - .map_err(|_| SignedDisputeStatementError::PayloadError)?; + let data = dispute_statement.payload_data(candidate_hash, session_index); let signature = keystore - .sr25519_sign(ValidatorId::ID, validator_public.as_ref(), &data) - .map_err(SignedDisputeStatementError::KeyStoreError)? + .sr25519_sign(ValidatorId::ID, validator_public.as_ref(), &data)? .map(|sig| Self { dispute_statement, candidate_hash, diff --git a/polkadot/node/primitives/src/lib.rs b/polkadot/node/primitives/src/lib.rs index 6ac6b82c223..dab72bb2a5e 100644 --- a/polkadot/node/primitives/src/lib.rs +++ b/polkadot/node/primitives/src/lib.rs @@ -58,7 +58,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.5.0"; +pub const NODE_VERSION: &'static str = "1.1.0"; // For a 16-ary Merkle Prefix Trie, we can expect at most 16 32-byte hashes per node // plus some overhead: @@ -442,7 +442,7 @@ pub struct CollationSecondedSignal { pub relay_parent: Hash, /// The statement about seconding the collation. /// - /// Anything else than [`Statement::Seconded`] is forbidden here. + /// Anything else than [`Statement::Seconded`](Statement::Seconded) is forbidden here. pub statement: SignedFullStatement, } diff --git a/polkadot/node/service/Cargo.toml b/polkadot/node/service/Cargo.toml index 85accff9e29..e7a4f4a825c 100644 --- a/polkadot/node/service/Cargo.toml +++ b/polkadot/node/service/Cargo.toml @@ -7,9 +7,6 @@ edition.workspace = true license.workspace = true description = "Utils to tie different Polkadot components together and allow instantiation of a node." -[lints] -workspace = true - [dependencies] # Substrate Client sc-authority-discovery = { path = "../../../substrate/client/authority-discovery" } @@ -85,14 +82,13 @@ is_executable = "1.0.1" gum = { package = "tracing-gum", path = "../gum" } log = "0.4.17" schnellru = "0.2.1" -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.108" thiserror = "1.0.48" kvdb = "0.13.0" kvdb-rocksdb = { version = "0.19.0", optional = true } -parity-db = { version = "0.4.12", optional = true } +parity-db = { version = "0.4.8", optional = true } codec = { package = "parity-scale-codec", version = "3.6.1" } -parking_lot = "0.12.1" # Polkadot polkadot-core-primitives = { path = "../../core-primitives" } @@ -151,9 +147,9 @@ serial_test = "2.0.0" tempfile = "3.2" [features] -default = ["db", "full-node"] +default = [ "db", "full-node" ] -db = ["service/rocksdb"] +db = [ "service/rocksdb" ] full-node = [ "kvdb-rocksdb", @@ -184,8 +180,8 @@ full-node = [ ] # Configure the native runtimes to use. -westend-native = ["westend-runtime", "westend-runtime-constants"] -rococo-native = ["rococo-runtime", "rococo-runtime-constants"] +westend-native = [ "westend-runtime", "westend-runtime-constants" ] +rococo-native = [ "rococo-runtime", "rococo-runtime-constants" ] runtime-benchmarks = [ "frame-benchmarking-cli/runtime-benchmarks", @@ -222,9 +218,13 @@ fast-runtime = [ "westend-runtime?/fast-runtime", ] -malus = ["full-node"] +malus = [ "full-node" ] runtime-metrics = [ "polkadot-runtime-parachains/runtime-metrics", "rococo-runtime?/runtime-metrics", "westend-runtime?/runtime-metrics", ] + +network-protocol-staging = [ + "polkadot-node-network-protocol/network-protocol-staging", +] diff --git a/polkadot/node/service/chain-specs/kusama.json b/polkadot/node/service/chain-specs/kusama.json index 979550c7570..6676bbe154b 100644 --- a/polkadot/node/service/chain-specs/kusama.json +++ b/polkadot/node/service/chain-specs/kusama.json @@ -33,9 +33,7 @@ "/dns/ksm-bootnode.stakeworld.io/tcp/30301/ws/p2p/12D3KooWFRin7WWVS6RgUsSpkfUHSv4tfGKnr2zJPmf1pbMv118H", "/dns/ksm-bootnode.stakeworld.io/tcp/30302/wss/p2p/12D3KooWFRin7WWVS6RgUsSpkfUHSv4tfGKnr2zJPmf1pbMv118H", "/dns/ksm14.rotko.net/tcp/35224/wss/p2p/12D3KooWAa5THTw8HPfnhEei23HdL8P9McBXdozG2oTtMMksjZkK", - "/dns/ksm14.rotko.net/tcp/33224/p2p/12D3KooWAa5THTw8HPfnhEei23HdL8P9McBXdozG2oTtMMksjZkK", - "/dns/ibp-boot-kusama.luckyfriday.io/tcp/30333/p2p/12D3KooW9vu1GWHBuxyhm7rZgD3fhGZpNajPXFexadvhujWMgwfT", - "/dns/ibp-boot-kusama.luckyfriday.io/tcp/30334/wss/p2p/12D3KooW9vu1GWHBuxyhm7rZgD3fhGZpNajPXFexadvhujWMgwfT" + "/dns/ksm14.rotko.net/tcp/33224/p2p/12D3KooWAa5THTw8HPfnhEei23HdL8P9McBXdozG2oTtMMksjZkK" ], "telemetryEndpoints": [ [ diff --git a/polkadot/node/service/chain-specs/polkadot.json b/polkadot/node/service/chain-specs/polkadot.json index 71dbb900403..53349208816 100644 --- a/polkadot/node/service/chain-specs/polkadot.json +++ b/polkadot/node/service/chain-specs/polkadot.json @@ -34,9 +34,7 @@ "/dns/dot-bootnode.stakeworld.io/tcp/30311/ws/p2p/12D3KooWAb5MyC1UJiEQJk4Hg4B2Vi3AJdqSUhTGYUqSnEqCFMFg", "/dns/dot-bootnode.stakeworld.io/tcp/30312/wss/p2p/12D3KooWAb5MyC1UJiEQJk4Hg4B2Vi3AJdqSUhTGYUqSnEqCFMFg", "/dns/dot14.rotko.net/tcp/35214/wss/p2p/12D3KooWPyEvPEXghnMC67Gff6PuZiSvfx3fmziKiPZcGStZ5xff", - "/dns/dot14.rotko.net/tcp/33214/p2p/12D3KooWPyEvPEXghnMC67Gff6PuZiSvfx3fmziKiPZcGStZ5xff", - "/dns/ibp-boot-polkadot.luckyfriday.io/tcp/30333/p2p/12D3KooWEjk6QXrZJ26fLpaajisJGHiz6WiQsR8k7mkM9GmWKnRZ", - "/dns/ibp-boot-polkadot.luckyfriday.io/tcp/30334/wss/p2p/12D3KooWEjk6QXrZJ26fLpaajisJGHiz6WiQsR8k7mkM9GmWKnRZ" + "/dns/dot14.rotko.net/tcp/33214/p2p/12D3KooWPyEvPEXghnMC67Gff6PuZiSvfx3fmziKiPZcGStZ5xff" ], "telemetryEndpoints": [ [ diff --git a/polkadot/node/service/chain-specs/westend.json b/polkadot/node/service/chain-specs/westend.json index 697675871fc..b2ffba9304b 100644 --- a/polkadot/node/service/chain-specs/westend.json +++ b/polkadot/node/service/chain-specs/westend.json @@ -31,9 +31,7 @@ "/dns/wnd-bootnode.stakeworld.io/tcp/30321/ws/p2p/12D3KooWBYdKipcNbrV5rCbgT5hco8HMLME7cE9hHC3ckqCKDuzP", "/dns/wnd-bootnode.stakeworld.io/tcp/30322/wss/p2p/12D3KooWBYdKipcNbrV5rCbgT5hco8HMLME7cE9hHC3ckqCKDuzP", "/dns/wnd14.rotko.net/tcp/35234/wss/p2p/12D3KooWLK8Zj1uZ46phU3vQwiDVda8tB76S8J26rXZQLHpwWkDJ", - "/dns/wnd14.rotko.net/tcp/33234/p2p/12D3KooWLK8Zj1uZ46phU3vQwiDVda8tB76S8J26rXZQLHpwWkDJ", - "/dns/ibp-boot-westend.luckyfriday.io/tcp/30333/p2p/12D3KooWDg1YEytdwFFNWroFj6gio4YFsMB3miSbHKgdpJteUMB9", - "/dns/ibp-boot-westend.luckyfriday.io/tcp/30334/wss/p2p/12D3KooWDg1YEytdwFFNWroFj6gio4YFsMB3miSbHKgdpJteUMB9" + "/dns/wnd14.rotko.net/tcp/33234/p2p/12D3KooWLK8Zj1uZ46phU3vQwiDVda8tB76S8J26rXZQLHpwWkDJ" ], "telemetryEndpoints": [ [ diff --git a/polkadot/node/service/src/chain_spec.rs b/polkadot/node/service/src/chain_spec.rs index fd35a4aaf6a..871d7e82911 100644 --- a/polkadot/node/service/src/chain_spec.rs +++ b/polkadot/node/service/src/chain_spec.rs @@ -18,6 +18,7 @@ use beefy_primitives::ecdsa_crypto::AuthorityId as BeefyId; use grandpa::AuthorityId as GrandpaId; +use pallet_im_online::sr25519::AuthorityId as ImOnlineId; #[cfg(feature = "westend-native")] use pallet_staking::Forcing; use polkadot_primitives::{AccountId, AccountPublic, AssignmentId, ValidatorId}; @@ -161,6 +162,7 @@ fn default_parachains_host_configuration_is_consistent() { fn westend_session_keys( babe: BabeId, grandpa: GrandpaId, + im_online: ImOnlineId, para_validator: ValidatorId, para_assignment: AssignmentId, authority_discovery: AuthorityDiscoveryId, @@ -169,6 +171,7 @@ fn westend_session_keys( westend::SessionKeys { babe, grandpa, + im_online, para_validator, para_assignment, authority_discovery, @@ -180,6 +183,7 @@ fn westend_session_keys( fn rococo_session_keys( babe: BabeId, grandpa: GrandpaId, + im_online: ImOnlineId, para_validator: ValidatorId, para_assignment: AssignmentId, authority_discovery: AuthorityDiscoveryId, @@ -188,6 +192,7 @@ fn rococo_session_keys( rococo_runtime::SessionKeys { babe, grandpa, + im_online, para_validator, para_assignment, authority_discovery, @@ -215,6 +220,7 @@ fn westend_staging_testnet_config_genesis() -> serde_json::Value { AccountId, BabeId, GrandpaId, + ImOnlineId, ValidatorId, AssignmentId, AuthorityDiscoveryId, @@ -231,6 +237,9 @@ fn westend_staging_testnet_config_genesis() -> serde_json::Value { //5Eb7wM65PNgtY6e33FEAzYtU5cRTXt6WQvZTnzaKQwkVcABk hex!["6faae44b21c6f2681a7f60df708e9f79d340f7d441d28bd987fab8d05c6487e8"] .unchecked_into(), + //5CdS2wGo4qdTQceVfEnbZH8vULeBrnGYCxSCxDna4tQSMV6y + hex!["18f5d55f138bfa8e0ea26ed6fa56817b247de3c2e2030a908c63fb37c146473f"] + .unchecked_into(), //5FqMLAgygdX9UqzukDp15Uid9PAKdFAR621U7xtp5ut2NfrW hex!["a6c1a5b501985a83cb1c37630c5b41e6b0a15b3675b2fd94694758e6cfa6794d"] .unchecked_into(), @@ -255,6 +264,9 @@ fn westend_staging_testnet_config_genesis() -> serde_json::Value { //5FXFsPReTUEYPRNKhbTdUathcWBsxTNsLbk2mTpYdKCJewjA hex!["98f4d81cb383898c2c3d54dab28698c0f717c81b509cb32dc6905af3cc697b18"] .unchecked_into(), + //5CDYSCJK91r8y2r1V4Ddrit4PFMEkwZXJe8mNBqGXJ4xWCWq + hex!["06bd7dd4ab4c808c7d09d9cb6bd27fbcd99ad8400e99212b335056c475c24031"] + .unchecked_into(), //5CZjurB78XbSHf6SLkLhCdkqw52Zm7aBYUDdfkLqEDWJ9Zhj hex!["162508accd470e379b04cb0c7c60b35a7d5357e84407a89ed2dd48db4b726960"] .unchecked_into(), @@ -279,6 +291,9 @@ fn westend_staging_testnet_config_genesis() -> serde_json::Value { //5G4kCbgqUhEyrRHCyFwFEkgBZXoYA8sbgsRxT9rY8Tp5Jj5F hex!["b0f8d2b9e4e1eafd4dab6358e0b9d5380d78af27c094e69ae9d6d30ca300fd86"] .unchecked_into(), + //5HVhFBLFTKSZK9fX6RktckWDTgYNoSd33fgonsEC8zfr4ddm + hex!["f03c3e184b2883eec9beaeb97f54321587e7476b228831ea0b5fc6da847ea975"] + .unchecked_into(), //5CS7thd2n54WfqeKU3cjvZzK4z5p7zku1Zw97mSzXgPioAAs hex!["1055100a283968271a0781450b389b9093231be809be1e48a305ebad2a90497e"] .unchecked_into(), @@ -303,6 +318,9 @@ fn westend_staging_testnet_config_genesis() -> serde_json::Value { //5ChfdrAqmLjCeDJvynbMjcxYLHYzPe8UWXd3HnX9JDThUMbn hex!["1c309a70b4e274314b84c9a0a1f973c9c4fc084df5479ef686c54b1ae4950424"] .unchecked_into(), + //5DnsMm24575xK2b2aGfmafiDxwCet6Mr4iiZQeDdWvi8CzuF + hex!["4c64868ba6d8ace235d3efb4c10d745a67cf3bdfeae23b264d7ea2f3439dec42"] + .unchecked_into(), //5D8C3HHEp5E8fJsXRD56494F413CdRSR9QKGXe7v5ZEfymdj hex!["2ee4d78f328db178c54f205ac809da12e291a33bcbd4f29f081ce7e74bdc5044"] .unchecked_into(), @@ -343,6 +361,7 @@ fn westend_staging_testnet_config_genesis() -> serde_json::Value { x.5.clone(), x.6.clone(), x.7.clone(), + x.8.clone(), ), ) }) @@ -389,6 +408,7 @@ fn rococo_staging_testnet_config_genesis() -> serde_json::Value { AccountId, BabeId, GrandpaId, + ImOnlineId, ValidatorId, AssignmentId, AuthorityDiscoveryId, @@ -405,6 +425,9 @@ fn rococo_staging_testnet_config_genesis() -> serde_json::Value { //5CPd3zoV9Aaah4xWucuDivMHJ2nEEmpdi864nPTiyRZp4t87 hex!["0e6d7d1afbcc6547b92995a394ba0daed07a2420be08220a5a1336c6731f0bfa"] .unchecked_into(), + //5F7BEa1LGFksUihyatf3dCDYneB8pWzVyavnByCsm5nBgezi + hex!["86975a37211f8704e947a365b720f7a3e2757988eaa7d0f197e83dba355ef743"] + .unchecked_into(), //5CP6oGfwqbEfML8efqm1tCZsUgRsJztp9L8ZkEUxA16W8PPz hex!["0e07a51d3213842f8e9363ce8e444255990a225f87e80a3d651db7841e1a0205"] .unchecked_into(), @@ -429,6 +452,9 @@ fn rococo_staging_testnet_config_genesis() -> serde_json::Value { //5HnDVBN9mD6mXyx8oryhDbJtezwNSj1VRXgLoYCBA6uEkiao hex!["fcd5f87a6fd5707a25122a01b4dac0a8482259df7d42a9a096606df1320df08d"] .unchecked_into(), + //5DhyXZiuB1LvqYKFgT5tRpgGsN3is2cM9QxgW7FikvakbAZP + hex!["48a910c0af90898f11bd57d37ceaea53c78994f8e1833a7ade483c9a84bde055"] + .unchecked_into(), //5EPEWRecy2ApL5n18n3aHyU1956zXTRqaJpzDa9DoqiggNwF hex!["669a10892119453e9feb4e3f1ee8e028916cc3240022920ad643846fbdbee816"] .unchecked_into(), @@ -453,6 +479,9 @@ fn rococo_staging_testnet_config_genesis() -> serde_json::Value { //5HAes2RQYPbYKbLBfKb88f4zoXv6pPA6Ke8CjN7dob3GpmSP hex!["e1b68fbd84333e31486c08e6153d9a1415b2e7e71b413702b7d64e9b631184a1"] .unchecked_into(), + //5HTXBf36LXmkFWJLokNUK6fPxVpkr2ToUnB1pvaagdGu4c1T + hex!["ee93e26259decb89afcf17ef2aa0fa2db2e1042fb8f56ecfb24d19eae8629878"] + .unchecked_into(), //5FtAGDZYJKXkhVhAxCQrXmaP7EE2mGbBMfmKDHjfYDgq2BiU hex!["a8e61ffacafaf546283dc92d14d7cc70ea0151a5dd81fdf73ff5a2951f2b6037"] .unchecked_into(), @@ -477,6 +506,9 @@ fn rococo_staging_testnet_config_genesis() -> serde_json::Value { //5DJV3zCBTJBLGNDCcdWrYxWDacSz84goGTa4pFeKVvehEBte hex!["36be9069cdb4a8a07ecd51f257875150f0a8a1be44a10d9d98dabf10a030aef4"] .unchecked_into(), + //5FHf8kpK4fPjEJeYcYon2gAPwEBubRvtwpzkUbhMWSweKPUY + hex!["8e95b9b5b4dc69790b67b566567ca8bf8cdef3a3a8bb65393c0d1d1c87cd2d2c"] + .unchecked_into(), //5F9FsRjpecP9GonktmtFL3kjqNAMKjHVFjyjRdTPa4hbQRZA hex!["882d72965e642677583b333b2d173ac94b5fd6c405c76184bb14293be748a13b"] .unchecked_into(), @@ -501,6 +533,9 @@ fn rococo_staging_testnet_config_genesis() -> serde_json::Value { //5EX1JBghGbQqWohTPU6msR9qZ2nYPhK9r3RTQ2oD1K8TCxaG hex!["6c878e33b83c20324238d22240f735457b6fba544b383e70bb62a27b57380c81"] .unchecked_into(), + //5GqL8RbVAuNXpDhjQi1KrS1MyNuKhvus2AbmQwRGjpuGZmFu + hex!["d2f9d537ffa59919a4028afdb627c14c14c97a1547e13e8e82203d2049b15b1a"] + .unchecked_into(), //5EUNaBpX9mJgcmLQHyG5Pkms6tbDiKuLbeTEJS924Js9cA1N hex!["6a8570b9c6408e54bacf123cc2bb1b0f087f9c149147d0005badba63a5a4ac01"] .unchecked_into(), @@ -525,6 +560,9 @@ fn rococo_staging_testnet_config_genesis() -> serde_json::Value { //5GzDPGbUM9uH52ZEwydasTj8edokGUJ7vEpoFWp9FE1YNuFB hex!["d9c056c98ca0e6b4eb7f5c58c007c1db7be0fe1f3776108f797dd4990d1ccc33"] .unchecked_into(), + //5GWZbVkJEfWZ7fRca39YAQeqri2Z7pkeHyd7rUctUHyQifLp + hex!["c4a980da30939d5bb9e4a734d12bf81259ae286aa21fa4b65405347fa40eff35"] + .unchecked_into(), //5CmLCFeSurRXXtwMmLcVo7sdJ9EqDguvJbuCYDcHkr3cpqyE hex!["1efc23c0b51ad609ab670ecf45807e31acbd8e7e5cb7c07cf49ee42992d2867c"] .unchecked_into(), @@ -549,6 +587,9 @@ fn rococo_staging_testnet_config_genesis() -> serde_json::Value { //5DnEySxbnppWEyN8cCLqvGjAorGdLRg2VmkY96dbJ1LHFK8N hex!["4bea0b37e0cce9bddd80835fa2bfd5606f5dcfb8388bbb10b10c483f0856cf14"] .unchecked_into(), + //5E1Y1FJ7dVP7qtE3wm241pTm72rTMcDT5Jd8Czv7Pwp7N3AH + hex!["560d90ca51e9c9481b8a9810060e04d0708d246714960439f804e5c6f40ca651"] + .unchecked_into(), //5CAC278tFCHAeHYqE51FTWYxHmeLcENSS1RG77EFRTvPZMJT hex!["042f07fc5268f13c026bbe199d63e6ac77a0c2a780f71cda05cee5a6f1b3f11f"] .unchecked_into(), @@ -573,6 +614,9 @@ fn rococo_staging_testnet_config_genesis() -> serde_json::Value { //5DrA2fZdzmNqT5j6DXNwVxPBjDV9jhkAqvjt6Us3bQHKy3cF hex!["4ee66173993dd0db5d628c4c9cb61a27b76611ad3c3925947f0d0011ee2c5dcc"] .unchecked_into(), + //5FNFDUGNLUtqg5LgrwYLNmBiGoP8KRxsvQpBkc7GQP6qaBUG + hex!["92156f54a114ee191415898f2da013d9db6a5362d6b36330d5fc23e27360ab66"] + .unchecked_into(), //5Gx6YeNhynqn8qkda9QKpc9S7oDr4sBrfAu516d3sPpEt26F hex!["d822d4088b20dca29a580a577a97d6f024bb24c9550bebdfd7d2d18e946a1c7d"] .unchecked_into(), @@ -613,6 +657,7 @@ fn rococo_staging_testnet_config_genesis() -> serde_json::Value { x.5.clone(), x.6.clone(), x.7.clone(), + x.8.clone(), ), ) }) @@ -723,24 +768,35 @@ pub fn get_authority_keys_from_seed( AccountId, BabeId, GrandpaId, + ImOnlineId, ValidatorId, AssignmentId, AuthorityDiscoveryId, BeefyId, ) { let keys = get_authority_keys_from_seed_no_beefy(seed); - (keys.0, keys.1, keys.2, keys.3, keys.4, keys.5, keys.6, get_from_seed::(seed)) + (keys.0, keys.1, keys.2, keys.3, keys.4, keys.5, keys.6, keys.7, get_from_seed::(seed)) } /// Helper function to generate stash, controller and session key from seed pub fn get_authority_keys_from_seed_no_beefy( seed: &str, -) -> (AccountId, AccountId, BabeId, GrandpaId, ValidatorId, AssignmentId, AuthorityDiscoveryId) { +) -> ( + AccountId, + AccountId, + BabeId, + GrandpaId, + ImOnlineId, + ValidatorId, + AssignmentId, + AuthorityDiscoveryId, +) { ( get_account_id_from_seed::(&format!("{}//stash", seed)), get_account_id_from_seed::(seed), get_from_seed::(seed), get_from_seed::(seed), + get_from_seed::(seed), get_from_seed::(seed), get_from_seed::(seed), get_from_seed::(seed), @@ -773,6 +829,7 @@ pub fn westend_testnet_genesis( AccountId, BabeId, GrandpaId, + ImOnlineId, ValidatorId, AssignmentId, AuthorityDiscoveryId, @@ -804,6 +861,7 @@ pub fn westend_testnet_genesis( x.5.clone(), x.6.clone(), x.7.clone(), + x.8.clone(), ), ) }) @@ -841,6 +899,7 @@ pub fn rococo_testnet_genesis( AccountId, BabeId, GrandpaId, + ImOnlineId, ValidatorId, AssignmentId, AuthorityDiscoveryId, @@ -871,6 +930,7 @@ pub fn rococo_testnet_genesis( x.5.clone(), x.6.clone(), x.7.clone(), + x.8.clone(), ), ) }) diff --git a/polkadot/node/service/src/fake_runtime_api.rs b/polkadot/node/service/src/fake_runtime_api.rs index ccc3da22400..d9553afa024 100644 --- a/polkadot/node/service/src/fake_runtime_api.rs +++ b/polkadot/node/service/src/fake_runtime_api.rs @@ -116,7 +116,7 @@ sp_api::impl_runtime_apis! { } } - impl runtime_api::ParachainHost for Runtime { + impl runtime_api::ParachainHost for Runtime { fn validators() -> Vec { unimplemented!() } diff --git a/polkadot/node/service/src/grandpa_support.rs b/polkadot/node/service/src/grandpa_support.rs index 729dbfde5c7..3a767d9783f 100644 --- a/polkadot/node/service/src/grandpa_support.rs +++ b/polkadot/node/service/src/grandpa_support.rs @@ -16,6 +16,8 @@ //! Polkadot-specific GRANDPA integration utilities. +use std::sync::Arc; + use sp_runtime::traits::{Block as BlockT, Header as _, NumberFor}; use crate::HeaderProvider; @@ -57,6 +59,55 @@ where } } +/// A custom GRANDPA voting rule that "pauses" voting (i.e. keeps voting for the +/// same last finalized block) after a given block at height `N` has been +/// finalized and for a delay of `M` blocks, i.e. until the best block reaches +/// `N` + `M`, the voter will keep voting for block `N`. +#[derive(Clone)] +pub(crate) struct PauseAfterBlockFor(pub(crate) N, pub(crate) N); + +impl grandpa::VotingRule for PauseAfterBlockFor> +where + Block: BlockT, + B: sp_blockchain::HeaderBackend + 'static, +{ + fn restrict_vote( + &self, + backend: Arc, + base: &Block::Header, + best_target: &Block::Header, + current_target: &Block::Header, + ) -> grandpa::VotingRuleResult { + let aux = || { + // only restrict votes targeting a block higher than the block + // we've set for the pause + if *current_target.number() > self.0 { + // if we're past the pause period (i.e. `self.0 + self.1`) + // then we no longer need to restrict any votes + if *best_target.number() > self.0 + self.1 { + return None + } + + // if we've finalized the pause block, just keep returning it + // until best number increases enough to pass the condition above + if *base.number() >= self.0 { + return Some((base.hash(), *base.number())) + } + + // otherwise find the target header at the pause block + // to vote on + return walk_backwards_to_target_block(&*backend, self.0, current_target).ok() + } + + None + }; + + let target = aux(); + + Box::pin(async move { target }) + } +} + /// GRANDPA hard forks due to borked migration of session keys after a runtime /// upgrade (at #1491596), the signaled authority set changes were invalid /// (blank keys) and were impossible to finalize. The authorities for these @@ -163,3 +214,130 @@ pub(crate) fn kusama_hard_forks() -> Vec> { }) .collect() } + +#[cfg(test)] +mod tests { + use consensus_common::BlockOrigin; + use grandpa::VotingRule; + use polkadot_test_client::{ + ClientBlockImportExt, DefaultTestClientBuilderExt, InitPolkadotBlockBuilder, + TestClientBuilder, TestClientBuilderExt, + }; + use sp_blockchain::HeaderBackend; + use sp_runtime::traits::Header; + use std::sync::Arc; + + #[test] + fn grandpa_pause_voting_rule_works() { + let _ = env_logger::try_init(); + + let client = Arc::new(TestClientBuilder::new().build()); + let mut hashes = vec![]; + hashes.push(client.info().genesis_hash); + + let mut push_blocks = { + let mut client = client.clone(); + + move |hashes: &mut Vec<_>, n| { + for _ in 0..n { + let block = client.init_polkadot_block_builder().build().unwrap().block; + hashes.push(block.header.hash()); + futures::executor::block_on(client.import(BlockOrigin::Own, block)).unwrap(); + } + } + }; + + let get_header = { + let client = client.clone(); + move |n| client.expect_header(n).unwrap() + }; + + // the rule should filter all votes after block #20 + // is finalized until block #50 is imported. + let voting_rule = super::PauseAfterBlockFor(20, 30); + + // add 10 blocks + push_blocks(&mut hashes, 10); + assert_eq!(client.info().best_number, 10); + + // we have not reached the pause block + // therefore nothing should be restricted + assert_eq!( + futures::executor::block_on(voting_rule.restrict_vote( + client.clone(), + &get_header(hashes[0]), + &get_header(hashes[10]), + &get_header(hashes[10]) + )), + None, + ); + + // add 15 more blocks + // best block: #25 + push_blocks(&mut hashes, 15); + + // we are targeting the pause block, + // the vote should not be restricted + assert_eq!( + futures::executor::block_on(voting_rule.restrict_vote( + client.clone(), + &get_header(hashes[10]), + &get_header(hashes[20]), + &get_header(hashes[20]) + )), + None, + ); + + // we are past the pause block, votes should + // be limited to the pause block. + let pause_block = get_header(hashes[20]); + assert_eq!( + futures::executor::block_on(voting_rule.restrict_vote( + client.clone(), + &get_header(hashes[10]), + &get_header(hashes[21]), + &get_header(hashes[21]) + )), + Some((pause_block.hash(), *pause_block.number())), + ); + + // we've finalized the pause block, so we'll keep + // restricting our votes to it. + assert_eq!( + futures::executor::block_on(voting_rule.restrict_vote( + client.clone(), + &pause_block, // #20 + &get_header(hashes[21]), + &get_header(hashes[21]), + )), + Some((pause_block.hash(), *pause_block.number())), + ); + + // add 30 more blocks + // best block: #55 + push_blocks(&mut hashes, 30); + + // we're at the last block of the pause, this block + // should still be considered in the pause period + assert_eq!( + futures::executor::block_on(voting_rule.restrict_vote( + client.clone(), + &pause_block, // #20 + &get_header(hashes[50]), + &get_header(hashes[50]), + )), + Some((pause_block.hash(), *pause_block.number())), + ); + + // we're past the pause period, no votes should be filtered + assert_eq!( + futures::executor::block_on(voting_rule.restrict_vote( + client.clone(), + &pause_block, // #20 + &get_header(hashes[51]), + &get_header(hashes[51]), + )), + None, + ); + } +} diff --git a/polkadot/node/service/src/lib.rs b/polkadot/node/service/src/lib.rs index e92e15fc0e0..c03835b2a4b 100644 --- a/polkadot/node/service/src/lib.rs +++ b/polkadot/node/service/src/lib.rs @@ -51,8 +51,7 @@ use { }, polkadot_node_core_dispute_coordinator::Config as DisputeCoordinatorConfig, polkadot_node_network_protocol::{ - peer_set::{PeerSet, PeerSetProtocolNames}, - request_response::ReqProtocolNames, + peer_set::PeerSetProtocolNames, request_response::ReqProtocolNames, }, sc_client_api::BlockBackend, sc_transaction_pool_api::OffchainTransactionPoolFactory, @@ -75,7 +74,7 @@ pub use { #[cfg(feature = "full-node")] use polkadot_node_subsystem::jaeger; -use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Duration}; +use std::{path::PathBuf, sync::Arc, time::Duration}; use prometheus_endpoint::Registry; #[cfg(feature = "full-node")] @@ -624,17 +623,13 @@ where #[cfg(feature = "full-node")] pub struct NewFullParams { pub is_parachain_node: IsParachainNode, + pub grandpa_pause: Option<(u32, u32)>, pub enable_beefy: bool, - /// Whether to enable the block authoring backoff on production networks - /// where it isn't enabled by default. - pub force_authoring_backoff: bool, pub jaeger_agent: Option, pub telemetry_worker_handle: Option, /// The version of the node. TESTING ONLY: `None` can be passed to skip the node/worker version /// check, both on startup and in the workers. pub node_version: Option, - /// Whether the node is attempting to run as a secure validator. - pub secure_validator_mode: bool, /// An optional path to a directory containing the workers. pub workers_path: Option, /// Optional custom names for the prepare and execute workers. @@ -719,12 +714,11 @@ pub fn new_full( mut config: Configuration, NewFullParams { is_parachain_node, + grandpa_pause, enable_beefy, - force_authoring_backoff, jaeger_agent, telemetry_worker_handle, node_version, - secure_validator_mode, workers_path, workers_names, overseer_gen, @@ -739,21 +733,15 @@ pub fn new_full( let is_offchain_indexing_enabled = config.offchain_worker.indexing_enabled; let role = config.role.clone(); let force_authoring = config.force_authoring; - let backoff_authoring_blocks = if !force_authoring_backoff && - (config.chain_spec.is_polkadot() || config.chain_spec.is_kusama()) - { - // the block authoring backoff is disabled by default on production networks - None - } else { + let backoff_authoring_blocks = { let mut backoff = sc_consensus_slots::BackoffAuthoringOnFinalizedHeadLagging::default(); if config.chain_spec.is_rococo() || config.chain_spec.is_wococo() || - config.chain_spec.is_versi() || - config.chain_spec.is_dev() + config.chain_spec.is_versi() { - // on testnets that are in flux (like rococo or versi), finality has stalled - // sometimes due to operational issues and it's annoying to slow down block + // it's a testnet that's in flux, finality has stalled sometimes due + // to operational issues and it's annoying to slow down block // production to 1 block per hour. backoff.max_interval = 10; } @@ -813,9 +801,9 @@ pub fn new_full( // anything in terms of behaviour, but makes the logs more consistent with the other // Substrate nodes. let grandpa_protocol_name = grandpa::protocol_standard_name(&genesis_hash, &config.chain_spec); - let (grandpa_protocol_config, grandpa_notification_service) = - grandpa::grandpa_peers_set_config(grandpa_protocol_name.clone()); - net_config.add_notification_protocol(grandpa_protocol_config); + net_config.add_notification_protocol(grandpa::grandpa_peers_set_config( + grandpa_protocol_name.clone(), + )); let beefy_gossip_proto_name = beefy::gossip_protocol_name(&genesis_hash, config.chain_spec.fork_id()); @@ -828,17 +816,12 @@ pub fn new_full( client.clone(), prometheus_registry.clone(), ); - let beefy_notification_service = match enable_beefy { - false => None, - true => { - let (beefy_notification_config, beefy_notification_service) = - beefy::communication::beefy_peers_set_config(beefy_gossip_proto_name.clone()); - - net_config.add_notification_protocol(beefy_notification_config); - net_config.add_request_response_protocol(beefy_req_resp_cfg); - Some(beefy_notification_service) - }, - }; + if enable_beefy { + net_config.add_notification_protocol(beefy::communication::beefy_peers_set_config( + beefy_gossip_proto_name.clone(), + )); + net_config.add_request_response_protocol(beefy_req_resp_cfg); + } // validation/collation protocols are enabled only if `Overseer` is enabled let peerset_protocol_names = @@ -849,21 +832,13 @@ pub fn new_full( // // Collators and parachain full nodes require the collator and validator networking to send // collations and to be able to recover PoVs. - let notification_services = - if role.is_authority() || is_parachain_node.is_running_alongside_parachain_node() { - use polkadot_network_bridge::{peer_sets_info, IsAuthority}; - let is_authority = if role.is_authority() { IsAuthority::Yes } else { IsAuthority::No }; - - peer_sets_info(is_authority, &peerset_protocol_names) - .into_iter() - .map(|(config, (peerset, service))| { - net_config.add_notification_protocol(config); - (peerset, service) - }) - .collect::>>() - } else { - std::collections::HashMap::new() - }; + if role.is_authority() || is_parachain_node.is_running_alongside_parachain_node() { + use polkadot_network_bridge::{peer_sets_info, IsAuthority}; + let is_authority = if role.is_authority() { IsAuthority::Yes } else { IsAuthority::No }; + for config in peer_sets_info(is_authority, &peerset_protocol_names) { + net_config.add_notification_protocol(config); + } + } let req_protocol_names = ReqProtocolNames::new(&genesis_hash, config.chain_spec.fork_id()); @@ -956,7 +931,6 @@ pub fn new_full( .ok_or(Error::DatabasePathRequired)? .join("pvf-artifacts"), node_version, - secure_validator_mode, prep_worker_path, exec_worker_path, }) @@ -1096,7 +1070,6 @@ pub fn new_full( offchain_transaction_pool_factory: OffchainTransactionPoolFactory::new( transaction_pool.clone(), ), - notification_services, }, ) .map_err(|e| { @@ -1198,15 +1171,13 @@ pub fn new_full( // need a keystore, regardless of which protocol we use below. let keystore_opt = if role.is_authority() { Some(keystore_container.keystore()) } else { None }; - // beefy is enabled if its notification service exists - if let Some(notification_service) = beefy_notification_service { + if enable_beefy { let justifications_protocol_name = beefy_on_demand_justifications_handler.protocol_name(); let network_params = beefy::BeefyNetworkParams { network: network.clone(), sync: sync_service.clone(), gossip_protocol_name: beefy_gossip_proto_name, justifications_protocol_name, - notification_service, _phantom: core::marker::PhantomData::, }; let payload_provider = beefy_primitives::mmr::MmrRootProvider::new(client.clone()); @@ -1267,14 +1238,32 @@ pub fn new_full( // provide better guarantees of block and vote data availability than // the observer. - let mut voting_rules_builder = grandpa::VotingRulesBuilder::default(); + // add a custom voting rule to temporarily stop voting for new blocks + // after the given pause block is finalized and restarting after the + // given delay. + let mut builder = grandpa::VotingRulesBuilder::default(); #[cfg(not(feature = "malus"))] let _malus_finality_delay = None; if let Some(delay) = _malus_finality_delay { info!(?delay, "Enabling malus finality delay",); - voting_rules_builder = voting_rules_builder.add(grandpa::BeforeBestBlockBy(delay)); + builder = builder.add(grandpa::BeforeBestBlockBy(delay)); + }; + + let voting_rule = match grandpa_pause { + Some((block, delay)) => { + info!( + block_number = %block, + delay = %delay, + "GRANDPA scheduled voting pause set for block #{} with a duration of {} blocks.", + block, + delay, + ); + + builder.add(grandpa_support::PauseAfterBlockFor(block, delay)).build() + }, + None => builder.build(), }; let grandpa_config = grandpa::GrandpaParams { @@ -1282,11 +1271,10 @@ pub fn new_full( link: link_half, network: network.clone(), sync: sync_service.clone(), - voting_rule: voting_rules_builder.build(), + voting_rule, prometheus_registry: prometheus_registry.clone(), shared_voter_state, telemetry: telemetry.as_ref().map(|x| x.handle()), - notification_service: grandpa_notification_service, offchain_tx_pool_factory: OffchainTransactionPoolFactory::new(transaction_pool.clone()), }; diff --git a/polkadot/node/service/src/overseer.rs b/polkadot/node/service/src/overseer.rs index 599563d6454..fd618863eea 100644 --- a/polkadot/node/service/src/overseer.rs +++ b/polkadot/node/service/src/overseer.rs @@ -26,7 +26,7 @@ use polkadot_node_core_candidate_validation::Config as CandidateValidationConfig use polkadot_node_core_chain_selection::Config as ChainSelectionConfig; use polkadot_node_core_dispute_coordinator::Config as DisputeCoordinatorConfig; use polkadot_node_network_protocol::{ - peer_set::{PeerSet, PeerSetProtocolNames}, + peer_set::PeerSetProtocolNames, request_response::{ v1 as request_v1, v2 as request_v2, IncomingRequestReceiver, ReqProtocolNames, }, @@ -41,16 +41,15 @@ use polkadot_overseer::{ OverseerConnector, OverseerHandle, SpawnGlue, }; -use parking_lot::Mutex; use polkadot_primitives::runtime_api::ParachainHost; use sc_authority_discovery::Service as AuthorityDiscoveryService; use sc_client_api::AuxStore; use sc_keystore::LocalKeystore; -use sc_network::{NetworkStateInfo, NotificationService}; +use sc_network::NetworkStateInfo; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_consensus_babe::BabeApi; -use std::{collections::HashMap, sync::Arc}; +use std::sync::Arc; pub use polkadot_approval_distribution::ApprovalDistribution as ApprovalDistributionSubsystem; pub use polkadot_availability_bitfield_distribution::BitfieldDistribution as BitfieldDistributionSubsystem; @@ -141,8 +140,6 @@ where pub peerset_protocol_names: PeerSetProtocolNames, /// The offchain transaction pool factory. pub offchain_transaction_pool_factory: OffchainTransactionPoolFactory, - /// Notification services for validation/collation protocols. - pub notification_services: HashMap>, } /// Obtain a prepared `OverseerBuilder`, that is initialized @@ -176,7 +173,6 @@ pub fn prepared_overseer_builder( req_protocol_names, peerset_protocol_names, offchain_transaction_pool_factory, - notification_services, }: OverseerGenArgs, ) -> Result< InitializedOverseerBuilder< @@ -222,7 +218,6 @@ where use polkadot_node_subsystem_util::metrics::Metrics; let metrics = ::register(registry)?; - let notification_sinks = Arc::new(Mutex::new(HashMap::new())); let spawner = SpawnGlue(spawner); @@ -240,7 +235,6 @@ where network_bridge_metrics.clone(), req_protocol_names, peerset_protocol_names.clone(), - notification_sinks.clone(), )) .network_bridge_rx(NetworkBridgeRxSubsystem::new( network_service.clone(), @@ -248,8 +242,6 @@ where Box::new(sync_service.clone()), network_bridge_metrics, peerset_protocol_names, - notification_services, - notification_sinks, )) .availability_distribution(AvailabilityDistributionSubsystem::new( keystore.clone(), diff --git a/polkadot/node/service/src/parachains_db/upgrade.rs b/polkadot/node/service/src/parachains_db/upgrade.rs index d22eebb5c8d..1d76c79d3e3 100644 --- a/polkadot/node/service/src/parachains_db/upgrade.rs +++ b/polkadot/node/service/src/parachains_db/upgrade.rs @@ -20,16 +20,10 @@ use std::{ fs, io, path::{Path, PathBuf}, str::FromStr, - sync::Arc, }; -use polkadot_node_core_approval_voting::approval_db::{ - common::{Config as ApprovalDbConfig, Result as ApprovalDbResult}, - v2::migration_helpers::v1_to_latest, - v3::migration_helpers::v2_to_latest, -}; -use polkadot_node_subsystem_util::database::{ - kvdb_impl::DbAdapter as RocksDbAdapter, paritydb_impl::DbAdapter as ParityDbAdapter, Database, +use polkadot_node_core_approval_voting::approval_db::v2::{ + migration_helpers::v1_to_v2, Config as ApprovalDbConfig, }; type Version = u32; @@ -38,9 +32,7 @@ const VERSION_FILE_NAME: &'static str = "parachain_db_version"; /// Current db version. /// Version 4 changes approval db format for `OurAssignment`. -/// Version 5 changes approval db format to hold some additional -/// information about delayed approvals. -pub(crate) const CURRENT_VERSION: Version = 5; +pub(crate) const CURRENT_VERSION: Version = 4; #[derive(thiserror::Error, Debug)] pub enum Error { @@ -109,8 +101,7 @@ pub(crate) fn try_upgrade_db_to_next_version( // 2 -> 3 migration Some(2) => migrate_from_version_2_to_3(db_path, db_kind)?, // 3 -> 4 migration - Some(3) => migrate_from_version_3_or_4_to_5(db_path, db_kind, v1_to_latest)?, - Some(4) => migrate_from_version_3_or_4_to_5(db_path, db_kind, v2_to_latest)?, + Some(3) => migrate_from_version_3_to_4(db_path, db_kind)?, // Already at current version, do nothing. Some(CURRENT_VERSION) => CURRENT_VERSION, // This is an arbitrary future version, we don't handle it. @@ -183,19 +174,14 @@ fn migrate_from_version_1_to_2(path: &Path, db_kind: DatabaseKind) -> Result( - path: &Path, - db_kind: DatabaseKind, - migration_function: F, -) -> Result -where - F: Fn(Arc, ApprovalDbConfig) -> ApprovalDbResult<()>, -{ +fn migrate_from_version_3_to_4(path: &Path, db_kind: DatabaseKind) -> Result { gum::info!(target: LOG_TARGET, "Migrating parachains db from version 3 to version 4 ..."); + use polkadot_node_subsystem_util::database::{ + kvdb_impl::DbAdapter as RocksDbAdapter, paritydb_impl::DbAdapter as ParityDbAdapter, + }; + use std::sync::Arc; let approval_db_config = ApprovalDbConfig { col_approval_data: super::REAL_COLUMNS.col_approval_data }; @@ -208,8 +194,7 @@ where super::columns::v3::ORDERED_COL, ); - migration_function(Arc::new(db), approval_db_config) - .map_err(|_| Error::MigrationFailed)?; + v1_to_v2(Arc::new(db), approval_db_config).map_err(|_| Error::MigrationFailed)?; }, DatabaseKind::RocksDB => { let db_path = path @@ -222,8 +207,7 @@ where &super::columns::v3::ORDERED_COL, ); - migration_function(Arc::new(db), approval_db_config) - .map_err(|_| Error::MigrationFailed)?; + v1_to_v2(Arc::new(db), approval_db_config).map_err(|_| Error::MigrationFailed)?; }, }; @@ -457,12 +441,7 @@ mod tests { columns::{v2::COL_SESSION_WINDOW_DATA, v4::*}, *, }; - use kvdb_rocksdb::{Database, DatabaseConfig}; - use polkadot_node_core_approval_voting::approval_db::{ - v2::migration_helpers::v1_fill_test_data, - v3::migration_helpers::{v1_to_latest_sanity_check, v2_fill_test_data}, - }; - use polkadot_node_subsystem_util::database::kvdb_impl::DbAdapter; + use polkadot_node_core_approval_voting::approval_db::v2::migration_helpers::v1_to_v2_fill_test_data; use test_helpers::dummy_candidate_receipt; #[test] @@ -601,38 +580,11 @@ mod tests { } #[test] - fn test_migrate_3_to_5() { - let db_dir = tempfile::tempdir().unwrap(); - let db_path = db_dir.path().to_str().unwrap(); - let db_cfg: DatabaseConfig = DatabaseConfig::with_columns(super::columns::v3::NUM_COLUMNS); - - let approval_cfg = ApprovalDbConfig { - col_approval_data: crate::parachains_db::REAL_COLUMNS.col_approval_data, - }; - - // We need to properly set db version for upgrade to work. - fs::write(version_file_path(db_dir.path()), "3").expect("Failed to write DB version"); - let expected_candidates = { - let db = Database::open(&db_cfg, db_path).unwrap(); - assert_eq!(db.num_columns(), super::columns::v3::NUM_COLUMNS as u32); - let db = DbAdapter::new(db, columns::v3::ORDERED_COL); - // Fill the approval voting column with test data. - v1_fill_test_data(std::sync::Arc::new(db), approval_cfg, dummy_candidate_receipt) - .unwrap() - }; - - try_upgrade_db(&db_dir.path(), DatabaseKind::RocksDB, 5).unwrap(); - - let db_cfg = DatabaseConfig::with_columns(super::columns::v4::NUM_COLUMNS); - let db = Database::open(&db_cfg, db_path).unwrap(); - let db = DbAdapter::new(db, columns::v4::ORDERED_COL); - - v1_to_latest_sanity_check(std::sync::Arc::new(db), approval_cfg, expected_candidates) - .unwrap(); - } + fn test_migrate_3_to_4() { + use kvdb_rocksdb::{Database, DatabaseConfig}; + use polkadot_node_core_approval_voting::approval_db::v2::migration_helpers::v1_to_v2_sanity_check; + use polkadot_node_subsystem_util::database::kvdb_impl::DbAdapter; - #[test] - fn test_migrate_4_to_5() { let db_dir = tempfile::tempdir().unwrap(); let db_path = db_dir.path().to_str().unwrap(); let db_cfg: DatabaseConfig = DatabaseConfig::with_columns(super::columns::v3::NUM_COLUMNS); @@ -642,35 +594,34 @@ mod tests { }; // We need to properly set db version for upgrade to work. - fs::write(version_file_path(db_dir.path()), "4").expect("Failed to write DB version"); + fs::write(version_file_path(db_dir.path()), "3").expect("Failed to write DB version"); let expected_candidates = { let db = Database::open(&db_cfg, db_path).unwrap(); assert_eq!(db.num_columns(), super::columns::v3::NUM_COLUMNS as u32); let db = DbAdapter::new(db, columns::v3::ORDERED_COL); // Fill the approval voting column with test data. - v2_fill_test_data(std::sync::Arc::new(db), approval_cfg, dummy_candidate_receipt) + v1_to_v2_fill_test_data(std::sync::Arc::new(db), approval_cfg, dummy_candidate_receipt) .unwrap() }; - try_upgrade_db(&db_dir.path(), DatabaseKind::RocksDB, 5).unwrap(); + try_upgrade_db(&db_dir.path(), DatabaseKind::RocksDB, 4).unwrap(); let db_cfg = DatabaseConfig::with_columns(super::columns::v4::NUM_COLUMNS); let db = Database::open(&db_cfg, db_path).unwrap(); let db = DbAdapter::new(db, columns::v4::ORDERED_COL); - v1_to_latest_sanity_check(std::sync::Arc::new(db), approval_cfg, expected_candidates) - .unwrap(); + v1_to_v2_sanity_check(std::sync::Arc::new(db), approval_cfg, expected_candidates).unwrap(); } #[test] - fn test_rocksdb_migrate_0_to_5() { + fn test_rocksdb_migrate_0_to_4() { use kvdb_rocksdb::{Database, DatabaseConfig}; let db_dir = tempfile::tempdir().unwrap(); let db_path = db_dir.path().to_str().unwrap(); fs::write(version_file_path(db_dir.path()), "0").expect("Failed to write DB version"); - try_upgrade_db(&db_dir.path(), DatabaseKind::RocksDB, 5).unwrap(); + try_upgrade_db(&db_dir.path(), DatabaseKind::RocksDB, 4).unwrap(); let db_cfg = DatabaseConfig::with_columns(super::columns::v4::NUM_COLUMNS); let db = Database::open(&db_cfg, db_path).unwrap(); @@ -679,7 +630,7 @@ mod tests { } #[test] - fn test_paritydb_migrate_0_to_5() { + fn test_paritydb_migrate_0_to_4() { use parity_db::Db; let db_dir = tempfile::tempdir().unwrap(); @@ -693,7 +644,7 @@ mod tests { assert_eq!(db.num_columns(), columns::v0::NUM_COLUMNS as u8); } - try_upgrade_db(&path, DatabaseKind::ParityDB, 5).unwrap(); + try_upgrade_db(&path, DatabaseKind::ParityDB, 4).unwrap(); let db = Db::open(&paritydb_version_3_config(&path)).unwrap(); assert_eq!(db.num_columns(), columns::v4::NUM_COLUMNS as u8); diff --git a/polkadot/node/subsystem-bench/Cargo.toml b/polkadot/node/subsystem-bench/Cargo.toml deleted file mode 100644 index 08d1a31adf5..00000000000 --- a/polkadot/node/subsystem-bench/Cargo.toml +++ /dev/null @@ -1,61 +0,0 @@ -[package] -name = "polkadot-subsystem-bench" -description = "Subsystem performance benchmark client" -version = "1.0.0" -authors.workspace = true -edition.workspace = true -license.workspace = true -readme = "README.md" -publish = false - -[[bin]] -name = "subsystem-bench" -path = "src/subsystem-bench.rs" - -# Prevent rustdoc error. Already documented from top-level Cargo.toml. -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"] } -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.57" -sp-keystore = { path = "../../../substrate/primitives/keystore" } -sc-keystore = { path = "../../../substrate/client/keystore" } -sp-core = { path = "../../../substrate/primitives/core" } -clap = { version = "4.4.6", features = ["derive"] } -futures = "0.3.21" -futures-timer = "3.0.2" -gum = { package = "tracing-gum", path = "../gum" } -polkadot-erasure-coding = { package = "polkadot-erasure-coding", path = "../../erasure-coding" } -log = "0.4.17" -env_logger = "0.9.0" -rand = "0.8.5" -parity-scale-codec = { version = "3.6.1", features = ["derive", "std"] } -tokio = "1.24.2" -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-service = { path = "../../../substrate/client/service" } -polkadot-node-metrics = { path = "../metrics" } -itertools = "0.11.0" -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 } -serde = "1.0.192" -serde_yaml = "0.9" -paste = "1.0.14" -orchestra = { version = "0.3.3", default-features = false, features = ["futures_channel"] } - -[features] -default = [] diff --git a/polkadot/node/subsystem-bench/README.md b/polkadot/node/subsystem-bench/README.md deleted file mode 100644 index 21844853334..00000000000 --- a/polkadot/node/subsystem-bench/README.md +++ /dev/null @@ -1,216 +0,0 @@ -# Subsystem benchmark client - -Run parachain consensus stress and performance tests on your development machine. - -## Motivation - -The parachain consensus node implementation spans across many modules which we call subsystems. Each subsystem is -responsible for a small part of logic of the parachain consensus pipeline, but in general the most load and -performance issues are localized in just a few core subsystems like `availability-recovery`, `approval-voting` or -`dispute-coordinator`. In the absence of such a tool, we would run large test nets to load/stress test these parts of -the system. Setting up and making sense of the amount of data produced by such a large test is very expensive, hard -to orchestrate and is a huge development time sink. - -This tool aims to solve the problem by making it easy to: - -- set up and run core subsystem load tests locally on your development machine -- iterate and conclude faster when benchmarking new optimizations or comparing implementations -- automate and keep track of performance regressions in CI runs -- simulate various networking topologies, bandwidth and connectivity issues - -## Test environment setup - -`cargo build --profile=testnet --bin subsystem-bench -p polkadot-subsystem-bench` - -The output binary will be placed in `target/testnet/subsystem-bench`. - -### Test metrics - -Subsystem, CPU usage and network metrics are exposed via a prometheus endpoint during the test execution. -A small subset of these collected metrics are displayed in the CLI, but for an in depth analysys of the test results, -a local Grafana/Prometheus stack is needed. - -### Install Prometheus - -Please follow the [official installation guide](https://prometheus.io/docs/prometheus/latest/installation/) for your -platform/OS. - -After succesfully installing and starting up Prometheus, we need to alter it's configuration such that it -will scrape the benchmark prometheus endpoint `127.0.0.1:9999`. Please check the prometheus official documentation -regarding the location of `prometheus.yml`. On MacOS for example the full path `/opt/homebrew/etc/prometheus.yml` - -prometheus.yml: - -``` -global: - scrape_interval: 5s - -scrape_configs: - - job_name: "prometheus" - static_configs: - - targets: ["localhost:9090"] - - job_name: "subsystem-bench" - scrape_interval: 0s500ms - static_configs: - - targets: ['localhost:9999'] -``` - -To complete this step restart Prometheus server such that it picks up the new configuration. - -### Install and setup Grafana - -Follow the [installation guide](https://grafana.com/docs/grafana/latest/setup-grafana/installation/) relevant -to your operating system. - -Once you have the installation up and running, configure the local Prometheus as a data source by following -[this guide](https://grafana.com/docs/grafana/latest/datasources/prometheus/configure-prometheus-data-source/) - -#### Import dashboards - -Follow [this guide](https://grafana.com/docs/grafana/latest/dashboards/manage-dashboards/#export-and-import-dashboards) -to import the dashboards from the repository `grafana` folder. - -## How to run a test - -To run a test, you need to first choose a test objective. Currently, we support the following: - -``` -target/testnet/subsystem-bench --help -The almighty Subsystem Benchmark Tool™️ - -Usage: subsystem-bench [OPTIONS] - -Commands: - data-availability-read Benchmark availability recovery strategies - -``` - -Note: `test-sequence` is a special test objective that wraps up an arbitrary number of test objectives. It is tipically - used to run a suite of tests defined in a `yaml` file like in this [example](examples/availability_read.yaml). - -### Standard test options - -``` -Options: - --network The type of network to be emulated [default: ideal] [possible values: - ideal, healthy, degraded] - --n-cores Number of cores to fetch availability for [default: 100] - --n-validators Number of validators to fetch chunks from [default: 500] - --min-pov-size The minimum pov size in KiB [default: 5120] - --max-pov-size The maximum pov size bytes [default: 5120] - -n, --num-blocks The number of blocks the test is going to run [default: 1] - -p, --peer-bandwidth The bandwidth of simulated remote peers in KiB - -b, --bandwidth The bandwidth of our simulated node in KiB - --peer-error Simulated conection error ratio [0-100] - --peer-min-latency Minimum remote peer latency in milliseconds [0-5000] - --peer-max-latency Maximum remote peer latency in milliseconds [0-5000] - -h, --help Print help - -V, --version Print version -``` - -These apply to all test objectives, except `test-sequence` which relies on the values being specified in a file. - -### Test objectives - -Each test objective can have it's specific configuration options, in contrast with the standard test options. - -For `data-availability-read` the recovery strategy to be used is configurable. - -``` -target/testnet/subsystem-bench data-availability-read --help -Benchmark availability recovery strategies - -Usage: subsystem-bench data-availability-read [OPTIONS] - -Options: - -f, --fetch-from-backers Turbo boost AD Read by fetching the full availability datafrom backers first. Saves CPU - as we don't need to re-construct from chunks. Tipically this is only faster if nodes - have enough bandwidth - -h, --help Print help -``` - -### Understanding the test configuration - -A single test configuration `TestConfiguration` struct applies to a single run of a certain test objective. - -The configuration describes the following important parameters that influence the test duration and resource -usage: - -- how many validators are on the emulated network (`n_validators`) -- how many cores per block the subsystem will have to do work on (`n_cores`) -- for how many blocks the test should run (`num_blocks`) - -From the perspective of the subsystem under test, this means that it will receive an `ActiveLeavesUpdate` signal -followed by an arbitrary amount of messages. This process repeats itself for `num_blocks`. The messages are generally -test payloads pre-generated before the test run, or constructed on pre-genereated payloads. For example the -`AvailabilityRecoveryMessage::RecoverAvailableData` message includes a `CandidateReceipt` which is generated before -the test is started. - -### Example run - -Let's run an availabilty read test which will recover availability for 10 cores with max PoV size on a 500 -node validator network. - -``` - target/testnet/subsystem-bench --n-cores 10 data-availability-read -[2023-11-28T09:01:59Z INFO subsystem_bench::core::display] n_validators = 500, n_cores = 10, pov_size = 5120 - 5120, - error = 0, latency = None -[2023-11-28T09:01:59Z INFO subsystem-bench::availability] Generating template candidate index=0 pov_size=5242880 -[2023-11-28T09:01:59Z INFO subsystem-bench::availability] Created test environment. -[2023-11-28T09:01:59Z INFO subsystem-bench::availability] Pre-generating 10 candidates. -[2023-11-28T09:02:01Z INFO subsystem-bench::core] Initializing network emulation for 500 peers. -[2023-11-28T09:02:01Z INFO substrate_prometheus_endpoint] 〽️ Prometheus exporter started at 127.0.0.1:9999 -[2023-11-28T09:02:01Z INFO subsystem-bench::availability] Current block 1/1 -[2023-11-28T09:02:01Z INFO subsystem_bench::availability] 10 recoveries pending -[2023-11-28T09:02:04Z INFO subsystem_bench::availability] Block time 3231ms -[2023-11-28T09:02:04Z INFO subsystem-bench::availability] Sleeping till end of block (2768ms) -[2023-11-28T09:02:07Z INFO subsystem_bench::availability] All blocks processed in 6001ms -[2023-11-28T09:02:07Z INFO subsystem_bench::availability] Throughput: 51200 KiB/block -[2023-11-28T09:02:07Z INFO subsystem_bench::availability] Block time: 6001 ms -[2023-11-28T09:02:07Z INFO subsystem_bench::availability] - - Total received from network: 66 MiB - Total sent to network: 58 KiB - Total subsystem CPU usage 4.16s - CPU usage per block 4.16s - Total test environment CPU usage 0.00s - CPU usage per block 0.00s -``` - -`Block time` in the context of `data-availability-read` has a different meaning. It measures the amount of time it -took the subsystem to finish processing all of the messages sent in the context of the current test block. - -### Test logs - -You can select log target, subtarget and verbosity just like with Polkadot node CLI, simply setting -`RUST_LOOG="parachain=debug"` turns on debug logs for all parachain consensus subsystems in the test. - -### View test metrics - -Assuming the Grafana/Prometheus stack installation steps completed succesfully, you should be able to -view the test progress in real time by accessing [this link](http://localhost:3000/goto/SM5B8pNSR?orgId=1). - -Now run -`target/testnet/subsystem-bench test-sequence --path polkadot/node/subsystem-bench/examples/availability_read.yaml` -and view the metrics in real time and spot differences between different `n_valiator` values. - -## Create new test objectives - -This tool is intended to make it easy to write new test objectives that focus individual subsystems, -or even multiple subsystems (for example `approval-distribution` and `approval-voting`). - -A special kind of test objectives are performance regression tests for the CI pipeline. These should be sequences -of tests that check the performance characteristics (such as CPU usage, speed) of the subsystem under test in both -happy and negative scenarios (low bandwidth, network errors and low connectivity). - -### Reusable test components - -To faster write a new test objective you need to use some higher level wrappers and logic: `TestEnvironment`, -`TestConfiguration`, `TestAuthorities`, `NetworkEmulator`. To create the `TestEnvironment` you will -need to also build an `Overseer`, but that should be easy using the mockups for subsystems in`core::mock`. - -### Mocking - -Ideally we want to have a single mock implementation for subsystems that can be minimally configured to -be used in different tests. A good example is `runtime-api` which currently only responds to session information -requests based on static data. It can be easily extended to service other requests. diff --git a/polkadot/node/subsystem-bench/examples/availability_read.yaml b/polkadot/node/subsystem-bench/examples/availability_read.yaml deleted file mode 100644 index 311ea972141..00000000000 --- a/polkadot/node/subsystem-bench/examples/availability_read.yaml +++ /dev/null @@ -1,57 +0,0 @@ -TestConfiguration: -# Test 1 -- objective: !DataAvailabilityRead - fetch_from_backers: false - n_validators: 300 - n_cores: 20 - min_pov_size: 5120 - max_pov_size: 5120 - peer_bandwidth: 52428800 - bandwidth: 52428800 - latency: - min_latency: - secs: 0 - nanos: 1000000 - max_latency: - secs: 0 - nanos: 100000000 - error: 3 - num_blocks: 3 - -# Test 2 -- objective: !DataAvailabilityRead - fetch_from_backers: false - n_validators: 500 - n_cores: 20 - min_pov_size: 5120 - max_pov_size: 5120 - peer_bandwidth: 52428800 - bandwidth: 52428800 - latency: - min_latency: - secs: 0 - nanos: 1000000 - max_latency: - secs: 0 - nanos: 100000000 - error: 3 - num_blocks: 3 - -# Test 3 -- objective: !DataAvailabilityRead - fetch_from_backers: false - n_validators: 1000 - n_cores: 20 - min_pov_size: 5120 - max_pov_size: 5120 - peer_bandwidth: 52428800 - bandwidth: 52428800 - latency: - min_latency: - secs: 0 - nanos: 1000000 - max_latency: - secs: 0 - nanos: 100000000 - error: 3 - num_blocks: 3 diff --git a/polkadot/node/subsystem-bench/grafana/availability-read.json b/polkadot/node/subsystem-bench/grafana/availability-read.json deleted file mode 100644 index 31c4ad3c795..00000000000 --- a/polkadot/node/subsystem-bench/grafana/availability-read.json +++ /dev/null @@ -1,1874 +0,0 @@ -{ - "annotations": { - "list": [ - { - "builtIn": 1, - "datasource": { - "type": "datasource", - "uid": "grafana" - }, - "enable": true, - "hide": true, - "iconColor": "rgba(0, 211, 255, 1)", - "name": "Annotations & Alerts", - "target": { - "limit": 100, - "matchAny": false, - "tags": [], - "type": "dashboard" - }, - "type": "dashboard" - } - ] - }, - "description": "Subsystem and test environment metrics", - "editable": true, - "fiscalYearStartMonth": 0, - "graphTooltip": 0, - "id": 2, - "links": [], - "liveNow": false, - "panels": [ - { - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 0, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "insertNulls": false, - "lineInterpolation": "linear", - "lineStyle": { - "fill": "solid" - }, - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "type": "linear" - }, - "showPoints": "auto", - "spanNulls": 60000, - "stacking": { - "group": "A", - "mode": "none" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - } - }, - "overrides": [] - }, - "gridPos": { - "h": 9, - "w": 24, - "x": 0, - "y": 0 - }, - "id": 90, - "interval": "1s", - "options": { - "legend": { - "calcs": [], - "displayMode": "list", - "placement": "bottom", - "showLegend": true - }, - "tooltip": { - "mode": "multi", - "sort": "none" - } - }, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "editorMode": "code", - "expr": "subsystem_benchmark_n_validators{}", - "instant": false, - "legendFormat": "n_vaidators", - "range": true, - "refId": "A" - }, - { - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "editorMode": "code", - "expr": "subsystem_benchmark_n_cores{}", - "hide": false, - "instant": false, - "legendFormat": "n_cores", - "range": true, - "refId": "B" - } - ], - "title": "Test configuration", - "type": "timeseries" - }, - { - "collapsed": false, - "datasource": { - "type": "datasource", - "uid": "grafana" - }, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 9 - }, - "id": 31, - "panels": [], - "targets": [ - { - "datasource": { - "type": "datasource", - "uid": "grafana" - }, - "refId": "A" - } - ], - "title": "Overview", - "type": "row" - }, - { - "datasource": { - "type": "prometheus", - "uid": "$data_source" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 30, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "insertNulls": false, - "lineInterpolation": "linear", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "type": "linear" - }, - "showPoints": "never", - "spanNulls": false, - "stacking": { - "group": "A", - "mode": "normal" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "links": [], - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - }, - "unit": "percentunit" - }, - "overrides": [] - }, - "gridPos": { - "h": 10, - "w": 24, - "x": 0, - "y": 10 - }, - "id": 57, - "interval": "1s", - "options": { - "legend": { - "calcs": [ - "mean", - "min", - "max" - ], - "displayMode": "table", - "placement": "right", - "showLegend": true, - "sortBy": "Mean", - "sortDesc": true - }, - "tooltip": { - "mode": "multi", - "sort": "desc" - } - }, - "pluginVersion": "10.0.2", - "repeat": "nodename", - "targets": [ - { - "datasource": { - "uid": "$data_source" - }, - "editorMode": "code", - "expr": "sum(rate(substrate_tasks_polling_duration_sum{}[2s])) by ($cpu_group_by)", - "interval": "", - "legendFormat": "{{task_group}}", - "range": true, - "refId": "A" - } - ], - "title": "All tasks CPU usage breakdown", - "type": "timeseries" - }, - { - "datasource": { - "type": "prometheus", - "uid": "$data_source" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 30, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "insertNulls": false, - "lineInterpolation": "linear", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "type": "linear" - }, - "showPoints": "never", - "spanNulls": false, - "stacking": { - "group": "A", - "mode": "normal" - }, - "thresholdsStyle": { - "mode": "area" - } - }, - "links": [], - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 6 - } - ] - }, - "unit": "s" - }, - "overrides": [] - }, - "gridPos": { - "h": 10, - "w": 24, - "x": 0, - "y": 20 - }, - "id": 93, - "interval": "1s", - "options": { - "legend": { - "calcs": [ - "mean", - "min", - "max" - ], - "displayMode": "table", - "placement": "right", - "showLegend": true, - "sortBy": "Mean", - "sortDesc": true - }, - "tooltip": { - "mode": "multi", - "sort": "desc" - } - }, - "pluginVersion": "10.0.2", - "targets": [ - { - "datasource": { - "uid": "$data_source" - }, - "editorMode": "code", - "expr": "increase(substrate_tasks_polling_duration_sum{task_group=\"availability-recovery\"}[6s])", - "interval": "", - "legendFormat": "{{task_name}}", - "range": true, - "refId": "A" - } - ], - "title": "Availability subsystem CPU usage per block", - "type": "timeseries" - }, - { - "datasource": { - "type": "prometheus", - "uid": "$data_source" - }, - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 30, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "insertNulls": false, - "lineInterpolation": "linear", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "log": 10, - "type": "log" - }, - "showPoints": "never", - "spanNulls": false, - "stacking": { - "group": "A", - "mode": "none" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "links": [], - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - } - ] - }, - "unit": "s" - }, - "overrides": [] - }, - "gridPos": { - "h": 10, - "w": 24, - "x": 0, - "y": 30 - }, - "id": 94, - "interval": "1s", - "options": { - "legend": { - "calcs": [ - "last" - ], - "displayMode": "table", - "placement": "right", - "showLegend": true, - "sortBy": "Last", - "sortDesc": true - }, - "tooltip": { - "mode": "multi", - "sort": "desc" - } - }, - "pluginVersion": "10.0.2", - "targets": [ - { - "datasource": { - "uid": "$data_source" - }, - "editorMode": "code", - "expr": "sum(substrate_tasks_polling_duration_sum{}) by ($cpu_group_by)", - "interval": "", - "legendFormat": "{{task_name}}", - "range": true, - "refId": "A" - } - ], - "title": "Total CPU burn", - "type": "timeseries" - }, - { - "datasource": { - "type": "prometheus", - "uid": "$data_source" - }, - "description": "", - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 30, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "insertNulls": false, - "lineInterpolation": "linear", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "log": 10, - "type": "log" - }, - "showPoints": "never", - "spanNulls": false, - "stacking": { - "group": "A", - "mode": "none" - }, - "thresholdsStyle": { - "mode": "area" - } - }, - "links": [], - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "dark-red", - "value": 6000 - } - ] - }, - "unit": "ms" - }, - "overrides": [] - }, - "gridPos": { - "h": 12, - "w": 12, - "x": 0, - "y": 40 - }, - "id": 95, - "interval": "1s", - "options": { - "legend": { - "calcs": [], - "displayMode": "list", - "placement": "bottom", - "showLegend": true, - "sortBy": "Last", - "sortDesc": true - }, - "tooltip": { - "mode": "multi", - "sort": "desc" - } - }, - "pluginVersion": "10.0.2", - "targets": [ - { - "datasource": { - "uid": "$data_source" - }, - "editorMode": "code", - "expr": "subsystem_benchmark_block_time", - "interval": "", - "legendFormat": "Instant block time", - "range": true, - "refId": "A" - } - ], - "title": "All candidates in block recovery time", - "type": "timeseries" - }, - { - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "description": "", - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 100, - "gradientMode": "hue", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "insertNulls": false, - "lineInterpolation": "linear", - "lineWidth": 1, - "pointSize": 2, - "scaleDistribution": { - "log": 2, - "type": "log" - }, - "showPoints": "auto", - "spanNulls": false, - "stacking": { - "group": "A", - "mode": "normal" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - }, - "unit": "binBps" - }, - "overrides": [] - }, - "gridPos": { - "h": 12, - "w": 12, - "x": 12, - "y": 40 - }, - "id": 89, - "interval": "1s", - "options": { - "legend": { - "calcs": [], - "displayMode": "list", - "placement": "bottom", - "showLegend": true - }, - "tooltip": { - "mode": "multi", - "sort": "none" - } - }, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "editorMode": "code", - "expr": "sum(rate(subsystem_benchmark_network_peer_total_bytes_received{}[5s]))", - "instant": false, - "legendFormat": "Received", - "range": true, - "refId": "A" - }, - { - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "editorMode": "code", - "expr": "sum(rate(subsystem_benchmark_network_peer_total_bytes_sent{}[5s]))", - "hide": false, - "instant": false, - "legendFormat": "Sent", - "range": true, - "refId": "B" - } - ], - "title": "Emulated network throughput ", - "type": "timeseries" - }, - { - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "description": "", - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 0, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "insertNulls": false, - "lineInterpolation": "linear", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "log": 2, - "type": "log" - }, - "showPoints": "auto", - "spanNulls": false, - "stacking": { - "group": "A", - "mode": "none" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - }, - "unit": "bytes" - }, - "overrides": [] - }, - "gridPos": { - "h": 15, - "w": 12, - "x": 0, - "y": 52 - }, - "id": 88, - "interval": "1s", - "options": { - "legend": { - "calcs": [], - "displayMode": "list", - "placement": "bottom", - "showLegend": true - }, - "tooltip": { - "mode": "single", - "sort": "none" - } - }, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "editorMode": "code", - "expr": "rate(subsystem_benchmark_network_peer_total_bytes_received{}[10s])", - "instant": false, - "legendFormat": "Received by {{peer}}", - "range": true, - "refId": "A" - }, - { - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "editorMode": "code", - "expr": "rate(subsystem_benchmark_network_peer_total_bytes_sent{}[10s])", - "hide": false, - "instant": false, - "legendFormat": "Sent by {{peer}}", - "range": true, - "refId": "B" - } - ], - "title": "Emulated peer throughput", - "type": "timeseries" - }, - { - "cards": {}, - "color": { - "cardColor": "#b4ff00", - "colorScale": "sqrt", - "colorScheme": "interpolateInferno", - "exponent": 0.5, - "mode": "spectrum" - }, - "dataFormat": "tsbuckets", - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "description": "", - "fieldConfig": { - "defaults": { - "custom": { - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "scaleDistribution": { - "type": "linear" - } - } - }, - "overrides": [] - }, - "gridPos": { - "h": 15, - "w": 12, - "x": 12, - "y": 52 - }, - "heatmap": {}, - "hideZeroBuckets": true, - "highlightCards": true, - "id": 92, - "interval": "1s", - "legend": { - "show": true - }, - "maxDataPoints": 1340, - "options": { - "calculate": false, - "calculation": {}, - "cellGap": 2, - "cellValues": { - "decimals": 0 - }, - "color": { - "exponent": 0.5, - "fill": "#b4ff00", - "mode": "scheme", - "reverse": false, - "scale": "exponential", - "scheme": "Inferno", - "steps": 128 - }, - "exemplars": { - "color": "rgba(255,0,255,0.7)" - }, - "filterValues": { - "le": 1e-9 - }, - "legend": { - "show": true - }, - "rowsFrame": { - "layout": "auto" - }, - "showValue": "never", - "tooltip": { - "show": true, - "yHistogram": true - }, - "yAxis": { - "axisPlacement": "left", - "decimals": 0, - "reverse": false, - "unit": "bytes" - } - }, - "pluginVersion": "10.1.1", - "reverseYBuckets": false, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "editorMode": "code", - "exemplar": false, - "expr": "sum(increase(subsystem_benchmark_pov_size_bucket{}[$__rate_interval])) by (le)", - "format": "heatmap", - "hide": false, - "instant": false, - "interval": "", - "legendFormat": "{{le}}", - "queryType": "randomWalk", - "refId": "B" - } - ], - "title": "Recovered PoV sizes", - "tooltip": { - "show": true, - "showHistogram": true - }, - "tooltipDecimals": 0, - "transformations": [], - "type": "heatmap", - "xAxis": { - "show": true - }, - "yAxis": { - "decimals": 0, - "format": "s", - "logBase": 1, - "show": true - }, - "yBucketBound": "auto" - }, - { - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "description": "Number of erasure-encoded chunks of data belonging to candidate blocks. ", - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic", - "seriesBy": "max" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 10, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "insertNulls": false, - "lineInterpolation": "smooth", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "type": "linear" - }, - "showPoints": "never", - "spanNulls": true, - "stacking": { - "group": "A", - "mode": "none" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - }, - "unit": "chunks/s" - }, - "overrides": [] - }, - "gridPos": { - "h": 10, - "w": 12, - "x": 0, - "y": 67 - }, - "id": 43, - "interval": "1s", - "maxDataPoints": 1340, - "options": { - "legend": { - "calcs": [], - "displayMode": "list", - "placement": "bottom", - "showLegend": true - }, - "tooltip": { - "mode": "multi", - "sort": "none" - } - }, - "pluginVersion": "8.2.2", - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "editorMode": "code", - "exemplar": true, - "expr": "sum(rate(polkadot_parachain_availability_recovery_chunk_requests_issued{}[10s]))", - "format": "time_series", - "hide": false, - "instant": false, - "interval": "", - "legendFormat": "Chunks requested", - "queryType": "randomWalk", - "refId": "B" - } - ], - "title": "Availability", - "transformations": [], - "type": "timeseries" - }, - { - "collapsed": false, - "datasource": { - "type": "datasource", - "uid": "grafana" - }, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 77 - }, - "id": 35, - "panels": [], - "targets": [ - { - "datasource": { - "type": "datasource", - "uid": "grafana" - }, - "refId": "A" - } - ], - "title": "Availability subystem metrics", - "type": "row" - }, - { - "cards": {}, - "color": { - "cardColor": "#b4ff00", - "colorScale": "sqrt", - "colorScheme": "interpolateInferno", - "exponent": 0.5, - "mode": "spectrum" - }, - "dataFormat": "tsbuckets", - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "description": "", - "fieldConfig": { - "defaults": { - "custom": { - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "scaleDistribution": { - "type": "linear" - } - } - }, - "overrides": [] - }, - "gridPos": { - "h": 10, - "w": 12, - "x": 0, - "y": 78 - }, - "heatmap": {}, - "hideZeroBuckets": true, - "highlightCards": true, - "id": 68, - "interval": "1s", - "legend": { - "show": true - }, - "maxDataPoints": 1340, - "options": { - "calculate": false, - "calculation": {}, - "cellGap": 2, - "cellValues": { - "decimals": 0 - }, - "color": { - "exponent": 0.5, - "fill": "#b4ff00", - "mode": "scheme", - "reverse": false, - "scale": "exponential", - "scheme": "Inferno", - "steps": 128 - }, - "exemplars": { - "color": "rgba(255,0,255,0.7)" - }, - "filterValues": { - "le": 1e-9 - }, - "legend": { - "show": true - }, - "rowsFrame": { - "layout": "auto" - }, - "showValue": "never", - "tooltip": { - "show": true, - "yHistogram": true - }, - "yAxis": { - "axisPlacement": "left", - "decimals": 0, - "reverse": false, - "unit": "s" - } - }, - "pluginVersion": "10.1.1", - "reverseYBuckets": false, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "editorMode": "code", - "exemplar": false, - "expr": "sum(increase(polkadot_parachain_availability_recovery_time_total_bucket{}[$__rate_interval])) by (le)", - "format": "heatmap", - "hide": false, - "instant": false, - "interval": "", - "legendFormat": "{{le}}", - "queryType": "randomWalk", - "refId": "B" - } - ], - "title": "Time to recover a PoV", - "tooltip": { - "show": true, - "showHistogram": true - }, - "tooltipDecimals": 0, - "transformations": [], - "type": "heatmap", - "xAxis": { - "show": true - }, - "yAxis": { - "decimals": 0, - "format": "s", - "logBase": 1, - "show": true - }, - "yBucketBound": "auto" - }, - { - "cards": {}, - "color": { - "cardColor": "#b4ff00", - "colorScale": "sqrt", - "colorScheme": "interpolateInferno", - "exponent": 0.5, - "mode": "spectrum" - }, - "dataFormat": "tsbuckets", - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "description": "", - "fieldConfig": { - "defaults": { - "custom": { - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "scaleDistribution": { - "type": "linear" - } - } - }, - "overrides": [] - }, - "gridPos": { - "h": 10, - "w": 12, - "x": 12, - "y": 78 - }, - "heatmap": {}, - "hideZeroBuckets": true, - "highlightCards": true, - "id": 67, - "interval": "1s", - "legend": { - "show": true - }, - "maxDataPoints": 1340, - "options": { - "calculate": false, - "calculation": {}, - "cellGap": 2, - "cellValues": { - "decimals": 0 - }, - "color": { - "exponent": 0.5, - "fill": "#b4ff00", - "mode": "scheme", - "reverse": false, - "scale": "exponential", - "scheme": "Inferno", - "steps": 128 - }, - "exemplars": { - "color": "rgba(255,0,255,0.7)" - }, - "filterValues": { - "le": 1e-9 - }, - "legend": { - "show": true - }, - "rowsFrame": { - "layout": "auto" - }, - "showValue": "never", - "tooltip": { - "show": true, - "yHistogram": true - }, - "yAxis": { - "axisPlacement": "left", - "decimals": 0, - "reverse": false, - "unit": "s" - } - }, - "pluginVersion": "10.1.1", - "reverseYBuckets": false, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "editorMode": "code", - "exemplar": false, - "expr": "sum(increase(polkadot_parachain_availability_recovery_time_chunk_request_bucket{}[$__rate_interval])) by (le)", - "format": "heatmap", - "instant": false, - "interval": "", - "legendFormat": "{{le}}", - "queryType": "randomWalk", - "refId": "A" - } - ], - "title": "Chunk request duration", - "tooltip": { - "show": true, - "showHistogram": true - }, - "tooltipDecimals": 0, - "transformations": [], - "type": "heatmap", - "xAxis": { - "show": true - }, - "yAxis": { - "decimals": 0, - "format": "bitfields", - "logBase": 1, - "show": true - }, - "yBucketBound": "auto" - }, - { - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "description": "", - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic", - "seriesBy": "max" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 10, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "insertNulls": false, - "lineInterpolation": "smooth", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "type": "linear" - }, - "showPoints": "never", - "spanNulls": true, - "stacking": { - "group": "A", - "mode": "none" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - }, - "unit": "Bps" - }, - "overrides": [] - }, - "gridPos": { - "h": 10, - "w": 12, - "x": 0, - "y": 88 - }, - "id": 85, - "interval": "1s", - "maxDataPoints": 1340, - "options": { - "legend": { - "calcs": [], - "displayMode": "list", - "placement": "bottom", - "showLegend": true - }, - "tooltip": { - "mode": "multi", - "sort": "none" - } - }, - "pluginVersion": "8.2.2", - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "editorMode": "code", - "exemplar": true, - "expr": "rate(polkadot_parachain_availability_recovery_bytes_total{}[30s])", - "format": "time_series", - "hide": false, - "instant": false, - "interval": "", - "legendFormat": "Bytes recovered", - "queryType": "randomWalk", - "refId": "B" - } - ], - "title": "Recovery throughtput", - "transformations": [], - "type": "timeseries" - }, - { - "cards": {}, - "color": { - "cardColor": "#b4ff00", - "colorScale": "sqrt", - "colorScheme": "interpolateInferno", - "exponent": 0.5, - "mode": "spectrum" - }, - "dataFormat": "tsbuckets", - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "description": "", - "fieldConfig": { - "defaults": { - "custom": { - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "scaleDistribution": { - "type": "linear" - } - } - }, - "overrides": [] - }, - "gridPos": { - "h": 10, - "w": 12, - "x": 12, - "y": 88 - }, - "heatmap": {}, - "hideZeroBuckets": true, - "highlightCards": true, - "id": 84, - "interval": "1s", - "legend": { - "show": true - }, - "maxDataPoints": 1340, - "options": { - "calculate": false, - "calculation": {}, - "cellGap": 2, - "cellValues": { - "decimals": 0 - }, - "color": { - "exponent": 0.5, - "fill": "#b4ff00", - "mode": "scheme", - "reverse": false, - "scale": "exponential", - "scheme": "Inferno", - "steps": 128 - }, - "exemplars": { - "color": "rgba(255,0,255,0.7)" - }, - "filterValues": { - "le": 1e-9 - }, - "legend": { - "show": true - }, - "rowsFrame": { - "layout": "auto" - }, - "showValue": "never", - "tooltip": { - "show": true, - "yHistogram": true - }, - "yAxis": { - "axisPlacement": "left", - "decimals": 0, - "reverse": false, - "unit": "s" - } - }, - "pluginVersion": "10.1.1", - "reverseYBuckets": false, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "editorMode": "code", - "exemplar": false, - "expr": "sum(increase(polkadot_parachain_availability_reencode_chunks_bucket{}[$__rate_interval])) by (le)", - "format": "heatmap", - "hide": false, - "instant": false, - "interval": "", - "legendFormat": "{{le}}", - "queryType": "randomWalk", - "refId": "B" - } - ], - "title": "Re-encoding chunks timing", - "tooltip": { - "show": true, - "showHistogram": true - }, - "tooltipDecimals": 0, - "transformations": [], - "type": "heatmap", - "xAxis": { - "show": true - }, - "yAxis": { - "decimals": 0, - "format": "s", - "logBase": 1, - "show": true - }, - "yBucketBound": "auto" - }, - { - "cards": {}, - "color": { - "cardColor": "#b4ff00", - "colorScale": "sqrt", - "colorScheme": "interpolateInferno", - "exponent": 0.5, - "mode": "spectrum" - }, - "dataFormat": "tsbuckets", - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "description": "", - "fieldConfig": { - "defaults": { - "custom": { - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "scaleDistribution": { - "type": "linear" - } - } - }, - "overrides": [] - }, - "gridPos": { - "h": 10, - "w": 12, - "x": 0, - "y": 98 - }, - "heatmap": {}, - "hideZeroBuckets": true, - "highlightCards": true, - "id": 83, - "interval": "1s", - "legend": { - "show": true - }, - "maxDataPoints": 1340, - "options": { - "calculate": false, - "calculation": {}, - "cellGap": 2, - "cellValues": { - "decimals": 0 - }, - "color": { - "exponent": 0.5, - "fill": "#b4ff00", - "mode": "scheme", - "reverse": false, - "scale": "exponential", - "scheme": "Inferno", - "steps": 128 - }, - "exemplars": { - "color": "rgba(255,0,255,0.7)" - }, - "filterValues": { - "le": 1e-9 - }, - "legend": { - "show": true - }, - "rowsFrame": { - "layout": "auto" - }, - "showValue": "never", - "tooltip": { - "show": true, - "yHistogram": true - }, - "yAxis": { - "axisPlacement": "left", - "decimals": 0, - "reverse": false, - "unit": "s" - } - }, - "pluginVersion": "10.1.1", - "reverseYBuckets": false, - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "editorMode": "code", - "exemplar": false, - "expr": "sum(increase(polkadot_parachain_availability_recovery_time_erasure_recovery_bucket{}[$__rate_interval])) by (le)", - "format": "heatmap", - "hide": false, - "instant": false, - "interval": "", - "legendFormat": "{{le}}", - "queryType": "randomWalk", - "refId": "B" - } - ], - "title": "Erasure recovery (no I/O)", - "tooltip": { - "show": true, - "showHistogram": true - }, - "tooltipDecimals": 0, - "transformations": [], - "type": "heatmap", - "xAxis": { - "show": true - }, - "yAxis": { - "decimals": 0, - "format": "s", - "logBase": 1, - "show": true - }, - "yBucketBound": "auto" - }, - { - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "description": "Number of erasure-encoded chunks of data belonging to candidate blocks. ", - "fieldConfig": { - "defaults": { - "color": { - "mode": "palette-classic", - "seriesBy": "max" - }, - "custom": { - "axisCenteredZero": false, - "axisColorMode": "text", - "axisLabel": "", - "axisPlacement": "auto", - "barAlignment": 0, - "drawStyle": "line", - "fillOpacity": 10, - "gradientMode": "none", - "hideFrom": { - "legend": false, - "tooltip": false, - "viz": false - }, - "insertNulls": false, - "lineInterpolation": "stepAfter", - "lineWidth": 1, - "pointSize": 5, - "scaleDistribution": { - "type": "linear" - }, - "showPoints": "never", - "spanNulls": true, - "stacking": { - "group": "A", - "mode": "none" - }, - "thresholdsStyle": { - "mode": "off" - } - }, - "mappings": [], - "thresholds": { - "mode": "absolute", - "steps": [ - { - "color": "green", - "value": null - }, - { - "color": "red", - "value": 80 - } - ] - }, - "unit": "cps" - }, - "overrides": [] - }, - "gridPos": { - "h": 10, - "w": 12, - "x": 0, - "y": 108 - }, - "id": 86, - "interval": "1s", - "maxDataPoints": 1340, - "options": { - "legend": { - "calcs": [], - "displayMode": "list", - "placement": "bottom", - "showLegend": true - }, - "tooltip": { - "mode": "multi", - "sort": "none" - } - }, - "pluginVersion": "8.2.2", - "targets": [ - { - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "editorMode": "code", - "exemplar": true, - "expr": "sum(rate(polkadot_parachain_availability_recovery_recoveries_finished{}[1s]))", - "format": "time_series", - "hide": false, - "instant": false, - "interval": "", - "legendFormat": "Finished", - "queryType": "randomWalk", - "refId": "B" - }, - { - "datasource": { - "type": "prometheus", - "uid": "${data_source}" - }, - "editorMode": "code", - "exemplar": true, - "expr": "sum(rate(polkadot_parachain_availability_recovery_recovieries_started{}[1s]))", - "format": "time_series", - "hide": false, - "instant": false, - "interval": "", - "legendFormat": "Started", - "queryType": "randomWalk", - "refId": "A" - } - ], - "title": "Recoveries", - "transformations": [], - "type": "timeseries" - }, - { - "collapsed": false, - "datasource": { - "type": "datasource", - "uid": "grafana" - }, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 118 - }, - "id": 2, - "panels": [], - "targets": [ - { - "datasource": { - "type": "datasource", - "uid": "grafana" - }, - "refId": "A" - } - ], - "title": "Approval voting", - "type": "row" - } - ], - "refresh": false, - "schemaVersion": 38, - "style": "dark", - "tags": [ - "subsystem", - "benchmark" - ], - "templating": { - "list": [ - { - "current": { - "selected": false, - "text": "Prometheus", - "value": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "hide": 0, - "includeAll": false, - "label": "Source of data", - "multi": false, - "name": "data_source", - "options": [], - "query": "prometheus", - "queryValue": "", - "refresh": 1, - "regex": "", - "skipUrlSync": false, - "type": "datasource" - }, - { - "current": { - "selected": true, - "text": "task_name", - "value": "task_name" - }, - "description": "Sum CPU usage by task name or task group.", - "hide": 0, - "includeAll": false, - "label": "Group CPU usage", - "multi": false, - "name": "cpu_group_by", - "options": [ - { - "selected": true, - "text": "task_name", - "value": "task_name" - }, - { - "selected": false, - "text": "task_group", - "value": "task_group" - } - ], - "query": "task_name, task_group", - "queryValue": "", - "skipUrlSync": false, - "type": "custom" - } - ] - }, - "time": { - "from": "2023-11-28T13:05:32.794Z", - "to": "2023-11-28T13:06:56.173Z" - }, - "timepicker": { - "refresh_intervals": [ - "5s", - "10s" - ] - }, - "timezone": "utc", - "title": "Data Availability Read", - "uid": "asdadasd1", - "version": 58, - "weekStart": "" -} \ No newline at end of file diff --git a/polkadot/node/subsystem-bench/grafana/task-cpu-usage.json b/polkadot/node/subsystem-bench/grafana/task-cpu-usage.json deleted file mode 100644 index 90763444abf..00000000000 --- a/polkadot/node/subsystem-bench/grafana/task-cpu-usage.json +++ /dev/null @@ -1,755 +0,0 @@ -{ - "annotations": { - "list": [ - { - "$$hashKey": "object:326", - "builtIn": 1, - "datasource": { - "type": "datasource", - "uid": "grafana" - }, - "enable": true, - "hide": true, - "iconColor": "rgba(0, 211, 255, 1)", - "limit": 100, - "name": "Annotations & Alerts", - "showIn": 0, - "target": { - "limit": 100, - "matchAny": false, - "tags": [], - "type": "dashboard" - }, - "type": "dashboard" - }, - { - "$$hashKey": "object:327", - "datasource": { - "uid": "$data_source" - }, - "enable": true, - "expr": "increase(${metric_namespace}_tasks_ended_total{reason=\"panic\", node=~\"${nodename}\"}[10m])", - "hide": true, - "iconColor": "rgba(255, 96, 96, 1)", - "limit": 100, - "name": "Task panics", - "rawQuery": "SELECT\n extract(epoch from time_column) AS time,\n text_column as text,\n tags_column as tags\nFROM\n metric_table\nWHERE\n $__timeFilter(time_column)\n", - "showIn": 0, - "step": "10m", - "tags": [], - "textFormat": "{{node}} - {{task_name}}", - "titleFormat": "Panic!", - "type": "tags" - }, - { - "$$hashKey": "object:621", - "datasource": { - "uid": "$data_source" - }, - "enable": true, - "expr": "changes(${metric_namespace}_process_start_time_seconds{node=~\"${nodename}\"}[10m])", - "hide": false, - "iconColor": "#8AB8FF", - "name": "Node reboots", - "showIn": 0, - "step": "10m", - "textFormat": "{{node}}", - "titleFormat": "Reboots" - } - ] - }, - "editable": true, - "fiscalYearStartMonth": 0, - "graphTooltip": 0, - "id": 1, - "links": [], - "liveNow": false, - "panels": [ - { - "collapsed": false, - "datasource": { - "type": "datasource", - "uid": "grafana" - }, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 0 - }, - "id": 29, - "panels": [], - "targets": [ - { - "datasource": { - "type": "datasource", - "uid": "grafana" - }, - "refId": "A" - } - ], - "title": "Tasks", - "type": "row" - }, - { - "aliasColors": {}, - "bars": false, - "dashLength": 10, - "dashes": false, - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "fieldConfig": { - "defaults": { - "links": [] - }, - "overrides": [] - }, - "fill": 3, - "fillGradient": 0, - "gridPos": { - "h": 9, - "w": 24, - "x": 0, - "y": 1 - }, - "hiddenSeries": false, - "id": 11, - "interval": "1s", - "legend": { - "alignAsTable": true, - "avg": true, - "current": false, - "hideEmpty": false, - "hideZero": false, - "max": false, - "min": false, - "rightSide": true, - "show": true, - "sort": "avg", - "sortDesc": true, - "total": false, - "values": true - }, - "lines": true, - "linewidth": 1, - "nullPointMode": "null", - "options": { - "alertThreshold": true - }, - "percentage": false, - "pluginVersion": "10.1.1", - "pointradius": 2, - "points": false, - "renderer": "flot", - "repeat": "nodename", - "seriesOverrides": [], - "spaceLength": 10, - "stack": true, - "steppedLine": false, - "targets": [ - { - "datasource": { - "uid": "$data_source" - }, - "editorMode": "code", - "expr": "sum(rate(substrate_tasks_polling_duration_sum{}[$__rate_interval])) by (task_name)", - "interval": "", - "legendFormat": "{{task_name}}", - "range": true, - "refId": "A" - } - ], - "thresholds": [], - "timeRegions": [], - "title": "CPU time spent on each task", - "tooltip": { - "shared": true, - "sort": 2, - "value_type": "individual" - }, - "type": "graph", - "xaxis": { - "mode": "time", - "show": true, - "values": [] - }, - "yaxes": [ - { - "$$hashKey": "object:2721", - "format": "percentunit", - "logBase": 1, - "show": true - }, - { - "$$hashKey": "object:2722", - "format": "short", - "logBase": 1, - "show": false - } - ], - "yaxis": { - "align": false - } - }, - { - "aliasColors": {}, - "bars": false, - "dashLength": 10, - "dashes": false, - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "fieldConfig": { - "defaults": { - "links": [] - }, - "overrides": [] - }, - "fill": 3, - "fillGradient": 0, - "gridPos": { - "h": 6, - "w": 24, - "x": 0, - "y": 10 - }, - "hiddenSeries": false, - "id": 30, - "interval": "1s", - "legend": { - "alignAsTable": true, - "avg": true, - "current": false, - "hideEmpty": false, - "hideZero": false, - "max": false, - "min": false, - "rightSide": true, - "show": true, - "total": false, - "values": true - }, - "lines": true, - "linewidth": 1, - "nullPointMode": "connected", - "options": { - "alertThreshold": true - }, - "percentage": false, - "pluginVersion": "10.1.1", - "pointradius": 2, - "points": false, - "renderer": "flot", - "repeat": "nodename", - "seriesOverrides": [], - "spaceLength": 10, - "stack": true, - "steppedLine": false, - "targets": [ - { - "datasource": { - "uid": "$data_source" - }, - "editorMode": "code", - "expr": "rate(substrate_tasks_polling_duration_count{}[$__rate_interval])", - "interval": "", - "legendFormat": "{{task_name}}", - "range": true, - "refId": "A" - } - ], - "thresholds": [], - "timeRegions": [], - "title": "Task polling rate per second", - "tooltip": { - "shared": true, - "sort": 2, - "value_type": "individual" - }, - "type": "graph", - "xaxis": { - "mode": "time", - "show": true, - "values": [] - }, - "yaxes": [ - { - "$$hashKey": "object:2571", - "format": "cps", - "logBase": 1, - "show": true - }, - { - "$$hashKey": "object:2572", - "format": "short", - "logBase": 1, - "show": false - } - ], - "yaxis": { - "align": false - } - }, - { - "aliasColors": {}, - "bars": false, - "dashLength": 10, - "dashes": false, - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "fieldConfig": { - "defaults": { - "links": [] - }, - "overrides": [] - }, - "fill": 0, - "fillGradient": 0, - "gridPos": { - "h": 6, - "w": 24, - "x": 0, - "y": 16 - }, - "hiddenSeries": false, - "id": 43, - "interval": "1s", - "legend": { - "alignAsTable": true, - "avg": true, - "current": false, - "hideEmpty": true, - "hideZero": false, - "max": true, - "min": true, - "rightSide": true, - "show": true, - "total": true, - "values": true - }, - "lines": true, - "linewidth": 1, - "nullPointMode": "connected", - "options": { - "alertThreshold": true - }, - "percentage": false, - "pluginVersion": "10.1.1", - "pointradius": 2, - "points": false, - "renderer": "flot", - "repeat": "nodename", - "seriesOverrides": [], - "spaceLength": 10, - "stack": false, - "steppedLine": false, - "targets": [ - { - "datasource": { - "uid": "$data_source" - }, - "editorMode": "code", - "expr": "increase(substrate_tasks_polling_duration_sum{}[$__rate_interval]) / increase(substrate_tasks_polling_duration_count{}[$__rate_interval])", - "interval": "", - "legendFormat": "{{task_name}}", - "range": true, - "refId": "A" - } - ], - "thresholds": [], - "timeRegions": [], - "title": "Average time it takes to call Future::poll()", - "tooltip": { - "shared": true, - "sort": 2, - "value_type": "individual" - }, - "type": "graph", - "xaxis": { - "mode": "time", - "show": true, - "values": [] - }, - "yaxes": [ - { - "$$hashKey": "object:2571", - "format": "s", - "logBase": 1, - "min": "0", - "show": true - }, - { - "$$hashKey": "object:2572", - "format": "short", - "logBase": 1, - "show": false - } - ], - "yaxis": { - "align": false - } - }, - { - "aliasColors": {}, - "bars": true, - "dashLength": 10, - "dashes": false, - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "fieldConfig": { - "defaults": { - "links": [] - }, - "overrides": [] - }, - "fill": 0, - "fillGradient": 0, - "gridPos": { - "h": 6, - "w": 24, - "x": 0, - "y": 22 - }, - "hiddenSeries": false, - "id": 15, - "interval": "1s", - "legend": { - "alignAsTable": true, - "avg": false, - "current": false, - "max": false, - "min": false, - "rightSide": true, - "show": true, - "total": true, - "values": true - }, - "lines": false, - "linewidth": 1, - "nullPointMode": "null as zero", - "options": { - "alertThreshold": true - }, - "percentage": false, - "pluginVersion": "10.1.1", - "pointradius": 2, - "points": false, - "renderer": "flot", - "repeat": "nodename", - "seriesOverrides": [], - "spaceLength": 10, - "stack": true, - "steppedLine": true, - "targets": [ - { - "datasource": { - "uid": "$data_source" - }, - "editorMode": "code", - "expr": "increase(substrate_tasks_spawned_total{}[$__rate_interval])", - "interval": "", - "intervalFactor": 1, - "legendFormat": "{{task_name}}", - "range": true, - "refId": "A" - } - ], - "thresholds": [], - "timeRegions": [], - "title": "Number of tasks started", - "tooltip": { - "shared": true, - "sort": 2, - "value_type": "individual" - }, - "type": "graph", - "xaxis": { - "mode": "time", - "show": true, - "values": [] - }, - "yaxes": [ - { - "$$hashKey": "object:771", - "format": "short", - "logBase": 10, - "min": "0", - "show": true - }, - { - "$$hashKey": "object:772", - "format": "short", - "logBase": 1, - "show": true - } - ], - "yaxis": { - "align": false - } - }, - { - "aliasColors": {}, - "bars": false, - "dashLength": 10, - "dashes": false, - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "fieldConfig": { - "defaults": { - "links": [] - }, - "overrides": [] - }, - "fill": 0, - "fillGradient": 0, - "gridPos": { - "h": 6, - "w": 24, - "x": 0, - "y": 28 - }, - "hiddenSeries": false, - "id": 2, - "interval": "1s", - "legend": { - "alignAsTable": true, - "avg": false, - "current": true, - "max": true, - "min": true, - "rightSide": true, - "show": true, - "total": false, - "values": true - }, - "lines": true, - "linewidth": 1, - "nullPointMode": "connected", - "options": { - "alertThreshold": true - }, - "percentage": false, - "pluginVersion": "10.1.1", - "pointradius": 2, - "points": false, - "renderer": "flot", - "repeat": "nodename", - "seriesOverrides": [], - "spaceLength": 10, - "stack": false, - "steppedLine": false, - "targets": [ - { - "datasource": { - "uid": "$data_source" - }, - "editorMode": "code", - "expr": "substrate_tasks_spawned_total{} - sum(substrate_tasks_ended_total{}) without(reason)\n\n# Fallback if tasks_ended_total is null for that task\nor on(task_name) substrate_tasks_spawned_total{}", - "interval": "", - "legendFormat": "{{task_name}}", - "range": true, - "refId": "A" - } - ], - "thresholds": [], - "timeRegions": [], - "title": "Number of tasks running", - "tooltip": { - "shared": true, - "sort": 2, - "value_type": "individual" - }, - "type": "graph", - "xaxis": { - "mode": "time", - "show": true, - "values": [] - }, - "yaxes": [ - { - "$$hashKey": "object:919", - "format": "short", - "logBase": 1, - "min": "0", - "show": true - }, - { - "$$hashKey": "object:920", - "format": "short", - "logBase": 1, - "show": true - } - ], - "yaxis": { - "align": false - } - }, - { - "aliasColors": {}, - "bars": false, - "dashLength": 10, - "dashes": false, - "datasource": { - "type": "prometheus", - "uid": "e56e7dd2-a992-4eec-aa96-e47b21c9020b" - }, - "fieldConfig": { - "defaults": { - "links": [] - }, - "overrides": [] - }, - "fill": 0, - "fillGradient": 0, - "gridPos": { - "h": 6, - "w": 24, - "x": 0, - "y": 34 - }, - "hiddenSeries": false, - "id": 7, - "interval": "1s", - "legend": { - "alignAsTable": true, - "avg": true, - "current": false, - "hideEmpty": true, - "hideZero": true, - "max": false, - "min": false, - "rightSide": true, - "show": true, - "total": false, - "values": true - }, - "lines": true, - "linewidth": 1, - "nullPointMode": "null as zero", - "options": { - "alertThreshold": true - }, - "percentage": false, - "pluginVersion": "10.1.1", - "pointradius": 2, - "points": false, - "renderer": "flot", - "repeat": "nodename", - "seriesOverrides": [], - "spaceLength": 10, - "stack": true, - "steppedLine": true, - "targets": [ - { - "datasource": { - "uid": "$data_source" - }, - "editorMode": "code", - "expr": "irate(substrate_tasks_polling_duration_bucket{le=\"+Inf\"}[$__rate_interval])\n - ignoring(le)\n irate(substrate_tasks_polling_duration_bucket{le=\"1.024\"}[$__rate_interval]) > 0", - "interval": "", - "legendFormat": "{{task_name}}", - "range": true, - "refId": "A" - } - ], - "thresholds": [], - "timeRegions": [], - "title": "Number of calls to `Future::poll` that took more than one second", - "tooltip": { - "shared": true, - "sort": 2, - "value_type": "cumulative" - }, - "type": "graph", - "xaxis": { - "mode": "time", - "show": true, - "values": [] - }, - "yaxes": [ - { - "$$hashKey": "object:3040", - "format": "cps", - "label": "Calls to `Future::poll`/second", - "logBase": 1, - "min": "0", - "show": true - }, - { - "$$hashKey": "object:3041", - "format": "short", - "logBase": 1, - "show": false - } - ], - "yaxis": { - "align": false - } - }, - { - "collapsed": false, - "datasource": { - "type": "datasource", - "uid": "grafana" - }, - "gridPos": { - "h": 1, - "w": 24, - "x": 0, - "y": 40 - }, - "id": 27, - "panels": [], - "targets": [ - { - "datasource": { - "type": "datasource", - "uid": "grafana" - }, - "refId": "A" - } - ], - "title": "Unbounded Channels", - "type": "row" - } - ], - "refresh": "5s", - "schemaVersion": 38, - "style": "dark", - "tags": [], - "templating": { - "list": [] - }, - "time": { - "from": "now-15m", - "to": "now" - }, - "timepicker": { - "refresh_intervals": [ - "5s", - "10s", - "30s", - "1m", - "5m", - "15m", - "30m", - "1h", - "2h", - "1d" - ] - }, - "timezone": "utc", - "title": "Substrate Service Tasks with substrate prefix", - "uid": "S7sc-M_Gk", - "version": 17, - "weekStart": "" - } \ No newline at end of file diff --git a/polkadot/node/subsystem-bench/src/availability/cli.rs b/polkadot/node/subsystem-bench/src/availability/cli.rs deleted file mode 100644 index 65df8c1552a..00000000000 --- a/polkadot/node/subsystem-bench/src/availability/cli.rs +++ /dev/null @@ -1,37 +0,0 @@ -// 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 serde::{Deserialize, Serialize}; - -#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq)] -#[value(rename_all = "kebab-case")] -#[non_exhaustive] -pub enum NetworkEmulation { - Ideal, - Healthy, - Degraded, -} - -#[derive(Debug, Clone, Serialize, Deserialize, clap::Parser)] -#[clap(rename_all = "kebab-case")] -#[allow(missing_docs)] -pub struct DataAvailabilityReadOptions { - #[clap(short, long, default_value_t = false)] - /// Turbo boost AD Read by fetching the full availability datafrom backers first. Saves CPU as - /// we don't need to re-construct from chunks. Tipically this is only faster if nodes have - /// enough bandwidth. - pub fetch_from_backers: bool, -} diff --git a/polkadot/node/subsystem-bench/src/availability/mod.rs b/polkadot/node/subsystem-bench/src/availability/mod.rs deleted file mode 100644 index 7c81b931365..00000000000 --- a/polkadot/node/subsystem-bench/src/availability/mod.rs +++ /dev/null @@ -1,339 +0,0 @@ -// 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 itertools::Itertools; -use std::{collections::HashMap, iter::Cycle, ops::Sub, sync::Arc, time::Instant}; - -use crate::TestEnvironment; -use polkadot_node_subsystem::{Overseer, OverseerConnector, SpawnGlue}; -use polkadot_node_subsystem_test_helpers::derive_erasure_chunks_with_proofs_and_root; -use polkadot_overseer::Handle as OverseerHandle; -use sc_network::request_responses::ProtocolConfig; - -use colored::Colorize; - -use futures::{channel::oneshot, stream::FuturesUnordered, StreamExt}; -use polkadot_node_metrics::metrics::Metrics; - -use polkadot_availability_recovery::AvailabilityRecoverySubsystem; - -use crate::GENESIS_HASH; -use parity_scale_codec::Encode; -use polkadot_node_network_protocol::request_response::{IncomingRequest, ReqProtocolNames}; -use polkadot_node_primitives::{BlockData, PoV}; -use polkadot_node_subsystem::messages::{AllMessages, AvailabilityRecoveryMessage}; - -use crate::core::{ - environment::TestEnvironmentDependencies, - mock::{ - av_store, - network_bridge::{self, MockNetworkBridgeTx, NetworkAvailabilityState}, - runtime_api, MockAvailabilityStore, MockRuntimeApi, - }, -}; - -use super::core::{configuration::TestConfiguration, mock::dummy_builder, network::*}; - -const LOG_TARGET: &str = "subsystem-bench::availability"; - -use polkadot_node_primitives::{AvailableData, ErasureChunk}; - -use super::{cli::TestObjective, core::mock::AlwaysSupportsParachains}; -use polkadot_node_subsystem_test_helpers::mock::new_block_import_info; -use polkadot_primitives::{ - CandidateHash, CandidateReceipt, GroupIndex, Hash, HeadData, PersistedValidationData, -}; -use polkadot_primitives_test_helpers::{dummy_candidate_receipt, dummy_hash}; -use sc_service::SpawnTaskHandle; - -mod cli; -pub use cli::{DataAvailabilityReadOptions, NetworkEmulation}; - -fn build_overseer( - spawn_task_handle: SpawnTaskHandle, - runtime_api: MockRuntimeApi, - av_store: MockAvailabilityStore, - network_bridge: MockNetworkBridgeTx, - availability_recovery: AvailabilityRecoverySubsystem, -) -> (Overseer, AlwaysSupportsParachains>, OverseerHandle) { - let overseer_connector = OverseerConnector::with_event_capacity(64000); - let dummy = dummy_builder!(spawn_task_handle); - let builder = dummy - .replace_runtime_api(|_| runtime_api) - .replace_availability_store(|_| av_store) - .replace_network_bridge_tx(|_| network_bridge) - .replace_availability_recovery(|_| availability_recovery); - - let (overseer, raw_handle) = - builder.build_with_connector(overseer_connector).expect("Should not fail"); - - (overseer, OverseerHandle::new(raw_handle)) -} - -/// Takes a test configuration and uses it to creates the `TestEnvironment`. -pub fn prepare_test( - config: TestConfiguration, - state: &mut TestState, -) -> (TestEnvironment, ProtocolConfig) { - prepare_test_inner(config, state, TestEnvironmentDependencies::default()) -} - -fn prepare_test_inner( - config: TestConfiguration, - state: &mut TestState, - dependencies: TestEnvironmentDependencies, -) -> (TestEnvironment, ProtocolConfig) { - // Generate test authorities. - let test_authorities = config.generate_authorities(); - - let runtime_api = runtime_api::MockRuntimeApi::new(config.clone(), test_authorities.clone()); - - let av_store = - av_store::MockAvailabilityStore::new(state.chunks.clone(), state.candidate_hashes.clone()); - - let availability_state = NetworkAvailabilityState { - candidate_hashes: state.candidate_hashes.clone(), - available_data: state.available_data.clone(), - chunks: state.chunks.clone(), - }; - - let network = NetworkEmulator::new(&config, &dependencies, &test_authorities); - - let network_bridge_tx = network_bridge::MockNetworkBridgeTx::new( - config.clone(), - availability_state, - network.clone(), - ); - - let use_fast_path = match &state.config().objective { - TestObjective::DataAvailabilityRead(options) => options.fetch_from_backers, - _ => panic!("Unexpected objective"), - }; - - let (collation_req_receiver, req_cfg) = - IncomingRequest::get_config_receiver(&ReqProtocolNames::new(GENESIS_HASH, None)); - - let subsystem = if use_fast_path { - AvailabilityRecoverySubsystem::with_fast_path( - collation_req_receiver, - Metrics::try_register(&dependencies.registry).unwrap(), - ) - } else { - AvailabilityRecoverySubsystem::with_chunks_only( - collation_req_receiver, - Metrics::try_register(&dependencies.registry).unwrap(), - ) - }; - - let (overseer, overseer_handle) = build_overseer( - dependencies.task_manager.spawn_handle(), - runtime_api, - av_store, - network_bridge_tx, - subsystem, - ); - - (TestEnvironment::new(dependencies, config, network, overseer, overseer_handle), req_cfg) -} - -#[derive(Clone)] -pub struct TestState { - // Full test configuration - config: TestConfiguration, - // A cycle iterator on all PoV sizes used in the test. - pov_sizes: Cycle>, - // Generated candidate receipts to be used in the test - candidates: Cycle>, - // Map from pov size to candidate index - pov_size_to_candidate: HashMap, - // Map from generated candidate hashes to candidate index in `available_data` - // and `chunks`. - candidate_hashes: HashMap, - // Per candidate index receipts. - candidate_receipt_templates: Vec, - // Per candidate index `AvailableData` - available_data: Vec, - // Per candiadte index chunks - chunks: Vec>, -} - -impl TestState { - fn config(&self) -> &TestConfiguration { - &self.config - } - - pub fn next_candidate(&mut self) -> Option { - let candidate = self.candidates.next(); - let candidate_hash = candidate.as_ref().unwrap().hash(); - gum::trace!(target: LOG_TARGET, "Next candidate selected {:?}", candidate_hash); - candidate - } - - /// Generate candidates to be used in the test. - fn generate_candidates(&mut self) { - let count = self.config.n_cores * self.config.num_blocks; - gum::info!(target: LOG_TARGET,"{}", format!("Pre-generating {} candidates.", count).bright_blue()); - - // Generate all candidates - self.candidates = (0..count) - .map(|index| { - let pov_size = self.pov_sizes.next().expect("This is a cycle; qed"); - let candidate_index = *self - .pov_size_to_candidate - .get(&pov_size) - .expect("pov_size always exists; qed"); - let mut candidate_receipt = - self.candidate_receipt_templates[candidate_index].clone(); - - // Make it unique. - candidate_receipt.descriptor.relay_parent = Hash::from_low_u64_be(index as u64); - // Store the new candidate in the state - self.candidate_hashes.insert(candidate_receipt.hash(), candidate_index); - - gum::debug!(target: LOG_TARGET, candidate_hash = ?candidate_receipt.hash(), "new candidate"); - - candidate_receipt - }) - .collect::>() - .into_iter() - .cycle(); - } - - pub fn new(config: &TestConfiguration) -> Self { - let config = config.clone(); - - let mut chunks = Vec::new(); - let mut available_data = Vec::new(); - let mut candidate_receipt_templates = Vec::new(); - let mut pov_size_to_candidate = HashMap::new(); - - // we use it for all candidates. - let persisted_validation_data = PersistedValidationData { - parent_head: HeadData(vec![7, 8, 9]), - relay_parent_number: Default::default(), - max_pov_size: 1024, - relay_parent_storage_root: Default::default(), - }; - - // For each unique pov we create a candidate receipt. - for (index, pov_size) in config.pov_sizes().iter().cloned().unique().enumerate() { - gum::info!(target: LOG_TARGET, index, pov_size, "{}", "Generating template candidate".bright_blue()); - - let mut candidate_receipt = dummy_candidate_receipt(dummy_hash()); - let pov = PoV { block_data: BlockData(vec![index as u8; pov_size]) }; - - let new_available_data = AvailableData { - validation_data: persisted_validation_data.clone(), - pov: Arc::new(pov), - }; - - let (new_chunks, erasure_root) = derive_erasure_chunks_with_proofs_and_root( - config.n_validators, - &new_available_data, - |_, _| {}, - ); - - candidate_receipt.descriptor.erasure_root = erasure_root; - - chunks.push(new_chunks); - available_data.push(new_available_data); - pov_size_to_candidate.insert(pov_size, index); - candidate_receipt_templates.push(candidate_receipt); - } - - let pov_sizes = config.pov_sizes().to_owned(); - let pov_sizes = pov_sizes.into_iter().cycle(); - gum::info!(target: LOG_TARGET, "{}","Created test environment.".bright_blue()); - - let mut _self = Self { - config, - available_data, - candidate_receipt_templates, - chunks, - pov_size_to_candidate, - pov_sizes, - candidate_hashes: HashMap::new(), - candidates: Vec::new().into_iter().cycle(), - }; - - _self.generate_candidates(); - _self - } -} - -pub async fn benchmark_availability_read(env: &mut TestEnvironment, mut state: TestState) { - let config = env.config().clone(); - - env.import_block(new_block_import_info(Hash::repeat_byte(1), 1)).await; - - let start_marker = Instant::now(); - let mut batch = FuturesUnordered::new(); - let mut availability_bytes = 0u128; - - env.metrics().set_n_validators(config.n_validators); - env.metrics().set_n_cores(config.n_cores); - - for block_num in 0..env.config().num_blocks { - gum::info!(target: LOG_TARGET, "Current block {}/{}", block_num + 1, env.config().num_blocks); - env.metrics().set_current_block(block_num); - - let block_start_ts = Instant::now(); - for candidate_num in 0..config.n_cores as u64 { - let candidate = - state.next_candidate().expect("We always send up to n_cores*num_blocks; qed"); - let (tx, rx) = oneshot::channel(); - batch.push(rx); - - let message = AllMessages::AvailabilityRecovery( - AvailabilityRecoveryMessage::RecoverAvailableData( - candidate.clone(), - 1, - Some(GroupIndex( - candidate_num as u32 % (std::cmp::max(5, config.n_cores) / 5) as u32, - )), - tx, - ), - ); - env.send_message(message).await; - } - - gum::info!("{}", format!("{} recoveries pending", batch.len()).bright_black()); - while let Some(completed) = batch.next().await { - let available_data = completed.unwrap().unwrap(); - env.metrics().on_pov_size(available_data.encoded_size()); - availability_bytes += available_data.encoded_size() as u128; - } - - let block_time = Instant::now().sub(block_start_ts).as_millis() as u64; - env.metrics().set_block_time(block_time); - gum::info!("All work for block completed in {}", format!("{:?}ms", block_time).cyan()); - } - - let duration: u128 = start_marker.elapsed().as_millis(); - let availability_bytes = availability_bytes / 1024; - gum::info!("All blocks processed in {}", format!("{:?}ms", duration).cyan()); - gum::info!( - "Throughput: {}", - format!("{} KiB/block", availability_bytes / env.config().num_blocks as u128).bright_red() - ); - gum::info!( - "Block time: {}", - format!("{} ms", start_marker.elapsed().as_millis() / env.config().num_blocks as u128) - .red() - ); - - gum::info!("{}", &env); - env.stop().await; -} diff --git a/polkadot/node/subsystem-bench/src/cli.rs b/polkadot/node/subsystem-bench/src/cli.rs deleted file mode 100644 index 3352f33a350..00000000000 --- a/polkadot/node/subsystem-bench/src/cli.rs +++ /dev/null @@ -1,60 +0,0 @@ -// 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::availability::DataAvailabilityReadOptions; -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Serialize, Deserialize, clap::Parser)] -#[clap(rename_all = "kebab-case")] -#[allow(missing_docs)] -pub struct TestSequenceOptions { - #[clap(short, long, ignore_case = true)] - pub path: String, -} - -/// Define the supported benchmarks targets -#[derive(Debug, Clone, clap::Parser, Serialize, Deserialize)] -#[command(rename_all = "kebab-case")] -pub enum TestObjective { - /// Benchmark availability recovery strategies. - DataAvailabilityRead(DataAvailabilityReadOptions), - /// Run a test sequence specified in a file - TestSequence(TestSequenceOptions), -} - -#[derive(Debug, clap::Parser)] -#[clap(rename_all = "kebab-case")] -#[allow(missing_docs)] -pub struct StandardTestOptions { - #[clap(long, ignore_case = true, default_value_t = 100)] - /// Number of cores to fetch availability for. - pub n_cores: usize, - - #[clap(long, ignore_case = true, default_value_t = 500)] - /// Number of validators to fetch chunks from. - pub n_validators: usize, - - #[clap(long, ignore_case = true, default_value_t = 5120)] - /// The minimum pov size in KiB - pub min_pov_size: usize, - - #[clap(long, ignore_case = true, default_value_t = 5120)] - /// The maximum pov size bytes - pub max_pov_size: usize, - - #[clap(short, long, ignore_case = true, default_value_t = 1)] - /// The number of blocks the test is going to run. - pub num_blocks: usize, -} diff --git a/polkadot/node/subsystem-bench/src/core/configuration.rs b/polkadot/node/subsystem-bench/src/core/configuration.rs deleted file mode 100644 index 164addb5190..00000000000 --- a/polkadot/node/subsystem-bench/src/core/configuration.rs +++ /dev/null @@ -1,262 +0,0 @@ -// 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 . -// -//! Test configuration definition and helpers. -use super::*; -use keyring::Keyring; -use std::{path::Path, time::Duration}; - -pub use crate::cli::TestObjective; -use polkadot_primitives::{AuthorityDiscoveryId, ValidatorId}; -use rand::{distributions::Uniform, prelude::Distribution, thread_rng}; -use serde::{Deserialize, Serialize}; - -pub fn random_pov_size(min_pov_size: usize, max_pov_size: usize) -> usize { - random_uniform_sample(min_pov_size, max_pov_size) -} - -fn random_uniform_sample + From>(min_value: T, max_value: T) -> T { - Uniform::from(min_value.into()..=max_value.into()) - .sample(&mut thread_rng()) - .into() -} - -/// Peer response latency configuration. -#[derive(Clone, Debug, Default, Serialize, Deserialize)] -pub struct PeerLatency { - /// Min latency for `NetworkAction` completion. - pub min_latency: Duration, - /// Max latency or `NetworkAction` completion. - pub max_latency: Duration, -} - -// Default PoV size in KiB. -fn default_pov_size() -> usize { - 5120 -} - -// Default bandwidth in bytes -fn default_bandwidth() -> usize { - 52428800 -} - -// Default connectivity percentage -fn default_connectivity() -> usize { - 100 -} - -/// The test input parameters -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct TestConfiguration { - /// The test objective - pub objective: TestObjective, - /// Number of validators - pub n_validators: usize, - /// Number of cores - pub n_cores: usize, - /// The min PoV size - #[serde(default = "default_pov_size")] - pub min_pov_size: usize, - /// The max PoV size, - #[serde(default = "default_pov_size")] - pub max_pov_size: usize, - /// Randomly sampled pov_sizes - #[serde(skip)] - pov_sizes: Vec, - /// The amount of bandiwdth remote validators have. - #[serde(default = "default_bandwidth")] - pub peer_bandwidth: usize, - /// The amount of bandiwdth our node has. - #[serde(default = "default_bandwidth")] - pub bandwidth: usize, - /// Optional peer emulation latency - #[serde(default)] - pub latency: Option, - /// Error probability, applies to sending messages to the emulated network peers - #[serde(default)] - pub error: usize, - /// Connectivity ratio, the percentage of peers we are not connected to, but ar part of - /// the topology. - #[serde(default = "default_connectivity")] - pub connectivity: usize, - /// Number of blocks to run the test for - pub num_blocks: usize, -} - -fn generate_pov_sizes(count: usize, min_kib: usize, max_kib: usize) -> Vec { - (0..count).map(|_| random_pov_size(min_kib * 1024, max_kib * 1024)).collect() -} - -#[derive(Serialize, Deserialize)] -pub struct TestSequence { - #[serde(rename(serialize = "TestConfiguration", deserialize = "TestConfiguration"))] - test_configurations: Vec, -} - -impl TestSequence { - pub fn into_vec(self) -> Vec { - self.test_configurations - .into_iter() - .map(|mut config| { - config.pov_sizes = - generate_pov_sizes(config.n_cores, config.min_pov_size, config.max_pov_size); - config - }) - .collect() - } -} - -impl TestSequence { - pub fn new_from_file(path: &Path) -> std::io::Result { - let string = String::from_utf8(std::fs::read(path)?).expect("File is valid UTF8"); - Ok(serde_yaml::from_str(&string).expect("File is valid test sequence YA")) - } -} - -/// Helper struct for authority related state. -#[derive(Clone)] -pub struct TestAuthorities { - pub keyrings: Vec, - pub validator_public: Vec, - pub validator_authority_id: Vec, -} - -impl TestConfiguration { - #[allow(unused)] - pub fn write_to_disk(&self) { - // Serialize a slice of configurations - let yaml = serde_yaml::to_string(&TestSequence { test_configurations: vec![self.clone()] }) - .unwrap(); - std::fs::write("last_test.yaml", yaml).unwrap(); - } - - pub fn pov_sizes(&self) -> &[usize] { - &self.pov_sizes - } - - /// Generates the authority keys we need for the network emulation. - pub fn generate_authorities(&self) -> TestAuthorities { - let keyrings = (0..self.n_validators) - .map(|peer_index| Keyring::new(format!("Node{}", peer_index))) - .collect::>(); - - // Generate `AuthorityDiscoveryId`` for each peer - let validator_public: Vec = keyrings - .iter() - .map(|keyring: &Keyring| keyring.clone().public().into()) - .collect::>(); - - let validator_authority_id: Vec = keyrings - .iter() - .map(|keyring| keyring.clone().public().into()) - .collect::>(); - - TestAuthorities { keyrings, validator_public, validator_authority_id } - } - - /// An unconstrained standard configuration matching Polkadot/Kusama - pub fn ideal_network( - objective: TestObjective, - num_blocks: usize, - n_validators: usize, - n_cores: usize, - min_pov_size: usize, - max_pov_size: usize, - ) -> TestConfiguration { - Self { - objective, - n_cores, - n_validators, - pov_sizes: generate_pov_sizes(n_cores, min_pov_size, max_pov_size), - bandwidth: 50 * 1024 * 1024, - peer_bandwidth: 50 * 1024 * 1024, - // No latency - latency: None, - error: 0, - num_blocks, - min_pov_size, - max_pov_size, - connectivity: 100, - } - } - - pub fn healthy_network( - objective: TestObjective, - num_blocks: usize, - n_validators: usize, - n_cores: usize, - min_pov_size: usize, - max_pov_size: usize, - ) -> TestConfiguration { - Self { - objective, - n_cores, - n_validators, - pov_sizes: generate_pov_sizes(n_cores, min_pov_size, max_pov_size), - bandwidth: 50 * 1024 * 1024, - peer_bandwidth: 50 * 1024 * 1024, - latency: Some(PeerLatency { - min_latency: Duration::from_millis(1), - max_latency: Duration::from_millis(100), - }), - error: 3, - num_blocks, - min_pov_size, - max_pov_size, - connectivity: 95, - } - } - - pub fn degraded_network( - objective: TestObjective, - num_blocks: usize, - n_validators: usize, - n_cores: usize, - min_pov_size: usize, - max_pov_size: usize, - ) -> TestConfiguration { - Self { - objective, - n_cores, - n_validators, - pov_sizes: generate_pov_sizes(n_cores, min_pov_size, max_pov_size), - bandwidth: 50 * 1024 * 1024, - peer_bandwidth: 50 * 1024 * 1024, - latency: Some(PeerLatency { - min_latency: Duration::from_millis(10), - max_latency: Duration::from_millis(500), - }), - error: 33, - num_blocks, - min_pov_size, - max_pov_size, - connectivity: 67, - } - } -} - -/// Produce a randomized duration between `min` and `max`. -pub fn random_latency(maybe_peer_latency: Option<&PeerLatency>) -> Option { - maybe_peer_latency.map(|peer_latency| { - Uniform::from(peer_latency.min_latency..=peer_latency.max_latency).sample(&mut thread_rng()) - }) -} - -/// Generate a random error based on `probability`. -/// `probability` should be a number between 0 and 100. -pub fn random_error(probability: usize) -> bool { - Uniform::from(0..=99).sample(&mut thread_rng()) < probability -} diff --git a/polkadot/node/subsystem-bench/src/core/display.rs b/polkadot/node/subsystem-bench/src/core/display.rs deleted file mode 100644 index d600cc484c1..00000000000 --- a/polkadot/node/subsystem-bench/src/core/display.rs +++ /dev/null @@ -1,191 +0,0 @@ -// 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 . -// -//! Display implementations and helper methods for parsing prometheus metrics -//! to a format that can be displayed in the CLI. -//! -//! Currently histogram buckets are skipped. -use super::{configuration::TestConfiguration, LOG_TARGET}; -use colored::Colorize; -use prometheus::{ - proto::{MetricFamily, MetricType}, - Registry, -}; -use std::fmt::Display; - -#[derive(Default)] -pub struct MetricCollection(Vec); - -impl From> for MetricCollection { - fn from(metrics: Vec) -> Self { - MetricCollection(metrics) - } -} - -impl MetricCollection { - pub fn all(&self) -> &Vec { - &self.0 - } - - /// Sums up all metrics with the given name in the collection - pub fn sum_by(&self, name: &str) -> f64 { - self.all() - .iter() - .filter(|metric| metric.name == name) - .map(|metric| metric.value) - .sum() - } - - pub fn subset_with_label_value(&self, label_name: &str, label_value: &str) -> MetricCollection { - self.0 - .iter() - .filter_map(|metric| { - if let Some(index) = metric.label_names.iter().position(|label| label == label_name) - { - if Some(&String::from(label_value)) == metric.label_values.get(index) { - Some(metric.clone()) - } else { - None - } - } else { - None - } - }) - .collect::>() - .into() - } -} - -impl Display for MetricCollection { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - writeln!(f)?; - let metrics = self.all(); - for metric in metrics { - writeln!(f, "{}", metric)?; - } - Ok(()) - } -} -#[derive(Debug, Clone)] -pub struct TestMetric { - name: String, - label_names: Vec, - label_values: Vec, - value: f64, -} - -impl Display for TestMetric { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "({} = {}) [{:?}, {:?}]", - self.name.cyan(), - format!("{}", self.value).white(), - self.label_names, - self.label_values - ) - } -} - -// Returns `false` if metric should be skipped. -fn check_metric_family(mf: &MetricFamily) -> bool { - if mf.get_metric().is_empty() { - gum::error!(target: LOG_TARGET, "MetricFamily has no metrics: {:?}", mf); - return false - } - if mf.get_name().is_empty() { - gum::error!(target: LOG_TARGET, "MetricFamily has no name: {:?}", mf); - return false - } - - true -} - -pub fn parse_metrics(registry: &Registry) -> MetricCollection { - let metric_families = registry.gather(); - let mut test_metrics = Vec::new(); - for mf in metric_families { - if !check_metric_family(&mf) { - continue - } - - let name: String = mf.get_name().into(); - let metric_type = mf.get_field_type(); - for m in mf.get_metric() { - let (label_names, label_values): (Vec, Vec) = m - .get_label() - .iter() - .map(|pair| (String::from(pair.get_name()), String::from(pair.get_value()))) - .unzip(); - - match metric_type { - MetricType::COUNTER => { - test_metrics.push(TestMetric { - name: name.clone(), - label_names, - label_values, - value: m.get_counter().get_value(), - }); - }, - MetricType::GAUGE => { - test_metrics.push(TestMetric { - name: name.clone(), - label_names, - label_values, - value: m.get_gauge().get_value(), - }); - }, - MetricType::HISTOGRAM => { - let h = m.get_histogram(); - let h_name = name.clone() + "_sum"; - test_metrics.push(TestMetric { - name: h_name, - label_names: label_names.clone(), - label_values: label_values.clone(), - value: h.get_sample_sum(), - }); - - let h_name = name.clone() + "_count"; - test_metrics.push(TestMetric { - name: h_name, - label_names, - label_values, - value: h.get_sample_sum(), - }); - }, - MetricType::SUMMARY => { - unimplemented!(); - }, - MetricType::UNTYPED => { - unimplemented!(); - }, - } - } - } - test_metrics.into() -} - -pub fn display_configuration(test_config: &TestConfiguration) { - gum::info!( - "{}, {}, {}, {}, {}", - format!("n_validators = {}", test_config.n_validators).blue(), - format!("n_cores = {}", test_config.n_cores).blue(), - format!("pov_size = {} - {}", test_config.min_pov_size, test_config.max_pov_size) - .bright_black(), - format!("error = {}", test_config.error).bright_black(), - format!("latency = {:?}", test_config.latency).bright_black(), - ); -} diff --git a/polkadot/node/subsystem-bench/src/core/environment.rs b/polkadot/node/subsystem-bench/src/core/environment.rs deleted file mode 100644 index 24759647407..00000000000 --- a/polkadot/node/subsystem-bench/src/core/environment.rs +++ /dev/null @@ -1,333 +0,0 @@ -// 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 . -//! Test environment implementation -use crate::{ - core::{mock::AlwaysSupportsParachains, network::NetworkEmulator}, - TestConfiguration, -}; -use colored::Colorize; -use core::time::Duration; -use futures::FutureExt; -use polkadot_overseer::{BlockInfo, Handle as OverseerHandle}; - -use polkadot_node_subsystem::{messages::AllMessages, Overseer, SpawnGlue, TimeoutExt}; -use polkadot_node_subsystem_types::Hash; -use polkadot_node_subsystem_util::metrics::prometheus::{ - self, Gauge, Histogram, PrometheusError, Registry, U64, -}; - -use sc_network::peer_store::LOG_TARGET; -use sc_service::{SpawnTaskHandle, TaskManager}; -use std::{ - fmt::Display, - net::{Ipv4Addr, SocketAddr}, -}; -use tokio::runtime::Handle; - -const MIB: f64 = 1024.0 * 1024.0; - -/// Test environment/configuration metrics -#[derive(Clone)] -pub struct TestEnvironmentMetrics { - /// Number of bytes sent per peer. - n_validators: Gauge, - /// Number of received sent per peer. - n_cores: Gauge, - /// PoV size - pov_size: Histogram, - /// Current block - current_block: Gauge, - /// Current block - block_time: Gauge, -} - -impl TestEnvironmentMetrics { - pub fn new(registry: &Registry) -> Result { - let mut buckets = prometheus::exponential_buckets(16384.0, 2.0, 9) - .expect("arguments are always valid; qed"); - buckets.extend(vec![5.0 * MIB, 6.0 * MIB, 7.0 * MIB, 8.0 * MIB, 9.0 * MIB, 10.0 * MIB]); - - Ok(Self { - n_validators: prometheus::register( - Gauge::new( - "subsystem_benchmark_n_validators", - "Total number of validators in the test", - )?, - registry, - )?, - n_cores: prometheus::register( - Gauge::new( - "subsystem_benchmark_n_cores", - "Number of cores we fetch availability for each block", - )?, - registry, - )?, - current_block: prometheus::register( - Gauge::new("subsystem_benchmark_current_block", "The current test block")?, - registry, - )?, - block_time: prometheus::register( - Gauge::new("subsystem_benchmark_block_time", "The time it takes for the target subsystems(s) to complete all the requests in a block")?, - registry, - )?, - pov_size: prometheus::register( - Histogram::with_opts( - prometheus::HistogramOpts::new( - "subsystem_benchmark_pov_size", - "The compressed size of the proof of validity of a candidate", - ) - .buckets(buckets), - )?, - registry, - )?, - }) - } - - pub fn set_n_validators(&self, n_validators: usize) { - self.n_validators.set(n_validators as u64); - } - - pub fn set_n_cores(&self, n_cores: usize) { - self.n_cores.set(n_cores as u64); - } - - pub fn set_current_block(&self, current_block: usize) { - self.current_block.set(current_block as u64); - } - - pub fn set_block_time(&self, block_time_ms: u64) { - self.block_time.set(block_time_ms); - } - - pub fn on_pov_size(&self, pov_size: usize) { - self.pov_size.observe(pov_size as f64); - } -} - -fn new_runtime() -> tokio::runtime::Runtime { - tokio::runtime::Builder::new_multi_thread() - .thread_name("subsystem-bench") - .enable_all() - .thread_stack_size(3 * 1024 * 1024) - .build() - .unwrap() -} - -/// Wrapper for dependencies -pub struct TestEnvironmentDependencies { - pub registry: Registry, - pub task_manager: TaskManager, - pub runtime: tokio::runtime::Runtime, -} - -impl Default for TestEnvironmentDependencies { - fn default() -> Self { - let runtime = new_runtime(); - let registry = Registry::new(); - let task_manager: TaskManager = - TaskManager::new(runtime.handle().clone(), Some(®istry)).unwrap(); - - Self { runtime, registry, task_manager } - } -} - -// A dummy genesis hash -pub const GENESIS_HASH: Hash = Hash::repeat_byte(0xff); - -// We use this to bail out sending messages to the subsystem if it is overloaded such that -// the time of flight is breaches 5s. -// This should eventually be a test parameter. -const MAX_TIME_OF_FLIGHT: Duration = Duration::from_millis(5000); - -/// The test environment is the high level wrapper of all things required to test -/// a certain subsystem. -/// -/// ## Mockups -/// The overseer is passed in during construction and it can host an arbitrary number of -/// real subsystems instances and the corresponding mocked instances such that the real -/// subsystems can get their messages answered. -/// -/// As the subsystem's performance depends on network connectivity, the test environment -/// emulates validator nodes on the network, see `NetworkEmulator`. The network emulation -/// is configurable in terms of peer bandwidth, latency and connection error rate using -/// uniform distribution sampling. -/// -/// -/// ## Usage -/// `TestEnvironment` is used in tests to send `Overseer` messages or signals to the subsystem -/// under test. -/// -/// ## Collecting test metrics -/// -/// ### Prometheus -/// A prometheus endpoint is exposed while the test is running. A local Prometheus instance -/// can scrape it every 1s and a Grafana dashboard is the preferred way of visualizing -/// the performance characteristics of the subsystem. -/// -/// ### CLI -/// A subset of the Prometheus metrics are printed at the end of the test. -pub struct TestEnvironment { - /// Test dependencies - dependencies: TestEnvironmentDependencies, - /// A runtime handle - runtime_handle: tokio::runtime::Handle, - /// A handle to the lovely overseer - overseer_handle: OverseerHandle, - /// The test configuration. - config: TestConfiguration, - /// A handle to the network emulator. - network: NetworkEmulator, - /// Configuration/env metrics - metrics: TestEnvironmentMetrics, -} - -impl TestEnvironment { - /// Create a new test environment - pub fn new( - dependencies: TestEnvironmentDependencies, - config: TestConfiguration, - network: NetworkEmulator, - overseer: Overseer, AlwaysSupportsParachains>, - overseer_handle: OverseerHandle, - ) -> Self { - let metrics = TestEnvironmentMetrics::new(&dependencies.registry) - .expect("Metrics need to be registered"); - - let spawn_handle = dependencies.task_manager.spawn_handle(); - spawn_handle.spawn_blocking("overseer", "overseer", overseer.run().boxed()); - - let registry_clone = dependencies.registry.clone(); - dependencies.task_manager.spawn_handle().spawn_blocking( - "prometheus", - "test-environment", - async move { - prometheus_endpoint::init_prometheus( - SocketAddr::new(std::net::IpAddr::V4(Ipv4Addr::LOCALHOST), 9999), - registry_clone, - ) - .await - .unwrap(); - }, - ); - - TestEnvironment { - runtime_handle: dependencies.runtime.handle().clone(), - dependencies, - overseer_handle, - config, - network, - metrics, - } - } - - pub fn config(&self) -> &TestConfiguration { - &self.config - } - - pub fn network(&self) -> &NetworkEmulator { - &self.network - } - - pub fn registry(&self) -> &Registry { - &self.dependencies.registry - } - - pub fn metrics(&self) -> &TestEnvironmentMetrics { - &self.metrics - } - - pub fn runtime(&self) -> Handle { - self.runtime_handle.clone() - } - - // Send a message to the subsystem under test environment. - pub async fn send_message(&mut self, msg: AllMessages) { - self.overseer_handle - .send_msg(msg, LOG_TARGET) - .timeout(MAX_TIME_OF_FLIGHT) - .await - .unwrap_or_else(|| { - panic!("{}ms maximum time of flight breached", MAX_TIME_OF_FLIGHT.as_millis()) - }); - } - - // Send an `ActiveLeavesUpdate` signal to all subsystems under test. - pub async fn import_block(&mut self, block: BlockInfo) { - self.overseer_handle - .block_imported(block) - .timeout(MAX_TIME_OF_FLIGHT) - .await - .unwrap_or_else(|| { - panic!("{}ms maximum time of flight breached", MAX_TIME_OF_FLIGHT.as_millis()) - }); - } - - // Stop overseer and subsystems. - pub async fn stop(&mut self) { - self.overseer_handle.stop().await; - } -} - -impl Display for TestEnvironment { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let stats = self.network().stats(); - - writeln!(f, "\n")?; - writeln!( - f, - "Total received from network: {}", - format!( - "{} MiB", - stats - .iter() - .enumerate() - .map(|(_index, stats)| stats.tx_bytes_total as u128) - .sum::() / (1024 * 1024) - ) - .cyan() - )?; - writeln!( - f, - "Total sent to network: {}", - format!("{} KiB", stats[0].tx_bytes_total / (1024)).cyan() - )?; - - let test_metrics = super::display::parse_metrics(self.registry()); - let subsystem_cpu_metrics = - test_metrics.subset_with_label_value("task_group", "availability-recovery"); - let total_cpu = subsystem_cpu_metrics.sum_by("substrate_tasks_polling_duration_sum"); - writeln!(f, "Total subsystem CPU usage {}", format!("{:.2}s", total_cpu).bright_purple())?; - writeln!( - f, - "CPU usage per block {}", - format!("{:.2}s", total_cpu / self.config().num_blocks as f64).bright_purple() - )?; - - let test_env_cpu_metrics = - test_metrics.subset_with_label_value("task_group", "test-environment"); - let total_cpu = test_env_cpu_metrics.sum_by("substrate_tasks_polling_duration_sum"); - writeln!( - f, - "Total test environment CPU usage {}", - format!("{:.2}s", total_cpu).bright_purple() - )?; - writeln!( - f, - "CPU usage per block {}", - format!("{:.2}s", total_cpu / self.config().num_blocks as f64).bright_purple() - ) - } -} diff --git a/polkadot/node/subsystem-bench/src/core/keyring.rs b/polkadot/node/subsystem-bench/src/core/keyring.rs deleted file mode 100644 index 2d9aa348a92..00000000000 --- a/polkadot/node/subsystem-bench/src/core/keyring.rs +++ /dev/null @@ -1,40 +0,0 @@ -// 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 . - -pub use sp_core::sr25519; -use sp_core::{ - sr25519::{Pair, Public}, - Pair as PairT, -}; -/// Set of test accounts. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct Keyring { - name: String, -} - -impl Keyring { - pub fn new(name: String) -> Keyring { - Self { name } - } - - pub fn pair(self) -> Pair { - Pair::from_string(&format!("//{}", self.name), None).expect("input is always good; qed") - } - - pub fn public(self) -> Public { - self.pair().public() - } -} diff --git a/polkadot/node/subsystem-bench/src/core/mock/av_store.rs b/polkadot/node/subsystem-bench/src/core/mock/av_store.rs deleted file mode 100644 index a471230f1b3..00000000000 --- a/polkadot/node/subsystem-bench/src/core/mock/av_store.rs +++ /dev/null @@ -1,137 +0,0 @@ -// 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 . -//! -//! A generic av store subsystem mockup suitable to be used in benchmarks. - -use parity_scale_codec::Encode; -use polkadot_primitives::CandidateHash; - -use std::collections::HashMap; - -use futures::{channel::oneshot, FutureExt}; - -use polkadot_node_primitives::ErasureChunk; - -use polkadot_node_subsystem::{ - messages::AvailabilityStoreMessage, overseer, SpawnedSubsystem, SubsystemError, -}; - -use polkadot_node_subsystem_types::OverseerSignal; - -pub struct AvailabilityStoreState { - candidate_hashes: HashMap, - chunks: Vec>, -} - -const LOG_TARGET: &str = "subsystem-bench::av-store-mock"; - -/// A mock of the availability store subsystem. This one also generates all the -/// candidates that a -pub struct MockAvailabilityStore { - state: AvailabilityStoreState, -} - -impl MockAvailabilityStore { - pub fn new( - chunks: Vec>, - candidate_hashes: HashMap, - ) -> MockAvailabilityStore { - Self { state: AvailabilityStoreState { chunks, candidate_hashes } } - } - - async fn respond_to_query_all_request( - &self, - candidate_hash: CandidateHash, - send_chunk: impl Fn(usize) -> bool, - tx: oneshot::Sender>, - ) { - let candidate_index = self - .state - .candidate_hashes - .get(&candidate_hash) - .expect("candidate was generated previously; qed"); - gum::debug!(target: LOG_TARGET, ?candidate_hash, candidate_index, "Candidate mapped to index"); - - let v = self - .state - .chunks - .get(*candidate_index) - .unwrap() - .iter() - .filter(|c| send_chunk(c.index.0 as usize)) - .cloned() - .collect(); - - let _ = tx.send(v); - } -} - -#[overseer::subsystem(AvailabilityStore, error=SubsystemError, prefix=self::overseer)] -impl MockAvailabilityStore { - fn start(self, ctx: Context) -> SpawnedSubsystem { - let future = self.run(ctx).map(|_| Ok(())).boxed(); - - SpawnedSubsystem { name: "test-environment", future } - } -} - -#[overseer::contextbounds(AvailabilityStore, prefix = self::overseer)] -impl MockAvailabilityStore { - async fn run(self, mut ctx: Context) { - gum::debug!(target: LOG_TARGET, "Subsystem running"); - loop { - let msg = ctx.recv().await.expect("Overseer never fails us"); - - match msg { - orchestra::FromOrchestra::Signal(signal) => - if signal == OverseerSignal::Conclude { - return - }, - orchestra::FromOrchestra::Communication { msg } => match msg { - AvailabilityStoreMessage::QueryAvailableData(candidate_hash, tx) => { - gum::debug!(target: LOG_TARGET, candidate_hash = ?candidate_hash, "Responding to QueryAvailableData"); - - // We never have the full available data. - let _ = tx.send(None); - }, - AvailabilityStoreMessage::QueryAllChunks(candidate_hash, tx) => { - // We always have our own chunk. - gum::debug!(target: LOG_TARGET, candidate_hash = ?candidate_hash, "Responding to QueryAllChunks"); - self.respond_to_query_all_request(candidate_hash, |index| index == 0, tx) - .await; - }, - AvailabilityStoreMessage::QueryChunkSize(candidate_hash, tx) => { - gum::debug!(target: LOG_TARGET, candidate_hash = ?candidate_hash, "Responding to QueryChunkSize"); - - let candidate_index = self - .state - .candidate_hashes - .get(&candidate_hash) - .expect("candidate was generated previously; qed"); - gum::debug!(target: LOG_TARGET, ?candidate_hash, candidate_index, "Candidate mapped to index"); - - let chunk_size = - self.state.chunks.get(*candidate_index).unwrap()[0].encoded_size(); - let _ = tx.send(Some(chunk_size)); - }, - _ => { - unimplemented!("Unexpected av-store message") - }, - }, - } - } - } -} diff --git a/polkadot/node/subsystem-bench/src/core/mock/dummy.rs b/polkadot/node/subsystem-bench/src/core/mock/dummy.rs deleted file mode 100644 index 0628368a49c..00000000000 --- a/polkadot/node/subsystem-bench/src/core/mock/dummy.rs +++ /dev/null @@ -1,98 +0,0 @@ -// 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 . -//! Dummy subsystem mocks. -use paste::paste; - -use futures::FutureExt; -use polkadot_node_subsystem::{overseer, SpawnedSubsystem, SubsystemError}; -use std::time::Duration; -use tokio::time::sleep; - -const LOG_TARGET: &str = "subsystem-bench::mockery"; - -macro_rules! mock { - // Just query by relay parent - ($subsystem_name:ident) => { - paste! { - pub struct [] {} - #[overseer::subsystem($subsystem_name, error=SubsystemError, prefix=self::overseer)] - impl [] { - fn start(self, ctx: Context) -> SpawnedSubsystem { - let future = self.run(ctx).map(|_| Ok(())).boxed(); - - // The name will appear in substrate CPU task metrics as `task_group`.` - SpawnedSubsystem { name: "test-environment", future } - } - } - - #[overseer::contextbounds($subsystem_name, prefix = self::overseer)] - impl [] { - async fn run(self, mut ctx: Context) { - let mut count_total_msg = 0; - loop { - futures::select!{ - msg = ctx.recv().fuse() => { - match msg.unwrap() { - orchestra::FromOrchestra::Signal(signal) => { - match signal { - polkadot_node_subsystem_types::OverseerSignal::Conclude => {return}, - _ => {} - } - }, - orchestra::FromOrchestra::Communication { msg } => { - gum::debug!(target: LOG_TARGET, msg = ?msg, "mocked subsystem received message"); - } - } - - count_total_msg +=1; - } - _ = sleep(Duration::from_secs(6)).fuse() => { - if count_total_msg > 0 { - gum::trace!(target: LOG_TARGET, "Subsystem {} processed {} messages since last time", stringify!($subsystem_name), count_total_msg); - } - count_total_msg = 0; - } - } - } - } - } - } - }; -} - -mock!(AvailabilityStore); -mock!(StatementDistribution); -mock!(BitfieldSigning); -mock!(BitfieldDistribution); -mock!(Provisioner); -mock!(NetworkBridgeRx); -mock!(CollationGeneration); -mock!(CollatorProtocol); -mock!(GossipSupport); -mock!(DisputeDistribution); -mock!(DisputeCoordinator); -mock!(ProspectiveParachains); -mock!(PvfChecker); -mock!(CandidateBacking); -mock!(AvailabilityDistribution); -mock!(CandidateValidation); -mock!(AvailabilityRecovery); -mock!(NetworkBridgeTx); -mock!(ChainApi); -mock!(ChainSelection); -mock!(ApprovalVoting); -mock!(ApprovalDistribution); -mock!(RuntimeApi); diff --git a/polkadot/node/subsystem-bench/src/core/mock/mod.rs b/polkadot/node/subsystem-bench/src/core/mock/mod.rs deleted file mode 100644 index d59642e9605..00000000000 --- a/polkadot/node/subsystem-bench/src/core/mock/mod.rs +++ /dev/null @@ -1,77 +0,0 @@ -// 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 polkadot_node_subsystem::HeadSupportsParachains; -use polkadot_node_subsystem_types::Hash; - -pub mod av_store; -pub mod dummy; -pub mod network_bridge; -pub mod runtime_api; - -pub use av_store::*; -pub use network_bridge::*; -pub use runtime_api::*; - -pub struct AlwaysSupportsParachains {} -#[async_trait::async_trait] -impl HeadSupportsParachains for AlwaysSupportsParachains { - async fn head_supports_parachains(&self, _head: &Hash) -> bool { - true - } -} - -// An orchestra with dummy subsystems -macro_rules! dummy_builder { - ($spawn_task_handle: ident) => {{ - use super::core::mock::dummy::*; - - // Initialize a mock overseer. - // All subsystem except approval_voting and approval_distribution are mock subsystems. - Overseer::builder() - .approval_voting(MockApprovalVoting {}) - .approval_distribution(MockApprovalDistribution {}) - .availability_recovery(MockAvailabilityRecovery {}) - .candidate_validation(MockCandidateValidation {}) - .chain_api(MockChainApi {}) - .chain_selection(MockChainSelection {}) - .dispute_coordinator(MockDisputeCoordinator {}) - .runtime_api(MockRuntimeApi {}) - .network_bridge_tx(MockNetworkBridgeTx {}) - .availability_distribution(MockAvailabilityDistribution {}) - .availability_store(MockAvailabilityStore {}) - .pvf_checker(MockPvfChecker {}) - .candidate_backing(MockCandidateBacking {}) - .statement_distribution(MockStatementDistribution {}) - .bitfield_signing(MockBitfieldSigning {}) - .bitfield_distribution(MockBitfieldDistribution {}) - .provisioner(MockProvisioner {}) - .network_bridge_rx(MockNetworkBridgeRx {}) - .collation_generation(MockCollationGeneration {}) - .collator_protocol(MockCollatorProtocol {}) - .gossip_support(MockGossipSupport {}) - .dispute_distribution(MockDisputeDistribution {}) - .prospective_parachains(MockProspectiveParachains {}) - .activation_external_listeners(Default::default()) - .span_per_active_leaf(Default::default()) - .active_leaves(Default::default()) - .metrics(Default::default()) - .supports_parachains(AlwaysSupportsParachains {}) - .spawner(SpawnGlue($spawn_task_handle)) - }}; -} - -pub(crate) use dummy_builder; diff --git a/polkadot/node/subsystem-bench/src/core/mock/network_bridge.rs b/polkadot/node/subsystem-bench/src/core/mock/network_bridge.rs deleted file mode 100644 index b106b832011..00000000000 --- a/polkadot/node/subsystem-bench/src/core/mock/network_bridge.rs +++ /dev/null @@ -1,323 +0,0 @@ -// 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 . -//! -//! A generic av store subsystem mockup suitable to be used in benchmarks. - -use futures::Future; -use parity_scale_codec::Encode; -use polkadot_node_subsystem_types::OverseerSignal; -use std::{collections::HashMap, pin::Pin}; - -use futures::FutureExt; - -use polkadot_node_primitives::{AvailableData, ErasureChunk}; - -use polkadot_primitives::CandidateHash; -use sc_network::{OutboundFailure, RequestFailure}; - -use polkadot_node_subsystem::{ - messages::NetworkBridgeTxMessage, overseer, SpawnedSubsystem, SubsystemError, -}; - -use polkadot_node_network_protocol::request_response::{ - self as req_res, v1::ChunkResponse, Requests, -}; -use polkadot_primitives::AuthorityDiscoveryId; - -use crate::core::{ - configuration::{random_error, random_latency, TestConfiguration}, - network::{NetworkAction, NetworkEmulator, RateLimit}, -}; - -/// The availability store state of all emulated peers. -/// The network bridge tx mock will respond to requests as if the request is being serviced -/// by a remote peer on the network -pub struct NetworkAvailabilityState { - pub candidate_hashes: HashMap, - pub available_data: Vec, - pub chunks: Vec>, -} - -const LOG_TARGET: &str = "subsystem-bench::network-bridge-tx-mock"; - -/// A mock of the network bridge tx subsystem. -pub struct MockNetworkBridgeTx { - /// The test configurationg - config: TestConfiguration, - /// The network availability state - availabilty: NetworkAvailabilityState, - /// A network emulator instance - network: NetworkEmulator, -} - -impl MockNetworkBridgeTx { - pub fn new( - config: TestConfiguration, - availabilty: NetworkAvailabilityState, - network: NetworkEmulator, - ) -> MockNetworkBridgeTx { - Self { config, availabilty, network } - } - - fn not_connected_response( - &self, - authority_discovery_id: &AuthorityDiscoveryId, - future: Pin + Send>>, - ) -> NetworkAction { - // The network action will send the error after a random delay expires. - return NetworkAction::new( - authority_discovery_id.clone(), - future, - 0, - // Generate a random latency based on configuration. - random_latency(self.config.latency.as_ref()), - ) - } - /// Returns an `NetworkAction` corresponding to the peer sending the response. If - /// the peer is connected, the error is sent with a randomized latency as defined in - /// configuration. - fn respond_to_send_request( - &mut self, - request: Requests, - ingress_tx: &mut tokio::sync::mpsc::UnboundedSender, - ) -> NetworkAction { - let ingress_tx = ingress_tx.clone(); - - match request { - Requests::ChunkFetchingV1(outgoing_request) => { - let authority_discovery_id = match outgoing_request.peer { - req_res::Recipient::Authority(authority_discovery_id) => authority_discovery_id, - _ => unimplemented!("Peer recipient not supported yet"), - }; - // Account our sent request bytes. - self.network.peer_stats(0).inc_sent(outgoing_request.payload.encoded_size()); - - // If peer is disconnected return an error - if !self.network.is_peer_connected(&authority_discovery_id) { - // We always send `NotConnected` error and we ignore `IfDisconnected` value in - // the caller. - let future = async move { - let _ = outgoing_request - .pending_response - .send(Err(RequestFailure::NotConnected)); - } - .boxed(); - return self.not_connected_response(&authority_discovery_id, future) - } - - // Account for remote received request bytes. - self.network - .peer_stats_by_id(&authority_discovery_id) - .inc_received(outgoing_request.payload.encoded_size()); - - let validator_index: usize = outgoing_request.payload.index.0 as usize; - let candidate_hash = outgoing_request.payload.candidate_hash; - - let candidate_index = self - .availabilty - .candidate_hashes - .get(&candidate_hash) - .expect("candidate was generated previously; qed"); - gum::warn!(target: LOG_TARGET, ?candidate_hash, candidate_index, "Candidate mapped to index"); - - let chunk: ChunkResponse = self.availabilty.chunks.get(*candidate_index).unwrap() - [validator_index] - .clone() - .into(); - let mut size = chunk.encoded_size(); - - let response = if random_error(self.config.error) { - // Error will not account to any bandwidth used. - size = 0; - Err(RequestFailure::Network(OutboundFailure::ConnectionClosed)) - } else { - Ok(req_res::v1::ChunkFetchingResponse::from(Some(chunk)).encode()) - }; - - let authority_discovery_id_clone = authority_discovery_id.clone(); - - let future = async move { - let _ = outgoing_request.pending_response.send(response); - } - .boxed(); - - let future_wrapper = async move { - // Forward the response to the ingress channel of our node. - // On receive side we apply our node receiving rate limit. - let action = - NetworkAction::new(authority_discovery_id_clone, future, size, None); - ingress_tx.send(action).unwrap(); - } - .boxed(); - - NetworkAction::new( - authority_discovery_id, - future_wrapper, - size, - // Generate a random latency based on configuration. - random_latency(self.config.latency.as_ref()), - ) - }, - Requests::AvailableDataFetchingV1(outgoing_request) => { - let candidate_hash = outgoing_request.payload.candidate_hash; - let candidate_index = self - .availabilty - .candidate_hashes - .get(&candidate_hash) - .expect("candidate was generated previously; qed"); - gum::debug!(target: LOG_TARGET, ?candidate_hash, candidate_index, "Candidate mapped to index"); - - let authority_discovery_id = match outgoing_request.peer { - req_res::Recipient::Authority(authority_discovery_id) => authority_discovery_id, - _ => unimplemented!("Peer recipient not supported yet"), - }; - - // Account our sent request bytes. - self.network.peer_stats(0).inc_sent(outgoing_request.payload.encoded_size()); - - // If peer is disconnected return an error - if !self.network.is_peer_connected(&authority_discovery_id) { - let future = async move { - let _ = outgoing_request - .pending_response - .send(Err(RequestFailure::NotConnected)); - } - .boxed(); - return self.not_connected_response(&authority_discovery_id, future) - } - - // Account for remote received request bytes. - self.network - .peer_stats_by_id(&authority_discovery_id) - .inc_received(outgoing_request.payload.encoded_size()); - - let available_data = - self.availabilty.available_data.get(*candidate_index).unwrap().clone(); - - let size = available_data.encoded_size(); - - let response = if random_error(self.config.error) { - Err(RequestFailure::Network(OutboundFailure::ConnectionClosed)) - } else { - Ok(req_res::v1::AvailableDataFetchingResponse::from(Some(available_data)) - .encode()) - }; - - let future = async move { - let _ = outgoing_request.pending_response.send(response); - } - .boxed(); - - let authority_discovery_id_clone = authority_discovery_id.clone(); - - let future_wrapper = async move { - // Forward the response to the ingress channel of our node. - // On receive side we apply our node receiving rate limit. - let action = - NetworkAction::new(authority_discovery_id_clone, future, size, None); - ingress_tx.send(action).unwrap(); - } - .boxed(); - - NetworkAction::new( - authority_discovery_id, - future_wrapper, - size, - // Generate a random latency based on configuration. - random_latency(self.config.latency.as_ref()), - ) - }, - _ => panic!("received an unexpected request"), - } - } -} - -#[overseer::subsystem(NetworkBridgeTx, error=SubsystemError, prefix=self::overseer)] -impl MockNetworkBridgeTx { - fn start(self, ctx: Context) -> SpawnedSubsystem { - let future = self.run(ctx).map(|_| Ok(())).boxed(); - - SpawnedSubsystem { name: "test-environment", future } - } -} - -#[overseer::contextbounds(NetworkBridgeTx, prefix = self::overseer)] -impl MockNetworkBridgeTx { - async fn run(mut self, mut ctx: Context) { - let (mut ingress_tx, mut ingress_rx) = - tokio::sync::mpsc::unbounded_channel::(); - - // Initialize our node bandwidth limits. - let mut rx_limiter = RateLimit::new(10, self.config.bandwidth); - - let our_network = self.network.clone(); - - // This task will handle node messages receipt from the simulated network. - ctx.spawn_blocking( - "network-receive", - async move { - while let Some(action) = ingress_rx.recv().await { - let size = action.size(); - - // account for our node receiving the data. - our_network.inc_received(size); - rx_limiter.reap(size).await; - action.run().await; - } - } - .boxed(), - ) - .expect("We never fail to spawn tasks"); - - // Main subsystem loop. - loop { - let msg = ctx.recv().await.expect("Overseer never fails us"); - - match msg { - orchestra::FromOrchestra::Signal(signal) => - if signal == OverseerSignal::Conclude { - return - }, - orchestra::FromOrchestra::Communication { msg } => match msg { - NetworkBridgeTxMessage::SendRequests(requests, _if_disconnected) => { - for request in requests { - gum::debug!(target: LOG_TARGET, request = ?request, "Processing request"); - self.network.inc_sent(request_size(&request)); - let action = self.respond_to_send_request(request, &mut ingress_tx); - - // Will account for our node sending the request over the emulated - // network. - self.network.submit_peer_action(action.peer(), action); - } - }, - _ => { - unimplemented!("Unexpected network bridge message") - }, - }, - } - } - } -} - -// A helper to determine the request payload size. -fn request_size(request: &Requests) -> usize { - match request { - Requests::ChunkFetchingV1(outgoing_request) => outgoing_request.payload.encoded_size(), - Requests::AvailableDataFetchingV1(outgoing_request) => - outgoing_request.payload.encoded_size(), - _ => unimplemented!("received an unexpected request"), - } -} diff --git a/polkadot/node/subsystem-bench/src/core/mock/runtime_api.rs b/polkadot/node/subsystem-bench/src/core/mock/runtime_api.rs deleted file mode 100644 index d664ebead3c..00000000000 --- a/polkadot/node/subsystem-bench/src/core/mock/runtime_api.rs +++ /dev/null @@ -1,110 +0,0 @@ -// 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 . -//! -//! A generic runtime api subsystem mockup suitable to be used in benchmarks. - -use polkadot_primitives::{GroupIndex, IndexedVec, SessionInfo, ValidatorIndex}; - -use polkadot_node_subsystem::{ - messages::{RuntimeApiMessage, RuntimeApiRequest}, - overseer, SpawnedSubsystem, SubsystemError, -}; -use polkadot_node_subsystem_types::OverseerSignal; - -use crate::core::configuration::{TestAuthorities, TestConfiguration}; -use futures::FutureExt; - -const LOG_TARGET: &str = "subsystem-bench::runtime-api-mock"; - -pub struct RuntimeApiState { - authorities: TestAuthorities, -} - -pub struct MockRuntimeApi { - state: RuntimeApiState, - config: TestConfiguration, -} - -impl MockRuntimeApi { - pub fn new(config: TestConfiguration, authorities: TestAuthorities) -> MockRuntimeApi { - Self { state: RuntimeApiState { authorities }, config } - } - - fn session_info(&self) -> SessionInfo { - let all_validators = (0..self.config.n_validators) - .map(|i| ValidatorIndex(i as _)) - .collect::>(); - - let validator_groups = all_validators.chunks(5).map(Vec::from).collect::>(); - - SessionInfo { - validators: self.state.authorities.validator_public.clone().into(), - discovery_keys: self.state.authorities.validator_authority_id.clone(), - validator_groups: IndexedVec::>::from(validator_groups), - assignment_keys: vec![], - n_cores: self.config.n_cores as u32, - zeroth_delay_tranche_width: 0, - relay_vrf_modulo_samples: 0, - n_delay_tranches: 0, - no_show_slots: 0, - needed_approvals: 0, - active_validator_indices: vec![], - dispute_period: 6, - random_seed: [0u8; 32], - } - } -} - -#[overseer::subsystem(RuntimeApi, error=SubsystemError, prefix=self::overseer)] -impl MockRuntimeApi { - fn start(self, ctx: Context) -> SpawnedSubsystem { - let future = self.run(ctx).map(|_| Ok(())).boxed(); - - SpawnedSubsystem { name: "test-environment", future } - } -} - -#[overseer::contextbounds(RuntimeApi, prefix = self::overseer)] -impl MockRuntimeApi { - async fn run(self, mut ctx: Context) { - loop { - let msg = ctx.recv().await.expect("Overseer never fails us"); - - match msg { - orchestra::FromOrchestra::Signal(signal) => - if signal == OverseerSignal::Conclude { - return - }, - orchestra::FromOrchestra::Communication { msg } => { - gum::debug!(target: LOG_TARGET, msg=?msg, "recv message"); - - match msg { - RuntimeApiMessage::Request( - _request, - RuntimeApiRequest::SessionInfo(_session_index, sender), - ) => { - let _ = sender.send(Ok(Some(self.session_info()))); - }, - // Long term TODO: implement more as needed. - _ => { - unimplemented!("Unexpected runtime-api message") - }, - } - }, - } - } - } -} diff --git a/polkadot/node/subsystem-bench/src/core/mod.rs b/polkadot/node/subsystem-bench/src/core/mod.rs deleted file mode 100644 index 282788d143b..00000000000 --- a/polkadot/node/subsystem-bench/src/core/mod.rs +++ /dev/null @@ -1,24 +0,0 @@ -// 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 . - -const LOG_TARGET: &str = "subsystem-bench::core"; - -pub mod configuration; -pub mod display; -pub mod environment; -pub mod keyring; -pub mod mock; -pub mod network; diff --git a/polkadot/node/subsystem-bench/src/core/network.rs b/polkadot/node/subsystem-bench/src/core/network.rs deleted file mode 100644 index c4e20b421d3..00000000000 --- a/polkadot/node/subsystem-bench/src/core/network.rs +++ /dev/null @@ -1,485 +0,0 @@ -// 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::{ - configuration::{TestAuthorities, TestConfiguration}, - environment::TestEnvironmentDependencies, - *, -}; -use colored::Colorize; -use polkadot_primitives::AuthorityDiscoveryId; -use prometheus_endpoint::U64; -use rand::{seq::SliceRandom, thread_rng}; -use sc_service::SpawnTaskHandle; -use std::{ - collections::HashMap, - sync::{ - atomic::{AtomicU64, Ordering}, - Arc, - }, - time::{Duration, Instant}, -}; -use tokio::sync::mpsc::UnboundedSender; - -// An emulated node egress traffic rate_limiter. -#[derive(Debug)] -pub struct RateLimit { - // How often we refill credits in buckets - tick_rate: usize, - // Total ticks - total_ticks: usize, - // Max refill per tick - max_refill: usize, - // Available credit. We allow for bursts over 1/tick_rate of `cps` budget, but we - // account it by negative credit. - credits: isize, - // When last refilled. - last_refill: Instant, -} - -impl RateLimit { - // Create a new `RateLimit` from a `cps` (credits per second) budget and - // `tick_rate`. - pub fn new(tick_rate: usize, cps: usize) -> Self { - // Compute how much refill for each tick - let max_refill = cps / tick_rate; - RateLimit { - tick_rate, - total_ticks: 0, - max_refill, - // A fresh start - credits: max_refill as isize, - last_refill: Instant::now(), - } - } - - pub async fn refill(&mut self) { - // If this is called to early, we need to sleep until next tick. - let now = Instant::now(); - let next_tick_delta = - (self.last_refill + Duration::from_millis(1000 / self.tick_rate as u64)) - now; - - // Sleep until next tick. - if !next_tick_delta.is_zero() { - gum::trace!(target: LOG_TARGET, "need to sleep {}ms", next_tick_delta.as_millis()); - tokio::time::sleep(next_tick_delta).await; - } - - self.total_ticks += 1; - self.credits += self.max_refill as isize; - self.last_refill = Instant::now(); - } - - // Reap credits from the bucket. - // Blocks if credits budged goes negative during call. - pub async fn reap(&mut self, amount: usize) { - self.credits -= amount as isize; - - if self.credits >= 0 { - return - } - - while self.credits < 0 { - gum::trace!(target: LOG_TARGET, "Before refill: {:?}", &self); - self.refill().await; - gum::trace!(target: LOG_TARGET, "After refill: {:?}", &self); - } - } -} - -#[cfg(test)] -mod tests { - use std::time::Instant; - - use super::RateLimit; - - #[tokio::test] - async fn test_expected_rate() { - let tick_rate = 200; - let budget = 1_000_000; - // rate must not exceeed 100 credits per second - let mut rate_limiter = RateLimit::new(tick_rate, budget); - let mut total_sent = 0usize; - let start = Instant::now(); - - let mut reap_amount = 0; - while rate_limiter.total_ticks < tick_rate { - reap_amount += 1; - reap_amount %= 100; - - rate_limiter.reap(reap_amount).await; - total_sent += reap_amount; - } - - let end = Instant::now(); - - println!("duration: {}", (end - start).as_millis()); - - // Allow up to `budget/max_refill` error tolerance - let lower_bound = budget as u128 * ((end - start).as_millis() / 1000u128); - let upper_bound = budget as u128 * - ((end - start).as_millis() / 1000u128 + rate_limiter.max_refill as u128); - assert!(total_sent as u128 >= lower_bound); - assert!(total_sent as u128 <= upper_bound); - } -} - -// A network peer emulator. It spawns a task that accepts `NetworkActions` and -// executes them with a configurable delay and bandwidth constraints. Tipically -// these actions wrap a future that performs a channel send to the subsystem(s) under test. -#[derive(Clone)] -struct PeerEmulator { - // The queue of requests waiting to be served by the emulator - actions_tx: UnboundedSender, -} - -impl PeerEmulator { - pub fn new( - bandwidth: usize, - spawn_task_handle: SpawnTaskHandle, - stats: Arc, - ) -> Self { - let (actions_tx, mut actions_rx) = tokio::sync::mpsc::unbounded_channel(); - - spawn_task_handle - .clone() - .spawn("peer-emulator", "test-environment", async move { - // Rate limit peer send. - let mut rate_limiter = RateLimit::new(10, bandwidth); - loop { - let stats_clone = stats.clone(); - let maybe_action: Option = actions_rx.recv().await; - if let Some(action) = maybe_action { - let size = action.size(); - rate_limiter.reap(size).await; - if let Some(latency) = action.latency { - spawn_task_handle.spawn( - "peer-emulator-latency", - "test-environment", - async move { - tokio::time::sleep(latency).await; - action.run().await; - stats_clone.inc_sent(size); - }, - ) - } else { - action.run().await; - stats_clone.inc_sent(size); - } - } else { - break - } - } - }); - - Self { actions_tx } - } - - // Queue a send request from the emulated peer. - pub fn send(&mut self, action: NetworkAction) { - self.actions_tx.send(action).expect("peer emulator task lives"); - } -} - -pub type ActionFuture = std::pin::Pin + std::marker::Send>>; -/// An network action to be completed by the emulator task. -pub struct NetworkAction { - // The function that performs the action - run: ActionFuture, - // The payload size that we simulate sending/receiving from a peer - size: usize, - // Peer which should run the action. - peer: AuthorityDiscoveryId, - // The amount of time to delay the polling `run` - latency: Option, -} - -unsafe impl Send for NetworkAction {} - -/// Book keeping of sent and received bytes. -pub struct PeerEmulatorStats { - rx_bytes_total: AtomicU64, - tx_bytes_total: AtomicU64, - metrics: Metrics, - peer_index: usize, -} - -impl PeerEmulatorStats { - pub(crate) fn new(peer_index: usize, metrics: Metrics) -> Self { - Self { - metrics, - rx_bytes_total: AtomicU64::from(0), - tx_bytes_total: AtomicU64::from(0), - peer_index, - } - } - - pub fn inc_sent(&self, bytes: usize) { - self.tx_bytes_total.fetch_add(bytes as u64, Ordering::Relaxed); - self.metrics.on_peer_sent(self.peer_index, bytes); - } - - pub fn inc_received(&self, bytes: usize) { - self.rx_bytes_total.fetch_add(bytes as u64, Ordering::Relaxed); - self.metrics.on_peer_received(self.peer_index, bytes); - } - - pub fn sent(&self) -> u64 { - self.tx_bytes_total.load(Ordering::Relaxed) - } - - pub fn received(&self) -> u64 { - self.rx_bytes_total.load(Ordering::Relaxed) - } -} - -#[derive(Debug, Default)] -pub struct PeerStats { - pub rx_bytes_total: u64, - pub tx_bytes_total: u64, -} -impl NetworkAction { - pub fn new( - peer: AuthorityDiscoveryId, - run: ActionFuture, - size: usize, - latency: Option, - ) -> Self { - Self { run, size, peer, latency } - } - - pub fn size(&self) -> usize { - self.size - } - - pub async fn run(self) { - self.run.await; - } - - pub fn peer(&self) -> AuthorityDiscoveryId { - self.peer.clone() - } -} - -/// The state of a peer on the emulated network. -#[derive(Clone)] -enum Peer { - Connected(PeerEmulator), - Disconnected(PeerEmulator), -} - -impl Peer { - pub fn disconnect(&mut self) { - let new_self = match self { - Peer::Connected(peer) => Peer::Disconnected(peer.clone()), - _ => return, - }; - *self = new_self; - } - - pub fn is_connected(&self) -> bool { - matches!(self, Peer::Connected(_)) - } - - pub fn emulator(&mut self) -> &mut PeerEmulator { - match self { - Peer::Connected(ref mut emulator) => emulator, - Peer::Disconnected(ref mut emulator) => emulator, - } - } -} - -/// Mocks the network bridge and an arbitrary number of connected peer nodes. -/// Implements network latency, bandwidth and connection errors. -#[derive(Clone)] -pub struct NetworkEmulator { - // Per peer network emulation. - peers: Vec, - /// Per peer stats. - stats: Vec>, - /// Each emulated peer is a validator. - validator_authority_ids: HashMap, -} - -impl NetworkEmulator { - pub fn new( - config: &TestConfiguration, - dependencies: &TestEnvironmentDependencies, - authorities: &TestAuthorities, - ) -> Self { - let n_peers = config.n_validators; - gum::info!(target: LOG_TARGET, "{}",format!("Initializing emulation for a {} peer network.", n_peers).bright_blue()); - gum::info!(target: LOG_TARGET, "{}",format!("connectivity {}%, error {}%", config.connectivity, config.error).bright_black()); - - let metrics = - Metrics::new(&dependencies.registry).expect("Metrics always register succesfully"); - let mut validator_authority_id_mapping = HashMap::new(); - - // Create a `PeerEmulator` for each peer. - let (stats, mut peers): (_, Vec<_>) = (0..n_peers) - .zip(authorities.validator_authority_id.clone()) - .map(|(peer_index, authority_id)| { - validator_authority_id_mapping.insert(authority_id, peer_index); - let stats = Arc::new(PeerEmulatorStats::new(peer_index, metrics.clone())); - ( - stats.clone(), - Peer::Connected(PeerEmulator::new( - config.peer_bandwidth, - dependencies.task_manager.spawn_handle(), - stats, - )), - ) - }) - .unzip(); - - let connected_count = config.n_validators as f64 / (100.0 / config.connectivity as f64); - - let (_connected, to_disconnect) = - peers.partial_shuffle(&mut thread_rng(), connected_count as usize); - - for peer in to_disconnect { - peer.disconnect(); - } - - gum::info!(target: LOG_TARGET, "{}",format!("Network created, connected validator count {}", connected_count).bright_black()); - - Self { peers, stats, validator_authority_ids: validator_authority_id_mapping } - } - - pub fn is_peer_connected(&self, peer: &AuthorityDiscoveryId) -> bool { - self.peer(peer).is_connected() - } - - pub fn submit_peer_action(&mut self, peer: AuthorityDiscoveryId, action: NetworkAction) { - let index = self - .validator_authority_ids - .get(&peer) - .expect("all test authorities are valid; qed"); - - let peer = self.peers.get_mut(*index).expect("We just retrieved the index above; qed"); - - // Only actions of size 0 are allowed on disconnected peers. - // Typically this are delayed error response sends. - if action.size() > 0 && !peer.is_connected() { - gum::warn!(target: LOG_TARGET, peer_index = index, "Attempted to send data from a disconnected peer, operation ignored"); - return - } - - peer.emulator().send(action); - } - - // Returns the sent/received stats for `peer_index`. - pub fn peer_stats(&self, peer_index: usize) -> Arc { - self.stats[peer_index].clone() - } - - // Helper to get peer index by `AuthorityDiscoveryId` - fn peer_index(&self, peer: &AuthorityDiscoveryId) -> usize { - *self - .validator_authority_ids - .get(peer) - .expect("all test authorities are valid; qed") - } - - // Return the Peer entry for a given `AuthorityDiscoveryId`. - fn peer(&self, peer: &AuthorityDiscoveryId) -> &Peer { - &self.peers[self.peer_index(peer)] - } - // Returns the sent/received stats for `peer`. - pub fn peer_stats_by_id(&mut self, peer: &AuthorityDiscoveryId) -> Arc { - let peer_index = self.peer_index(peer); - - self.stats[peer_index].clone() - } - - // Returns the sent/received stats for all peers. - pub fn stats(&self) -> Vec { - let r = self - .stats - .iter() - .map(|stats| PeerStats { - rx_bytes_total: stats.received(), - tx_bytes_total: stats.sent(), - }) - .collect::>(); - r - } - - // Increment bytes sent by our node (the node that contains the subsystem under test) - pub fn inc_sent(&self, bytes: usize) { - // Our node always is peer 0. - self.peer_stats(0).inc_sent(bytes); - } - - // Increment bytes received by our node (the node that contains the subsystem under test) - pub fn inc_received(&self, bytes: usize) { - // Our node always is peer 0. - self.peer_stats(0).inc_received(bytes); - } -} - -use polkadot_node_subsystem_util::metrics::prometheus::{ - self, CounterVec, Opts, PrometheusError, Registry, -}; - -/// Emulated network metrics. -#[derive(Clone)] -pub(crate) struct Metrics { - /// Number of bytes sent per peer. - peer_total_sent: CounterVec, - /// Number of received sent per peer. - peer_total_received: CounterVec, -} - -impl Metrics { - pub fn new(registry: &Registry) -> Result { - Ok(Self { - peer_total_sent: prometheus::register( - CounterVec::new( - Opts::new( - "subsystem_benchmark_network_peer_total_bytes_sent", - "Total number of bytes a peer has sent.", - ), - &["peer"], - )?, - registry, - )?, - peer_total_received: prometheus::register( - CounterVec::new( - Opts::new( - "subsystem_benchmark_network_peer_total_bytes_received", - "Total number of bytes a peer has received.", - ), - &["peer"], - )?, - registry, - )?, - }) - } - - /// Increment total sent for a peer. - pub fn on_peer_sent(&self, peer_index: usize, bytes: usize) { - self.peer_total_sent - .with_label_values(vec![format!("node{}", peer_index).as_str()].as_slice()) - .inc_by(bytes as u64); - } - - /// Increment total receioved for a peer. - pub fn on_peer_received(&self, peer_index: usize, bytes: usize) { - self.peer_total_received - .with_label_values(vec![format!("node{}", peer_index).as_str()].as_slice()) - .inc_by(bytes as u64); - } -} diff --git a/polkadot/node/subsystem-bench/src/subsystem-bench.rs b/polkadot/node/subsystem-bench/src/subsystem-bench.rs deleted file mode 100644 index da7e5441f74..00000000000 --- a/polkadot/node/subsystem-bench/src/subsystem-bench.rs +++ /dev/null @@ -1,186 +0,0 @@ -// 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 . - -//! A tool for running subsystem benchmark tests designed for development and -//! CI regression testing. -use clap::Parser; -use color_eyre::eyre; - -use colored::Colorize; -use std::{path::Path, time::Duration}; - -pub(crate) mod availability; -pub(crate) mod cli; -pub(crate) mod core; - -use availability::{prepare_test, NetworkEmulation, TestState}; -use cli::TestObjective; - -use core::{ - configuration::TestConfiguration, - environment::{TestEnvironment, GENESIS_HASH}, -}; - -use clap_num::number_range; - -use crate::core::display::display_configuration; - -fn le_100(s: &str) -> Result { - number_range(s, 0, 100) -} - -fn le_5000(s: &str) -> Result { - number_range(s, 0, 5000) -} - -#[derive(Debug, Parser)] -#[allow(missing_docs)] -struct BenchCli { - #[arg(long, value_enum, ignore_case = true, default_value_t = NetworkEmulation::Ideal)] - /// The type of network to be emulated - pub network: NetworkEmulation, - - #[clap(flatten)] - pub standard_configuration: cli::StandardTestOptions, - - #[clap(short, long)] - /// The bandwidth of simulated remote peers in KiB - pub peer_bandwidth: Option, - - #[clap(short, long)] - /// The bandwidth of our simulated node in KiB - pub bandwidth: Option, - - #[clap(long, value_parser=le_100)] - /// Simulated conection error ratio [0-100]. - pub peer_error: Option, - - #[clap(long, value_parser=le_5000)] - /// Minimum remote peer latency in milliseconds [0-5000]. - pub peer_min_latency: Option, - - #[clap(long, value_parser=le_5000)] - /// Maximum remote peer latency in milliseconds [0-5000]. - pub peer_max_latency: Option, - - #[command(subcommand)] - pub objective: cli::TestObjective, -} - -impl BenchCli { - fn launch(self) -> eyre::Result<()> { - let configuration = self.standard_configuration; - let mut test_config = match self.objective { - TestObjective::TestSequence(options) => { - let test_sequence = - core::configuration::TestSequence::new_from_file(Path::new(&options.path)) - .expect("File exists") - .into_vec(); - let num_steps = test_sequence.len(); - gum::info!( - "{}", - format!("Sequence contains {} step(s)", num_steps).bright_purple() - ); - for (index, test_config) in test_sequence.into_iter().enumerate() { - gum::info!("{}", format!("Step {}/{}", index + 1, num_steps).bright_purple(),); - display_configuration(&test_config); - - let mut state = TestState::new(&test_config); - let (mut env, _protocol_config) = prepare_test(test_config, &mut state); - env.runtime() - .block_on(availability::benchmark_availability_read(&mut env, state)); - } - return Ok(()) - }, - TestObjective::DataAvailabilityRead(ref _options) => match self.network { - NetworkEmulation::Healthy => TestConfiguration::healthy_network( - self.objective, - configuration.num_blocks, - configuration.n_validators, - configuration.n_cores, - configuration.min_pov_size, - configuration.max_pov_size, - ), - NetworkEmulation::Degraded => TestConfiguration::degraded_network( - self.objective, - configuration.num_blocks, - configuration.n_validators, - configuration.n_cores, - configuration.min_pov_size, - configuration.max_pov_size, - ), - NetworkEmulation::Ideal => TestConfiguration::ideal_network( - self.objective, - configuration.num_blocks, - configuration.n_validators, - configuration.n_cores, - configuration.min_pov_size, - configuration.max_pov_size, - ), - }, - }; - - let mut latency_config = test_config.latency.clone().unwrap_or_default(); - - if let Some(latency) = self.peer_min_latency { - latency_config.min_latency = Duration::from_millis(latency); - } - - if let Some(latency) = self.peer_max_latency { - latency_config.max_latency = Duration::from_millis(latency); - } - - if let Some(error) = self.peer_error { - test_config.error = error; - } - - if let Some(bandwidth) = self.peer_bandwidth { - // CLI expects bw in KiB - test_config.peer_bandwidth = bandwidth * 1024; - } - - if let Some(bandwidth) = self.bandwidth { - // CLI expects bw in KiB - test_config.bandwidth = bandwidth * 1024; - } - - display_configuration(&test_config); - - let mut state = TestState::new(&test_config); - let (mut env, _protocol_config) = prepare_test(test_config, &mut state); - // test_config.write_to_disk(); - env.runtime() - .block_on(availability::benchmark_availability_read(&mut env, state)); - - Ok(()) - } -} - -fn main() -> eyre::Result<()> { - color_eyre::install()?; - env_logger::builder() - .filter(Some("hyper"), log::LevelFilter::Info) - // Avoid `Terminating due to subsystem exit subsystem` warnings - .filter(Some("polkadot_overseer"), log::LevelFilter::Error) - .filter(None, log::LevelFilter::Info) - // .filter(None, log::LevelFilter::Trace) - .try_init() - .unwrap(); - - let cli: BenchCli = BenchCli::parse(); - cli.launch()?; - Ok(()) -} diff --git a/polkadot/node/subsystem-test-helpers/Cargo.toml b/polkadot/node/subsystem-test-helpers/Cargo.toml index 7b616bdb438..9087ca11f5d 100644 --- a/polkadot/node/subsystem-test-helpers/Cargo.toml +++ b/polkadot/node/subsystem-test-helpers/Cargo.toml @@ -7,19 +7,13 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] async-trait = "0.1.57" futures = "0.3.21" parking_lot = "0.12.0" 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" } - sc-client-api = { path = "../../../substrate/client/api" } sc-utils = { path = "../../../substrate/client/utils" } sp-core = { path = "../../../substrate/primitives/core" } diff --git a/polkadot/node/subsystem-test-helpers/src/lib.rs b/polkadot/node/subsystem-test-helpers/src/lib.rs index dfa78e04b8c..3f92513498c 100644 --- a/polkadot/node/subsystem-test-helpers/src/lib.rs +++ b/polkadot/node/subsystem-test-helpers/src/lib.rs @@ -18,14 +18,11 @@ #![warn(missing_docs)] -use polkadot_erasure_coding::{branches, obtain_chunks_v1 as obtain_chunks}; -use polkadot_node_primitives::{AvailableData, ErasureChunk, Proof}; use polkadot_node_subsystem::{ messages::AllMessages, overseer, FromOrchestra, OverseerSignal, SpawnGlue, SpawnedSubsystem, SubsystemError, SubsystemResult, TrySendError, }; use polkadot_node_subsystem_util::TimeoutExt; -use polkadot_primitives::{Hash, ValidatorIndex}; use futures::{channel::mpsc, poll, prelude::*}; use parking_lot::Mutex; @@ -443,34 +440,6 @@ impl Future for Yield { } } -/// Helper for chunking available data. -pub fn derive_erasure_chunks_with_proofs_and_root( - n_validators: usize, - available_data: &AvailableData, - alter_chunk: impl Fn(usize, &mut Vec), -) -> (Vec, Hash) { - let mut chunks: Vec> = obtain_chunks(n_validators, available_data).unwrap(); - - for (i, chunk) in chunks.iter_mut().enumerate() { - alter_chunk(i, chunk) - } - - // create proofs for each erasure chunk - let branches = branches(chunks.as_ref()); - - let root = branches.root(); - let erasure_chunks = branches - .enumerate() - .map(|(index, (proof, chunk))| ErasureChunk { - chunk: chunk.to_vec(), - index: ValidatorIndex(index as _), - proof: Proof::try_from(proof).unwrap(), - }) - .collect::>(); - - (erasure_chunks, root) -} - #[cfg(test)] mod tests { use super::*; diff --git a/polkadot/node/subsystem-test-helpers/src/mock.rs b/polkadot/node/subsystem-test-helpers/src/mock.rs index 14026960ac1..522bc3c2cc4 100644 --- a/polkadot/node/subsystem-test-helpers/src/mock.rs +++ b/polkadot/node/subsystem-test-helpers/src/mock.rs @@ -16,7 +16,7 @@ use std::sync::Arc; -use polkadot_node_subsystem::{jaeger, ActivatedLeaf, BlockInfo}; +use polkadot_node_subsystem::{jaeger, ActivatedLeaf}; use sc_client_api::UnpinHandle; use sc_keystore::LocalKeystore; use sc_utils::mpsc::tracing_unbounded; @@ -59,8 +59,3 @@ pub fn new_leaf(hash: Hash, number: BlockNumber) -> ActivatedLeaf { span: Arc::new(jaeger::Span::Disabled), } } - -/// Create a new leaf with the given hash and number. -pub fn new_block_import_info(hash: Hash, number: BlockNumber) -> BlockInfo { - BlockInfo { hash, parent_hash: Hash::default(), number, unpin_handle: dummy_unpin_handle(hash) } -} diff --git a/polkadot/node/subsystem-types/Cargo.toml b/polkadot/node/subsystem-types/Cargo.toml index 5518e9d080c..71e5257cab9 100644 --- a/polkadot/node/subsystem-types/Cargo.toml +++ b/polkadot/node/subsystem-types/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] derive_more = "0.99.17" futures = "0.3.21" @@ -17,7 +14,7 @@ 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.3", default-features = false, features = ["futures_channel"] } +orchestra = { version = "0.3.3", default-features = false, features=["futures_channel"] } sc-network = { path = "../../../substrate/client/network" } sp-api = { path = "../../../substrate/primitives/api" } sp-blockchain = { path = "../../../substrate/primitives/blockchain" } diff --git a/polkadot/node/subsystem-types/src/messages.rs b/polkadot/node/subsystem-types/src/messages.rs index c7675c84b91..44c6f27b17c 100644 --- a/polkadot/node/subsystem-types/src/messages.rs +++ b/polkadot/node/subsystem-types/src/messages.rs @@ -33,8 +33,8 @@ use polkadot_node_network_protocol::{ }; use polkadot_node_primitives::{ approval::{ - v1::BlockApprovalMeta, - v2::{CandidateBitfield, IndirectAssignmentCertV2, IndirectSignedApprovalVoteV2}, + v1::{BlockApprovalMeta, IndirectSignedApprovalVote}, + v2::{CandidateBitfield, IndirectAssignmentCertV2}, }, AvailableData, BabeEpoch, BlockWeight, CandidateVotes, CollationGenerationConfig, CollationSecondedSignal, DisputeMessage, DisputeStatus, ErasureChunk, PoV, @@ -42,15 +42,14 @@ use polkadot_node_primitives::{ ValidationResult, }; use polkadot_primitives::{ - async_backing, slashing, - vstaging::{ApprovalVotingParams, NodeFeatures}, - AuthorityDiscoveryId, BackedCandidate, BlockNumber, CandidateEvent, CandidateHash, - CandidateIndex, CandidateReceipt, CollatorId, CommittedCandidateReceipt, CoreState, - DisputeState, ExecutorParams, GroupIndex, GroupRotationInfo, Hash, Header as BlockHeader, - Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, MultiDisputeStatementSet, - OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, PvfExecKind, SessionIndex, - SessionInfo, SignedAvailabilityBitfield, SignedAvailabilityBitfields, ValidationCode, - ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, + async_backing, slashing, vstaging::NodeFeatures, AuthorityDiscoveryId, BackedCandidate, + BlockNumber, CandidateEvent, CandidateHash, CandidateIndex, CandidateReceipt, CollatorId, + CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, GroupIndex, + GroupRotationInfo, Hash, Header as BlockHeader, Id as ParaId, InboundDownwardMessage, + InboundHrmpMessage, MultiDisputeStatementSet, OccupiedCoreAssumption, PersistedValidationData, + PvfCheckStatement, PvfExecKind, SessionIndex, SessionInfo, SignedAvailabilityBitfield, + SignedAvailabilityBitfields, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, + ValidatorSignature, }; use polkadot_statement_table::v2::Misbehavior; use std::{ @@ -721,9 +720,6 @@ pub enum RuntimeApiRequest { AsyncBackingParams(RuntimeApiSender), /// Get the node features. NodeFeatures(SessionIndex, RuntimeApiSender), - /// Approval voting params - /// `V10` - ApprovalVotingParams(SessionIndex, RuntimeApiSender), } impl RuntimeApiRequest { @@ -755,9 +751,6 @@ impl RuntimeApiRequest { /// `Node features` pub const NODE_FEATURES_RUNTIME_REQUIREMENT: u32 = 9; - - /// `approval_voting_params` - pub const APPROVAL_VOTING_PARAMS_REQUIREMENT: u32 = 10; } /// A message to the Runtime API subsystem. @@ -943,7 +936,7 @@ pub enum ApprovalVotingMessage { /// protocol. /// /// Should not be sent unless the block hash within the indirect vote is known. - CheckAndImportApproval(IndirectSignedApprovalVoteV2, oneshot::Sender), + CheckAndImportApproval(IndirectSignedApprovalVote, oneshot::Sender), /// Returns the highest possible ancestor hash of the provided block hash which is /// acceptable to vote on finality for. /// The `BlockNumber` provided is the number of the block's ancestor which is the @@ -959,7 +952,7 @@ pub enum ApprovalVotingMessage { /// requires calling into `approval-distribution`: Calls should be infrequent and bounded. GetApprovalSignaturesForCandidate( CandidateHash, - oneshot::Sender, ValidatorSignature)>>, + oneshot::Sender>, ), } @@ -975,7 +968,7 @@ pub enum ApprovalDistributionMessage { /// Distribute an approval vote for the local validator. The approval vote is assumed to be /// valid, relevant, and the corresponding approval already issued. /// If not, the subsystem is free to drop the message. - DistributeApproval(IndirectSignedApprovalVoteV2), + DistributeApproval(IndirectSignedApprovalVote), /// An update from the network bridge. #[from] NetworkBridgeUpdate(NetworkBridgeEvent), @@ -983,7 +976,7 @@ pub enum ApprovalDistributionMessage { /// Get all approval signatures for all chains a candidate appeared in. GetApprovalSignatures( HashSet<(Hash, CandidateIndex)>, - oneshot::Sender, ValidatorSignature)>>, + oneshot::Sender>, ), /// Approval checking lag update measured in blocks. ApprovalCheckingLagUpdate(BlockNumber), diff --git a/polkadot/node/subsystem-types/src/runtime_client.rs b/polkadot/node/subsystem-types/src/runtime_client.rs index 7f618307610..21df1483b9e 100644 --- a/polkadot/node/subsystem-types/src/runtime_client.rs +++ b/polkadot/node/subsystem-types/src/runtime_client.rs @@ -16,15 +16,12 @@ use async_trait::async_trait; use polkadot_primitives::{ - async_backing, - runtime_api::ParachainHost, - slashing, - vstaging::{self, ApprovalVotingParams}, - Block, BlockNumber, CandidateCommitments, CandidateEvent, CandidateHash, - CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, GroupRotationInfo, Hash, - Header, Id, InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, - PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, SessionIndex, SessionInfo, - ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, + async_backing, runtime_api::ParachainHost, slashing, vstaging, Block, BlockNumber, + CandidateCommitments, CandidateEvent, CandidateHash, CommittedCandidateReceipt, CoreState, + DisputeState, ExecutorParams, GroupRotationInfo, Hash, Header, Id, InboundDownwardMessage, + InboundHrmpMessage, OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, + ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidationCode, ValidationCodeHash, + ValidatorId, ValidatorIndex, ValidatorSignature, }; use sc_client_api::HeaderBackend; use sc_transaction_pool_api::OffchainTransactionPoolFactory; @@ -319,16 +316,9 @@ pub trait RuntimeApiSubsystemClient { async fn disabled_validators(&self, at: Hash) -> Result, ApiError>; // === v9 === + /// Get the node features. async fn node_features(&self, at: Hash) -> Result; - - // == v10: Approval voting params == - /// Approval voting configuration parameters - async fn approval_voting_params( - &self, - at: Hash, - session_index: SessionIndex, - ) -> Result; } /// Default implementation of [`RuntimeApiSubsystemClient`] using the client. @@ -585,13 +575,4 @@ where async fn disabled_validators(&self, at: Hash) -> Result, ApiError> { self.client.runtime_api().disabled_validators(at) } - - /// Approval voting configuration parameters - async fn approval_voting_params( - &self, - at: Hash, - _session_index: SessionIndex, - ) -> Result { - self.client.runtime_api().approval_voting_params(at) - } } diff --git a/polkadot/node/subsystem-util/Cargo.toml b/polkadot/node/subsystem-util/Cargo.toml index d6df3fbe3e2..d9364e2c2c0 100644 --- a/polkadot/node/subsystem-util/Cargo.toml +++ b/polkadot/node/subsystem-util/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] async-trait = "0.1.57" futures = "0.3.21" @@ -32,7 +29,7 @@ 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.5.1", default-features = false, features = ["futures_channel"] } +metered = { package = "prioritized-metered-channel", version = "0.5.1", default-features = false, features=["futures_channel"] } sp-core = { path = "../../../substrate/primitives/core" } sp-application-crypto = { path = "../../../substrate/primitives/application-crypto" } @@ -40,7 +37,7 @@ sp-keystore = { path = "../../../substrate/primitives/keystore" } sc-client-api = { path = "../../../substrate/client/api" } kvdb = "0.13.0" -parity-db = { version = "0.4.12" } +parity-db = { version = "0.4.8"} [dev-dependencies] assert_matches = "1.4.0" diff --git a/polkadot/node/subsystem-util/src/runtime/mod.rs b/polkadot/node/subsystem-util/src/runtime/mod.rs index 0e44423b4e3..aada7a5d77a 100644 --- a/polkadot/node/subsystem-util/src/runtime/mod.rs +++ b/polkadot/node/subsystem-util/src/runtime/mod.rs @@ -30,12 +30,10 @@ use polkadot_node_subsystem::{ }; use polkadot_node_subsystem_types::UnpinHandle; use polkadot_primitives::{ - slashing, - vstaging::{node_features::FeatureIndex, NodeFeatures}, - AsyncBackingParams, CandidateEvent, CandidateHash, CoreState, EncodeAs, ExecutorParams, - GroupIndex, GroupRotationInfo, Hash, IndexedVec, OccupiedCore, ScrapedOnChainVotes, - SessionIndex, SessionInfo, Signed, SigningContext, UncheckedSigned, ValidationCode, - ValidationCodeHash, ValidatorId, ValidatorIndex, LEGACY_MIN_BACKING_VOTES, + slashing, vstaging::NodeFeatures, AsyncBackingParams, CandidateEvent, CandidateHash, CoreState, + EncodeAs, ExecutorParams, GroupIndex, GroupRotationInfo, Hash, IndexedVec, OccupiedCore, + ScrapedOnChainVotes, SessionIndex, SessionInfo, Signed, SigningContext, UncheckedSigned, + ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, LEGACY_MIN_BACKING_VOTES, }; use crate::{ @@ -94,8 +92,6 @@ pub struct ExtendedSessionInfo { pub validator_info: ValidatorInfo, /// Session executor parameters pub executor_params: ExecutorParams, - /// Node features - pub node_features: NodeFeatures, } /// Information about ourselves, in case we are an `Authority`. @@ -206,20 +202,7 @@ impl RuntimeInfo { let validator_info = self.get_validator_info(&session_info)?; - let node_features = request_node_features(parent, session_index, sender) - .await? - .unwrap_or(NodeFeatures::EMPTY); - let last_set_index = node_features.iter_ones().last().unwrap_or_default(); - if last_set_index >= FeatureIndex::FirstUnassigned as usize { - gum::warn!(target: LOG_TARGET, "Runtime requires feature bit {} that node doesn't support, please upgrade node version", last_set_index); - } - - let full_info = ExtendedSessionInfo { - session_info, - validator_info, - executor_params, - node_features, - }; + let full_info = ExtendedSessionInfo { session_info, validator_info, executor_params }; self.session_info_cache.insert(session_index, full_info); } diff --git a/polkadot/node/subsystem/Cargo.toml b/polkadot/node/subsystem/Cargo.toml index b0b396d7f62..9b77359517c 100644 --- a/polkadot/node/subsystem/Cargo.toml +++ b/polkadot/node/subsystem/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] polkadot-overseer = { path = "../overseer" } polkadot-node-subsystem-types = { path = "../subsystem-types" } diff --git a/polkadot/node/test/client/Cargo.toml b/polkadot/node/test/client/Cargo.toml index 36748c3b455..bc4ff74be4b 100644 --- a/polkadot/node/test/client/Cargo.toml +++ b/polkadot/node/test/client/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive"] } @@ -41,7 +38,7 @@ sp-keyring = { path = "../../../../substrate/primitives/keyring" } futures = "0.3.21" [features] -runtime-benchmarks = [ +runtime-benchmarks= [ "frame-benchmarking/runtime-benchmarks", "polkadot-primitives/runtime-benchmarks", "polkadot-test-runtime/runtime-benchmarks", diff --git a/polkadot/node/test/service/Cargo.toml b/polkadot/node/test/service/Cargo.toml index 3199dc262bb..437fa66b75a 100644 --- a/polkadot/node/test/service/Cargo.toml +++ b/polkadot/node/test/service/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] futures = "0.3.21" hex = "0.4.3" @@ -66,8 +63,8 @@ substrate-test-utils = { path = "../../../../substrate/test-utils" } tokio = { version = "1.24.2", features = ["macros"] } [features] -runtime-metrics = ["polkadot-test-runtime/runtime-metrics"] -runtime-benchmarks = [ +runtime-metrics=[ "polkadot-test-runtime/runtime-metrics" ] +runtime-benchmarks= [ "frame-system/runtime-benchmarks", "pallet-balances/runtime-benchmarks", "pallet-staking/runtime-benchmarks", diff --git a/polkadot/node/test/service/src/lib.rs b/polkadot/node/test/service/src/lib.rs index 855b983e5f7..fda1f639bac 100644 --- a/polkadot/node/test/service/src/lib.rs +++ b/polkadot/node/test/service/src/lib.rs @@ -80,12 +80,11 @@ pub fn new_full( config, polkadot_service::NewFullParams { is_parachain_node, + grandpa_pause: None, enable_beefy: true, - force_authoring_backoff: false, jaeger_agent: None, telemetry_worker_handle: None, node_version: None, - secure_validator_mode: false, workers_path, workers_names: None, overseer_gen: polkadot_service::RealOverseerGen, diff --git a/polkadot/node/tracking-allocator/Cargo.toml b/polkadot/node/tracking-allocator/Cargo.toml index 486346e1fe1..b1b33091344 100644 --- a/polkadot/node/tracking-allocator/Cargo.toml +++ b/polkadot/node/tracking-allocator/Cargo.toml @@ -5,6 +5,3 @@ version = "1.0.0" authors.workspace = true edition.workspace = true license.workspace = true - -[lints] -workspace = true diff --git a/polkadot/node/zombienet-backchannel/Cargo.toml b/polkadot/node/zombienet-backchannel/Cargo.toml index e81ab2db14b..c1b08b4a2bb 100644 --- a/polkadot/node/zombienet-backchannel/Cargo.toml +++ b/polkadot/node/zombienet-backchannel/Cargo.toml @@ -8,9 +8,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] tokio = { version = "1.24.2", default-features = false, features = ["macros", "net", "rt-multi-thread", "sync"] } url = "2.3.1" diff --git a/polkadot/parachain/Cargo.toml b/polkadot/parachain/Cargo.toml index 0521af3bf2d..27aa117a87f 100644 --- a/polkadot/parachain/Cargo.toml +++ b/polkadot/parachain/Cargo.toml @@ -6,14 +6,11 @@ edition.workspace = true license.workspace = true version = "1.0.0" -[lints] -workspace = true - [dependencies] # 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. -parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive"] } +parity-scale-codec = { version = "3.6.1", default-features = false, features = [ "derive" ] } scale-info = { version = "2.10.0", 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"] } @@ -24,10 +21,10 @@ derive_more = "0.99.11" bounded-collections = { version = "0.1.8", default-features = false, features = ["serde"] } # all optional crates. -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"] } +serde = { version = "1.0.188", default-features = false, features = ["derive", "alloc"] } [features] -default = ["std"] +default = [ "std" ] wasm-api = [] std = [ "bounded-collections/std", @@ -40,4 +37,4 @@ std = [ "sp-std/std", "sp-weights/std", ] -runtime-benchmarks = ["sp-runtime/runtime-benchmarks"] +runtime-benchmarks = [ "sp-runtime/runtime-benchmarks" ] diff --git a/polkadot/parachain/src/lib.rs b/polkadot/parachain/src/lib.rs index bd75296bf83..913d887e4a8 100644 --- a/polkadot/parachain/src/lib.rs +++ b/polkadot/parachain/src/lib.rs @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . +#![warn(unused_crate_dependencies)] + //! Defines primitive types for creating or validating a parachain. //! //! When compiled with standard library support, this crate exports a `wasm` diff --git a/polkadot/parachain/test-parachains/Cargo.toml b/polkadot/parachain/test-parachains/Cargo.toml index 6acdedf67ff..3252d1f83cd 100644 --- a/polkadot/parachain/test-parachains/Cargo.toml +++ b/polkadot/parachain/test-parachains/Cargo.toml @@ -7,9 +7,6 @@ edition.workspace = true license.workspace = true publish = false -[lints] -workspace = true - [dependencies] tiny-keccak = { version = "2.0.2", features = ["keccak"] } parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive"] } @@ -21,5 +18,5 @@ halt = { package = "test-parachain-halt", path = "halt" } sp-core = { path = "../../../substrate/primitives/core" } [features] -default = ["std"] -std = ["adder/std", "halt/std", "parity-scale-codec/std"] +default = [ "std" ] +std = [ "adder/std", "halt/std", "parity-scale-codec/std" ] diff --git a/polkadot/parachain/test-parachains/adder/Cargo.toml b/polkadot/parachain/test-parachains/adder/Cargo.toml index eec19ef788a..1a47328b28e 100644 --- a/polkadot/parachain/test-parachains/adder/Cargo.toml +++ b/polkadot/parachain/test-parachains/adder/Cargo.toml @@ -8,22 +8,19 @@ version = "1.0.0" authors.workspace = true publish = false -[lints] -workspace = true - [dependencies] -parachain = { package = "polkadot-parachain-primitives", path = "../..", default-features = false, features = ["wasm-api"] } +parachain = { package = "polkadot-parachain-primitives", path = "../..", default-features = false, features = [ "wasm-api" ] } parity-scale-codec = { version = "3.6.1", 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"] } +dlmalloc = { version = "0.2.4", features = [ "global" ] } # 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 = { path = "../../../../substrate/primitives/io", default-features = false, features = [ "disable_allocator" ] } [build-dependencies] substrate-wasm-builder = { path = "../../../../substrate/utils/wasm-builder" } [features] -default = ["std"] -std = ["parachain/std", "parity-scale-codec/std", "sp-io/std", "sp-std/std"] +default = [ "std" ] +std = [ "parachain/std", "parity-scale-codec/std", "sp-io/std", "sp-std/std" ] diff --git a/polkadot/parachain/test-parachains/adder/collator/Cargo.toml b/polkadot/parachain/test-parachains/adder/collator/Cargo.toml index b8f0c579b8b..70f2ae769a8 100644 --- a/polkadot/parachain/test-parachains/adder/collator/Cargo.toml +++ b/polkadot/parachain/test-parachains/adder/collator/Cargo.toml @@ -7,16 +7,13 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [[bin]] name = "adder-collator" path = "src/main.rs" [dependencies] parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive"] } -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } futures = "0.3.21" futures-timer = "3.0.2" log = "0.4.17" diff --git a/polkadot/parachain/test-parachains/adder/collator/src/cli.rs b/polkadot/parachain/test-parachains/adder/collator/src/cli.rs index f81e4cc0fff..14b25970683 100644 --- a/polkadot/parachain/test-parachains/adder/collator/src/cli.rs +++ b/polkadot/parachain/test-parachains/adder/collator/src/cli.rs @@ -24,16 +24,16 @@ use sc_cli::SubstrateCli; pub enum Subcommand { /// Export the genesis state of the parachain. #[command(name = "export-genesis-state")] - ExportGenesisState(ExportGenesisHeadCommand), + ExportGenesisState(ExportGenesisStateCommand), /// Export the genesis wasm of the parachain. #[command(name = "export-genesis-wasm")] ExportGenesisWasm(ExportGenesisWasmCommand), } -/// Command for exporting the genesis head data of the parachain +/// Command for exporting the genesis state of the parachain #[derive(Debug, Parser)] -pub struct ExportGenesisHeadCommand {} +pub struct ExportGenesisStateCommand {} /// Command for exporting the genesis wasm file. #[derive(Debug, Parser)] diff --git a/polkadot/parachain/test-parachains/adder/collator/src/main.rs b/polkadot/parachain/test-parachains/adder/collator/src/main.rs index 6ce93ef4ad1..dfaa1973206 100644 --- a/polkadot/parachain/test-parachains/adder/collator/src/main.rs +++ b/polkadot/parachain/test-parachains/adder/collator/src/main.rs @@ -62,14 +62,13 @@ fn main() -> Result<()> { is_parachain_node: polkadot_service::IsParachainNode::Collator( collator.collator_key(), ), + grandpa_pause: None, enable_beefy: false, - force_authoring_backoff: false, jaeger_agent: None, telemetry_worker_handle: None, // Collators don't spawn PVF workers, so we can disable version checks. node_version: None, - secure_validator_mode: false, workers_path: None, workers_names: None, diff --git a/polkadot/parachain/test-parachains/halt/Cargo.toml b/polkadot/parachain/test-parachains/halt/Cargo.toml index 1bdd4392ad3..cb2918273eb 100644 --- a/polkadot/parachain/test-parachains/halt/Cargo.toml +++ b/polkadot/parachain/test-parachains/halt/Cargo.toml @@ -8,9 +8,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] [build-dependencies] @@ -18,5 +15,5 @@ substrate-wasm-builder = { path = "../../../../substrate/utils/wasm-builder" } rustversion = "1.0.6" [features] -default = ["std"] +default = [ "std" ] std = [] diff --git a/polkadot/parachain/test-parachains/undying/Cargo.toml b/polkadot/parachain/test-parachains/undying/Cargo.toml index 19e1261db1e..273eef4b63a 100644 --- a/polkadot/parachain/test-parachains/undying/Cargo.toml +++ b/polkadot/parachain/test-parachains/undying/Cargo.toml @@ -8,25 +8,22 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] -parachain = { package = "polkadot-parachain-primitives", path = "../..", default-features = false, features = ["wasm-api"] } +parachain = { package = "polkadot-parachain-primitives", path = "../..", default-features = false, features = [ "wasm-api" ] } parity-scale-codec = { version = "3.6.1", 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"] } +dlmalloc = { version = "0.2.4", features = [ "global" ] } log = { version = "0.4.17", default-features = false } # 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 = { path = "../../../../substrate/primitives/io", default-features = false, features = [ "disable_allocator" ] } [build-dependencies] substrate-wasm-builder = { path = "../../../../substrate/utils/wasm-builder" } [features] -default = ["std"] +default = [ "std" ] std = [ "log/std", "parachain/std", diff --git a/polkadot/parachain/test-parachains/undying/collator/Cargo.toml b/polkadot/parachain/test-parachains/undying/collator/Cargo.toml index 4ef24ca83dc..578c3d6715d 100644 --- a/polkadot/parachain/test-parachains/undying/collator/Cargo.toml +++ b/polkadot/parachain/test-parachains/undying/collator/Cargo.toml @@ -7,16 +7,13 @@ version = "1.0.0" authors.workspace = true publish = false -[lints] -workspace = true - [[bin]] name = "undying-collator" path = "src/main.rs" [dependencies] parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive"] } -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } futures = "0.3.21" futures-timer = "3.0.2" log = "0.4.17" @@ -42,3 +39,6 @@ sc-service = { path = "../../../../../substrate/client/service" } sp-keyring = { path = "../../../../../substrate/primitives/keyring" } tokio = { version = "1.24.2", features = ["macros"] } + +[features] +network-protocol-staging = [ "polkadot-cli/network-protocol-staging" ] diff --git a/polkadot/parachain/test-parachains/undying/collator/src/cli.rs b/polkadot/parachain/test-parachains/undying/collator/src/cli.rs index 9572887a51a..d04122f2f68 100644 --- a/polkadot/parachain/test-parachains/undying/collator/src/cli.rs +++ b/polkadot/parachain/test-parachains/undying/collator/src/cli.rs @@ -25,16 +25,16 @@ use std::path::PathBuf; pub enum Subcommand { /// Export the genesis state of the parachain. #[command(name = "export-genesis-state")] - ExportGenesisState(ExportGenesisHeadCommand), + ExportGenesisState(ExportGenesisStateCommand), /// Export the genesis wasm of the parachain. #[command(name = "export-genesis-wasm")] ExportGenesisWasm(ExportGenesisWasmCommand), } -/// Command for exporting the genesis head data of the parachain +/// Command for exporting the genesis state of the parachain #[derive(Debug, Parser)] -pub struct ExportGenesisHeadCommand { +pub struct ExportGenesisStateCommand { /// Output file name or stdout if unspecified. #[arg()] pub output: Option, diff --git a/polkadot/parachain/test-parachains/undying/collator/src/main.rs b/polkadot/parachain/test-parachains/undying/collator/src/main.rs index 4a15cdd697c..c6b338a20dc 100644 --- a/polkadot/parachain/test-parachains/undying/collator/src/main.rs +++ b/polkadot/parachain/test-parachains/undying/collator/src/main.rs @@ -82,14 +82,13 @@ fn main() -> Result<()> { is_parachain_node: polkadot_service::IsParachainNode::Collator( collator.collator_key(), ), + grandpa_pause: None, enable_beefy: false, - force_authoring_backoff: false, jaeger_agent: None, telemetry_worker_handle: None, // Collators don't spawn PVF workers, so we can disable version checks. node_version: None, - secure_validator_mode: false, workers_path: None, workers_names: None, diff --git a/polkadot/primitives/Cargo.toml b/polkadot/primitives/Cargo.toml index de6df85051a..316644a372d 100644 --- a/polkadot/primitives/Cargo.toml +++ b/polkadot/primitives/Cargo.toml @@ -6,15 +6,12 @@ edition.workspace = true license.workspace = true description = "Shared primitives used by Polkadot runtime" -[lints] -workspace = true - [dependencies] bitvec = { version = "1.0.0", default-features = false, features = ["alloc", "serde"] } hex-literal = "0.4.1" parity-scale-codec = { version = "3.6.1", default-features = false, features = ["bit-vec", "derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["bit-vec", "derive", "serde"] } -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"] } +serde = { version = "1.0.188", default-features = false, features = ["derive", "alloc"] } application-crypto = { package = "sp-application-crypto", path = "../../substrate/primitives/application-crypto", default-features = false, features = ["serde"] } inherents = { package = "sp-inherents", path = "../../substrate/primitives/inherents", default-features = false } @@ -33,7 +30,7 @@ polkadot-core-primitives = { path = "../core-primitives", default-features = fal polkadot-parachain-primitives = { path = "../parachain", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "application-crypto/std", "bitvec/std", diff --git a/polkadot/primitives/src/runtime_api.rs b/polkadot/primitives/src/runtime_api.rs index d661005e32f..e4c1d590f45 100644 --- a/polkadot/primitives/src/runtime_api.rs +++ b/polkadot/primitives/src/runtime_api.rs @@ -114,14 +114,13 @@ //! separated from the stable primitives. use crate::{ - async_backing, slashing, - vstaging::{self, ApprovalVotingParams}, - AsyncBackingParams, BlockNumber, CandidateCommitments, CandidateEvent, CandidateHash, - CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, GroupRotationInfo, Hash, - OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, - SessionIndex, SessionInfo, ValidatorId, ValidatorIndex, ValidatorSignature, + async_backing, slashing, vstaging, AsyncBackingParams, BlockNumber, CandidateCommitments, + CandidateEvent, CandidateHash, CommittedCandidateReceipt, CoreState, DisputeState, + ExecutorParams, GroupRotationInfo, OccupiedCoreAssumption, PersistedValidationData, + PvfCheckStatement, ScrapedOnChainVotes, SessionIndex, SessionInfo, ValidatorId, ValidatorIndex, + ValidatorSignature, }; - +use parity_scale_codec::{Decode, Encode}; use polkadot_core_primitives as pcp; use polkadot_parachain_primitives::primitives as ppp; use sp_std::{collections::btree_map::BTreeMap, prelude::*}; @@ -129,18 +128,18 @@ use sp_std::{collections::btree_map::BTreeMap, prelude::*}; sp_api::decl_runtime_apis! { /// The API for querying the state of parachains on-chain. #[api_version(5)] - pub trait ParachainHost { + pub trait ParachainHost { /// Get the current validators. fn validators() -> Vec; /// Returns the validator groups and rotation info localized based on the hypothetical child /// of a block whose state this is invoked on. Note that `now` in the `GroupRotationInfo` /// should be the successor of the number of the block. - fn validator_groups() -> (Vec>, GroupRotationInfo); + fn validator_groups() -> (Vec>, GroupRotationInfo); /// Yields information on all availability cores as relevant to the child block. /// Cores are either free or occupied. Free cores can have paras assigned to them. - fn availability_cores() -> Vec>; + fn availability_cores() -> Vec>; /// Yields the persisted validation data for the given `ParaId` along with an assumption that /// should be used if the para currently occupies a core. @@ -148,15 +147,15 @@ sp_api::decl_runtime_apis! { /// Returns `None` if either the para is not registered or the assumption is `Freed` /// and the para already occupies a core. fn persisted_validation_data(para_id: ppp::Id, assumption: OccupiedCoreAssumption) - -> Option>; + -> Option>; /// Returns the persisted validation data for the given `ParaId` along with the corresponding /// validation code hash. Instead of accepting assumption about the para, matches the validation /// data hash against an expected one and yields `None` if they're not equal. fn assumed_validation_data( para_id: ppp::Id, - expected_persisted_validation_data_hash: Hash, - ) -> Option<(PersistedValidationData, ppp::ValidationCodeHash)>; + expected_persisted_validation_data_hash: pcp::v2::Hash, + ) -> Option<(PersistedValidationData, ppp::ValidationCodeHash)>; /// Checks if the given validation outputs pass the acceptance criteria. fn check_validation_outputs(para_id: ppp::Id, outputs: CandidateCommitments) -> bool; @@ -170,34 +169,30 @@ sp_api::decl_runtime_apis! { /// /// Returns `None` if either the para is not registered or the assumption is `Freed` /// and the para already occupies a core. - fn validation_code( - para_id: ppp::Id, - assumption: OccupiedCoreAssumption, - ) -> Option; + fn validation_code(para_id: ppp::Id, assumption: OccupiedCoreAssumption) + -> Option; /// Get the receipt of a candidate pending availability. This returns `Some` for any paras /// assigned to occupied cores in `availability_cores` and `None` otherwise. - fn candidate_pending_availability(para_id: ppp::Id) -> Option>; + fn candidate_pending_availability(para_id: ppp::Id) -> Option>; /// Get a vector of events concerning candidates that occurred within a block. - fn candidate_events() -> Vec>; + fn candidate_events() -> Vec>; /// Get all the pending inbound messages in the downward message queue for a para. fn dmq_contents( recipient: ppp::Id, - ) -> Vec>; + ) -> Vec>; /// Get the contents of all channels addressed to the given recipient. Channels that have no /// messages in them are also included. - fn inbound_hrmp_channels_contents( - recipient: ppp::Id, - ) -> BTreeMap>>; + fn inbound_hrmp_channels_contents(recipient: ppp::Id) -> BTreeMap>>; /// Get the validation code from its hash. fn validation_code_by_hash(hash: ppp::ValidationCodeHash) -> Option; /// Scrape dispute relevant from on-chain, backing votes and resolved disputes. - fn on_chain_votes() -> Option>; + fn on_chain_votes() -> Option>; /***** Added in v2 *****/ @@ -258,7 +253,7 @@ sp_api::decl_runtime_apis! { /// Returns the state of parachain backing for a given para. #[api_version(7)] - fn para_backing_state(_: ppp::Id) -> Option>; + fn para_backing_state(_: ppp::Id) -> Option>; /// Returns candidate's acceptance limitations for asynchronous backing for a relay parent. #[api_version(7)] @@ -276,10 +271,5 @@ sp_api::decl_runtime_apis! { /// This is a staging method! Do not use on production runtimes! #[api_version(9)] fn node_features() -> vstaging::NodeFeatures; - - /***** Added in v10 *****/ - /// Approval voting configuration parameters - #[api_version(10)] - fn approval_voting_params() -> ApprovalVotingParams; } } diff --git a/polkadot/primitives/src/v6/mod.rs b/polkadot/primitives/src/v6/mod.rs index c3a947644ff..83b590dc320 100644 --- a/polkadot/primitives/src/v6/mod.rs +++ b/polkadot/primitives/src/v6/mod.rs @@ -1070,26 +1070,6 @@ impl ApprovalVote { } } -/// A vote of approval for multiple candidates. -#[derive(Clone, RuntimeDebug)] -pub struct ApprovalVoteMultipleCandidates<'a>(pub &'a [CandidateHash]); - -impl<'a> ApprovalVoteMultipleCandidates<'a> { - /// Yields the signing payload for this approval vote. - pub fn signing_payload(&self, session_index: SessionIndex) -> Vec { - const MAGIC: [u8; 4] = *b"APPR"; - // Make this backwards compatible with `ApprovalVote` so if we have just on candidate the - // signature will look the same. - // This gives us the nice benefit that old nodes can still check signatures when len is 1 - // and the new node can check the signature coming from old nodes. - if self.0.len() == 1 { - (MAGIC, self.0.first().expect("QED: we just checked"), session_index).encode() - } else { - (MAGIC, &self.0, session_index).encode() - } - } -} - /// Custom validity errors used in Polkadot while validating transactions. #[repr(u8)] pub enum ValidityError { @@ -1266,42 +1246,25 @@ pub enum DisputeStatement { impl DisputeStatement { /// Get the payload data for this type of dispute statement. - /// - /// Returns Error if the candidate_hash is not included in the list of signed - /// candidate from ApprovalCheckingMultipleCandidate. - pub fn payload_data( - &self, - candidate_hash: CandidateHash, - session: SessionIndex, - ) -> Result, ()> { - match self { + pub fn payload_data(&self, candidate_hash: CandidateHash, session: SessionIndex) -> Vec { + match *self { DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) => - Ok(ExplicitDisputeStatement { valid: true, candidate_hash, session } - .signing_payload()), + ExplicitDisputeStatement { valid: true, candidate_hash, session }.signing_payload(), DisputeStatement::Valid(ValidDisputeStatementKind::BackingSeconded( inclusion_parent, - )) => Ok(CompactStatement::Seconded(candidate_hash).signing_payload(&SigningContext { + )) => CompactStatement::Seconded(candidate_hash).signing_payload(&SigningContext { session_index: session, - parent_hash: *inclusion_parent, - })), + parent_hash: inclusion_parent, + }), DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(inclusion_parent)) => - Ok(CompactStatement::Valid(candidate_hash).signing_payload(&SigningContext { + CompactStatement::Valid(candidate_hash).signing_payload(&SigningContext { session_index: session, - parent_hash: *inclusion_parent, - })), + parent_hash: inclusion_parent, + }), DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) => - Ok(ApprovalVote(candidate_hash).signing_payload(session)), - DisputeStatement::Valid( - ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(candidate_hashes), - ) => - if candidate_hashes.contains(&candidate_hash) { - Ok(ApprovalVoteMultipleCandidates(candidate_hashes).signing_payload(session)) - } else { - Err(()) - }, + ApprovalVote(candidate_hash).signing_payload(session), DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) => - Ok(ExplicitDisputeStatement { valid: false, candidate_hash, session } - .signing_payload()), + ExplicitDisputeStatement { valid: false, candidate_hash, session }.signing_payload(), } } @@ -1313,7 +1276,7 @@ impl DisputeStatement { session: SessionIndex, validator_signature: &ValidatorSignature, ) -> Result<(), ()> { - let payload = self.payload_data(candidate_hash, session)?; + let payload = self.payload_data(candidate_hash, session); if validator_signature.verify(&payload[..], &validator_public) { Ok(()) @@ -1345,14 +1308,13 @@ impl DisputeStatement { Self::Valid(ValidDisputeStatementKind::BackingValid(_)) => true, Self::Valid(ValidDisputeStatementKind::Explicit) | Self::Valid(ValidDisputeStatementKind::ApprovalChecking) | - Self::Valid(ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates(_)) | Self::Invalid(_) => false, } } } /// Different kinds of statements of validity on a candidate. -#[derive(Encode, Decode, Clone, PartialEq, RuntimeDebug, TypeInfo)] +#[derive(Encode, Decode, Copy, Clone, PartialEq, RuntimeDebug, TypeInfo)] pub enum ValidDisputeStatementKind { /// An explicit statement issued as part of a dispute. #[codec(index = 0)] @@ -1366,12 +1328,6 @@ pub enum ValidDisputeStatementKind { /// An approval vote from the approval checking phase. #[codec(index = 3)] ApprovalChecking, - /// An approval vote from the new version. - /// We can't create this version untill all nodes - /// have been updated to support it and max_approval_coalesce_count - /// is set to more than 1. - #[codec(index = 4)] - ApprovalCheckingMultipleCandidates(Vec), } /// Different kinds of statements of invalidity on a candidate. diff --git a/polkadot/primitives/src/vstaging/mod.rs b/polkadot/primitives/src/vstaging/mod.rs index 630bcf8679a..083e0f42d56 100644 --- a/polkadot/primitives/src/vstaging/mod.rs +++ b/polkadot/primitives/src/vstaging/mod.rs @@ -17,56 +17,8 @@ //! Staging Primitives. // Put any primitives used by staging APIs functions here -pub use crate::v6::*; -use sp_std::prelude::*; - -use parity_scale_codec::{Decode, Encode}; -use primitives::RuntimeDebug; -use scale_info::TypeInfo; - -/// Approval voting configuration parameters -#[derive( - RuntimeDebug, - Copy, - Clone, - PartialEq, - Encode, - Decode, - TypeInfo, - serde::Serialize, - serde::Deserialize, -)] -pub struct ApprovalVotingParams { - /// The maximum number of candidates `approval-voting` can vote for with - /// a single signatures. - /// - /// Setting it to 1, means we send the approval as soon as we have it available. - pub max_approval_coalesce_count: u32, -} - -impl Default for ApprovalVotingParams { - fn default() -> Self { - Self { max_approval_coalesce_count: 1 } - } -} use bitvec::vec::BitVec; /// Bit indices in the `HostConfiguration.node_features` that correspond to different node features. pub type NodeFeatures = BitVec; - -/// Module containing feature-specific bit indices into the `NodeFeatures` bitvec. -pub mod node_features { - /// A feature index used to indentify a bit into the node_features array stored - /// in the HostConfiguration. - #[repr(u8)] - pub enum FeatureIndex { - /// Tells if tranch0 assignments could be sent in a single certificate. - /// Reserved for: `` - EnableAssignmentsV2 = 0, - /// First unassigned feature bit. - /// Every time a new feature flag is assigned it should take this value. - /// and this should be incremented. - FirstUnassigned = 1, - } -} diff --git a/polkadot/primitives/test-helpers/Cargo.toml b/polkadot/primitives/test-helpers/Cargo.toml index fab9480cfde..8215b842ba4 100644 --- a/polkadot/primitives/test-helpers/Cargo.toml +++ b/polkadot/primitives/test-helpers/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] sp-keyring = { path = "../../../substrate/primitives/keyring" } sp-application-crypto = { package = "sp-application-crypto", path = "../../../substrate/primitives/application-crypto", default-features = false } diff --git a/polkadot/roadmap/implementers-guide/README.md b/polkadot/roadmap/implementers-guide/README.md index abff017138c..e03c0c45ddb 100644 --- a/polkadot/roadmap/implementers-guide/README.md +++ b/polkadot/roadmap/implementers-guide/README.md @@ -8,7 +8,7 @@ This is available [here](https://paritytech.github.io/polkadot-sdk/book/). ## Local build -To view it locally, run the following (from the `polkadot/` directory): +To view it locally from the repo root: Ensure graphviz is installed: diff --git a/polkadot/roadmap/implementers-guide/book.toml b/polkadot/roadmap/implementers-guide/book.toml index f91591ff170..f677c0d59c0 100644 --- a/polkadot/roadmap/implementers-guide/book.toml +++ b/polkadot/roadmap/implementers-guide/book.toml @@ -15,7 +15,7 @@ renderer = ["html"] [output.html] additional-css = ["last-changed.css"] -additional-js = ["mermaid-init.js", "mermaid.min.js"] +additional-js = ["mermaid.min.js", "mermaid-init.js"] # Repository URL used in the last-changed link. git-repository-url = "https://github.com/paritytech/polkadot-sdk" diff --git a/polkadot/roadmap/implementers-guide/src/glossary.md b/polkadot/roadmap/implementers-guide/src/glossary.md index ac2392b14d2..b2365ba51c5 100644 --- a/polkadot/roadmap/implementers-guide/src/glossary.md +++ b/polkadot/roadmap/implementers-guide/src/glossary.md @@ -48,13 +48,10 @@ has exactly one downward message queue. - **Proof-of-Validity (PoV):** A stateless-client proof that a parachain candidate is valid, with respect to some validation function. - **PVF:** Parachain Validation Function. The validation code that is run by validators on parachains. -- **PVF Prechecking:** This is the process of checking a PVF when it appears - on-chain, either when the parachain is onboarded or when it signalled an - upgrade of its validation code. We attempt preparation of the PVF and make - sure it that succeeds within a given timeout, plus some additional checks. +- **PVF Prechecking:** This is the process of initially checking the PVF when it is first added. We attempt preparation + of the PVF and make sure it succeeds within a given timeout, plus some additional checks. - **PVF Preparation:** This is the process of preparing the WASM blob and includes both prevalidation and compilation. -- **PVF Prevalidation:** Some basic checks for correctness of the PVF blob. The - first step of PVF preparation, before compilation. + As there is no prevalidation right now, preparation just consists of compilation. - **Relay Parent:** A block in the relay chain, referred to in a context where work is being done in the context of the state at this block. - **Runtime:** The relay-chain state machine. diff --git a/polkadot/roadmap/implementers-guide/src/node/approval/approval-voting.md b/polkadot/roadmap/implementers-guide/src/node/approval/approval-voting.md index 345b3d2e697..1a17f90d9ba 100644 --- a/polkadot/roadmap/implementers-guide/src/node/approval/approval-voting.md +++ b/polkadot/roadmap/implementers-guide/src/node/approval/approval-voting.md @@ -4,13 +4,10 @@ Reading the [section on the approval protocol](../../protocol-approval.md) will aims of this subsystem. Approval votes are split into two parts: Assignments and Approvals. Validators first broadcast their assignment to -indicate intent to check a candidate. Upon successfully checking, they don't immediately send the vote instead -they queue the check for a short period of time `MAX_APPROVAL_COALESCE_WAIT_TICKS` to give the opportunity of the -validator to vote for more than one candidate. Once MAX_APPROVAL_COALESCE_WAIT_TICKS have passed or at least -`MAX_APPROVAL_COALESCE_COUNT` are ready they broadcast an approval vote for all candidates. If a validator -doesn't broadcast their approval vote shortly after issuing an assignment, this is an indication that they are -being prevented from recovering or validating the block data and that more validators should self-select to -check the candidate. This is known as a "no-show". +indicate intent to check a candidate. Upon successfully checking, they broadcast an approval vote. If a validator +doesn't broadcast their approval vote shortly after issuing an assignment, this is an indication that they are being +prevented from recovering or validating the block data and that more validators should self-select to check the +candidate. This is known as a "no-show". The core of this subsystem is a Tick-based timer loop, where Ticks are 500ms. We also reason about time in terms of `DelayTranche`s, which measure the number of ticks elapsed since a block was produced. We track metadata for all @@ -123,13 +120,6 @@ struct BlockEntry { // this block. The block can be considered approved has all bits set to 1 approved_bitfield: Bitfield, children: Vec, - // A list of candidates we have checked, but didn't not sign and - // advertise the vote yet. - candidates_pending_signature: BTreeMap, - // Assignments we already distributed. A 1 bit means the candidate index for which - // we already have sent out an assignment. We need this to avoid distributing - // multiple core assignments more than once. - distributed_assignments: Bitfield, } // slot_duration * 2 + DelayTranche gives the number of delay tranches since the @@ -313,12 +303,12 @@ entry. The cert itself contains information necessary to determine the candidate On receiving a `CheckAndImportApproval(indirect_approval_vote, response_channel)` message: * Fetch the `BlockEntry` from the indirect approval vote's `block_hash`. If none, return `ApprovalCheckResult::Bad`. - * Fetch all `CandidateEntry` from the indirect approval vote's `candidate_indices`. If the block did not trigger + * Fetch the `CandidateEntry` from the indirect approval vote's `candidate_index`. If the block did not trigger inclusion of enough candidates, return `ApprovalCheckResult::Bad`. - * Construct a `SignedApprovalVote` using the candidates hashes and check against the validator's approval key, - based on the session info of the block. If invalid or no such validator, return `ApprovalCheckResult::Bad`. + * Construct a `SignedApprovalVote` using the candidate hash and check against the validator's approval key, based on + the session info of the block. If invalid or no such validator, return `ApprovalCheckResult::Bad`. * Send `ApprovalCheckResult::Accepted` - * [Import the checked approval vote](#import-checked-approval) for all candidates + * [Import the checked approval vote](#import-checked-approval) #### `ApprovalVotingMessage::ApprovedAncestor` @@ -412,25 +402,10 @@ On receiving an `ApprovedAncestor(Hash, BlockNumber, response_channel)`: #### Issue Approval Vote * Fetch the block entry and candidate entry. Ignore if `None` - we've probably just lost a race with finality. + * Construct a `SignedApprovalVote` with the validator index for the session. * [Import the checked approval vote](#import-checked-approval). It is "checked" as we've just issued the signature. - * IF `MAX_APPROVAL_COALESCE_COUNT` candidates are in the waiting queue - * Construct a `SignedApprovalVote` with the validator index for the session and all candidate hashes in the waiting queue. - * Construct a `IndirectSignedApprovalVote` using the information about the vote. - * Dispatch `ApprovalDistributionMessage::DistributeApproval`. - * ELSE - * Queue the candidate in the `BlockEntry::candidates_pending_signature` - * Arm a per BlockEntry timer with latest tick we can send the vote. - -### Delayed vote distribution - * [Issue Approval Vote](#issue-approval-vote) arms once a per block timer if there are no requirements to send the - vote immediately. - * When the timer wakes up it will either: - * IF there is a candidate in the queue past its sending tick: - * Construct a `SignedApprovalVote` with the validator index for the session and all candidate hashes in the waiting queue. - * Construct a `IndirectSignedApprovalVote` using the information about the vote. - * Dispatch `ApprovalDistributionMessage::DistributeApproval`. - * ELSE - * Re-arm the timer with latest tick we have the send a the vote. + * Construct a `IndirectSignedApprovalVote` using the information about the vote. + * Dispatch `ApprovalDistributionMessage::DistributeApproval`. ### Determining Approval of Candidate diff --git a/polkadot/roadmap/implementers-guide/src/node/utility/candidate-validation.md b/polkadot/roadmap/implementers-guide/src/node/utility/candidate-validation.md index 1a3ff1c6aff..e252ec237b7 100644 --- a/polkadot/roadmap/implementers-guide/src/node/utility/candidate-validation.md +++ b/polkadot/roadmap/implementers-guide/src/node/utility/candidate-validation.md @@ -5,31 +5,6 @@ This subsystem is responsible for handling candidate validation requests. It is A variety of subsystems want to know if a parachain block candidate is valid. None of them care about the detailed mechanics of how a candidate gets validated, just the results. This subsystem handles those details. -## High-Level Flow - -```dot process -digraph { - rankdir="LR"; - - pre [label = "Pvf-Checker"; shape = square] - bac [label = "Backing"; shape = square] - app [label = "Approval\nVoting"; shape = square] - dis [label = "Dispute\nCoordinator"; shape = square] - - can [label = "Candidate\nValidation"; shape = square] - - pvf [label = "PVF Host"; shape = square] - - pre -> can [style = dashed] - bac -> can - app -> can - dis -> can - - can -> pvf [label = "Precheck"; style = dashed] - can -> pvf [label = "Validate"] -} -``` - ## Protocol Input: [`CandidateValidationMessage`](../../types/overseer-protocol.md#validation-request-type) diff --git a/polkadot/roadmap/implementers-guide/src/node/utility/pvf-host-and-workers.md b/polkadot/roadmap/implementers-guide/src/node/utility/pvf-host-and-workers.md index e0984bd58d1..56bdd48bc0c 100644 --- a/polkadot/roadmap/implementers-guide/src/node/utility/pvf-host-and-workers.md +++ b/polkadot/roadmap/implementers-guide/src/node/utility/pvf-host-and-workers.md @@ -2,82 +2,12 @@ The PVF host is responsible for handling requests to prepare and execute PVF code blobs, which it sends to PVF **workers** running in their own child -processes. These workers are spawned from the `polkadot-prepare-worker` and -`polkadot-execute-worker` binaries. +processes. While the workers are generally long-living, they also spawn one-off secure **job processes** that perform the jobs. See "Job Processes" section below. -## High-Level Flow - -```dot process -digraph { - rankdir="LR"; - - can [label = "Candidate\nValidation\nSubsystem"; shape = square] - - pvf [label = "PVF Host"; shape = square] - - pq [label = "Prepare\nQueue"; shape = square] - eq [label = "Execute\nQueue"; shape = square] - pp [label = "Prepare\nPool"; shape = square] - - subgraph "cluster partial_sandbox_prep" { - label = "polkadot-prepare-worker\n(Partial Sandbox)\n\n\n"; - labelloc = "t"; - - pw [label = "Prepare\nWorker"; shape = square] - - subgraph "cluster full_sandbox_prep" { - label = "Fully Isolated Sandbox\n\n\n"; - labelloc = "t"; - - pj [label = "Prepare\nJob"; shape = square] - } - } - - subgraph "cluster partial_sandbox_exec" { - label = "polkadot-execute-worker\n(Partial Sandbox)\n\n\n"; - labelloc = "t"; - - ew [label = "Execute\nWorker"; shape = square] - - subgraph "cluster full_sandbox_exec" { - label = "Fully Isolated Sandbox\n\n\n"; - labelloc = "t"; - - ej [label = "Execute\nJob"; shape = square] - } - } - - can -> pvf [label = "Precheck"; style = dashed] - can -> pvf [label = "Validate"] - - pvf -> pq [label = "Prepare"; style = dashed] - pvf -> eq [label = "Execute";] - pvf -> pvf [label = "see (2) and (3)"; style = dashed] - pq -> pp [style = dashed] - - pp -> pw [style = dashed] - eq -> ew - - pw -> pj [style = dashed] - ew -> ej -} -``` - -Some notes about the graph: - -1. Once a job has finished, the response will flow back up the way it came. -2. In the case of execution, the host will send a request for preparation to the - Prepare Queue if needed. In that case, only after the preparation succeeds - does the Execute Queue continue with validation. -3. Multiple requests for preparing the same artifact are coalesced, so that the - work is only done once. - -## Goals - -This system has two high-level goals that we will touch on here: *determinism* +This system has two high-levels goals that we will touch on here: *determinism* and *security*. ## Determinism @@ -212,24 +142,19 @@ So what are we actually worried about? Things that come to mind: 6. **Intercepting and manipulating packages** - Effect very similar to the above, hard to do without also being able to do 4 or 5. -We do not protect against (1), (2), and (3), because there are too many sources -of randomness for an attacker to exploit. - -We provide very good protection against (4), (5), and (6). - ### Job Processes As mentioned above, our architecture includes long-living **worker processes** -and one-off **job processes**. This separation is important so that the handling +and one-off **job processes*. This separation is important so that the handling of untrusted code can be limited to the job processes. A hijacked job process can therefore not interfere with other jobs running in separate processes. -Furthermore, if an unexpected execution error occurred in the execution worker -and not the job itself, we generally can be confident that it has nothing to do -with the candidate, so we can abstain from voting. On the other hand, a hijacked -job is able to send back erroneous responses for candidates, so we know that we -should not abstain from voting on such errors from jobs. Otherwise, an attacker -could trigger a finality stall. (See "Internal Errors" section above.) +Furthermore, if an unexpected execution error occurred in the worker and not the +job, we generally can be confident that it has nothing to do with the candidate, +so we can abstain from voting. On the other hand, a hijacked job can send back +erroneous responses for candidates, so we know that we should not abstain from +voting on such errors from jobs. Otherwise, an attacker could trigger a finality +stall. (See "Internal Errors" section above.) ### Restricting file-system access diff --git a/polkadot/roadmap/implementers-guide/src/node/utility/pvf-prechecker.md b/polkadot/roadmap/implementers-guide/src/node/utility/pvf-prechecker.md index 7f6fef7ddf6..f0de50f2267 100644 --- a/polkadot/roadmap/implementers-guide/src/node/utility/pvf-prechecker.md +++ b/polkadot/roadmap/implementers-guide/src/node/utility/pvf-prechecker.md @@ -8,9 +8,9 @@ pre-checking. Head over to [overview] for the PVF pre-checking process overview. There is no dedicated input mechanism for PVF pre-checker. Instead, PVF pre-checker looks on the `ActiveLeavesUpdate` event stream for work. -This subsytem does not produce any output messages either. The subsystem will, however, send messages to the -[Runtime API] subsystem to query for the pending PVFs and to submit votes. In addition to that, it will also -communicate with [Candidate Validation] Subsystem to request PVF pre-check. +This subsytem does not produce any output messages either. The subsystem will, however, send messages to the [Runtime +API] subsystem to query for the pending PVFs and to submit votes. In addition to that, it will also communicate with +[Candidate Validation] Subsystem to request PVF pre-check. ## Functionality diff --git a/polkadot/roadmap/implementers-guide/src/protocol-approval.md b/polkadot/roadmap/implementers-guide/src/protocol-approval.md index b6aa16646ad..70bc0233d65 100644 --- a/polkadot/roadmap/implementers-guide/src/protocol-approval.md +++ b/polkadot/roadmap/implementers-guide/src/protocol-approval.md @@ -296,18 +296,6 @@ provide somewhat more security. TODO: When? Is this optimal for the network? etc. -## Approval coalescing -To reduce the necessary network bandwidth and cpu time when a validator has more than one candidate to approve we are -doing our best effort to send a single message that approves all available candidates with a single signature. -The implemented heuristic, is that each time we are ready to create a signature and send a vote for a candidate we -delay sending it until one of three things happen: -- We gathered a maximum of `MAX_APPROVAL_COALESCE_COUNT` candidates that we have already checked and we are - ready to sign approval for. -- `MAX_APPROVAL_COALESCE_WAIT_TICKS` have passed since checking oldest candidate and we were ready to sign - and send the approval message. -- We are already in the last third of the no-show period in order to avoid creating accidental no-shows, which in - turn might trigger other assignments. - ## On-chain verification We should verify approval on-chain to reward approval checkers. We therefore require the "no show" timeout to be longer diff --git a/polkadot/roadmap/phase-1.toml b/polkadot/roadmap/phase-1.toml index 3a5f0d752de..50ef1f741fe 100644 --- a/polkadot/roadmap/phase-1.toml +++ b/polkadot/roadmap/phase-1.toml @@ -14,7 +14,7 @@ requires = ["phase-0"] items = [ { label = "Buffer submitted parachain candidate until considered available." }, { label = "Validators submit signed bitfields re: availability of parachains" }, - { label = "relay chain fully includes candidate once considered available" }, + { label = "relay chain fully includes candidate once considered available" } ] [[group]] @@ -23,8 +23,8 @@ label = "Secondary checks and self-selection by validators" requires = ["two-phase-inclusion"] items = [ { label = "Extract #VCheck for all checkable candidates" }, - { label = "Listen for new reports on candidates and new checks to update frontier" }, { label = "Maintain a frontier of candidates that are likely to be checked soon" }, + { label = "Listen for new reports on candidates and new checks to update frontier" }, ] [[group]] @@ -32,8 +32,8 @@ name = "runtime-availability-validity-slashing" label = "Availability and Validity slashing in the runtime" requires = ["two-phase-inclusion"] items = [ - { label = "Submit secondary checks to runtime", port = "submitsecondary", requires = ["secondary-checking"] }, { label = "Track all candidates within the slash period as well as their session" }, + { label = "Submit secondary checks to runtime", port = "submitsecondary", requires = ["secondary-checking"]}, { label = "Track reports and attestatations for candidates" }, ] @@ -41,10 +41,10 @@ items = [ name = "non-direct-ancestor" label = "Allow candidates with non-direct ancestor" items = [ + { label = "Extend GlobalValidationData with random seed and session index"}, { label = "Block author can provide minimally-attested candidate with older relay parent" }, - { label = "Extend GlobalValidationData with random seed and session index" }, - { label = "Revise availability-store pruning to ensure only needed data is kept" }, { label = "Runtime can accept and process candidates with older relay-parent" }, + { label = "Revise availability-store pruning to ensure only needed data is kept" }, ] [[group]] @@ -52,13 +52,13 @@ name = "grandpa-voting-rule" label = "GRANDPA voting rule to follow valid/available chains" requires = ["runtime-availability-validity-slashing"] items = [ - { label = "Accept new blocks on abandoned but mark them abandoned as well." }, { label = "Add a utility to flag a block and all of its ancestors as abandoned" }, + { label = "Accept new blocks on abandoned but mark them abandoned as well." }, { label = "Do not vote or build on abandoned chains" }, ] [[group]] name = "phase-1" label = "Phase 1: Availability and Validity" -requires = ["grandpa-voting-rule", "non-direct-ancestor", "runtime-availability-validity-slashing"] +requires = ["non-direct-ancestor", "grandpa-voting-rule", "runtime-availability-validity-slashing"] items = [] diff --git a/polkadot/rpc/Cargo.toml b/polkadot/rpc/Cargo.toml index 8c582c623ba..ce11b26e554 100644 --- a/polkadot/rpc/Cargo.toml +++ b/polkadot/rpc/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "Polkadot specific RPC functionality." -[lints] -workspace = true - [dependencies] jsonrpsee = { version = "0.16.2", features = ["server"] } polkadot-primitives = { path = "../primitives" } diff --git a/polkadot/runtime/common/Cargo.toml b/polkadot/runtime/common/Cargo.toml index 1af29be0ae8..4391b6d81eb 100644 --- a/polkadot/runtime/common/Cargo.toml +++ b/polkadot/runtime/common/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] impl-trait-for-tuples = "0.2.2" bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } @@ -16,7 +13,7 @@ parity-scale-codec = { version = "3.6.1", default-features = false, features = [ log = { version = "0.4.17", default-features = false } rustc-hex = { version = "2.1.0", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, features = ["alloc"] } +serde = { version = "1.0.188", default-features = false, features = ["alloc"] } serde_derive = { version = "1.0.117" } static_assertions = "1.1.0" @@ -24,11 +21,11 @@ sp-api = { path = "../../../substrate/primitives/api", default-features = false inherents = { package = "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-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-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"] } pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false } pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } @@ -73,7 +70,7 @@ libsecp256k1 = "0.7.0" test-helpers = { package = "polkadot-primitives-test-helpers", path = "../../primitives/test-helpers" } [features] -default = ["std"] +default = [ "std" ] no_std = [] std = [ "bitvec/std", diff --git a/polkadot/runtime/common/slot_range_helper/Cargo.toml b/polkadot/runtime/common/slot_range_helper/Cargo.toml index 3a402d01196..59c76a6cabb 100644 --- a/polkadot/runtime/common/slot_range_helper/Cargo.toml +++ b/polkadot/runtime/common/slot_range_helper/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "Helper crate for generating slot ranges for the Polkadot runtime." -[lints] -workspace = true - [dependencies] paste = "1.0" enumn = "0.1.12" @@ -17,5 +14,5 @@ sp-std = { package = "sp-std", path = "../../../../substrate/primitives/std", de sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } [features] -default = ["std"] -std = ["parity-scale-codec/std", "sp-runtime/std", "sp-std/std"] +default = [ "std" ] +std = [ "parity-scale-codec/std", "sp-runtime/std", "sp-std/std" ] diff --git a/polkadot/runtime/common/src/assigned_slots/mod.rs b/polkadot/runtime/common/src/assigned_slots/mod.rs index f5e3aaef632..cb2e5083b0a 100644 --- a/polkadot/runtime/common/src/assigned_slots/mod.rs +++ b/polkadot/runtime/common/src/assigned_slots/mod.rs @@ -636,7 +636,7 @@ mod tests { use crate::{assigned_slots, mock::TestRegistrar, slots}; use ::test_helpers::{dummy_head_data, dummy_validation_code}; - use frame_support::{assert_noop, assert_ok, derive_impl, parameter_types}; + use frame_support::{assert_noop, assert_ok, parameter_types}; use frame_system::EnsureRoot; use pallet_balances; use primitives::BlockNumber; @@ -679,8 +679,6 @@ mod tests { parameter_types! { pub const BlockHashCount: u32 = 250; } - - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/polkadot/runtime/common/src/auctions.rs b/polkadot/runtime/common/src/auctions.rs index baa66d83a3f..267413eb1ba 100644 --- a/polkadot/runtime/common/src/auctions.rs +++ b/polkadot/runtime/common/src/auctions.rs @@ -677,8 +677,7 @@ mod tests { use crate::{auctions, mock::TestRegistrar}; use ::test_helpers::{dummy_hash, dummy_head_data, dummy_validation_code}; use frame_support::{ - assert_noop, assert_ok, assert_storage_noop, derive_impl, ord_parameter_types, - parameter_types, + assert_noop, assert_ok, assert_storage_noop, ord_parameter_types, parameter_types, traits::{ConstU32, EitherOfDiverse, OnFinalize, OnInitialize}, }; use frame_system::{EnsureRoot, EnsureSignedBy}; @@ -706,8 +705,6 @@ mod tests { parameter_types! { pub const BlockHashCount: u32 = 250; } - - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/polkadot/runtime/common/src/claims.rs b/polkadot/runtime/common/src/claims.rs index 6b77845cb3e..e57272151d1 100644 --- a/polkadot/runtime/common/src/claims.rs +++ b/polkadot/runtime/common/src/claims.rs @@ -716,7 +716,7 @@ mod tests { use crate::claims; use claims::Call as ClaimsCall; use frame_support::{ - assert_err, assert_noop, assert_ok, derive_impl, + assert_err, assert_noop, assert_ok, dispatch::{GetDispatchInfo, Pays}, ord_parameter_types, parameter_types, traits::{ConstU32, ExistenceRequirement, WithdrawReasons}, @@ -745,8 +745,6 @@ mod tests { parameter_types! { pub const BlockHashCount: u32 = 250; } - - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); @@ -807,7 +805,6 @@ mod tests { type MinVestedTransfer = MinVestedTransfer; type WeightInfo = (); type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; - type BlockNumberProvider = System; const MAX_VESTING_SCHEDULES: u32 = 28; } diff --git a/polkadot/runtime/common/src/crowdloan/mod.rs b/polkadot/runtime/common/src/crowdloan/mod.rs index 77ef406e579..f67fc12a67f 100644 --- a/polkadot/runtime/common/src/crowdloan/mod.rs +++ b/polkadot/runtime/common/src/crowdloan/mod.rs @@ -863,7 +863,7 @@ mod tests { use super::*; use frame_support::{ - assert_noop, assert_ok, derive_impl, parameter_types, + assert_noop, assert_ok, parameter_types, traits::{ConstU32, OnFinalize, OnInitialize}, }; use primitives::Id as ParaId; @@ -900,7 +900,6 @@ mod tests { type BlockNumber = u64; - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/polkadot/runtime/common/src/impls.rs b/polkadot/runtime/common/src/impls.rs index d71c626cd98..e50ffb634b3 100644 --- a/polkadot/runtime/common/src/impls.rs +++ b/polkadot/runtime/common/src/impls.rs @@ -149,11 +149,8 @@ impl TryConvert<&VersionedMultiLocation, xcm::latest::MultiLocation> #[cfg(feature = "runtime-benchmarks")] pub mod benchmarks { use super::VersionedLocatableAsset; - use core::marker::PhantomData; - use frame_support::traits::Get; use pallet_asset_rate::AssetKindFactory; use pallet_treasury::ArgumentsFactory as TreasuryArgumentsFactory; - use sp_core::{ConstU32, ConstU8}; use xcm::prelude::*; /// Provides a factory method for the [`VersionedLocatableAsset`]. @@ -175,22 +172,12 @@ pub mod benchmarks { /// Provide factory methods for the [`VersionedLocatableAsset`] and the `Beneficiary` of the /// [`VersionedMultiLocation`]. The location of the asset is determined as a Parachain with an /// ID equal to the passed seed. - pub struct TreasuryArguments, ParaId = ConstU32<0>>( - PhantomData<(Parents, ParaId)>, - ); - impl, ParaId: Get> - TreasuryArgumentsFactory - for TreasuryArguments + pub struct TreasuryArguments; + impl TreasuryArgumentsFactory + for TreasuryArguments { fn create_asset_kind(seed: u32) -> VersionedLocatableAsset { - VersionedLocatableAsset::V3 { - location: xcm::v3::MultiLocation::new(Parents::get(), X1(Parachain(ParaId::get()))), - asset_id: xcm::v3::MultiLocation::new( - 0, - X2(PalletInstance(seed.try_into().unwrap()), GeneralIndex(seed.into())), - ) - .into(), - } + AssetRateArguments::create_asset_kind(seed) } fn create_beneficiary(seed: [u8; 32]) -> VersionedMultiLocation { VersionedMultiLocation::V3(xcm::v3::MultiLocation::new( @@ -205,7 +192,6 @@ pub mod benchmarks { mod tests { use super::*; use frame_support::{ - derive_impl, dispatch::DispatchClass, parameter_types, traits::{ @@ -251,7 +237,6 @@ mod tests { pub const AvailableBlockRatio: Perbill = Perbill::one(); } - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; diff --git a/polkadot/runtime/common/src/integration_tests.rs b/polkadot/runtime/common/src/integration_tests.rs index b0d277a702d..793f75e79cd 100644 --- a/polkadot/runtime/common/src/integration_tests.rs +++ b/polkadot/runtime/common/src/integration_tests.rs @@ -25,7 +25,7 @@ use crate::{ traits::{AuctionStatus, Auctioneer, Leaser, Registrar as RegistrarT}, }; use frame_support::{ - assert_noop, assert_ok, derive_impl, parameter_types, + assert_noop, assert_ok, parameter_types, traits::{ConstU32, Currency, OnFinalize, OnInitialize}, weights::Weight, PalletId, @@ -114,7 +114,6 @@ parameter_types! { ); } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = BlockWeights; diff --git a/polkadot/runtime/common/src/paras_registrar/mod.rs b/polkadot/runtime/common/src/paras_registrar/mod.rs index 12376ae6f1f..2d33cf28993 100644 --- a/polkadot/runtime/common/src/paras_registrar/mod.rs +++ b/polkadot/runtime/common/src/paras_registrar/mod.rs @@ -699,7 +699,7 @@ mod tests { mock::conclude_pvf_checking, paras_registrar, traits::Registrar as RegistrarTrait, }; use frame_support::{ - assert_noop, assert_ok, derive_impl, + assert_noop, assert_ok, error::BadOrigin, parameter_types, traits::{ConstU32, OnFinalize, OnInitialize}, @@ -751,7 +751,6 @@ mod tests { limits::BlockLength::max_with_normal_ratio(4 * 1024 * 1024, NORMAL_RATIO); } - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; diff --git a/polkadot/runtime/common/src/purchase.rs b/polkadot/runtime/common/src/purchase.rs index f43f16b838c..bc95483dd7e 100644 --- a/polkadot/runtime/common/src/purchase.rs +++ b/polkadot/runtime/common/src/purchase.rs @@ -484,7 +484,7 @@ mod tests { // or public keys. `u64` is used as the `AccountId` and no `Signature`s are required. use crate::purchase; use frame_support::{ - assert_noop, assert_ok, derive_impl, ord_parameter_types, parameter_types, + assert_noop, assert_ok, ord_parameter_types, parameter_types, traits::{Currency, WithdrawReasons}, }; use sp_runtime::{ @@ -511,8 +511,6 @@ mod tests { parameter_types! { pub const BlockHashCount: u32 = 250; } - - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); @@ -573,7 +571,6 @@ mod tests { type MinVestedTransfer = MinVestedTransfer; type WeightInfo = (); type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; - type BlockNumberProvider = System; const MAX_VESTING_SCHEDULES: u32 = 28; } diff --git a/polkadot/runtime/common/src/slots/mod.rs b/polkadot/runtime/common/src/slots/mod.rs index c3aaf8b51b8..01f6365b791 100644 --- a/polkadot/runtime/common/src/slots/mod.rs +++ b/polkadot/runtime/common/src/slots/mod.rs @@ -505,7 +505,7 @@ mod tests { use crate::{mock::TestRegistrar, slots}; use ::test_helpers::{dummy_head_data, dummy_validation_code}; - use frame_support::{assert_noop, assert_ok, derive_impl, parameter_types}; + use frame_support::{assert_noop, assert_ok, parameter_types}; use frame_system::EnsureRoot; use pallet_balances; use primitives::BlockNumber; @@ -529,8 +529,6 @@ mod tests { parameter_types! { pub const BlockHashCount: u32 = 250; } - - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/polkadot/runtime/metrics/Cargo.toml b/polkadot/runtime/metrics/Cargo.toml index 9a16749bf60..cdfab82d00c 100644 --- a/polkadot/runtime/metrics/Cargo.toml +++ b/polkadot/runtime/metrics/Cargo.toml @@ -6,11 +6,8 @@ edition.workspace = true license.workspace = true description = "Runtime metric interface for the Polkadot node" -[lints] -workspace = true - [dependencies] -sp-std = { package = "sp-std", path = "../../../substrate/primitives/std", default-features = false } +sp-std = { package = "sp-std", path = "../../../substrate/primitives/std", default-features = false} sp-tracing = { path = "../../../substrate/primitives/tracing", default-features = false } parity-scale-codec = { version = "3.6.1", default-features = false } primitives = { package = "polkadot-primitives", path = "../../primitives", default-features = false } @@ -19,7 +16,7 @@ frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-f bs58 = { version = "0.5.0", default-features = false, features = ["alloc"] } [features] -default = ["std"] +default = [ "std" ] std = [ "bs58/std", "frame-benchmarking?/std", @@ -28,4 +25,4 @@ std = [ "sp-std/std", "sp-tracing/std", ] -runtime-metrics = ["frame-benchmarking", "sp-tracing/with-tracing"] +runtime-metrics = [ "frame-benchmarking", "sp-tracing/with-tracing" ] diff --git a/polkadot/runtime/parachains/Cargo.toml b/polkadot/runtime/parachains/Cargo.toml index 0bcf5c04c34..b6800fc0844 100644 --- a/polkadot/runtime/parachains/Cargo.toml +++ b/polkadot/runtime/parachains/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] impl-trait-for-tuples = "0.2.2" bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } @@ -16,7 +13,7 @@ parity-scale-codec = { version = "3.6.1", default-features = false, features = [ log = { version = "0.4.17", default-features = false } rustc-hex = { version = "2.1.0", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"] } +serde = { version = "1.0.188", default-features = false, features = ["derive", "alloc"] } derive_more = "0.99.17" bitflags = "1.3.2" @@ -24,10 +21,10 @@ sp-api = { path = "../../../substrate/primitives/api", default-features = false inherents = { package = "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-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-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 } sp-application-crypto = { path = "../../../substrate/primitives/application-crypto", default-features = false, optional = true } sp-tracing = { path = "../../../substrate/primitives/tracing", default-features = false, optional = true } @@ -53,7 +50,7 @@ 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-runtime-metrics = { path = "../metrics", default-features = false} polkadot-core-primitives = { path = "../../core-primitives", default-features = false } [dev-dependencies] @@ -69,7 +66,7 @@ assert_matches = "1" serde_json = "1.0.108" [features] -default = ["std"] +default = [ "std" ] no_std = [] std = [ "bitvec/std", diff --git a/polkadot/runtime/parachains/src/builder.rs b/polkadot/runtime/parachains/src/builder.rs index 23916bbdc8a..dced24df0ae 100644 --- a/polkadot/runtime/parachains/src/builder.rs +++ b/polkadot/runtime/parachains/src/builder.rs @@ -636,7 +636,7 @@ impl BenchBuilder { } else { DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) }; - let data = dispute_statement.payload_data(candidate_hash, session).unwrap(); + let data = dispute_statement.payload_data(candidate_hash, session); let statement_sig = validator_public.sign(&data).unwrap(); (dispute_statement, ValidatorIndex(validator_index), statement_sig) diff --git a/polkadot/runtime/parachains/src/configuration.rs b/polkadot/runtime/parachains/src/configuration.rs index 272c227dfef..bff9cc34b4f 100644 --- a/polkadot/runtime/parachains/src/configuration.rs +++ b/polkadot/runtime/parachains/src/configuration.rs @@ -26,9 +26,8 @@ use polkadot_parachain_primitives::primitives::{ MAX_HORIZONTAL_MESSAGE_NUM, MAX_UPWARD_MESSAGE_NUM, }; use primitives::{ - vstaging::{ApprovalVotingParams, NodeFeatures}, - AsyncBackingParams, Balance, ExecutorParamError, ExecutorParams, SessionIndex, - LEGACY_MIN_BACKING_VOTES, MAX_CODE_SIZE, MAX_HEAD_DATA_SIZE, MAX_POV_SIZE, + vstaging::NodeFeatures, AsyncBackingParams, Balance, ExecutorParamError, ExecutorParams, + SessionIndex, LEGACY_MIN_BACKING_VOTES, MAX_CODE_SIZE, MAX_HEAD_DATA_SIZE, MAX_POV_SIZE, ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE, }; use sp_runtime::{traits::Zero, Perbill}; @@ -264,8 +263,6 @@ pub struct HostConfiguration { pub minimum_backing_votes: u32, /// Node features enablement. pub node_features: NodeFeatures, - /// Params used by approval-voting - pub approval_voting_params: ApprovalVotingParams, } impl> Default for HostConfiguration { @@ -311,7 +308,6 @@ impl> Default for HostConfiguration /// v8-v9: /// v9-v10: - /// v10-11: - const STORAGE_VERSION: StorageVersion = StorageVersion::new(11); + const STORAGE_VERSION: StorageVersion = StorageVersion::new(10); #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] @@ -1196,7 +1191,6 @@ pub mod pallet { config.on_demand_ttl = new; }) } - /// Set the minimum backing votes threshold. #[pallet::call_index(52)] #[pallet::weight(( @@ -1209,7 +1203,6 @@ pub mod pallet { config.minimum_backing_votes = new; }) } - /// Set/Unset a node feature. #[pallet::call_index(53)] #[pallet::weight(( @@ -1227,22 +1220,6 @@ pub mod pallet { config.node_features.set(index, value); }) } - - /// Set approval-voting-params. - #[pallet::call_index(54)] - #[pallet::weight(( - T::WeightInfo::set_config_with_executor_params(), - DispatchClass::Operational, - ))] - pub fn set_approval_voting_params( - origin: OriginFor, - new: ApprovalVotingParams, - ) -> DispatchResult { - ensure_root(origin)?; - Self::schedule_config_update(|config| { - config.approval_voting_params = new; - }) - } } #[pallet::hooks] diff --git a/polkadot/runtime/parachains/src/configuration/migration.rs b/polkadot/runtime/parachains/src/configuration/migration.rs index 2838b73092d..db323d3aad9 100644 --- a/polkadot/runtime/parachains/src/configuration/migration.rs +++ b/polkadot/runtime/parachains/src/configuration/migration.rs @@ -17,7 +17,6 @@ //! A module that is responsible for migration of storage. pub mod v10; -pub mod v11; pub mod v6; pub mod v7; pub mod v8; diff --git a/polkadot/runtime/parachains/src/configuration/migration/v10.rs b/polkadot/runtime/parachains/src/configuration/migration/v10.rs index cf228610e5c..3c934082dc1 100644 --- a/polkadot/runtime/parachains/src/configuration/migration/v10.rs +++ b/polkadot/runtime/parachains/src/configuration/migration/v10.rs @@ -16,121 +16,17 @@ //! A module that is responsible for migration of storage. -use crate::configuration::{Config, Pallet}; +use crate::configuration::{self, Config, Pallet}; use frame_support::{pallet_prelude::*, traits::Defensive, weights::Weight}; use frame_system::pallet_prelude::BlockNumberFor; -use primitives::{ - vstaging::NodeFeatures, AsyncBackingParams, Balance, ExecutorParams, SessionIndex, - LEGACY_MIN_BACKING_VOTES, ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE, -}; -use sp_runtime::Perbill; +use primitives::{vstaging::NodeFeatures, SessionIndex}; use sp_std::vec::Vec; use frame_support::traits::OnRuntimeUpgrade; use super::v9::V9HostConfiguration; -// All configuration of the runtime with respect to paras. -#[derive(Clone, Encode, PartialEq, Decode, Debug)] -pub struct V10HostConfiguration { - pub max_code_size: u32, - pub max_head_data_size: u32, - pub max_upward_queue_count: u32, - pub max_upward_queue_size: u32, - pub max_upward_message_size: u32, - pub max_upward_message_num_per_candidate: u32, - pub hrmp_max_message_num_per_candidate: u32, - pub validation_upgrade_cooldown: BlockNumber, - pub validation_upgrade_delay: BlockNumber, - pub async_backing_params: AsyncBackingParams, - pub max_pov_size: u32, - pub max_downward_message_size: u32, - pub hrmp_max_parachain_outbound_channels: u32, - pub hrmp_sender_deposit: Balance, - pub hrmp_recipient_deposit: Balance, - pub hrmp_channel_max_capacity: u32, - pub hrmp_channel_max_total_size: u32, - pub hrmp_max_parachain_inbound_channels: u32, - pub hrmp_channel_max_message_size: u32, - pub executor_params: ExecutorParams, - pub code_retention_period: BlockNumber, - pub on_demand_cores: u32, - pub on_demand_retries: u32, - pub on_demand_queue_max_size: u32, - pub on_demand_target_queue_utilization: Perbill, - pub on_demand_fee_variability: Perbill, - pub on_demand_base_fee: Balance, - pub on_demand_ttl: BlockNumber, - pub group_rotation_frequency: BlockNumber, - pub paras_availability_period: BlockNumber, - pub scheduling_lookahead: u32, - pub max_validators_per_core: Option, - pub max_validators: Option, - pub dispute_period: SessionIndex, - pub dispute_post_conclusion_acceptance_period: BlockNumber, - pub no_show_slots: u32, - pub n_delay_tranches: u32, - pub zeroth_delay_tranche_width: u32, - pub needed_approvals: u32, - pub relay_vrf_modulo_samples: u32, - pub pvf_voting_ttl: SessionIndex, - pub minimum_validation_upgrade_delay: BlockNumber, - pub minimum_backing_votes: u32, - pub node_features: NodeFeatures, -} -impl> Default for V10HostConfiguration { - fn default() -> Self { - Self { - async_backing_params: AsyncBackingParams { - max_candidate_depth: 0, - allowed_ancestry_len: 0, - }, - group_rotation_frequency: 1u32.into(), - paras_availability_period: 1u32.into(), - no_show_slots: 1u32.into(), - validation_upgrade_cooldown: Default::default(), - validation_upgrade_delay: 2u32.into(), - code_retention_period: Default::default(), - max_code_size: Default::default(), - max_pov_size: Default::default(), - max_head_data_size: Default::default(), - on_demand_cores: Default::default(), - on_demand_retries: Default::default(), - scheduling_lookahead: 1, - max_validators_per_core: Default::default(), - max_validators: None, - dispute_period: 6, - dispute_post_conclusion_acceptance_period: 100.into(), - n_delay_tranches: Default::default(), - zeroth_delay_tranche_width: Default::default(), - needed_approvals: Default::default(), - relay_vrf_modulo_samples: Default::default(), - max_upward_queue_count: Default::default(), - max_upward_queue_size: Default::default(), - max_downward_message_size: Default::default(), - max_upward_message_size: Default::default(), - max_upward_message_num_per_candidate: Default::default(), - hrmp_sender_deposit: Default::default(), - hrmp_recipient_deposit: Default::default(), - hrmp_channel_max_capacity: Default::default(), - hrmp_channel_max_total_size: Default::default(), - hrmp_max_parachain_inbound_channels: Default::default(), - hrmp_channel_max_message_size: Default::default(), - hrmp_max_parachain_outbound_channels: Default::default(), - hrmp_max_message_num_per_candidate: Default::default(), - pvf_voting_ttl: 2u32.into(), - minimum_validation_upgrade_delay: 2.into(), - executor_params: Default::default(), - on_demand_queue_max_size: ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE, - on_demand_base_fee: 10_000_000u128, - on_demand_fee_variability: Perbill::from_percent(3), - on_demand_target_queue_utilization: Perbill::from_percent(25), - on_demand_ttl: 5u32.into(), - minimum_backing_votes: LEGACY_MIN_BACKING_VOTES, - node_features: NodeFeatures::EMPTY, - } - } -} +type V10HostConfiguration = configuration::HostConfiguration; mod v9 { use super::*; diff --git a/polkadot/runtime/parachains/src/configuration/migration/v11.rs b/polkadot/runtime/parachains/src/configuration/migration/v11.rs deleted file mode 100644 index b7dec7070f9..00000000000 --- a/polkadot/runtime/parachains/src/configuration/migration/v11.rs +++ /dev/null @@ -1,329 +0,0 @@ -// 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 . - -//! A module that is responsible for migration of storage. - -use crate::configuration::{self, Config, Pallet}; -use frame_support::{ - migrations::VersionedMigration, pallet_prelude::*, traits::Defensive, weights::Weight, -}; -use frame_system::pallet_prelude::BlockNumberFor; -use primitives::{vstaging::ApprovalVotingParams, SessionIndex}; -use sp_std::vec::Vec; - -use frame_support::traits::OnRuntimeUpgrade; - -use super::v10::V10HostConfiguration; -type V11HostConfiguration = configuration::HostConfiguration; - -mod v10 { - use super::*; - - #[frame_support::storage_alias] - pub(crate) type ActiveConfig = - StorageValue, V10HostConfiguration>, OptionQuery>; - - #[frame_support::storage_alias] - pub(crate) type PendingConfigs = StorageValue< - Pallet, - Vec<(SessionIndex, V10HostConfiguration>)>, - OptionQuery, - >; -} - -mod v11 { - use super::*; - - #[frame_support::storage_alias] - pub(crate) type ActiveConfig = - StorageValue, V11HostConfiguration>, OptionQuery>; - - #[frame_support::storage_alias] - pub(crate) type PendingConfigs = StorageValue< - Pallet, - Vec<(SessionIndex, V11HostConfiguration>)>, - OptionQuery, - >; -} - -pub type MigrateToV11 = VersionedMigration< - 10, - 11, - UncheckedMigrateToV11, - Pallet, - ::DbWeight, ->; - -pub struct UncheckedMigrateToV11(sp_std::marker::PhantomData); -impl OnRuntimeUpgrade for UncheckedMigrateToV11 { - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { - log::trace!(target: crate::configuration::LOG_TARGET, "Running pre_upgrade() for HostConfiguration MigrateToV11"); - Ok(Vec::new()) - } - - fn on_runtime_upgrade() -> Weight { - log::info!(target: configuration::LOG_TARGET, "HostConfiguration MigrateToV11 started"); - let weight_consumed = migrate_to_v11::(); - - log::info!(target: configuration::LOG_TARGET, "HostConfiguration MigrateToV11 executed successfully"); - - weight_consumed - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(_state: Vec) -> Result<(), sp_runtime::TryRuntimeError> { - log::trace!(target: crate::configuration::LOG_TARGET, "Running post_upgrade() for HostConfiguration MigrateToV11"); - ensure!( - StorageVersion::get::>() >= 11, - "Storage version should be >= 11 after the migration" - ); - - Ok(()) - } -} - -fn migrate_to_v11() -> Weight { - // Unusual formatting is justified: - // - make it easier to verify that fields assign what they supposed to assign. - // - this code is transient and will be removed after all migrations are done. - // - this code is important enough to optimize for legibility sacrificing consistency. - #[rustfmt::skip] - let translate = - |pre: V10HostConfiguration>| -> - V11HostConfiguration> - { - V11HostConfiguration { -max_code_size : pre.max_code_size, -max_head_data_size : pre.max_head_data_size, -max_upward_queue_count : pre.max_upward_queue_count, -max_upward_queue_size : pre.max_upward_queue_size, -max_upward_message_size : pre.max_upward_message_size, -max_upward_message_num_per_candidate : pre.max_upward_message_num_per_candidate, -hrmp_max_message_num_per_candidate : pre.hrmp_max_message_num_per_candidate, -validation_upgrade_cooldown : pre.validation_upgrade_cooldown, -validation_upgrade_delay : pre.validation_upgrade_delay, -max_pov_size : pre.max_pov_size, -max_downward_message_size : pre.max_downward_message_size, -hrmp_sender_deposit : pre.hrmp_sender_deposit, -hrmp_recipient_deposit : pre.hrmp_recipient_deposit, -hrmp_channel_max_capacity : pre.hrmp_channel_max_capacity, -hrmp_channel_max_total_size : pre.hrmp_channel_max_total_size, -hrmp_max_parachain_inbound_channels : pre.hrmp_max_parachain_inbound_channels, -hrmp_max_parachain_outbound_channels : pre.hrmp_max_parachain_outbound_channels, -hrmp_channel_max_message_size : pre.hrmp_channel_max_message_size, -code_retention_period : pre.code_retention_period, -on_demand_cores : pre.on_demand_cores, -on_demand_retries : pre.on_demand_retries, -group_rotation_frequency : pre.group_rotation_frequency, -paras_availability_period : pre.paras_availability_period, -scheduling_lookahead : pre.scheduling_lookahead, -max_validators_per_core : pre.max_validators_per_core, -max_validators : pre.max_validators, -dispute_period : pre.dispute_period, -dispute_post_conclusion_acceptance_period: pre.dispute_post_conclusion_acceptance_period, -no_show_slots : pre.no_show_slots, -n_delay_tranches : pre.n_delay_tranches, -zeroth_delay_tranche_width : pre.zeroth_delay_tranche_width, -needed_approvals : pre.needed_approvals, -relay_vrf_modulo_samples : pre.relay_vrf_modulo_samples, -pvf_voting_ttl : pre.pvf_voting_ttl, -minimum_validation_upgrade_delay : pre.minimum_validation_upgrade_delay, -async_backing_params : pre.async_backing_params, -executor_params : pre.executor_params, -on_demand_queue_max_size : pre.on_demand_queue_max_size, -on_demand_base_fee : pre.on_demand_base_fee, -on_demand_fee_variability : pre.on_demand_fee_variability, -on_demand_target_queue_utilization : pre.on_demand_target_queue_utilization, -on_demand_ttl : pre.on_demand_ttl, -minimum_backing_votes : pre.minimum_backing_votes, -node_features : pre.node_features, -approval_voting_params : ApprovalVotingParams { - max_approval_coalesce_count: 1, - } - } - }; - - let v10 = v10::ActiveConfig::::get() - .defensive_proof("Could not decode old config") - .unwrap_or_default(); - let v11 = translate(v10); - v11::ActiveConfig::::set(Some(v11)); - - // Allowed to be empty. - let pending_v9 = v10::PendingConfigs::::get().unwrap_or_default(); - let mut pending_v10 = Vec::new(); - - for (session, v10) in pending_v9.into_iter() { - let v11 = translate(v10); - pending_v10.push((session, v11)); - } - v11::PendingConfigs::::set(Some(pending_v10.clone())); - - let num_configs = (pending_v10.len() + 1) as u64; - T::DbWeight::get().reads_writes(num_configs, num_configs) -} - -#[cfg(test)] -mod tests { - use primitives::LEGACY_MIN_BACKING_VOTES; - - use super::*; - use crate::mock::{new_test_ext, Test}; - - #[test] - fn v11_deserialized_from_actual_data() { - // Example how to get new `raw_config`: - // We'll obtain the raw_config at a specified a block - // Steps: - // 1. Go to Polkadot.js -> Developer -> Chain state -> Storage: https://polkadot.js.org/apps/#/chainstate - // 2. Set these parameters: - // 2.1. selected state query: configuration; activeConfig(): - // PolkadotRuntimeParachainsConfigurationHostConfiguration - // 2.2. blockhash to query at: - // 0xf89d3ab5312c5f70d396dc59612f0aa65806c798346f9db4b35278baed2e0e53 (the hash of - // the block) - // 2.3. Note the value of encoded storage key -> - // 0x06de3d8a54d27e44a9d5ce189618f22db4b49d95320d9021994c850f25b8e385 for the - // referenced block. - // 2.4. You'll also need the decoded values to update the test. - // 3. Go to Polkadot.js -> Developer -> Chain state -> Raw storage - // 3.1 Enter the encoded storage key and you get the raw config. - - // This exceeds the maximal line width length, but that's fine, since this is not code and - // doesn't need to be read and also leaving it as one line allows to easily copy it. - let raw_config = - hex_literal::hex![" - 0000300000800000080000000000100000c8000005000000050000000200000002000000000000000000000000005000000010000400000000000000000000000000000000000000000000000000000000000000000000000800000000200000040000000000100000b004000000000000000000001027000080b2e60e80c3c9018096980000000000000000000000000005000000140000000400000001000000010100000000060000006400000002000000190000000000000002000000020000000200000005000000020000000001000000" - ]; - - let v11 = - V11HostConfiguration::::decode(&mut &raw_config[..]).unwrap(); - - // We check only a sample of the values here. If we missed any fields or messed up data - // types that would skew all the fields coming after. - assert_eq!(v11.max_code_size, 3_145_728); - assert_eq!(v11.validation_upgrade_cooldown, 2); - assert_eq!(v11.max_pov_size, 5_242_880); - assert_eq!(v11.hrmp_channel_max_message_size, 1_048_576); - assert_eq!(v11.n_delay_tranches, 25); - assert_eq!(v11.minimum_validation_upgrade_delay, 5); - assert_eq!(v11.group_rotation_frequency, 20); - assert_eq!(v11.on_demand_cores, 0); - assert_eq!(v11.on_demand_base_fee, 10_000_000); - assert_eq!(v11.minimum_backing_votes, LEGACY_MIN_BACKING_VOTES); - assert_eq!(v11.approval_voting_params.max_approval_coalesce_count, 1); - } - - #[test] - fn test_migrate_to_v11() { - // Host configuration has lots of fields. However, in this migration we only add one - // field. The most important part to check are a couple of the last fields. We also pick - // extra fields to check arbitrarily, e.g. depending on their position (i.e. the middle) and - // also their type. - // - // We specify only the picked fields and the rest should be provided by the `Default` - // implementation. That implementation is copied over between the two types and should work - // fine. - let v10 = V10HostConfiguration:: { - needed_approvals: 69, - paras_availability_period: 55, - hrmp_recipient_deposit: 1337, - max_pov_size: 1111, - minimum_validation_upgrade_delay: 20, - ..Default::default() - }; - - let mut pending_configs = Vec::new(); - pending_configs.push((100, v10.clone())); - pending_configs.push((300, v10.clone())); - - new_test_ext(Default::default()).execute_with(|| { - // Implant the v10 version in the state. - v10::ActiveConfig::::set(Some(v10)); - v10::PendingConfigs::::set(Some(pending_configs)); - - migrate_to_v11::(); - - let v11 = v11::ActiveConfig::::get().unwrap(); - assert_eq!(v11.approval_voting_params.max_approval_coalesce_count, 1); - - let mut configs_to_check = v11::PendingConfigs::::get().unwrap(); - configs_to_check.push((0, v11.clone())); - - for (_, v10) in configs_to_check { - #[rustfmt::skip] - { - assert_eq!(v10.max_code_size , v11.max_code_size); - assert_eq!(v10.max_head_data_size , v11.max_head_data_size); - assert_eq!(v10.max_upward_queue_count , v11.max_upward_queue_count); - assert_eq!(v10.max_upward_queue_size , v11.max_upward_queue_size); - assert_eq!(v10.max_upward_message_size , v11.max_upward_message_size); - assert_eq!(v10.max_upward_message_num_per_candidate , v11.max_upward_message_num_per_candidate); - assert_eq!(v10.hrmp_max_message_num_per_candidate , v11.hrmp_max_message_num_per_candidate); - assert_eq!(v10.validation_upgrade_cooldown , v11.validation_upgrade_cooldown); - assert_eq!(v10.validation_upgrade_delay , v11.validation_upgrade_delay); - assert_eq!(v10.max_pov_size , v11.max_pov_size); - assert_eq!(v10.max_downward_message_size , v11.max_downward_message_size); - assert_eq!(v10.hrmp_max_parachain_outbound_channels , v11.hrmp_max_parachain_outbound_channels); - assert_eq!(v10.hrmp_sender_deposit , v11.hrmp_sender_deposit); - assert_eq!(v10.hrmp_recipient_deposit , v11.hrmp_recipient_deposit); - assert_eq!(v10.hrmp_channel_max_capacity , v11.hrmp_channel_max_capacity); - assert_eq!(v10.hrmp_channel_max_total_size , v11.hrmp_channel_max_total_size); - assert_eq!(v10.hrmp_max_parachain_inbound_channels , v11.hrmp_max_parachain_inbound_channels); - assert_eq!(v10.hrmp_channel_max_message_size , v11.hrmp_channel_max_message_size); - assert_eq!(v10.code_retention_period , v11.code_retention_period); - assert_eq!(v10.on_demand_cores , v11.on_demand_cores); - assert_eq!(v10.on_demand_retries , v11.on_demand_retries); - assert_eq!(v10.group_rotation_frequency , v11.group_rotation_frequency); - assert_eq!(v10.paras_availability_period , v11.paras_availability_period); - assert_eq!(v10.scheduling_lookahead , v11.scheduling_lookahead); - assert_eq!(v10.max_validators_per_core , v11.max_validators_per_core); - assert_eq!(v10.max_validators , v11.max_validators); - assert_eq!(v10.dispute_period , v11.dispute_period); - assert_eq!(v10.no_show_slots , v11.no_show_slots); - assert_eq!(v10.n_delay_tranches , v11.n_delay_tranches); - assert_eq!(v10.zeroth_delay_tranche_width , v11.zeroth_delay_tranche_width); - assert_eq!(v10.needed_approvals , v11.needed_approvals); - assert_eq!(v10.relay_vrf_modulo_samples , v11.relay_vrf_modulo_samples); - assert_eq!(v10.pvf_voting_ttl , v11.pvf_voting_ttl); - assert_eq!(v10.minimum_validation_upgrade_delay , v11.minimum_validation_upgrade_delay); - assert_eq!(v10.async_backing_params.allowed_ancestry_len, v11.async_backing_params.allowed_ancestry_len); - assert_eq!(v10.async_backing_params.max_candidate_depth , v11.async_backing_params.max_candidate_depth); - assert_eq!(v10.executor_params , v11.executor_params); - assert_eq!(v10.minimum_backing_votes , v11.minimum_backing_votes); - }; // ; makes this a statement. `rustfmt::skip` cannot be put on an expression. - } - }); - } - - // Test that migration doesn't panic in case there're no pending configurations upgrades in - // pallet's storage. - #[test] - fn test_migrate_to_v11_no_pending() { - let v10 = V10HostConfiguration::::default(); - - new_test_ext(Default::default()).execute_with(|| { - // Implant the v10 version in the state. - v10::ActiveConfig::::set(Some(v10)); - // Ensure there're no pending configs. - v11::PendingConfigs::::set(None); - - // Shouldn't fail. - migrate_to_v11::(); - }); - } -} diff --git a/polkadot/runtime/parachains/src/configuration/migration/v8.rs b/polkadot/runtime/parachains/src/configuration/migration/v8.rs index 537dfa9abd7..d1bc9005112 100644 --- a/polkadot/runtime/parachains/src/configuration/migration/v8.rs +++ b/polkadot/runtime/parachains/src/configuration/migration/v8.rs @@ -250,7 +250,7 @@ on_demand_fee_variability : Perbill::from_percent(3), on_demand_target_queue_utilization : Perbill::from_percent(25), on_demand_ttl : 5u32.into(), } -}; + }; let v7 = v7::ActiveConfig::::get() .defensive_proof("Could not decode old config") diff --git a/polkadot/runtime/parachains/src/configuration/tests.rs b/polkadot/runtime/parachains/src/configuration/tests.rs index d88572d3b55..b62a45355e1 100644 --- a/polkadot/runtime/parachains/src/configuration/tests.rs +++ b/polkadot/runtime/parachains/src/configuration/tests.rs @@ -313,7 +313,6 @@ fn setting_pending_config_members() { pvf_voting_ttl: 3, minimum_validation_upgrade_delay: 20, executor_params: Default::default(), - approval_voting_params: ApprovalVotingParams { max_approval_coalesce_count: 1 }, on_demand_queue_max_size: 10_000u32, on_demand_base_fee: 10_000_000u128, on_demand_fee_variability: Perbill::from_percent(3), diff --git a/polkadot/runtime/parachains/src/disputes.rs b/polkadot/runtime/parachains/src/disputes.rs index c2383dad305..cf2e99e7359 100644 --- a/polkadot/runtime/parachains/src/disputes.rs +++ b/polkadot/runtime/parachains/src/disputes.rs @@ -25,11 +25,11 @@ use frame_system::pallet_prelude::*; use parity_scale_codec::{Decode, Encode}; use polkadot_runtime_metrics::get_current_time; use primitives::{ - byzantine_threshold, supermajority_threshold, vstaging::ApprovalVoteMultipleCandidates, - ApprovalVote, CandidateHash, CheckedDisputeStatementSet, CheckedMultiDisputeStatementSet, - CompactStatement, ConsensusLog, DisputeState, DisputeStatement, DisputeStatementSet, - ExplicitDisputeStatement, InvalidDisputeStatementKind, MultiDisputeStatementSet, SessionIndex, - SigningContext, ValidDisputeStatementKind, ValidatorId, ValidatorIndex, ValidatorSignature, + byzantine_threshold, supermajority_threshold, ApprovalVote, CandidateHash, + CheckedDisputeStatementSet, CheckedMultiDisputeStatementSet, CompactStatement, ConsensusLog, + DisputeState, DisputeStatement, DisputeStatementSet, ExplicitDisputeStatement, + InvalidDisputeStatementKind, MultiDisputeStatementSet, SessionIndex, SigningContext, + ValidDisputeStatementKind, ValidatorId, ValidatorIndex, ValidatorSignature, }; use scale_info::TypeInfo; use sp_runtime::{ @@ -952,8 +952,6 @@ impl Pallet { None => return StatementSetFilter::RemoveAll, }; - let config = >::config(); - let n_validators = session_info.validators.len(); // Check for ancient. @@ -1017,14 +1015,7 @@ impl Pallet { set.session, statement, signature, - // This is here to prevent malicious nodes of generating - // `ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates` before that - // is enabled, via setting `max_approval_coalesce_count` in the parachain host - // config. - config.approval_voting_params.max_approval_coalesce_count > 1, ) { - log::warn!("Failed to check dispute signature"); - importer.undo(undo); filter.remove_index(i); continue @@ -1269,31 +1260,22 @@ fn check_signature( session: SessionIndex, statement: &DisputeStatement, validator_signature: &ValidatorSignature, - approval_multiple_candidates_enabled: bool, ) -> Result<(), ()> { - let payload = match statement { + let payload = match *statement { DisputeStatement::Valid(ValidDisputeStatementKind::Explicit) => ExplicitDisputeStatement { valid: true, candidate_hash, session }.signing_payload(), DisputeStatement::Valid(ValidDisputeStatementKind::BackingSeconded(inclusion_parent)) => CompactStatement::Seconded(candidate_hash).signing_payload(&SigningContext { session_index: session, - parent_hash: *inclusion_parent, + parent_hash: inclusion_parent, }), DisputeStatement::Valid(ValidDisputeStatementKind::BackingValid(inclusion_parent)) => CompactStatement::Valid(candidate_hash).signing_payload(&SigningContext { session_index: session, - parent_hash: *inclusion_parent, + parent_hash: inclusion_parent, }), DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalChecking) => ApprovalVote(candidate_hash).signing_payload(session), - DisputeStatement::Valid(ValidDisputeStatementKind::ApprovalCheckingMultipleCandidates( - candidates, - )) => - if approval_multiple_candidates_enabled && candidates.contains(&candidate_hash) { - ApprovalVoteMultipleCandidates(candidates).signing_payload(session) - } else { - return Err(()) - }, DisputeStatement::Invalid(InvalidDisputeStatementKind::Explicit) => ExplicitDisputeStatement { valid: false, candidate_hash, session }.signing_payload(), }; diff --git a/polkadot/runtime/parachains/src/disputes/tests.rs b/polkadot/runtime/parachains/src/disputes/tests.rs index 1f3f00132d6..0757084084f 100644 --- a/polkadot/runtime/parachains/src/disputes/tests.rs +++ b/polkadot/runtime/parachains/src/disputes/tests.rs @@ -1500,8 +1500,7 @@ fn test_check_signature() { candidate_hash, session, &statement_1, - &signed_1, - true, + &signed_1 ) .is_ok()); assert!(check_signature( @@ -1509,8 +1508,7 @@ fn test_check_signature() { candidate_hash, session, &statement_1, - &signed_1, - true + &signed_1 ) .is_err()); assert!(check_signature( @@ -1518,8 +1516,7 @@ fn test_check_signature() { wrong_candidate_hash, session, &statement_1, - &signed_1, - true, + &signed_1 ) .is_err()); assert!(check_signature( @@ -1527,8 +1524,7 @@ fn test_check_signature() { candidate_hash, wrong_session, &statement_1, - &signed_1, - true + &signed_1 ) .is_err()); assert!(check_signature( @@ -1536,8 +1532,7 @@ fn test_check_signature() { candidate_hash, session, &statement_2, - &signed_1, - true, + &signed_1 ) .is_err()); assert!(check_signature( @@ -1545,8 +1540,7 @@ fn test_check_signature() { candidate_hash, session, &statement_3, - &signed_1, - true + &signed_1 ) .is_err()); assert!(check_signature( @@ -1554,8 +1548,7 @@ fn test_check_signature() { candidate_hash, session, &statement_4, - &signed_1, - true + &signed_1 ) .is_err()); assert!(check_signature( @@ -1563,8 +1556,7 @@ fn test_check_signature() { candidate_hash, session, &statement_5, - &signed_1, - true, + &signed_1 ) .is_err()); @@ -1573,8 +1565,7 @@ fn test_check_signature() { candidate_hash, session, &statement_2, - &signed_2, - true, + &signed_2 ) .is_ok()); assert!(check_signature( @@ -1582,8 +1573,7 @@ fn test_check_signature() { candidate_hash, session, &statement_2, - &signed_2, - true, + &signed_2 ) .is_err()); assert!(check_signature( @@ -1591,8 +1581,7 @@ fn test_check_signature() { wrong_candidate_hash, session, &statement_2, - &signed_2, - true, + &signed_2 ) .is_err()); assert!(check_signature( @@ -1600,8 +1589,7 @@ fn test_check_signature() { candidate_hash, wrong_session, &statement_2, - &signed_2, - true + &signed_2 ) .is_err()); assert!(check_signature( @@ -1609,8 +1597,7 @@ fn test_check_signature() { candidate_hash, session, &wrong_statement_2, - &signed_2, - true, + &signed_2 ) .is_err()); assert!(check_signature( @@ -1618,8 +1605,7 @@ fn test_check_signature() { candidate_hash, session, &statement_1, - &signed_2, - true, + &signed_2 ) .is_err()); assert!(check_signature( @@ -1627,8 +1613,7 @@ fn test_check_signature() { candidate_hash, session, &statement_3, - &signed_2, - true, + &signed_2 ) .is_err()); assert!(check_signature( @@ -1636,8 +1621,7 @@ fn test_check_signature() { candidate_hash, session, &statement_4, - &signed_2, - true, + &signed_2 ) .is_err()); assert!(check_signature( @@ -1645,8 +1629,7 @@ fn test_check_signature() { candidate_hash, session, &statement_5, - &signed_2, - true, + &signed_2 ) .is_err()); @@ -1655,8 +1638,7 @@ fn test_check_signature() { candidate_hash, session, &statement_3, - &signed_3, - true, + &signed_3 ) .is_ok()); assert!(check_signature( @@ -1664,8 +1646,7 @@ fn test_check_signature() { candidate_hash, session, &statement_3, - &signed_3, - true, + &signed_3 ) .is_err()); assert!(check_signature( @@ -1673,8 +1654,7 @@ fn test_check_signature() { wrong_candidate_hash, session, &statement_3, - &signed_3, - true, + &signed_3 ) .is_err()); assert!(check_signature( @@ -1682,8 +1662,7 @@ fn test_check_signature() { candidate_hash, wrong_session, &statement_3, - &signed_3, - true, + &signed_3 ) .is_err()); assert!(check_signature( @@ -1691,8 +1670,7 @@ fn test_check_signature() { candidate_hash, session, &wrong_statement_3, - &signed_3, - true, + &signed_3 ) .is_err()); assert!(check_signature( @@ -1700,8 +1678,7 @@ fn test_check_signature() { candidate_hash, session, &statement_1, - &signed_3, - true, + &signed_3 ) .is_err()); assert!(check_signature( @@ -1709,8 +1686,7 @@ fn test_check_signature() { candidate_hash, session, &statement_2, - &signed_3, - true + &signed_3 ) .is_err()); assert!(check_signature( @@ -1718,8 +1694,7 @@ fn test_check_signature() { candidate_hash, session, &statement_4, - &signed_3, - true, + &signed_3 ) .is_err()); assert!(check_signature( @@ -1727,8 +1702,7 @@ fn test_check_signature() { candidate_hash, session, &statement_5, - &signed_3, - true, + &signed_3 ) .is_err()); @@ -1737,8 +1711,7 @@ fn test_check_signature() { candidate_hash, session, &statement_4, - &signed_4, - true, + &signed_4 ) .is_ok()); assert!(check_signature( @@ -1746,8 +1719,7 @@ fn test_check_signature() { candidate_hash, session, &statement_4, - &signed_4, - true, + &signed_4 ) .is_err()); assert!(check_signature( @@ -1755,8 +1727,7 @@ fn test_check_signature() { wrong_candidate_hash, session, &statement_4, - &signed_4, - true, + &signed_4 ) .is_err()); assert!(check_signature( @@ -1764,8 +1735,7 @@ fn test_check_signature() { candidate_hash, wrong_session, &statement_4, - &signed_4, - true, + &signed_4 ) .is_err()); assert!(check_signature( @@ -1773,8 +1743,7 @@ fn test_check_signature() { candidate_hash, session, &statement_1, - &signed_4, - true, + &signed_4 ) .is_err()); assert!(check_signature( @@ -1782,8 +1751,7 @@ fn test_check_signature() { candidate_hash, session, &statement_2, - &signed_4, - true, + &signed_4 ) .is_err()); assert!(check_signature( @@ -1791,8 +1759,7 @@ fn test_check_signature() { candidate_hash, session, &statement_3, - &signed_4, - true, + &signed_4 ) .is_err()); assert!(check_signature( @@ -1800,8 +1767,7 @@ fn test_check_signature() { candidate_hash, session, &statement_5, - &signed_4, - true, + &signed_4 ) .is_err()); @@ -1810,8 +1776,7 @@ fn test_check_signature() { candidate_hash, session, &statement_5, - &signed_5, - true, + &signed_5 ) .is_ok()); assert!(check_signature( @@ -1819,8 +1784,7 @@ fn test_check_signature() { candidate_hash, session, &statement_5, - &signed_5, - true, + &signed_5 ) .is_err()); assert!(check_signature( @@ -1828,8 +1792,7 @@ fn test_check_signature() { wrong_candidate_hash, session, &statement_5, - &signed_5, - true, + &signed_5 ) .is_err()); assert!(check_signature( @@ -1837,8 +1800,7 @@ fn test_check_signature() { candidate_hash, wrong_session, &statement_5, - &signed_5, - true, + &signed_5 ) .is_err()); assert!(check_signature( @@ -1846,8 +1808,7 @@ fn test_check_signature() { candidate_hash, session, &statement_1, - &signed_5, - true, + &signed_5 ) .is_err()); assert!(check_signature( @@ -1855,8 +1816,7 @@ fn test_check_signature() { candidate_hash, session, &statement_2, - &signed_5, - true, + &signed_5 ) .is_err()); assert!(check_signature( @@ -1864,8 +1824,7 @@ fn test_check_signature() { candidate_hash, session, &statement_3, - &signed_5, - true, + &signed_5 ) .is_err()); assert!(check_signature( @@ -1873,8 +1832,7 @@ fn test_check_signature() { candidate_hash, session, &statement_4, - &signed_5, - true, + &signed_5 ) .is_err()); } diff --git a/polkadot/runtime/parachains/src/mock.rs b/polkadot/runtime/parachains/src/mock.rs index 222942922f9..9df54bf29d3 100644 --- a/polkadot/runtime/parachains/src/mock.rs +++ b/polkadot/runtime/parachains/src/mock.rs @@ -25,7 +25,7 @@ use crate::{ }; use frame_support::{ - assert_ok, derive_impl, parameter_types, + assert_ok, parameter_types, traits::{ Currency, ProcessMessage, ProcessMessageError, ValidatorSet, ValidatorSetWithIdentification, }, @@ -94,7 +94,6 @@ parameter_types! { pub type AccountId = u64; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = BlockWeights; diff --git a/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs b/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs index 0da50f6a537..200fd57915f 100644 --- a/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs +++ b/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs @@ -17,10 +17,7 @@ //! Put implementations of functions from staging APIs here. use crate::{configuration, initializer, shared}; -use primitives::{ - vstaging::{ApprovalVotingParams, NodeFeatures}, - ValidatorIndex, -}; +use primitives::{vstaging::NodeFeatures, ValidatorIndex}; use sp_std::{collections::btree_map::BTreeMap, prelude::Vec}; /// Implementation for `DisabledValidators` @@ -50,9 +47,3 @@ where pub fn node_features() -> NodeFeatures { >::config().node_features } - -/// Approval voting subsystem configuration parameteres -pub fn approval_voting_params() -> ApprovalVotingParams { - let config = >::config(); - config.approval_voting_params -} diff --git a/polkadot/runtime/parachains/src/ump_tests.rs b/polkadot/runtime/parachains/src/ump_tests.rs index 426993ffa65..def60888205 100644 --- a/polkadot/runtime/parachains/src/ump_tests.rs +++ b/polkadot/runtime/parachains/src/ump_tests.rs @@ -523,21 +523,21 @@ fn overweight_queue_works() { assert_last_events( [ pallet_message_queue::Event::::Processed { - id: hash_1.into(), + id: hash_1, origin: Ump(UmpQueueId::Para(para_a)), weight_used: Weight::from_parts(301, 301), success: true, } .into(), pallet_message_queue::Event::::OverweightEnqueued { - id: hash_2.into(), + id: hash_2, origin: Ump(UmpQueueId::Para(para_a)), page_index: 0, message_index: 1, } .into(), pallet_message_queue::Event::::OverweightEnqueued { - id: hash_3.into(), + id: hash_3, origin: Ump(UmpQueueId::Para(para_a)), page_index: 0, message_index: 2, @@ -565,7 +565,7 @@ fn overweight_queue_works() { )); assert_last_event( pallet_message_queue::Event::::Processed { - id: hash_3.into(), + id: hash_3, origin: Ump(UmpQueueId::Para(para_a)), weight_used: Weight::from_parts(501, 501), success: true, diff --git a/polkadot/runtime/rococo/Cargo.toml b/polkadot/runtime/rococo/Cargo.toml index c7236572ed7..9693d351cf4 100644 --- a/polkadot/runtime/rococo/Cargo.toml +++ b/polkadot/runtime/rococo/Cargo.toml @@ -7,14 +7,11 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } -serde = { version = "1.0.193", default-features = false } +serde = { version = "1.0.188", default-features = false } serde_derive = { version = "1.0.117", optional = true } static_assertions = "1.1.0" smallvec = "1.8.0" @@ -56,7 +53,7 @@ pallet-collective = { path = "../../../substrate/frame/collective", default-feat 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 } +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 } @@ -108,7 +105,7 @@ xcm-builder = { package = "staging-xcm-builder", path = "../../xcm/xcm-builder", [dev-dependencies] tiny-keccak = { version = "2.0.2", features = ["keccak"] } keyring = { package = "sp-keyring", path = "../../../substrate/primitives/keyring" } -remote-externalities = { package = "frame-remote-externalities", path = "../../../substrate/utils/frame/remote-externalities" } +remote-externalities = { package = "frame-remote-externalities" , path = "../../../substrate/utils/frame/remote-externalities" } sp-trie = { path = "../../../substrate/primitives/trie" } separator = "0.4.1" serde_json = "1.0.108" @@ -119,7 +116,7 @@ tokio = { version = "1.24.2", features = ["macros"] } substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] no_std = [] std = [ "authority-discovery-primitives/std", @@ -316,11 +313,11 @@ try-runtime = [ ] # Set timing constants (e.g. session period) to faster versions to speed up testing. -fast-runtime = ["rococo-runtime-constants/fast-runtime"] +fast-runtime = [ "rococo-runtime-constants/fast-runtime" ] -runtime-metrics = ["runtime-parachains/runtime-metrics", "sp-io/with-tracing"] +runtime-metrics = [ "runtime-parachains/runtime-metrics", "sp-io/with-tracing" ] # A feature that should be enabled when the runtime should be built for on-chain # deployment. This will disable stuff that shouldn't be part of the on-chain wasm # to make it smaller like logging for example. -on-chain-release-build = ["sp-api/disable-logging"] +on-chain-release-build = [ "sp-api/disable-logging" ] diff --git a/polkadot/runtime/rococo/constants/Cargo.toml b/polkadot/runtime/rococo/constants/Cargo.toml index 1e6b0a5f903..8ff6d57ea5b 100644 --- a/polkadot/runtime/rococo/constants/Cargo.toml +++ b/polkadot/runtime/rococo/constants/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] smallvec = "1.8.0" @@ -20,10 +17,9 @@ sp-weights = { path = "../../../../substrate/primitives/weights", default-featur sp-core = { path = "../../../../substrate/primitives/core", default-features = false } xcm = { package = "staging-xcm", path = "../../../xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../xcm/xcm-builder", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "frame-support/std", "primitives/std", @@ -31,7 +27,6 @@ std = [ "sp-core/std", "sp-runtime/std", "sp-weights/std", - "xcm-builder/std", "xcm/std", ] diff --git a/polkadot/runtime/rococo/constants/src/lib.rs b/polkadot/runtime/rococo/constants/src/lib.rs index 4e728421b67..2f641d60fc8 100644 --- a/polkadot/runtime/rococo/constants/src/lib.rs +++ b/polkadot/runtime/rococo/constants/src/lib.rs @@ -103,8 +103,7 @@ pub mod fee { /// System Parachains. pub mod system_parachain { - use primitives::Id; - use xcm_builder::IsChildSystemParachain; + use xcm::latest::prelude::*; /// Network's Asset Hub parachain ID. pub const ASSET_HUB_ID: u32 = 1000; @@ -112,13 +111,14 @@ pub mod system_parachain { pub const CONTRACTS_ID: u32 = 1002; /// Encointer parachain ID. pub const ENCOINTER_ID: u32 = 1003; - /// People parachain ID. - pub const PEOPLE_ID: u32 = 1004; /// BridgeHub parachain ID. pub const BRIDGE_HUB_ID: u32 = 1013; - /// All system parachains of Rococo. - pub type SystemParachains = IsChildSystemParachain; + frame_support::match_types! { + pub type SystemParachains: impl Contains = { + MultiLocation { parents: 0, interior: X1(Parachain(ASSET_HUB_ID | CONTRACTS_ID | ENCOINTER_ID | BRIDGE_HUB_ID)) } + }; + } } /// Rococo Treasury pallet instance. diff --git a/polkadot/runtime/rococo/src/impls.rs b/polkadot/runtime/rococo/src/impls.rs index eddbfacc3b1..71b1091eeb6 100644 --- a/polkadot/runtime/rococo/src/impls.rs +++ b/polkadot/runtime/rococo/src/impls.rs @@ -79,8 +79,6 @@ impl ToParachainIdentityReaper { } } -// Note / Warning: This implementation should only be used in a transactional context. If not, then -// an error could result in assets being burned. impl OnReapIdentity for ToParachainIdentityReaper where Runtime: frame_system::Config + pallet_xcm::Config, @@ -102,19 +100,6 @@ where // Do `check_out` accounting since the XCM Executor's `InitiateTeleport` doesn't support // unpaid teleports. - // withdraw the asset from `who` - let who_origin = - Junction::AccountId32 { network: None, id: who.clone().into() }.into_location(); - let _withdrawn = xcm_config::LocalAssetTransactor::withdraw_asset(&roc, &who_origin, None) - .map_err(|err| { - log::error!( - target: "runtime::on_reap_identity", - "withdraw_asset(what: {:?}, who_origin: {:?}) error: {:?}", - roc, who_origin, err - ); - pallet_xcm::Error::::LowBalance - })?; - // check out xcm_config::LocalAssetTransactor::can_check_out( &destination, @@ -122,14 +107,7 @@ where // not used in AssetTransactor &XcmContext { origin: None, message_id: [0; 32], topic: None }, ) - .map_err(|err| { - log::error!( - target: "runtime::on_reap_identity", - "can_check_out(destination: {:?}, asset: {:?}, _) error: {:?}", - destination, roc, err - ); - pallet_xcm::Error::::CannotCheckOutTeleport - })?; + .map_err(|_| pallet_xcm::Error::::CannotCheckOutTeleport)?; xcm_config::LocalAssetTransactor::check_out( &destination, &roc, diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index 9efa897217d..8d3ff9192b7 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -23,13 +23,12 @@ use pallet_nis::WithMaximumOf; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use primitives::{ - slashing, - vstaging::{ApprovalVotingParams, NodeFeatures}, - AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CandidateHash, - CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, GroupRotationInfo, Hash, - Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, Moment, Nonce, - OccupiedCoreAssumption, PersistedValidationData, ScrapedOnChainVotes, SessionInfo, Signature, - ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, PARACHAIN_KEY_TYPE_ID, + slashing, vstaging::NodeFeatures, AccountId, AccountIndex, Balance, BlockNumber, + CandidateEvent, CandidateHash, CommittedCandidateReceipt, CoreState, DisputeState, + ExecutorParams, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, + InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, + ScrapedOnChainVotes, SessionInfo, Signature, ValidationCode, ValidationCodeHash, ValidatorId, + ValidatorIndex, PARACHAIN_KEY_TYPE_ID, }; use runtime_common::{ assigned_slots, auctions, claims, crowdloan, identity_migrator, impl_runtime_weights, @@ -65,7 +64,7 @@ use beefy_primitives::{ }; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, genesis_builder_helper::{build_config, create_default_config}, parameter_types, traits::{ @@ -79,18 +78,19 @@ use frame_support::{ use frame_system::EnsureRoot; use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId}; use pallet_identity::legacy::IdentityInfo; +use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use pallet_session::historical as session_historical; use pallet_transaction_payment::{CurrencyAdapter, FeeDetails, RuntimeDispatchInfo}; use sp_core::{ConstU128, OpaqueMetadata, H256}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{ - BlakeTwo256, Block as BlockT, ConstU32, ConvertInto, Extrinsic as ExtrinsicT, - IdentityLookup, Keccak256, OpaqueKeys, SaturatedConversion, Verify, + AccountIdLookup, BlakeTwo256, Block as BlockT, ConstU32, ConvertInto, + Extrinsic as ExtrinsicT, IdentityLookup, Keccak256, OpaqueKeys, SaturatedConversion, + Verify, }, transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, BoundToRuntimeAppPublic, FixedU128, KeyTypeId, Perbill, Percent, Permill, - RuntimeAppPublic, RuntimeDebug, + ApplyExtrinsicResult, FixedU128, KeyTypeId, Perbill, Percent, Permill, RuntimeDebug, }; use sp_staking::SessionIndex; #[cfg(any(feature = "std", test))] @@ -150,10 +150,10 @@ 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_005_000, + spec_version: 10020, impl_version: 0, apis: RUNTIME_API_VERSIONS, - transaction_version: 24, + transaction_version: 22, state_version: 1, }; @@ -186,21 +186,29 @@ parameter_types! { pub const SS58Prefix: u8 = 42; } -#[derive_impl(frame_system::config_preludes::RelayChainDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = EverythingBut; type BlockWeights = BlockWeights; type BlockLength = BlockLength; type DbWeight = RocksDbWeight; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; type Nonce = Nonce; type Hash = Hash; + type Hashing = BlakeTwo256; type AccountId = AccountId; + type Lookup = AccountIdLookup; type Block = Block; + type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type Version = Version; + type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); type SystemWeightInfo = weights::frame_system::WeightInfo; type SS58Prefix = SS58Prefix; + type OnSetCode = (); type MaxConsumers = frame_support::traits::ConstU32<16>; } @@ -277,7 +285,8 @@ impl pallet_babe::Config for Runtime { type WeightInfo = (); type MaxAuthorities = MaxAuthorities; type MaxNominators = ConstU32<0>; - type KeyOwnerProof = sp_session::MembershipProof; + type KeyOwnerProof = + >::Proof; type EquivocationReportSystem = pallet_babe::EquivocationReportSystem; } @@ -345,53 +354,14 @@ impl pallet_timestamp::Config for Runtime { impl pallet_authorship::Config for Runtime { type FindAuthor = pallet_session::FindAccountFromAuthorIndex; - type EventHandler = (); -} - -#[derive(Clone, Debug, PartialEq, Eq, Encode, Decode)] -pub struct OldSessionKeys { - pub grandpa: ::Public, - pub babe: ::Public, - pub im_online: pallet_im_online::sr25519::AuthorityId, - pub para_validator: ::Public, - pub para_assignment: ::Public, - pub authority_discovery: ::Public, - pub beefy: ::Public, -} - -impl OpaqueKeys for OldSessionKeys { - type KeyTypeIdProviders = (); - fn key_ids() -> &'static [KeyTypeId] { - &[ - <::Public>::ID, - <::Public>::ID, - sp_core::crypto::key_types::IM_ONLINE, - <::Public>::ID, - <::Public>::ID, - <::Public>::ID, - <::Public>::ID, - ] - } - fn get_raw(&self, i: KeyTypeId) -> &[u8] { - match i { - <::Public>::ID => self.grandpa.as_ref(), - <::Public>::ID => self.babe.as_ref(), - sp_core::crypto::key_types::IM_ONLINE => self.im_online.as_ref(), - <::Public>::ID => self.para_validator.as_ref(), - <::Public>::ID => - self.para_assignment.as_ref(), - <::Public>::ID => - self.authority_discovery.as_ref(), - <::Public>::ID => self.beefy.as_ref(), - _ => &[], - } - } + type EventHandler = ImOnline; } impl_opaque_keys! { pub struct SessionKeys { pub grandpa: Grandpa, pub babe: Babe, + pub im_online: ImOnline, pub para_validator: Initializer, pub para_assignment: ParaSessionInfo, pub authority_discovery: AuthorityDiscovery, @@ -399,18 +369,6 @@ impl_opaque_keys! { } } -// remove this when removing `OldSessionKeys` -fn transform_session_keys(_val: AccountId, old: OldSessionKeys) -> SessionKeys { - SessionKeys { - grandpa: old.grandpa, - babe: old.babe, - para_validator: old.para_validator, - para_assignment: old.para_assignment, - authority_discovery: old.authority_discovery, - beefy: old.beefy, - } -} - /// Special `ValidatorIdOf` implementation that is just returning the input as result. pub struct ValidatorIdOf; impl sp_runtime::traits::Convert> for ValidatorIdOf { @@ -555,6 +513,22 @@ impl pallet_authority_discovery::Config for Runtime { type MaxAuthorities = MaxAuthorities; } +parameter_types! { + pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value(); +} + +impl pallet_im_online::Config for Runtime { + type AuthorityId = ImOnlineId; + type RuntimeEvent = RuntimeEvent; + type ValidatorSet = Historical; + type NextSessionRotation = Babe; + type ReportUnresponsiveness = Offences; + type UnsignedPriority = ImOnlineUnsignedPriority; + type WeightInfo = weights::pallet_im_online::WeightInfo; + type MaxKeys = MaxKeys; + type MaxPeerInHeartbeats = MaxPeerInHeartbeats; +} + parameter_types! { pub const MaxSetIdSessionEntries: u32 = BondingDuration::get() * SessionsPerEra::get(); } @@ -565,7 +539,7 @@ impl pallet_grandpa::Config for Runtime { type MaxAuthorities = MaxAuthorities; type MaxNominators = ConstU32<0>; type MaxSetIdSessionEntries = MaxSetIdSessionEntries; - type KeyOwnerProof = sp_session::MembershipProof; + type KeyOwnerProof = >::Proof; type EquivocationReportSystem = pallet_grandpa::EquivocationReportSystem; } @@ -746,7 +720,6 @@ impl pallet_vesting::Config for Runtime { type MinVestedTransfer = MinVestedTransfer; type WeightInfo = weights::pallet_vesting::WeightInfo; type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; - type BlockNumberProvider = System; const MAX_VESTING_SCHEDULES: u32 = 28; } @@ -806,6 +779,7 @@ impl InstanceFilter for ProxyType { // Specifically omitting the entire Balances pallet RuntimeCall::Session(..) | RuntimeCall::Grandpa(..) | + RuntimeCall::ImOnline(..) | RuntimeCall::Treasury(..) | RuntimeCall::Bounties(..) | RuntimeCall::ChildBounties(..) | @@ -1319,7 +1293,8 @@ construct_runtime! { TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 33, // Consensus support. - // Authorship must be before session in order to note author in the correct session and era. + // Authorship must be before session in order to note author in the correct session and era + // for im-online. Authorship: pallet_authorship::{Pallet, Storage} = 5, Offences: pallet_offences::{Pallet, Storage, Event} = 7, Historical: session_historical::{Pallet} = 34, @@ -1333,6 +1308,7 @@ construct_runtime! { Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 8, Grandpa: pallet_grandpa::{Pallet, Call, Storage, Config, Event, ValidateUnsigned} = 10, + ImOnline: pallet_im_online::{Pallet, Call, Storage, Event, ValidateUnsigned, Config} = 11, AuthorityDiscovery: pallet_authority_discovery::{Pallet, Config} = 12, // Governance stuff; uncallable initially. @@ -1478,8 +1454,6 @@ pub mod migrations { use frame_support::traits::LockIdentifier; use frame_system::pallet_prelude::BlockNumberFor; - #[cfg(feature = "try-runtime")] - use sp_core::crypto::ByteArray; parameter_types! { pub const DemocracyPalletName: &'static str = "Democracy"; @@ -1488,7 +1462,6 @@ pub mod migrations { pub const PhragmenElectionPalletName: &'static str = "PhragmenElection"; pub const TechnicalMembershipPalletName: &'static str = "TechnicalMembership"; pub const TipsPalletName: &'static str = "Tips"; - pub const ImOnlinePalletName: &'static str = "ImOnline"; pub const PhragmenElectionPalletId: LockIdentifier = *b"phrelect"; } @@ -1525,82 +1498,10 @@ pub mod migrations { type PalletName = TipsPalletName; } - /// Upgrade Session keys to exclude `ImOnline` key. - /// When this is removed, should also remove `OldSessionKeys`. - pub struct UpgradeSessionKeys; - const UPGRADE_SESSION_KEYS_FROM_SPEC: u32 = 104000; - - impl frame_support::traits::OnRuntimeUpgrade for UpgradeSessionKeys { - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { - if System::last_runtime_upgrade_spec_version() > UPGRADE_SESSION_KEYS_FROM_SPEC { - log::warn!(target: "runtime::session_keys", "Skipping session keys migration pre-upgrade check due to spec version (already applied?)"); - return Ok(Vec::new()) - } - - log::info!(target: "runtime::session_keys", "Collecting pre-upgrade session keys state"); - let key_ids = SessionKeys::key_ids(); - frame_support::ensure!( - key_ids.into_iter().find(|&k| *k == sp_core::crypto::key_types::IM_ONLINE) == None, - "New session keys contain the ImOnline key that should have been removed", - ); - let storage_key = pallet_session::QueuedKeys::::hashed_key(); - let mut state: Vec = Vec::new(); - frame_support::storage::unhashed::get::>( - &storage_key, - ) - .ok_or::("Queued keys are not available".into())? - .into_iter() - .for_each(|(id, keys)| { - state.extend_from_slice(id.as_slice()); - for key_id in key_ids { - state.extend_from_slice(keys.get_raw(*key_id)); - } - }); - frame_support::ensure!(state.len() > 0, "Queued keys are not empty before upgrade"); - Ok(state) - } - - fn on_runtime_upgrade() -> Weight { - if System::last_runtime_upgrade_spec_version() > UPGRADE_SESSION_KEYS_FROM_SPEC { - log::info!("Skipping session keys upgrade: already applied"); - return ::DbWeight::get().reads(1) - } - log::trace!("Upgrading session keys"); - Session::upgrade_keys::(transform_session_keys); - Perbill::from_percent(50) * BlockWeights::get().max_block - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade( - old_state: sp_std::vec::Vec, - ) -> Result<(), sp_runtime::TryRuntimeError> { - if System::last_runtime_upgrade_spec_version() > UPGRADE_SESSION_KEYS_FROM_SPEC { - log::warn!(target: "runtime::session_keys", "Skipping session keys migration post-upgrade check due to spec version (already applied?)"); - return Ok(()) - } - - let key_ids = SessionKeys::key_ids(); - let mut new_state: Vec = Vec::new(); - pallet_session::QueuedKeys::::get().into_iter().for_each(|(id, keys)| { - new_state.extend_from_slice(id.as_slice()); - for key_id in key_ids { - new_state.extend_from_slice(keys.get_raw(*key_id)); - } - }); - frame_support::ensure!(new_state.len() > 0, "Queued keys are not empty after upgrade"); - frame_support::ensure!( - old_state == new_state, - "Pre-upgrade and post-upgrade keys do not match!" - ); - log::info!(target: "runtime::session_keys", "Session keys migrated successfully"); - Ok(()) - } - } - /// Unreleased migrations. Add new ones here: pub type Unreleased = ( pallet_society::migrations::MigrateToV2, + pallet_im_online::migration::v1::Migration, parachains_configuration::migration::v7::MigrateToV7, assigned_slots::migration::v1::MigrateToV1, parachains_scheduler::migration::v1::MigrateToV1, @@ -1627,13 +1528,6 @@ pub mod migrations { pallet_grandpa::migrations::MigrateV4ToV5, parachains_configuration::migration::v10::MigrateToV10, - - // Upgrade `SessionKeys` to exclude `ImOnline` - UpgradeSessionKeys, - - // Remove `im-online` pallet on-chain storage - frame_support::migrations::RemovePallet::DbWeight>, - parachains_configuration::migration::v11::MigrateToV11, ); } @@ -1704,6 +1598,7 @@ mod benches { [pallet_conviction_voting, ConvictionVoting] [pallet_nis, Nis] [pallet_identity, Identity] + [pallet_im_online, ImOnline] [pallet_indices, Indices] [pallet_message_queue, MessageQueue] [pallet_multisig, Multisig] @@ -1795,8 +1690,8 @@ sp_api::impl_runtime_apis! { } } - #[api_version(10)] - impl primitives::runtime_api::ParachainHost for Runtime { + #[api_version(9)] + impl primitives::runtime_api::ParachainHost for Runtime { fn validators() -> Vec { parachains_runtime_api_impl::validators::() } @@ -1939,10 +1834,6 @@ sp_api::impl_runtime_apis! { parachains_runtime_api_impl::async_backing_params::() } - fn approval_voting_params() -> ApprovalVotingParams { - parachains_staging_runtime_api_impl::approval_voting_params::() - } - fn disabled_validators() -> Vec { parachains_staging_runtime_api_impl::disabled_validators::() } @@ -2268,20 +2159,6 @@ sp_api::impl_runtime_apis! { Parachain(43211234).into(), )) } - - fn set_up_complex_asset_transfer( - ) -> Option<(MultiAssets, u32, MultiLocation, Box)> { - // Relay supports only native token, either reserve transfer it to non-system parachains, - // or teleport it to system parachain. Use the teleport case for benchmarking as it's - // slightly heavier. - // Relay/native token can be teleported to/from AH. - let native_location = Here.into(); - let dest = crate::xcm_config::AssetHub::get(); - pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::( - native_location, - dest - ) - } } impl pallet_xcm_benchmarks::Config for Runtime { type XcmConfig = XcmConfig; diff --git a/polkadot/runtime/rococo/src/weights/pallet_xcm.rs b/polkadot/runtime/rococo/src/weights/pallet_xcm.rs index 177407ef708..aafded3f731 100644 --- a/polkadot/runtime/rococo/src/weights/pallet_xcm.rs +++ b/polkadot/runtime/rococo/src/weights/pallet_xcm.rs @@ -48,10 +48,6 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { - fn transfer_assets() -> Weight { - // TODO: run benchmarks - Weight::zero() - } /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) diff --git a/polkadot/runtime/rococo/src/xcm_config.rs b/polkadot/runtime/rococo/src/xcm_config.rs index e5edba2570c..c8f8f59dae9 100644 --- a/polkadot/runtime/rococo/src/xcm_config.rs +++ b/polkadot/runtime/rococo/src/xcm_config.rs @@ -36,16 +36,15 @@ use runtime_common::{ }; use sp_core::ConstU32; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter as XcmCurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, - ChildParachainConvertsVia, DescribeBodyTerminal, DescribeFamily, FixedWeightBounds, - HashedDescription, IsChildSystemParachain, IsConcrete, MintLocation, OriginToPluralityVoice, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, - XcmFeeManagerFromComponents, XcmFeeToAccount, + ChildParachainConvertsVia, CurrencyAdapter as XcmCurrencyAdapter, DescribeBodyTerminal, + DescribeFamily, FixedWeightBounds, HashedDescription, IsChildSystemParachain, IsConcrete, + MintLocation, OriginToPluralityVoice, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, + WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, + XcmFeeToAccount, }; use xcm_executor::XcmExecutor; @@ -71,7 +70,6 @@ pub type LocationConverter = ( /// point of view of XCM-only concepts like `MultiLocation` and `MultiAsset`. /// /// Ours is only aware of the Balances pallet, which is mapped to `RocLocation`. -#[allow(deprecated)] pub type LocalAssetTransactor = XcmCurrencyAdapter< // Use this currency: Balances, diff --git a/polkadot/runtime/test-runtime/Cargo.toml b/polkadot/runtime/test-runtime/Cargo.toml index 585f16ac86f..29debad7b53 100644 --- a/polkadot/runtime/test-runtime/Cargo.toml +++ b/polkadot/runtime/test-runtime/Cargo.toml @@ -7,16 +7,13 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } rustc-hex = { version = "2.1.0", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false } +serde = { version = "1.0.188", default-features = false } serde_derive = { version = "1.0.117", optional = true } smallvec = "1.8.0" @@ -80,7 +77,7 @@ serde_json = "1.0.108" substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder" } [features] -default = ["std"] +default = [ "std" ] no_std = [] only-staking = [] runtime-metrics = [ diff --git a/polkadot/runtime/test-runtime/constants/Cargo.toml b/polkadot/runtime/test-runtime/constants/Cargo.toml index 2b387bbd307..d83e92a6ce8 100644 --- a/polkadot/runtime/test-runtime/constants/Cargo.toml +++ b/polkadot/runtime/test-runtime/constants/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] smallvec = "1.8.0" @@ -20,7 +17,7 @@ sp-weights = { path = "../../../../substrate/primitives/weights", default-featur sp-core = { path = "../../../../substrate/primitives/core", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "frame-support/std", "primitives/std", diff --git a/polkadot/runtime/test-runtime/src/lib.rs b/polkadot/runtime/test-runtime/src/lib.rs index d24cd7d332d..4b071ef79d2 100644 --- a/polkadot/runtime/test-runtime/src/lib.rs +++ b/polkadot/runtime/test-runtime/src/lib.rs @@ -42,10 +42,10 @@ use frame_election_provider_support::{ onchain, SequentialPhragmen, }; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, genesis_builder_helper::{build_config, create_default_config}, parameter_types, - traits::{KeyOwnerProofSystem, WithdrawReasons}, + traits::{Everything, KeyOwnerProofSystem, WithdrawReasons}, }; use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId}; use pallet_session::historical as session_historical; @@ -139,19 +139,29 @@ parameter_types! { pub const SS58Prefix: u8 = 42; } -#[derive_impl(frame_system::config_preludes::RelayChainDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { + type BaseCallFilter = Everything; type BlockWeights = BlockWeights; type BlockLength = BlockLength; + type DbWeight = (); + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; type Nonce = Nonce; type Hash = HashT; + type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = Indices; type Block = Block; + type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type Version = Version; + type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); type SS58Prefix = SS58Prefix; + type OnSetCode = (); type MaxConsumers = frame_support::traits::ConstU32<16>; } @@ -356,7 +366,6 @@ impl pallet_staking::Config for Runtime { type TargetList = pallet_staking::UseValidatorsMap; type NominationsQuota = pallet_staking::FixedNominationsQuota; type MaxUnlockingChunks = frame_support::traits::ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<5900>; type HistoryDepth = frame_support::traits::ConstU32<84>; type BenchmarkingConfig = runtime_common::StakingBenchmarkingConfig; type EventListeners = (); @@ -465,7 +474,6 @@ impl pallet_vesting::Config for Runtime { type MinVestedTransfer = MinVestedTransfer; type WeightInfo = (); type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; - type BlockNumberProvider = System; const MAX_VESTING_SCHEDULES: u32 = 28; } @@ -819,7 +827,7 @@ sp_api::impl_runtime_apis! { } } - impl primitives::runtime_api::ParachainHost for Runtime { + impl primitives::runtime_api::ParachainHost for Runtime { fn validators() -> Vec { runtime_impl::validators::() } diff --git a/polkadot/runtime/westend/Cargo.toml b/polkadot/runtime/westend/Cargo.toml index 335ac14d47a..eaebf01e3a7 100644 --- a/polkadot/runtime/westend/Cargo.toml +++ b/polkadot/runtime/westend/Cargo.toml @@ -7,16 +7,13 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } rustc-hex = { version = "2.1.0", default-features = false } -serde = { version = "1.0.193", default-features = false } +serde = { version = "1.0.188", default-features = false } serde_derive = { version = "1.0.117", optional = true } smallvec = "1.8.0" @@ -49,7 +46,7 @@ frame-support = { path = "../../../substrate/frame/support", default-features = 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-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 } @@ -120,7 +117,7 @@ hex-literal = "0.4.1" tiny-keccak = { version = "2.0.2", features = ["keccak"] } keyring = { package = "sp-keyring", path = "../../../substrate/primitives/keyring" } serde_json = "1.0.108" -remote-externalities = { package = "frame-remote-externalities", path = "../../../substrate/utils/frame/remote-externalities" } +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 } @@ -128,7 +125,7 @@ sp-tracing = { path = "../../../substrate/primitives/tracing", default-features substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder" } [features] -default = ["std"] +default = [ "std" ] no_std = [] only-staking = [] std = [ @@ -342,9 +339,9 @@ try-runtime = [ # Set timing constants (e.g. session period) to faster versions to speed up testing. fast-runtime = [] -runtime-metrics = ["runtime-parachains/runtime-metrics", "sp-io/with-tracing"] +runtime-metrics = [ "runtime-parachains/runtime-metrics", "sp-io/with-tracing" ] # A feature that should be enabled when the runtime should be built for on-chain # deployment. This will disable stuff that shouldn't be part of the on-chain wasm # to make it smaller like logging for example. -on-chain-release-build = ["sp-api/disable-logging"] +on-chain-release-build = [ "sp-api/disable-logging" ] diff --git a/polkadot/runtime/westend/constants/Cargo.toml b/polkadot/runtime/westend/constants/Cargo.toml index d2e86970e50..2243210975b 100644 --- a/polkadot/runtime/westend/constants/Cargo.toml +++ b/polkadot/runtime/westend/constants/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] smallvec = "1.8.0" @@ -20,10 +17,9 @@ sp-weights = { path = "../../../../substrate/primitives/weights", default-featur sp-core = { path = "../../../../substrate/primitives/core", default-features = false } xcm = { package = "staging-xcm", path = "../../../xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../xcm/xcm-builder", default-features = false } [features] -default = ["std"] +default = [ "std" ] std = [ "frame-support/std", "primitives/std", @@ -31,6 +27,5 @@ std = [ "sp-core/std", "sp-runtime/std", "sp-weights/std", - "xcm-builder/std", "xcm/std", ] diff --git a/polkadot/runtime/westend/constants/src/lib.rs b/polkadot/runtime/westend/constants/src/lib.rs index c2bce3a1791..a06b3ba602a 100644 --- a/polkadot/runtime/westend/constants/src/lib.rs +++ b/polkadot/runtime/westend/constants/src/lib.rs @@ -98,8 +98,7 @@ pub mod fee { /// System Parachains. pub mod system_parachain { - use primitives::Id; - use xcm_builder::IsChildSystemParachain; + use xcm::latest::prelude::*; /// Network's Asset Hub parachain ID. pub const ASSET_HUB_ID: u32 = 1000; @@ -108,8 +107,11 @@ pub mod system_parachain { /// BridgeHub parachain ID. pub const BRIDGE_HUB_ID: u32 = 1002; - /// All system parachains of Westend. - pub type SystemParachains = IsChildSystemParachain; + frame_support::match_types! { + pub type SystemParachains: impl Contains = { + MultiLocation { parents: 0, interior: X1(Parachain(ASSET_HUB_ID | COLLECTIVES_ID | BRIDGE_HUB_ID ))} + }; + } } /// Westend Treasury pallet instance. @@ -124,7 +126,6 @@ pub mod xcm { const ROOT_INDEX: u32 = 0; // The bodies corresponding to the Polkadot OpenGov Origins. pub const FELLOWSHIP_ADMIN_INDEX: u32 = 1; - pub const TREASURER_INDEX: u32 = 2; } } diff --git a/polkadot/runtime/westend/src/impls.rs b/polkadot/runtime/westend/src/impls.rs index 5f23bd373b1..80105594965 100644 --- a/polkadot/runtime/westend/src/impls.rs +++ b/polkadot/runtime/westend/src/impls.rs @@ -79,8 +79,6 @@ impl ToParachainIdentityReaper { } } -// Note / Warning: This implementation should only be used in a transactional context. If not, then -// an error could result in assets being burned. impl OnReapIdentity for ToParachainIdentityReaper where Runtime: frame_system::Config + pallet_xcm::Config, @@ -102,19 +100,6 @@ where // Do `check_out` accounting since the XCM Executor's `InitiateTeleport` doesn't support // unpaid teleports. - // withdraw the asset from `who` - let who_origin = - Junction::AccountId32 { network: None, id: who.clone().into() }.into_location(); - let _withdrawn = xcm_config::LocalAssetTransactor::withdraw_asset(&wnd, &who_origin, None) - .map_err(|err| { - log::error!( - target: "runtime::on_reap_identity", - "withdraw_asset(what: {:?}, who_origin: {:?}) error: {:?}", - wnd, who_origin, err - ); - pallet_xcm::Error::::LowBalance - })?; - // check out xcm_config::LocalAssetTransactor::can_check_out( &destination, @@ -122,14 +107,7 @@ where // not used in AssetTransactor &XcmContext { origin: None, message_id: [0; 32], topic: None }, ) - .map_err(|err| { - log::error!( - target: "runtime::on_reap_identity", - "can_check_out(destination: {:?}, asset: {:?}, _) error: {:?}", - destination, wnd, err - ); - pallet_xcm::Error::::CannotCheckOutTeleport - })?; + .map_err(|_| pallet_xcm::Error::::CannotCheckOutTeleport)?; xcm_config::LocalAssetTransactor::check_out( &destination, &wnd, diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index ac75be08c55..d147dfdbfdf 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -27,7 +27,7 @@ use beefy_primitives::{ }; use frame_election_provider_support::{bounds::ElectionBoundsBuilder, onchain, SequentialPhragmen}; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, genesis_builder_helper::{build_config, create_default_config}, parameter_types, traits::{ @@ -41,18 +41,17 @@ use frame_support::{ use frame_system::EnsureRoot; use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId}; use pallet_identity::legacy::IdentityInfo; +use pallet_im_online::sr25519::AuthorityId as ImOnlineId; use pallet_session::historical as session_historical; use pallet_transaction_payment::{CurrencyAdapter, FeeDetails, RuntimeDispatchInfo}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; use primitives::{ - slashing, - vstaging::{ApprovalVotingParams, NodeFeatures}, - AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CandidateHash, - CommittedCandidateReceipt, CoreState, DisputeState, ExecutorParams, GroupRotationInfo, Hash, - Id as ParaId, InboundDownwardMessage, InboundHrmpMessage, Moment, Nonce, - OccupiedCoreAssumption, PersistedValidationData, PvfCheckStatement, ScrapedOnChainVotes, - SessionInfo, Signature, ValidationCode, ValidationCodeHash, ValidatorId, ValidatorIndex, - ValidatorSignature, PARACHAIN_KEY_TYPE_ID, + slashing, vstaging::NodeFeatures, AccountId, AccountIndex, Balance, BlockNumber, + CandidateEvent, CandidateHash, CommittedCandidateReceipt, CoreState, DisputeState, + ExecutorParams, GroupRotationInfo, Hash, Id as ParaId, InboundDownwardMessage, + InboundHrmpMessage, Moment, Nonce, OccupiedCoreAssumption, PersistedValidationData, + PvfCheckStatement, ScrapedOnChainVotes, SessionInfo, Signature, ValidationCode, + ValidationCodeHash, ValidatorId, ValidatorIndex, ValidatorSignature, PARACHAIN_KEY_TYPE_ID, }; use runtime_common::{ assigned_slots, auctions, crowdloan, @@ -85,12 +84,11 @@ use sp_runtime::{ curve::PiecewiseLinear, generic, impl_opaque_keys, traits::{ - BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic as ExtrinsicT, IdentityLookup, - Keccak256, OpaqueKeys, SaturatedConversion, Verify, + AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, Extrinsic as ExtrinsicT, + IdentityLookup, Keccak256, OpaqueKeys, SaturatedConversion, Verify, }, transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, BoundToRuntimeAppPublic, FixedU128, KeyTypeId, Perbill, Percent, Permill, - RuntimeAppPublic, + ApplyExtrinsicResult, FixedU128, KeyTypeId, Perbill, Percent, Permill, }; use sp_staking::SessionIndex; use sp_std::{collections::btree_map::BTreeMap, prelude::*}; @@ -147,10 +145,10 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("westend"), impl_name: create_runtime_str!("parity-westend"), authoring_version: 2, - spec_version: 1_005_000, + spec_version: 10020, impl_version: 0, apis: RUNTIME_API_VERSIONS, - transaction_version: 24, + transaction_version: 22, state_version: 1, }; @@ -183,21 +181,29 @@ parameter_types! { pub const SS58Prefix: u8 = 42; } -#[derive_impl(frame_system::config_preludes::RelayChainDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = EverythingBut; type BlockWeights = BlockWeights; type BlockLength = BlockLength; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; type Nonce = Nonce; type Hash = Hash; + type Hashing = BlakeTwo256; type AccountId = AccountId; + type Lookup = AccountIdLookup; type Block = Block; + type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type DbWeight = RocksDbWeight; type Version = Version; + type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); type SystemWeightInfo = weights::frame_system::WeightInfo; type SS58Prefix = SS58Prefix; + type OnSetCode = (); type MaxConsumers = frame_support::traits::ConstU32<16>; } @@ -266,7 +272,8 @@ impl pallet_babe::Config for Runtime { type MaxAuthorities = MaxAuthorities; type MaxNominators = MaxNominators; - type KeyOwnerProof = sp_session::MembershipProof; + type KeyOwnerProof = + >::Proof; type EquivocationReportSystem = pallet_babe::EquivocationReportSystem; @@ -318,7 +325,7 @@ impl pallet_beefy::Config for Runtime { type MaxSetIdSessionEntries = BeefySetIdSessionEntries; type OnNewValidatorSet = BeefyMmrLeaf; type WeightInfo = (); - type KeyOwnerProof = sp_session::MembershipProof; + type KeyOwnerProof = >::Proof; type EquivocationReportSystem = pallet_beefy::EquivocationReportSystem; } @@ -410,7 +417,7 @@ impl pallet_timestamp::Config for Runtime { impl pallet_authorship::Config for Runtime { type FindAuthor = pallet_session::FindAccountFromAuthorIndex; - type EventHandler = Staking; + type EventHandler = (Staking, ImOnline); } parameter_types! { @@ -418,50 +425,11 @@ parameter_types! { pub const Offset: BlockNumber = 0; } -#[derive(Clone, Debug, PartialEq, Eq, Encode, Decode)] -pub struct OldSessionKeys { - pub grandpa: ::Public, - pub babe: ::Public, - pub im_online: pallet_im_online::sr25519::AuthorityId, - pub para_validator: ::Public, - pub para_assignment: ::Public, - pub authority_discovery: ::Public, - pub beefy: ::Public, -} - -impl OpaqueKeys for OldSessionKeys { - type KeyTypeIdProviders = (); - fn key_ids() -> &'static [KeyTypeId] { - &[ - <::Public>::ID, - <::Public>::ID, - sp_core::crypto::key_types::IM_ONLINE, - <::Public>::ID, - <::Public>::ID, - <::Public>::ID, - <::Public>::ID, - ] - } - fn get_raw(&self, i: KeyTypeId) -> &[u8] { - match i { - <::Public>::ID => self.grandpa.as_ref(), - <::Public>::ID => self.babe.as_ref(), - sp_core::crypto::key_types::IM_ONLINE => self.im_online.as_ref(), - <::Public>::ID => self.para_validator.as_ref(), - <::Public>::ID => - self.para_assignment.as_ref(), - <::Public>::ID => - self.authority_discovery.as_ref(), - <::Public>::ID => self.beefy.as_ref(), - _ => &[], - } - } -} - impl_opaque_keys! { pub struct SessionKeys { pub grandpa: Grandpa, pub babe: Babe, + pub im_online: ImOnline, pub para_validator: Initializer, pub para_assignment: ParaSessionInfo, pub authority_discovery: AuthorityDiscovery, @@ -469,18 +437,6 @@ impl_opaque_keys! { } } -// remove this when removing `OldSessionKeys` -fn transform_session_keys(_v: AccountId, old: OldSessionKeys) -> SessionKeys { - SessionKeys { - grandpa: old.grandpa, - babe: old.babe, - para_validator: old.para_validator, - para_assignment: old.para_assignment, - authority_discovery: old.authority_discovery, - beefy: old.beefy, - } -} - impl pallet_session::Config for Runtime { type RuntimeEvent = RuntimeEvent; type ValidatorId = AccountId; @@ -674,7 +630,6 @@ parameter_types! { pub const MaxNominators: u32 = 64; pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(17); pub const MaxNominations: u32 = ::LIMIT as u32; - pub const MaxControllersInDeprecationBatch: u32 = 751; } impl pallet_staking::Config for Runtime { @@ -689,7 +644,7 @@ impl pallet_staking::Config for Runtime { type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; type SlashDeferDuration = SlashDeferDuration; - type AdminOrigin = EitherOf, StakingAdmin>; + type AdminOrigin = EnsureRoot; type SessionInterface = Self; type EraPayout = pallet_staking::ConvertCurve; type MaxExposurePageSize = MaxExposurePageSize; @@ -702,7 +657,6 @@ impl pallet_staking::Config for Runtime { type NominationsQuota = pallet_staking::FixedNominationsQuota<{ MaxNominations::get() }>; type MaxUnlockingChunks = frame_support::traits::ConstU32<32>; type HistoryDepth = frame_support::traits::ConstU32<84>; - type MaxControllersInDeprecationBatch = MaxControllersInDeprecationBatch; type BenchmarkingConfig = runtime_common::StakingBenchmarkingConfig; type EventListeners = NominationPools; type WeightInfo = weights::pallet_staking::WeightInfo; @@ -790,6 +744,19 @@ impl pallet_authority_discovery::Config for Runtime { parameter_types! { pub const NposSolutionPriority: TransactionPriority = TransactionPriority::max_value() / 2; + pub const ImOnlineUnsignedPriority: TransactionPriority = TransactionPriority::max_value(); +} + +impl pallet_im_online::Config for Runtime { + type AuthorityId = ImOnlineId; + type RuntimeEvent = RuntimeEvent; + type ValidatorSet = Historical; + type NextSessionRotation = Babe; + type ReportUnresponsiveness = Offences; + type UnsignedPriority = ImOnlineUnsignedPriority; + type WeightInfo = weights::pallet_im_online::WeightInfo; + type MaxKeys = MaxKeys; + type MaxPeerInHeartbeats = MaxPeerInHeartbeats; } parameter_types! { @@ -804,7 +771,7 @@ impl pallet_grandpa::Config for Runtime { type MaxNominators = MaxNominators; type MaxSetIdSessionEntries = MaxSetIdSessionEntries; - type KeyOwnerProof = sp_session::MembershipProof; + type KeyOwnerProof = >::Proof; type EquivocationReportSystem = pallet_grandpa::EquivocationReportSystem; @@ -953,7 +920,6 @@ impl pallet_vesting::Config for Runtime { type MinVestedTransfer = MinVestedTransfer; type WeightInfo = weights::pallet_vesting::WeightInfo; type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; - type BlockNumberProvider = System; const MAX_VESTING_SCHEDULES: u32 = 28; } @@ -1021,6 +987,7 @@ impl InstanceFilter for ProxyType { RuntimeCall::Staking(..) | RuntimeCall::Session(..) | RuntimeCall::Grandpa(..) | + RuntimeCall::ImOnline(..) | RuntimeCall::Utility(..) | RuntimeCall::Identity(..) | RuntimeCall::ConvictionVoting(..) | @@ -1408,7 +1375,8 @@ construct_runtime! { TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 26, // Consensus support. - // Authorship must be before session in order to note author in the correct session and era. + // Authorship must be before session in order to note author in the correct session and era + // for im-online and staking. Authorship: pallet_authorship::{Pallet, Storage} = 5, Staking: pallet_staking::{Pallet, Call, Storage, Config, Event} = 6, Offences: pallet_offences::{Pallet, Storage, Event} = 7, @@ -1423,6 +1391,7 @@ construct_runtime! { Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 8, Grandpa: pallet_grandpa::{Pallet, Call, Storage, Config, Event, ValidateUnsigned} = 10, + ImOnline: pallet_im_online::{Pallet, Call, Storage, Event, ValidateUnsigned, Config} = 11, AuthorityDiscovery: pallet_authority_discovery::{Pallet, Config} = 12, // Utility module. @@ -1554,88 +1523,10 @@ pub type Migrations = migrations::Unreleased; #[allow(deprecated, missing_docs)] pub mod migrations { use super::*; - #[cfg(feature = "try-runtime")] - use sp_core::crypto::ByteArray; - - parameter_types! { - pub const ImOnlinePalletName: &'static str = "ImOnline"; - } - - /// Upgrade Session keys to exclude `ImOnline` key. - /// When this is removed, should also remove `OldSessionKeys`. - pub struct UpgradeSessionKeys; - const UPGRADE_SESSION_KEYS_FROM_SPEC: u32 = 104000; - - impl frame_support::traits::OnRuntimeUpgrade for UpgradeSessionKeys { - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { - if System::last_runtime_upgrade_spec_version() > UPGRADE_SESSION_KEYS_FROM_SPEC { - log::warn!(target: "runtime::session_keys", "Skipping session keys migration pre-upgrade check due to spec version (already applied?)"); - return Ok(Vec::new()) - } - - log::info!(target: "runtime::session_keys", "Collecting pre-upgrade session keys state"); - let key_ids = SessionKeys::key_ids(); - frame_support::ensure!( - key_ids.into_iter().find(|&k| *k == sp_core::crypto::key_types::IM_ONLINE) == None, - "New session keys contain the ImOnline key that should have been removed", - ); - let storage_key = pallet_session::QueuedKeys::::hashed_key(); - let mut state: Vec = Vec::new(); - frame_support::storage::unhashed::get::>( - &storage_key, - ) - .ok_or::("Queued keys are not available".into())? - .into_iter() - .for_each(|(id, keys)| { - state.extend_from_slice(id.as_slice()); - for key_id in key_ids { - state.extend_from_slice(keys.get_raw(*key_id)); - } - }); - frame_support::ensure!(state.len() > 0, "Queued keys are not empty before upgrade"); - Ok(state) - } - - fn on_runtime_upgrade() -> Weight { - if System::last_runtime_upgrade_spec_version() > UPGRADE_SESSION_KEYS_FROM_SPEC { - log::warn!("Skipping session keys upgrade: already applied"); - return ::DbWeight::get().reads(1) - } - log::info!("Upgrading session keys"); - Session::upgrade_keys::(transform_session_keys); - Perbill::from_percent(50) * BlockWeights::get().max_block - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade( - old_state: sp_std::vec::Vec, - ) -> Result<(), sp_runtime::TryRuntimeError> { - if System::last_runtime_upgrade_spec_version() > UPGRADE_SESSION_KEYS_FROM_SPEC { - log::warn!(target: "runtime::session_keys", "Skipping session keys migration post-upgrade check due to spec version (already applied?)"); - return Ok(()) - } - - let key_ids = SessionKeys::key_ids(); - let mut new_state: Vec = Vec::new(); - pallet_session::QueuedKeys::::get().into_iter().for_each(|(id, keys)| { - new_state.extend_from_slice(id.as_slice()); - for key_id in key_ids { - new_state.extend_from_slice(keys.get_raw(*key_id)); - } - }); - frame_support::ensure!(new_state.len() > 0, "Queued keys are not empty after upgrade"); - frame_support::ensure!( - old_state == new_state, - "Pre-upgrade and post-upgrade keys do not match!" - ); - log::info!(target: "runtime::session_keys", "Session keys migrated successfully"); - Ok(()) - } - } /// Unreleased migrations. Add new ones here: pub type Unreleased = ( + pallet_im_online::migration::v1::Migration, parachains_configuration::migration::v7::MigrateToV7, pallet_staking::migrations::v14::MigrateToV14, assigned_slots::migration::v1::MigrateToV1, @@ -1643,16 +1534,11 @@ pub mod migrations { parachains_configuration::migration::v8::MigrateToV8, parachains_configuration::migration::v9::MigrateToV9, paras_registrar::migration::MigrateToV1, + pallet_nomination_pools::migration::versioned::V5toV6, pallet_referenda::migration::v1::MigrateV0ToV1, + pallet_nomination_pools::migration::versioned::V6ToV7, pallet_grandpa::migrations::MigrateV4ToV5, parachains_configuration::migration::v10::MigrateToV10, - pallet_nomination_pools::migration::versioned::V7ToV8, - UpgradeSessionKeys, - frame_support::migrations::RemovePallet< - ImOnlinePalletName, - ::DbWeight, - >, - parachains_configuration::migration::v11::MigrateToV11, ); } @@ -1699,6 +1585,7 @@ mod benches { [frame_election_provider_support, ElectionProviderBench::] [pallet_fast_unstake, FastUnstake] [pallet_identity, Identity] + [pallet_im_online, ImOnline] [pallet_indices, Indices] [pallet_message_queue, MessageQueue] [pallet_multisig, Multisig] @@ -1793,8 +1680,8 @@ sp_api::impl_runtime_apis! { } } - #[api_version(10)] - impl primitives::runtime_api::ParachainHost for Runtime { + #[api_version(9)] + impl primitives::runtime_api::ParachainHost for Runtime { fn validators() -> Vec { parachains_runtime_api_impl::validators::() } @@ -1937,10 +1824,6 @@ sp_api::impl_runtime_apis! { parachains_runtime_api_impl::async_backing_params::() } - fn approval_voting_params() -> ApprovalVotingParams { - parachains_staging_runtime_api_impl::approval_voting_params::() - } - fn disabled_validators() -> Vec { parachains_staging_runtime_api_impl::disabled_validators::() } @@ -2305,21 +2188,6 @@ sp_api::impl_runtime_apis! { crate::Junction::Parachain(43211234).into(), )) } - - fn set_up_complex_asset_transfer( - ) -> Option<(MultiAssets, u32, MultiLocation, Box)> { - // Relay supports only native token, either reserve transfer it to non-system parachains, - // or teleport it to system parachain. Use the teleport case for benchmarking as it's - // slightly heavier. - - // Relay/native token can be teleported to/from AH. - let native_location = Here.into(); - let dest = crate::xcm_config::AssetHub::get(); - pallet_xcm::benchmarking::helpers::native_teleport_as_asset_transfer::( - native_location, - dest - ) - } } impl frame_system_benchmarking::Config for Runtime {} impl pallet_nomination_pools_benchmarking::Config for Runtime {} diff --git a/polkadot/runtime/westend/src/weights/pallet_nomination_pools.rs b/polkadot/runtime/westend/src/weights/pallet_nomination_pools.rs index 6aa5ddd1ec8..49bc687a3e4 100644 --- a/polkadot/runtime/westend/src/weights/pallet_nomination_pools.rs +++ b/polkadot/runtime/westend/src/weights/pallet_nomination_pools.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_nomination_pools` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-11-24, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-09-22, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-nbnwcyh-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("westend-dev")`, DB CACHE: 1024 // Executed Command: @@ -53,7 +53,7 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(717), added: 3192, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:1) @@ -78,22 +78,20 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `VoterList::ListNodes` (`max_values`: None, `max_size`: Some(154), added: 2629, mode: `MaxEncodedLen`) /// Storage: `VoterList::ListBags` (r:2 w:2) /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn join() -> Weight { // Proof Size summary in bytes: - // Measured: `3355` + // Measured: `3318` // Estimated: `8877` - // Minimum execution time: 173_707_000 picoseconds. - Weight::from_parts(179_920_000, 0) + // Minimum execution time: 187_795_000 picoseconds. + Weight::from_parts(193_857_000, 0) .saturating_add(Weight::from_parts(0, 8877)) - .saturating_add(T::DbWeight::get().reads(20)) - .saturating_add(T::DbWeight::get().writes(13)) + .saturating_add(T::DbWeight::get().reads(19)) + .saturating_add(T::DbWeight::get().writes(12)) } /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(717), added: 3192, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -112,24 +110,22 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `VoterList::ListNodes` (`max_values`: None, `max_size`: Some(154), added: 2629, mode: `MaxEncodedLen`) /// Storage: `VoterList::ListBags` (r:2 w:2) /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn bond_extra_transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `3365` + // Measured: `3328` // Estimated: `8877` - // Minimum execution time: 174_414_000 picoseconds. - Weight::from_parts(178_068_000, 0) + // Minimum execution time: 186_245_000 picoseconds. + Weight::from_parts(190_916_000, 0) .saturating_add(Weight::from_parts(0, 8877)) - .saturating_add(T::DbWeight::get().reads(17)) - .saturating_add(T::DbWeight::get().writes(13)) + .saturating_add(T::DbWeight::get().reads(16)) + .saturating_add(T::DbWeight::get().writes(12)) } /// Storage: `NominationPools::ClaimPermissions` (r:1 w:0) /// Proof: `NominationPools::ClaimPermissions` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(717), added: 3192, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -148,24 +144,22 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `VoterList::ListNodes` (`max_values`: None, `max_size`: Some(154), added: 2629, mode: `MaxEncodedLen`) /// Storage: `VoterList::ListBags` (r:2 w:2) /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn bond_extra_other() -> Weight { // Proof Size summary in bytes: - // Measured: `3312` + // Measured: `3274` // Estimated: `8799` - // Minimum execution time: 198_864_000 picoseconds. - Weight::from_parts(203_783_000, 0) + // Minimum execution time: 217_918_000 picoseconds. + Weight::from_parts(224_772_000, 0) .saturating_add(Weight::from_parts(0, 8799)) - .saturating_add(T::DbWeight::get().reads(17)) - .saturating_add(T::DbWeight::get().writes(13)) + .saturating_add(T::DbWeight::get().reads(16)) + .saturating_add(T::DbWeight::get().writes(12)) } /// Storage: `NominationPools::ClaimPermissions` (r:1 w:0) /// Proof: `NominationPools::ClaimPermissions` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(717), added: 3192, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -174,10 +168,10 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn claim_payout() -> Weight { // Proof Size summary in bytes: - // Measured: `1138` + // Measured: `1137` // Estimated: `4182` - // Minimum execution time: 70_250_000 picoseconds. - Weight::from_parts(72_231_000, 0) + // Minimum execution time: 76_958_000 picoseconds. + Weight::from_parts(78_278_000, 0) .saturating_add(Weight::from_parts(0, 4182)) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) @@ -185,7 +179,7 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(717), added: 3192, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) @@ -216,16 +210,16 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `NominationPools::CounterForSubPoolsStorage` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn unbond() -> Weight { // Proof Size summary in bytes: - // Measured: `3545` + // Measured: `3597` // Estimated: `8877` - // Minimum execution time: 155_853_000 picoseconds. - Weight::from_parts(161_032_000, 0) + // Minimum execution time: 170_992_000 picoseconds. + Weight::from_parts(179_987_000, 0) .saturating_add(Weight::from_parts(0, 8877)) .saturating_add(T::DbWeight::get().reads(20)) .saturating_add(T::DbWeight::get().writes(13)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:1) @@ -236,27 +230,25 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:1 w:0) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 100]`. fn pool_withdraw_unbonded(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1744` + // Measured: `1670` // Estimated: `4764` - // Minimum execution time: 62_933_000 picoseconds. - Weight::from_parts(65_847_171, 0) + // Minimum execution time: 60_740_000 picoseconds. + Weight::from_parts(64_502_831, 0) .saturating_add(Weight::from_parts(0, 4764)) - // Standard Error: 1_476 - .saturating_add(Weight::from_parts(59_648, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(7)) - .saturating_add(T::DbWeight::get().writes(3)) + // Standard Error: 2_724 + .saturating_add(Weight::from_parts(37_725, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(6)) + .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(717), added: 3192, mode: `MaxEncodedLen`) /// Storage: `Staking::CurrentEra` (r:1 w:0) /// Proof: `Staking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::SubPoolsStorage` (r:1 w:1) /// Proof: `NominationPools::SubPoolsStorage` (`max_values`: None, `max_size`: Some(261), added: 2736, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) @@ -269,8 +261,6 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `NominationPools::CounterForPoolMembers` (r:1 w:1) /// Proof: `NominationPools::CounterForPoolMembers` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::ClaimPermissions` (r:0 w:1) @@ -278,22 +268,22 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// The range of component `s` is `[0, 100]`. fn withdraw_unbonded_update(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `2134` + // Measured: `2098` // Estimated: `4764` - // Minimum execution time: 123_641_000 picoseconds. - Weight::from_parts(127_222_589, 0) + // Minimum execution time: 127_322_000 picoseconds. + Weight::from_parts(132_064_603, 0) .saturating_add(Weight::from_parts(0, 4764)) - // Standard Error: 2_493 - .saturating_add(Weight::from_parts(83_361, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(11)) - .saturating_add(T::DbWeight::get().writes(9)) + // Standard Error: 3_424 + .saturating_add(Weight::from_parts(64_590, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(10)) + .saturating_add(T::DbWeight::get().writes(8)) } /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(717), added: 3192, mode: `MaxEncodedLen`) /// Storage: `Staking::CurrentEra` (r:1 w:0) /// Proof: `Staking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::SubPoolsStorage` (r:1 w:1) /// Proof: `NominationPools::SubPoolsStorage` (`max_values`: None, `max_size`: Some(261), added: 2736, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:1) @@ -302,18 +292,16 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) /// Storage: `Staking::SlashingSpans` (r:1 w:0) /// Proof: `Staking::SlashingSpans` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `Balances::Locks` (r:2 w:1) - /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) - /// Storage: `Balances::Freezes` (r:2 w:1) - /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Staking::Validators` (r:1 w:0) /// Proof: `Staking::Validators` (`max_values`: None, `max_size`: Some(45), added: 2520, mode: `MaxEncodedLen`) /// Storage: `Staking::Nominators` (r:1 w:0) /// Proof: `Staking::Nominators` (`max_values`: None, `max_size`: Some(558), added: 3033, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:2 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:2 w:1) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) /// Storage: `NominationPools::CounterForPoolMembers` (r:1 w:1) /// Proof: `NominationPools::CounterForPoolMembers` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::ReversePoolIdLookup` (r:1 w:1) @@ -335,15 +323,17 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Storage: `NominationPools::ClaimPermissions` (r:0 w:1) /// Proof: `NominationPools::ClaimPermissions` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 100]`. - fn withdraw_unbonded_kill(_s: u32, ) -> Weight { + fn withdraw_unbonded_kill(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `2453` + // Measured: `2454` // Estimated: `8538` - // Minimum execution time: 219_469_000 picoseconds. - Weight::from_parts(227_526_000, 0) + // Minimum execution time: 236_510_000 picoseconds. + Weight::from_parts(243_943_334, 0) .saturating_add(Weight::from_parts(0, 8538)) - .saturating_add(T::DbWeight::get().reads(24)) - .saturating_add(T::DbWeight::get().writes(20)) + // Standard Error: 4_864 + .saturating_add(Weight::from_parts(14_974, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(23)) + .saturating_add(T::DbWeight::get().writes(19)) } /// Storage: `NominationPools::LastPoolId` (r:1 w:1) /// Proof: `NominationPools::LastPoolId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -369,12 +359,14 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:1) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) + /// Storage: `Staking::Ledger` (r:1 w:1) + /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) + /// Storage: `Staking::CurrentEra` (r:1 w:0) + /// Proof: `Staking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Balances::Locks` (r:2 w:1) /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:2 w:1) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::CounterForRewardPools` (r:1 w:1) @@ -384,23 +376,21 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Storage: `NominationPools::CounterForReversePoolIdLookup` (r:1 w:1) /// Proof: `NominationPools::CounterForReversePoolIdLookup` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) - /// Storage: `Staking::Ledger` (r:0 w:1) - /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Payee` (r:0 w:1) /// Proof: `Staking::Payee` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn create() -> Weight { // Proof Size summary in bytes: - // Measured: `1102` + // Measured: `1222` // Estimated: `8538` - // Minimum execution time: 166_466_000 picoseconds. - Weight::from_parts(171_425_000, 0) + // Minimum execution time: 197_883_000 picoseconds. + Weight::from_parts(201_750_000, 0) .saturating_add(Weight::from_parts(0, 8538)) - .saturating_add(T::DbWeight::get().reads(23)) - .saturating_add(T::DbWeight::get().writes(17)) + .saturating_add(T::DbWeight::get().reads(24)) + .saturating_add(T::DbWeight::get().writes(16)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:0) @@ -426,36 +416,36 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// The range of component `n` is `[1, 16]`. fn nominate(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1738` + // Measured: `1779` // Estimated: `4556 + n * (2520 ±0)` - // Minimum execution time: 59_650_000 picoseconds. - Weight::from_parts(60_620_077, 0) + // Minimum execution time: 65_505_000 picoseconds. + Weight::from_parts(67_148_657, 0) .saturating_add(Weight::from_parts(0, 4556)) - // Standard Error: 7_316 - .saturating_add(Weight::from_parts(1_467_406, 0).saturating_mul(n.into())) + // Standard Error: 9_115 + .saturating_add(Weight::from_parts(1_421_198, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(12)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(5)) .saturating_add(Weight::from_parts(0, 2520).saturating_mul(n.into())) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:0) /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) fn set_state() -> Weight { // Proof Size summary in bytes: - // Measured: `1363` + // Measured: `1367` // Estimated: `4556` - // Minimum execution time: 31_170_000 picoseconds. - Weight::from_parts(32_217_000, 0) + // Minimum execution time: 34_157_000 picoseconds. + Weight::from_parts(35_557_000, 0) .saturating_add(Weight::from_parts(0, 4556)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::Metadata` (r:1 w:1) /// Proof: `NominationPools::Metadata` (`max_values`: None, `max_size`: Some(270), added: 2745, mode: `MaxEncodedLen`) /// Storage: `NominationPools::CounterForMetadata` (r:1 w:1) @@ -463,13 +453,13 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// The range of component `n` is `[1, 256]`. fn set_metadata(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `498` + // Measured: `497` // Estimated: `3735` - // Minimum execution time: 12_603_000 picoseconds. - Weight::from_parts(13_241_702, 0) + // Minimum execution time: 13_806_000 picoseconds. + Weight::from_parts(14_540_018, 0) .saturating_add(Weight::from_parts(0, 3735)) - // Standard Error: 116 - .saturating_add(Weight::from_parts(1_428, 0).saturating_mul(n.into())) + // Standard Error: 123 + .saturating_add(Weight::from_parts(644, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -489,25 +479,25 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_608_000 picoseconds. - Weight::from_parts(3_801_000, 0) + // Minimum execution time: 5_870_000 picoseconds. + Weight::from_parts(6_253_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(6)) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) fn update_roles() -> Weight { // Proof Size summary in bytes: - // Measured: `498` - // Estimated: `3719` - // Minimum execution time: 16_053_000 picoseconds. - Weight::from_parts(16_473_000, 0) - .saturating_add(Weight::from_parts(0, 3719)) + // Measured: `497` + // Estimated: `3685` + // Minimum execution time: 18_290_000 picoseconds. + Weight::from_parts(18_961_000, 0) + .saturating_add(Weight::from_parts(0, 3685)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:0) @@ -526,16 +516,16 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `VoterList::CounterForListNodes` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn chill() -> Weight { // Proof Size summary in bytes: - // Measured: `1901` + // Measured: `1942` // Estimated: `4556` - // Minimum execution time: 57_251_000 picoseconds. - Weight::from_parts(59_390_000, 0) + // Minimum execution time: 63_708_000 picoseconds. + Weight::from_parts(65_570_000, 0) .saturating_add(Weight::from_parts(0, 4556)) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(5)) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -544,49 +534,37 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn set_commission() -> Weight { // Proof Size summary in bytes: - // Measured: `770` - // Estimated: `3719` - // Minimum execution time: 29_888_000 picoseconds. - Weight::from_parts(31_056_000, 0) - .saturating_add(Weight::from_parts(0, 3719)) + // Measured: `736` + // Estimated: `3685` + // Minimum execution time: 34_291_000 picoseconds. + Weight::from_parts(34_767_000, 0) + .saturating_add(Weight::from_parts(0, 3685)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) /// Proof: `NominationPools::GlobalMaxCommission` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn set_commission_max() -> Weight { // Proof Size summary in bytes: - // Measured: `538` - // Estimated: `3719` - // Minimum execution time: 15_769_000 picoseconds. - Weight::from_parts(16_579_000, 0) - .saturating_add(Weight::from_parts(0, 3719)) + // Measured: `537` + // Estimated: `3685` + // Minimum execution time: 18_406_000 picoseconds. + Weight::from_parts(18_999_000, 0) + .saturating_add(Weight::from_parts(0, 3685)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) fn set_commission_change_rate() -> Weight { // Proof Size summary in bytes: - // Measured: `498` - // Estimated: `3719` - // Minimum execution time: 15_385_000 picoseconds. - Weight::from_parts(16_402_000, 0) - .saturating_add(Weight::from_parts(0, 3719)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) - fn set_commission_claim_permission() -> Weight { - // Proof Size summary in bytes: - // Measured: `498` - // Estimated: `3719` - // Minimum execution time: 14_965_000 picoseconds. - Weight::from_parts(15_548_000, 0) - .saturating_add(Weight::from_parts(0, 3719)) + // Measured: `497` + // Estimated: `3685` + // Minimum execution time: 18_440_000 picoseconds. + Weight::from_parts(19_230_000, 0) + .saturating_add(Weight::from_parts(0, 3685)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -598,14 +576,14 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo // Proof Size summary in bytes: // Measured: `508` // Estimated: `4182` - // Minimum execution time: 13_549_000 picoseconds. - Weight::from_parts(14_307_000, 0) + // Minimum execution time: 14_310_000 picoseconds. + Weight::from_parts(14_681_000, 0) .saturating_add(Weight::from_parts(0, 4182)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -614,16 +592,16 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn claim_commission() -> Weight { // Proof Size summary in bytes: - // Measured: `968` - // Estimated: `3719` - // Minimum execution time: 60_153_000 picoseconds. - Weight::from_parts(61_369_000, 0) - .saturating_add(Weight::from_parts(0, 3719)) + // Measured: `934` + // Estimated: `3685` + // Minimum execution time: 64_526_000 picoseconds. + Weight::from_parts(66_800_000, 0) + .saturating_add(Weight::from_parts(0, 3685)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:1 w:1) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) @@ -632,10 +610,10 @@ impl pallet_nomination_pools::WeightInfo for WeightInfo /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) fn adjust_pool_deposit() -> Weight { // Proof Size summary in bytes: - // Measured: `867` + // Measured: `866` // Estimated: `4764` - // Minimum execution time: 64_985_000 picoseconds. - Weight::from_parts(66_616_000, 0) + // Minimum execution time: 73_472_000 picoseconds. + Weight::from_parts(74_698_000, 0) .saturating_add(Weight::from_parts(0, 4764)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) diff --git a/polkadot/runtime/westend/src/weights/pallet_staking.rs b/polkadot/runtime/westend/src/weights/pallet_staking.rs index 1ecd44747ef..87b603621e8 100644 --- a/polkadot/runtime/westend/src/weights/pallet_staking.rs +++ b/polkadot/runtime/westend/src/weights/pallet_staking.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_staking` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-11-21, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("westend-dev")`, DB CACHE: 1024 // Executed Command: @@ -62,8 +62,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `894` // Estimated: `4764` - // Minimum execution time: 38_316_000 picoseconds. - Weight::from_parts(40_022_000, 0) + // Minimum execution time: 38_052_000 picoseconds. + Weight::from_parts(39_303_000, 0) .saturating_add(Weight::from_parts(0, 4764)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(4)) @@ -84,8 +84,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `1921` // Estimated: `8877` - // Minimum execution time: 81_027_000 picoseconds. - Weight::from_parts(83_964_000, 0) + // Minimum execution time: 81_690_000 picoseconds. + Weight::from_parts(83_889_000, 0) .saturating_add(Weight::from_parts(0, 8877)) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(7)) @@ -112,8 +112,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `2128` // Estimated: `8877` - // Minimum execution time: 85_585_000 picoseconds. - Weight::from_parts(87_256_000, 0) + // Minimum execution time: 84_409_000 picoseconds. + Weight::from_parts(87_330_000, 0) .saturating_add(Weight::from_parts(0, 8877)) .saturating_add(T::DbWeight::get().reads(12)) .saturating_add(T::DbWeight::get().writes(7)) @@ -133,11 +133,11 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `1075` // Estimated: `4764` - // Minimum execution time: 39_520_000 picoseconds. - Weight::from_parts(41_551_548, 0) + // Minimum execution time: 39_770_000 picoseconds. + Weight::from_parts(40_828_632, 0) .saturating_add(Weight::from_parts(0, 4764)) - // Standard Error: 1_094 - .saturating_add(Weight::from_parts(50_426, 0).saturating_mul(s.into())) + // Standard Error: 824 + .saturating_add(Weight::from_parts(51_107, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -174,11 +174,11 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `2127 + s * (4 ±0)` // Estimated: `6248 + s * (4 ±0)` - // Minimum execution time: 82_915_000 picoseconds. - Weight::from_parts(89_597_160, 0) + // Minimum execution time: 82_500_000 picoseconds. + Weight::from_parts(90_099_121, 0) .saturating_add(Weight::from_parts(0, 6248)) - // Standard Error: 3_146 - .saturating_add(Weight::from_parts(1_228_061, 0).saturating_mul(s.into())) + // Standard Error: 3_280 + .saturating_add(Weight::from_parts(1_273_212, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(13)) .saturating_add(T::DbWeight::get().writes(11)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(s.into()))) @@ -210,8 +210,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `1301` // Estimated: `4556` - // Minimum execution time: 48_070_000 picoseconds. - Weight::from_parts(49_226_000, 0) + // Minimum execution time: 48_236_000 picoseconds. + Weight::from_parts(49_518_000, 0) .saturating_add(Weight::from_parts(0, 4556)) .saturating_add(T::DbWeight::get().reads(11)) .saturating_add(T::DbWeight::get().writes(5)) @@ -225,11 +225,11 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `1243 + k * (569 ±0)` // Estimated: `4556 + k * (3033 ±0)` - // Minimum execution time: 29_140_000 picoseconds. - Weight::from_parts(30_225_579, 0) + // Minimum execution time: 28_280_000 picoseconds. + Weight::from_parts(29_182_740, 0) .saturating_add(Weight::from_parts(0, 4556)) - // Standard Error: 5_394 - .saturating_add(Weight::from_parts(6_401_367, 0).saturating_mul(k.into())) + // Standard Error: 6_102 + .saturating_add(Weight::from_parts(6_412_107, 0).saturating_mul(k.into())) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(k.into()))) @@ -262,11 +262,11 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `1797 + n * (102 ±0)` // Estimated: `6248 + n * (2520 ±0)` - // Minimum execution time: 59_287_000 picoseconds. - Weight::from_parts(58_285_052, 0) + // Minimum execution time: 59_846_000 picoseconds. + Weight::from_parts(58_029_857, 0) .saturating_add(Weight::from_parts(0, 6248)) - // Standard Error: 14_556 - .saturating_add(Weight::from_parts(3_863_008, 0).saturating_mul(n.into())) + // Standard Error: 15_967 + .saturating_add(Weight::from_parts(3_898_764, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(12)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(6)) @@ -290,8 +290,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `1581` // Estimated: `6248` - // Minimum execution time: 51_035_000 picoseconds. - Weight::from_parts(52_163_000, 0) + // Minimum execution time: 51_223_000 picoseconds. + Weight::from_parts(52_310_000, 0) .saturating_add(Weight::from_parts(0, 6248)) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(6)) @@ -306,8 +306,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `865` // Estimated: `4556` - // Minimum execution time: 15_809_000 picoseconds. - Weight::from_parts(16_451_000, 0) + // Minimum execution time: 15_762_000 picoseconds. + Weight::from_parts(16_381_000, 0) .saturating_add(Weight::from_parts(0, 4556)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) @@ -322,8 +322,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `932` // Estimated: `4556` - // Minimum execution time: 21_695_000 picoseconds. - Weight::from_parts(22_351_000, 0) + // Minimum execution time: 21_904_000 picoseconds. + Weight::from_parts(22_373_000, 0) .saturating_add(Weight::from_parts(0, 4556)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(1)) @@ -336,8 +336,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `865` // Estimated: `4556` - // Minimum execution time: 18_548_000 picoseconds. - Weight::from_parts(19_205_000, 0) + // Minimum execution time: 18_869_000 picoseconds. + Weight::from_parts(19_422_000, 0) .saturating_add(Weight::from_parts(0, 4556)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(3)) @@ -348,8 +348,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_193_000 picoseconds. - Weight::from_parts(2_408_000, 0) + // Minimum execution time: 2_205_000 picoseconds. + Weight::from_parts(2_320_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -359,8 +359,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_475_000 picoseconds. - Weight::from_parts(7_874_000, 0) + // Minimum execution time: 7_179_000 picoseconds. + Weight::from_parts(7_843_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -370,8 +370,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_393_000 picoseconds. - Weight::from_parts(7_643_000, 0) + // Minimum execution time: 7_206_000 picoseconds. + Weight::from_parts(7_829_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -381,8 +381,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_474_000 picoseconds. - Weight::from_parts(7_814_000, 0) + // Minimum execution time: 7_414_000 picoseconds. + Weight::from_parts(7_770_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -393,33 +393,13 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_358_000 picoseconds. - Weight::from_parts(2_589_423, 0) + // Minimum execution time: 2_256_000 picoseconds. + Weight::from_parts(2_645_840, 0) .saturating_add(Weight::from_parts(0, 0)) - // Standard Error: 81 - .saturating_add(Weight::from_parts(13_612, 0).saturating_mul(v.into())) + // Standard Error: 37 + .saturating_add(Weight::from_parts(10_207, 0).saturating_mul(v.into())) .saturating_add(T::DbWeight::get().writes(1)) } - /// Storage: `Staking::Ledger` (r:751 w:1502) - /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) - /// Storage: `Staking::Payee` (r:751 w:0) - /// Proof: `Staking::Payee` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) - /// Storage: `Staking::Bonded` (r:0 w:751) - /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) - /// The range of component `i` is `[0, 751]`. - fn deprecate_controller_batch(i: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `668 + i * (148 ±0)` - // Estimated: `990 + i * (3566 ±0)` - // Minimum execution time: 1_934_000 picoseconds. - Weight::from_parts(2_070_000, 0) - .saturating_add(Weight::from_parts(0, 990)) - // Standard Error: 19_129 - .saturating_add(Weight::from_parts(13_231_580, 0).saturating_mul(i.into())) - .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(i.into()))) - .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(i.into()))) - .saturating_add(Weight::from_parts(0, 3566).saturating_mul(i.into())) - } /// Storage: `Staking::SlashingSpans` (r:1 w:1) /// Proof: `Staking::SlashingSpans` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `Staking::Bonded` (r:1 w:1) @@ -453,11 +433,11 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `2127 + s * (4 ±0)` // Estimated: `6248 + s * (4 ±0)` - // Minimum execution time: 80_290_000 picoseconds. - Weight::from_parts(87_901_664, 0) + // Minimum execution time: 81_032_000 picoseconds. + Weight::from_parts(88_297_596, 0) .saturating_add(Weight::from_parts(0, 6248)) - // Standard Error: 2_960 - .saturating_add(Weight::from_parts(1_195_050, 0).saturating_mul(s.into())) + // Standard Error: 3_070 + .saturating_add(Weight::from_parts(1_207_207, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(13)) .saturating_add(T::DbWeight::get().writes(12)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(s.into()))) @@ -470,11 +450,11 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `66639` // Estimated: `70104` - // Minimum execution time: 132_682_000 picoseconds. - Weight::from_parts(932_504_297, 0) + // Minimum execution time: 131_456_000 picoseconds. + Weight::from_parts(935_254_517, 0) .saturating_add(Weight::from_parts(0, 70104)) - // Standard Error: 57_593 - .saturating_add(Weight::from_parts(4_829_705, 0).saturating_mul(s.into())) + // Standard Error: 57_806 + .saturating_add(Weight::from_parts(4_823_189, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -510,12 +490,12 @@ impl pallet_staking::WeightInfo for WeightInfo { fn payout_stakers_alive_staked(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `8249 + n * (396 ±0)` - // Estimated: `10779 + n * (3774 ±3)` - // Minimum execution time: 129_091_000 picoseconds. - Weight::from_parts(166_186_167, 0) + // Estimated: `10779 + n * (3774 ±0)` + // Minimum execution time: 129_233_000 picoseconds. + Weight::from_parts(165_096_042, 0) .saturating_add(Weight::from_parts(0, 10779)) - // Standard Error: 36_242 - .saturating_add(Weight::from_parts(40_467_481, 0).saturating_mul(n.into())) + // Standard Error: 29_598 + .saturating_add(Weight::from_parts(40_716_425, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(14)) .saturating_add(T::DbWeight::get().reads((6_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(4)) @@ -539,11 +519,11 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `1922 + l * (5 ±0)` // Estimated: `8877` - // Minimum execution time: 77_461_000 picoseconds. - Weight::from_parts(80_118_021, 0) + // Minimum execution time: 77_223_000 picoseconds. + Weight::from_parts(80_026_259, 0) .saturating_add(Weight::from_parts(0, 8877)) - // Standard Error: 4_343 - .saturating_add(Weight::from_parts(59_113, 0).saturating_mul(l.into())) + // Standard Error: 4_493 + .saturating_add(Weight::from_parts(52_909, 0).saturating_mul(l.into())) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(7)) } @@ -578,11 +558,11 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `2127 + s * (4 ±0)` // Estimated: `6248 + s * (4 ±0)` - // Minimum execution time: 89_366_000 picoseconds. - Weight::from_parts(91_964_557, 0) + // Minimum execution time: 89_871_000 picoseconds. + Weight::from_parts(92_313_331, 0) .saturating_add(Weight::from_parts(0, 6248)) - // Standard Error: 2_799 - .saturating_add(Weight::from_parts(1_206_123, 0).saturating_mul(s.into())) + // Standard Error: 3_321 + .saturating_add(Weight::from_parts(1_243_347, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(12)) .saturating_add(T::DbWeight::get().writes(11)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(s.into()))) @@ -627,14 +607,14 @@ impl pallet_staking::WeightInfo for WeightInfo { fn new_era(v: u32, n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0 + n * (716 ±0) + v * (3594 ±0)` - // Estimated: `456136 + n * (3566 ±4) + v * (3566 ±40)` - // Minimum execution time: 520_430_000 picoseconds. - Weight::from_parts(527_125_000, 0) + // Estimated: `456136 + n * (3566 ±0) + v * (3566 ±0)` + // Minimum execution time: 518_819_000 picoseconds. + Weight::from_parts(522_108_000, 0) .saturating_add(Weight::from_parts(0, 456136)) - // Standard Error: 1_974_092 - .saturating_add(Weight::from_parts(64_885_491, 0).saturating_mul(v.into())) - // Standard Error: 196_707 - .saturating_add(Weight::from_parts(18_100_326, 0).saturating_mul(n.into())) + // Standard Error: 1_987_848 + .saturating_add(Weight::from_parts(64_855_377, 0).saturating_mul(v.into())) + // Standard Error: 198_078 + .saturating_add(Weight::from_parts(18_343_485, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(184)) .saturating_add(T::DbWeight::get().reads((5_u64).saturating_mul(v.into()))) .saturating_add(T::DbWeight::get().reads((4_u64).saturating_mul(n.into()))) @@ -665,13 +645,13 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `3108 + n * (907 ±0) + v * (391 ±0)` // Estimated: `456136 + n * (3566 ±0) + v * (3566 ±0)` - // Minimum execution time: 33_917_323_000 picoseconds. - Weight::from_parts(34_173_565_000, 0) + // Minimum execution time: 34_976_277_000 picoseconds. + Weight::from_parts(35_245_501_000, 0) .saturating_add(Weight::from_parts(0, 456136)) - // Standard Error: 367_135 - .saturating_add(Weight::from_parts(4_696_840, 0).saturating_mul(v.into())) - // Standard Error: 367_135 - .saturating_add(Weight::from_parts(3_889_075, 0).saturating_mul(n.into())) + // Standard Error: 386_461 + .saturating_add(Weight::from_parts(5_145_210, 0).saturating_mul(v.into())) + // Standard Error: 386_461 + .saturating_add(Weight::from_parts(3_762_623, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(179)) .saturating_add(T::DbWeight::get().reads((5_u64).saturating_mul(v.into()))) .saturating_add(T::DbWeight::get().reads((4_u64).saturating_mul(n.into()))) @@ -688,11 +668,11 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `946 + v * (50 ±0)` // Estimated: `3510 + v * (2520 ±0)` - // Minimum execution time: 2_447_197_000 picoseconds. - Weight::from_parts(13_003_614, 0) + // Minimum execution time: 2_577_411_000 picoseconds. + Weight::from_parts(86_073_486, 0) .saturating_add(Weight::from_parts(0, 3510)) - // Standard Error: 9_738 - .saturating_add(Weight::from_parts(4_953_442, 0).saturating_mul(v.into())) + // Standard Error: 8_363 + .saturating_add(Weight::from_parts(5_074_828, 0).saturating_mul(v.into())) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(v.into()))) .saturating_add(Weight::from_parts(0, 2520).saturating_mul(v.into())) @@ -713,8 +693,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_714_000 picoseconds. - Weight::from_parts(3_956_000, 0) + // Minimum execution time: 3_539_000 picoseconds. + Weight::from_parts(3_903_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(6)) } @@ -734,13 +714,11 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_361_000 picoseconds. - Weight::from_parts(3_632_000, 0) + // Minimum execution time: 3_244_000 picoseconds. + Weight::from_parts(3_450_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(6)) } - /// Storage: `Staking::Bonded` (r:1 w:0) - /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:0) /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) /// Storage: `Staking::Nominators` (r:1 w:1) @@ -763,12 +741,12 @@ impl pallet_staking::WeightInfo for WeightInfo { /// Proof: `VoterList::CounterForListNodes` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn chill_other() -> Weight { // Proof Size summary in bytes: - // Measured: `1870` + // Measured: `1704` // Estimated: `6248` - // Minimum execution time: 65_329_000 picoseconds. - Weight::from_parts(67_247_000, 0) + // Minimum execution time: 62_606_000 picoseconds. + Weight::from_parts(64_678_000, 0) .saturating_add(Weight::from_parts(0, 6248)) - .saturating_add(T::DbWeight::get().reads(12)) + .saturating_add(T::DbWeight::get().reads(11)) .saturating_add(T::DbWeight::get().writes(6)) } /// Storage: `Staking::MinCommission` (r:1 w:0) @@ -779,8 +757,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `658` // Estimated: `3510` - // Minimum execution time: 11_760_000 picoseconds. - Weight::from_parts(12_095_000, 0) + // Minimum execution time: 11_490_000 picoseconds. + Weight::from_parts(11_867_000, 0) .saturating_add(Weight::from_parts(0, 3510)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)) @@ -791,8 +769,8 @@ impl pallet_staking::WeightInfo for WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_256_000 picoseconds. - Weight::from_parts(2_378_000, 0) + // Minimum execution time: 2_125_000 picoseconds. + Weight::from_parts(2_337_000, 0) .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } diff --git a/polkadot/runtime/westend/src/weights/pallet_xcm.rs b/polkadot/runtime/westend/src/weights/pallet_xcm.rs index 493acd0f9e7..cca4bdbd91e 100644 --- a/polkadot/runtime/westend/src/weights/pallet_xcm.rs +++ b/polkadot/runtime/westend/src/weights/pallet_xcm.rs @@ -50,10 +50,6 @@ use core::marker::PhantomData; /// Weight functions for `pallet_xcm`. pub struct WeightInfo(PhantomData); impl pallet_xcm::WeightInfo for WeightInfo { - fn transfer_assets() -> Weight { - // TODO: run benchmarks - Weight::zero() - } /// Storage: `Dmp::DeliveryFeeFactor` (r:1 w:0) /// Proof: `Dmp::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `XcmPallet::SupportedVersion` (r:1 w:0) diff --git a/polkadot/runtime/westend/src/xcm_config.rs b/polkadot/runtime/westend/src/xcm_config.rs index 506df3025fd..9ab6470f6da 100644 --- a/polkadot/runtime/westend/src/xcm_config.rs +++ b/polkadot/runtime/westend/src/xcm_config.rs @@ -21,7 +21,7 @@ use super::{ GeneralAdmin, ParaId, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, StakingAdmin, TransactionByteFee, Treasury, WeightToFee, XcmPallet, }; -use crate::governance::pallet_custom_origins::Treasurer; + use frame_support::{ match_types, parameter_types, traits::{Everything, Nothing}, @@ -34,21 +34,17 @@ use runtime_common::{ }; use sp_core::ConstU32; use westend_runtime_constants::{ - currency::CENTS, - system_parachain::*, - xcm::body::{FELLOWSHIP_ADMIN_INDEX, TREASURER_INDEX}, + currency::CENTS, system_parachain::*, xcm::body::FELLOWSHIP_ADMIN_INDEX, }; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter as XcmCurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, - ChildParachainConvertsVia, DescribeBodyTerminal, DescribeFamily, HashedDescription, IsConcrete, - MintLocation, OriginToPluralityVoice, SignedAccountId32AsNative, SignedToAccountId32, - SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, - WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, - XcmFeeToAccount, + ChildParachainConvertsVia, CurrencyAdapter as XcmCurrencyAdapter, DescribeBodyTerminal, + DescribeFamily, HashedDescription, IsConcrete, MintLocation, OriginToPluralityVoice, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, + XcmFeeManagerFromComponents, XcmFeeToAccount, }; use xcm_executor::XcmExecutor; @@ -74,7 +70,6 @@ pub type LocationConverter = ( HashedDescription>, ); -#[allow(deprecated)] pub type LocalAssetTransactor = XcmCurrencyAdapter< // Use this currency: Balances, @@ -203,8 +198,6 @@ parameter_types! { pub const StakingAdminBodyId: BodyId = BodyId::Defense; // FellowshipAdmin pluralistic body. pub const FellowshipAdminBodyId: BodyId = BodyId::Index(FELLOWSHIP_ADMIN_INDEX); - // `Treasurer` pluralistic body. - pub const TreasurerBodyId: BodyId = BodyId::Index(TREASURER_INDEX); } /// Type to convert the `GeneralAdmin` origin to a Plurality `MultiLocation` value. @@ -227,9 +220,6 @@ pub type StakingAdminToPlurality = pub type FellowshipAdminToPlurality = OriginToPluralityVoice; -/// Type to convert the `Treasurer` origin to a Plurality `MultiLocation` value. -pub type TreasurerToPlurality = OriginToPluralityVoice; - /// Type to convert a pallet `Origin` type value into a `MultiLocation` value which represents an /// interior location of this chain for a destination chain. pub type LocalPalletOriginToLocation = ( @@ -239,8 +229,6 @@ pub type LocalPalletOriginToLocation = ( StakingAdminToPlurality, // FellowshipAdmin origin to be used in XCM as a corresponding Plurality `MultiLocation` value. FellowshipAdminToPlurality, - // `Treasurer` origin to be used in XCM as a corresponding Plurality `MultiLocation` value. - TreasurerToPlurality, ); impl pallet_xcm::Config for Runtime { diff --git a/polkadot/statement-table/Cargo.toml b/polkadot/statement-table/Cargo.toml index 9a313882da7..d2518591d26 100644 --- a/polkadot/statement-table/Cargo.toml +++ b/polkadot/statement-table/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true description = "Stores messages other authorities issue about candidates in Polkadot." -[lints] -workspace = true - [dependencies] parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive"] } sp-core = { path = "../../substrate/primitives/core" } diff --git a/polkadot/utils/generate-bags/Cargo.toml b/polkadot/utils/generate-bags/Cargo.toml index 97f15f02e35..ed29001aa4f 100644 --- a/polkadot/utils/generate-bags/Cargo.toml +++ b/polkadot/utils/generate-bags/Cargo.toml @@ -6,11 +6,8 @@ edition.workspace = true license.workspace = true description = "CLI to generate voter bags for Polkadot runtimes" -[lints] -workspace = true - [dependencies] -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } generate-bags = { path = "../../../substrate/utils/frame/generate-bags" } sp-io = { path = "../../../substrate/primitives/io" } diff --git a/polkadot/utils/remote-ext-tests/bags-list/Cargo.toml b/polkadot/utils/remote-ext-tests/bags-list/Cargo.toml index 6b8c4be38a1..e305edc039b 100644 --- a/polkadot/utils/remote-ext-tests/bags-list/Cargo.toml +++ b/polkadot/utils/remote-ext-tests/bags-list/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] westend-runtime = { path = "../../../runtime/westend" } westend-runtime-constants = { path = "../../../runtime/westend/constants" } @@ -18,6 +15,6 @@ sp-tracing = { path = "../../../../substrate/primitives/tracing" } frame-system = { path = "../../../../substrate/frame/system" } sp-core = { path = "../../../../substrate/primitives/core" } -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } log = "0.4.17" tokio = { version = "1.24.2", features = ["macros"] } diff --git a/polkadot/xcm/Cargo.toml b/polkadot/xcm/Cargo.toml index 235a4b204c9..60c27f7fcfc 100644 --- a/polkadot/xcm/Cargo.toml +++ b/polkadot/xcm/Cargo.toml @@ -6,19 +6,15 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] -bounded-collections = { version = "0.1.9", default-features = false, features = ["serde"] } -derivative = { version = "2.2.0", default-features = false, features = ["use_core"] } +bounded-collections = { version = "0.1.8", default-features = false, features = ["serde"] } +derivative = { version = "2.2.0", default-features = false, features = [ "use_core" ] } impl-trait-for-tuples = "0.2.2" log = { version = "0.4.17", default-features = false } -parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } +parity-scale-codec = { version = "3.6.1", default-features = false, features = [ "derive", "max-encoded-len" ] } scale-info = { version = "2.10.0", default-features = false, features = ["derive", "serde"] } sp-weights = { path = "../../substrate/primitives/weights", default-features = false, features = ["serde"] } -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"] } -schemars = { version = "0.8.13", default-features = true, optional = true } +serde = { version = "1.0.188", default-features = false, features = ["alloc", "derive"] } xcm-procedural = { path = "procedural" } environmental = { version = "1.1.4", default-features = false } @@ -28,7 +24,7 @@ hex = "0.4.3" hex-literal = "0.4.1" [features] -default = ["std"] +default = [ "std" ] wasm-api = [] std = [ "bounded-collections/std", @@ -39,4 +35,3 @@ std = [ "serde/std", "sp-weights/std", ] -json-schema = ["bounded-collections/json-schema", "dep:schemars", "sp-weights/json-schema"] diff --git a/polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml b/polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml index d9cc7e34c06..5be0bbe4ae5 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml +++ b/polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml @@ -6,22 +6,19 @@ license.workspace = true version = "1.0.0" description = "Benchmarks for the XCM pallet" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.10.0", 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 } +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 } +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 } log = "0.4.17" @@ -39,7 +36,7 @@ polkadot-runtime-common = { path = "../../runtime/common" } polkadot-primitives = { path = "../../primitives" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking/std", diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/mock.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/mock.rs index 43892c31c7c..9adc706fc18 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/mock.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/mock.rs @@ -45,8 +45,6 @@ parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::simple_max(Weight::from_parts(1024, u64::MAX)); } - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = Everything; type BlockWeights = (); @@ -103,7 +101,6 @@ impl xcm_executor::traits::MatchesFungible for MatchAnyFungible { } // Use balances as the asset transactor. -#[allow(deprecated)] pub type AssetTransactor = xcm_builder::CurrencyAdapter< Balances, MatchAnyFungible, diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mock.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mock.rs index 6efd2304e28..710ff0d8019 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mock.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mock.rs @@ -51,7 +51,6 @@ parameter_types! { frame_system::limits::BlockWeights::simple_max(Weight::from_parts(1024, u64::MAX)); } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = Everything; type BlockWeights = (); diff --git a/polkadot/xcm/pallet-xcm/Cargo.toml b/polkadot/xcm/pallet-xcm/Cargo.toml index 220aad01398..cc5d7d97c45 100644 --- a/polkadot/xcm/pallet-xcm/Cargo.toml +++ b/polkadot/xcm/pallet-xcm/Cargo.toml @@ -6,22 +6,19 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] bounded-collections = { version = "0.1.8", default-features = false } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", optional = true, features = ["derive"] } +serde = { version = "1.0.188", optional = true, features = ["derive"] } log = { version = "0.4.17", default-features = false } -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 = { 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} xcm = { package = "staging-xcm", path = "..", default-features = false } xcm-executor = { package = "staging-xcm-executor", path = "../xcm-executor", default-features = false } @@ -37,7 +34,7 @@ polkadot-runtime-parachains = { path = "../../runtime/parachains" } polkadot-parachain-primitives = { path = "../../parachain" } [features] -default = ["std"] +default = [ "std" ] std = [ "bounded-collections/std", "codec/std", diff --git a/polkadot/xcm/pallet-xcm/src/benchmarking.rs b/polkadot/xcm/pallet-xcm/src/benchmarking.rs index 28a198f40a0..f0289512399 100644 --- a/polkadot/xcm/pallet-xcm/src/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm/src/benchmarking.rs @@ -44,7 +44,7 @@ pub trait Config: crate::Config { /// /// Implementation should also make sure `dest` is reachable/connected. /// - /// If `None`, the benchmarks that depend on this will default to `Weight::MAX`. + /// If `None`, the benchmarks that depend on this will be skipped. fn teleportable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { None } @@ -54,27 +54,10 @@ pub trait Config: crate::Config { /// /// Implementation should also make sure `dest` is reachable/connected. /// - /// If `None`, the benchmarks that depend on this will default to `Weight::MAX`. + /// If `None`, the benchmarks that depend on this will be skipped. fn reserve_transferable_asset_and_dest() -> Option<(MultiAsset, MultiLocation)> { None } - - /// Sets up a complex transfer (usually consisting of a teleport and reserve-based transfer), so - /// that runtime can properly benchmark `transfer_assets()` extrinsic. Should return a tuple - /// `(MultiAsset, u32, MultiLocation, dyn FnOnce())` representing the assets to transfer, the - /// `u32` index of the asset to be used for fees, the destination chain for the transfer, and a - /// `verify()` closure to verify the intended transfer side-effects. - /// - /// Implementation should make sure the provided assets can be transacted by the runtime, there - /// are enough balances in the involved accounts, and that `dest` is reachable/connected. - /// - /// Used only in benchmarks. - /// - /// If `None`, the benchmarks that depend on this will default to `Weight::MAX`. - fn set_up_complex_asset_transfer( - ) -> Option<(MultiAssets, u32, MultiLocation, Box)> { - None - } } benchmarks! { @@ -175,23 +158,6 @@ benchmarks! { assert!(pallet_balances::Pallet::::free_balance(&caller) <= balance - transferred_amount); } - transfer_assets { - let (assets, fee_index, destination, verify) = T::set_up_complex_asset_transfer().ok_or( - BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)), - )?; - let caller: T::AccountId = whitelisted_caller(); - let send_origin = RawOrigin::Signed(caller.clone()); - let recipient = [0u8; 32]; - let versioned_dest: VersionedMultiLocation = destination.into(); - let versioned_beneficiary: VersionedMultiLocation = - AccountId32 { network: None, id: recipient.into() }.into(); - let versioned_assets: VersionedMultiAssets = assets.into(); - }: _>(send_origin.into(), Box::new(versioned_dest), Box::new(versioned_beneficiary), Box::new(versioned_assets), 0, WeightLimit::Unlimited) - verify { - // run provided verification function - verify(); - } - execute { let execute_origin = T::ExecuteXcmOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; @@ -336,36 +302,3 @@ benchmarks! { crate::mock::Test ); } - -pub mod helpers { - use super::*; - pub fn native_teleport_as_asset_transfer( - native_asset_location: MultiLocation, - destination: MultiLocation, - ) -> Option<(MultiAssets, u32, MultiLocation, Box)> - where - T: Config + pallet_balances::Config, - u128: From<::Balance>, - { - // Relay/native token can be teleported to/from AH. - let amount = T::ExistentialDeposit::get() * 100u32.into(); - let assets: MultiAssets = - MultiAsset { fun: Fungible(amount.into()), id: Concrete(native_asset_location) }.into(); - let fee_index = 0u32; - - // Give some multiple of transferred amount - let balance = amount * 10u32.into(); - let who = whitelisted_caller(); - let _ = - as frame_support::traits::Currency<_>>::make_free_balance_be(&who, balance); - // verify initial balance - assert_eq!(pallet_balances::Pallet::::free_balance(&who), balance); - - // verify transferred successfully - let verify = Box::new(move || { - // verify balance after transfer, decreased by transferred amount (and delivery fees) - assert!(pallet_balances::Pallet::::free_balance(&who) <= balance - amount); - }); - Some((assets, fee_index, destination, verify)) - } -} diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 2848527f150..74a24b132da 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -66,7 +66,6 @@ pub trait WeightInfo { fn send() -> Weight; fn teleport_assets() -> Weight; fn reserve_transfer_assets() -> Weight; - fn transfer_assets() -> Weight; fn execute() -> Weight; fn force_xcm_version() -> Weight; fn force_default_xcm_version() -> Weight; @@ -99,10 +98,6 @@ impl WeightInfo for TestWeightInfo { Weight::from_parts(100_000_000, 0) } - fn transfer_assets() -> Weight { - Weight::from_parts(100_000_000, 0) - } - fn execute() -> Weight { Weight::from_parts(100_000_000, 0) } @@ -910,8 +905,8 @@ pub mod pallet { /// from relay to parachain. /// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will /// generally be an `AccountId32` value. - /// - `assets`: The assets to be withdrawn. This should include the assets used to pay the - /// fee on the `dest` chain. + /// - `assets`: The assets to be withdrawn. The first item should be the currency used to to + /// pay the fee on the `dest` side. May not be empty. /// - `fee_asset_item`: The index into `assets` of the item which should be used to pay /// fees. #[pallet::call_index(1)] @@ -942,19 +937,8 @@ pub mod pallet { Self::do_teleport_assets(origin, dest, beneficiary, assets, fee_asset_item, Unlimited) } - /// Transfer some assets from the local chain to the destination chain through their local, - /// destination or remote reserve. - /// - /// `assets` must have same reserve location and may not be teleportable to `dest`. - /// - `assets` have local reserve: transfer assets to sovereign account of destination - /// chain and forward a notification XCM to `dest` to mint and deposit reserve-based - /// assets to `beneficiary`. - /// - `assets` have destination reserve: burn local assets and forward a notification to - /// `dest` chain to withdraw the reserve assets from this chain's sovereign account and - /// deposit them to `beneficiary`. - /// - `assets` have remote reserve: burn local assets, forward XCM to reserve chain to move - /// reserves from this chain's SA to `dest` chain's SA, and forward another XCM to `dest` - /// to mint and deposit reserve-based assets to `beneficiary`. + /// Transfer some assets from the local chain to the sovereign account of a destination + /// chain and forward a notification XCM. /// /// **This function is deprecated: Use `limited_reserve_transfer_assets` instead.** /// @@ -969,7 +953,7 @@ pub mod pallet { /// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will /// generally be an `AccountId32` value. /// - `assets`: The assets to be withdrawn. This should include the assets used to pay the - /// fee on the `dest` (and possibly reserve) chains. + /// fee on the `dest` side. /// - `fee_asset_item`: The index into `assets` of the item which should be used to pay /// fees. #[pallet::call_index(2)] @@ -1121,19 +1105,8 @@ pub mod pallet { }) } - /// Transfer some assets from the local chain to the destination chain through their local, - /// destination or remote reserve. - /// - /// `assets` must have same reserve location and may not be teleportable to `dest`. - /// - `assets` have local reserve: transfer assets to sovereign account of destination - /// chain and forward a notification XCM to `dest` to mint and deposit reserve-based - /// assets to `beneficiary`. - /// - `assets` have destination reserve: burn local assets and forward a notification to - /// `dest` chain to withdraw the reserve assets from this chain's sovereign account and - /// deposit them to `beneficiary`. - /// - `assets` have remote reserve: burn local assets, forward XCM to reserve chain to move - /// reserves from this chain's SA to `dest` chain's SA, and forward another XCM to `dest` - /// to mint and deposit reserve-based assets to `beneficiary`. + /// Transfer some assets from the local chain to the sovereign account of a destination + /// chain and forward a notification XCM. /// /// Fee payment on the destination side is made from the asset in the `assets` vector of /// index `fee_asset_item`, up to enough to pay for `weight_limit` of weight. If more weight @@ -1147,7 +1120,7 @@ pub mod pallet { /// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will /// generally be an `AccountId32` value. /// - `assets`: The assets to be withdrawn. This should include the assets used to pay the - /// fee on the `dest` (and possibly reserve) chains. + /// fee on the `dest` side. /// - `fee_asset_item`: The index into `assets` of the item which should be used to pay /// fees. /// - `weight_limit`: The remote-side weight limit, if any, for the XCM fee purchase. @@ -1200,8 +1173,8 @@ pub mod pallet { /// from relay to parachain. /// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will /// generally be an `AccountId32` value. - /// - `assets`: The assets to be withdrawn. This should include the assets used to pay the - /// fee on the `dest` chain. + /// - `assets`: The assets to be withdrawn. The first item should be the currency used to to + /// pay the fee on the `dest` side. May not be empty. /// - `fee_asset_item`: The index into `assets` of the item which should be used to pay /// fees. /// - `weight_limit`: The remote-side weight limit, if any, for the XCM fee purchase. @@ -1252,162 +1225,12 @@ pub mod pallet { XcmExecutionSuspended::::set(suspended); Ok(()) } - - /// Transfer some assets from the local chain to the destination chain through their local, - /// destination or remote reserve, or through teleports. - /// - /// Fee payment on the destination side is made from the asset in the `assets` vector of - /// index `fee_asset_item` (hence referred to as `fees`), up to enough to pay for - /// `weight_limit` of weight. If more weight is needed than `weight_limit`, then the - /// operation will fail and the assets sent may be at risk. - /// - /// `assets` (excluding `fees`) must have same reserve location or otherwise be teleportable - /// to `dest`, no limitations imposed on `fees`. - /// - for local reserve: transfer assets to sovereign account of destination chain and - /// forward a notification XCM to `dest` to mint and deposit reserve-based assets to - /// `beneficiary`. - /// - for destination reserve: burn local assets and forward a notification to `dest` chain - /// to withdraw the reserve assets from this chain's sovereign account and deposit them - /// to `beneficiary`. - /// - for remote reserve: burn local assets, forward XCM to reserve chain to move reserves - /// from this chain's SA to `dest` chain's SA, and forward another XCM to `dest` to mint - /// and deposit reserve-based assets to `beneficiary`. - /// - for teleports: burn local assets and forward XCM to `dest` chain to mint/teleport - /// assets and deposit them to `beneficiary`. - /// - /// - `origin`: Must be capable of withdrawing the `assets` and executing XCM. - /// - `dest`: Destination context for the assets. Will typically be `X2(Parent, - /// Parachain(..))` to send from parachain to parachain, or `X1(Parachain(..))` to send - /// from relay to parachain. - /// - `beneficiary`: A beneficiary location for the assets in the context of `dest`. Will - /// generally be an `AccountId32` value. - /// - `assets`: The assets to be withdrawn. This should include the assets used to pay the - /// fee on the `dest` (and possibly reserve) chains. - /// - `fee_asset_item`: The index into `assets` of the item which should be used to pay - /// fees. - /// - `weight_limit`: The remote-side weight limit, if any, for the XCM fee purchase. - #[pallet::call_index(11)] - #[pallet::weight({ - let maybe_assets: Result = (*assets.clone()).try_into(); - let maybe_dest: Result = (*dest.clone()).try_into(); - match (maybe_assets, maybe_dest) { - (Ok(assets), Ok(dest)) => { - use sp_std::vec; - // heaviest version of locally executed XCM program: equivalent in weight to withdrawing fees, - // burning them, transferring rest of assets to SA, reanchoring them, extending XCM program, - // and sending onward XCM - let mut message = Xcm(vec![ - SetFeesMode { jit_withdraw: true }, - WithdrawAsset(assets.clone()), - BurnAsset(assets.clone()), - TransferReserveAsset { assets, dest, xcm: Xcm(vec![]) } - ]); - T::Weigher::weight(&mut message).map_or(Weight::MAX, |w| T::WeightInfo::transfer_assets().saturating_add(w)) - } - _ => Weight::MAX, - } - })] - pub fn transfer_assets( - origin: OriginFor, - dest: Box, - beneficiary: Box, - assets: Box, - fee_asset_item: u32, - weight_limit: WeightLimit, - ) -> DispatchResult { - let origin = T::ExecuteXcmOrigin::ensure_origin(origin)?; - let dest = (*dest).try_into().map_err(|()| Error::::BadVersion)?; - let beneficiary: MultiLocation = - (*beneficiary).try_into().map_err(|()| Error::::BadVersion)?; - let assets: MultiAssets = (*assets).try_into().map_err(|()| Error::::BadVersion)?; - log::debug!( - target: "xcm::pallet_xcm::transfer_assets", - "origin {:?}, dest {:?}, beneficiary {:?}, assets {:?}, fee-idx {:?}, weight_limit {:?}", - origin, dest, beneficiary, assets, fee_asset_item, weight_limit, - ); - - ensure!(assets.len() <= MAX_ASSETS_FOR_TRANSFER, Error::::TooManyAssets); - let mut assets = assets.into_inner(); - let fee_asset_item = fee_asset_item as usize; - let fees = assets.get(fee_asset_item as usize).ok_or(Error::::Empty)?.clone(); - // Find transfer types for fee and non-fee assets. - let (fees_transfer_type, assets_transfer_type) = - Self::find_fee_and_assets_transfer_types(&assets, fee_asset_item, &dest)?; - - // local and remote XCM programs to potentially handle fees separately - let fees = if fees_transfer_type == assets_transfer_type { - // no need for custom fees instructions, fees are batched with assets - FeesHandling::Batched { fees } - } else { - // Disallow _remote reserves_ unless assets & fees have same remote reserve (covered - // by branch above). The reason for this is that we'd need to send XCMs to separate - // chains with no guarantee of delivery order on final destination; therefore we - // cannot guarantee to have fees in place on final destination chain to pay for - // assets transfer. - ensure!( - !matches!(assets_transfer_type, TransferType::RemoteReserve(_)), - Error::::InvalidAssetUnsupportedReserve - ); - let weight_limit = weight_limit.clone(); - // remove `fees` from `assets` and build separate fees transfer instructions to be - // added to assets transfers XCM programs - let fees = assets.remove(fee_asset_item); - let (local_xcm, remote_xcm) = match fees_transfer_type { - TransferType::LocalReserve => - Self::local_reserve_fees_instructions(origin, dest, fees, weight_limit)?, - TransferType::DestinationReserve => - Self::destination_reserve_fees_instructions( - origin, - dest, - fees, - weight_limit, - )?, - TransferType::Teleport => - Self::teleport_fees_instructions(origin, dest, fees, weight_limit)?, - TransferType::RemoteReserve(_) => - return Err(Error::::InvalidAssetUnsupportedReserve.into()), - }; - FeesHandling::Separate { local_xcm, remote_xcm } - }; - - Self::build_and_execute_xcm_transfer_type( - origin, - dest, - beneficiary, - assets, - assets_transfer_type, - fees, - weight_limit, - ) - } } } /// The maximum number of distinct assets allowed to be transferred in a single helper extrinsic. const MAX_ASSETS_FOR_TRANSFER: usize = 2; -/// Specify how assets used for fees are handled during asset transfers. -#[derive(Clone, PartialEq)] -enum FeesHandling { - /// `fees` asset can be batch-transferred with rest of assets using same XCM instructions. - Batched { fees: MultiAsset }, - /// fees cannot be batched, they are handled separately using XCM programs here. - Separate { local_xcm: Xcm<::RuntimeCall>, remote_xcm: Xcm<()> }, -} - -impl sp_std::fmt::Debug for FeesHandling { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { - match self { - Self::Batched { fees } => write!(f, "FeesHandling::Batched({:?})", fees), - Self::Separate { local_xcm, remote_xcm } => write!( - f, - "FeesHandling::Separate(local: {:?}, remote: {:?})", - local_xcm, remote_xcm - ), - } - } -} - impl QueryHandler for Pallet { type QueryId = u64; type BlockNumber = BlockNumberFor; @@ -1469,45 +1292,31 @@ impl QueryHandler for Pallet { } impl Pallet { - /// Find `TransferType`s for `assets` and fee identified through `fee_asset_item`, when - /// transferring to `dest`. - /// - /// Validate `assets` to all have same `TransferType`. - fn find_fee_and_assets_transfer_types( + /// Validate `assets` to be reserve-transferred and return their reserve location. + fn validate_assets_and_find_reserve( assets: &[MultiAsset], - fee_asset_item: usize, dest: &MultiLocation, - ) -> Result<(TransferType, TransferType), Error> { - let mut fees_transfer_type = None; - let mut assets_transfer_type = None; - for (idx, asset) in assets.iter().enumerate() { + ) -> Result> { + let mut reserve = None; + for asset in assets.iter() { if let Fungible(x) = asset.fun { // If fungible asset, ensure non-zero amount. ensure!(!x.is_zero(), Error::::Empty); } let transfer_type = T::XcmExecutor::determine_for(&asset, dest).map_err(Error::::from)?; - if idx == fee_asset_item { - fees_transfer_type = Some(transfer_type); + // Ensure asset is not teleportable to `dest`. + ensure!(transfer_type != TransferType::Teleport, Error::::Filtered); + if let Some(reserve) = reserve.as_ref() { + // Ensure transfer for multiple assets uses same reserve location (only fee may have + // different reserve location) + ensure!(reserve == &transfer_type, Error::::TooManyReserves); } else { - if let Some(existing) = assets_transfer_type.as_ref() { - // Ensure transfer for multiple assets uses same transfer type (only fee may - // have different transfer type/path) - ensure!(existing == &transfer_type, Error::::TooManyReserves); - } else { - // asset reserve identified - assets_transfer_type = Some(transfer_type); - } + // asset reserve identified + reserve = Some(transfer_type); } } - // single asset also marked as fee item - if assets.len() == 1 { - assets_transfer_type = fees_transfer_type - } - Ok(( - fees_transfer_type.ok_or(Error::::Empty)?, - assets_transfer_type.ok_or(Error::::Empty)?, - )) + reserve.ok_or(Error::::Empty) } fn do_reserve_transfer_assets( @@ -1523,7 +1332,7 @@ impl Pallet { let beneficiary: MultiLocation = (*beneficiary).try_into().map_err(|()| Error::::BadVersion)?; let assets: MultiAssets = (*assets).try_into().map_err(|()| Error::::BadVersion)?; - log::debug!( + log::trace!( target: "xcm::pallet_xcm::do_reserve_transfer_assets", "origin {:?}, dest {:?}, beneficiary {:?}, assets {:?}, fee-idx {:?}", origin_location, dest, beneficiary, assets, fee_asset_item, @@ -1532,26 +1341,64 @@ impl Pallet { ensure!(assets.len() <= MAX_ASSETS_FOR_TRANSFER, Error::::TooManyAssets); let value = (origin_location, assets.into_inner()); ensure!(T::XcmReserveTransferFilter::contains(&value), Error::::Filtered); - let (origin, assets) = value; + let (origin_location, mut assets) = value; - let fee_asset_item = fee_asset_item as usize; - let fees = assets.get(fee_asset_item as usize).ok_or(Error::::Empty)?.clone(); + if fee_asset_item as usize >= assets.len() { + return Err(Error::::Empty.into()) + } + let fees = assets.swap_remove(fee_asset_item as usize); + let fees_transfer_type = + T::XcmExecutor::determine_for(&fees, &dest).map_err(Error::::from)?; + let assets_transfer_type = if assets.is_empty() { + // Single asset to transfer (one used for fees where transfer type is determined above). + ensure!(fees_transfer_type != TransferType::Teleport, Error::::Filtered); + fees_transfer_type + } else { + // Find reserve for non-fee assets. + Self::validate_assets_and_find_reserve(&assets, &dest)? + }; - // Find transfer types for fee and non-fee assets. - let (fees_transfer_type, assets_transfer_type) = - Self::find_fee_and_assets_transfer_types(&assets, fee_asset_item, &dest)?; - // Ensure assets (and fees according to check below) are not teleportable to `dest`. - ensure!(assets_transfer_type != TransferType::Teleport, Error::::Filtered); - // Ensure all assets (including fees) have same reserve location. - ensure!(assets_transfer_type == fees_transfer_type, Error::::TooManyReserves); + // local and remote XCM programs to potentially handle fees separately + let separate_fees_instructions: Option<(Xcm<::RuntimeCall>, Xcm<()>)>; + if fees_transfer_type == assets_transfer_type { + // Same reserve location (fees not teleportable), we can batch together fees and assets + // in same reserve-based-transfer. + assets.push(fees.clone()); + // no need for custom fees instructions, fees are batched with assets + separate_fees_instructions = None; + } else { + // Disallow _remote reserves_ unless assets & fees have same remote reserve (covered by + // branch above). The reason for this is that we'd need to send XCMs to separate chains + // with no guarantee of delivery order on final destination; therefore we cannot + // guarantee to have fees in place on final destination chain to pay for assets + // transfer. + ensure!( + !matches!(assets_transfer_type, TransferType::RemoteReserve(_)), + Error::::InvalidAssetUnsupportedReserve + ); + let fees = fees.clone(); + let weight_limit = weight_limit.clone(); + // build fees transfer instructions to be added to assets transfers XCM programs + separate_fees_instructions = Some(match fees_transfer_type { + TransferType::LocalReserve => + Self::local_reserve_fees_instructions(dest, fees, weight_limit)?, + TransferType::DestinationReserve => + Self::destination_reserve_fees_instructions(dest, fees, weight_limit)?, + TransferType::Teleport => + Self::teleport_fees_instructions(origin_location, dest, fees, weight_limit)?, + TransferType::RemoteReserve(_) => + return Err(Error::::InvalidAssetUnsupportedReserve.into()), + }); + }; Self::build_and_execute_xcm_transfer_type( - origin, + origin_location, dest, beneficiary, assets, assets_transfer_type, - FeesHandling::Batched { fees }, + fees, + separate_fees_instructions, weight_limit, ) } @@ -1569,11 +1416,6 @@ impl Pallet { let beneficiary: MultiLocation = (*beneficiary).try_into().map_err(|()| Error::::BadVersion)?; let assets: MultiAssets = (*assets).try_into().map_err(|()| Error::::BadVersion)?; - log::debug!( - target: "xcm::pallet_xcm::do_teleport_assets", - "origin {:?}, dest {:?}, beneficiary {:?}, assets {:?}, fee-idx {:?}, weight_limit {:?}", - origin_location, dest, beneficiary, assets, fee_asset_item, weight_limit, - ); ensure!(assets.len() <= MAX_ASSETS_FOR_TRANSFER, Error::::TooManyAssets); let value = (origin_location, assets.into_inner()); @@ -1582,7 +1424,7 @@ impl Pallet { for asset in assets.iter() { let transfer_type = T::XcmExecutor::determine_for(asset, &dest).map_err(Error::::from)?; - ensure!(transfer_type == TransferType::Teleport, Error::::Filtered); + ensure!(matches!(transfer_type, TransferType::Teleport), Error::::Filtered); } let fees = assets.get(fee_asset_item as usize).ok_or(Error::::Empty)?.clone(); @@ -1592,7 +1434,8 @@ impl Pallet { beneficiary, assets, TransferType::Teleport, - FeesHandling::Batched { fees }, + fees, + None, weight_limit, ) } @@ -1603,65 +1446,54 @@ impl Pallet { beneficiary: MultiLocation, assets: Vec, transfer_type: TransferType, - fees: FeesHandling, + fees: MultiAsset, + separate_fees_instructions: Option<(Xcm<::RuntimeCall>, Xcm<()>)>, weight_limit: WeightLimit, ) -> DispatchResult { - log::debug!( + log::trace!( target: "xcm::pallet_xcm::build_and_execute_xcm_transfer_type", "origin {:?}, dest {:?}, beneficiary {:?}, assets {:?}, transfer_type {:?}, \ - fees_handling {:?}, weight_limit: {:?}", - origin, dest, beneficiary, assets, transfer_type, fees, weight_limit, + fees {:?}, fees_xcm: {:?}, weight_limit: {:?}", + origin, dest, beneficiary, assets, transfer_type, fees, separate_fees_instructions, weight_limit, ); let (mut local_xcm, remote_xcm) = match transfer_type { TransferType::LocalReserve => { let (local, remote) = Self::local_reserve_transfer_programs( - origin, dest, beneficiary, assets, fees, + separate_fees_instructions, weight_limit, )?; (local, Some(remote)) }, TransferType::DestinationReserve => { let (local, remote) = Self::destination_reserve_transfer_programs( - origin, dest, beneficiary, assets, fees, + separate_fees_instructions, weight_limit, )?; (local, Some(remote)) }, - TransferType::RemoteReserve(reserve) => { - let fees = match fees { - FeesHandling::Batched { fees } => fees, - _ => return Err(Error::::InvalidAssetUnsupportedReserve.into()), - }; - let local = Self::remote_reserve_transfer_program( - origin, + TransferType::RemoteReserve(reserve) => ( + Self::remote_reserve_transfer_program( reserve, dest, beneficiary, assets, fees, weight_limit, - )?; - (local, None) - }, - TransferType::Teleport => { - let (local, remote) = Self::teleport_assets_program( - origin, - dest, - beneficiary, - assets, - fees, - weight_limit, - )?; - (local, Some(remote)) - }, + )?, + None, + ), + TransferType::Teleport => ( + Self::teleport_assets_program(dest, beneficiary, assets, fees, weight_limit)?, + None, + ), }; let weight = T::Weigher::weight(&mut local_xcm).map_err(|()| Error::::UnweighableMessage)?; @@ -1697,45 +1529,11 @@ impl Pallet { Ok(()) } - fn add_fees_to_xcm( - dest: MultiLocation, - fees: FeesHandling, - weight_limit: WeightLimit, - local: &mut Xcm<::RuntimeCall>, - remote: &mut Xcm<()>, - ) -> Result<(), Error> { - match fees { - FeesHandling::Batched { fees } => { - let context = T::UniversalLocation::get(); - // no custom fees instructions, they are batched together with `assets` transfer; - // BuyExecution happens after receiving all `assets` - let reanchored_fees = - fees.reanchored(&dest, context).map_err(|_| Error::::CannotReanchor)?; - // buy execution using `fees` batched together with above `reanchored_assets` - remote.inner_mut().push(BuyExecution { fees: reanchored_fees, weight_limit }); - }, - FeesHandling::Separate { local_xcm: mut local_fees, remote_xcm: mut remote_fees } => { - // fees are handled by separate XCM instructions, prepend fees instructions (for - // remote XCM they have to be prepended instead of appended to pass barriers). - sp_std::mem::swap(local, &mut local_fees); - sp_std::mem::swap(remote, &mut remote_fees); - // these are now swapped so fees actually go first - local.inner_mut().append(&mut local_fees.into_inner()); - remote.inner_mut().append(&mut remote_fees.into_inner()); - }, - } - Ok(()) - } - fn local_reserve_fees_instructions( - origin: MultiLocation, dest: MultiLocation, fees: MultiAsset, weight_limit: WeightLimit, ) -> Result<(Xcm<::RuntimeCall>, Xcm<()>), Error> { - let value = (origin, vec![fees.clone()]); - ensure!(T::XcmReserveTransferFilter::contains(&value), Error::::Filtered); - let context = T::UniversalLocation::get(); let reanchored_fees = fees .clone() @@ -1756,20 +1554,16 @@ impl Pallet { } fn local_reserve_transfer_programs( - origin: MultiLocation, dest: MultiLocation, beneficiary: MultiLocation, assets: Vec, - fees: FeesHandling, + fees: MultiAsset, + separate_fees_instructions: Option<(Xcm<::RuntimeCall>, Xcm<()>)>, weight_limit: WeightLimit, ) -> Result<(Xcm<::RuntimeCall>, Xcm<()>), Error> { - let value = (origin, assets); - ensure!(T::XcmReserveTransferFilter::contains(&value), Error::::Filtered); - let (_, assets) = value; - // max assets is `assets` (+ potentially separately handled fee) let max_assets = - assets.len() as u32 + if matches!(&fees, FeesHandling::Batched { .. }) { 0 } else { 1 }; + assets.len() as u32 + separate_fees_instructions.as_ref().map(|_| 1).unwrap_or(0); let assets: MultiAssets = assets.into(); let context = T::UniversalLocation::get(); let mut reanchored_assets = assets.clone(); @@ -1777,37 +1571,45 @@ impl Pallet { .reanchor(&dest, context) .map_err(|_| Error::::CannotReanchor)?; - // XCM instructions to be executed on local chain - let mut local_execute_xcm = Xcm(vec![ - // locally move `assets` to `dest`s local sovereign account - TransferAsset { assets, beneficiary: dest }, - ]); - // XCM instructions to be executed on destination chain - let mut xcm_on_dest = Xcm(vec![ + // fees are either handled through dedicated instructions, or batched together with assets + let fees_already_handled = separate_fees_instructions.is_some(); + let (fees_local_xcm, fees_remote_xcm) = separate_fees_instructions + .map(|(local, remote)| (local.into_inner(), remote.into_inner())) + .unwrap_or_default(); + + // start off with any necessary local fees specific instructions + let mut local_execute_xcm = fees_local_xcm; + // move `assets` to `dest`s local sovereign account + local_execute_xcm.push(TransferAsset { assets, beneficiary: dest }); + + // on destination chain, start off with custom fee instructions + let mut xcm_on_dest = fees_remote_xcm; + // continue with rest of assets + xcm_on_dest.extend_from_slice(&[ // let (dest) chain know assets are in its SA on reserve ReserveAssetDeposited(reanchored_assets), // following instructions are not exec'ed on behalf of origin chain anymore ClearOrigin, ]); - // handle fees - Self::add_fees_to_xcm(dest, fees, weight_limit, &mut local_execute_xcm, &mut xcm_on_dest)?; + if !fees_already_handled { + // no custom fees instructions, they are batched together with `assets` transfer; + // BuyExecution happens after receiving all `assets` + let reanchored_fees = + fees.reanchored(&dest, context).map_err(|_| Error::::CannotReanchor)?; + // buy execution using `fees` batched together with above `reanchored_assets` + xcm_on_dest.push(BuyExecution { fees: reanchored_fees, weight_limit }); + } // deposit all remaining assets in holding to `beneficiary` location - xcm_on_dest - .inner_mut() - .push(DepositAsset { assets: Wild(AllCounted(max_assets)), beneficiary }); + xcm_on_dest.push(DepositAsset { assets: Wild(AllCounted(max_assets)), beneficiary }); - Ok((local_execute_xcm, xcm_on_dest)) + Ok((Xcm(local_execute_xcm), Xcm(xcm_on_dest))) } fn destination_reserve_fees_instructions( - origin: MultiLocation, dest: MultiLocation, fees: MultiAsset, weight_limit: WeightLimit, ) -> Result<(Xcm<::RuntimeCall>, Xcm<()>), Error> { - let value = (origin, vec![fees.clone()]); - ensure!(T::XcmReserveTransferFilter::contains(&value), Error::::Filtered); - let context = T::UniversalLocation::get(); let reanchored_fees = fees .clone() @@ -1831,20 +1633,16 @@ impl Pallet { } fn destination_reserve_transfer_programs( - origin: MultiLocation, dest: MultiLocation, beneficiary: MultiLocation, assets: Vec, - fees: FeesHandling, + fees: MultiAsset, + separate_fees_instructions: Option<(Xcm<::RuntimeCall>, Xcm<()>)>, weight_limit: WeightLimit, ) -> Result<(Xcm<::RuntimeCall>, Xcm<()>), Error> { - let value = (origin, assets); - ensure!(T::XcmReserveTransferFilter::contains(&value), Error::::Filtered); - let (_, assets) = value; - // max assets is `assets` (+ potentially separately handled fee) let max_assets = - assets.len() as u32 + if matches!(&fees, FeesHandling::Batched { .. }) { 0 } else { 1 }; + assets.len() as u32 + separate_fees_instructions.as_ref().map(|_| 1).unwrap_or(0); let assets: MultiAssets = assets.into(); let context = T::UniversalLocation::get(); let mut reanchored_assets = assets.clone(); @@ -1852,33 +1650,47 @@ impl Pallet { .reanchor(&dest, context) .map_err(|_| Error::::CannotReanchor)?; - // XCM instructions to be executed on local chain - let mut local_execute_xcm = Xcm(vec![ + // fees are either handled through dedicated instructions, or batched together with assets + let fees_already_handled = separate_fees_instructions.is_some(); + let (fees_local_xcm, fees_remote_xcm) = separate_fees_instructions + .map(|(local, remote)| (local.into_inner(), remote.into_inner())) + .unwrap_or_default(); + + // start off with any necessary local fees specific instructions + let mut local_execute_xcm = fees_local_xcm; + // continue with rest of assets + local_execute_xcm.extend_from_slice(&[ // withdraw reserve-based assets WithdrawAsset(assets.clone()), // burn reserve-based assets BurnAsset(assets), ]); - // XCM instructions to be executed on destination chain - let mut xcm_on_dest = Xcm(vec![ + + // on destination chain, start off with custom fee instructions + let mut xcm_on_dest = fees_remote_xcm; + // continue with rest of assets + xcm_on_dest.extend_from_slice(&[ // withdraw `assets` from origin chain's sovereign account WithdrawAsset(reanchored_assets), // following instructions are not exec'ed on behalf of origin chain anymore ClearOrigin, ]); - // handle fees - Self::add_fees_to_xcm(dest, fees, weight_limit, &mut local_execute_xcm, &mut xcm_on_dest)?; + if !fees_already_handled { + // no custom fees instructions, they are batched together with `assets` transfer; + // BuyExecution happens after receiving all `assets` + let reanchored_fees = + fees.reanchored(&dest, context).map_err(|_| Error::::CannotReanchor)?; + // buy execution using `fees` batched together with above `reanchored_assets` + xcm_on_dest.push(BuyExecution { fees: reanchored_fees, weight_limit }); + } // deposit all remaining assets in holding to `beneficiary` location - xcm_on_dest - .inner_mut() - .push(DepositAsset { assets: Wild(AllCounted(max_assets)), beneficiary }); + xcm_on_dest.push(DepositAsset { assets: Wild(AllCounted(max_assets)), beneficiary }); - Ok((local_execute_xcm, xcm_on_dest)) + Ok((Xcm(local_execute_xcm), Xcm(xcm_on_dest))) } // function assumes fees and assets have the same remote reserve fn remote_reserve_transfer_program( - origin: MultiLocation, reserve: MultiLocation, dest: MultiLocation, beneficiary: MultiLocation, @@ -1886,10 +1698,6 @@ impl Pallet { fees: MultiAsset, weight_limit: WeightLimit, ) -> Result::RuntimeCall>, Error> { - let value = (origin, assets); - ensure!(T::XcmReserveTransferFilter::contains(&value), Error::::Filtered); - let (_, assets) = value; - let max_assets = assets.len() as u32; let context = T::UniversalLocation::get(); // we spend up to half of fees for execution on reserve and other half for execution on @@ -1952,8 +1760,6 @@ impl Pallet { &dummy_context, ) .map_err(|_| Error::::CannotCheckOutTeleport)?; - // safe to do this here, we're in a transactional call that will be reverted on any - // errors down the line ::AssetTransactor::check_out( &dest, &fees, @@ -1977,74 +1783,24 @@ impl Pallet { } fn teleport_assets_program( - origin: MultiLocation, dest: MultiLocation, beneficiary: MultiLocation, assets: Vec, - fees: FeesHandling, + mut fees: MultiAsset, weight_limit: WeightLimit, - ) -> Result<(Xcm<::RuntimeCall>, Xcm<()>), Error> { - let value = (origin, assets); - ensure!(T::XcmTeleportFilter::contains(&value), Error::::Filtered); - let (_, assets) = value; - - // max assets is `assets` (+ potentially separately handled fee) - let max_assets = - assets.len() as u32 + if matches!(&fees, FeesHandling::Batched { .. }) { 0 } else { 1 }; + ) -> Result::RuntimeCall>, Error> { let context = T::UniversalLocation::get(); - let assets: MultiAssets = assets.into(); - let mut reanchored_assets = assets.clone(); - reanchored_assets - .reanchor(&dest, context) - .map_err(|_| Error::::CannotReanchor)?; - - // XcmContext irrelevant in teleports checks - let dummy_context = - XcmContext { origin: None, message_id: Default::default(), topic: None }; - for asset in assets.inner() { - // We should check that the asset can actually be teleported out (for this to - // be in error, there would need to be an accounting violation by ourselves, - // so it's unlikely, but we don't want to allow that kind of bug to leak into - // a trusted chain. - ::AssetTransactor::can_check_out( - &dest, - asset, - &dummy_context, - ) - .map_err(|_| Error::::CannotCheckOutTeleport)?; - } - for asset in assets.inner() { - // safe to do this here, we're in a transactional call that will be reverted on any - // errors down the line - ::AssetTransactor::check_out( - &dest, - asset, - &dummy_context, - ); - } - - // XCM instructions to be executed on local chain - let mut local_execute_xcm = Xcm(vec![ - // withdraw assets to be teleported - WithdrawAsset(assets.clone()), - // burn assets on local chain - BurnAsset(assets), - ]); - // XCM instructions to be executed on destination chain - let mut xcm_on_dest = Xcm(vec![ - // teleport `assets` in from origin chain - ReceiveTeleportedAsset(reanchored_assets), - // following instructions are not exec'ed on behalf of origin chain anymore - ClearOrigin, + fees.reanchor(&dest, context).map_err(|_| Error::::CannotReanchor)?; + let max_assets = assets.len() as u32; + let xcm_on_dest = Xcm(vec![ + BuyExecution { fees, weight_limit }, + DepositAsset { assets: Wild(AllCounted(max_assets)), beneficiary }, ]); - // handle fees - Self::add_fees_to_xcm(dest, fees, weight_limit, &mut local_execute_xcm, &mut xcm_on_dest)?; - // deposit all remaining assets in holding to `beneficiary` location - xcm_on_dest - .inner_mut() - .push(DepositAsset { assets: Wild(AllCounted(max_assets)), beneficiary }); - - Ok((local_execute_xcm, xcm_on_dest)) + Ok(Xcm(vec![ + WithdrawAsset(assets.into()), + SetFeesMode { jit_withdraw: true }, + InitiateTeleport { assets: Wild(AllCounted(max_assets)), dest, xcm: xcm_on_dest }, + ])) } /// Halve `fees` fungible amount. @@ -2591,7 +2347,7 @@ impl WrapVersion for Pallet { dest: &MultiLocation, xcm: impl Into>, ) -> Result, ()> { - Self::get_version_for(dest) + SupportedVersion::::get(XCM_VERSION, LatestVersionedMultiLocation(dest)) .or_else(|| { Self::note_unknown_version(dest); SafeXcmVersion::::get() @@ -2608,12 +2364,6 @@ impl WrapVersion for Pallet { } } -impl GetVersion for Pallet { - fn get_version_for(dest: &MultiLocation) -> Option { - SupportedVersion::::get(XCM_VERSION, LatestVersionedMultiLocation(dest)) - } -} - impl VersionChangeNotifier for Pallet { /// Start notifying `location` should the XCM version of this chain change. /// diff --git a/polkadot/xcm/pallet-xcm/src/mock.rs b/polkadot/xcm/pallet-xcm/src/mock.rs index bc9a3c3c35a..0b0f795100c 100644 --- a/polkadot/xcm/pallet-xcm/src/mock.rs +++ b/polkadot/xcm/pallet-xcm/src/mock.rs @@ -16,7 +16,7 @@ use codec::Encode; use frame_support::{ - construct_runtime, derive_impl, match_types, parameter_types, + construct_runtime, match_types, parameter_types, traits::{ AsEnsureOriginWithArg, ConstU128, ConstU32, Contains, Equals, Everything, EverythingBut, Nothing, @@ -32,15 +32,13 @@ pub use sp_std::{ cell::RefCell, collections::btree_map::BTreeMap, fmt::Debug, marker::PhantomData, }; use xcm::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter as XcmCurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, Case, ChildParachainAsNative, ChildParachainConvertsVia, - ChildSystemParachainAsSuperuser, DescribeAllTerminal, FixedRateOfFungible, FixedWeightBounds, - FungiblesAdapter, HashedDescription, IsConcrete, MatchedConvertedConcreteId, NoChecking, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - XcmFeeManagerFromComponents, XcmFeeToAccount, + ChildSystemParachainAsSuperuser, CurrencyAdapter as XcmCurrencyAdapter, DescribeAllTerminal, + FixedRateOfFungible, FixedWeightBounds, FungiblesAdapter, HashedDescription, IsConcrete, + MatchedConvertedConcreteId, NoChecking, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, XcmFeeManagerFromComponents, XcmFeeToAccount, }; use xcm_executor::{ traits::{Identity, JustTry}, @@ -248,7 +246,6 @@ parameter_types! { pub const BlockHashCount: u64 = 250; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; @@ -430,7 +427,6 @@ pub type ForeignAssetsConvertedConcreteId = MatchedConvertedConcreteId< JustTry, >; -#[allow(deprecated)] pub type AssetTransactors = ( XcmCurrencyAdapter, SovereignAccountOf, AccountId, ()>, FungiblesAdapter< @@ -582,57 +578,6 @@ impl super::benchmarking::Config for Test { Parachain(OTHER_PARA_ID).into(), )) } - - fn set_up_complex_asset_transfer( - ) -> Option<(MultiAssets, u32, MultiLocation, Box)> { - use crate::tests::assets_transfer::{into_multiassets_checked, set_up_foreign_asset}; - // Transfer native asset (local reserve) to `USDT_PARA_ID`. Using teleport-trusted USDT for - // fees. - - let asset_amount = 10u128; - let fee_amount = 2u128; - - let existential_deposit = ExistentialDeposit::get(); - let caller = frame_benchmarking::whitelisted_caller(); - - // Give some multiple of the existential deposit - let balance = asset_amount + existential_deposit * 1000; - let _ = >::make_free_balance_be( - &caller, balance, - ); - // create sufficient foreign asset USDT - let usdt_initial_local_amount = fee_amount * 10; - let (usdt_chain, _, usdt_id_multilocation) = set_up_foreign_asset( - USDT_PARA_ID, - None, - caller.clone(), - usdt_initial_local_amount, - true, - ); - - // native assets transfer destination is USDT chain (teleport trust only for USDT) - let dest = usdt_chain; - let (assets, fee_index, _, _) = into_multiassets_checked( - // USDT for fees (is sufficient on local chain too) - teleported - (usdt_id_multilocation, fee_amount).into(), - // native asset to transfer (not used for fees) - local reserve - (MultiLocation::here(), asset_amount).into(), - ); - // verify initial balances - assert_eq!(Balances::free_balance(&caller), balance); - assert_eq!(Assets::balance(usdt_id_multilocation, &caller), usdt_initial_local_amount); - - // verify transferred successfully - let verify = Box::new(move || { - // verify balances after transfer, decreased by transferred amounts - assert_eq!(Balances::free_balance(&caller), balance - asset_amount); - assert_eq!( - Assets::balance(usdt_id_multilocation, &caller), - usdt_initial_local_amount - fee_amount - ); - }); - Some((assets, fee_index as u32, dest, verify)) - } } pub(crate) fn last_event() -> RuntimeEvent { @@ -658,17 +603,6 @@ pub(crate) fn buy_limited_execution( pub(crate) fn new_test_ext_with_balances( balances: Vec<(AccountId, Balance)>, -) -> sp_io::TestExternalities { - new_test_ext_with_balances_and_xcm_version( - balances, - // By default set actual latest XCM version - Some(XCM_VERSION), - ) -} - -pub(crate) fn new_test_ext_with_balances_and_xcm_version( - balances: Vec<(AccountId, Balance)>, - safe_xcm_version: Option, ) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); @@ -676,7 +610,7 @@ pub(crate) fn new_test_ext_with_balances_and_xcm_version( .assimilate_storage(&mut t) .unwrap(); - pallet_xcm::GenesisConfig:: { safe_xcm_version, ..Default::default() } + pallet_xcm::GenesisConfig:: { safe_xcm_version: Some(2), ..Default::default() } .assimilate_storage(&mut t) .unwrap(); diff --git a/polkadot/xcm/pallet-xcm/src/tests/assets_transfer.rs b/polkadot/xcm/pallet-xcm/src/tests/assets_transfer.rs index 6893bae2b6c..d1b298765e2 100644 --- a/polkadot/xcm/pallet-xcm/src/tests/assets_transfer.rs +++ b/polkadot/xcm/pallet-xcm/src/tests/assets_transfer.rs @@ -19,7 +19,6 @@ use crate::{ mock::*, tests::{ALICE, BOB, FEE_AMOUNT, INITIAL_BALANCE, SEND_AMOUNT}, - DispatchResult, OriginFor, }; use frame_support::{ assert_ok, @@ -33,7 +32,6 @@ use xcm_executor::traits::ConvertLocation; // Helper function to deduplicate testing different teleport types. fn do_test_and_verify_teleport_assets( - origin_location: MultiLocation, expected_beneficiary: MultiLocation, call: Call, expected_weight_limit: WeightLimit, @@ -42,9 +40,8 @@ fn do_test_and_verify_teleport_assets( (ALICE, INITIAL_BALANCE), (ParaId::from(OTHER_PARA_ID).into_account_truncating(), INITIAL_BALANCE), ]; - let dest = RelayLocation::get().into(); new_test_ext_with_balances(balances).execute_with(|| { - let weight = BaseXcmWeight::get() * 2; + let weight = BaseXcmWeight::get() * 3; assert_eq!(Balances::total_balance(&ALICE), INITIAL_BALANCE); // call extrinsic call(); @@ -52,7 +49,7 @@ fn do_test_and_verify_teleport_assets( assert_eq!( sent_xcm(), vec![( - dest, + RelayLocation::get().into(), Xcm(vec![ ReceiveTeleportedAsset((Here, SEND_AMOUNT).into()), ClearOrigin, @@ -66,23 +63,10 @@ fn do_test_and_verify_teleport_assets( ); let versioned_sent = VersionedXcm::from(sent_xcm().into_iter().next().unwrap().1); let _check_v2_ok: xcm::v2::Xcm<()> = versioned_sent.try_into().unwrap(); - - let mut last_events = last_events(3).into_iter(); assert_eq!( - last_events.next().unwrap(), + last_event(), RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(weight) }) ); - assert_eq!( - last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: origin_location, - fees: MultiAssets::new(), - }) - ); - assert!(matches!( - last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::Sent { .. }) - )); }); } @@ -92,10 +76,8 @@ fn do_test_and_verify_teleport_assets( /// local effects. #[test] fn teleport_assets_works() { - let origin_location: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); let beneficiary: MultiLocation = AccountId32 { network: None, id: BOB.into() }.into(); do_test_and_verify_teleport_assets( - origin_location, beneficiary, || { assert_ok!(XcmPallet::teleport_assets( @@ -116,12 +98,10 @@ fn teleport_assets_works() { /// local effects. #[test] fn limited_teleport_assets_works() { - let origin_location: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); let beneficiary: MultiLocation = AccountId32 { network: None, id: BOB.into() }.into(); let weight_limit = WeightLimit::Limited(Weight::from_parts(5000, 5000)); let expected_weight_limit = weight_limit.clone(); do_test_and_verify_teleport_assets( - origin_location, beneficiary, || { assert_ok!(XcmPallet::limited_teleport_assets( @@ -180,7 +160,7 @@ fn reserve_transfer_assets_with_paid_router_works() { let xcm_router_fee_amount = Para3000PaymentAmount::get(); let weight = BaseXcmWeight::get(); let dest: MultiLocation = - AccountId32 { network: None, id: user_account.clone().into() }.into(); + Junction::AccountId32 { network: None, id: user_account.clone().into() }.into(); assert_eq!(Balances::total_balance(&user_account), INITIAL_BALANCE); assert_ok!(XcmPallet::reserve_transfer_assets( RuntimeOrigin::signed(user_account.clone()), @@ -241,10 +221,9 @@ fn reserve_transfer_assets_with_paid_router_works() { }); } -pub(crate) fn set_up_foreign_asset( +fn set_up_foreign_asset( reserve_para_id: u32, inner_junction: Option, - benficiary: AccountId, initial_amount: u128, is_sufficient: bool, ) -> (MultiLocation, AccountId, MultiLocation) { @@ -259,7 +238,7 @@ pub(crate) fn set_up_foreign_asset( reserve_location }; - // create sufficient (to be used as fees as well) foreign asset + // create sufficient (to be used as fees as well) foreign asset (0 total issuance) assert_ok!(Assets::force_create( RuntimeOrigin::root(), foreign_asset_id_multilocation, @@ -272,7 +251,7 @@ pub(crate) fn set_up_foreign_asset( assert_ok!(Assets::mint( RuntimeOrigin::signed(BOB), foreign_asset_id_multilocation, - benficiary, + ALICE, initial_amount )); @@ -281,7 +260,7 @@ pub(crate) fn set_up_foreign_asset( // Helper function that provides correct `fee_index` after `sort()` done by // `vec![MultiAsset, MultiAsset].into()`. -pub(crate) fn into_multiassets_checked( +fn into_multiassets_checked( fee_asset: MultiAsset, transfer_asset: MultiAsset, ) -> (MultiAssets, usize, MultiAsset, MultiAsset) { @@ -290,31 +269,29 @@ pub(crate) fn into_multiassets_checked( (assets, fee_index, fee_asset, transfer_asset) } -/// Test `tested_call` with local asset reserve and local fee reserve. +/// Test `limited_reserve_transfer_assets` with local asset reserve and local fee reserve. /// /// Transferring native asset (local reserve) to some `OTHER_PARA_ID` (no teleport trust). /// Using native asset for fees as well. /// -/// Verifies `expected_result` -fn local_asset_reserve_and_local_fee_reserve_call( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ +/// ```nocompile +/// Here (source) OTHER_PARA_ID (destination) +/// | `assets` reserve +/// | `fees` reserve +/// | +/// | 1. execute `TransferReserveAsset(assets_and_fees_batched_together)` +/// | \--> sends `ReserveAssetDeposited(both), ClearOrigin, BuyExecution(fees), DepositAsset` +/// \------------------------------------------> +/// ``` +#[test] +fn limited_reserve_transfer_assets_with_local_asset_reserve_and_local_fee_reserve_works() { let balances = vec![ (ALICE, INITIAL_BALANCE), (ParaId::from(OTHER_PARA_ID).into_account_truncating(), INITIAL_BALANCE), ]; - let origin_location: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); let weight_limit = WeightLimit::Limited(Weight::from_parts(5000, 5000)); let expected_weight_limit = weight_limit.clone(); let expected_beneficiary = beneficiary; @@ -324,19 +301,14 @@ fn local_asset_reserve_and_local_fee_reserve_call( let weight = BaseXcmWeight::get(); assert_eq!(Balances::total_balance(&ALICE), INITIAL_BALANCE); // call extrinsic - let result = tested_call( + assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(dest.into()), Box::new(beneficiary.into()), Box::new((Here, SEND_AMOUNT).into()), 0, weight_limit, - ); - assert_eq!(result, expected_result); - if expected_result.is_err() { - // short-circuit here for tests where we expect failure - return - } + )); // Alice spent amount assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE - SEND_AMOUNT); // Destination account (parachain account) has amount @@ -365,7 +337,7 @@ fn local_asset_reserve_and_local_fee_reserve_call( assert_eq!( last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: origin_location, + paying: expected_beneficiary, fees: MultiAssets::new(), }) ); @@ -376,72 +348,38 @@ fn local_asset_reserve_and_local_fee_reserve_call( }); } -/// Test `transfer_assets` with local asset reserve and local fee reserve works. -#[test] -fn transfer_assets_with_local_asset_reserve_and_local_fee_reserve_works() { - let expected_result = Ok(()); - local_asset_reserve_and_local_fee_reserve_call(XcmPallet::transfer_assets, expected_result); -} - -/// Test `limited_reserve_transfer_assets` with local asset reserve and local fee reserve works. -#[test] -fn reserve_transfer_assets_with_local_asset_reserve_and_local_fee_reserve_works() { - let expected_result = Ok(()); - local_asset_reserve_and_local_fee_reserve_call( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with local asset reserve and local fee reserve disallowed. -#[test] -fn teleport_assets_with_local_asset_reserve_and_local_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - local_asset_reserve_and_local_fee_reserve_call( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - -/// Test `tested_call` with destination asset reserve and local fee reserve. +/// Test `reserve_transfer_assets` with destination asset reserve and local fee reserve. /// /// Transferring foreign asset (`FOREIGN_ASSET_RESERVE_PARA_ID` reserve) to /// `FOREIGN_ASSET_RESERVE_PARA_ID` (no teleport trust). /// Using native asset (local reserve) for fees. /// +/// ```nocompile +/// Here (source) FOREIGN_ASSET_RESERVE_PARA_ID (destination) +/// | `fees` reserve `assets` reserve +/// | +/// | 1. execute `TransferReserveAsset(fees)` +/// | \-> sends `ReserveAssetDeposited(fees), ClearOrigin, BuyExecution(fees), DepositAsset` +/// | 2. execute `InitiateReserveWithdraw(assets)` +/// | \--> sends `WithdrawAsset(assets), ClearOrigin, BuyExecution(fees), DepositAsset` +/// \------------------------------------------> +/// ``` +/// /// Asserts that the sender's balance is decreased and the beneficiary's balance /// is increased. Verifies the correct message is sent and event is emitted. -/// -/// Verifies `expected_result`. -fn destination_asset_reserve_and_local_fee_reserve_call( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ +#[test] +fn reserve_transfer_assets_with_destination_asset_reserve_and_local_fee_reserve_works() { let weight = BaseXcmWeight::get() * 3; let balances = vec![(ALICE, INITIAL_BALANCE)]; - let origin_location: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { - // create non-sufficient foreign asset BLA + // create non-sufficient foreign asset BLA (0 total issuance) let foreign_initial_amount = 142; let (reserve_location, reserve_sovereign_account, foreign_asset_id_multilocation) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), - ALICE, foreign_initial_amount, false, ); @@ -466,19 +404,14 @@ fn destination_asset_reserve_and_local_fee_reserve_call( assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer - let result = tested_call( + assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(dest.into()), Box::new(beneficiary.into()), Box::new(assets.into()), fee_index as u32, Unlimited, - ); - assert_eq!(result, expected_result); - if expected_result.is_err() { - // short-circuit here for tests where we expect failure - return - } + )); let mut last_events = last_events(3).into_iter(); assert_eq!( @@ -521,7 +454,7 @@ fn destination_asset_reserve_and_local_fee_reserve_call( assert_eq!( last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: origin_location, + paying: beneficiary, fees: MultiAssets::new(), }) ); @@ -532,72 +465,21 @@ fn destination_asset_reserve_and_local_fee_reserve_call( }); } -/// Test `transfer_assets` with destination asset reserve and local fee reserve. -#[test] -fn transfer_assets_with_destination_asset_reserve_and_local_fee_reserve_works() { - let expected_result = Ok(()); - destination_asset_reserve_and_local_fee_reserve_call( - XcmPallet::transfer_assets, - expected_result, - ); -} - -/// Test `limited_reserve_transfer_assets` with destination asset reserve and local fee reserve -/// disallowed. -#[test] -fn reserve_transfer_assets_with_destination_asset_reserve_and_local_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [23, 0, 0, 0], - message: Some("TooManyReserves"), - })); - destination_asset_reserve_and_local_fee_reserve_call( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with destination asset reserve and local fee reserve -/// disallowed. -#[test] -fn teleport_assets_with_destination_asset_reserve_and_local_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - destination_asset_reserve_and_local_fee_reserve_call( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - -/// Test `tested_call` with remote asset reserve and local fee reserve is disallowed. +/// Test `reserve_transfer_assets` with remote asset reserve and local fee reserve. /// /// Transferring foreign asset (reserve on `FOREIGN_ASSET_RESERVE_PARA_ID`) to `OTHER_PARA_ID`. /// Using native (local reserve) as fee should be disallowed. -fn remote_asset_reserve_and_local_fee_reserve_call_disallowed( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ +#[test] +fn reserve_transfer_assets_with_remote_asset_reserve_and_local_fee_reserve_disallowed() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { - // create non-sufficient foreign asset BLA + // create non-sufficient foreign asset BLA (0 total issuance) let foreign_initial_amount = 142; let (_, _, foreign_asset_id_multilocation) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), - ALICE, foreign_initial_amount, false, ); @@ -618,7 +500,7 @@ fn remote_asset_reserve_and_local_fee_reserve_call_disallowed( assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // try the transfer - let result = tested_call( + let result = XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(dest.into()), Box::new(beneficiary.into()), @@ -626,7 +508,14 @@ fn remote_asset_reserve_and_local_fee_reserve_call_disallowed( fee_index as u32, Unlimited, ); - assert_eq!(result, expected_result); + assert_eq!( + result, + Err(DispatchError::Module(ModuleError { + index: 4, + error: [22, 0, 0, 0], + message: Some("InvalidAssetUnsupportedReserve") + })) + ); // Alice transferred nothing assert_eq!(Assets::balance(foreign_asset_id_multilocation, ALICE), foreign_initial_amount); @@ -640,82 +529,33 @@ fn remote_asset_reserve_and_local_fee_reserve_call_disallowed( }); } -/// Test `transfer_assets` with remote asset reserve and local fee reserve is disallowed. -#[test] -fn transfer_assets_with_remote_asset_reserve_and_local_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [22, 0, 0, 0], - message: Some("InvalidAssetUnsupportedReserve"), - })); - remote_asset_reserve_and_local_fee_reserve_call_disallowed( - XcmPallet::transfer_assets, - expected_result, - ); -} - -/// Test `limited_reserve_transfer_assets` with remote asset reserve and local fee reserve is -/// disallowed. -#[test] -fn reserve_transfer_assets_with_remote_asset_reserve_and_local_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [23, 0, 0, 0], - message: Some("TooManyReserves"), - })); - remote_asset_reserve_and_local_fee_reserve_call_disallowed( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with remote asset reserve and local fee reserve is disallowed. -#[test] -fn teleport_assets_with_remote_asset_reserve_and_local_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - remote_asset_reserve_and_local_fee_reserve_call_disallowed( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - -/// Test `tested_call` with local asset reserve and destination fee reserve. +/// Test `reserve_transfer_assets` with local asset reserve and destination fee reserve. /// /// Transferring native asset (local reserve) to `USDC_RESERVE_PARA_ID` (no teleport trust). Using /// foreign asset (`USDC_RESERVE_PARA_ID` reserve) for fees. /// -/// Asserts that the sender's balance is decreased and the beneficiary's balance -/// is increased. Verifies the correct message is sent and event is emitted. -/// -/// Verifies `expected_result`. -fn local_asset_reserve_and_destination_fee_reserve_call( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ +/// ```nocompile +/// Here (source) USDC_RESERVE_PARA_ID (destination) +/// | `assets` reserve `fees` reserve +/// | +/// | 1. execute `InitiateReserveWithdraw(fees)` +/// | \--> sends `WithdrawAsset(fees), ClearOrigin, BuyExecution(fees), DepositAsset` +/// | 2. execute `TransferReserveAsset(assets)` +/// | \-> sends `ReserveAssetDeposited(assets), ClearOrigin, BuyExecution(fees), DepositAsset` +/// \------------------------------------------> +/// ``` +#[test] +fn reserve_transfer_assets_with_local_asset_reserve_and_destination_fee_reserve_works() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let origin_location: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { - // create sufficient foreign asset USDC + // create sufficient foreign asset USDC (0 total issuance) let usdc_initial_local_amount = 142; let (usdc_reserve_location, usdc_chain_sovereign_account, usdc_id_multilocation) = set_up_foreign_asset( USDC_RESERVE_PARA_ID, Some(USDC_INNER_JUNCTION), - ALICE, usdc_initial_local_amount, true, ); @@ -740,20 +580,14 @@ fn local_asset_reserve_and_destination_fee_reserve_call( assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer - let result = tested_call( + assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(dest.into()), Box::new(beneficiary.into()), Box::new(assets.into()), fee_index as u32, Unlimited, - ); - assert_eq!(result, expected_result); - if expected_result.is_err() { - // short-circuit here for tests where we expect failure - return - } - + )); let weight = BaseXcmWeight::get() * 3; let mut last_events = last_events(3).into_iter(); assert_eq!( @@ -763,7 +597,7 @@ fn local_asset_reserve_and_destination_fee_reserve_call( assert_eq!( last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: origin_location, + paying: beneficiary, fees: MultiAssets::new(), }) ); @@ -808,64 +642,22 @@ fn local_asset_reserve_and_destination_fee_reserve_call( }); } -/// Test `transfer_assets` with local asset reserve and destination fee reserve. -#[test] -fn transfer_assets_with_local_asset_reserve_and_destination_fee_reserve_works() { - let expected_result = Ok(()); - local_asset_reserve_and_destination_fee_reserve_call( - XcmPallet::transfer_assets, - expected_result, - ); -} - -/// Test `limited_reserve_transfer_assets` with local asset reserve and destination fee reserve -/// disallowed. -#[test] -fn reserve_transfer_assets_with_local_asset_reserve_and_destination_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [23, 0, 0, 0], - message: Some("TooManyReserves"), - })); - local_asset_reserve_and_destination_fee_reserve_call( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with local asset reserve and destination fee reserve disallowed. -#[test] -fn teleport_assets_with_local_asset_reserve_and_destination_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - local_asset_reserve_and_destination_fee_reserve_call( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - -/// Test `tested_call` with destination asset reserve and destination fee reserve. +/// Test `reserve_transfer_assets` with destination asset reserve and destination fee reserve. /// -/// Verifies `expected_result` -fn destination_asset_reserve_and_destination_fee_reserve_call( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ +/// ```nocompile +/// Here (source) FOREIGN_ASSET_RESERVE_PARA_ID (destination) +/// | `fees` reserve +/// | `assets` reserve +/// | +/// | 1. execute `InitiateReserveWithdraw(assets_and_fees_batched_together)` +/// | \--> sends `WithdrawAsset(batch), ClearOrigin, BuyExecution(fees), DepositAsset` +/// \------------------------------------------> +/// ``` +#[test] +fn reserve_transfer_assets_with_destination_asset_reserve_and_destination_fee_reserve_works() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let origin_location: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { // we'll send just this foreign asset back to its reserve location and use it for fees as // well @@ -874,7 +666,6 @@ fn destination_asset_reserve_and_destination_fee_reserve_call( set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), - ALICE, foreign_initial_amount, true, ); @@ -893,19 +684,14 @@ fn destination_asset_reserve_and_destination_fee_reserve_call( assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer - let result = tested_call( + assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(dest.into()), Box::new(beneficiary.into()), Box::new(assets.into()), fee_index, Unlimited, - ); - assert_eq!(result, expected_result); - if expected_result.is_err() { - // short-circuit here for tests where we expect failure - return - } + )); let weight = BaseXcmWeight::get() * 2; let mut last_events = last_events(3).into_iter(); @@ -916,7 +702,7 @@ fn destination_asset_reserve_and_destination_fee_reserve_call( assert_eq!( last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: origin_location, + paying: beneficiary, fees: MultiAssets::new(), }) ); @@ -957,78 +743,31 @@ fn destination_asset_reserve_and_destination_fee_reserve_call( }); } -/// Test `transfer_assets` with destination asset reserve and destination fee reserve. -#[test] -fn transfer_assets_with_destination_asset_reserve_and_destination_fee_reserve_works() { - let expected_result = Ok(()); - destination_asset_reserve_and_destination_fee_reserve_call( - XcmPallet::transfer_assets, - expected_result, - ); -} - -/// Test `limited_reserve_transfer_assets` with destination asset reserve and destination fee -/// reserve. -#[test] -fn reserve_transfer_assets_with_destination_asset_reserve_and_destination_fee_reserve_works() { - let expected_result = Ok(()); - destination_asset_reserve_and_destination_fee_reserve_call( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with destination asset reserve and destination fee reserve +/// Test `reserve_transfer_assets` with remote asset reserve and destination fee reserve is /// disallowed. -#[test] -fn teleport_assets_with_destination_asset_reserve_and_destination_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - destination_asset_reserve_and_destination_fee_reserve_call( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - -/// Test `transfer_assets` with remote asset reserve and destination fee reserve is disallowed. /// /// Transferring foreign asset (reserve on `FOREIGN_ASSET_RESERVE_PARA_ID`) to /// `USDC_RESERVE_PARA_ID`. Using USDC (destination reserve) as fee. -fn remote_asset_reserve_and_destination_fee_reserve_call_disallowed( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ +#[test] +fn reserve_transfer_assets_with_remote_asset_reserve_and_destination_fee_reserve_disallowed() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { - // create sufficient foreign asset USDC + // create sufficient foreign asset USDC (0 total issuance) let usdc_initial_local_amount = 42; let (usdc_chain, _, usdc_id_multilocation) = set_up_foreign_asset( USDC_RESERVE_PARA_ID, Some(USDC_INNER_JUNCTION), - ALICE, usdc_initial_local_amount, true, ); - // create non-sufficient foreign asset BLA + // create non-sufficient foreign asset BLA (0 total issuance) let foreign_initial_amount = 142; let (_, _, foreign_asset_id_multilocation) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), - ALICE, foreign_initial_amount, false, ); @@ -1050,7 +789,7 @@ fn remote_asset_reserve_and_destination_fee_reserve_call_disallowed( assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer - let result = tested_call( + let result = XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(dest.into()), Box::new(beneficiary.into()), @@ -1058,7 +797,14 @@ fn remote_asset_reserve_and_destination_fee_reserve_call_disallowed( fee_index as u32, Unlimited, ); - assert_eq!(result, expected_result); + assert_eq!( + result, + Err(DispatchError::Module(ModuleError { + index: 4, + error: [22, 0, 0, 0], + message: Some("InvalidAssetUnsupportedReserve") + })) + ); // Alice native asset untouched assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); @@ -1073,76 +819,21 @@ fn remote_asset_reserve_and_destination_fee_reserve_call_disallowed( }); } -/// Test `transfer_assets` with remote asset reserve and destination fee reserve is disallowed. -#[test] -fn transfer_assets_with_remote_asset_reserve_and_destination_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [22, 0, 0, 0], - message: Some("InvalidAssetUnsupportedReserve"), - })); - remote_asset_reserve_and_destination_fee_reserve_call_disallowed( - XcmPallet::transfer_assets, - expected_result, - ); -} - -/// Test `limited_reserve_transfer_assets` with remote asset reserve and destination fee reserve is -/// disallowed. -#[test] -fn reserve_transfer_assets_with_remote_asset_reserve_and_destination_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [23, 0, 0, 0], - message: Some("TooManyReserves"), - })); - remote_asset_reserve_and_destination_fee_reserve_call_disallowed( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with remote asset reserve and destination fee reserve is -/// disallowed. -#[test] -fn teleport_assets_with_remote_asset_reserve_and_destination_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - remote_asset_reserve_and_destination_fee_reserve_call_disallowed( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - -/// Test `tested_call` with local asset reserve and remote fee reserve is disallowed. +/// Test `reserve_transfer_assets` with local asset reserve and remote fee reserve is disallowed. /// /// Transferring native asset (local reserve) to `OTHER_PARA_ID` (no teleport trust). Using foreign /// asset (`USDC_RESERVE_PARA_ID` remote reserve) for fees. -fn local_asset_reserve_and_remote_fee_reserve_call_disallowed( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ +#[test] +fn reserve_transfer_assets_with_local_asset_reserve_and_remote_fee_reserve_disallowed() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { - // create sufficient foreign asset USDC + // create sufficient foreign asset USDC (0 total issuance) let usdc_initial_local_amount = 142; let (_, usdc_chain_sovereign_account, usdc_id_multilocation) = set_up_foreign_asset( USDC_RESERVE_PARA_ID, Some(USDC_INNER_JUNCTION), - ALICE, usdc_initial_local_amount, true, ); @@ -1163,7 +854,7 @@ fn local_asset_reserve_and_remote_fee_reserve_call_disallowed( assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer - let result = tested_call( + let result = XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(dest.into()), Box::new(beneficiary.into()), @@ -1171,7 +862,14 @@ fn local_asset_reserve_and_remote_fee_reserve_call_disallowed( fee_index as u32, Unlimited, ); - assert_eq!(result, expected_result); + assert_eq!( + result, + Err(DispatchError::Module(ModuleError { + index: 4, + error: [22, 0, 0, 0], + message: Some("InvalidAssetUnsupportedReserve") + })) + ); assert_eq!(Assets::balance(usdc_id_multilocation, ALICE), usdc_initial_local_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // Sovereign account of reserve parachain is unchanged @@ -1184,86 +882,32 @@ fn local_asset_reserve_and_remote_fee_reserve_call_disallowed( }); } -/// Test `transfer_assets` with local asset reserve and remote fee reserve is disallowed. -#[test] -fn transfer_assets_with_local_asset_reserve_and_remote_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [22, 0, 0, 0], - message: Some("InvalidAssetUnsupportedReserve"), - })); - local_asset_reserve_and_remote_fee_reserve_call_disallowed( - XcmPallet::transfer_assets, - expected_result, - ); -} - -/// Test `limited_reserve_transfer_assets` with local asset reserve and remote fee reserve is +/// Test `reserve_transfer_assets` with destination asset reserve and remote fee reserve is /// disallowed. -#[test] -fn reserve_transfer_assets_with_local_asset_reserve_and_remote_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [23, 0, 0, 0], - message: Some("TooManyReserves"), - })); - local_asset_reserve_and_remote_fee_reserve_call_disallowed( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with local asset reserve and remote fee reserve is disallowed. -#[test] -fn teleport_assets_with_local_asset_reserve_and_remote_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - local_asset_reserve_and_remote_fee_reserve_call_disallowed( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - -/// Test `tested_call` with destination asset reserve and remote fee reserve is disallowed. /// /// Transferring native asset (local reserve) to `OTHER_PARA_ID` (no teleport trust). Using foreign /// asset (`USDC_RESERVE_PARA_ID` remote reserve) for fees. -fn destination_asset_reserve_and_remote_fee_reserve_call_disallowed( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ +#[test] +fn reserve_transfer_assets_with_destination_asset_reserve_and_remote_fee_reserve_disallowed() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { - // create sufficient foreign asset USDC + // create sufficient foreign asset USDC (0 total issuance) let usdc_initial_local_amount = 42; let (_, usdc_chain_sovereign_account, usdc_id_multilocation) = set_up_foreign_asset( USDC_RESERVE_PARA_ID, Some(USDC_INNER_JUNCTION), - ALICE, usdc_initial_local_amount, true, ); - // create non-sufficient foreign asset BLA + // create non-sufficient foreign asset BLA (0 total issuance) let foreign_initial_amount = 142; let (reserve_location, foreign_sovereign_account, foreign_asset_id_multilocation) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), - ALICE, foreign_initial_amount, false, ); @@ -1284,7 +928,7 @@ fn destination_asset_reserve_and_remote_fee_reserve_call_disallowed( assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer - let result = tested_call( + let result = XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(dest.into()), Box::new(beneficiary.into()), @@ -1292,7 +936,14 @@ fn destination_asset_reserve_and_remote_fee_reserve_call_disallowed( fee_index as u32, Unlimited, ); - assert_eq!(result, expected_result); + assert_eq!( + result, + Err(DispatchError::Module(ModuleError { + index: 4, + error: [22, 0, 0, 0], + message: Some("InvalidAssetUnsupportedReserve") + })) + ); // Alice native asset untouched assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); assert_eq!(Assets::balance(usdc_id_multilocation, ALICE), usdc_initial_local_amount); @@ -1310,51 +961,7 @@ fn destination_asset_reserve_and_remote_fee_reserve_call_disallowed( }); } -/// Test `transfer_assets` with destination asset reserve and remote fee reserve is disallowed. -#[test] -fn transfer_assets_with_destination_asset_reserve_and_remote_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [22, 0, 0, 0], - message: Some("InvalidAssetUnsupportedReserve"), - })); - destination_asset_reserve_and_remote_fee_reserve_call_disallowed( - XcmPallet::transfer_assets, - expected_result, - ); -} - -/// Test `limited_reserve_transfer_assets` with destination asset reserve and remote fee reserve is -/// disallowed. -#[test] -fn reserve_transfer_assets_with_destination_asset_reserve_and_remote_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [23, 0, 0, 0], - message: Some("TooManyReserves"), - })); - destination_asset_reserve_and_remote_fee_reserve_call_disallowed( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with destination asset reserve and remote fee reserve is -/// disallowed. -#[test] -fn teleport_assets_with_destination_asset_reserve_and_remote_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - destination_asset_reserve_and_remote_fee_reserve_call_disallowed( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - -/// Test `tested_call` with remote asset reserve and (same) remote fee reserve. +/// Test `reserve_transfer_assets` with remote asset reserve and (same) remote fee reserve. /// /// Transferring native asset (local reserve) to `OTHER_PARA_ID` (no teleport trust). Using foreign /// asset (`USDC_RESERVE_PARA_ID` remote reserve) for fees. @@ -1369,31 +976,18 @@ fn teleport_assets_with_destination_asset_reserve_and_remote_fee_reserve_disallo /// | -----------------> `C` executes `DepositReserveAsset(both)` dest `B` /// | --------------------------> `DepositAsset(both)` /// ``` -/// -/// Verifies `expected_result` -fn remote_asset_reserve_and_remote_fee_reserve_call( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ +#[test] +fn reserve_transfer_assets_with_remote_asset_reserve_and_remote_fee_reserve_works() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { - // create sufficient foreign asset USDC + // create sufficient foreign asset USDC (0 total issuance) let usdc_initial_local_amount = 142; let (usdc_chain, usdc_chain_sovereign_account, usdc_id_multilocation) = set_up_foreign_asset( USDC_RESERVE_PARA_ID, Some(USDC_INNER_JUNCTION), - ALICE, usdc_initial_local_amount, true, ); @@ -1402,12 +996,12 @@ fn remote_asset_reserve_and_remote_fee_reserve_call( let dest = RelayLocation::get().pushed_with_interior(Parachain(OTHER_PARA_ID)).unwrap(); let assets: MultiAssets = vec![(usdc_id_multilocation, SEND_AMOUNT).into()].into(); - let fee_index = 0u32; + let fee_index = 0; // reanchor according to test-case let context = UniversalLocation::get(); let expected_dest_on_reserve = dest.reanchored(&usdc_chain, context).unwrap(); - let fees = assets.get(fee_index as usize).unwrap().clone(); + let fees = assets.get(fee_index).unwrap().clone(); let (fees_half_1, fees_half_2) = XcmPallet::halve_fees(fees).unwrap(); let mut expected_assets_on_reserve = assets.clone(); expected_assets_on_reserve.reanchor(&usdc_chain, context).unwrap(); @@ -1419,20 +1013,14 @@ fn remote_asset_reserve_and_remote_fee_reserve_call( assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer - let result = tested_call( + assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(dest.into()), Box::new(beneficiary.into()), Box::new(assets.into()), - fee_index, + fee_index as u32, Unlimited, - ); - assert_eq!(result, expected_result); - if expected_result.is_err() { - // short-circuit here for tests where we expect failure - return - } - + )); assert!(matches!( last_event(), RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(_) }) @@ -1479,65 +1067,31 @@ fn remote_asset_reserve_and_remote_fee_reserve_call( }); } -/// Test `transfer_assets` with remote asset reserve and (same) remote fee reserve. -#[test] -fn transfer_assets_with_remote_asset_reserve_and_remote_fee_reserve_works() { - let expected_result = Ok(()); - remote_asset_reserve_and_remote_fee_reserve_call(XcmPallet::transfer_assets, expected_result); -} - -/// Test `limited_reserve_transfer_assets` with remote asset reserve and (same) remote fee reserve. -#[test] -fn reserve_transfer_assets_with_remote_asset_reserve_and_remote_fee_reserve_works() { - let expected_result = Ok(()); - remote_asset_reserve_and_remote_fee_reserve_call( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with remote asset reserve and (same) remote fee reserve -/// disallowed. -#[test] -fn teleport_assets_with_remote_asset_reserve_and_remote_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - remote_asset_reserve_and_remote_fee_reserve_call( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - -/// Test `tested_call` with local asset reserve and teleported fee. +/// Test `reserve_transfer_assets` with local asset reserve and teleported fee. /// /// Transferring native asset (local reserve) to `USDT_PARA_ID`. Using teleport-trusted USDT for /// fees. /// -/// Verifies `expected_result` -fn local_asset_reserve_and_teleported_fee_call( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ +/// ```nocompile +/// Here (source) USDT_PARA_ID (destination) +/// | `assets` reserve `fees` teleport-trust +/// | +/// | 1. execute `InitiateTeleport(fees)` +/// | \--> sends `ReceiveTeleportedAsset(fees), .., DepositAsset(fees)` +/// | 2. execute `TransferReserveAsset(assets)` +/// | \-> sends `ReserveAssetDeposited(assets), ClearOrigin, BuyExecution(fees), DepositAsset` +/// \------------------------------------------> +/// ``` +#[test] +fn reserve_transfer_assets_with_local_asset_reserve_and_teleported_fee_works() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let origin_location: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { - // create sufficient foreign asset USDT + // create sufficient foreign asset USDT (0 total issuance) let usdt_initial_local_amount = 42; let (usdt_chain, usdt_chain_sovereign_account, usdt_id_multilocation) = - set_up_foreign_asset(USDT_PARA_ID, None, ALICE, usdt_initial_local_amount, true); + set_up_foreign_asset(USDT_PARA_ID, None, usdt_initial_local_amount, true); // native assets transfer destination is USDT chain (teleport trust only for USDT) let dest = usdt_chain; @@ -1559,20 +1113,14 @@ fn local_asset_reserve_and_teleported_fee_call( assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer - let result = tested_call( + assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(dest.into()), Box::new(beneficiary.into()), Box::new(assets.into()), fee_index as u32, Unlimited, - ); - assert_eq!(result, expected_result); - if expected_result.is_err() { - // short-circuit here for tests where we expect failure - return - } - + )); let weight = BaseXcmWeight::get() * 3; let mut last_events = last_events(3).into_iter(); assert_eq!( @@ -1582,7 +1130,7 @@ fn local_asset_reserve_and_teleported_fee_call( assert_eq!( last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: origin_location, + paying: beneficiary, fees: MultiAssets::new(), }) ); @@ -1625,76 +1173,39 @@ fn local_asset_reserve_and_teleported_fee_call( }); } -/// Test `transfer_assets` with local asset reserve and teleported fee. -#[test] -fn transfer_assets_with_local_asset_reserve_and_teleported_fee_works() { - let expected_result = Ok(()); - local_asset_reserve_and_teleported_fee_call(XcmPallet::transfer_assets, expected_result); -} - -/// Test `limited_reserve_transfer_assets` with local asset reserve and teleported fee disallowed. -#[test] -fn reserve_transfer_assets_with_local_asset_reserve_and_teleported_fee_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [23, 0, 0, 0], - message: Some("TooManyReserves"), - })); - local_asset_reserve_and_teleported_fee_call( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with local asset reserve and teleported fee disallowed. -#[test] -fn teleport_assets_with_local_asset_reserve_and_teleported_fee_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - local_asset_reserve_and_teleported_fee_call( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - -/// Test `tested_call` with destination asset reserve and teleported fee. +/// Test `reserve_transfer_assets` with destination asset reserve and teleported fee. /// /// Transferring foreign asset (destination reserve) to `FOREIGN_ASSET_RESERVE_PARA_ID`. Using /// teleport-trusted USDT for fees. /// -/// Verifies `expected_result` -fn destination_asset_reserve_and_teleported_fee_call( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ +/// ```nocompile +/// Here (source) FOREIGN_ASSET_RESERVE_PARA_ID (destination) +/// | `fees` (USDT) teleport-trust +/// | `assets` reserve +/// | +/// | 1. execute `InitiateTeleport(fees)` +/// | \--> sends `ReceiveTeleportedAsset(fees), .., DepositAsset(fees)` +/// | 2. execute `InitiateReserveWithdraw(assets)` +/// | \--> sends `WithdrawAsset(asset), ClearOrigin, BuyExecution(fees), DepositAsset` +/// \------------------------------------------> +/// ``` +#[test] +fn reserve_transfer_assets_with_destination_asset_reserve_and_teleported_fee_works() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let origin_location: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { - // create sufficient foreign asset USDT + // create sufficient foreign asset USDT (0 total issuance) let usdt_initial_local_amount = 42; let (_, usdt_chain_sovereign_account, usdt_id_multilocation) = - set_up_foreign_asset(USDT_PARA_ID, None, ALICE, usdt_initial_local_amount, true); + set_up_foreign_asset(USDT_PARA_ID, None, usdt_initial_local_amount, true); - // create non-sufficient foreign asset BLA + // create non-sufficient foreign asset BLA (0 total issuance) let foreign_initial_amount = 142; let (reserve_location, foreign_sovereign_account, foreign_asset_id_multilocation) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), - ALICE, foreign_initial_amount, false, ); @@ -1720,20 +1231,14 @@ fn destination_asset_reserve_and_teleported_fee_call( assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); // do the transfer - let result = tested_call( + assert_ok!(XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(dest.into()), Box::new(beneficiary.into()), Box::new(assets.into()), fee_index as u32, Unlimited, - ); - assert_eq!(result, expected_result); - if expected_result.is_err() { - // short-circuit here for tests where we expect failure - return - } - + )); let weight = BaseXcmWeight::get() * 4; let mut last_events = last_events(3).into_iter(); assert_eq!( @@ -1743,7 +1248,7 @@ fn destination_asset_reserve_and_teleported_fee_call( assert_eq!( last_events.next().unwrap(), RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: origin_location, + paying: beneficiary, fees: MultiAssets::new(), }) ); @@ -1798,73 +1303,26 @@ fn destination_asset_reserve_and_teleported_fee_call( }); } -/// Test `transfer_assets` with destination asset reserve and teleported fee. -#[test] -fn transfer_assets_with_destination_asset_reserve_and_teleported_fee_works() { - let expected_result = Ok(()); - destination_asset_reserve_and_teleported_fee_call(XcmPallet::transfer_assets, expected_result); -} - -/// Test `limited_reserve_transfer_assets` with destination asset reserve and teleported fee -/// disallowed. -#[test] -fn reserve_transfer_assets_with_destination_asset_reserve_and_teleported_fee_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [23, 0, 0, 0], - message: Some("TooManyReserves"), - })); - destination_asset_reserve_and_teleported_fee_call( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with destination asset reserve and teleported fee disallowed. -#[test] -fn teleport_assets_with_destination_asset_reserve_and_teleported_fee_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - destination_asset_reserve_and_teleported_fee_call( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - -/// Test `tested_call` with remote asset reserve and teleported fee is disallowed. +/// Test `reserve_transfer_assets` with remote asset reserve and teleported fee is disallowed. /// /// Transferring foreign asset (reserve on `FOREIGN_ASSET_RESERVE_PARA_ID`) to `USDT_PARA_ID`. /// Using teleport-trusted USDT for fees. -fn remote_asset_reserve_and_teleported_fee_reserve_call_disallowed( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ +#[test] +fn reserve_transfer_assets_with_remote_asset_reserve_and_teleported_fee_disallowed() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { - // create sufficient foreign asset USDT + // create sufficient foreign asset USDT (0 total issuance) let usdt_initial_local_amount = 42; let (usdt_chain, usdt_chain_sovereign_account, usdt_id_multilocation) = - set_up_foreign_asset(USDT_PARA_ID, None, ALICE, usdt_initial_local_amount, true); + set_up_foreign_asset(USDT_PARA_ID, None, usdt_initial_local_amount, true); - // create non-sufficient foreign asset BLA + // create non-sufficient foreign asset BLA (0 total issuance) let foreign_initial_amount = 142; let (_, reserve_sovereign_account, foreign_asset_id_multilocation) = set_up_foreign_asset( FOREIGN_ASSET_RESERVE_PARA_ID, Some(FOREIGN_ASSET_INNER_JUNCTION), - ALICE, foreign_initial_amount, false, ); @@ -1883,8 +1341,8 @@ fn remote_asset_reserve_and_teleported_fee_reserve_call_disallowed( assert_eq!(Assets::balance(usdt_id_multilocation, ALICE), usdt_initial_local_amount); assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); - // try the transfer - let result = tested_call( + // do the transfer + let result = XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(dest.into()), Box::new(beneficiary.into()), @@ -1892,7 +1350,14 @@ fn remote_asset_reserve_and_teleported_fee_reserve_call_disallowed( fee_index as u32, Unlimited, ); - assert_eq!(result, expected_result); + assert_eq!( + result, + Err(DispatchError::Module(ModuleError { + index: 4, + error: [22, 0, 0, 0], + message: Some("InvalidAssetUnsupportedReserve") + })) + ); // Alice native asset untouched assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); assert_eq!(Assets::balance(usdt_id_multilocation, ALICE), usdt_initial_local_amount); @@ -1910,62 +1375,20 @@ fn remote_asset_reserve_and_teleported_fee_reserve_call_disallowed( }); } -/// Test `transfer_assets` with remote asset reserve and teleported fee is disallowed. -#[test] -fn transfer_assets_with_remote_asset_reserve_and_teleported_fee_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [22, 0, 0, 0], - message: Some("InvalidAssetUnsupportedReserve"), - })); - remote_asset_reserve_and_teleported_fee_reserve_call_disallowed( - XcmPallet::transfer_assets, - expected_result, - ); -} - -/// Test `limited_reserve_transfer_assets` with remote asset reserve and teleported fee is -/// disallowed. -#[test] -fn reserve_transfer_assets_with_remote_asset_reserve_and_teleported_fee_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [23, 0, 0, 0], - message: Some("TooManyReserves"), - })); - remote_asset_reserve_and_teleported_fee_reserve_call_disallowed( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with remote asset reserve and teleported fee is disallowed. -#[test] -fn teleport_assets_with_remote_asset_reserve_and_teleported_fee_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - remote_asset_reserve_and_teleported_fee_reserve_call_disallowed( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - /// Test `reserve_transfer_assets` single asset which is teleportable - should fail. /// /// Attempting to reserve-transfer teleport-trusted USDT to `USDT_PARA_ID` should fail. #[test] -fn reserve_transfer_assets_with_teleportable_asset_disallowed() { +fn reserve_transfer_assets_with_teleportable_asset_fails() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { - // create sufficient foreign asset USDT + // create sufficient foreign asset USDT (0 total issuance) let usdt_initial_local_amount = 42; let (usdt_chain, usdt_chain_sovereign_account, usdt_id_multilocation) = - set_up_foreign_asset(USDT_PARA_ID, None, ALICE, usdt_initial_local_amount, true); + set_up_foreign_asset(USDT_PARA_ID, None, usdt_initial_local_amount, true); // transfer destination is USDT chain (foreign asset needs to go through its reserve chain) let dest = usdt_chain; @@ -2005,9 +1428,9 @@ fn reserve_transfer_assets_with_teleportable_asset_disallowed() { }); } -/// Test `transfer_assets` with teleportable fee that is filtered - should fail. +/// Test `reserve_transfer_assets` with teleportable fee that is filtered - should fail. #[test] -fn transfer_assets_with_filtered_teleported_fee_disallowed() { +fn reserve_transfer_assets_with_filtered_teleported_fee_disallowed() { let beneficiary: MultiLocation = AccountId32 { network: None, id: BOB.into() }.into(); new_test_ext_with_balances(vec![(ALICE, INITIAL_BALANCE)]).execute_with(|| { let (assets, fee_index, _, _) = into_multiassets_checked( @@ -2016,7 +1439,7 @@ fn transfer_assets_with_filtered_teleported_fee_disallowed() { // native asset to transfer (not used for fees) - local reserve (MultiLocation::here(), SEND_AMOUNT).into(), ); - let result = XcmPallet::transfer_assets( + let result = XcmPallet::limited_reserve_transfer_assets( RuntimeOrigin::signed(ALICE), Box::new(FilteredTeleportLocation::get().into()), Box::new(beneficiary.into()), @@ -2043,14 +1466,14 @@ fn transfer_assets_with_filtered_teleported_fee_disallowed() { #[test] fn intermediary_error_reverts_side_effects() { let balances = vec![(ALICE, INITIAL_BALANCE)]; - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); + let beneficiary: MultiLocation = + Junction::AccountId32 { network: None, id: ALICE.into() }.into(); new_test_ext_with_balances(balances).execute_with(|| { - // create sufficient foreign asset USDC + // create sufficient foreign asset USDC (0 total issuance) let usdc_initial_local_amount = 142; let (_, usdc_chain_sovereign_account, usdc_id_multilocation) = set_up_foreign_asset( USDC_RESERVE_PARA_ID, Some(USDC_INNER_JUNCTION), - ALICE, usdc_initial_local_amount, true, ); @@ -2092,330 +1515,3 @@ fn intermediary_error_reverts_side_effects() { assert_eq!(sent_xcm(), vec![]); }); } - -/// Test `tested_call` with teleportable asset and local fee reserve. -/// -/// Transferring USDT to `USDT_PARA_ID` (teleport trust). Using native asset (local reserve) for -/// fees. -/// -/// Verifies `expected_result` -fn teleport_asset_using_local_fee_reserve_call( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ - let weight = BaseXcmWeight::get() * 3; - let balances = vec![(ALICE, INITIAL_BALANCE)]; - let origin_location: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); - new_test_ext_with_balances(balances).execute_with(|| { - // create non-sufficient foreign asset USDT - let usdt_initial_local_amount = 42; - let (usdt_chain, usdt_chain_sovereign_account, usdt_id_multilocation) = - set_up_foreign_asset(USDT_PARA_ID, None, ALICE, usdt_initial_local_amount, false); - - // transfer destination is reserve location (no teleport trust) - let dest = usdt_chain; - - let (assets, fee_index, fee_asset, xfer_asset) = into_multiassets_checked( - // native asset for fee - local reserve - (MultiLocation::here(), FEE_AMOUNT).into(), - // USDT to transfer - destination reserve - (usdt_id_multilocation, SEND_AMOUNT).into(), - ); - - // reanchor according to test-case - let context = UniversalLocation::get(); - let expected_fee = fee_asset.reanchored(&dest, context).unwrap(); - let expected_asset = xfer_asset.reanchored(&dest, context).unwrap(); - - // balances checks before - assert_eq!(Assets::balance(usdt_id_multilocation, ALICE), usdt_initial_local_amount); - assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); - - // do the transfer - let result = tested_call( - RuntimeOrigin::signed(ALICE), - Box::new(dest.into()), - Box::new(beneficiary.into()), - Box::new(assets.into()), - fee_index as u32, - Unlimited, - ); - assert_eq!(result, expected_result); - if expected_result.is_err() { - // short-circuit here for tests where we expect failure - return - } - - let mut last_events = last_events(3).into_iter(); - assert_eq!( - last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(weight) }) - ); - - // Alice spent (transferred) amount - assert_eq!( - Assets::balance(usdt_id_multilocation, ALICE), - usdt_initial_local_amount - SEND_AMOUNT - ); - // Alice used native asset for fees - assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE - FEE_AMOUNT); - // Destination account (parachain account) added native reserve to balances - assert_eq!(Balances::free_balance(usdt_chain_sovereign_account.clone()), FEE_AMOUNT); - assert_eq!(Assets::balance(usdt_id_multilocation, usdt_chain_sovereign_account), 0); - // Verify total and active issuance of foreign BLA have decreased (burned on - // reserve-withdraw) - let expected_issuance = usdt_initial_local_amount - SEND_AMOUNT; - assert_eq!(Assets::total_issuance(usdt_id_multilocation), expected_issuance); - assert_eq!(Assets::active_issuance(usdt_id_multilocation), expected_issuance); - - // Verify sent XCM program - assert_eq!( - sent_xcm(), - vec![( - dest, - // `fees` are being sent through local-reserve transfer because fee reserve is - // local chain; `assets` are burned on source and withdrawn from SA here - Xcm(vec![ - ReserveAssetDeposited(expected_fee.clone().into()), - buy_limited_execution(expected_fee, Unlimited), - ReceiveTeleportedAsset(expected_asset.into()), - ClearOrigin, - DepositAsset { assets: AllCounted(2).into(), beneficiary }, - ]) - )] - ); - assert_eq!( - last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: origin_location, - fees: MultiAssets::new(), - }) - ); - assert!(matches!( - last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::Sent { .. }) - )); - }); -} - -/// Test `transfer_assets` with teleportable asset and local fee reserve. -#[test] -fn transfer_assets_with_teleportable_asset_and_local_fee_reserve_works() { - let expected_result = Ok(()); - teleport_asset_using_local_fee_reserve_call(XcmPallet::transfer_assets, expected_result); -} - -/// Test `limited_reserve_transfer_assets` with teleportable asset and local fee reserve disallowed. -#[test] -fn reserve_transfer_assets_with_teleportable_asset_and_local_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - teleport_asset_using_local_fee_reserve_call( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with teleportable asset and local fee reserve disallowed. -#[test] -fn teleport_assets_with_teleportable_asset_and_local_fee_reserve_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - teleport_asset_using_local_fee_reserve_call( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} - -/// Test `tested_call` with teleported asset reserve and destination fee. -/// -/// Transferring USDT to `FOREIGN_ASSET_RESERVE_PARA_ID` (teleport trust). Using foreign asset -/// (destination reserve) for fees. -/// -/// Verifies `expected_result` -fn teleported_asset_using_destination_reserve_fee_call( - tested_call: Call, - expected_result: DispatchResult, -) where - Call: FnOnce( - OriginFor, - Box, - Box, - Box, - u32, - WeightLimit, - ) -> DispatchResult, -{ - let balances = vec![(ALICE, INITIAL_BALANCE)]; - let origin_location: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); - let beneficiary: MultiLocation = AccountId32 { network: None, id: ALICE.into() }.into(); - new_test_ext_with_balances(balances).execute_with(|| { - // create sufficient foreign asset BLA to be used for fees - let foreign_initial_amount = 142; - let (reserve_location, foreign_sovereign_account, foreign_asset_id_multilocation) = - set_up_foreign_asset( - FOREIGN_ASSET_RESERVE_PARA_ID, - Some(FOREIGN_ASSET_INNER_JUNCTION), - ALICE, - foreign_initial_amount, - true, - ); - - // create non-sufficient foreign asset USDT - let usdt_initial_local_amount = 42; - let (_, usdt_chain_sovereign_account, usdt_id_multilocation) = - set_up_foreign_asset(USDT_PARA_ID, None, ALICE, usdt_initial_local_amount, false); - - // transfer destination is BLA reserve location - let dest = reserve_location; - let dest_sovereign_account = foreign_sovereign_account; - - let (assets, fee_index, fee_asset, xfer_asset) = into_multiassets_checked( - // foreign asset BLA used for fees - destination reserve - (foreign_asset_id_multilocation, FEE_AMOUNT).into(), - // USDT to transfer - teleported - (usdt_id_multilocation, SEND_AMOUNT).into(), - ); - - // reanchor according to test-case - let context = UniversalLocation::get(); - let expected_fee = fee_asset.reanchored(&dest, context).unwrap(); - let expected_asset = xfer_asset.reanchored(&dest, context).unwrap(); - - // balances checks before - assert_eq!(Assets::balance(usdt_id_multilocation, ALICE), usdt_initial_local_amount); - assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); - - // do the transfer - let result = tested_call( - RuntimeOrigin::signed(ALICE), - Box::new(dest.into()), - Box::new(beneficiary.into()), - Box::new(assets.into()), - fee_index as u32, - Unlimited, - ); - assert_eq!(result, expected_result); - if expected_result.is_err() { - // short-circuit here for tests where we expect failure - return - } - - let weight = BaseXcmWeight::get() * 4; - let mut last_events = last_events(3).into_iter(); - assert_eq!( - last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::Attempted { outcome: Outcome::Complete(weight) }) - ); - assert_eq!( - last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::FeesPaid { - paying: origin_location, - fees: MultiAssets::new(), - }) - ); - assert!(matches!( - last_events.next().unwrap(), - RuntimeEvent::XcmPallet(crate::Event::Sent { .. }) - )); - // Alice native asset untouched - assert_eq!(Balances::free_balance(ALICE), INITIAL_BALANCE); - // Alice spent USDT for fees - assert_eq!( - Assets::balance(usdt_id_multilocation, ALICE), - usdt_initial_local_amount - SEND_AMOUNT - ); - // Alice transferred BLA - assert_eq!( - Assets::balance(foreign_asset_id_multilocation, ALICE), - foreign_initial_amount - FEE_AMOUNT - ); - // Verify balances of USDT reserve parachain - assert_eq!(Balances::free_balance(usdt_chain_sovereign_account.clone()), 0); - assert_eq!(Assets::balance(usdt_id_multilocation, usdt_chain_sovereign_account), 0); - // Verify balances of transferred-asset reserve parachain - assert_eq!(Balances::free_balance(dest_sovereign_account.clone()), 0); - assert_eq!(Assets::balance(foreign_asset_id_multilocation, dest_sovereign_account), 0); - // Verify total and active issuance of USDT have decreased (teleported) - let expected_usdt_issuance = usdt_initial_local_amount - SEND_AMOUNT; - assert_eq!(Assets::total_issuance(usdt_id_multilocation), expected_usdt_issuance); - assert_eq!(Assets::active_issuance(usdt_id_multilocation), expected_usdt_issuance); - // Verify total and active issuance of foreign BLA asset have decreased (burned on - // reserve-withdraw) - let expected_bla_issuance = foreign_initial_amount - FEE_AMOUNT; - assert_eq!(Assets::total_issuance(foreign_asset_id_multilocation), expected_bla_issuance); - assert_eq!(Assets::active_issuance(foreign_asset_id_multilocation), expected_bla_issuance); - - // Verify sent XCM program - assert_eq!( - sent_xcm(), - vec![( - dest, - Xcm(vec![ - // fees are withdrawn from origin's local SA - WithdrawAsset(expected_fee.clone().into()), - buy_limited_execution(expected_fee, Unlimited), - // assets are teleported to destination chain - ReceiveTeleportedAsset(expected_asset.into()), - ClearOrigin, - DepositAsset { assets: AllCounted(2).into(), beneficiary }, - ]) - )] - ); - }); -} - -/// Test `transfer_assets` with teleported asset reserve and destination fee. -#[test] -fn transfer_teleported_assets_using_destination_reserve_fee_works() { - let expected_result = Ok(()); - teleported_asset_using_destination_reserve_fee_call( - XcmPallet::transfer_assets, - expected_result, - ); -} - -/// Test `limited_reserve_transfer_assets` with teleported asset reserve and destination fee -/// disallowed. -#[test] -fn reserve_transfer_teleported_assets_using_destination_reserve_fee_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - teleported_asset_using_destination_reserve_fee_call( - XcmPallet::limited_reserve_transfer_assets, - expected_result, - ); -} - -/// Test `limited_teleport_assets` with teleported asset reserve and destination fee disallowed. -#[test] -fn teleport_assets_using_destination_reserve_fee_disallowed() { - let expected_result = Err(DispatchError::Module(ModuleError { - index: 4, - error: [2, 0, 0, 0], - message: Some("Filtered"), - })); - teleported_asset_using_destination_reserve_fee_call( - XcmPallet::limited_teleport_assets, - expected_result, - ); -} diff --git a/polkadot/xcm/pallet-xcm/src/tests/mod.rs b/polkadot/xcm/pallet-xcm/src/tests/mod.rs index e7a6fdc9dce..056c7dcc196 100644 --- a/polkadot/xcm/pallet-xcm/src/tests/mod.rs +++ b/polkadot/xcm/pallet-xcm/src/tests/mod.rs @@ -16,7 +16,7 @@ #![cfg(test)] -pub(crate) mod assets_transfer; +mod assets_transfer; use crate::{ mock::*, AssetTraps, CurrentMigration, Error, LatestVersionedMultiLocation, Queries, @@ -774,13 +774,12 @@ fn subscription_side_upgrades_work_without_notify() { #[test] fn subscriber_side_subscription_works() { - new_test_ext_with_balances_and_xcm_version(vec![], Some(XCM_VERSION)).execute_with(|| { + new_test_ext_with_balances(vec![]).execute_with(|| { let remote: MultiLocation = Parachain(1000).into(); assert_ok!(XcmPallet::force_subscribe_version_notify( RuntimeOrigin::root(), Box::new(remote.into()), )); - assert_eq!(XcmPallet::get_version_for(&remote), None); take_sent_xcm(); // Assume subscription target is working ok. @@ -799,7 +798,6 @@ fn subscriber_side_subscription_works() { let r = XcmExecutor::::execute_xcm(remote, message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); assert_eq!(take_sent_xcm(), vec![]); - assert_eq!(XcmPallet::get_version_for(&remote), Some(1)); // This message cannot be sent to a v2 remote. let v2_msg = xcm::v2::Xcm::<()>(vec![xcm::v2::Instruction::Trap(0)]); @@ -817,8 +815,6 @@ fn subscriber_side_subscription_works() { let hash = fake_message_hash(&message); let r = XcmExecutor::::execute_xcm(remote, message, hash, weight); assert_eq!(r, Outcome::Complete(weight)); - assert_eq!(take_sent_xcm(), vec![]); - assert_eq!(XcmPallet::get_version_for(&remote), Some(2)); // This message can now be sent to remote as it's v2. assert_eq!( @@ -831,7 +827,7 @@ fn subscriber_side_subscription_works() { /// We should auto-subscribe when we don't know the remote's version. #[test] fn auto_subscription_works() { - new_test_ext_with_balances_and_xcm_version(vec![], None).execute_with(|| { + new_test_ext_with_balances(vec![]).execute_with(|| { let remote_v2: MultiLocation = Parachain(1000).into(); let remote_v3: MultiLocation = Parachain(1001).into(); @@ -999,68 +995,3 @@ fn subscription_side_upgrades_work_with_multistage_notify() { ); }); } - -#[test] -fn get_and_wrap_version_works() { - new_test_ext_with_balances_and_xcm_version(vec![], None).execute_with(|| { - let remote_a: MultiLocation = Parachain(1000).into(); - let remote_b: MultiLocation = Parachain(1001).into(); - let remote_c: MultiLocation = Parachain(1002).into(); - - // no `safe_xcm_version` version at `GenesisConfig` - assert_eq!(XcmPallet::get_version_for(&remote_a), None); - assert_eq!(XcmPallet::get_version_for(&remote_b), None); - assert_eq!(XcmPallet::get_version_for(&remote_c), None); - assert_eq!(VersionDiscoveryQueue::::get().into_inner(), vec![]); - - // set default XCM version (a.k.a. `safe_xcm_version`) - assert_ok!(XcmPallet::force_default_xcm_version(RuntimeOrigin::root(), Some(1))); - assert_eq!(XcmPallet::get_version_for(&remote_a), None); - assert_eq!(XcmPallet::get_version_for(&remote_b), None); - assert_eq!(XcmPallet::get_version_for(&remote_c), None); - assert_eq!(VersionDiscoveryQueue::::get().into_inner(), vec![]); - - // set XCM version only for `remote_a` - assert_ok!(XcmPallet::force_xcm_version( - RuntimeOrigin::root(), - Box::new(remote_a), - XCM_VERSION - )); - assert_eq!(XcmPallet::get_version_for(&remote_a), Some(XCM_VERSION)); - assert_eq!(XcmPallet::get_version_for(&remote_b), None); - assert_eq!(XcmPallet::get_version_for(&remote_c), None); - assert_eq!(VersionDiscoveryQueue::::get().into_inner(), vec![]); - - let xcm = Xcm::<()>::default(); - - // wrap version - works because remote_a has `XCM_VERSION` - assert_eq!( - XcmPallet::wrap_version(&remote_a, xcm.clone()), - Ok(VersionedXcm::from(xcm.clone())) - ); - // does not work because remote_b has unknown version and default is set to 1, and - // `XCM_VERSION` cannot be wrapped to the `1` - assert_eq!(XcmPallet::wrap_version(&remote_b, xcm.clone()), Err(())); - assert_eq!(VersionDiscoveryQueue::::get().into_inner(), vec![(remote_b.into(), 1)]); - - // set default to the `XCM_VERSION` - assert_ok!(XcmPallet::force_default_xcm_version(RuntimeOrigin::root(), Some(XCM_VERSION))); - assert_eq!(XcmPallet::get_version_for(&remote_b), None); - assert_eq!(XcmPallet::get_version_for(&remote_c), None); - - // now works, because default is `XCM_VERSION` - assert_eq!( - XcmPallet::wrap_version(&remote_b, xcm.clone()), - Ok(VersionedXcm::from(xcm.clone())) - ); - assert_eq!(VersionDiscoveryQueue::::get().into_inner(), vec![(remote_b.into(), 2)]); - - // change remote_c to `1` - assert_ok!(XcmPallet::force_xcm_version(RuntimeOrigin::root(), Box::new(remote_c), 1)); - - // does not work because remote_c has `1` and default is `XCM_VERSION` which cannot be - // wrapped to the `1` - assert_eq!(XcmPallet::wrap_version(&remote_c, xcm.clone()), Err(())); - assert_eq!(VersionDiscoveryQueue::::get().into_inner(), vec![(remote_b.into(), 2)]); - }) -} diff --git a/polkadot/xcm/procedural/Cargo.toml b/polkadot/xcm/procedural/Cargo.toml index 8467016070a..8ab27c91dae 100644 --- a/polkadot/xcm/procedural/Cargo.toml +++ b/polkadot/xcm/procedural/Cargo.toml @@ -7,16 +7,13 @@ license.workspace = true version = "1.0.0" publish = true -[lints] -workspace = true - [lib] proc-macro = true [dependencies] proc-macro2 = "1.0.56" quote = "1.0.28" -syn = "2.0.40" +syn = "2.0.38" Inflector = "0.11.4" [dev-dependencies] diff --git a/polkadot/xcm/src/double_encoded.rs b/polkadot/xcm/src/double_encoded.rs index 45856f657d1..875b811da3f 100644 --- a/polkadot/xcm/src/double_encoded.rs +++ b/polkadot/xcm/src/double_encoded.rs @@ -25,7 +25,6 @@ use parity_scale_codec::{Decode, DecodeLimit, Encode}; #[codec(decode_bound())] #[scale_info(bounds(), skip_type_params(T))] #[scale_info(replace_segment("staging_xcm", "xcm"))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub struct DoubleEncoded { encoded: Vec, #[codec(skip)] diff --git a/polkadot/xcm/src/lib.rs b/polkadot/xcm/src/lib.rs index ddad0b5303b..d804e4bf735 100644 --- a/polkadot/xcm/src/lib.rs +++ b/polkadot/xcm/src/lib.rs @@ -373,12 +373,6 @@ pub trait WrapVersion { ) -> Result, ()>; } -/// Check and return the `Version` that should be used for the `Xcm` datum for the destination -/// `MultiLocation`, which will interpret it. -pub trait GetVersion { - fn get_version_for(dest: &latest::MultiLocation) -> Option; -} - /// `()` implementation does nothing with the XCM, just sending with whatever version it was /// authored as. impl WrapVersion for () { @@ -401,11 +395,6 @@ impl WrapVersion for AlwaysV2 { Ok(VersionedXcm::::V2(xcm.into().try_into()?)) } } -impl GetVersion for AlwaysV2 { - fn get_version_for(_dest: &latest::MultiLocation) -> Option { - Some(v2::VERSION) - } -} /// `WrapVersion` implementation which attempts to always convert the XCM to version 3 before /// wrapping it. @@ -418,11 +407,6 @@ impl WrapVersion for AlwaysV3 { Ok(VersionedXcm::::V3(xcm.into().try_into()?)) } } -impl GetVersion for AlwaysV3 { - fn get_version_for(_dest: &latest::MultiLocation) -> Option { - Some(v3::VERSION) - } -} /// `WrapVersion` implementation which attempts to always convert the XCM to the latest version /// before wrapping it. @@ -434,8 +418,8 @@ pub type AlwaysLts = AlwaysV3; pub mod prelude { pub use super::{ - latest::prelude::*, AlwaysLatest, AlwaysLts, AlwaysV2, AlwaysV3, GetVersion, IntoVersion, - Unsupported, Version as XcmVersion, VersionedAssetId, VersionedInteriorMultiLocation, + latest::prelude::*, AlwaysLatest, AlwaysLts, AlwaysV2, AlwaysV3, IntoVersion, Unsupported, + Version as XcmVersion, VersionedAssetId, VersionedInteriorMultiLocation, VersionedMultiAsset, VersionedMultiAssets, VersionedMultiLocation, VersionedResponse, VersionedXcm, WrapVersion, }; diff --git a/polkadot/xcm/src/v2/mod.rs b/polkadot/xcm/src/v2/mod.rs index 188b7f0b5c9..7f654ebfd9e 100644 --- a/polkadot/xcm/src/v2/mod.rs +++ b/polkadot/xcm/src/v2/mod.rs @@ -82,7 +82,6 @@ pub use traits::{Error, ExecuteXcm, GetWeight, Outcome, Result, SendError, SendR /// Basically just the XCM (more general) version of `ParachainDispatchOrigin`. #[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] #[scale_info(replace_segment("staging_xcm", "xcm"))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub enum OriginKind { /// Origin should just be the native dispatch origin representation for the sender in the /// local runtime framework. For Cumulus/Frame chains this is the `Parachain` or `Relay` origin diff --git a/polkadot/xcm/src/v3/junction.rs b/polkadot/xcm/src/v3/junction.rs index 6ae339db2ae..47429a8c36e 100644 --- a/polkadot/xcm/src/v3/junction.rs +++ b/polkadot/xcm/src/v3/junction.rs @@ -49,7 +49,6 @@ use serde::{Deserialize, Serialize}; Serialize, Deserialize, )] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum NetworkId { /// Network specified by the first 32 bytes of its genesis block. @@ -76,8 +75,6 @@ pub enum NetworkId { BitcoinCore, /// The Bitcoin network, including hard-forks supported by Bitcoin Cash developers. BitcoinCash, - /// The Polkadot Bulletin chain. - PolkadotBulletin, } impl From for Option { @@ -120,7 +117,6 @@ impl TryFrom for NetworkId { Serialize, Deserialize, )] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum BodyId { /// The only body in its context. @@ -192,7 +188,6 @@ impl TryFrom for BodyId { Serialize, Deserialize, )] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum BodyPart { /// The body's declaration, under whatever means it decides. @@ -269,7 +264,6 @@ impl TryFrom for BodyPart { Serialize, Deserialize, )] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum Junction { /// An indexed parachain belonging to and operated by the context. diff --git a/polkadot/xcm/src/v3/junctions.rs b/polkadot/xcm/src/v3/junctions.rs index 88da20cb1a1..d1cbc2dbed4 100644 --- a/polkadot/xcm/src/v3/junctions.rs +++ b/polkadot/xcm/src/v3/junctions.rs @@ -44,7 +44,6 @@ pub(crate) const MAX_JUNCTIONS: usize = 8; serde::Serialize, serde::Deserialize, )] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum Junctions { /// The interpreting consensus system. diff --git a/polkadot/xcm/src/v3/mod.rs b/polkadot/xcm/src/v3/mod.rs index 50b7a539122..bbdd504ceb0 100644 --- a/polkadot/xcm/src/v3/mod.rs +++ b/polkadot/xcm/src/v3/mod.rs @@ -69,7 +69,6 @@ pub type QueryId = u64; #[codec(encode_bound())] #[scale_info(bounds(), skip_type_params(Call))] #[scale_info(replace_segment("staging_xcm", "xcm"))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub struct Xcm(pub Vec>); /// The maximal number of instructions in an XCM before decoding fails. @@ -233,19 +232,15 @@ pub mod prelude { } parameter_types! { - #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub MaxPalletNameLen: u32 = 48; /// Maximum size of the encoded error code coming from a `Dispatch` result, used for /// `MaybeErrorCode`. This is not (yet) enforced, so it's just an indication of expectation. - #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub MaxDispatchErrorLen: u32 = 128; - #[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub MaxPalletsInfo: u32 = 64; } #[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] #[scale_info(replace_segment("staging_xcm", "xcm"))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub struct PalletInfo { #[codec(compact)] pub index: u32, @@ -277,7 +272,6 @@ impl PalletInfo { #[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] #[scale_info(replace_segment("staging_xcm", "xcm"))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub enum MaybeErrorCode { Success, Error(BoundedVec), @@ -302,7 +296,6 @@ impl Default for MaybeErrorCode { /// Response data to a query. #[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] #[scale_info(replace_segment("staging_xcm", "xcm"))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub enum Response { /// No response. Serves as a neutral default. Null, @@ -327,7 +320,6 @@ impl Default for Response { /// Information regarding the composition of a query response. #[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] #[scale_info(replace_segment("staging_xcm", "xcm"))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub struct QueryResponseInfo { /// The destination to which the query response message should be send. pub destination: MultiLocation, @@ -341,7 +333,6 @@ pub struct QueryResponseInfo { /// An optional weight limit. #[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo)] #[scale_info(replace_segment("staging_xcm", "xcm"))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub enum WeightLimit { /// No weight limit imposed. Unlimited, @@ -426,7 +417,6 @@ impl XcmContext { #[codec(decode_bound())] #[scale_info(bounds(), skip_type_params(Call))] #[scale_info(replace_segment("staging_xcm", "xcm"))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub enum Instruction { /// Withdraw asset(s) (`assets`) from the ownership of `origin` and place them into the Holding /// Register. diff --git a/polkadot/xcm/src/v3/multiasset.rs b/polkadot/xcm/src/v3/multiasset.rs index c8801f5a461..454120a1a7b 100644 --- a/polkadot/xcm/src/v3/multiasset.rs +++ b/polkadot/xcm/src/v3/multiasset.rs @@ -47,7 +47,6 @@ use scale_info::TypeInfo; Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, TypeInfo, MaxEncodedLen, )] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum AssetInstance { /// Undefined - used if the non-fungible asset class has only one instance. @@ -244,7 +243,6 @@ impl TryFrom for u128 { /// instance. #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum Fungibility { /// A fungible asset; we record a number of units, as a `u128` in the inner item. @@ -315,7 +313,6 @@ impl TryFrom for Fungibility { Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo, MaxEncodedLen, )] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum WildFungibility { /// The asset is fungible. @@ -340,7 +337,6 @@ impl TryFrom for WildFungibility { Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo, MaxEncodedLen, )] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum AssetId { /// A specific location identifying an asset. @@ -416,7 +412,6 @@ impl AssetId { /// Either an amount of a single fungible asset, or a single well-identified non-fungible asset. #[derive(Clone, Eq, PartialEq, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub struct MultiAsset { /// The overall asset identity (aka *class*, in the case of a non-fungible). @@ -515,7 +510,6 @@ impl TryFrom for MultiAsset { /// - The number of items should grow no larger than `MAX_ITEMS_IN_MULTIASSETS`. #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, TypeInfo, Default)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub struct MultiAssets(Vec); @@ -716,7 +710,6 @@ impl MultiAssets { /// A wildcard representing a set of assets. #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum WildMultiAsset { /// All assets in Holding. @@ -830,7 +823,6 @@ impl, B: Into> From<(A, B)> for WildMultiAsset /// `MultiAsset` collection, defined either by a number of `MultiAssets` or a single wildcard. #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)] #[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] #[scale_info(replace_segment("staging_xcm", "xcm"))] pub enum MultiAssetFilter { /// Specify the filter as being everything contained by the given `MultiAssets` inner. diff --git a/polkadot/xcm/src/v3/multilocation.rs b/polkadot/xcm/src/v3/multilocation.rs index 9649b1b3207..89e25984443 100644 --- a/polkadot/xcm/src/v3/multilocation.rs +++ b/polkadot/xcm/src/v3/multilocation.rs @@ -66,7 +66,6 @@ use scale_info::TypeInfo; serde::Serialize, serde::Deserialize, )] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub struct MultiLocation { /// The number of parent junctions at the beginning of this `MultiLocation`. pub parents: u8, diff --git a/polkadot/xcm/src/v3/traits.rs b/polkadot/xcm/src/v3/traits.rs index 29bd40a6a2d..6054bf1456a 100644 --- a/polkadot/xcm/src/v3/traits.rs +++ b/polkadot/xcm/src/v3/traits.rs @@ -30,7 +30,6 @@ use super::*; /// they will retain the same index over time. #[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)] #[scale_info(replace_segment("staging_xcm", "xcm"))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub enum Error { // Errors that happen due to instructions being executed. These alone are defined in the // XCM specification. diff --git a/polkadot/xcm/xcm-builder/Cargo.toml b/polkadot/xcm/xcm-builder/Cargo.toml index ff528d7d075..7d6c40eb841 100644 --- a/polkadot/xcm/xcm-builder/Cargo.toml +++ b/polkadot/xcm/xcm-builder/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true version = "1.0.0" -[lints] -workspace = true - [dependencies] impl-trait-for-tuples = "0.2.1" parity-scale-codec = { version = "3.6.1", default-features = false, features = ["derive"] } @@ -40,7 +37,7 @@ assert_matches = "1.5.0" polkadot-test-runtime = { path = "../../runtime/test-runtime" } [features] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", diff --git a/polkadot/xcm/xcm-builder/src/currency_adapter.rs b/polkadot/xcm/xcm-builder/src/currency_adapter.rs index c3842a498ad..8ecf1dee72d 100644 --- a/polkadot/xcm/xcm-builder/src/currency_adapter.rs +++ b/polkadot/xcm/xcm-builder/src/currency_adapter.rs @@ -16,8 +16,6 @@ //! Adapters to work with `frame_support::traits::Currency` through XCM. -#![allow(deprecated)] - use super::MintLocation; use frame_support::traits::{ExistenceRequirement::AllowDeath, Get, WithdrawReasons}; use sp_runtime::traits::CheckedSub; @@ -87,7 +85,6 @@ impl From for XcmError { /// CheckingAccount, /// >; /// ``` -#[deprecated = "Use `FungibleAdapter` instead"] pub struct CurrencyAdapter( PhantomData<(Currency, Matcher, AccountIdConverter, AccountId, CheckedAccount)>, ); diff --git a/polkadot/xcm/xcm-builder/src/fungible_adapter.rs b/polkadot/xcm/xcm-builder/src/fungible_adapter.rs deleted file mode 100644 index 90608faa447..00000000000 --- a/polkadot/xcm/xcm-builder/src/fungible_adapter.rs +++ /dev/null @@ -1,317 +0,0 @@ -// 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 . - -//! Adapters to work with [`frame_support::traits::fungible`] through XCM. - -use super::MintLocation; -use frame_support::traits::{ - tokens::{ - fungible, Fortitude::Polite, Precision::Exact, Preservation::Preserve, Provenance::Minted, - }, - Get, -}; -use sp_std::{marker::PhantomData, prelude::*, result}; -use xcm::latest::prelude::*; -use xcm_executor::traits::{ConvertLocation, Error as MatchError, MatchesFungible, TransactAsset}; - -/// [`TransactAsset`] implementation that allows the use of a [`fungible`] implementation for -/// handling an asset in the XCM executor. -/// Only works for transfers. -pub struct FungibleTransferAdapter( - PhantomData<(Fungible, Matcher, AccountIdConverter, AccountId)>, -); -impl< - Fungible: fungible::Mutate, - Matcher: MatchesFungible, - AccountIdConverter: ConvertLocation, - AccountId: Eq + Clone, - > TransactAsset for FungibleTransferAdapter -{ - fn internal_transfer_asset( - what: &MultiAsset, - from: &MultiLocation, - to: &MultiLocation, - _context: &XcmContext, - ) -> result::Result { - log::trace!( - target: "xcm::fungible_adapter", - "internal_transfer_asset what: {:?}, from: {:?}, to: {:?}", - what, from, to - ); - // Check we handle the asset - let amount = Matcher::matches_fungible(what).ok_or(MatchError::AssetNotHandled)?; - let source = AccountIdConverter::convert_location(from) - .ok_or(MatchError::AccountIdConversionFailed)?; - let dest = AccountIdConverter::convert_location(to) - .ok_or(MatchError::AccountIdConversionFailed)?; - Fungible::transfer(&source, &dest, amount, Preserve) - .map_err(|error| XcmError::FailedToTransactAsset(error.into()))?; - Ok(what.clone().into()) - } -} - -/// [`TransactAsset`] implementation that allows the use of a [`fungible`] implementation for -/// handling an asset in the XCM executor. -/// Works for everything but transfers. -pub struct FungibleMutateAdapter( - PhantomData<(Fungible, Matcher, AccountIdConverter, AccountId, CheckingAccount)>, -); - -impl< - Fungible: fungible::Mutate, - Matcher: MatchesFungible, - AccountIdConverter: ConvertLocation, - AccountId: Eq + Clone, - CheckingAccount: Get>, - > FungibleMutateAdapter -{ - fn can_accrue_checked(checking_account: AccountId, amount: Fungible::Balance) -> XcmResult { - Fungible::can_deposit(&checking_account, amount, Minted) - .into_result() - .map_err(|_| XcmError::NotDepositable) - } - - fn can_reduce_checked(checking_account: AccountId, amount: Fungible::Balance) -> XcmResult { - Fungible::can_withdraw(&checking_account, amount) - .into_result(false) - .map_err(|_| XcmError::NotWithdrawable) - .map(|_| ()) - } - - fn accrue_checked(checking_account: AccountId, amount: Fungible::Balance) { - let ok = Fungible::mint_into(&checking_account, amount).is_ok(); - debug_assert!(ok, "`can_accrue_checked` must have returned `true` immediately prior; qed"); - } - - fn reduce_checked(checking_account: AccountId, amount: Fungible::Balance) { - let ok = Fungible::burn_from(&checking_account, amount, Exact, Polite).is_ok(); - debug_assert!(ok, "`can_reduce_checked` must have returned `true` immediately prior; qed"); - } -} - -impl< - Fungible: fungible::Mutate, - Matcher: MatchesFungible, - AccountIdConverter: ConvertLocation, - AccountId: Eq + Clone, - CheckingAccount: Get>, - > TransactAsset - for FungibleMutateAdapter -{ - fn can_check_in( - _origin: &MultiLocation, - what: &MultiAsset, - _context: &XcmContext, - ) -> XcmResult { - log::trace!( - target: "xcm::fungible_adapter", - "can_check_in origin: {:?}, what: {:?}", - _origin, what - ); - // Check we handle this asset - let amount = Matcher::matches_fungible(what).ok_or(MatchError::AssetNotHandled)?; - match CheckingAccount::get() { - Some((checking_account, MintLocation::Local)) => - Self::can_reduce_checked(checking_account, amount), - Some((checking_account, MintLocation::NonLocal)) => - Self::can_accrue_checked(checking_account, amount), - None => Ok(()), - } - } - - fn check_in(_origin: &MultiLocation, what: &MultiAsset, _context: &XcmContext) { - log::trace!( - target: "xcm::fungible_adapter", - "check_in origin: {:?}, what: {:?}", - _origin, what - ); - if let Some(amount) = Matcher::matches_fungible(what) { - match CheckingAccount::get() { - Some((checking_account, MintLocation::Local)) => - Self::reduce_checked(checking_account, amount), - Some((checking_account, MintLocation::NonLocal)) => - Self::accrue_checked(checking_account, amount), - None => (), - } - } - } - - fn can_check_out(_dest: &MultiLocation, what: &MultiAsset, _context: &XcmContext) -> XcmResult { - log::trace!( - target: "xcm::fungible_adapter", - "check_out dest: {:?}, what: {:?}", - _dest, - what - ); - let amount = Matcher::matches_fungible(what).ok_or(MatchError::AssetNotHandled)?; - match CheckingAccount::get() { - Some((checking_account, MintLocation::Local)) => - Self::can_accrue_checked(checking_account, amount), - Some((checking_account, MintLocation::NonLocal)) => - Self::can_reduce_checked(checking_account, amount), - None => Ok(()), - } - } - - fn check_out(_dest: &MultiLocation, what: &MultiAsset, _context: &XcmContext) { - log::trace!( - target: "xcm::fungible_adapter", - "check_out dest: {:?}, what: {:?}", - _dest, - what - ); - if let Some(amount) = Matcher::matches_fungible(what) { - match CheckingAccount::get() { - Some((checking_account, MintLocation::Local)) => - Self::accrue_checked(checking_account, amount), - Some((checking_account, MintLocation::NonLocal)) => - Self::reduce_checked(checking_account, amount), - None => (), - } - } - } - - fn deposit_asset( - what: &MultiAsset, - who: &MultiLocation, - _context: Option<&XcmContext>, - ) -> XcmResult { - log::trace!( - target: "xcm::fungible_adapter", - "deposit_asset what: {:?}, who: {:?}", - what, who, - ); - let amount = Matcher::matches_fungible(what).ok_or(MatchError::AssetNotHandled)?; - let who = AccountIdConverter::convert_location(who) - .ok_or(MatchError::AccountIdConversionFailed)?; - Fungible::mint_into(&who, amount) - .map_err(|error| XcmError::FailedToTransactAsset(error.into()))?; - Ok(()) - } - - fn withdraw_asset( - what: &MultiAsset, - who: &MultiLocation, - _context: Option<&XcmContext>, - ) -> result::Result { - log::trace!( - target: "xcm::fungible_adapter", - "deposit_asset what: {:?}, who: {:?}", - what, who, - ); - let amount = Matcher::matches_fungible(what).ok_or(MatchError::AssetNotHandled)?; - let who = AccountIdConverter::convert_location(who) - .ok_or(MatchError::AccountIdConversionFailed)?; - Fungible::burn_from(&who, amount, Exact, Polite) - .map_err(|error| XcmError::FailedToTransactAsset(error.into()))?; - Ok(what.clone().into()) - } -} - -/// [`TransactAsset`] implementation that allows the use of a [`fungible`] implementation for -/// handling an asset in the XCM executor. -/// Works for everything, transfers and teleport bookkeeping. -pub struct FungibleAdapter( - PhantomData<(Fungible, Matcher, AccountIdConverter, AccountId, CheckingAccount)>, -); -impl< - Fungible: fungible::Mutate, - Matcher: MatchesFungible, - AccountIdConverter: ConvertLocation, - AccountId: Eq + Clone, - CheckingAccount: Get>, - > TransactAsset - for FungibleAdapter -{ - fn can_check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { - FungibleMutateAdapter::< - Fungible, - Matcher, - AccountIdConverter, - AccountId, - CheckingAccount, - >::can_check_in(origin, what, context) - } - - fn check_in(origin: &MultiLocation, what: &MultiAsset, context: &XcmContext) { - FungibleMutateAdapter::< - Fungible, - Matcher, - AccountIdConverter, - AccountId, - CheckingAccount, - >::check_in(origin, what, context) - } - - fn can_check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) -> XcmResult { - FungibleMutateAdapter::< - Fungible, - Matcher, - AccountIdConverter, - AccountId, - CheckingAccount, - >::can_check_out(dest, what, context) - } - - fn check_out(dest: &MultiLocation, what: &MultiAsset, context: &XcmContext) { - FungibleMutateAdapter::< - Fungible, - Matcher, - AccountIdConverter, - AccountId, - CheckingAccount, - >::check_out(dest, what, context) - } - - fn deposit_asset( - what: &MultiAsset, - who: &MultiLocation, - context: Option<&XcmContext>, - ) -> XcmResult { - FungibleMutateAdapter::< - Fungible, - Matcher, - AccountIdConverter, - AccountId, - CheckingAccount, - >::deposit_asset(what, who, context) - } - - fn withdraw_asset( - what: &MultiAsset, - who: &MultiLocation, - maybe_context: Option<&XcmContext>, - ) -> result::Result { - FungibleMutateAdapter::< - Fungible, - Matcher, - AccountIdConverter, - AccountId, - CheckingAccount, - >::withdraw_asset(what, who, maybe_context) - } - - fn internal_transfer_asset( - what: &MultiAsset, - from: &MultiLocation, - to: &MultiLocation, - context: &XcmContext, - ) -> result::Result { - FungibleTransferAdapter::::internal_transfer_asset( - what, from, to, context - ) - } -} diff --git a/polkadot/xcm/xcm-builder/src/lib.rs b/polkadot/xcm/xcm-builder/src/lib.rs index e7431ae0254..455f17a5348 100644 --- a/polkadot/xcm/xcm-builder/src/lib.rs +++ b/polkadot/xcm/xcm-builder/src/lib.rs @@ -65,7 +65,6 @@ mod process_xcm_message; pub use process_xcm_message::ProcessXcmMessage; mod currency_adapter; -#[allow(deprecated)] pub use currency_adapter::CurrencyAdapter; mod fee_handling; @@ -73,9 +72,6 @@ pub use fee_handling::{ deposit_or_burn_fee, HandleFee, XcmFeeManagerFromComponents, XcmFeeToAccount, }; -mod fungible_adapter; -pub use fungible_adapter::{FungibleAdapter, FungibleMutateAdapter, FungibleTransferAdapter}; - mod fungibles_adapter; pub use fungibles_adapter::{ AssetChecking, DualMint, FungiblesAdapter, FungiblesMutateAdapter, FungiblesTransferAdapter, diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/local_para_para.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/local_para_para.rs index b1361cc8577..de08dbee953 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/local_para_para.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/local_para_para.rs @@ -23,16 +23,11 @@ use super::*; parameter_types! { pub UniversalLocation: Junctions = X2(GlobalConsensus(Local::get()), Parachain(1)); pub RemoteUniversalLocation: Junctions = X2(GlobalConsensus(Remote::get()), Parachain(1)); - pub RemoteNetwork: MultiLocation = AncestorThen(2, GlobalConsensus(Remote::get())).into(); } type TheBridge = TestBridge>; -type Router = TestTopic< - UnpaidLocalExporter< - HaulBlobExporter, - UniversalLocation, - >, ->; +type Router = + TestTopic, UniversalLocation>>; /// ```nocompile /// local | remote diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs index 5371abccf66..8433b6e0212 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/local_relay_relay.rs @@ -23,16 +23,11 @@ use super::*; parameter_types! { pub UniversalLocation: Junctions = X1(GlobalConsensus(Local::get())); pub RemoteUniversalLocation: Junctions = X1(GlobalConsensus(Remote::get())); - pub RemoteNetwork: MultiLocation = AncestorThen(1, GlobalConsensus(Remote::get())).into(); } type TheBridge = TestBridge>; -type Router = TestTopic< - UnpaidLocalExporter< - HaulBlobExporter, - UniversalLocation, - >, ->; +type Router = + TestTopic, UniversalLocation>>; /// ```nocompile /// local | remote diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/mod.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/mod.rs index 0c749b66da6..45630dbfc24 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/mod.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/mod.rs @@ -20,7 +20,6 @@ use super::mock::*; use crate::{universal_exports::*, WithTopicSource}; use frame_support::{parameter_types, traits::Get}; use std::{cell::RefCell, marker::PhantomData}; -use xcm::AlwaysLatest; use xcm_executor::{ traits::{export_xcm, validate_export}, XcmExecutor, diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs index 079eb0175d7..23d6eb99a90 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/paid_remote_relay_relay.rs @@ -30,7 +30,6 @@ parameter_types! { pub UniversalLocation: Junctions = X2(GlobalConsensus(Local::get()), Parachain(100)); pub RelayUniversalLocation: Junctions = X1(GlobalConsensus(Local::get())); pub RemoteUniversalLocation: Junctions = X1(GlobalConsensus(Remote::get())); - pub RemoteNetwork: MultiLocation = AncestorThen(1, GlobalConsensus(Remote::get())).into(); pub BridgeTable: Vec = vec![ NetworkExportTableItem::new( Remote::get(), @@ -42,7 +41,7 @@ parameter_types! { } type TheBridge = TestBridge>; -type RelayExporter = HaulBlobExporter; +type RelayExporter = HaulBlobExporter; type LocalInnerRouter = ExecutingRouter; type LocalBridgeRouter = SovereignPaidRemoteExporter< NetworkExportTable, diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs index fb6c5da3eb0..f11143ab9f6 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para.rs @@ -24,7 +24,6 @@ parameter_types! { pub UniversalLocation: Junctions = X2(GlobalConsensus(Local::get()), Parachain(1000)); pub ParaBridgeUniversalLocation: Junctions = X2(GlobalConsensus(Local::get()), Parachain(1)); pub RemoteParaBridgeUniversalLocation: Junctions = X2(GlobalConsensus(Remote::get()), Parachain(1)); - pub RemoteNetwork: MultiLocation = AncestorThen(2, GlobalConsensus(Remote::get())).into(); pub BridgeTable: Vec = vec![ NetworkExportTableItem::new( Remote::get(), @@ -37,7 +36,7 @@ parameter_types! { type TheBridge = TestBridge< BridgeBlobDispatcher, >; -type RelayExporter = HaulBlobExporter; +type RelayExporter = HaulBlobExporter; type LocalInnerRouter = UnpaidExecutingRouter; type LocalBridgingRouter = diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs index 0b6dc01e2bf..7218e0a0488 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/remote_para_para_via_relay.rs @@ -24,7 +24,6 @@ parameter_types! { pub UniversalLocation: Junctions = X1(GlobalConsensus(Local::get())); pub ParaBridgeUniversalLocation: Junctions = X2(GlobalConsensus(Local::get()), Parachain(1)); pub RemoteParaBridgeUniversalLocation: Junctions = X2(GlobalConsensus(Remote::get()), Parachain(1)); - pub RemoteNetwork: MultiLocation = AncestorThen(2, GlobalConsensus(Remote::get())).into(); pub BridgeTable: Vec = vec![ NetworkExportTableItem::new( Remote::get(), @@ -37,7 +36,7 @@ parameter_types! { type TheBridge = TestBridge< BridgeBlobDispatcher, >; -type RelayExporter = HaulBlobExporter; +type RelayExporter = HaulBlobExporter; type LocalInnerRouter = UnpaidExecutingRouter; type LocalBridgingRouter = diff --git a/polkadot/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs b/polkadot/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs index e33c7b15b0a..45b5efbc44c 100644 --- a/polkadot/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs +++ b/polkadot/xcm/xcm-builder/src/tests/bridging/remote_relay_relay.rs @@ -24,7 +24,6 @@ parameter_types! { pub UniversalLocation: Junctions = X2(GlobalConsensus(Local::get()), Parachain(1000)); pub RelayUniversalLocation: Junctions = X1(GlobalConsensus(Local::get())); pub RemoteUniversalLocation: Junctions = X1(GlobalConsensus(Remote::get())); - pub RemoteNetwork: MultiLocation = AncestorThen(1, GlobalConsensus(Remote::get())).into(); pub BridgeTable: Vec = vec![ NetworkExportTableItem::new( Remote::get(), @@ -36,7 +35,7 @@ parameter_types! { } type TheBridge = TestBridge>; -type RelayExporter = HaulBlobExporter; +type RelayExporter = HaulBlobExporter; type LocalInnerRouter = UnpaidExecutingRouter; type LocalBridgeRouter = diff --git a/polkadot/xcm/xcm-builder/src/universal_exports.rs b/polkadot/xcm/xcm-builder/src/universal_exports.rs index 4aa6a0ef7a5..8e2cf88b3c3 100644 --- a/polkadot/xcm/xcm-builder/src/universal_exports.rs +++ b/polkadot/xcm/xcm-builder/src/universal_exports.rs @@ -422,25 +422,11 @@ impl< } } -pub struct HaulBlobExporter( - PhantomData<(Bridge, BridgedNetwork, DestinationVersion, Price)>, +pub struct HaulBlobExporter( + PhantomData<(Bridge, BridgedNetwork, Price)>, ); -/// `ExportXcm` implementation for `HaulBlobExporter`. -/// -/// # Type Parameters -/// -/// ```text -/// - Bridge: Implements `HaulBlob`. -/// - BridgedNetwork: The relative location of the bridged consensus system with the expected `GlobalConsensus` junction. -/// - DestinationVersion: Implements `GetVersion` for retrieving XCM version for the destination. -/// - Price: potential fees for exporting. -/// ``` -impl< - Bridge: HaulBlob, - BridgedNetwork: Get, - DestinationVersion: GetVersion, - Price: Get, - > ExportXcm for HaulBlobExporter +impl, Price: Get> ExportXcm + for HaulBlobExporter { type Ticket = (Vec, XcmHash); @@ -451,35 +437,17 @@ impl< destination: &mut Option, message: &mut Option>, ) -> Result<((Vec, XcmHash), MultiAssets), SendError> { - let (bridged_network, bridged_network_location_parents) = { - let MultiLocation { parents, interior: mut junctions } = BridgedNetwork::get(); - match junctions.take_first() { - Some(GlobalConsensus(network)) => (network, parents), - _ => return Err(SendError::NotApplicable), - } - }; + let bridged_network = BridgedNetwork::get(); ensure!(&network == &bridged_network, SendError::NotApplicable); // We don't/can't use the `channel` for this adapter. let dest = destination.take().ok_or(SendError::MissingArgument)?; - - // Let's resolve the known/supported XCM version for the destination because we don't know - // if it supports the same/latest version. - let (universal_dest, version) = - match dest.pushed_front_with(GlobalConsensus(bridged_network)) { - Ok(d) => { - let version = DestinationVersion::get_version_for(&MultiLocation::from( - AncestorThen(bridged_network_location_parents, d), - )) - .ok_or(SendError::DestinationUnsupported)?; - (d, version) - }, - Err((dest, _)) => { - *destination = Some(dest); - return Err(SendError::NotApplicable) - }, - }; - - // Let's adjust XCM with `UniversalOrigin`, `DescendOrigin` and`SetTopic`. + let universal_dest = match dest.pushed_front_with(GlobalConsensus(bridged_network)) { + Ok(d) => d.into(), + Err((dest, _)) => { + *destination = Some(dest); + return Err(SendError::NotApplicable) + }, + }; let (local_net, local_sub) = universal_source .take() .ok_or(SendError::MissingArgument)? @@ -494,17 +462,7 @@ impl< if local_sub != Here { message.0.insert(1, DescendOrigin(local_sub)); } - - // We cannot use the latest `Versioned` because we don't know if the target chain already - // supports the same version. Therefore, we better control the destination version with best - // efforts. - let message = VersionedXcm::from(message) - .into_version(version) - .map_err(|()| SendError::DestinationUnsupported)?; - let universal_dest = VersionedInteriorMultiLocation::from(universal_dest) - .into_version(version) - .map_err(|()| SendError::DestinationUnsupported)?; - + let message = VersionedXcm::from(message); let id = maybe_id.unwrap_or_else(|| message.using_encoded(sp_io::hashing::blake2_256)); let blob = BridgeMessage { universal_dest, message }.encode(); Ok(((blob, id), Price::get())) diff --git a/polkadot/xcm/xcm-builder/tests/mock/mod.rs b/polkadot/xcm/xcm-builder/tests/mock/mod.rs index 6b4d893f73c..4f183c7a15b 100644 --- a/polkadot/xcm/xcm-builder/tests/mock/mod.rs +++ b/polkadot/xcm/xcm-builder/tests/mock/mod.rs @@ -15,7 +15,7 @@ // along with Polkadot. If not, see . use frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, parameter_types, traits::{ConstU32, Everything, Nothing}, weights::Weight, }; @@ -32,14 +32,12 @@ use xcm_executor::XcmExecutor; use staging_xcm_builder as xcm_builder; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter as XcmCurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, ChildParachainAsNative, ChildParachainConvertsVia, ChildSystemParachainAsSuperuser, - FixedRateOfFungible, FixedWeightBounds, IsChildSystemParachain, IsConcrete, MintLocation, - RespectSuspension, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, - TakeWeightCredit, + CurrencyAdapter as XcmCurrencyAdapter, FixedRateOfFungible, FixedWeightBounds, + IsChildSystemParachain, IsConcrete, MintLocation, RespectSuspension, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, }; pub type AccountId = AccountId32; @@ -78,7 +76,6 @@ parameter_types! { pub const BlockHashCount: u64 = 250; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; @@ -145,7 +142,6 @@ parameter_types! { pub type SovereignAccountOf = (ChildParachainConvertsVia, AccountId32Aliases); -#[allow(deprecated)] pub type LocalCurrencyAdapter = XcmCurrencyAdapter< Balances, IsConcrete, diff --git a/polkadot/xcm/xcm-executor/Cargo.toml b/polkadot/xcm/xcm-executor/Cargo.toml index 32fa6669c0a..d5edb1ea0f5 100644 --- a/polkadot/xcm/xcm-executor/Cargo.toml +++ b/polkadot/xcm/xcm-executor/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true version = "1.0.0" -[lints] -workspace = true - [dependencies] impl-trait-for-tuples = "0.2.2" environmental = { version = "1.1.4", default-features = false } @@ -26,7 +23,7 @@ log = { version = "0.4.17", default-features = false } frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } [features] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", diff --git a/polkadot/xcm/xcm-executor/integration-tests/Cargo.toml b/polkadot/xcm/xcm-executor/integration-tests/Cargo.toml index cafe12dc587..ddb45965ee4 100644 --- a/polkadot/xcm/xcm-executor/integration-tests/Cargo.toml +++ b/polkadot/xcm/xcm-executor/integration-tests/Cargo.toml @@ -7,9 +7,6 @@ license.workspace = true version = "1.0.0" publish = false -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1" } frame-support = { path = "../../../../substrate/frame/support", default-features = false } @@ -29,5 +26,5 @@ xcm-executor = { package = "staging-xcm-executor", path = ".." } sp-tracing = { path = "../../../../substrate/primitives/tracing" } [features] -default = ["std"] -std = ["frame-support/std", "sp-runtime/std", "xcm/std"] +default = [ "std" ] +std = [ "frame-support/std", "sp-runtime/std", "xcm/std" ] diff --git a/polkadot/xcm/xcm-simulator/Cargo.toml b/polkadot/xcm/xcm-simulator/Cargo.toml index 051e9752f6e..eedcfa0032a 100644 --- a/polkadot/xcm/xcm-simulator/Cargo.toml +++ b/polkadot/xcm/xcm-simulator/Cargo.toml @@ -6,9 +6,6 @@ authors.workspace = true edition.workspace = true license.workspace = true -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1" } paste = "1.0.7" diff --git a/polkadot/xcm/xcm-simulator/example/Cargo.toml b/polkadot/xcm/xcm-simulator/example/Cargo.toml index 522b7855837..f0caa5ab48e 100644 --- a/polkadot/xcm/xcm-simulator/example/Cargo.toml +++ b/polkadot/xcm/xcm-simulator/example/Cargo.toml @@ -6,9 +6,6 @@ edition.workspace = true license.workspace = true version = "1.0.0" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1" } scale-info = { version = "2.10.0", features = ["derive"] } diff --git a/polkadot/xcm/xcm-simulator/example/src/parachain.rs b/polkadot/xcm/xcm-simulator/example/src/parachain.rs index 34828a4d2c0..9f0411970ce 100644 --- a/polkadot/xcm/xcm-simulator/example/src/parachain.rs +++ b/polkadot/xcm/xcm-simulator/example/src/parachain.rs @@ -19,7 +19,7 @@ use codec::{Decode, Encode}; use core::marker::PhantomData; use frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, parameter_types, traits::{ContainsPair, EnsureOrigin, EnsureOriginWithArg, Everything, EverythingBut, Nothing}, weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}, }; @@ -40,9 +40,10 @@ use polkadot_parachain_primitives::primitives::{ use xcm::{latest::prelude::*, VersionedXcm}; use xcm_builder::{ Account32Hash, AccountId32Aliases, AllowUnpaidExecutionFrom, ConvertedConcreteId, - EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, FungibleAdapter, IsConcrete, - NativeAsset, NoChecking, NonFungiblesAdapter, ParentIsPreset, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, + CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, + IsConcrete, NativeAsset, NoChecking, NonFungiblesAdapter, ParentIsPreset, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, }; use xcm_executor::{ traits::{ConvertLocation, JustTry}, @@ -62,7 +63,6 @@ parameter_types! { pub const BlockHashCount: u64 = 250; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; @@ -201,7 +201,7 @@ parameter_types! { } pub type LocalAssetTransactor = ( - FungibleAdapter, LocationToAccountId, AccountId, ()>, + XcmCurrencyAdapter, LocationToAccountId, AccountId, ()>, NonFungiblesAdapter< ForeignUniques, ConvertedConcreteId, diff --git a/polkadot/xcm/xcm-simulator/example/src/relay_chain.rs b/polkadot/xcm/xcm-simulator/example/src/relay_chain.rs index 24fc56eb717..bdd7ff6d3ea 100644 --- a/polkadot/xcm/xcm-simulator/example/src/relay_chain.rs +++ b/polkadot/xcm/xcm-simulator/example/src/relay_chain.rs @@ -17,7 +17,7 @@ //! Relay chain runtime mock. use frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, parameter_types, traits::{AsEnsureOriginWithArg, Everything, Nothing, ProcessMessage, ProcessMessageError}, weights::{Weight, WeightMeter}, }; @@ -36,9 +36,9 @@ use xcm::latest::prelude::*; use xcm_builder::{ Account32Hash, AccountId32Aliases, AllowUnpaidExecutionFrom, AsPrefixedGeneralIndex, ChildParachainAsNative, ChildParachainConvertsVia, ChildSystemParachainAsSuperuser, - ConvertedConcreteId, FixedRateOfFungible, FixedWeightBounds, FungibleAdapter, IsConcrete, - NoChecking, NonFungiblesAdapter, SignedAccountId32AsNative, SignedToAccountId32, - SovereignSignedViaLocation, + ConvertedConcreteId, CurrencyAdapter as XcmCurrencyAdapter, FixedRateOfFungible, + FixedWeightBounds, IsConcrete, NoChecking, NonFungiblesAdapter, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, }; use xcm_executor::{traits::JustTry, Config, XcmExecutor}; @@ -49,7 +49,6 @@ parameter_types! { pub const BlockHashCount: u64 = 250; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; @@ -141,7 +140,7 @@ pub type LocationToAccountId = ( ); pub type LocalAssetTransactor = ( - FungibleAdapter, LocationToAccountId, AccountId, ()>, + XcmCurrencyAdapter, LocationToAccountId, AccountId, ()>, NonFungiblesAdapter< Uniques, ConvertedConcreteId, JustTry>, diff --git a/polkadot/xcm/xcm-simulator/fuzzer/Cargo.toml b/polkadot/xcm/xcm-simulator/fuzzer/Cargo.toml index 1d13c76f171..acf28bec4f1 100644 --- a/polkadot/xcm/xcm-simulator/fuzzer/Cargo.toml +++ b/polkadot/xcm/xcm-simulator/fuzzer/Cargo.toml @@ -7,9 +7,6 @@ edition.workspace = true license.workspace = true publish = false -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1" } honggfuzz = "0.5.55" diff --git a/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs b/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs index 2262d18e860..41234837aca 100644 --- a/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs +++ b/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs @@ -18,7 +18,7 @@ use codec::{Decode, Encode}; use frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, parameter_types, traits::{Everything, Nothing}, weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight}, }; @@ -37,12 +37,11 @@ use polkadot_parachain_primitives::primitives::{ DmpMessageHandler, Id as ParaId, Sibling, XcmpMessageFormat, XcmpMessageHandler, }; use xcm::{latest::prelude::*, VersionedXcm}; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter as XcmCurrencyAdapter; use xcm_builder::{ - AccountId32Aliases, AllowUnpaidExecutionFrom, EnsureXcmOrigin, FixedRateOfFungible, - FixedWeightBounds, IsConcrete, NativeAsset, ParentIsPreset, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, + AccountId32Aliases, AllowUnpaidExecutionFrom, CurrencyAdapter as XcmCurrencyAdapter, + EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, IsConcrete, NativeAsset, + ParentIsPreset, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, }; use xcm_executor::{Config, XcmExecutor}; @@ -53,7 +52,6 @@ parameter_types! { pub const BlockHashCount: u64 = 250; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; @@ -133,7 +131,6 @@ parameter_types! { pub const MaxAssetsIntoHolding: u32 = 64; } -#[allow(deprecated)] pub type LocalAssetTransactor = XcmCurrencyAdapter, LocationToAccountId, AccountId, ()>; diff --git a/polkadot/xcm/xcm-simulator/fuzzer/src/relay_chain.rs b/polkadot/xcm/xcm-simulator/fuzzer/src/relay_chain.rs index bbf4f1e6cc5..c9a57db970a 100644 --- a/polkadot/xcm/xcm-simulator/fuzzer/src/relay_chain.rs +++ b/polkadot/xcm/xcm-simulator/fuzzer/src/relay_chain.rs @@ -17,7 +17,7 @@ //! Relay chain runtime mock. use frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, parameter_types, traits::{Everything, Nothing, ProcessMessage, ProcessMessageError}, weights::{Weight, WeightMeter}, }; @@ -33,13 +33,11 @@ use polkadot_runtime_parachains::{ origin, shared, }; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter as XcmCurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowUnpaidExecutionFrom, ChildParachainAsNative, - ChildParachainConvertsVia, ChildSystemParachainAsSuperuser, FixedRateOfFungible, - FixedWeightBounds, IsConcrete, SignedAccountId32AsNative, SignedToAccountId32, - SovereignSignedViaLocation, + ChildParachainConvertsVia, ChildSystemParachainAsSuperuser, + CurrencyAdapter as XcmCurrencyAdapter, FixedRateOfFungible, FixedWeightBounds, IsConcrete, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, }; use xcm_executor::{Config, XcmExecutor}; @@ -50,7 +48,6 @@ parameter_types! { pub const BlockHashCount: u64 = 250; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; @@ -116,7 +113,6 @@ parameter_types! { pub type SovereignAccountOf = (ChildParachainConvertsVia, AccountId32Aliases); -#[allow(deprecated)] pub type LocalAssetTransactor = XcmCurrencyAdapter, SovereignAccountOf, AccountId, ()>; diff --git a/polkadot/zombienet_tests/functional/0001-parachains-pvf.zndsl b/polkadot/zombienet_tests/functional/0001-parachains-pvf.zndsl index 3e1d8ba771c..135999a092a 100644 --- a/polkadot/zombienet_tests/functional/0001-parachains-pvf.zndsl +++ b/polkadot/zombienet_tests/functional/0001-parachains-pvf.zndsl @@ -32,8 +32,6 @@ alice: parachain 2005 block height is at least 10 within 300 seconds alice: parachain 2006 block height is at least 10 within 300 seconds alice: parachain 2007 block height is at least 10 within 300 seconds -alice: reports substrate_block_height{status="finalized"} is at least 30 within 400 seconds - # Check preparation time is under 10s. # Check all buckets <= 10. alice: reports histogram polkadot_pvf_preparation_time has at least 1 samples in buckets ["0.1", "0.5", "1", "2", "3", "10"] within 10 seconds diff --git a/polkadot/zombienet_tests/functional/0002-parachains-disputes.toml b/polkadot/zombienet_tests/functional/0002-parachains-disputes.toml index 27cd81dface..e70322e13e6 100644 --- a/polkadot/zombienet_tests/functional/0002-parachains-disputes.toml +++ b/polkadot/zombienet_tests/functional/0002-parachains-disputes.toml @@ -5,10 +5,6 @@ timeout = 1000 max_validators_per_core = 5 needed_approvals = 8 -[relaychain.genesis.runtime.runtime_genesis_config.configuration.config.approval_voting_params] - max_approval_coalesce_count = 5 - - [relaychain] default_image = "{{ZOMBIENET_INTEGRATION_TEST_IMAGE}}" chain = "rococo-local" diff --git a/polkadot/zombienet_tests/functional/0007-dispute-freshly-finalized.toml b/polkadot/zombienet_tests/functional/0007-dispute-freshly-finalized.toml deleted file mode 100644 index 69eb0804d8c..00000000000 --- a/polkadot/zombienet_tests/functional/0007-dispute-freshly-finalized.toml +++ /dev/null @@ -1,40 +0,0 @@ -[settings] -timeout = 1000 - -[relaychain.genesis.runtimeGenesis.patch.configuration.config] - max_validators_per_core = 1 - needed_approvals = 1 - -[relaychain] -default_image = "{{ZOMBIENET_INTEGRATION_TEST_IMAGE}}" -chain = "rococo-local" -default_command = "polkadot" - -[relaychain.default_resources] -limits = { memory = "4G", cpu = "2" } -requests = { memory = "2G", cpu = "1" } - - [[relaychain.node_groups]] - name = "honest" - count = 6 - args = ["-lparachain=debug"] - - [[relaychain.nodes]] - image = "{{MALUS_IMAGE}}" - name = "malus" - command = "malus dispute-finalized-candidates" - args = [ "--alice", "-lparachain=debug,MALUS=trace", "--dispute-offset=3" ] - -[[parachains]] -id = 2000 - - [parachains.collator] - image = "{{COL_IMAGE}}" - name = "collator" - command = "undying-collator" - args = ["-lparachain=debug"] - -[types.Header] -number = "u64" -parent_hash = "Hash" -post_state = "Hash" diff --git a/polkadot/zombienet_tests/functional/0007-dispute-freshly-finalized.zndsl b/polkadot/zombienet_tests/functional/0007-dispute-freshly-finalized.zndsl deleted file mode 100644 index 62d5a9768f9..00000000000 --- a/polkadot/zombienet_tests/functional/0007-dispute-freshly-finalized.zndsl +++ /dev/null @@ -1,29 +0,0 @@ -Description: Test if disputes triggered on finalized blocks within scope always end as valid. -Network: ./0007-dispute-freshly-finalized.toml -Creds: config - -# Check authority status and peers. -malus: reports node_roles is 4 -honest: reports node_roles is 4 - -# Ensure parachains are registered. -honest: parachain 2000 is registered within 30 seconds - -# Ensure parachains made progress. -honest: parachain 2000 block height is at least 10 within 200 seconds - -# Ensure that malus is already attempting to dispute -malus: log line contains "😈 Disputing candidate with hash:" within 180 seconds - -# Check if disputes are initiated and concluded. -honest: reports polkadot_parachain_candidate_disputes_total is at least 2 within 100 seconds -honest: reports polkadot_parachain_candidate_dispute_concluded{validity="valid"} is at least 2 within 100 seconds -honest: reports polkadot_parachain_candidate_dispute_concluded{validity="invalid"} is 0 within 100 seconds - -# Check lag - approval -honest: reports polkadot_parachain_approval_checking_finality_lag is 0 - -# Check lag - dispute conclusion -honest: reports polkadot_parachain_disputes_finality_lag is 0 - - diff --git a/polkadot/zombienet_tests/functional/0008-dispute-old-finalized.toml b/polkadot/zombienet_tests/functional/0008-dispute-old-finalized.toml deleted file mode 100644 index 1ea385c3a42..00000000000 --- a/polkadot/zombienet_tests/functional/0008-dispute-old-finalized.toml +++ /dev/null @@ -1,40 +0,0 @@ -[settings] -timeout = 1000 - -[relaychain.genesis.runtimeGenesis.patch.configuration.config] - max_validators_per_core = 1 - needed_approvals = 1 - -[relaychain] -default_image = "{{ZOMBIENET_INTEGRATION_TEST_IMAGE}}" -chain = "rococo-local" -default_command = "polkadot" - -[relaychain.default_resources] -limits = { memory = "4G", cpu = "2" } -requests = { memory = "2G", cpu = "1" } - - [[relaychain.node_groups]] - name = "honest" - count = 6 - args = ["-lparachain=debug"] - - [[relaychain.nodes]] - image = "{{MALUS_IMAGE}}" - name = "malus" - command = "malus dispute-finalized-candidates" - args = [ "--alice", "-lparachain=debug,MALUS=trace", "--dispute-offset=14" ] - -[[parachains]] -id = 2000 - - [parachains.collator] - image = "{{COL_IMAGE}}" - name = "collator" - command = "undying-collator" - args = ["-lparachain=debug"] - -[types.Header] -number = "u64" -parent_hash = "Hash" -post_state = "Hash" diff --git a/polkadot/zombienet_tests/functional/0008-dispute-old-finalized.zndsl b/polkadot/zombienet_tests/functional/0008-dispute-old-finalized.zndsl deleted file mode 100644 index b30c5801a1d..00000000000 --- a/polkadot/zombienet_tests/functional/0008-dispute-old-finalized.zndsl +++ /dev/null @@ -1,21 +0,0 @@ -Description: Test if disputes triggered on finalized blocks out of scope never get to be confirmed and concluded. -Network: ./0008-dispute-old-finalized.toml -Creds: config - -# Check authority status and peers. -malus: reports node_roles is 4 -honest: reports node_roles is 4 - - -# Ensure parachains are registered. -honest: parachain 2000 is registered within 30 seconds - -# Ensure parachains made progress. -honest: parachain 2000 block height is at least 20 within 300 seconds - -# Ensure that malus is already attempting to dispute -malus: log line contains "😈 Disputing candidate with hash:" within 180 seconds - -# Ensure that honest nodes don't participate and conclude any disputes -honest: count of log lines containing "Dispute on candidate concluded" is 0 within 100 seconds - diff --git a/polkadot/zombienet_tests/functional/0009-approval-voting-coalescing.toml b/polkadot/zombienet_tests/functional/0009-approval-voting-coalescing.toml deleted file mode 100644 index 19c7015403d..00000000000 --- a/polkadot/zombienet_tests/functional/0009-approval-voting-coalescing.toml +++ /dev/null @@ -1,115 +0,0 @@ -[settings] -timeout = 1000 - -[relaychain] -default_image = "{{ZOMBIENET_INTEGRATION_TEST_IMAGE}}" -chain = "rococo-local" - -[relaychain.genesis.runtimeGenesis.patch.configuration.config] - needed_approvals = 4 - relay_vrf_modulo_samples = 6 - -[relaychain.genesis.runtimeGenesis.patch.configuration.config.approval_voting_params] - max_approval_coalesce_count = 5 - -[relaychain.default_resources] -limits = { memory = "4G", cpu = "2" } -requests = { memory = "2G", cpu = "1" } - - [[relaychain.node_groups]] - name = "alice" - args = [ "-lparachain=trace,runtime=debug" ] - count = 13 - -[[parachains]] -id = 2000 -addToGenesis = true -genesis_state_generator = "undying-collator export-genesis-state --pov-size=100000 --pvf-complexity=1" - - [parachains.collator] - name = "collator01" - image = "{{COL_IMAGE}}" - command = "undying-collator" - args = ["-lparachain=debug", "--pov-size=100000", "--pvf-complexity=1", "--parachain-id=2000"] - -[[parachains]] -id = 2001 -addToGenesis = true -genesis_state_generator = "undying-collator export-genesis-state --pov-size=100000 --pvf-complexity=10" - - [parachains.collator] - name = "collator02" - image = "{{COL_IMAGE}}" - command = "undying-collator" - args = ["-lparachain=debug", "--pov-size=100000", "--parachain-id=2001", "--pvf-complexity=10"] - -[[parachains]] -id = 2002 -addToGenesis = true -genesis_state_generator = "undying-collator export-genesis-state --pov-size=100000 --pvf-complexity=100" - - [parachains.collator] - name = "collator03" - image = "{{COL_IMAGE}}" - command = "undying-collator" - args = ["-lparachain=debug", "--pov-size=100000", "--parachain-id=2002", "--pvf-complexity=100"] - -[[parachains]] -id = 2003 -addToGenesis = true -genesis_state_generator = "undying-collator export-genesis-state --pov-size=20000 --pvf-complexity=300" - - [parachains.collator] - name = "collator04" - image = "{{COL_IMAGE}}" - command = "undying-collator" - args = ["-lparachain=debug", "--pov-size=20000", "--parachain-id=2003", "--pvf-complexity=300"] - -[[parachains]] -id = 2004 -addToGenesis = true -genesis_state_generator = "undying-collator export-genesis-state --pov-size=100000 --pvf-complexity=300" - - [parachains.collator] - name = "collator05" - image = "{{COL_IMAGE}}" - command = "undying-collator" - args = ["-lparachain=debug", "--pov-size=100000", "--parachain-id=2004", "--pvf-complexity=300"] - -[[parachains]] -id = 2005 -addToGenesis = true -genesis_state_generator = "undying-collator export-genesis-state --pov-size=20000 --pvf-complexity=400" - - [parachains.collator] - name = "collator06" - image = "{{COL_IMAGE}}" - command = "undying-collator" - args = ["-lparachain=debug", "--pov-size=20000", "--pvf-complexity=400", "--parachain-id=2005"] - -[[parachains]] -id = 2006 -addToGenesis = true -genesis_state_generator = "undying-collator export-genesis-state --pov-size=100000 --pvf-complexity=300" - - [parachains.collator] - name = "collator07" - image = "{{COL_IMAGE}}" - command = "undying-collator" - args = ["-lparachain=debug", "--pov-size=100000", "--pvf-complexity=300", "--parachain-id=2006"] - -[[parachains]] -id = 2007 -addToGenesis = true -genesis_state_generator = "undying-collator export-genesis-state --pov-size=100000 --pvf-complexity=300" - - [parachains.collator] - name = "collator08" - image = "{{COL_IMAGE}}" - command = "undying-collator" - args = ["-lparachain=debug", "--pov-size=100000", "--pvf-complexity=300", "--parachain-id=2007"] - -[types.Header] -number = "u64" -parent_hash = "Hash" -post_state = "Hash" \ No newline at end of file diff --git a/polkadot/zombienet_tests/functional/0009-approval-voting-coalescing.zndsl b/polkadot/zombienet_tests/functional/0009-approval-voting-coalescing.zndsl deleted file mode 100644 index 1fc4f678446..00000000000 --- a/polkadot/zombienet_tests/functional/0009-approval-voting-coalescing.zndsl +++ /dev/null @@ -1,32 +0,0 @@ -Description: Approval voting coalescing does not lag finality -Network: ./0009-approval-voting-coalescing.toml -Creds: config - -# Check authority status. -alice: reports node_roles is 4 - -# Ensure parachains are registered. -alice: parachain 2000 is registered within 60 seconds -alice: parachain 2001 is registered within 60 seconds -alice: parachain 2002 is registered within 60 seconds -alice: parachain 2003 is registered within 60 seconds -alice: parachain 2004 is registered within 60 seconds -alice: parachain 2005 is registered within 60 seconds -alice: parachain 2006 is registered within 60 seconds -alice: parachain 2007 is registered within 60 seconds - -# Ensure parachains made progress. -alice: parachain 2000 block height is at least 10 within 300 seconds -alice: parachain 2001 block height is at least 10 within 300 seconds -alice: parachain 2002 block height is at least 10 within 300 seconds -alice: parachain 2003 block height is at least 10 within 300 seconds -alice: parachain 2004 block height is at least 10 within 300 seconds -alice: parachain 2005 block height is at least 10 within 300 seconds -alice: parachain 2006 block height is at least 10 within 300 seconds -alice: parachain 2007 block height is at least 10 within 300 seconds - -alice: reports substrate_block_height{status="finalized"} is at least 30 within 400 seconds - -alice: reports polkadot_parachain_approval_checking_finality_lag < 3 - -alice: reports polkadot_parachain_approvals_no_shows_total < 3 within 10 seconds diff --git a/polkadot/zombienet_tests/misc/0002-update-cmd.sh b/polkadot/zombienet_tests/misc/0002-update-cmd.sh deleted file mode 100755 index 7d0dc53ca0d..00000000000 --- a/polkadot/zombienet_tests/misc/0002-update-cmd.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/bash - -set -euxo pipefail - -if [[ $(grep "insecure-validator-i-know-what-i-do" /cfg/zombie.cmd) ]]; then - echo "insecure flag is already part of the cmd"; -else - echo -n " --insecure-validator-i-know-what-i-do" >> /cfg/zombie.cmd; -fi; - -echo "update-cmd" > /tmp/zombiepipe; \ No newline at end of file diff --git a/polkadot/zombienet_tests/misc/0002-upgrade-node.zndsl b/polkadot/zombienet_tests/misc/0002-upgrade-node.zndsl index db0a60ac1df..9191fb027de 100644 --- a/polkadot/zombienet_tests/misc/0002-upgrade-node.zndsl +++ b/polkadot/zombienet_tests/misc/0002-upgrade-node.zndsl @@ -13,11 +13,6 @@ dave: parachain 2001 block height is at least 10 within 200 seconds # avg 30s in our infra alice: run ./0002-download-polkadot-from-pr.sh with "{{POLKADOT_PR_ARTIFACTS_URL}}" within 60 seconds bob: run ./0002-download-polkadot-from-pr.sh with "{{POLKADOT_PR_ARTIFACTS_URL}}" within 60 seconds -# update the cmd to add the flag '--insecure-validator-i-know-what-i-do' -# once the base image include the version with this flag we can remove this logic. -alice: run ./0002-update-cmd.sh within 60 seconds -bob: run ./0002-update-cmd.sh within 60 seconds -# restart alice: restart after 5 seconds bob: restart after 5 seconds diff --git a/prdoc/.template.prdoc b/prdoc/.template.prdoc deleted file mode 100644 index 097741f388c..00000000000 --- a/prdoc/.template.prdoc +++ /dev/null @@ -1,11 +0,0 @@ -# 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: ... - -doc: - - audience: Node Dev - description: | - ... - -crates: [ ] diff --git a/prdoc/1.3.0/pr_1255.prdoc b/prdoc/1.3.0/pr_1255.prdoc deleted file mode 100644 index c00a7c307e9..00000000000 --- a/prdoc/1.3.0/pr_1255.prdoc +++ /dev/null @@ -1,21 +0,0 @@ -# Schema: Parity PR Documentation Schema (prdoc) -# See doc at https://github.com/paritytech/prdoc - -title: Fix for Reward Deficit in the pool - -doc: - - audience: Runtime Dev - description: | - Instead of fragile calculation of current balance by looking at free balance - ED, Nomination Pool now freezes ED in the pool reward account to restrict an account from going below minimum balance. This also has a nice side effect that if ED changes, we know how much is the imbalance in ED frozen in the pool and the current required ED. A pool operator can diligently top up the pool with the deficit in ED or vice versa, withdraw the excess they transferred to the pool. - - notes: - - Introduces new call `adjust_pool_deposit` that allows to top up the deficit or withdraw the excess deposit for the pool. - - Switch to using Fungible trait from Currency trait. - -migrations: - runtime: - - reference: pallet-nomination-pools - description: One time migration of freezing ED from each of the existing pools. - -crates: - - name: pallet-nomination-pools diff --git a/prdoc/1.3.0/readme.md b/prdoc/1.3.0/readme.md deleted file mode 100644 index 3d74fa34247..00000000000 --- a/prdoc/1.3.0/readme.md +++ /dev/null @@ -1,2 +0,0 @@ -Version 1.3.0 does not support `prddoc` yet. -Some prdoc files are provided but the list is NOT complete. diff --git a/prdoc/1.4.0/readme.md b/prdoc/1.4.0/readme.md deleted file mode 100644 index e1a1055d918..00000000000 --- a/prdoc/1.4.0/readme.md +++ /dev/null @@ -1,2 +0,0 @@ -Version 1.4.0 does not support `prddoc` yet. -Some prdoc files are provided but the list is NOT complete. diff --git a/prdoc/1.5.0/pr_1370_special.prdoc b/prdoc/1.5.0/pr_1370_special.prdoc deleted file mode 100644 index 692a6e03170..00000000000 --- a/prdoc/1.5.0/pr_1370_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Rework the event system of `sc-network` -author: altonen -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_1497_special.prdoc b/prdoc/1.5.0/pr_1497_special.prdoc deleted file mode 100644 index 3d603548260..00000000000 --- a/prdoc/1.5.0/pr_1497_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Update tick collator for async backing -author: Sophia-Gold -topic: Tests - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_1918_special.prdoc b/prdoc/1.5.0/pr_1918_special.prdoc deleted file mode 100644 index 9220ee970bc..00000000000 --- a/prdoc/1.5.0/pr_1918_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Preserve artifact cache unless stale -author: eagr -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_1946_prdoc_new_schema.prdoc b/prdoc/1.5.0/pr_1946_prdoc_new_schema.prdoc deleted file mode 100644 index fae063f6b1e..00000000000 --- a/prdoc/1.5.0/pr_1946_prdoc_new_schema.prdoc +++ /dev/null @@ -1,17 +0,0 @@ -# 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: New PRDoc Schema - -author: chevdor -topic: documentation - -doc: - - audience: Node Dev - description: &desc | - The new version of prdoc and the new schema is activated in this PR. - - - audience: Runtime Dev - description: *desc - -crates: [] diff --git a/prdoc/1.5.0/pr_1985_special.prdoc b/prdoc/1.5.0/pr_1985_special.prdoc deleted file mode 100644 index c4305d6bb29..00000000000 --- a/prdoc/1.5.0/pr_1985_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Enable parallel key scraping -author: eagr -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2001_special.prdoc b/prdoc/1.5.0/pr_2001_special.prdoc deleted file mode 100644 index 366b5fddb8b..00000000000 --- a/prdoc/1.5.0/pr_2001_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "cumulus-consensus-common: block import: `delayed_best_block` flag added" -author: michalkucharczyk -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2058_special.prdoc b/prdoc/1.5.0/pr_2058_special.prdoc deleted file mode 100644 index 6e3c83b09fa..00000000000 --- a/prdoc/1.5.0/pr_2058_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "PVF: Add test instructions" -author: mrcnski -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2142.prdoc b/prdoc/1.5.0/pr_2142.prdoc deleted file mode 100644 index 9cd1b23906d..00000000000 --- a/prdoc/1.5.0/pr_2142.prdoc +++ /dev/null @@ -1,17 +0,0 @@ -title: Cleanup XCMP `QueueConfigData` - -author: serban300 -topic: runtime - -doc: - - audience: Runtime Dev - description: Removes obsolete fields from the `QueueConfigData` structure. For the remaining fields, if they use the old defaults, we replace them with the new defaults. - -migrations: - runtime: - - reference: cumulus_pallet_xcmp_queue - description: "v4: Removes obsolete fields from the `QueueConfigData` structure. For the remaining fields, if they use the old defaults, we replace them with the new defaults." - -crates: [] - -host_functions: [] diff --git a/prdoc/1.5.0/pr_2167_special.prdoc b/prdoc/1.5.0/pr_2167_special.prdoc deleted file mode 100644 index 7bbde7002a2..00000000000 --- a/prdoc/1.5.0/pr_2167_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "add pallet nomination-pools versioned migration to kitchensink" -author: brunopgalvao -topic: Tests - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2174_special.prdoc b/prdoc/1.5.0/pr_2174_special.prdoc deleted file mode 100644 index f23d2803e96..00000000000 --- a/prdoc/1.5.0/pr_2174_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "chain-spec-builder: cleanup" -author: michalkucharczyk -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2182_special.prdoc b/prdoc/1.5.0/pr_2182_special.prdoc deleted file mode 100644 index ad57bf64916..00000000000 --- a/prdoc/1.5.0/pr_2182_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "remove retry from backers on failed candidate validation" -author: Jpserrat -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2184_special.prdoc b/prdoc/1.5.0/pr_2184_special.prdoc deleted file mode 100644 index b838bf41ba1..00000000000 --- a/prdoc/1.5.0/pr_2184_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Zombienet tests - disputes on finalized blocks -author: Overkillus -topic: Tests - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2221_special.prdoc b/prdoc/1.5.0/pr_2221_special.prdoc deleted file mode 100644 index dbd8c4a1fc1..00000000000 --- a/prdoc/1.5.0/pr_2221_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "PVF worker: switch on seccomp networking restrictions" -author: mrcnski -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2250_special.prdoc b/prdoc/1.5.0/pr_2250_special.prdoc deleted file mode 100644 index d3f87b81b92..00000000000 --- a/prdoc/1.5.0/pr_2250_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "crypto: `lazy_static` removed, light parser for address URI added" -author: michalkucharczyk -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2265_special.prdoc b/prdoc/1.5.0/pr_2265_special.prdoc deleted file mode 100644 index 336adec03ab..00000000000 --- a/prdoc/1.5.0/pr_2265_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Remove im-online pallet from Rococo and Westend -author: s0me0ne-unkn0wn -topic: Pallets - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2300_special.prdoc b/prdoc/1.5.0/pr_2300_special.prdoc deleted file mode 100644 index 407f0766325..00000000000 --- a/prdoc/1.5.0/pr_2300_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: '[testnet] Remove Wococo stuff from BridgeHubRococo/AssetHubRococo' -author: bkontur  -topic: Bridges - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2351_special.prdoc b/prdoc/1.5.0/pr_2351_special.prdoc deleted file mode 100644 index 16f9e5d15a7..00000000000 --- a/prdoc/1.5.0/pr_2351_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "frame-system: Add last_runtime_upgrade_spec_version" -author: bkchr -topic: Frame - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2354_special.prdoc b/prdoc/1.5.0/pr_2354_special.prdoc deleted file mode 100644 index 5fbedef0361..00000000000 --- a/prdoc/1.5.0/pr_2354_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "Fix Typo: `PalletXcmExtrinsicsBenchmark`" -author: joepetrowski -topic: Benchmarks - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2361_special.prdoc b/prdoc/1.5.0/pr_2361_special.prdoc deleted file mode 100644 index d44b87287c4..00000000000 --- a/prdoc/1.5.0/pr_2361_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "[ci] Enable zombienet jobs in PRs" -author: alvicsam -topic: Tests - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2368_special.prdoc b/prdoc/1.5.0/pr_2368_special.prdoc deleted file mode 100644 index e8ebcb38d30..00000000000 --- a/prdoc/1.5.0/pr_2368_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "implementers-guide: update github link" -author: ordian -topic: Documentation - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2369_special.prdoc b/prdoc/1.5.0/pr_2369_special.prdoc deleted file mode 100644 index ebcc533712d..00000000000 --- a/prdoc/1.5.0/pr_2369_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "[NPoS] Check if staker is exposed in paged exposure storage entries" -author: Ank4n -topic: Pallets - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2377_special.prdoc b/prdoc/1.5.0/pr_2377_special.prdoc deleted file mode 100644 index 2985db6f3f8..00000000000 --- a/prdoc/1.5.0/pr_2377_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "fix typo" -author: cuteolaf -topic: Documentation - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2378_special.prdoc b/prdoc/1.5.0/pr_2378_special.prdoc deleted file mode 100644 index bdc96500094..00000000000 --- a/prdoc/1.5.0/pr_2378_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "Beefy: small fixes" -author: serban300 -topic: Bridges - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2380_special.prdoc b/prdoc/1.5.0/pr_2380_special.prdoc deleted file mode 100644 index 058be28bf5d..00000000000 --- a/prdoc/1.5.0/pr_2380_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Deprecate `RewardDestination::Controller` -author: rossbulat -topic: XCM - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2381_special.prdoc b/prdoc/1.5.0/pr_2381_special.prdoc deleted file mode 100644 index eb4020424d7..00000000000 --- a/prdoc/1.5.0/pr_2381_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Make collator RPC mode non-experimental -author: skunert -topic: Cumulus - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2385_special.prdoc b/prdoc/1.5.0/pr_2385_special.prdoc deleted file mode 100644 index a5239d30652..00000000000 --- a/prdoc/1.5.0/pr_2385_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "Relax `force_default_xcm_version` for testnet system parachains" -author: bkontur -topic: Cumulus - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2388.prdoc b/prdoc/1.5.0/pr_2388.prdoc deleted file mode 100644 index 8f79097b8f6..00000000000 --- a/prdoc/1.5.0/pr_2388.prdoc +++ /dev/null @@ -1,30 +0,0 @@ -# Schema: Parity PR Documentation Schema (prdoc) -# See doc at https://github.com/paritytech/prdoc - -title: Add new flexible `pallet_xcm::transfer_assets()` call/extrinsic - -author: acatangiu -topic: runtime - -doc: - - audience: Runtime Dev - description: | - For complex combinations of asset transfers where assets and fees may have different reserves or - different reserve/teleport trust configurations, users can use the newly added `transfer_assets()` - extrinsic which is more flexible in allowing more complex scenarios. - The new extrinsic enables, for example, a (non-system) parachain to teleport their `ForeignAssets` - assets to `AssetHub` while using (reserve-based) `DOT` to pay fees. - notes: - - Now `(limited_)reserve_transfer_assets()` only allow reserve-based transfers for all assets - including fees, similarly `(limited_)teleport_assets()` only allows teleports for all assets - including fees. - -migrations: - db: [] - - runtime: [] - -crates: - - name: pallet-xcm - -host_functions: [] diff --git a/prdoc/1.5.0/pr_2397_special.prdoc b/prdoc/1.5.0/pr_2397_special.prdoc deleted file mode 100644 index 5f07b269b1e..00000000000 --- a/prdoc/1.5.0/pr_2397_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "Pools: Add `MaxUnbonding` to metadata" -author: rossbulat -topic: Pallets - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2406_special.prdoc b/prdoc/1.5.0/pr_2406_special.prdoc deleted file mode 100644 index 3fdb7ad8cf2..00000000000 --- a/prdoc/1.5.0/pr_2406_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Refactor ValidationError -author: eagr -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2411_special.prdoc b/prdoc/1.5.0/pr_2411_special.prdoc deleted file mode 100644 index 0bc01e66903..00000000000 --- a/prdoc/1.5.0/pr_2411_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "polkadot-node-subsystems: `ChainApiBackend` added + polkadot-debug image version fixed" -author: michalkucharczyk -topic: Tests - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2413_special.prdoc b/prdoc/1.5.0/pr_2413_special.prdoc deleted file mode 100644 index 38083ba845b..00000000000 --- a/prdoc/1.5.0/pr_2413_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "Update documentation for `SafeMode` and `TxPause` Pallets" -author: wilwade -topic: Documentation - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2426_special.prdoc b/prdoc/1.5.0/pr_2426_special.prdoc deleted file mode 100644 index a0f5ab8ac5b..00000000000 --- a/prdoc/1.5.0/pr_2426_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "PVF: Fix unshare `no such file or directory` error" -author: mrcnski -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2435_special.prdoc b/prdoc/1.5.0/pr_2435_special.prdoc deleted file mode 100644 index b2bb7a2b815..00000000000 --- a/prdoc/1.5.0/pr_2435_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "pallet-staking: Converts all math operations to safe" -author: gpestanaar -topic: Pallets - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2442_special.prdoc b/prdoc/1.5.0/pr_2442_special.prdoc deleted file mode 100644 index 52e672e765f..00000000000 --- a/prdoc/1.5.0/pr_2442_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "Fixes cumulus README instructions" -author: gpestana -topic: Documentation - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2446_special.prdoc b/prdoc/1.5.0/pr_2446_special.prdoc deleted file mode 100644 index 9fec1ad139c..00000000000 --- a/prdoc/1.5.0/pr_2446_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "sp-api: Move macro related re-exports to `__private`" -author: bkchr -topic: Runtime API - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2450_special.prdoc b/prdoc/1.5.0/pr_2450_special.prdoc deleted file mode 100644 index 343e71fbf6d..00000000000 --- a/prdoc/1.5.0/pr_2450_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Adapt test worker to profile flag -author: eagr -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2455_special.prdoc b/prdoc/1.5.0/pr_2455_special.prdoc deleted file mode 100644 index 928b8467807..00000000000 --- a/prdoc/1.5.0/pr_2455_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "Remove `RuntimeApi` dependency on system parachain runtime code" -author: seadanda -topic: "System Parachains" - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2457_special.prdoc b/prdoc/1.5.0/pr_2457_special.prdoc deleted file mode 100644 index ca6401206f4..00000000000 --- a/prdoc/1.5.0/pr_2457_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "polkadot-parachain: one chain-spec for all" -author: michalkucharczyk -topic: "System Parachains" - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2459_special.prdoc b/prdoc/1.5.0/pr_2459_special.prdoc deleted file mode 100644 index 125f390f4ac..00000000000 --- a/prdoc/1.5.0/pr_2459_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: '[NPoS] Use `EraInfo` to manipulate exposure in fast-unstake tests' -author: Ank4n -topic: Pallets,Tests - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2461_special.prdoc b/prdoc/1.5.0/pr_2461_special.prdoc deleted file mode 100644 index 60a46714ca4..00000000000 --- a/prdoc/1.5.0/pr_2461_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "PVF: remove audit log access" -author: mrcnski -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2462_special.prdoc b/prdoc/1.5.0/pr_2462_special.prdoc deleted file mode 100644 index ae1f1486327..00000000000 --- a/prdoc/1.5.0/pr_2462_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "relay-chain-consensus: set a fork_choice" -author: michalkucharczyk -topic: Node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2463_special.prdoc b/prdoc/1.5.0/pr_2463_special.prdoc deleted file mode 100644 index 0f35d50036f..00000000000 --- a/prdoc/1.5.0/pr_2463_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Add `on-chain-release-build` feature for Collectives Westend -author: liamaharon -topic: System Parachains - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2474_special.prdoc b/prdoc/1.5.0/pr_2474_special.prdoc deleted file mode 100644 index 42d67b5efa6..00000000000 --- a/prdoc/1.5.0/pr_2474_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "Pools: Add ability to configure commission claiming permissions" -author: rossbulat -topic: Pallets - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2483_special.prdoc b/prdoc/1.5.0/pr_2483_special.prdoc deleted file mode 100644 index 21fb045cae8..00000000000 --- a/prdoc/1.5.0/pr_2483_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Remove `dmp-queue`` pallet from Rococo Asset Hub and Bridge Hub -author: liamaharon -topic: Frame - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2486.prdoc b/prdoc/1.5.0/pr_2486.prdoc deleted file mode 100644 index c716f71c34e..00000000000 --- a/prdoc/1.5.0/pr_2486.prdoc +++ /dev/null @@ -1,25 +0,0 @@ -title: "PVF: Add Secure Validator Mode" - -author: mrcnski -topic: node - -doc: - - audience: Node Operator - description: | - Secure Validator Mode has been enabled for Polkadot validators by default. - This enforces PVF validation security, and prevents starting a validator node if some security features are missing on the machine. - SVM can be disabled using the `--insecure-validator-i-know-what-i-do` flag. - -migrations: - db: [] - - runtime: [] - -crates: - - name: polkadot-cli - - name: polkadot-node-core-pvf - - name: polkadot-node-core-pvf-common - - name: polkadot-node-core-pvf-prepare-worker - - name: polkadot-node-core-pvf-execute-worker - -host_functions: [] diff --git a/prdoc/1.5.0/pr_2487_special.prdoc b/prdoc/1.5.0/pr_2487_special.prdoc deleted file mode 100644 index 3d6a2e11e26..00000000000 --- a/prdoc/1.5.0/pr_2487_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "Do not pollute global base path with export genesis/wasm" -author: bkchr -topic: Cumulus - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2501_special.prdoc b/prdoc/1.5.0/pr_2501_special.prdoc deleted file mode 100644 index 125b9452c98..00000000000 --- a/prdoc/1.5.0/pr_2501_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "Staking: `chill_other` takes stash instead of controller" -author: rossbulat -topic: Pallets - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2509_special.prdoc b/prdoc/1.5.0/pr_2509_special.prdoc deleted file mode 100644 index 03ebfd80c96..00000000000 --- a/prdoc/1.5.0/pr_2509_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: "Breaking: Remove long deprecated `AllPalletsWithoutSystemReversed`" -author: skunert -topic: Frame - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2515_special.prdoc b/prdoc/1.5.0/pr_2515_special.prdoc deleted file mode 100644 index 4664058f86c..00000000000 --- a/prdoc/1.5.0/pr_2515_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Set `frame_system::LastRuntimeUpgrade` after running `try-runtime migrations` -author: liamaharon -topic: Frame - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2516_special.prdoc b/prdoc/1.5.0/pr_2516_special.prdoc deleted file mode 100644 index 5d452b63e59..00000000000 --- a/prdoc/1.5.0/pr_2516_special.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Remove `dmp_queue pallet` from Westend SP runtimes -author: liamaharon -topic: Frame - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2521_special.prdoc b/prdoc/1.5.0/pr_2521_special.prdoc deleted file mode 100644 index 3b70150619e..00000000000 --- a/prdoc/1.5.0/pr_2521_special.prdoc +++ /dev/null @@ -1,10 +0,0 @@ -title: 'substrate-node: `NativeElseWasmExecutor` is no longer used' - -author: michalkucharczyk -topic: node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2526_special.prdoc b/prdoc/1.5.0/pr_2526_special.prdoc deleted file mode 100644 index 6008d7bfa9d..00000000000 --- a/prdoc/1.5.0/pr_2526_special.prdoc +++ /dev/null @@ -1,10 +0,0 @@ -title: Remove `pov-recovery` race condition/Improve zombienet test - -author: skunert -topic: testing - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2552_special.prdoc b/prdoc/1.5.0/pr_2552_special.prdoc deleted file mode 100644 index 9f0140c8142..00000000000 --- a/prdoc/1.5.0/pr_2552_special.prdoc +++ /dev/null @@ -1,10 +0,0 @@ -title: Withdraw Assets Before Checking Out in OnReapIdentity impl - -author: joepetrowski -topic: xcm - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2555_special.prdoc b/prdoc/1.5.0/pr_2555_special.prdoc deleted file mode 100644 index f817810f433..00000000000 --- a/prdoc/1.5.0/pr_2555_special.prdoc +++ /dev/null @@ -1,10 +0,0 @@ -title: Remove dependency on rand's SliceRandom shuffle implementation in `gossip-support` - -author: rphmeier -topic: node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2572_special.prdoc b/prdoc/1.5.0/pr_2572_special.prdoc deleted file mode 100644 index 9d4c285798c..00000000000 --- a/prdoc/1.5.0/pr_2572_special.prdoc +++ /dev/null @@ -1,10 +0,0 @@ -title: Add missing glossary to ref docs - -author: juangirini -topic: documentation - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2579_special.prdoc b/prdoc/1.5.0/pr_2579_special.prdoc deleted file mode 100644 index 2992c92a8c5..00000000000 --- a/prdoc/1.5.0/pr_2579_special.prdoc +++ /dev/null @@ -1,10 +0,0 @@ -title: "impl guide: update PVF host page; add diagrams" - -author: mrcnsk -topic: documentation - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2581_special.prdoc b/prdoc/1.5.0/pr_2581_special.prdoc deleted file mode 100644 index ebe5855b401..00000000000 --- a/prdoc/1.5.0/pr_2581_special.prdoc +++ /dev/null @@ -1,10 +0,0 @@ -title: 'Bandersnatch: `ring-context` generic over domain size' - -author: davxy -topic: node - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2591.prdoc b/prdoc/1.5.0/pr_2591.prdoc deleted file mode 100644 index f827e70af8b..00000000000 --- a/prdoc/1.5.0/pr_2591.prdoc +++ /dev/null @@ -1,12 +0,0 @@ -title: Ensure to cleanup state in `remove_member` - -author: bkchr -topic: runtime - -doc: - - audience: Runtime Dev - description: | - Cleans up the state properly if a member of a ranked collective is removed. - -crates: - - name: pallet-ranked-collective diff --git a/prdoc/1.5.0/pr_2602_special.prdoc b/prdoc/1.5.0/pr_2602_special.prdoc deleted file mode 100644 index 56896348b4f..00000000000 --- a/prdoc/1.5.0/pr_2602_special.prdoc +++ /dev/null @@ -1,10 +0,0 @@ -title: 'Bridges subtree update' - -author: bkontur -topic: bridges - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/pr_2625_special.prdoc b/prdoc/1.5.0/pr_2625_special.prdoc deleted file mode 100644 index 3ffcf598660..00000000000 --- a/prdoc/1.5.0/pr_2625_special.prdoc +++ /dev/null @@ -1,10 +0,0 @@ -title: Improved `ExportXcm::validate` implementation for BridgeHubs - -author: bkontur -topic: bridges - -doc: - - audience: Runtime Dev - description: n/a - -crates: [] diff --git a/prdoc/1.5.0/readme.md b/prdoc/1.5.0/readme.md deleted file mode 100644 index 14b6d603314..00000000000 --- a/prdoc/1.5.0/readme.md +++ /dev/null @@ -1,2 +0,0 @@ -Version 1.5.0 does not fully support `prddoc` yet. -While the list is complete, not all prdoc files have a valid or accurate content. diff --git a/prdoc/1.4.0/pr_1178.prdoc b/prdoc/pr_1178.prdoc similarity index 96% rename from prdoc/1.4.0/pr_1178.prdoc rename to prdoc/pr_1178.prdoc index 528e523c432..36c3b05c7a3 100644 --- a/prdoc/1.4.0/pr_1178.prdoc +++ b/prdoc/pr_1178.prdoc @@ -6,9 +6,9 @@ doc: Changed approval-voting, approval-distribution to send all messages tranche0 assignments in one message. This required: * A new parachains_db version. - * A new validation protocol to support the new message types. + * A new validation protocol to support the new message types. The new logic will be disabled and will be enabled at a later date after all validators have upgraded. - + migrations: db: - name: Parachains database change from v3 to v4. @@ -18,5 +18,6 @@ migrations: crates: - name: "polkadot" + semver: patch host_functions: [] diff --git a/prdoc/pr_1191.prdoc b/prdoc/pr_1191.prdoc deleted file mode 100644 index 26626731be4..00000000000 --- a/prdoc/pr_1191.prdoc +++ /dev/null @@ -1,21 +0,0 @@ -title: Approve multiple candidates with a single signature - -doc: - - audience: Node Operator - description: | - Changed approval-voting, approval-distribution to approve multiple candidate with a single message, it adds: - * A new parachains_db version. - * A new validation protocol to support the new message types. - The new logic will be disabled and will be enabled at a later date after all validators have upgraded. - -migrations: - db: - - name: Parachains database change from v4 to v5. - description: | - Approval-voting column format has been updated with several new fields. All existing data will be automatically - be migrated to the new values. - -crates: - - name: "polkadot" - -host_functions: [] diff --git a/prdoc/pr_1226.prdoc b/prdoc/pr_1226.prdoc index caef324bfd0..df7a425b538 100644 --- a/prdoc/pr_1226.prdoc +++ b/prdoc/pr_1226.prdoc @@ -1,12 +1,17 @@ title: Removed deprecated `Balances::transfer` and `Balances::set_balance_deprecated` functions. doc: - - audience: Runtime User - description: | - The Balances pallet's dispatchables `set_balance_deprecated` and `transfer` were deprecated in [paritytech/substrate#12951](https://github.com/paritytech/substrate/pull/12951) and have now been removed. - - notes: + - audience: Builder + description: The Balances pallet's dispatchables `set_balance_deprecated` and `transfer` were deprecated in [paritytech/substrate#12951](https://github.com/paritytech/substrate/pull/12951) and have now been removed. + notes: - Use `set_balance_deprecated` instead `force_set_balance` and `transfer_allow_death` instead of `transfer`. +migrations: + db: [] + + runtime: [] + crates: - name: pallet-balances + +host_functions: [] diff --git a/prdoc/1.3.0/pr_1234.prdoc b/prdoc/pr_1234.prdoc similarity index 83% rename from prdoc/1.3.0/pr_1234.prdoc rename to prdoc/pr_1234.prdoc index e1e5d71050a..cc22a02d88b 100644 --- a/prdoc/1.3.0/pr_1234.prdoc +++ b/prdoc/pr_1234.prdoc @@ -4,10 +4,17 @@ title: Introduce XcmFeesToAccount fee manager doc: - - audience: Runtime User + - audience: Builder description: | Now all XCM sending, unless done by the system for the system, will be charged delivery fees. All runtimes are now configured to send these delivery fees to a treasury account. The fee formula is `delivery_fee_factor * (base_fee + encoded_msg_len * per_byte_fee)`. -crates: [ ] +migrations: + db: [] + + runtime: [] + +crates: [] + +host_functions: [] diff --git a/prdoc/1.4.0/pr_1246.prdoc b/prdoc/pr_1246.prdoc similarity index 87% rename from prdoc/1.4.0/pr_1246.prdoc rename to prdoc/pr_1246.prdoc index a4d270c45cb..f9c86781233 100644 --- a/prdoc/1.4.0/pr_1246.prdoc +++ b/prdoc/pr_1246.prdoc @@ -1,17 +1,17 @@ title: Use the `Message Queue` Pallet for DMP and XCMP dispatch queueing doc: - - audience: Runtime Dev + - audience: Parachain Dev description: Replaces the queueing capabilities of the `DMP and `XCMP-Queue` pallet for incoming messages with the `MessageQueue` pallet. This simplifies the code and improves security. migrations: runtime: - - reference: cumulus_pallet_dmp_queue + pallet: "cumulus_pallet_dmp_queue" description: "Messages from the DMP dispatch queue will be moved over to the MQ pallet via `on_initialize`. This happens over multiple blocks and emits a `Completed` event at the end. The pallet can be un-deployed and deleted afterwards. Note that the migration reverses the order of messages, which should be acceptable as a one-off." crates: - - name: cumulus_pallet_xcmp_queue + - name: "cumulus_pallet_xcmp_queue" note: Pallet config must be altered according to the MR description. host_functions: [] diff --git a/prdoc/pr_1255.prdoc b/prdoc/pr_1255.prdoc new file mode 100644 index 00000000000..793b5c3c859 --- /dev/null +++ b/prdoc/pr_1255.prdoc @@ -0,0 +1,22 @@ +# Schema: Parity PR Documentation Schema (prdoc) +# See doc at https://github.com/paritytech/prdoc + +title: Fix for Reward Deficit in the pool + +doc: + - audience: Core Dev + description: Instead of fragile calculation of current balance by looking at free balance - ED, Nomination Pool now freezes ED in the pool reward account to restrict an account from going below minimum balance. This also has a nice side effect that if ED changes, we know how much is the imbalance in ED frozen in the pool and the current required ED. A pool operator can diligently top up the pool with the deficit in ED or vice versa, withdraw the excess they transferred to the pool. + notes: + - Introduces new call `adjust_pool_deposit` that allows to top up the deficit or withdraw the excess deposit for the pool. + - Switch to using Fungible trait from Currency trait. + +migrations: + db: [] + + runtime: + - { pallet: "pallet-nomination-pools", description: "One time migration of freezing ED from each of the existing pools."} + +crates: + - name: pallet-nomination-pools + +host_functions: [] \ No newline at end of file diff --git a/prdoc/1.4.0/pr_1256.prdoc b/prdoc/pr_1256.prdoc similarity index 100% rename from prdoc/1.4.0/pr_1256.prdoc rename to prdoc/pr_1256.prdoc diff --git a/prdoc/pr_1289.prdoc b/prdoc/pr_1289.prdoc index 059d7608ba6..f3d8801d9d8 100644 --- a/prdoc/pr_1289.prdoc +++ b/prdoc/pr_1289.prdoc @@ -4,26 +4,25 @@ title: Supporting paged rewards allowing all nominators to be rewarded doc: - - audience: Node Operator + - audience: Validator description: | We used to clip top `MaxNominatorRewardedPerValidator` nominators by stake that are eligible for staking reward. This was done to limit computation cost of paying out rewards. This PR introduces paging to reward payouts, meaning we still clip nominators upto MaxExposurePageSize per page and there could be multiple pages of rewards to be paid out. Validators get commission pro-rata to the amount of reward that is paid out for the page. - notes: - - payout_stakers should be called multiple times, once for each page of nominators. - - payout_stakers_by_page can be used to pay out rewards for a specific page. - - Some old non-paged era storage items are deprecated, and can be removed in a future upgrade. + notes: + - payout_stakers should be called multiple times, once for each page of nominators. + - payout_stakers_by_page can be used to pay out rewards for a specific page. + - Some old non-paged era storage items are deprecated, and can be removed in a future upgrade. migrations: db: [] runtime: - - reference: pallet-staking - description: "v14: Migration of era exposure storage items to paged exposures." + - { pallet: "pallet-staking", description: "v14: Migration of era exposure storage items to paged exposures."} crates: - name: pallet-staking -host_functions: [] +host_functions: [] \ No newline at end of file diff --git a/prdoc/pr_1343.prdoc b/prdoc/pr_1343.prdoc deleted file mode 100644 index 84168230e0a..00000000000 --- a/prdoc/pr_1343.prdoc +++ /dev/null @@ -1,29 +0,0 @@ -title: Tasks API - A general system for recognizing and executing service work - -doc: - - audience: Runtime Dev - description: | - The Tasks API allows you to define some service work that can be recognized by a script or an off-chain worker. - Such a script can then create and submit all such work items at any given time. - `#[pallet:tasks_experimental]` provides a convenient way to define such work items. It can be attached to an - `impl` block inside a pallet, whose functions can then be annotated by the following attributes: - 1. `#[pallet::task_list]`: Define an iterator over the available work items for a task - 2. `#[pallet::task_condition]`: Define the conditions for a given work item to be valid - 3. `#[pallet::task_weight]`: Define the weight of a given work item - 4. `#[pallet::task_index]`: Define the index of a given work item - Each such function becomes a variant of the autogenerated enum `Task` for this pallet. - All such enums are aggregated into a `RuntimeTask` by `construct_runtime`. - An example pallet that uses the Tasks API is available at `substrate/frame/example/tasks`. - -migrations: - db: [] - - runtime: [] - -crates: - - name: frame-system - - name: frame-support - - name: frame-support-procedural - - name: pallet-example-tasks - -host_functions: [] diff --git a/prdoc/1.5.0/pr_1408_prodc-introduction.prdoc b/prdoc/pr_1408_prodc-introduction.prdoc similarity index 76% rename from prdoc/1.5.0/pr_1408_prodc-introduction.prdoc rename to prdoc/pr_1408_prodc-introduction.prdoc index 46f56068e27..4b10e0fe2e8 100644 --- a/prdoc/1.5.0/pr_1408_prodc-introduction.prdoc +++ b/prdoc/pr_1408_prodc-introduction.prdoc @@ -1,15 +1,19 @@ # This PR does not need a prdoc but it is provided in order to test title: PRdoc check -author: chevdor -topic: documentation - doc: - - audience: Node Dev + - audience: Core Dev description: | This PRdoc is an **example**. This PR brings support and automated checks for documentation in the form of a [`prdoc`](https://github.com/paritytech/prdoc/) file. -crates: [ ] +migrations: + db: [] + + runtime: [] + +crates: [] + +host_functions: [] diff --git a/prdoc/pr_1454.prdoc b/prdoc/pr_1454.prdoc deleted file mode 100644 index c96bfcde6cf..00000000000 --- a/prdoc/pr_1454.prdoc +++ /dev/null @@ -1,10 +0,0 @@ -title: Support XCM as part of Cosmos CosmWasm contract messages - -doc: - - audience: Runtime Dev - description: | - Made XCM JSON schema behind flag, bumped bounded-collection so to ensure it has that flag too. - -crates: - - name: staging-xcm - - name: sp-weights diff --git a/prdoc/1.4.0/pr_1805.prdoc b/prdoc/pr_1805.prdoc similarity index 87% rename from prdoc/1.4.0/pr_1805.prdoc rename to prdoc/pr_1805.prdoc index 30f0fbea307..8a8e6c2fde2 100644 --- a/prdoc/1.4.0/pr_1805.prdoc +++ b/prdoc/pr_1805.prdoc @@ -1,7 +1,7 @@ title: Introduce state decoding check after runtime upgrades. doc: - - audience: Runtime Dev + - audience: Core Dev description: | Adds a check to the try-runtime logic that will verify that all pallet on-chain storage still decodes. This can help to spot missing migrations before they become a problem. The check is enabled as soon as the `--checks` option of the `try-runtime` CLI is not `None`. @@ -10,8 +10,10 @@ migrations: runtime: [] -crates: +crates: - name: frame-support + semver: minor - name: frame-support-procedural + semver: minor host_functions: [] diff --git a/prdoc/1.3.0/pr_1818.prdoc b/prdoc/pr_1818.prdoc similarity index 63% rename from prdoc/1.3.0/pr_1818.prdoc rename to prdoc/pr_1818.prdoc index 0f59a0f9124..cbafa02f9af 100644 --- a/prdoc/1.3.0/pr_1818.prdoc +++ b/prdoc/pr_1818.prdoc @@ -1,9 +1,16 @@ title: FRAME pallets warning for unchecked weight witness doc: - - audience: Runtime Dev + - audience: Core Dev description: | FRAME pallets now emit a warning when a call uses a function argument that starts with an underscore in its weight declaration. +migrations: + db: [ ] + runtime: [ ] + +host_functions: [] + crates: - - name: frame-support-procedural +- name: "frame-support-procedural" + semver: minor diff --git a/prdoc/1.3.0/pr_1873.prdoc b/prdoc/pr_1873.prdoc similarity index 66% rename from prdoc/1.3.0/pr_1873.prdoc rename to prdoc/pr_1873.prdoc index c22b732c72f..6f3bc7646db 100644 --- a/prdoc/1.3.0/pr_1873.prdoc +++ b/prdoc/pr_1873.prdoc @@ -1,9 +1,15 @@ title: Message Queue use proper overweight limit doc: - - audience: Node Dev + - audience: Core Dev description: | Changed the overweight cutoff limit from the full `Config::ServiceWeight` to a lower value that is calculated based on the weight of the functions being called. -crates: - - name: pallet-message-queue +migrations: + db: [] + + runtime: [] + +crates: ["pallet-message-queue", patch] + +host_functions: [] diff --git a/prdoc/1.3.0/pr_1913.prdoc b/prdoc/pr_1913.prdoc similarity index 87% rename from prdoc/1.3.0/pr_1913.prdoc rename to prdoc/pr_1913.prdoc index c2e7627c9ac..155057054eb 100644 --- a/prdoc/1.3.0/pr_1913.prdoc +++ b/prdoc/pr_1913.prdoc @@ -7,6 +7,13 @@ doc: If experiencing stability issues caused by BEEFY, it can be disabled using `--no-beefy` flag. BEEFY doesn't (yet) support warp sync. So, attempting to Warp sync as a validator will throw an error. +migrations: + db: [] + + runtime: [] + crates: - name: polkadot-cli - name: polkadot-service + +host_functions: [] diff --git a/prdoc/1.3.0/pr_1921.prdoc b/prdoc/pr_1921.prdoc similarity index 67% rename from prdoc/1.3.0/pr_1921.prdoc rename to prdoc/pr_1921.prdoc index e71a68fa829..5ed0137cd5f 100644 --- a/prdoc/1.3.0/pr_1921.prdoc +++ b/prdoc/pr_1921.prdoc @@ -1,14 +1,19 @@ title: Fix para-scheduler migration doc: - - audience: Runtime Dev + - audience: Core Dev description: | Changing the `MigrateToV1` migration in the `ParachainScheduler` pallet to be truly idempotent. It is achieved by wrapping it in a `VersionedMigration`. migrations: + db: [] + runtime: - - reference: ParachainScheduler + - pallet: "ParachainScheduler" description: Non-critical fixup for `MigrateToV1`. crates: - - name: polkadot-runtime-parachains + - name: "polkadot-runtime-parachains" + semver: patch + +host_functions: [] diff --git a/prdoc/1.4.0/pr_1926.prdoc b/prdoc/pr_1926.prdoc similarity index 59% rename from prdoc/1.4.0/pr_1926.prdoc rename to prdoc/pr_1926.prdoc index e7c4293d9fd..9dc656f1260 100644 --- a/prdoc/1.4.0/pr_1926.prdoc +++ b/prdoc/pr_1926.prdoc @@ -1,10 +1,10 @@ title: Adds syntax for marking calls feeless doc: - - audience: Runtime Dev + - audience: Core Dev description: | 1. Adds an attribute `#[pallet::feeless_if]` that can be optionally attached to a `pallet::call`. - 2. Adds a signed extension SkipCheckIfFeeless that wraps a transaction + 2. Adds a signed extension SkipCheckIfFeeless that wraps a transaction payment processor to potentially skip payment fees for such calls. Note that both the attribute and the signed extension are needed to make the call feeless. @@ -14,11 +14,17 @@ migrations: runtime: [] crates: - - name: frame-support-procedural - - name: pallet-skip-feeless-payment - - name: pallet-example-kitchensink - - name: kitchensink-runtime - - name: node-testing - - name: node-cli + - name: "frame-support-procedural" + semver: minor + - name: "pallet-skip-feeless-payment" + semver: major + - pallet-example-kitchensink + semver: patch + - kitchensink-runtime + semver: major + - node-testing + semver: patch + - node-cli + semver: patch host_functions: [] diff --git a/prdoc/1.4.0/pr_2086.prdoc b/prdoc/pr_2086.prdoc similarity index 70% rename from prdoc/1.4.0/pr_2086.prdoc rename to prdoc/pr_2086.prdoc index 3bd568cc139..a9bbd0729d5 100644 --- a/prdoc/1.4.0/pr_2086.prdoc +++ b/prdoc/pr_2086.prdoc @@ -1,12 +1,15 @@ title: "Contracts: Add XCM traits to interface with contracts" doc: - - audience: Runtime Dev + - audience: Core Dev description: | We are introducing a new set of `XcmController` traits in `pallet-xcm`. - These traits extract functionality from `pallet-xcm` and provide high-level interaction with XCM. + These traits extract functionality from `pallet-xcm` and provide high-level interaction with XCM. They enable other pallets, like `pallet_contracts`, to rely on these traits instead of tight coupling to `pallet-xcm` itself. crates: - - name: pallet-xcm - - name: xcm-executor + - name: "pallet-xcm" + semver: patch + - name: "xcm-executor" + semver: patch + diff --git a/prdoc/1.4.0/pr_2107.prdoc b/prdoc/pr_2107.prdoc similarity index 91% rename from prdoc/1.4.0/pr_2107.prdoc rename to prdoc/pr_2107.prdoc index be71828cbad..0e33680555a 100644 --- a/prdoc/1.4.0/pr_2107.prdoc +++ b/prdoc/pr_2107.prdoc @@ -4,16 +4,14 @@ title: Add a builder pattern to create XCM programs doc: - - audience: Runtime Dev + - audience: Core Dev description: | XCMs can now be built using a builder pattern like so: - ``` Xcm::builder() .withdraw_asset(assets) .buy_execution(fees, weight_limit) .deposit_asset(assets, beneficiary) .build(); - ``` migrations: db: [] diff --git a/prdoc/1.4.0/pr_2165.prdoc b/prdoc/pr_2165.prdoc similarity index 80% rename from prdoc/1.4.0/pr_2165.prdoc rename to prdoc/pr_2165.prdoc index 3b10bcfe6a5..31cb691c43a 100644 --- a/prdoc/1.4.0/pr_2165.prdoc +++ b/prdoc/pr_2165.prdoc @@ -1,7 +1,7 @@ -title: Add `sudo::remove_key` +title: Add sudo::remove_key doc: - - audience: Runtime User + - audience: Core Dev description: | Pallet `Sudo` now has the ability to remove the sudo key via `remove_key`. This is a less-invasive way of rendering the sudo pallet useless without needing a code upgrade. @@ -12,5 +12,6 @@ migrations: crates: - name: pallet-sudo + semver: minor host_functions: [] diff --git a/prdoc/1.5.0/pr_2253.prdoc b/prdoc/pr_2253.prdoc similarity index 92% rename from prdoc/1.5.0/pr_2253.prdoc rename to prdoc/pr_2253.prdoc index 3f69bc2461e..398b0a29066 100644 --- a/prdoc/1.5.0/pr_2253.prdoc +++ b/prdoc/pr_2253.prdoc @@ -3,11 +3,8 @@ title: Different builder pattern constructors for XCM -author: franciscoaguirre -topic: runtime - doc: - - audience: Runtime Dev + - audience: Core Dev description: | The `builder()` constructor for XCM programs now only allows building messages that pay for fees, i.e. messages that would pass the `AllowTopLevelPaidExecutionFrom` barrier. diff --git a/prdoc/pr_2331.prdoc b/prdoc/pr_2331.prdoc deleted file mode 100644 index e3daf4c45bd..00000000000 --- a/prdoc/pr_2331.prdoc +++ /dev/null @@ -1,17 +0,0 @@ -title: Rename `ExportGenesisStateCommand` to `ExportGenesisHeadCommand` - -doc: - - audience: Node Operator - description: | - The `export-genesis-state` subcommand is now called `export-gensis-head`, but - `export-genesis-state` stays as an alias to not break any scripts. - - - audience: Node Dev - description: | - The struct `ExportGenesisStateCommand` is now called `ExportGenesisHeadCommand`. - So, you only need to rename the import and usage. The `run` function is now - taking only a `client` as argument to fetch the genesis header. This way - the exported genesis head is respecting custom genesis block builders. - -crates: - - name: "cumulus-client-cli" diff --git a/prdoc/pr_2403.prdoc b/prdoc/pr_2403.prdoc deleted file mode 100644 index f1c4d3ecbaf..00000000000 --- a/prdoc/pr_2403.prdoc +++ /dev/null @@ -1,9 +0,0 @@ -title: Configurable block number provider in pallet-vesting - -doc: - - audience: Runtime Dev - description: | - Adds `BlockNumberProvider` type to pallet-vesting Config trait, allowing for custom providers instead of hardcoding frame-system. - This is particularly useful for parachains wanting to use `cumulus_pallet_parachain_system::RelaychainDataProvider` with `pallet-vesting`. - -crates: [ ] diff --git a/prdoc/pr_2481.prdoc b/prdoc/pr_2481.prdoc deleted file mode 100644 index d8736b1afd6..00000000000 --- a/prdoc/pr_2481.prdoc +++ /dev/null @@ -1,13 +0,0 @@ -# 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-builder: `HaulBlobExporter` with improved XCM version check." - -doc: - - audience: Runtime Dev - description: | - Version check in `HaulBlobExporter` uses new trait `CheckVersion` to check known/configured destination versions, - ensuring compatibility. `HaulBlobExporter` will attempt to downgrade the message to destination's known version - instead of using the latest version. - -crates: [ ] diff --git a/prdoc/pr_2532.prdoc b/prdoc/pr_2532.prdoc deleted file mode 100644 index d0df0ee4aca..00000000000 --- a/prdoc/pr_2532.prdoc +++ /dev/null @@ -1,11 +0,0 @@ -# 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: Westend Fellowship Treasury - -doc: - - audience: Runtime User - description: | - Treasury Pallet Instance for the Fellowship in Westend Collectives. - -crates: [ ] diff --git a/prdoc/pr_2597.prdoc b/prdoc/pr_2597.prdoc deleted file mode 100644 index 33d85053184..00000000000 --- a/prdoc/pr_2597.prdoc +++ /dev/null @@ -1,17 +0,0 @@ -title: Make crate visible methods of `OverlayedChanges` public. - -doc: - - audience: Node Dev - description: | - Make some methods of `OverlayedChanges` namely `set_child_storage`, `clear_child_storage`, `clear_prefix` - and `clear_child_prefix` public which only had crate level visibility. - -migrations: - db: [] - - runtime: [] - -crates: - - name: sp-state-machine - -host_functions: [] diff --git a/prdoc/pr_2656.prdoc b/prdoc/pr_2656.prdoc deleted file mode 100644 index 563218dbde6..00000000000 --- a/prdoc/pr_2656.prdoc +++ /dev/null @@ -1,10 +0,0 @@ -title: "pallet-broker: Small improvements to the origin checks" - -doc: - - audience: Runtime User - description: | - Change the permissionless calls `drop_region`, `drop_contribution`, `drop_history` and - `drop_renewal` to allow any kind of origin. - -crates: - - name: "pallet-broker" diff --git a/prdoc/pr_2663-fix-could-not-create-temporary-drectory.prdoc b/prdoc/pr_2663-fix-could-not-create-temporary-drectory.prdoc deleted file mode 100644 index 2119599fce1..00000000000 --- a/prdoc/pr_2663-fix-could-not-create-temporary-drectory.prdoc +++ /dev/null @@ -1,17 +0,0 @@ -title: "PVF: fix unshare 'could not create temporary directory'" - -doc: - - audience: Node Operator - description: | - For validators: fixes the potential warning/error: - "Cannot unshare user namespace and change root, which are Linux-specific kernel security features: could not create a temporary directory in "/tmp/.tmpIcLriO". - -migrations: - db: [] - - runtime: [] - -crates: - - name: polkadot-node-core-pvf - -host_functions: [] diff --git a/prdoc/pr_2684.prdoc b/prdoc/pr_2684.prdoc deleted file mode 100644 index 8960b6460f0..00000000000 --- a/prdoc/pr_2684.prdoc +++ /dev/null @@ -1,14 +0,0 @@ -title: Add XCM FungibleAdapter - -doc: - - audience: Runtime Dev - description: | - A new AssetTransactor has been added to xcm-builder: FungibleAdapter. - It's meant to be used instead of the old CurrencyAdapter for configuring the XCM executor - to handle only one asset. - -crates: - - name: "xcm-builder" - -migrations: [] -host_functions: [] diff --git a/prdoc/pr_2687.prdoc b/prdoc/pr_2687.prdoc deleted file mode 100644 index 90e635d8052..00000000000 --- a/prdoc/pr_2687.prdoc +++ /dev/null @@ -1,18 +0,0 @@ -title: "pallet-uniques: Move migration over to `VersionedMigration`" - -doc: - - audience: Runtime Dev - description: | - Moves the migration over to `VersionedMigration`. Thus, if you had - used `migrate_to_v1` before in a custom `OnRuntimeUpgrade` implementation - you can now directly use the `MigrateV0ToV1`. - -migrations: - runtime: - - reference: MigrateV0ToV1 - description: | - Migrate the pallet storage from `0` to `1` by initializing - the `CollectionAccount` storage entry from all collections. - -crates: - - name: "pallet-uniques" diff --git a/prdoc/schema_user.json b/prdoc/schema_user.json deleted file mode 100644 index 82215d51866..00000000000 --- a/prdoc/schema_user.json +++ /dev/null @@ -1,222 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema#", - "$id": "https://raw.githubusercontent.com/paritytech/prdoc/master/prdoc_schema_user.json", - "version": { - "major": 1, - "minor": 0, - "patch": 0, - "timestamp": 20230817152351 - }, - "title": "Polkadot SDK PRDoc Schema", - "description": "JSON Schema definition for the Polkadot SDK PR documentation", - "type": "object", - "additionalProperties": false, - "properties": { - "title": { - "title": "Title of the change", - "type": "string", - "description": "Title for the PR. This is what will show up in the release notes.\nif needed, you may provide a different title override for each audience in the `doc` property." - }, - "author": { - "title": "Author handle", - "type": "string", - "description": "Author handle" - }, - "topic": { - "title": "Topic", - "type": "string", - "description": "Topic" - }, - - "doc": { - "type": "array", - "title": "Documentation adapted to the audience(s)", - "description": "Description of the PR. Provide a description for each relevant audience.\nSee the `audience` property for more documentation about audiences", - "items": { - "$ref": "#/$defs/doc" - }, - "minItems": 1 - }, - - "crates": { - "title": "Crates", - "description": "You have the option to provide a hint about the crates that have noticeable changes.\n This is used during the crate publishing to crates.io and to help users understand the impact of the changes introduced in your PR.", - "type": "array", - "items": { - "$ref": "#/$defs/crate" - } - }, - - "migrations": { - "title": "Migrations (DB & Runtime)", - "description": "It is important for users to be aware of migrations.\nMake sure to mention any migrations in the appropriate sub-properties:\n- db\n- runtime", - "type": "object", - "properties": { - "db": { - "type": "array", - "nullable": false, - "title": "Database Migration", - "description": "List of the Database Migrations or empty array: []", - "items": { - "$ref": "#/$defs/migration_db" - }, - "minItems": 0, - "required": [ - "name", - "description" - ] - }, - "runtime": { - "type": "array", - "title": "Runtime Migration", - "nullable": false, - "description": "List of the Runtime Migrations or empty array: []", - "minItems": 0, - "items": { - "$ref": "#/$defs/migration_runtime" - }, - "required": [ - "db", - "runtime" - ] - } - } - }, - "host_functions": { - "title": "Host Functions", - "description": "List of the host functions involved in this PR.", - "type": "array", - "items": { - "$ref": "#/$defs/host_function" - } - } - }, - "required": [ - "title", - "doc", - "crates" - ], - "$defs": { - "audience": { - "description": "You may pick one or more audiences and address those users with appropriate documentation, information and warning related to the PR.", - "oneOf": [ - {"const": "Node Dev", - "title": "Node Dev", - "description": "Those who build around the client side code. Alternative client builders, SMOLDOT, those who consume RPCs. These are people who are oblivious to the runtime changes. They only care about the meta-protocol, not the protocol itself."}, - - {"const": "Runtime Dev", - "title": "Runtime Dev", - "description": "All of those who rely on the runtime. A parachain team that is using a pallet. A DApp that is using a pallet. These are people who care about the protocol (WASM), not the meta-protocol (client)."}, - - {"const": "Node Operator", - "title": "Node Operator", - "description": "Those who don't write any code and only run code."}, - - {"const": "Runtime User", - "title": "Runtime User", - "description": "Anyone using the runtime. This can be a token holder or a dev writing a front end for a chain."} - ] - }, - "crate": { - "type": "object", - "description": "You have the option here to provide a hint about a crate that has changed to help with the publishing of crates.", - "additionalProperties": false, - "properties": { - "name": { - "type": "string" - }, - "note": { - "type": "string" - } - } - }, - "migration_db": { - "type": "object", - "description": "This property allows the documentation of database migrations.", - "properties": { - "name": { - "type": "string" - }, - "description": { - "type": "string" - } - }, - "additionalProperties": false, - "required": [ - "name", - "description" - ] - }, - "migration_runtime": { - "type": "object", - "description": "This property allows the documentation of runtime migrations.", - "properties": { - "reference": { - "title": "Migration reference", - "description": "Reference to the runtime migration", - "type": "string" - }, - "description": { - "type": "string" - } - }, - "additionalProperties": false, - "required": [ - "description" - ] - }, - "doc": { - "type": "object", - "description": "You have the the option to provide different description of your PR for different audiences.", - "additionalProperties": false, - "properties": { - "audience": { - "description": "The selected audience", - "$ref": "#/$defs/audience" - }, - "title": { - "type": "string", - "title": "Title for the audience", - "description": "Optional title override for the PR and for the current audience" - }, - "description": { - "title": "Description for the audience", - "description": "Description of the change", - "type": "string" - } - } - }, - "array_of_strings": { - "description": "An array of strings that can be empty", - "type": "array", - "items": { - "type": "string" - } - }, - "host_function": { - "type": "object", - "additionalProperties": false, - "title": "Host Functions", - "description": "List of host functions and their descriptions", - "properties": { - "name": { - "title": "Host function name", - "description": "Name or identifier to find the host function in the codebase", - "type": "string" - }, - "description": { - "title": "Host function description", - "description": "Short description of the host function", - "type": "string" - }, - "notes": { - "type": "string" - } - }, - "required": [ - "name", - "description" - ] - } - } - } diff --git a/scripts/release/build-changelogs.sh b/scripts/release/build-changelogs.sh deleted file mode 100755 index a9275f45a50..00000000000 --- a/scripts/release/build-changelogs.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env bash - -export PRODUCT=polkadot -export VERSION=${VERSION:-1.5.0} - -PROJECT_ROOT=`git rev-parse --show-toplevel` -echo $PROJECT_ROOT - -TMP=$(mktemp -d) -TEMPLATE_AUDIENCE="${PROJECT_ROOT}/scripts/release/templates/audience.md.tera" -TEMPLATE_CHANGELOG="${PROJECT_ROOT}/scripts/release/templates/changelog.md.tera" - -DATA_JSON="${TMP}/data.json" -CONTEXT_JSON="${TMP}/context.json" -echo -e "TEMPLATE_AUDIENCE: \t$TEMPLATE_AUDIENCE" -echo -e "DATA_JSON: \t\t$DATA_JSON" -echo -e "CONTEXT_JSON: \t\t$CONTEXT_JSON" - -# Create output folder -OUTPUT="${TMP}/changelogs/$PRODUCT/$VERSION" -echo -e "OUTPUT: \t\t$OUTPUT" -mkdir -p $OUTPUT - -prdoc load -d "$PROJECT_ROOT/prdoc/$VERSION" --json > $DATA_JSON -# ls -al $DATA_JSON - -cat $DATA_JSON | jq ' { "prdoc" : .}' > $CONTEXT_JSON -# ls -al $CONTEXT_JSON - -# Fetch the list of valid audiences -SCHEMA_URL=https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json -SCHEMA=$(curl -s $SCHEMA_URL | sed 's|^//.*||') -AUDIENCE_ARRAY=$(echo -E $SCHEMA | jq -r '."$defs".audience.oneOf[] | .const') - -readarray -t audiences < <(echo "$AUDIENCE_ARRAY") -declare -p audiences - - -# Generate a changelog -echo "Generating changelog..." -tera -t "${TEMPLATE_CHANGELOG}" --env --env-key env "${CONTEXT_JSON}" > "$OUTPUT/changelog.md" -echo "Changelog ready in $OUTPUT/changelog.md" - -# Generate a release notes doc per audience -for audience in "${audiences[@]}"; do - audience_id="$(tr [A-Z] [a-z] <<< "$audience")" - audience_id="$(tr ' ' '_' <<< "$audience_id")" - echo "Processing audience: $audience ($audience_id)" - export TARGET_AUDIENCE=$audience - tera -t "${TEMPLATE_AUDIENCE}" --env --env-key env "${CONTEXT_JSON}" > "$OUTPUT/relnote_${audience_id}.md" -done - -# Show the files -tree -s -h -c $OUTPUT/ diff --git a/scripts/release/templates/audience.md.tera b/scripts/release/templates/audience.md.tera deleted file mode 100644 index dc507053dd5..00000000000 --- a/scripts/release/templates/audience.md.tera +++ /dev/null @@ -1,13 +0,0 @@ -## Release {{ env.PRODUCT }} {{ env.VERSION }} - -Changelog for `{{ env.TARGET_AUDIENCE }}`. - -{% for file in prdoc -%} -#### PR #{{file.doc_filename.number}}: {{ file.content.title }} -{% for doc_item in file.content.doc %} -{%- if doc_item.audience == env.TARGET_AUDIENCE %} -{{ doc_item.description }} -{% endif -%} - -{%- endfor %} -{%- endfor %} diff --git a/scripts/release/templates/changelog.md.tera b/scripts/release/templates/changelog.md.tera deleted file mode 100644 index aaba761e8e4..00000000000 --- a/scripts/release/templates/changelog.md.tera +++ /dev/null @@ -1,7 +0,0 @@ -## Changelog for `{{ env.PRODUCT | capitalize }} v{{ env.VERSION }}` - -{% for file in prdoc | sort(attribute="doc_filename.number") -%} -{%- set author= file.content.author | default(value="n/a") -%} -{%- set topic= file.content.topic | default(value="n/a") -%} -- #{{file.doc_filename.number}}: {{ file.content.title }} (@{{ author }}) [{{ topic | capitalize }}] -{% endfor -%} diff --git a/substrate/Cargo.toml b/substrate/Cargo.toml new file mode 100644 index 00000000000..8fb1be5821b --- /dev/null +++ b/substrate/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "substrate" +description = "Next-generation framework for blockchain innovation" +license = "GPL-3.0-or-later WITH Classpath-exception-2.0" +homepage = "https://substrate.io" +repository.workspace = true +authors.workspace = true +edition.workspace = true +version = "1.0.0" +publish = false + +# The dependencies are only needed for docs. +[dependencies] +simple-mermaid = { git = "https://github.com/kianenigma/simple-mermaid.git", rev = "e48b187bcfd5cc75111acd9d241f1bd36604344b" } + +subkey = { path = "bin/utils/subkey" } +chain-spec-builder = { package = "staging-chain-spec-builder", path = "bin/utils/chain-spec-builder" } + +sc-service = { path = "client/service" } +sc-chain-spec = { path = "client/chain-spec" } +sc-cli = { path = "client/cli" } +sc-consensus-aura = { path = "client/consensus/aura" } +sc-consensus-babe = { path = "client/consensus/babe" } +sc-consensus-grandpa = { path = "client/consensus/grandpa" } +sc-consensus-beefy = { path = "client/consensus/beefy" } +sc-consensus-manual-seal = { path = "client/consensus/manual-seal" } +sc-consensus-pow = { path = "client/consensus/pow" } + +sp-runtime = { path = "primitives/runtime" } +frame-support = { path = "frame/support" } diff --git a/substrate/README.md b/substrate/README.md index f6961277262..f7afa7a894d 100644 --- a/substrate/README.md +++ b/substrate/README.md @@ -3,7 +3,7 @@ [![GitHub license](https://img.shields.io/badge/license-GPL3%2FApache2-blue)](#LICENSE) [![GitLab Status](https://gitlab.parity.io/parity/mirrors/polkadot-sdk/badges/master/pipeline.svg)](https://gitlab.parity.io/parity/mirrors/polkadot-sdk/-/pipelines) -[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](docs/contributor/CONTRIBUTING.md) +[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](docs/CONTRIBUTING.md) [![Stack Exchange](https://img.shields.io/badge/Substrate-Community%20&%20Support-24CC85?logo=stackexchange)](https://substrate.stackexchange.com/)

@@ -26,13 +26,15 @@ here](https://github.com/paritytech/polkadot-sdk/issues) for anything you suspec ## Contributions & Code of Conduct -Please follow the contributions guidelines as outlined in [`docs/contributor/CONTRIBUTING.md`](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md). -In all communications and contributions, this project follows the [Contributor Covenant Code of Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CODE_OF_CONDUCT.md). +Please follow the contributions guidelines as outlined in +[`docs/CONTRIBUTING.md`](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CONTRIBUTING.md). In all +communications and contributions, this project follows the [Contributor Covenant Code of +Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/CODE_OF_CONDUCT.md). ## Security The security policy and procedures can be found in -[`docs/contributor/SECURITY.md`](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/SECURITY.md). +[`docs/SECURITY.md`](https://github.com/paritytech/polkadot-sdk/blob/master/docs/SECURITY.md). ## License diff --git a/substrate/bin/minimal/node/Cargo.toml b/substrate/bin/minimal/node/Cargo.toml index 532cded68de..0506d0838f1 100644 --- a/substrate/bin/minimal/node/Cargo.toml +++ b/substrate/bin/minimal/node/Cargo.toml @@ -10,9 +10,6 @@ publish = false repository = "https://github.com/substrate-developer-hub/substrate-node-template/" build = "build.rs" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,16 +17,16 @@ targets = ["x86_64-unknown-linux-gnu"] name = "minimal-node" [dependencies] -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.0.9", features = ["derive"] } futures = { version = "0.3.21", features = ["thread-pool"] } futures-timer = "3.0.1" jsonrpsee = { version = "0.16.2", features = ["server"] } serde_json = "1.0.108" sc-cli = { path = "../../../client/cli" } -sc-executor = { path = "../../../client/executor" } -sc-network = { path = "../../../client/network" } -sc-service = { path = "../../../client/service" } +sc-executor = { path = "../../../client/executor" } +sc-network = { path = "../../../client/network" } +sc-service = { path = "../../../client/service" } sc-telemetry = { path = "../../../client/telemetry" } sc-transaction-pool = { path = "../../../client/transaction-pool" } sc-transaction-pool-api = { path = "../../../client/transaction-pool/api" } @@ -50,7 +47,7 @@ sp-runtime = { path = "../../../primitives/runtime" } substrate-frame-rpc-system = { path = "../../../utils/frame/rpc/system" } -frame = { path = "../../../frame", features = ["experimental", "runtime"] } +frame = { path = "../../../frame", features = ["runtime", "experimental"] } runtime = { package = "minimal-runtime", path = "../runtime" } [build-dependencies] diff --git a/substrate/bin/minimal/runtime/Cargo.toml b/substrate/bin/minimal/runtime/Cargo.toml index 296106544bb..85d56d0638a 100644 --- a/substrate/bin/minimal/runtime/Cargo.toml +++ b/substrate/bin/minimal/runtime/Cargo.toml @@ -8,16 +8,13 @@ repository.workspace = true license.workspace = true publish = false -[lints] -workspace = true - [dependencies] parity-scale-codec = { version = "3.0.0", default-features = false } scale-info = { version = "2.6.0", default-features = false } # this is a frame-based runtime, thus importing `frame` with runtime feature enabled. -frame = { path = "../../../frame", default-features = false, features = ["experimental", "runtime"] } -frame-support = { path = "../../../frame/support", default-features = false } +frame = { path = "../../../frame", default-features = false, features = ["runtime", "experimental"] } +frame-support = { path = "../../../frame/support", default-features = false} # pallets that we want to use pallet-balances = { path = "../../../frame/balances", default-features = false } @@ -27,14 +24,14 @@ pallet-transaction-payment = { path = "../../../frame/transaction-payment", defa pallet-transaction-payment-rpc-runtime-api = { path = "../../../frame/transaction-payment/rpc/runtime-api", default-features = false } # genesis builder that allows us to interacto with runtime genesis config -sp-genesis-builder = { path = "../../../primitives/genesis-builder", default-features = false } +sp-genesis-builder = { path = "../../../primitives/genesis-builder", default-features = false} [build-dependencies] substrate-wasm-builder = { path = "../../../utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "frame-support/std", "frame/std", diff --git a/substrate/bin/node-template/node/Cargo.toml b/substrate/bin/node-template/node/Cargo.toml index 9d8c4430c21..61953631d79 100644 --- a/substrate/bin/node-template/node/Cargo.toml +++ b/substrate/bin/node-template/node/Cargo.toml @@ -10,9 +10,6 @@ publish = false repository = "https://github.com/substrate-developer-hub/substrate-node-template/" build = "build.rs" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,8 +17,8 @@ targets = ["x86_64-unknown-linux-gnu"] name = "node-template" [dependencies] -clap = { version = "4.4.11", features = ["derive"] } -futures = { version = "0.3.21", features = ["thread-pool"] } +clap = { version = "4.4.6", features = ["derive"] } +futures = { version = "0.3.21", features = ["thread-pool"]} serde_json = "1.0.108" sc-cli = { path = "../../../client/cli" } @@ -45,7 +42,7 @@ sp-timestamp = { path = "../../../primitives/timestamp" } sp-inherents = { path = "../../../primitives/inherents" } sp-keyring = { path = "../../../primitives/keyring" } frame-system = { path = "../../../frame/system" } -pallet-transaction-payment = { path = "../../../frame/transaction-payment", default-features = false } +pallet-transaction-payment = { path = "../../../frame/transaction-payment", default-features = false} # These dependencies are used for the node template's RPCs jsonrpsee = { version = "0.16.2", features = ["server"] } @@ -65,7 +62,7 @@ frame-benchmarking-cli = { path = "../../../utils/frame/benchmarking-cli" } node-template-runtime = { path = "../runtime" } # CLI-specific dependencies -try-runtime-cli = { path = "../../../utils/frame/try-runtime/cli", optional = true } +try-runtime-cli = { path = "../../../utils/frame/try-runtime/cli", optional = true} [build-dependencies] substrate-build-script-utils = { path = "../../../utils/build-script-utils" } diff --git a/substrate/bin/node-template/node/src/service.rs b/substrate/bin/node-template/node/src/service.rs index c4a2b2f39d2..40320282924 100644 --- a/substrate/bin/node-template/node/src/service.rs +++ b/substrate/bin/node-template/node/src/service.rs @@ -5,17 +5,35 @@ use node_template_runtime::{self, opaque::Block, RuntimeApi}; use sc_client_api::{Backend, BlockBackend}; use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams}; use sc_consensus_grandpa::SharedVoterState; +pub use sc_executor::NativeElseWasmExecutor; use sc_service::{error::Error as ServiceError, Configuration, TaskManager, WarpSyncParams}; use sc_telemetry::{Telemetry, TelemetryWorker}; use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; use std::{sync::Arc, time::Duration}; -pub(crate) type FullClient = sc_service::TFullClient< - Block, - RuntimeApi, - sc_executor::WasmExecutor, ->; +// Our native executor instance. +pub struct ExecutorDispatch; + +impl sc_executor::NativeExecutionDispatch for ExecutorDispatch { + /// Only enable the benchmarking host functions when we actually want to benchmark. + #[cfg(feature = "runtime-benchmarks")] + type ExtendHostFunctions = frame_benchmarking::benchmarking::HostFunctions; + /// Otherwise we only use the default Substrate host functions. + #[cfg(not(feature = "runtime-benchmarks"))] + type ExtendHostFunctions = (); + + fn dispatch(method: &str, data: &[u8]) -> Option> { + node_template_runtime::api::dispatch(method, data) + } + + fn native_version() -> sc_executor::NativeVersion { + node_template_runtime::native_version() + } +} + +pub(crate) type FullClient = + sc_service::TFullClient>; type FullBackend = sc_service::TFullBackend; type FullSelectChain = sc_consensus::LongestChain; @@ -57,7 +75,7 @@ pub fn new_partial( }) .transpose()?; - let executor = sc_service::new_wasm_executor::(config); + let executor = sc_service::new_native_or_wasm_executor(config); let (client, backend, keystore_container, task_manager) = sc_service::new_full_parts::( config, @@ -145,9 +163,9 @@ pub fn new_full(config: Configuration) -> Result { &client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"), &config.chain_spec, ); - let (grandpa_protocol_config, grandpa_notification_service) = - sc_consensus_grandpa::grandpa_peers_set_config(grandpa_protocol_name.clone()); - net_config.add_notification_protocol(grandpa_protocol_config); + net_config.add_notification_protocol(sc_consensus_grandpa::grandpa_peers_set_config( + grandpa_protocol_name.clone(), + )); let warp_sync = Arc::new(sc_consensus_grandpa::warp_proof::NetworkProvider::new( backend.clone(), @@ -298,7 +316,6 @@ pub fn new_full(config: Configuration) -> Result { link: grandpa_link, network, sync: Arc::new(sync_service), - notification_service: grandpa_notification_service, voting_rule: sc_consensus_grandpa::VotingRulesBuilder::default().build(), prometheus_registry, shared_voter_state: SharedVoterState::empty(), diff --git a/substrate/bin/node-template/pallets/template/Cargo.toml b/substrate/bin/node-template/pallets/template/Cargo.toml index 51410a71c7b..77183c42cd6 100644 --- a/substrate/bin/node-template/pallets/template/Cargo.toml +++ b/substrate/bin/node-template/pallets/template/Cargo.toml @@ -9,9 +9,6 @@ license = "MIT-0" publish = false repository = "https://github.com/substrate-developer-hub/substrate-node-template/" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,10 +17,10 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = "derive", ] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../../../../frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../../frame/support", default-features = false } -frame-system = { path = "../../../../frame/system", default-features = false } -sp-std = { path = "../../../../primitives/std", default-features = false } +frame-benchmarking = { path = "../../../../frame/benchmarking", default-features = false, optional = true} +frame-support = { path = "../../../../frame/support", default-features = false} +frame-system = { path = "../../../../frame/system", default-features = false} +sp-std = { path = "../../../../primitives/std", default-features = false} [dev-dependencies] sp-core = { path = "../../../../primitives/core" } @@ -31,7 +28,7 @@ sp-io = { path = "../../../../primitives/io" } sp-runtime = { path = "../../../../primitives/runtime" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/bin/node-template/pallets/template/src/mock.rs b/substrate/bin/node-template/pallets/template/src/mock.rs index 8346461e6ed..244ae1b3785 100644 --- a/substrate/bin/node-template/pallets/template/src/mock.rs +++ b/substrate/bin/node-template/pallets/template/src/mock.rs @@ -1,8 +1,5 @@ use crate as pallet_template; -use frame_support::{ - derive_impl, - traits::{ConstU16, ConstU64}, -}; +use frame_support::traits::{ConstU16, ConstU64}; use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -20,7 +17,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/bin/node-template/runtime/Cargo.toml b/substrate/bin/node-template/runtime/Cargo.toml index 14a64948c0b..7711ddba34d 100644 --- a/substrate/bin/node-template/runtime/Cargo.toml +++ b/substrate/bin/node-template/runtime/Cargo.toml @@ -9,9 +9,6 @@ license = "MIT-0" publish = false repository = "https://github.com/substrate-developer-hub/substrate-node-template/" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,48 +16,48 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive", "serde"] } -pallet-aura = { path = "../../../frame/aura", default-features = false } -pallet-balances = { path = "../../../frame/balances", default-features = false } -frame-support = { path = "../../../frame/support", default-features = false } -pallet-grandpa = { path = "../../../frame/grandpa", default-features = false } -pallet-sudo = { path = "../../../frame/sudo", default-features = false } -frame-system = { path = "../../../frame/system", default-features = false } +pallet-aura = { path = "../../../frame/aura", default-features = false} +pallet-balances = { path = "../../../frame/balances", default-features = false} +frame-support = { path = "../../../frame/support", default-features = false} +pallet-grandpa = { path = "../../../frame/grandpa", default-features = false} +pallet-sudo = { path = "../../../frame/sudo", default-features = false} +frame-system = { path = "../../../frame/system", default-features = false} frame-try-runtime = { path = "../../../frame/try-runtime", default-features = false, optional = true } -pallet-timestamp = { path = "../../../frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../frame/transaction-payment", default-features = false } -frame-executive = { path = "../../../frame/executive", default-features = false } -sp-api = { path = "../../../primitives/api", default-features = false } -sp-block-builder = { path = "../../../primitives/block-builder", default-features = false } +pallet-timestamp = { path = "../../../frame/timestamp", default-features = false} +pallet-transaction-payment = { path = "../../../frame/transaction-payment", default-features = false} +frame-executive = { path = "../../../frame/executive", default-features = false} +sp-api = { path = "../../../primitives/api", default-features = false} +sp-block-builder = { path = "../../../primitives/block-builder", default-features = false} sp-consensus-aura = { path = "../../../primitives/consensus/aura", 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-inherents = { path = "../../../primitives/inherents", default-features = false } -sp-offchain = { path = "../../../primitives/offchain", default-features = false } +sp-core = { path = "../../../primitives/core", default-features = false, features = ["serde"]} +sp-inherents = { path = "../../../primitives/inherents", default-features = false} +sp-offchain = { path = "../../../primitives/offchain", default-features = false} sp-runtime = { path = "../../../primitives/runtime", default-features = false, features = ["serde"] } -sp-session = { path = "../../../primitives/session", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } -sp-storage = { path = "../../../primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../primitives/transaction-pool", default-features = false } +sp-session = { path = "../../../primitives/session", default-features = false} +sp-std = { path = "../../../primitives/std", default-features = false} +sp-storage = { path = "../../../primitives/storage", default-features = false} +sp-transaction-pool = { path = "../../../primitives/transaction-pool", default-features = false} sp-version = { path = "../../../primitives/version", default-features = false, features = ["serde"] } serde_json = { version = "1.0.108", default-features = false, features = ["alloc"] } sp-genesis-builder = { default-features = false, path = "../../../primitives/genesis-builder" } # Used for the node template's RPCs -frame-system-rpc-runtime-api = { path = "../../../frame/system/rpc/runtime-api", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../frame/transaction-payment/rpc/runtime-api", default-features = false } +frame-system-rpc-runtime-api = { path = "../../../frame/system/rpc/runtime-api", default-features = false} +pallet-transaction-payment-rpc-runtime-api = { path = "../../../frame/transaction-payment/rpc/runtime-api", default-features = false} # Used for runtime benchmarking frame-benchmarking = { path = "../../../frame/benchmarking", default-features = false, optional = true } frame-system-benchmarking = { path = "../../../frame/system/benchmarking", default-features = false, optional = true } # Local Dependencies -pallet-template = { path = "../pallets/template", default-features = false } +pallet-template = { path = "../pallets/template", default-features = false} [build-dependencies] substrate-wasm-builder = { path = "../../../utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", @@ -122,4 +119,4 @@ try-runtime = [ "pallet-transaction-payment/try-runtime", "sp-runtime/try-runtime", ] -experimental = ["pallet-aura/experimental"] +experimental = [ "pallet-aura/experimental" ] diff --git a/substrate/bin/node-template/runtime/src/lib.rs b/substrate/bin/node-template/runtime/src/lib.rs index 37150c581d2..44f63a822bd 100644 --- a/substrate/bin/node-template/runtime/src/lib.rs +++ b/substrate/bin/node-template/runtime/src/lib.rs @@ -12,7 +12,9 @@ use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, - traits::{BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, One, Verify}, + traits::{ + AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, One, Verify, + }, transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, MultiSignature, }; @@ -24,7 +26,7 @@ use sp_version::RuntimeVersion; use frame_support::genesis_builder_helper::{build_config, create_default_config}; // A few exports that help ease life for downstream crates. pub use frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, parameter_types, traits::{ ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, KeyOwnerProofSystem, Randomness, StorageInfo, @@ -149,11 +151,11 @@ parameter_types! { pub const SS58Prefix: u8 = 42; } -/// The default types are being injected by [`derive_impl`](`frame_support::derive_impl`) from -/// [`SoloChainDefaultConfig`](`struct@frame_system::config_preludes::SolochainDefaultConfig`), -/// but overridden as needed. -#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig as frame_system::DefaultConfig)] +// Configure FRAME pallets to include in runtime. + impl frame_system::Config for Runtime { + /// The basic call filter to use in dispatchable. + type BaseCallFilter = frame_support::traits::Everything; /// The block type for the runtime. type Block = Block; /// Block & extrinsics weights: base values and limits. @@ -162,20 +164,42 @@ impl frame_system::Config for Runtime { type BlockLength = BlockLength; /// The identifier used to distinguish between accounts. type AccountId = AccountId; + /// The aggregated dispatch type that is available for extrinsics. + type RuntimeCall = RuntimeCall; + /// The lookup mechanism to get account ID from whatever is passed in dispatchers. + type Lookup = AccountIdLookup; /// The type for storing how many extrinsics an account has signed. type Nonce = Nonce; /// The type for hashing blocks and tries. type Hash = Hash; + /// The hashing algorithm used. + type Hashing = BlakeTwo256; + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + /// The ubiquitous origin type. + type RuntimeOrigin = RuntimeOrigin; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). type BlockHashCount = BlockHashCount; /// The weight of database operations that the runtime can invoke. type DbWeight = RocksDbWeight; /// Version of the runtime. type Version = Version; + /// Converts a module to the index of the module in `construct_runtime!`. + /// + /// This type is being generated by `construct_runtime!`. + type PalletInfo = PalletInfo; + /// What to do if a new account is created. + type OnNewAccount = (); + /// What to do if an account is fully reaped from the system. + type OnKilledAccount = (); /// The data to be stored in an account. type AccountData = pallet_balances::AccountData; + /// Weight information for the extrinsics of this pallet. + type SystemWeightInfo = (); /// This is used as an identifier of the chain. 42 is the generic substrate prefix. type SS58Prefix = SS58Prefix; + /// The set code logic, just the default since we're not a parachain. + type OnSetCode = (); type MaxConsumers = frame_support::traits::ConstU32<16>; } diff --git a/substrate/bin/node-template/rust-toolchain.toml b/substrate/bin/node-template/rust-toolchain.toml index 2a35c6ed07c..64daeff6836 100644 --- a/substrate/bin/node-template/rust-toolchain.toml +++ b/substrate/bin/node-template/rust-toolchain.toml @@ -6,9 +6,9 @@ components = [ "rust-analyzer", "rust-src", "rust-std", - "rustc", "rustc-dev", + "rustc", "rustfmt", ] -targets = ["wasm32-unknown-unknown"] +targets = [ "wasm32-unknown-unknown" ] profile = "minimal" diff --git a/substrate/bin/node/bench/Cargo.toml b/substrate/bin/node/bench/Cargo.toml index 48b3ef1b67e..ee429ee8c0c 100644 --- a/substrate/bin/node/bench/Cargo.toml +++ b/substrate/bin/node/bench/Cargo.toml @@ -9,14 +9,11 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] array-bytes = "6.1" -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } log = "0.4.17" node-primitives = { path = "../primitives" } node-testing = { path = "../testing" } @@ -24,7 +21,7 @@ kitchensink-runtime = { path = "../runtime" } sc-client-api = { path = "../../../client/api" } sp-runtime = { path = "../../../primitives/runtime" } sp-state-machine = { path = "../../../primitives/state-machine" } -serde = "1.0.193" +serde = "1.0.188" serde_json = "1.0.108" derive_more = { version = "0.99.17", default-features = false, features = ["display"] } kvdb = "0.13.0" @@ -34,14 +31,14 @@ 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-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" +parity-db = "0.4.8" sc-transaction-pool = { path = "../../../client/transaction-pool" } sc-transaction-pool-api = { path = "../../../client/transaction-pool/api" } futures = { version = "0.3.21", features = ["thread-pool"] } diff --git a/substrate/bin/node/cli/Cargo.toml b/substrate/bin/node/cli/Cargo.toml index 4f78bd65e8f..8f3c2185deb 100644 --- a/substrate/bin/node/cli/Cargo.toml +++ b/substrate/bin/node/cli/Cargo.toml @@ -11,9 +11,6 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.wasm-pack.profile.release] # `wasm-opt` has some problems on linux, see # https://github.com/rustwasm/wasm-pack/issues/781 etc. @@ -41,9 +38,9 @@ crate-type = ["cdylib", "rlib"] [dependencies] # third-party dependencies array-bytes = "6.1" -clap = { version = "4.4.11", features = ["derive"], optional = true } +clap = { version = "4.4.6", features = ["derive"], optional = true } codec = { package = "parity-scale-codec", version = "3.6.1" } -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } jsonrpsee = { version = "0.16.2", features = ["server"] } futures = "0.3.21" log = "0.4.17" @@ -82,7 +79,7 @@ sc-consensus-babe = { path = "../../../client/consensus/babe" } grandpa = { package = "sc-consensus-grandpa", path = "../../../client/consensus/grandpa" } sc-rpc = { path = "../../../client/rpc" } sc-basic-authorship = { path = "../../../client/basic-authorship" } -sc-service = { path = "../../../client/service", default-features = false } +sc-service = { path = "../../../client/service", default-features = false} sc-telemetry = { path = "../../../client/telemetry" } sc-executor = { path = "../../../client/executor" } sc-authority-discovery = { path = "../../../client/authority-discovery" } @@ -93,25 +90,25 @@ sc-storage-monitor = { path = "../../../client/storage-monitor" } sc-offchain = { path = "../../../client/offchain" } # frame dependencies -frame-benchmarking = { path = "../../../frame/benchmarking" } frame-system = { path = "../../../frame/system" } frame-system-rpc-runtime-api = { path = "../../../frame/system/rpc/runtime-api" } 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-im-online = { path = "../../../frame/im-online", default-features = false } -pallet-skip-feeless-payment = { path = "../../../frame/transaction-payment/skip-feeless-payment", default-features = false } +pallet-im-online = { path = "../../../frame/im-online", default-features = false} +pallet-skip-feeless-payment = { path = "../../../frame/transaction-payment/skip-feeless-payment", default-features = false} # node-specific dependencies kitchensink-runtime = { path = "../runtime" } node-rpc = { path = "../rpc" } node-primitives = { path = "../primitives" } +node-executor = { package = "staging-node-executor", path = "../executor" } # CLI-specific dependencies -sc-cli = { path = "../../../client/cli", optional = true } -frame-benchmarking-cli = { path = "../../../utils/frame/benchmarking-cli", optional = true } -node-inspect = { package = "staging-node-inspect", path = "../inspect", optional = true } -try-runtime-cli = { path = "../../../utils/frame/try-runtime/cli", optional = true } +sc-cli = { path = "../../../client/cli", optional = true} +frame-benchmarking-cli = { path = "../../../utils/frame/benchmarking-cli", optional = true} +node-inspect = { package = "staging-node-inspect", path = "../inspect", optional = true} +try-runtime-cli = { path = "../../../utils/frame/try-runtime/cli", optional = true} serde_json = "1.0.108" [dev-dependencies] @@ -132,47 +129,27 @@ regex = "1.6.0" platforms = "3.0" soketto = "0.7.1" criterion = { version = "0.4.0", features = ["async_tokio"] } -tokio = { version = "1.22.0", features = ["macros", "parking_lot", "time"] } +tokio = { version = "1.22.0", features = ["macros", "time", "parking_lot"] } tokio-util = { version = "0.7.4", features = ["compat"] } wait-timeout = "0.2" substrate-rpc-client = { path = "../../../utils/frame/rpc/client" } pallet-timestamp = { path = "../../../frame/timestamp" } substrate-cli-test-utils = { path = "../../../test-utils/cli" } -wat = "1.0" -frame-support = { path = "../../../frame/support" } -node-testing = { path = "../testing" } -pallet-balances = { path = "../../../frame/balances" } -pallet-contracts = { path = "../../../frame/contracts" } -pallet-glutton = { path = "../../../frame/glutton" } -pallet-sudo = { path = "../../../frame/sudo" } -pallet-treasury = { path = "../../../frame/treasury" } -pallet-transaction-payment = { path = "../../../frame/transaction-payment" } -sp-application-crypto = { path = "../../../primitives/application-crypto" } -pallet-root-testing = { path = "../../../frame/root-testing" } -sp-consensus-babe = { path = "../../../primitives/consensus/babe" } -sp-externalities = { path = "../../../primitives/externalities" } -sp-keyring = { path = "../../../primitives/keyring" } -sp-runtime = { path = "../../../primitives/runtime" } -serde_json = "1.0.108" -scale-info = { version = "2.10.0", features = ["derive", "serde"] } -sp-trie = { path = "../../../primitives/trie" } -sp-state-machine = { path = "../../../primitives/state-machine" } - [build-dependencies] -clap = { version = "4.4.11", optional = true } +clap = { version = "4.4.6", optional = true } clap_complete = { version = "4.0.2", optional = true } -node-inspect = { package = "staging-node-inspect", path = "../inspect", optional = true } -frame-benchmarking-cli = { path = "../../../utils/frame/benchmarking-cli", optional = true } -substrate-build-script-utils = { path = "../../../utils/build-script-utils", optional = true } -substrate-frame-cli = { path = "../../../utils/frame/frame-utilities-cli", optional = true } -try-runtime-cli = { path = "../../../utils/frame/try-runtime/cli", optional = true } +node-inspect = { package = "staging-node-inspect", path = "../inspect", optional = true} +frame-benchmarking-cli = { path = "../../../utils/frame/benchmarking-cli", optional = true} +substrate-build-script-utils = { path = "../../../utils/build-script-utils", optional = true} +substrate-frame-cli = { path = "../../../utils/frame/frame-utilities-cli", optional = true} +try-runtime-cli = { path = "../../../utils/frame/try-runtime/cli", optional = true} sc-cli = { path = "../../../client/cli", optional = true } pallet-balances = { path = "../../../frame/balances" } sc-storage-monitor = { path = "../../../client/storage-monitor" } [features] -default = ["cli"] +default = [ "cli" ] cli = [ "clap", "clap_complete", @@ -186,21 +163,14 @@ cli = [ ] runtime-benchmarks = [ "frame-benchmarking-cli/runtime-benchmarks", - "frame-benchmarking/runtime-benchmarks", - "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "kitchensink-runtime/runtime-benchmarks", - "node-inspect?/runtime-benchmarks", "pallet-asset-tx-payment/runtime-benchmarks", "pallet-assets/runtime-benchmarks", "pallet-balances/runtime-benchmarks", - "pallet-contracts/runtime-benchmarks", - "pallet-glutton/runtime-benchmarks", "pallet-im-online/runtime-benchmarks", "pallet-skip-feeless-payment/runtime-benchmarks", - "pallet-sudo/runtime-benchmarks", "pallet-timestamp/runtime-benchmarks", - "pallet-treasury/runtime-benchmarks", "sc-client-db/runtime-benchmarks", "sc-service/runtime-benchmarks", "sp-runtime/runtime-benchmarks", @@ -208,22 +178,15 @@ runtime-benchmarks = [ # Enable features that allow the runtime to be tried and debugged. Name might be subject to change # in the near future. try-runtime = [ - "frame-support/try-runtime", "frame-system/try-runtime", "kitchensink-runtime/try-runtime", "pallet-asset-conversion-tx-payment/try-runtime", "pallet-asset-tx-payment/try-runtime", "pallet-assets/try-runtime", "pallet-balances/try-runtime", - "pallet-contracts/try-runtime", - "pallet-glutton/try-runtime", "pallet-im-online/try-runtime", - "pallet-root-testing/try-runtime", "pallet-skip-feeless-payment/try-runtime", - "pallet-sudo/try-runtime", "pallet-timestamp/try-runtime", - "pallet-transaction-payment/try-runtime", - "pallet-treasury/try-runtime", "sp-runtime/try-runtime", "substrate-cli-test-utils/try-runtime", "try-runtime-cli/try-runtime", @@ -236,7 +199,3 @@ harness = false [[bench]] name = "block_production" harness = false - -[[bench]] -name = "executor" -harness = false diff --git a/substrate/bin/node/cli/src/command.rs b/substrate/bin/node/cli/src/command.rs index dc28705c2ae..16d0415ff26 100644 --- a/substrate/bin/node/cli/src/command.rs +++ b/substrate/bin/node/cli/src/command.rs @@ -24,6 +24,7 @@ use crate::{ }; use frame_benchmarking_cli::*; use kitchensink_runtime::{ExistentialDeposit, RuntimeApi}; +use node_executor::ExecutorDispatch; use node_primitives::Block; use sc_cli::{Result, SubstrateCli}; use sc_service::PartialComponents; @@ -88,7 +89,7 @@ pub fn run() -> Result<()> { Some(Subcommand::Inspect(cmd)) => { let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run::(config)) + runner.sync_run(|config| cmd.run::(config)) }, Some(Subcommand::Benchmark(cmd)) => { let runner = cli.create_runner(cmd)?; diff --git a/substrate/bin/node/cli/src/service.rs b/substrate/bin/node/cli/src/service.rs index fb5ccf2a969..6fb1734b556 100644 --- a/substrate/bin/node/cli/src/service.rs +++ b/substrate/bin/node/cli/src/service.rs @@ -26,9 +26,11 @@ use frame_benchmarking_cli::SUBSTRATE_REFERENCE_HARDWARE; use frame_system_rpc_runtime_api::AccountNonceApi; use futures::prelude::*; use kitchensink_runtime::RuntimeApi; +use node_executor::ExecutorDispatch; use node_primitives::Block; use sc_client_api::{Backend, BlockBackend}; use sc_consensus_babe::{self, SlotProportion}; +use sc_executor::NativeElseWasmExecutor; use sc_network::{event::Event, NetworkEventStream, NetworkService}; use sc_network_sync::{warp::WarpSyncParams, SyncingService}; use sc_service::{config::Configuration, error::Error as ServiceError, RpcHandlers, TaskManager}; @@ -40,25 +42,9 @@ use sp_core::crypto::Pair; use sp_runtime::{generic, traits::Block as BlockT, SaturatedConversion}; use std::sync::Arc; -/// Host functions required for kitchensink runtime and Substrate node. -#[cfg(not(feature = "runtime-benchmarks"))] -pub type HostFunctions = - (sp_io::SubstrateHostFunctions, sp_statement_store::runtime_api::HostFunctions); - -/// Host functions required for kitchensink runtime and Substrate node. -#[cfg(feature = "runtime-benchmarks")] -pub type HostFunctions = ( - sp_io::SubstrateHostFunctions, - sp_statement_store::runtime_api::HostFunctions, - frame_benchmarking::benchmarking::HostFunctions, -); - -/// A specialized `WasmExecutor` intended to use accross substrate node. It provides all required -/// HostFunctions. -pub type RuntimeExecutor = sc_executor::WasmExecutor; - /// The full client type definition. -pub type FullClient = sc_service::TFullClient; +pub type FullClient = + sc_service::TFullClient>; type FullBackend = sc_service::TFullBackend; type FullSelectChain = sc_consensus::LongestChain; type FullGrandpaBlockImport = @@ -193,7 +179,7 @@ pub fn new_partial( }) .transpose()?; - let executor = sc_service::new_wasm_executor(&config); + let executor = sc_service::new_native_or_wasm_executor(&config); let (client, backend, keystore_container, task_manager) = sc_service::new_full_parts::( @@ -389,28 +375,28 @@ pub fn new_full_base( let shared_voter_state = rpc_setup; let auth_disc_publish_non_global_ips = config.network.allow_non_globals_in_dht; let mut net_config = sc_network::config::FullNetworkConfiguration::new(&config.network); + let genesis_hash = client.block_hash(0).ok().flatten().expect("Genesis block exists; qed"); let grandpa_protocol_name = grandpa::protocol_standard_name(&genesis_hash, &config.chain_spec); - let (grandpa_protocol_config, grandpa_notification_service) = - grandpa::grandpa_peers_set_config(grandpa_protocol_name.clone()); - net_config.add_notification_protocol(grandpa_protocol_config); - - let (statement_handler_proto, statement_config) = - sc_network_statement::StatementHandlerPrototype::new( - genesis_hash, - config.chain_spec.fork_id(), - ); - net_config.add_notification_protocol(statement_config); + net_config.add_notification_protocol(grandpa::grandpa_peers_set_config( + grandpa_protocol_name.clone(), + )); + + let statement_handler_proto = sc_network_statement::StatementHandlerPrototype::new( + genesis_hash, + config.chain_spec.fork_id(), + ); + net_config.add_notification_protocol(statement_handler_proto.set_config()); let mixnet_protocol_name = sc_mixnet::protocol_name(genesis_hash.as_ref(), config.chain_spec.fork_id()); - let mixnet_notification_service = mixnet_config.as_ref().map(|mixnet_config| { - let (config, notification_service) = - sc_mixnet::peers_set_config(mixnet_protocol_name.clone(), mixnet_config); - net_config.add_notification_protocol(config); - notification_service - }); + if let Some(mixnet_config) = &mixnet_config { + net_config.add_notification_protocol(sc_mixnet::peers_set_config( + mixnet_protocol_name.clone(), + mixnet_config, + )); + } let warp_sync = Arc::new(grandpa::warp_proof::NetworkProvider::new( backend.clone(), @@ -441,8 +427,6 @@ pub fn new_full_base( mixnet_protocol_name, transaction_pool.clone(), Some(keystore_container.keystore()), - mixnet_notification_service - .expect("`NotificationService` exists since mixnet was enabled; qed"), ); task_manager.spawn_handle().spawn("mixnet", None, mixnet); } @@ -611,7 +595,6 @@ pub fn new_full_base( link: grandpa_link, network: network.clone(), sync: Arc::new(sync_service.clone()), - notification_service: grandpa_notification_service, telemetry: telemetry.as_ref().map(|x| x.handle()), voting_rule: grandpa::VotingRulesBuilder::default().build(), prometheus_registry: prometheus_registry.clone(), diff --git a/substrate/bin/node/cli/tests/websocket_server.rs b/substrate/bin/node/cli/tests/websocket_server.rs index b34fc82b8be..432a4871cd3 100644 --- a/substrate/bin/node/cli/tests/websocket_server.rs +++ b/substrate/bin/node/cli/tests/websocket_server.rs @@ -205,7 +205,8 @@ impl WsServer { Ok(soketto::Data::Text(len)) => String::from_utf8(buf[..len].to_vec()) .map(Message::Text) .map_err(|err| Box::new(err) as Box<_>), - Ok(soketto::Data::Binary(len)) => Ok(Message::Binary(buf[..len].to_vec())), + Ok(soketto::Data::Binary(len)) => Ok(buf[..len].to_vec()) + .map(Message::Binary), Err(err) => Err(Box::new(err) as Box<_>), }; Some((ret, (receiver, buf))) diff --git a/substrate/bin/node/executor/Cargo.toml b/substrate/bin/node/executor/Cargo.toml new file mode 100644 index 00000000000..595a313d2cb --- /dev/null +++ b/substrate/bin/node/executor/Cargo.toml @@ -0,0 +1,57 @@ +[package] +name = "staging-node-executor" +version = "3.0.0-dev" +authors.workspace = true +description = "Substrate node implementation in Rust." +edition.workspace = true +license = "Apache-2.0" +homepage = "https://substrate.io" +repository.workspace = true +publish = false + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +codec = { package = "parity-scale-codec", version = "3.6.1" } +scale-info = { version = "2.10.0", features = ["derive", "serde"] } +frame-benchmarking = { path = "../../../frame/benchmarking" } +node-primitives = { path = "../primitives" } +kitchensink-runtime = { path = "../runtime" } +sc-executor = { path = "../../../client/executor" } +sp-core = { path = "../../../primitives/core", features=["serde"] } +sp-keystore = { path = "../../../primitives/keystore" } +sp-state-machine = { path = "../../../primitives/state-machine" } +sp-tracing = { path = "../../../primitives/tracing" } +sp-trie = { path = "../../../primitives/trie" } +sp-statement-store = { path = "../../../primitives/statement-store", features=["serde"] } + +[dev-dependencies] +criterion = "0.4.0" +futures = "0.3.21" +wat = "1.0" +frame-support = { path = "../../../frame/support" } +frame-system = { path = "../../../frame/system" } +node-testing = { path = "../testing" } +pallet-balances = { path = "../../../frame/balances" } +pallet-contracts = { path = "../../../frame/contracts" } +pallet-im-online = { path = "../../../frame/im-online" } +pallet-glutton = { path = "../../../frame/glutton" } +pallet-sudo = { path = "../../../frame/sudo" } +pallet-timestamp = { path = "../../../frame/timestamp" } +pallet-treasury = { path = "../../../frame/treasury" } +pallet-transaction-payment = { path = "../../../frame/transaction-payment" } +sp-application-crypto = { path = "../../../primitives/application-crypto" } +pallet-root-testing = { path = "../../../frame/root-testing" } +sp-consensus-babe = { path = "../../../primitives/consensus/babe" } +sp-externalities = { path = "../../../primitives/externalities" } +sp-keyring = { path = "../../../primitives/keyring" } +sp-runtime = { path = "../../../primitives/runtime" } +serde_json = "1.0.108" + +[features] +stress-test = [] + +[[bench]] +name = "bench" +harness = false diff --git a/substrate/bin/node/cli/benches/executor.rs b/substrate/bin/node/executor/benches/bench.rs similarity index 69% rename from substrate/bin/node/cli/benches/executor.rs rename to substrate/bin/node/executor/benches/bench.rs index e13d34f9657..c5ad19ffa37 100644 --- a/substrate/bin/node/cli/benches/executor.rs +++ b/substrate/bin/node/executor/benches/bench.rs @@ -22,16 +22,20 @@ use kitchensink_runtime::{ constants::currency::*, Block, BuildStorage, CheckedExtrinsic, Header, RuntimeCall, RuntimeGenesisConfig, UncheckedExtrinsic, }; +use node_executor::ExecutorDispatch; use node_primitives::{BlockNumber, Hash}; use node_testing::keyring::*; -use sc_executor::{Externalities, RuntimeVersionOf}; +use sc_executor::{ + Externalities, NativeElseWasmExecutor, RuntimeVersionOf, WasmExecutionMethod, WasmExecutor, + WasmtimeInstantiationStrategy, +}; use sp_core::{ storage::well_known_keys, traits::{CallContext, CodeExecutor, RuntimeCode}, }; use sp_runtime::{generic::ExtrinsicFormat, traits::BlakeTwo256}; use sp_state_machine::TestExternalities as CoreTestExternalities; -use staging_node_cli::service::RuntimeExecutor; +use staging_node_executor as node_executor; criterion_group!(benches, bench_execute_block); criterion_main!(benches); @@ -54,6 +58,12 @@ const HEAP_PAGES: u64 = 20; type TestExternalities = CoreTestExternalities; +#[derive(Debug)] +enum ExecutionMethod { + Native, + Wasm(WasmExecutionMethod), +} + fn sign(xt: CheckedExtrinsic) -> UncheckedExtrinsic { node_testing::keyring::sign(xt, SPEC_VERSION, TRANSACTION_VERSION, GENESIS_HASH) } @@ -70,7 +80,7 @@ fn new_test_ext(genesis_config: &RuntimeGenesisConfig) -> TestExternalities( - executor: &RuntimeExecutor, + executor: &NativeElseWasmExecutor, ext: &mut E, number: BlockNumber, parent_hash: Hash, @@ -103,7 +113,14 @@ fn construct_block( // execute the block to get the real header. executor - .call(ext, &runtime_code, "Core_initialize_block", &header.encode(), CallContext::Offchain) + .call( + ext, + &runtime_code, + "Core_initialize_block", + &header.encode(), + true, + CallContext::Offchain, + ) .0 .unwrap(); @@ -114,6 +131,7 @@ fn construct_block( &runtime_code, "BlockBuilder_apply_extrinsic", &i.encode(), + true, CallContext::Offchain, ) .0 @@ -127,6 +145,7 @@ fn construct_block( &runtime_code, "BlockBuilder_finalize_block", &[0u8; 0], + true, CallContext::Offchain, ) .0 @@ -140,7 +159,7 @@ fn construct_block( fn test_blocks( genesis_config: &RuntimeGenesisConfig, - executor: &RuntimeExecutor, + executor: &NativeElseWasmExecutor, ) -> Vec<(Vec, Hash)> { let mut test_ext = new_test_ext(genesis_config); let mut block1_extrinsics = vec![CheckedExtrinsic { @@ -162,42 +181,56 @@ fn test_blocks( fn bench_execute_block(c: &mut Criterion) { let mut group = c.benchmark_group("execute blocks"); - - group.bench_function("wasm", |b| { - let genesis_config = node_testing::genesis::config(); - - let executor = RuntimeExecutor::builder().build(); - let runtime_code = RuntimeCode { - code_fetcher: &sp_core::traits::WrappedRuntimeCode(compact_code_unwrap().into()), - hash: vec![1, 2, 3], - heap_pages: None, - }; - - // Get the runtime version to initialize the runtimes cache. - { - let mut test_ext = new_test_ext(&genesis_config); - executor.runtime_version(&mut test_ext.ext(), &runtime_code).unwrap(); - } - - let blocks = test_blocks(&genesis_config, &executor); - - b.iter_batched_ref( - || new_test_ext(&genesis_config), - |test_ext| { - for block in blocks.iter() { - executor - .call( - &mut test_ext.ext(), - &runtime_code, - "Core_execute_block", - &block.0, - CallContext::Offchain, - ) - .0 - .unwrap(); - } - }, - BatchSize::LargeInput, - ); - }); + let execution_methods = vec![ + ExecutionMethod::Native, + ExecutionMethod::Wasm(WasmExecutionMethod::Compiled { + instantiation_strategy: WasmtimeInstantiationStrategy::PoolingCopyOnWrite, + }), + ]; + + for strategy in execution_methods { + group.bench_function(format!("{:?}", strategy), |b| { + let genesis_config = node_testing::genesis::config(); + let use_native = match strategy { + ExecutionMethod::Native => true, + ExecutionMethod::Wasm(..) => false, + }; + + let executor = + NativeElseWasmExecutor::new_with_wasm_executor(WasmExecutor::builder().build()); + let runtime_code = RuntimeCode { + code_fetcher: &sp_core::traits::WrappedRuntimeCode(compact_code_unwrap().into()), + hash: vec![1, 2, 3], + heap_pages: None, + }; + + // Get the runtime version to initialize the runtimes cache. + { + let mut test_ext = new_test_ext(&genesis_config); + executor.runtime_version(&mut test_ext.ext(), &runtime_code).unwrap(); + } + + let blocks = test_blocks(&genesis_config, &executor); + + b.iter_batched_ref( + || new_test_ext(&genesis_config), + |test_ext| { + for block in blocks.iter() { + executor + .call( + &mut test_ext.ext(), + &runtime_code, + "Core_execute_block", + &block.0, + use_native, + CallContext::Offchain, + ) + .0 + .unwrap(); + } + }, + BatchSize::LargeInput, + ); + }); + } } diff --git a/substrate/bin/node/executor/src/lib.rs b/substrate/bin/node/executor/src/lib.rs new file mode 100644 index 00000000000..3557a16740b --- /dev/null +++ b/substrate/bin/node/executor/src/lib.rs @@ -0,0 +1,40 @@ +// 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. + +//! A `CodeExecutor` specialization which uses natively compiled runtime when the wasm to be +//! executed is equivalent to the natively compiled code. + +pub use sc_executor::NativeElseWasmExecutor; + +// Declare an instance of the native executor named `ExecutorDispatch`. Include the wasm binary as +// the equivalent wasm code. +pub struct ExecutorDispatch; + +impl sc_executor::NativeExecutionDispatch for ExecutorDispatch { + type ExtendHostFunctions = ( + frame_benchmarking::benchmarking::HostFunctions, + sp_statement_store::runtime_api::HostFunctions, + ); + + fn dispatch(method: &str, data: &[u8]) -> Option> { + kitchensink_runtime::api::dispatch(method, data) + } + + fn native_version() -> sc_executor::NativeVersion { + kitchensink_runtime::native_version() + } +} diff --git a/substrate/bin/node/cli/tests/basic.rs b/substrate/bin/node/executor/tests/basic.rs similarity index 94% rename from substrate/bin/node/cli/tests/basic.rs rename to substrate/bin/node/executor/tests/basic.rs index 1966a678607..d8f9c6e7b72 100644 --- a/substrate/bin/node/cli/tests/basic.rs +++ b/substrate/bin/node/executor/tests/basic.rs @@ -193,9 +193,11 @@ fn panic_execution_with_foreign_code_gives_error() { t.insert(>::hashed_key().to_vec(), 69_u128.encode()); t.insert(>::hashed_key_for(0), vec![0u8; 32]); - let r = executor_call(&mut t, "Core_initialize_block", &vec![].and(&from_block_number(1u32))).0; + let r = + executor_call(&mut t, "Core_initialize_block", &vec![].and(&from_block_number(1u32)), true) + .0; assert!(r.is_ok()); - let v = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt())) + let v = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt()), true) .0 .unwrap(); let r = ApplyExtrinsicResult::decode(&mut &v[..]).unwrap(); @@ -217,9 +219,11 @@ fn bad_extrinsic_with_native_equivalent_code_gives_error() { t.insert(>::hashed_key().to_vec(), 69u128.encode()); t.insert(>::hashed_key_for(0), vec![0u8; 32]); - let r = executor_call(&mut t, "Core_initialize_block", &vec![].and(&from_block_number(1u32))).0; + let r = + executor_call(&mut t, "Core_initialize_block", &vec![].and(&from_block_number(1u32)), true) + .0; assert!(r.is_ok()); - let v = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt())) + let v = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt()), true) .0 .unwrap(); let r = ApplyExtrinsicResult::decode(&mut &v[..]).unwrap(); @@ -252,12 +256,14 @@ fn successful_execution_with_native_equivalent_code_gives_ok() { ); t.insert(>::hashed_key_for(0), vec![0u8; 32]); - let r = executor_call(&mut t, "Core_initialize_block", &vec![].and(&from_block_number(1u32))).0; + let r = + executor_call(&mut t, "Core_initialize_block", &vec![].and(&from_block_number(1u32)), true) + .0; assert!(r.is_ok()); let fees = t.execute_with(|| transfer_fee(&xt())); - let r = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt())).0; + let r = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt()), true).0; assert!(r.is_ok()); t.execute_with(|| { @@ -292,12 +298,14 @@ fn successful_execution_with_foreign_code_gives_ok() { ); t.insert(>::hashed_key_for(0), vec![0u8; 32]); - let r = executor_call(&mut t, "Core_initialize_block", &vec![].and(&from_block_number(1u32))).0; + let r = + executor_call(&mut t, "Core_initialize_block", &vec![].and(&from_block_number(1u32)), true) + .0; assert!(r.is_ok()); let fees = t.execute_with(|| transfer_fee(&xt())); - let r = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt())).0; + let r = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt()), true).0; assert!(r.is_ok()); t.execute_with(|| { @@ -329,7 +337,7 @@ fn full_native_block_import_works() { .base_extrinsic, ); - executor_call(&mut t, "Core_execute_block", &block1.0).0.unwrap(); + executor_call(&mut t, "Core_execute_block", &block1.0, true).0.unwrap(); t.execute_with(|| { assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - fees); @@ -404,7 +412,7 @@ fn full_native_block_import_works() { fees = t.execute_with(|| transfer_fee(&xt())); let pot = t.execute_with(|| Treasury::pot()); - executor_call(&mut t, "Core_execute_block", &block2.0).0.unwrap(); + executor_call(&mut t, "Core_execute_block", &block2.0, true).0.unwrap(); t.execute_with(|| { assert_eq!( @@ -546,7 +554,7 @@ fn full_wasm_block_import_works() { let mut alice_last_known_balance: Balance = Default::default(); let mut fees = t.execute_with(|| transfer_fee(&xt())); - executor_call(&mut t, "Core_execute_block", &block1.0).0.unwrap(); + executor_call(&mut t, "Core_execute_block", &block1.0, false).0.unwrap(); t.execute_with(|| { assert_eq!(Balances::total_balance(&alice()), 42 * DOLLARS - fees); @@ -556,7 +564,7 @@ fn full_wasm_block_import_works() { fees = t.execute_with(|| transfer_fee(&xt())); - executor_call(&mut t, "Core_execute_block", &block2.0).0.unwrap(); + executor_call(&mut t, "Core_execute_block", &block2.0, false).0.unwrap(); t.execute_with(|| { assert_eq!( @@ -709,7 +717,7 @@ fn deploying_wasm_contract_should_work() { let mut t = new_test_ext(compact_code_unwrap()); - executor_call(&mut t, "Core_execute_block", &b.0).0.unwrap(); + executor_call(&mut t, "Core_execute_block", &b.0, false).0.unwrap(); t.execute_with(|| { // Verify that the contract does exist by querying some of its storage items @@ -724,7 +732,8 @@ fn wasm_big_block_import_fails() { set_heap_pages(&mut t.ext(), 4); - let result = executor_call(&mut t, "Core_execute_block", &block_with_size(42, 0, 120_000).0).0; + let result = + executor_call(&mut t, "Core_execute_block", &block_with_size(42, 0, 120_000).0, false).0; assert!(result.is_err()); // Err(Wasmi(Trap(Trap { kind: Host(AllocatorOutOfSpace) }))) } @@ -732,7 +741,7 @@ fn wasm_big_block_import_fails() { fn native_big_block_import_succeeds() { let mut t = new_test_ext(compact_code_unwrap()); - executor_call(&mut t, "Core_execute_block", &block_with_size(42, 0, 120_000).0) + executor_call(&mut t, "Core_execute_block", &block_with_size(42, 0, 120_000).0, true) .0 .unwrap(); } @@ -745,9 +754,11 @@ fn native_big_block_import_fails_on_fallback() { // block. set_heap_pages(&mut t.ext(), 8); - assert!(executor_call(&mut t, "Core_execute_block", &block_with_size(42, 0, 120_000).0) - .0 - .is_err()); + assert!( + executor_call(&mut t, "Core_execute_block", &block_with_size(42, 0, 120_000).0, false,) + .0 + .is_err() + ); } #[test] @@ -764,9 +775,15 @@ fn panic_execution_gives_error() { t.insert(>::hashed_key().to_vec(), 0_u128.encode()); t.insert(>::hashed_key_for(0), vec![0u8; 32]); - let r = executor_call(&mut t, "Core_initialize_block", &vec![].and(&from_block_number(1u32))).0; + let r = executor_call( + &mut t, + "Core_initialize_block", + &vec![].and(&from_block_number(1u32)), + false, + ) + .0; assert!(r.is_ok()); - let r = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt())) + let r = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt()), false) .0 .unwrap(); let r = ApplyExtrinsicResult::decode(&mut &r[..]).unwrap(); @@ -799,7 +816,13 @@ fn successful_execution_gives_ok() { ); t.insert(>::hashed_key_for(0), vec![0u8; 32]); - let r = executor_call(&mut t, "Core_initialize_block", &vec![].and(&from_block_number(1u32))).0; + let r = executor_call( + &mut t, + "Core_initialize_block", + &vec![].and(&from_block_number(1u32)), + false, + ) + .0; assert!(r.is_ok()); t.execute_with(|| { assert_eq!(Balances::total_balance(&alice()), 111 * DOLLARS); @@ -807,7 +830,7 @@ fn successful_execution_gives_ok() { let fees = t.execute_with(|| transfer_fee(&xt())); - let r = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt())) + let r = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt()), false) .0 .unwrap(); ApplyExtrinsicResult::decode(&mut &r[..]) @@ -838,7 +861,7 @@ fn should_import_block_with_test_client() { #[test] fn default_config_as_json_works() { let mut t = new_test_ext(compact_code_unwrap()); - let r = executor_call(&mut t, "GenesisBuilder_create_default_config", &vec![]) + let r = executor_call(&mut t, "GenesisBuilder_create_default_config", &vec![], false) .0 .unwrap(); let r = Vec::::decode(&mut &r[..]).unwrap(); diff --git a/substrate/bin/node/cli/tests/common.rs b/substrate/bin/node/executor/tests/common.rs similarity index 91% rename from substrate/bin/node/cli/tests/common.rs rename to substrate/bin/node/executor/tests/common.rs index 9019594ff62..2d68c88db92 100644 --- a/substrate/bin/node/cli/tests/common.rs +++ b/substrate/bin/node/executor/tests/common.rs @@ -18,7 +18,7 @@ use codec::{Decode, Encode}; use frame_support::Hashable; use frame_system::offchain::AppCrypto; -use sc_executor::error::Result; +use sc_executor::{error::Result, NativeElseWasmExecutor, WasmExecutor}; use sp_consensus_babe::{ digests::{PreDigest, SecondaryPlainPreDigest}, Slot, BABE_ENGINE_ID, @@ -38,10 +38,11 @@ use kitchensink_runtime::{ constants::currency::*, Block, BuildStorage, CheckedExtrinsic, Header, Runtime, UncheckedExtrinsic, }; +use node_executor::ExecutorDispatch; use node_primitives::{BlockNumber, Hash}; use node_testing::keyring::*; use sp_externalities::Externalities; -use staging_node_cli::service::RuntimeExecutor; +use staging_node_executor as node_executor; pub const TEST_KEY_TYPE_ID: KeyTypeId = KeyTypeId(*b"test"); @@ -97,14 +98,15 @@ pub fn from_block_number(n: u32) -> Header { Header::new(n, Default::default(), Default::default(), [69; 32].into(), Default::default()) } -pub fn executor() -> RuntimeExecutor { - RuntimeExecutor::builder().build() +pub fn executor() -> NativeElseWasmExecutor { + NativeElseWasmExecutor::new_with_wasm_executor(WasmExecutor::builder().build()) } pub fn executor_call( t: &mut TestExternalities, method: &str, data: &[u8], + use_native: bool, ) -> (Result>, bool) { let mut t = t.ext(); @@ -116,7 +118,7 @@ pub fn executor_call( heap_pages: heap_pages.and_then(|hp| Decode::decode(&mut &hp[..]).ok()), }; sp_tracing::try_init_simple(); - executor().call(&mut t, &runtime_code, method, data, CallContext::Onchain) + executor().call(&mut t, &runtime_code, method, data, use_native, CallContext::Onchain) } pub fn new_test_ext(code: &[u8]) -> TestExternalities { @@ -167,12 +169,12 @@ pub fn construct_block( }; // execute the block to get the real header. - executor_call(env, "Core_initialize_block", &header.encode()).0.unwrap(); + executor_call(env, "Core_initialize_block", &header.encode(), true).0.unwrap(); for extrinsic in extrinsics.iter() { // Try to apply the `extrinsic`. It should be valid, in the sense that it passes // all pre-inclusion checks. - let r = executor_call(env, "BlockBuilder_apply_extrinsic", &extrinsic.encode()) + let r = executor_call(env, "BlockBuilder_apply_extrinsic", &extrinsic.encode(), true) .0 .expect("application of an extrinsic failed"); @@ -185,7 +187,7 @@ pub fn construct_block( } let header = Header::decode( - &mut &executor_call(env, "BlockBuilder_finalize_block", &[0u8; 0]).0.unwrap()[..], + &mut &executor_call(env, "BlockBuilder_finalize_block", &[0u8; 0], true).0.unwrap()[..], ) .unwrap(); diff --git a/substrate/bin/node/cli/tests/fees.rs b/substrate/bin/node/executor/tests/fees.rs similarity index 95% rename from substrate/bin/node/cli/tests/fees.rs rename to substrate/bin/node/executor/tests/fees.rs index 9d6407067a3..12baff91036 100644 --- a/substrate/bin/node/cli/tests/fees.rs +++ b/substrate/bin/node/executor/tests/fees.rs @@ -95,7 +95,7 @@ fn fee_multiplier_increases_and_decreases_on_big_weight() { ); // execute a big block. - executor_call(&mut t, "Core_execute_block", &block1.0).0.unwrap(); + executor_call(&mut t, "Core_execute_block", &block1.0, true).0.unwrap(); // weight multiplier is increased for next block. t.execute_with(|| { @@ -106,7 +106,7 @@ fn fee_multiplier_increases_and_decreases_on_big_weight() { }); // execute a big block. - executor_call(&mut t, "Core_execute_block", &block2.0).0.unwrap(); + executor_call(&mut t, "Core_execute_block", &block2.0, true).0.unwrap(); // weight multiplier is increased for next block. t.execute_with(|| { @@ -151,10 +151,12 @@ fn transaction_fee_is_correct() { function: RuntimeCall::Balances(default_transfer_call()), }); - let r = executor_call(&mut t, "Core_initialize_block", &vec![].and(&from_block_number(1u32))).0; + let r = + executor_call(&mut t, "Core_initialize_block", &vec![].and(&from_block_number(1u32)), true) + .0; assert!(r.is_ok()); - let r = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt.clone())).0; + let r = executor_call(&mut t, "BlockBuilder_apply_extrinsic", &vec![].and(&xt.clone()), true).0; assert!(r.is_ok()); t.execute_with(|| { @@ -248,7 +250,7 @@ fn block_weight_capacity_report() { len / 1024 / 1024, ); - let r = executor_call(&mut t, "Core_execute_block", &block.0).0; + let r = executor_call(&mut t, "Core_execute_block", &block.0, true).0; println!(" || Result = {:?}", r); assert!(r.is_ok()); @@ -314,7 +316,7 @@ fn block_length_capacity_report() { len / 1024 / 1024, ); - let r = executor_call(&mut t, "Core_execute_block", &block.0).0; + let r = executor_call(&mut t, "Core_execute_block", &block.0, true).0; println!(" || Result = {:?}", r); assert!(r.is_ok()); diff --git a/substrate/bin/node/cli/tests/res/default_genesis_config.json b/substrate/bin/node/executor/tests/res/default_genesis_config.json similarity index 100% rename from substrate/bin/node/cli/tests/res/default_genesis_config.json rename to substrate/bin/node/executor/tests/res/default_genesis_config.json diff --git a/substrate/bin/node/cli/tests/submit_transaction.rs b/substrate/bin/node/executor/tests/submit_transaction.rs similarity index 100% rename from substrate/bin/node/cli/tests/submit_transaction.rs rename to substrate/bin/node/executor/tests/submit_transaction.rs diff --git a/substrate/bin/node/inspect/Cargo.toml b/substrate/bin/node/inspect/Cargo.toml index 44de013483e..30cc22b0e8c 100644 --- a/substrate/bin/node/inspect/Cargo.toml +++ b/substrate/bin/node/inspect/Cargo.toml @@ -8,27 +8,16 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.6.1" } thiserror = "1.0" sc-cli = { path = "../../../client/cli" } sc-client-api = { path = "../../../client/api" } -sc-service = { path = "../../../client/service", default-features = false } +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" } - -[features] -runtime-benchmarks = [ - "sc-service/runtime-benchmarks", - "sp-runtime/runtime-benchmarks", -] diff --git a/substrate/bin/node/inspect/src/command.rs b/substrate/bin/node/inspect/src/command.rs index e0e25707e31..dcecfd78826 100644 --- a/substrate/bin/node/inspect/src/command.rs +++ b/substrate/bin/node/inspect/src/command.rs @@ -23,20 +23,18 @@ use crate::{ Inspector, }; use sc_cli::{CliConfiguration, ImportParams, Result, SharedParams}; -use sc_service::Configuration; +use sc_service::{Configuration, NativeExecutionDispatch}; use sp_runtime::traits::Block; -type HostFunctions = - (sp_io::SubstrateHostFunctions, sp_statement_store::runtime_api::HostFunctions); - impl InspectCmd { /// Run the inspect command, passing the inspector. - pub fn run(&self, config: Configuration) -> Result<()> + pub fn run(&self, config: Configuration) -> Result<()> where B: Block, RA: Send + Sync + 'static, + D: NativeExecutionDispatch + 'static, { - let executor = sc_service::new_wasm_executor::(&config); + let executor = sc_service::new_native_or_wasm_executor::(&config); let client = sc_service::new_full_client::(&config, None, executor)?; let inspect = Inspector::::new(client); diff --git a/substrate/bin/node/primitives/Cargo.toml b/substrate/bin/node/primitives/Cargo.toml index 24279ad09c3..77bf7ad4676 100644 --- a/substrate/bin/node/primitives/Cargo.toml +++ b/substrate/bin/node/primitives/Cargo.toml @@ -9,16 +9,13 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] 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 = { path = "../../../primitives/core", default-features = false} +sp-runtime = { path = "../../../primitives/runtime", default-features = false} [features] -default = ["std"] -std = ["sp-core/std", "sp-runtime/std"] +default = [ "std" ] +std = [ "sp-core/std", "sp-runtime/std" ] diff --git a/substrate/bin/node/rpc/Cargo.toml b/substrate/bin/node/rpc/Cargo.toml index a4a361fadbc..43db4ab9d34 100644 --- a/substrate/bin/node/rpc/Cargo.toml +++ b/substrate/bin/node/rpc/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/bin/node/runtime/Cargo.toml b/substrate/bin/node/runtime/Cargo.toml index 1d3f71f3436..2414358b60b 100644 --- a/substrate/bin/node/runtime/Cargo.toml +++ b/substrate/bin/node/runtime/Cargo.toml @@ -10,9 +10,6 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -29,123 +26,123 @@ log = { version = "0.4.17", default-features = false } serde_json = { version = "1.0.108", default-features = false, features = ["alloc", "arbitrary_precision"] } # 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 = { version = "0.12.0", default-features = false, features = ["codec", "scale-info", "num-traits"] } # primitives -sp-authority-discovery = { path = "../../../primitives/authority-discovery", default-features = false, features = ["serde"] } -sp-consensus-babe = { path = "../../../primitives/consensus/babe", default-features = false, features = ["serde"] } -sp-consensus-grandpa = { path = "../../../primitives/consensus/grandpa", default-features = false, features = ["serde"] } -sp-block-builder = { path = "../../../primitives/block-builder", default-features = false } +sp-authority-discovery = { path = "../../../primitives/authority-discovery", default-features = false, features=["serde"] } +sp-consensus-babe = { path = "../../../primitives/consensus/babe", default-features = false, features=["serde"] } +sp-consensus-grandpa = { path = "../../../primitives/consensus/grandpa", default-features = false, features=["serde"] } +sp-block-builder = { path = "../../../primitives/block-builder", default-features = false} sp-genesis-builder = { default-features = false, path = "../../../primitives/genesis-builder" } -sp-inherents = { path = "../../../primitives/inherents", default-features = false } -node-primitives = { path = "../primitives", default-features = false } +sp-inherents = { path = "../../../primitives/inherents", default-features = false} +node-primitives = { path = "../primitives", default-features = false} sp-mixnet = { path = "../../../primitives/mixnet", default-features = false } -sp-offchain = { path = "../../../primitives/offchain", default-features = false } -sp-core = { path = "../../../primitives/core", default-features = false, features = ["serde"] } -sp-std = { path = "../../../primitives/std", default-features = false } -sp-api = { path = "../../../primitives/api", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false, features = ["serde"] } -sp-staking = { path = "../../../primitives/staking", default-features = false, features = ["serde"] } -sp-storage = { path = "../../../primitives/storage", default-features = false } -sp-session = { path = "../../../primitives/session", default-features = false } -sp-transaction-pool = { path = "../../../primitives/transaction-pool", default-features = false } -sp-statement-store = { path = "../../../primitives/statement-store", default-features = false, features = ["serde"] } -sp-version = { path = "../../../primitives/version", default-features = false, features = ["serde"] } -sp-io = { path = "../../../primitives/io", default-features = false } +sp-offchain = { path = "../../../primitives/offchain", default-features = false} +sp-core = { path = "../../../primitives/core", default-features = false, features=["serde"] } +sp-std = { path = "../../../primitives/std", default-features = false} +sp-api = { path = "../../../primitives/api", default-features = false} +sp-runtime = { path = "../../../primitives/runtime", default-features = false, features=["serde"] } +sp-staking = { path = "../../../primitives/staking", default-features = false, features=["serde"] } +sp-storage = { path = "../../../primitives/storage", default-features = false} +sp-session = { path = "../../../primitives/session", default-features = false} +sp-transaction-pool = { path = "../../../primitives/transaction-pool", default-features = false} +sp-statement-store = { path = "../../../primitives/statement-store", default-features = false, features=["serde"] } +sp-version = { path = "../../../primitives/version", default-features = false, features=["serde"] } +sp-io = { path = "../../../primitives/io", default-features = false} # frame dependencies -frame-executive = { path = "../../../frame/executive", default-features = false } -frame-benchmarking = { path = "../../../frame/benchmarking", default-features = false } -frame-benchmarking-pallet-pov = { path = "../../../frame/benchmarking/pov", default-features = false } +frame-executive = { path = "../../../frame/executive", default-features = false} +frame-benchmarking = { path = "../../../frame/benchmarking", default-features = false} +frame-benchmarking-pallet-pov = { path = "../../../frame/benchmarking/pov", default-features = false} frame-support = { path = "../../../frame/support", default-features = false, features = ["tuples-96"] } -frame-system = { path = "../../../frame/system", default-features = false } +frame-system = { path = "../../../frame/system", default-features = false} frame-system-benchmarking = { path = "../../../frame/system/benchmarking", default-features = false, optional = true } -frame-election-provider-support = { path = "../../../frame/election-provider-support", default-features = false } -frame-system-rpc-runtime-api = { path = "../../../frame/system/rpc/runtime-api", default-features = false } +frame-election-provider-support = { path = "../../../frame/election-provider-support", default-features = false} +frame-system-rpc-runtime-api = { path = "../../../frame/system/rpc/runtime-api", default-features = false} frame-try-runtime = { path = "../../../frame/try-runtime", default-features = false, optional = true } -pallet-alliance = { path = "../../../frame/alliance", default-features = false } -pallet-asset-conversion = { path = "../../../frame/asset-conversion", default-features = false } -pallet-asset-rate = { path = "../../../frame/asset-rate", default-features = false } -pallet-assets = { path = "../../../frame/assets", default-features = false } -pallet-authority-discovery = { path = "../../../frame/authority-discovery", default-features = false } -pallet-authorship = { path = "../../../frame/authorship", default-features = false } -pallet-babe = { path = "../../../frame/babe", default-features = false } -pallet-bags-list = { path = "../../../frame/bags-list", default-features = false } -pallet-balances = { path = "../../../frame/balances", default-features = false } -pallet-bounties = { path = "../../../frame/bounties", default-features = false } -pallet-broker = { path = "../../../frame/broker", default-features = false } -pallet-child-bounties = { path = "../../../frame/child-bounties", default-features = false } -pallet-collective = { path = "../../../frame/collective", default-features = false } -pallet-contracts = { path = "../../../frame/contracts", default-features = false } -pallet-conviction-voting = { path = "../../../frame/conviction-voting", default-features = false } -pallet-core-fellowship = { path = "../../../frame/core-fellowship", default-features = false } -pallet-democracy = { path = "../../../frame/democracy", default-features = false } -pallet-election-provider-multi-phase = { path = "../../../frame/election-provider-multi-phase", default-features = false } +pallet-alliance = { path = "../../../frame/alliance", default-features = false} +pallet-asset-conversion = { path = "../../../frame/asset-conversion", default-features = false} +pallet-asset-rate = { path = "../../../frame/asset-rate", default-features = false} +pallet-assets = { path = "../../../frame/assets", default-features = false} +pallet-authority-discovery = { path = "../../../frame/authority-discovery", default-features = false} +pallet-authorship = { path = "../../../frame/authorship", default-features = false} +pallet-babe = { path = "../../../frame/babe", default-features = false} +pallet-bags-list = { path = "../../../frame/bags-list", default-features = false} +pallet-balances = { path = "../../../frame/balances", default-features = false} +pallet-bounties = { path = "../../../frame/bounties", default-features = false} +pallet-broker = { path = "../../../frame/broker", default-features = false} +pallet-child-bounties = { path = "../../../frame/child-bounties", default-features = false} +pallet-collective = { path = "../../../frame/collective", default-features = false} +pallet-contracts = { path = "../../../frame/contracts", default-features = false} +pallet-contracts-primitives = { path = "../../../frame/contracts/primitives", default-features = false} +pallet-conviction-voting = { path = "../../../frame/conviction-voting", default-features = false} +pallet-core-fellowship = { path = "../../../frame/core-fellowship", default-features = false} +pallet-democracy = { path = "../../../frame/democracy", default-features = false} +pallet-election-provider-multi-phase = { path = "../../../frame/election-provider-multi-phase", default-features = false} pallet-election-provider-support-benchmarking = { path = "../../../frame/election-provider-support/benchmarking", default-features = false, optional = true } -pallet-elections-phragmen = { path = "../../../frame/elections-phragmen", default-features = false } -pallet-example-tasks = { path = "../../../frame/examples/tasks", default-features = false } -pallet-fast-unstake = { path = "../../../frame/fast-unstake", default-features = false } -pallet-nis = { path = "../../../frame/nis", default-features = false } -pallet-grandpa = { path = "../../../frame/grandpa", default-features = false } -pallet-im-online = { path = "../../../frame/im-online", default-features = false } -pallet-indices = { path = "../../../frame/indices", default-features = false } -pallet-identity = { path = "../../../frame/identity", default-features = false } -pallet-lottery = { path = "../../../frame/lottery", default-features = false } -pallet-membership = { path = "../../../frame/membership", default-features = false } -pallet-message-queue = { path = "../../../frame/message-queue", default-features = false } +pallet-elections-phragmen = { path = "../../../frame/elections-phragmen", default-features = false} +pallet-fast-unstake = { path = "../../../frame/fast-unstake", default-features = false} +pallet-nis = { path = "../../../frame/nis", default-features = false} +pallet-grandpa = { path = "../../../frame/grandpa", default-features = false} +pallet-im-online = { path = "../../../frame/im-online", default-features = false} +pallet-indices = { path = "../../../frame/indices", default-features = false} +pallet-identity = { path = "../../../frame/identity", default-features = false} +pallet-lottery = { path = "../../../frame/lottery", default-features = false} +pallet-membership = { path = "../../../frame/membership", default-features = false} +pallet-message-queue = { path = "../../../frame/message-queue", default-features = false} pallet-mixnet = { path = "../../../frame/mixnet", default-features = false } -pallet-mmr = { path = "../../../frame/merkle-mountain-range", default-features = false } -pallet-multisig = { path = "../../../frame/multisig", default-features = false } -pallet-nfts = { path = "../../../frame/nfts", default-features = false } -pallet-nfts-runtime-api = { path = "../../../frame/nfts/runtime-api", default-features = false } -pallet-nft-fractionalization = { path = "../../../frame/nft-fractionalization", default-features = false } -pallet-nomination-pools = { path = "../../../frame/nomination-pools", default-features = false } -pallet-nomination-pools-benchmarking = { path = "../../../frame/nomination-pools/benchmarking", default-features = false, optional = true } -pallet-nomination-pools-runtime-api = { path = "../../../frame/nomination-pools/runtime-api", default-features = false } -pallet-offences = { path = "../../../frame/offences", default-features = false } +pallet-mmr = { path = "../../../frame/merkle-mountain-range", default-features = false} +pallet-multisig = { path = "../../../frame/multisig", default-features = false} +pallet-nfts = { path = "../../../frame/nfts", default-features = false} +pallet-nfts-runtime-api = { path = "../../../frame/nfts/runtime-api", default-features = false} +pallet-nft-fractionalization = { path = "../../../frame/nft-fractionalization", default-features = false} +pallet-nomination-pools = { path = "../../../frame/nomination-pools", default-features = false} +pallet-nomination-pools-benchmarking = { path = "../../../frame/nomination-pools/benchmarking", default-features = false, optional = true} +pallet-nomination-pools-runtime-api = { path = "../../../frame/nomination-pools/runtime-api", default-features = false} +pallet-offences = { path = "../../../frame/offences", default-features = false} pallet-offences-benchmarking = { path = "../../../frame/offences/benchmarking", default-features = false, optional = true } -pallet-glutton = { path = "../../../frame/glutton", default-features = false } -pallet-preimage = { path = "../../../frame/preimage", default-features = false } -pallet-proxy = { path = "../../../frame/proxy", default-features = false } -pallet-insecure-randomness-collective-flip = { path = "../../../frame/insecure-randomness-collective-flip", default-features = false } -pallet-ranked-collective = { path = "../../../frame/ranked-collective", default-features = false } -pallet-recovery = { path = "../../../frame/recovery", default-features = false } -pallet-referenda = { path = "../../../frame/referenda", default-features = false } -pallet-remark = { path = "../../../frame/remark", default-features = false } -pallet-root-testing = { path = "../../../frame/root-testing", default-features = false } -pallet-salary = { path = "../../../frame/salary", default-features = false } -pallet-session = { path = "../../../frame/session", default-features = false, features = ["historical"] } +pallet-glutton = { path = "../../../frame/glutton", default-features = false} +pallet-preimage = { path = "../../../frame/preimage", default-features = false} +pallet-proxy = { path = "../../../frame/proxy", default-features = false} +pallet-insecure-randomness-collective-flip = { path = "../../../frame/insecure-randomness-collective-flip", default-features = false} +pallet-ranked-collective = { path = "../../../frame/ranked-collective", default-features = false} +pallet-recovery = { path = "../../../frame/recovery", default-features = false} +pallet-referenda = { path = "../../../frame/referenda", default-features = false} +pallet-remark = { path = "../../../frame/remark", default-features = false} +pallet-root-testing = { path = "../../../frame/root-testing", default-features = false} +pallet-salary = { path = "../../../frame/salary", default-features = false} +pallet-session = { path = "../../../frame/session", default-features = false , features = [ "historical" ]} pallet-session-benchmarking = { path = "../../../frame/session/benchmarking", default-features = false, optional = true } -pallet-staking = { path = "../../../frame/staking", default-features = false } -pallet-staking-reward-curve = { path = "../../../frame/staking/reward-curve", default-features = false } -pallet-staking-runtime-api = { path = "../../../frame/staking/runtime-api", default-features = false } -pallet-state-trie-migration = { path = "../../../frame/state-trie-migration", default-features = false } -pallet-statement = { path = "../../../frame/statement", default-features = false } -pallet-scheduler = { path = "../../../frame/scheduler", default-features = false } -pallet-society = { path = "../../../frame/society", default-features = false } -pallet-sudo = { path = "../../../frame/sudo", default-features = false } -pallet-timestamp = { path = "../../../frame/timestamp", default-features = false } -pallet-tips = { path = "../../../frame/tips", default-features = false } -pallet-treasury = { path = "../../../frame/treasury", default-features = false } -pallet-utility = { path = "../../../frame/utility", default-features = false } -pallet-transaction-payment = { path = "../../../frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-asset-conversion-tx-payment = { path = "../../../frame/transaction-payment/asset-conversion-tx-payment", default-features = false } -pallet-asset-tx-payment = { path = "../../../frame/transaction-payment/asset-tx-payment", default-features = false } -pallet-skip-feeless-payment = { path = "../../../frame/transaction-payment/skip-feeless-payment", default-features = false } -pallet-transaction-storage = { path = "../../../frame/transaction-storage", default-features = false } -pallet-uniques = { path = "../../../frame/uniques", default-features = false } -pallet-vesting = { path = "../../../frame/vesting", default-features = false } -pallet-whitelist = { path = "../../../frame/whitelist", default-features = false } -pallet-tx-pause = { path = "../../../frame/tx-pause", default-features = false } -pallet-safe-mode = { path = "../../../frame/safe-mode", default-features = false } +pallet-staking = { path = "../../../frame/staking", default-features = false} +pallet-staking-reward-curve = { path = "../../../frame/staking/reward-curve", default-features = false} +pallet-staking-runtime-api = { path = "../../../frame/staking/runtime-api", default-features = false} +pallet-state-trie-migration = { path = "../../../frame/state-trie-migration", default-features = false} +pallet-statement = { path = "../../../frame/statement", default-features = false} +pallet-scheduler = { path = "../../../frame/scheduler", default-features = false} +pallet-society = { path = "../../../frame/society", default-features = false} +pallet-sudo = { path = "../../../frame/sudo", default-features = false} +pallet-timestamp = { path = "../../../frame/timestamp", default-features = false} +pallet-tips = { path = "../../../frame/tips", default-features = false} +pallet-treasury = { path = "../../../frame/treasury", default-features = false} +pallet-utility = { path = "../../../frame/utility", default-features = false} +pallet-transaction-payment = { path = "../../../frame/transaction-payment", default-features = false} +pallet-transaction-payment-rpc-runtime-api = { path = "../../../frame/transaction-payment/rpc/runtime-api", default-features = false} +pallet-asset-conversion-tx-payment = { path = "../../../frame/transaction-payment/asset-conversion-tx-payment", default-features = false} +pallet-asset-tx-payment = { path = "../../../frame/transaction-payment/asset-tx-payment", default-features = false} +pallet-skip-feeless-payment = { path = "../../../frame/transaction-payment/skip-feeless-payment", default-features = false} +pallet-transaction-storage = { path = "../../../frame/transaction-storage", default-features = false} +pallet-uniques = { path = "../../../frame/uniques", default-features = false} +pallet-vesting = { path = "../../../frame/vesting", default-features = false} +pallet-whitelist = { path = "../../../frame/whitelist", default-features = false} +pallet-tx-pause = { path = "../../../frame/tx-pause", default-features = false} +pallet-safe-mode = { path = "../../../frame/safe-mode", default-features = false} [build-dependencies] substrate-wasm-builder = { path = "../../../utils/wasm-builder", optional = true } [features] -default = ["std"] -with-tracing = ["frame-executive/with-tracing"] +default = [ "std" ] +with-tracing = [ "frame-executive/with-tracing" ] std = [ "codec/std", "frame-benchmarking-pallet-pov/std", @@ -174,6 +171,7 @@ std = [ "pallet-broker/std", "pallet-child-bounties/std", "pallet-collective/std", + "pallet-contracts-primitives/std", "pallet-contracts/std", "pallet-conviction-voting/std", "pallet-core-fellowship/std", @@ -181,7 +179,6 @@ std = [ "pallet-election-provider-multi-phase/std", "pallet-election-provider-support-benchmarking?/std", "pallet-elections-phragmen/std", - "pallet-example-tasks/std", "pallet-fast-unstake/std", "pallet-glutton/std", "pallet-grandpa/std", @@ -284,7 +281,6 @@ runtime-benchmarks = [ "pallet-election-provider-multi-phase/runtime-benchmarks", "pallet-election-provider-support-benchmarking/runtime-benchmarks", "pallet-elections-phragmen/runtime-benchmarks", - "pallet-example-tasks/runtime-benchmarks", "pallet-fast-unstake/runtime-benchmarks", "pallet-glutton/runtime-benchmarks", "pallet-grandpa/runtime-benchmarks", @@ -359,7 +355,6 @@ try-runtime = [ "pallet-democracy/try-runtime", "pallet-election-provider-multi-phase/try-runtime", "pallet-elections-phragmen/try-runtime", - "pallet-example-tasks/try-runtime", "pallet-fast-unstake/try-runtime", "pallet-glutton/try-runtime", "pallet-grandpa/try-runtime", diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 98165da5289..69b25687b3f 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -28,7 +28,7 @@ use frame_election_provider_support::{ onchain, BalancingConfig, ElectionDataProvider, SequentialPhragmen, VoteWeight, }; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, instances::{Instance1, Instance2}, @@ -283,32 +283,34 @@ impl pallet_safe_mode::Config for Runtime { type WeightInfo = pallet_safe_mode::weights::SubstrateWeight; } -#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = InsideBoth; type BlockWeights = RuntimeBlockWeights; type BlockLength = RuntimeBlockLength; type DbWeight = RocksDbWeight; + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; type Nonce = Nonce; type Hash = Hash; + type Hashing = BlakeTwo256; type AccountId = AccountId; type Lookup = Indices; type Block = Block; + type RuntimeEvent = RuntimeEvent; type BlockHashCount = BlockHashCount; type Version = Version; + type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); type SystemWeightInfo = frame_system::weights::SubstrateWeight; type SS58Prefix = ConstU16<42>; + type OnSetCode = (); type MaxConsumers = ConstU32<16>; } impl pallet_insecure_randomness_collective_flip::Config for Runtime {} -impl pallet_example_tasks::Config for Runtime { - type RuntimeTask = RuntimeTask; - type WeightInfo = pallet_example_tasks::weights::SubstrateWeight; -} - impl pallet_utility::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; @@ -632,7 +634,6 @@ parameter_types! { pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; pub const MaxNominators: u32 = 64; pub const OffendingValidatorsThreshold: Perbill = Perbill::from_percent(17); - pub const MaxControllersInDeprecationBatch: u32 = 5900; pub OffchainRepeat: BlockNumber = 5; pub HistoryDepth: u32 = 84; } @@ -675,7 +676,6 @@ impl pallet_staking::Config for Runtime { // This a placeholder, to be introduced in the next PR as an instance of bags-list type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = MaxControllersInDeprecationBatch; type HistoryDepth = HistoryDepth; type EventListeners = NominationPools; type WeightInfo = pallet_staking::weights::SubstrateWeight; @@ -1558,7 +1558,6 @@ impl pallet_vesting::Config for Runtime { type MinVestedTransfer = MinVestedTransfer; type WeightInfo = pallet_vesting::weights::SubstrateWeight; type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; - type BlockNumberProvider = System; // `VestingInfo` encode length is 36bytes. 28 schedules gets encoded as 1009 bytes, which is the // highest number of schedules that encodes less than 2^10. const MAX_VESTING_SCHEDULES: u32 = 28; @@ -2147,7 +2146,6 @@ construct_runtime!( SafeMode: pallet_safe_mode, Statement: pallet_statement, Broker: pallet_broker, - TasksExample: pallet_example_tasks, Mixnet: pallet_mixnet, SkipFeelessPayment: pallet_skip_feeless_payment, } @@ -2242,7 +2240,6 @@ mod benches { [pallet_conviction_voting, ConvictionVoting] [pallet_contracts, Contracts] [pallet_core_fellowship, CoreFellowship] - [tasks_example, TasksExample] [pallet_democracy, Democracy] [pallet_asset_conversion, AssetConversion] [pallet_election_provider_multi_phase, ElectionProviderMultiPhase] @@ -2506,7 +2503,7 @@ impl_runtime_apis! { gas_limit: Option, storage_deposit_limit: Option, input_data: Vec, - ) -> pallet_contracts::ContractExecResult { + ) -> pallet_contracts_primitives::ContractExecResult { let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block); Contracts::bare_call( origin, @@ -2526,10 +2523,10 @@ impl_runtime_apis! { value: Balance, gas_limit: Option, storage_deposit_limit: Option, - code: pallet_contracts::Code, + code: pallet_contracts_primitives::Code, data: Vec, salt: Vec, - ) -> pallet_contracts::ContractInstantiateResult + ) -> pallet_contracts_primitives::ContractInstantiateResult { let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block); Contracts::bare_instantiate( @@ -2550,7 +2547,7 @@ impl_runtime_apis! { code: Vec, storage_deposit_limit: Option, determinism: pallet_contracts::Determinism, - ) -> pallet_contracts::CodeUploadResult + ) -> pallet_contracts_primitives::CodeUploadResult { Contracts::bare_upload_code( origin, @@ -2563,7 +2560,7 @@ impl_runtime_apis! { fn get_storage( address: AccountId, key: Vec, - ) -> pallet_contracts::GetStorageResult { + ) -> pallet_contracts_primitives::GetStorageResult { Contracts::get_storage( address, key diff --git a/substrate/bin/node/testing/Cargo.toml b/substrate/bin/node/testing/Cargo.toml index 76188ed446c..e4fb06b5dcd 100644 --- a/substrate/bin/node/testing/Cargo.toml +++ b/substrate/bin/node/testing/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -22,7 +19,7 @@ futures = "0.3.21" log = "0.4.17" tempfile = "3.1.0" frame-system = { path = "../../../frame/system" } -node-cli = { package = "staging-node-cli", path = "../cli" } +node-executor = { package = "staging-node-executor", path = "../executor" } node-primitives = { path = "../primitives" } kitchensink-runtime = { path = "../runtime" } pallet-asset-conversion = { path = "../../../frame/asset-conversion" } @@ -32,13 +29,13 @@ pallet-asset-tx-payment = { path = "../../../frame/transaction-payment/asset-tx- 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-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", -] } + "rocksdb", +]} sp-api = { path = "../../../primitives/api" } sp-block-builder = { path = "../../../primitives/block-builder" } sp-blockchain = { path = "../../../primitives/blockchain" } @@ -48,5 +45,5 @@ 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 } +sp-timestamp = { path = "../../../primitives/timestamp", default-features = false} substrate-test-client = { path = "../../../test-utils/client" } diff --git a/substrate/bin/node/testing/src/bench.rs b/substrate/bin/node/testing/src/bench.rs index 8de4620fd87..ee1bb5532d1 100644 --- a/substrate/bin/node/testing/src/bench.rs +++ b/substrate/bin/node/testing/src/bench.rs @@ -43,7 +43,7 @@ use sc_block_builder::BlockBuilderBuilder; use sc_client_api::{execution_extensions::ExecutionExtensions, UsageProvider}; use sc_client_db::PruningMode; use sc_consensus::{BlockImport, BlockImportParams, ForkChoiceStrategy, ImportResult, ImportedAux}; -use sc_executor::{WasmExecutionMethod, WasmtimeInstantiationStrategy}; +use sc_executor::{NativeElseWasmExecutor, WasmExecutionMethod, WasmtimeInstantiationStrategy}; use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder; use sp_consensus::BlockOrigin; @@ -389,11 +389,13 @@ impl BenchDb { let task_executor = TaskExecutor::new(); let backend = sc_service::new_db_backend(db_config).expect("Should not fail"); - let executor = sc_executor::WasmExecutor::builder() - .with_execution_method(WasmExecutionMethod::Compiled { - instantiation_strategy: WasmtimeInstantiationStrategy::PoolingCopyOnWrite, - }) - .build(); + let executor = NativeElseWasmExecutor::new_with_wasm_executor( + sc_executor::WasmExecutor::builder() + .with_execution_method(WasmExecutionMethod::Compiled { + instantiation_strategy: WasmtimeInstantiationStrategy::PoolingCopyOnWrite, + }) + .build(), + ); let client_config = sc_service::ClientConfig::default(); let genesis_block_builder = sc_service::GenesisBlockBuilder::new( diff --git a/substrate/bin/node/testing/src/client.rs b/substrate/bin/node/testing/src/client.rs index 07ba1cdbbfb..22276833fb6 100644 --- a/substrate/bin/node/testing/src/client.rs +++ b/substrate/bin/node/testing/src/client.rs @@ -23,7 +23,7 @@ use sp_runtime::BuildStorage; pub use substrate_test_client::*; /// Call executor for `kitchensink-runtime` `TestClient`. -use node_cli::service::RuntimeExecutor; +pub type ExecutorDispatch = sc_executor::NativeElseWasmExecutor; /// Default backend type. pub type Backend = sc_client_db::Backend; @@ -31,7 +31,7 @@ pub type Backend = sc_client_db::Backend; /// Test client type. pub type Client = client::Client< Backend, - client::LocalCallExecutor, + client::LocalCallExecutor, node_primitives::Block, kitchensink_runtime::RuntimeApi, >; @@ -63,7 +63,7 @@ pub trait TestClientBuilderExt: Sized { impl TestClientBuilderExt for substrate_test_client::TestClientBuilder< node_primitives::Block, - client::LocalCallExecutor, + client::LocalCallExecutor, Backend, GenesisParameters, > @@ -71,17 +71,8 @@ impl TestClientBuilderExt fn new() -> Self { Self::default() } + fn build(self) -> Client { - let executor = RuntimeExecutor::builder().build(); - use sc_service::client::LocalCallExecutor; - use std::sync::Arc; - let executor = LocalCallExecutor::new( - self.backend().clone(), - executor.clone(), - Default::default(), - ExecutionExtensions::new(None, Arc::new(executor)), - ) - .expect("Creates LocalCallExecutor"); - self.build_with_executor(executor).0 + self.build_with_native_executor(None).0 } } diff --git a/substrate/bin/utils/chain-spec-builder/Cargo.toml b/substrate/bin/utils/chain-spec-builder/Cargo.toml index dcbe26f6a8f..f587989e003 100644 --- a/substrate/bin/utils/chain-spec-builder/Cargo.toml +++ b/substrate/bin/utils/chain-spec-builder/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -23,7 +20,7 @@ name = "chain-spec-builder" crate-type = ["rlib"] [dependencies] -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } log = "0.4.17" sc-chain-spec = { path = "../../../client/chain-spec" } serde_json = "1.0.108" diff --git a/substrate/bin/utils/subkey/Cargo.toml b/substrate/bin/utils/subkey/Cargo.toml index 58aa036a631..6606d8ac365 100644 --- a/substrate/bin/utils/subkey/Cargo.toml +++ b/substrate/bin/utils/subkey/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,5 +17,5 @@ path = "src/main.rs" name = "subkey" [dependencies] -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } sc-cli = { path = "../../../client/cli" } diff --git a/substrate/client/allocator/Cargo.toml b/substrate/client/allocator/Cargo.toml index ef13c1a4573..31c714180ce 100644 --- a/substrate/client/allocator/Cargo.toml +++ b/substrate/client/allocator/Cargo.toml @@ -10,9 +10,6 @@ description = "Collection of allocator implementations." documentation = "https://docs.rs/sc-allocator" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/allocator/src/lib.rs b/substrate/client/allocator/src/lib.rs index 70ed764bef8..e50d7d54c8e 100644 --- a/substrate/client/allocator/src/lib.rs +++ b/substrate/client/allocator/src/lib.rs @@ -18,7 +18,7 @@ //! Collection of allocator implementations. //! //! This crate provides the following allocator implementations: -//! - A freeing-bump allocator: [`FreeingBumpHeapAllocator`] +//! - A freeing-bump allocator: [`FreeingBumpHeapAllocator`](freeing_bump::FreeingBumpHeapAllocator) #![warn(missing_docs)] diff --git a/substrate/client/api/Cargo.toml b/substrate/client/api/Cargo.toml index 8c50b872914..2b64c86038d 100644 --- a/substrate/client/api/Cargo.toml +++ b/substrate/client/api/Cargo.toml @@ -10,9 +10,6 @@ description = "Substrate client interfaces." documentation = "https://docs.rs/sc-client-api" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -31,10 +28,10 @@ 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-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-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" } diff --git a/substrate/client/api/src/execution_extensions.rs b/substrate/client/api/src/execution_extensions.rs index 26d3ae73f69..6f927105df0 100644 --- a/substrate/client/api/src/execution_extensions.rs +++ b/substrate/client/api/src/execution_extensions.rs @@ -91,6 +91,7 @@ impl ExtensionsFactory /// /// This crate aggregates extensions available for the offchain calls /// and is responsible for producing a correct `Extensions` object. +/// for each call, based on required `Capabilities`. pub struct ExecutionExtensions { extensions_factory: RwLock>>, read_runtime_version: Arc, @@ -115,7 +116,8 @@ impl ExecutionExtensions { *self.extensions_factory.write() = Box::new(maker); } - /// Produces default extensions based on the input parameters. + /// Based on the execution context and capabilities it produces + /// the extensions object to support desired set of APIs. pub fn extensions( &self, block_hash: Block::Hash, @@ -125,6 +127,7 @@ impl ExecutionExtensions { self.extensions_factory.read().extensions_for(block_hash, block_number); extensions.register(ReadRuntimeVersionExt::new(self.read_runtime_version.clone())); + extensions } } diff --git a/substrate/client/authority-discovery/Cargo.toml b/substrate/client/authority-discovery/Cargo.toml index 33db0c156eb..ef2fdcfd485 100644 --- a/substrate/client/authority-discovery/Cargo.toml +++ b/substrate/client/authority-discovery/Cargo.toml @@ -10,9 +10,6 @@ repository.workspace = true description = "Substrate authority discovery." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -24,11 +21,8 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = futures = "0.3.21" futures-timer = "3.0.1" ip_network = "0.4.1" -libp2p = { version = "0.51.3", features = ["ed25519", "kad"] } -multihash = { version = "0.18.1", default-features = false, features = [ - "sha2", - "std", -] } +libp2p = { version = "0.51.3", features = ["kad", "ed25519"] } +multihash = { version = "0.17.0", default-features = false, features = ["std", "sha2"] } log = "0.4.17" prost = "0.11" rand = "0.8.5" @@ -43,11 +37,6 @@ sp-core = { path = "../../primitives/core" } sp-keystore = { path = "../../primitives/keystore" } sp-runtime = { path = "../../primitives/runtime" } async-trait = "0.1.56" -multihash-codetable = { version = "0.1.1", features = [ - "digest", - "serde", - "sha2", -] } [dev-dependencies] quickcheck = { version = "1.0.3", default-features = false } diff --git a/substrate/client/authority-discovery/src/worker.rs b/substrate/client/authority-discovery/src/worker.rs index 6db25416dee..a29e74df9ac 100644 --- a/substrate/client/authority-discovery/src/worker.rs +++ b/substrate/client/authority-discovery/src/worker.rs @@ -35,7 +35,7 @@ use addr_cache::AddrCache; use codec::{Decode, Encode}; use ip_network::IpNetwork; use libp2p::{core::multiaddr, identity::PublicKey, multihash::Multihash, Multiaddr, PeerId}; -use multihash_codetable::{Code, MultihashDigest}; +use multihash::{Code, MultihashDigest}; use log::{debug, error, log_enabled}; use prometheus_endpoint::{register, Counter, CounterVec, Gauge, Opts, U64}; diff --git a/substrate/client/basic-authorship/Cargo.toml b/substrate/client/basic-authorship/Cargo.toml index 926909ec7b7..1d60fc7f53e 100644 --- a/substrate/client/basic-authorship/Cargo.toml +++ b/substrate/client/basic-authorship/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Basic implementation of block-authoring logic." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/block-builder/Cargo.toml b/substrate/client/block-builder/Cargo.toml index 4477f5f1d77..2492c4101b2 100644 --- a/substrate/client/block-builder/Cargo.toml +++ b/substrate/client/block-builder/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Substrate block builder" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -23,7 +20,6 @@ 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" } diff --git a/substrate/client/block-builder/src/lib.rs b/substrate/client/block-builder/src/lib.rs index 258e39d962b..f62b941fdb1 100644 --- a/substrate/client/block-builder/src/lib.rs +++ b/substrate/client/block-builder/src/lib.rs @@ -42,7 +42,6 @@ use sp_runtime::{ use std::marker::PhantomData; pub use sp_block_builder::BlockBuilder as BlockBuilderApi; -use sp_trie::proof_size_extension::ProofSizeExt; /// A builder for creating an instance of [`BlockBuilder`]. pub struct BlockBuilderBuilder<'a, B, C> { @@ -236,10 +235,6 @@ where if record_proof { api.record_proof(); - let recorder = api - .proof_recorder() - .expect("Proof recording is enabled in the line above; qed."); - api.register_extension(ProofSizeExt::new(recorder)); } api.set_call_context(CallContext::Onchain); diff --git a/substrate/client/chain-spec/Cargo.toml b/substrate/client/chain-spec/Cargo.toml index c870ff19b2a..5b7cdda8ebe 100644 --- a/substrate/client/chain-spec/Cargo.toml +++ b/substrate/client/chain-spec/Cargo.toml @@ -9,16 +9,13 @@ repository.workspace = true description = "Substrate chain configurations." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } memmap2 = "0.5.0" -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.108" sc-client-api = { path = "../api" } sc-chain-spec-derive = { path = "derive" } @@ -38,5 +35,5 @@ docify = "0.2.0" [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-application-crypto = { default-features = false, path = "../../primitives/application-crypto", features = ["serde"] } sp-consensus-babe = { default-features = false, path = "../../primitives/consensus/babe", features = ["serde"] } diff --git a/substrate/client/chain-spec/derive/Cargo.toml b/substrate/client/chain-spec/derive/Cargo.toml index b5a2bdc09b3..74b8b656a40 100644 --- a/substrate/client/chain-spec/derive/Cargo.toml +++ b/substrate/client/chain-spec/derive/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "Macros to derive chain spec extension traits implementation." -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -18,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -proc-macro-crate = "2.0.1" +proc-macro-crate = "1.1.3" proc-macro2 = "1.0.56" quote = "1.0.28" -syn = "2.0.40" +syn = "2.0.38" diff --git a/substrate/client/chain-spec/src/extension.rs b/substrate/client/chain-spec/src/extension.rs index f2939741535..25ab011a05b 100644 --- a/substrate/client/chain-spec/src/extension.rs +++ b/substrate/client/chain-spec/src/extension.rs @@ -284,7 +284,7 @@ where } } -/// A subset of the `Extension` trait that only allows for quering extensions. +/// A subset if the `Extension` trait that only allows for quering extensions. pub trait GetExtension { /// Get an extension of specific type. fn get_any(&self, t: TypeId) -> &dyn Any; diff --git a/substrate/client/chain-spec/src/genesis_config_builder.rs b/substrate/client/chain-spec/src/genesis_config_builder.rs index 68f3d886049..9ccf6b4efb2 100644 --- a/substrate/client/chain-spec/src/genesis_config_builder.rs +++ b/substrate/client/chain-spec/src/genesis_config_builder.rs @@ -76,6 +76,7 @@ where &RuntimeCode { heap_pages: None, code_fetcher: self, hash: self.code_hash.clone() }, method, data, + false, CallContext::Offchain, ) .0 diff --git a/substrate/client/cli/Cargo.toml b/substrate/client/cli/Cargo.toml index 82362e35ea6..c4464c5f787 100644 --- a/substrate/client/cli/Cargo.toml +++ b/substrate/client/cli/Cargo.toml @@ -9,37 +9,34 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] array-bytes = "6.1" chrono = "0.4.27" -clap = { version = "4.4.11", features = ["derive", "string", "wrap_help"] } +clap = { version = "4.4.6", features = ["derive", "string", "wrap_help"] } fdlimit = "0.3.0" futures = "0.3.21" itertools = "0.10.3" -libp2p-identity = { version = "0.1.3", features = ["ed25519", "peerid"] } +libp2p-identity = { version = "0.1.3", features = ["peerid", "ed25519"]} log = "0.4.17" -names = { version = "0.14.0", default-features = false } +names = { version = "0.13.0", default-features = false } parity-scale-codec = "3.6.1" rand = "0.8.5" regex = "1.6.0" rpassword = "7.0.0" -serde = "1.0.193" +serde = "1.0.188" serde_json = "1.0.108" thiserror = "1.0.48" bip39 = "2.0.0" -tokio = { version = "1.22.0", features = ["parking_lot", "rt-multi-thread", "signal"] } +tokio = { version = "1.22.0", features = ["signal", "rt-multi-thread", "parking_lot"] } sc-client-api = { path = "../api" } -sc-client-db = { path = "../db", default-features = false } +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-service = { path = "../service", default-features = false} sc-telemetry = { path = "../telemetry" } sc-tracing = { path = "../tracing" } sc-utils = { path = "../utils" } @@ -57,5 +54,5 @@ futures-timer = "3.0.1" sp-tracing = { path = "../../primitives/tracing" } [features] -default = ["rocksdb"] -rocksdb = ["sc-client-db/rocksdb"] +default = [ "rocksdb" ] +rocksdb = [ "sc-client-db/rocksdb" ] diff --git a/substrate/client/consensus/aura/Cargo.toml b/substrate/client/consensus/aura/Cargo.toml index a323a1dda47..bc9648f683a 100644 --- a/substrate/client/consensus/aura/Cargo.toml +++ b/substrate/client/consensus/aura/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/consensus/babe/Cargo.toml b/substrate/client/consensus/babe/Cargo.toml index 996063cef1b..c8cff0981b3 100644 --- a/substrate/client/consensus/babe/Cargo.toml +++ b/substrate/client/consensus/babe/Cargo.toml @@ -10,9 +10,6 @@ repository.workspace = true documentation = "https://docs.rs/sc-consensus-babe" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -23,7 +20,7 @@ futures = "0.3.21" log = "0.4.17" num-bigint = "0.4.3" num-rational = "0.4.1" -num-traits = "0.2.17" +num-traits = "0.2.8" parking_lot = "0.12.1" thiserror = "1.0" fork-tree = { path = "../../../utils/fork-tree" } diff --git a/substrate/client/consensus/babe/rpc/Cargo.toml b/substrate/client/consensus/babe/rpc/Cargo.toml index b23f3f81d43..c95d95ae427 100644 --- a/substrate/client/consensus/babe/rpc/Cargo.toml +++ b/substrate/client/consensus/babe/rpc/Cargo.toml @@ -9,16 +9,13 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -jsonrpsee = { version = "0.16.2", features = ["client-core", "macros", "server"] } +jsonrpsee = { version = "0.16.2", features = ["client-core", "server", "macros"] } futures = "0.3.21" -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } thiserror = "1.0" sc-consensus-babe = { path = ".." } sc-consensus-epochs = { path = "../../epochs" } diff --git a/substrate/client/consensus/babe/src/authorship.rs b/substrate/client/consensus/babe/src/authorship.rs index fb172239801..3580caba746 100644 --- a/substrate/client/consensus/babe/src/authorship.rs +++ b/substrate/client/consensus/babe/src/authorship.rs @@ -249,7 +249,7 @@ fn claim_primary_slot( .make_bytes::( AUTHORING_SCORE_VRF_CONTEXT, &data.as_ref(), - &vrf_signature.pre_output, + &vrf_signature.output, ) .map(|bytes| u128::from_le_bytes(bytes) < threshold) .unwrap_or_default(); diff --git a/substrate/client/consensus/babe/src/tests.rs b/substrate/client/consensus/babe/src/tests.rs index 38c9e1ff6ac..82bfa284650 100644 --- a/substrate/client/consensus/babe/src/tests.rs +++ b/substrate/client/consensus/babe/src/tests.rs @@ -580,7 +580,7 @@ fn claim_vrf_check() { }; let data = make_vrf_sign_data(&epoch.randomness.clone(), 0.into(), epoch.epoch_index); let sign = keystore.sr25519_vrf_sign(AuthorityId::ID, &public, &data).unwrap().unwrap(); - assert_eq!(pre_digest.vrf_signature.pre_output, sign.pre_output); + assert_eq!(pre_digest.vrf_signature.output, sign.output); // We expect a SecondaryVRF claim for slot 1 let pre_digest = match claim_slot(1.into(), &epoch, &keystore).unwrap().0 { @@ -589,7 +589,7 @@ fn claim_vrf_check() { }; let data = make_vrf_sign_data(&epoch.randomness.clone(), 1.into(), epoch.epoch_index); let sign = keystore.sr25519_vrf_sign(AuthorityId::ID, &public, &data).unwrap().unwrap(); - assert_eq!(pre_digest.vrf_signature.pre_output, sign.pre_output); + assert_eq!(pre_digest.vrf_signature.output, sign.output); // Check that correct epoch index has been used if epochs are skipped (primary VRF) let slot = Slot::from(103); @@ -601,7 +601,7 @@ fn claim_vrf_check() { let data = make_vrf_sign_data(&epoch.randomness.clone(), slot, fixed_epoch.epoch_index); let sign = keystore.sr25519_vrf_sign(AuthorityId::ID, &public, &data).unwrap().unwrap(); assert_eq!(fixed_epoch.epoch_index, 11); - assert_eq!(claim.vrf_signature.pre_output, sign.pre_output); + assert_eq!(claim.vrf_signature.output, sign.output); // Check that correct epoch index has been used if epochs are skipped (secondary VRF) let slot = Slot::from(100); @@ -613,7 +613,7 @@ fn claim_vrf_check() { let data = make_vrf_sign_data(&epoch.randomness.clone(), slot, fixed_epoch.epoch_index); let sign = keystore.sr25519_vrf_sign(AuthorityId::ID, &public, &data).unwrap().unwrap(); assert_eq!(fixed_epoch.epoch_index, 11); - assert_eq!(pre_digest.vrf_signature.pre_output, sign.pre_output); + assert_eq!(pre_digest.vrf_signature.output, sign.output); } // Propose and import a new BABE block on top of the given parent. diff --git a/substrate/client/consensus/babe/src/verification.rs b/substrate/client/consensus/babe/src/verification.rs index c6e4ec0c10c..3de5eacc2c5 100644 --- a/substrate/client/consensus/babe/src/verification.rs +++ b/substrate/client/consensus/babe/src/verification.rs @@ -185,7 +185,7 @@ fn check_primary_header( .make_bytes::( AUTHORING_SCORE_VRF_CONTEXT, &data.as_ref(), - &pre_digest.vrf_signature.pre_output, + &pre_digest.vrf_signature.output, ) .map(u128::from_le_bytes) .map_err(|_| babe_err(Error::VrfVerificationFailed))?; diff --git a/substrate/client/consensus/beefy/Cargo.toml b/substrate/client/consensus/beefy/Cargo.toml index 8ffa6b24be8..aae5a44d7fa 100644 --- a/substrate/client/consensus/beefy/Cargo.toml +++ b/substrate/client/consensus/beefy/Cargo.toml @@ -8,9 +8,6 @@ repository.workspace = true description = "BEEFY Client gadget for substrate" homepage = "https://substrate.io" -[lints] -workspace = true - [dependencies] array-bytes = "6.1" async-channel = "1.8.0" @@ -41,7 +38,7 @@ sp-mmr-primitives = { path = "../../../primitives/merkle-mountain-range" } sp-runtime = { path = "../../../primitives/runtime" } [dev-dependencies] -serde = "1.0.193" +serde = "1.0.188" tempfile = "3.1.0" tokio = "1.22.0" sc-block-builder = { path = "../../block-builder" } diff --git a/substrate/client/consensus/beefy/rpc/Cargo.toml b/substrate/client/consensus/beefy/rpc/Cargo.toml index 157b0cc87fc..c7464fdc653 100644 --- a/substrate/client/consensus/beefy/rpc/Cargo.toml +++ b/substrate/client/consensus/beefy/rpc/Cargo.toml @@ -8,16 +8,13 @@ repository.workspace = true description = "RPC for the BEEFY Client gadget for substrate" homepage = "https://substrate.io" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", features = ["derive"] } futures = "0.3.21" -jsonrpsee = { version = "0.16.2", features = ["client-core", "macros", "server"] } +jsonrpsee = { version = "0.16.2", features = ["client-core", "server", "macros"] } log = "0.4" parking_lot = "0.12.1" -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } thiserror = "1.0" sc-consensus-beefy = { path = ".." } sp-consensus-beefy = { path = "../../../../primitives/consensus/beefy" } @@ -27,6 +24,6 @@ sp-runtime = { path = "../../../../primitives/runtime" } [dev-dependencies] serde_json = "1.0.108" -sc-rpc = { path = "../../../rpc", features = ["test-helpers"] } +sc-rpc = { path = "../../../rpc", features = ["test-helpers"]} substrate-test-runtime-client = { path = "../../../../test-utils/runtime/client" } tokio = { version = "1.22.0", features = ["macros"] } diff --git a/substrate/client/consensus/beefy/src/communication/mod.rs b/substrate/client/consensus/beefy/src/communication/mod.rs index 3827559057d..10a6071aae6 100644 --- a/substrate/client/consensus/beefy/src/communication/mod.rs +++ b/substrate/client/consensus/beefy/src/communication/mod.rs @@ -67,16 +67,10 @@ pub(crate) mod beefy_protocol_name { /// For standard protocol name see [`beefy_protocol_name::gossip_protocol_name`]. pub fn beefy_peers_set_config( gossip_protocol_name: sc_network::ProtocolName, -) -> (sc_network::config::NonDefaultSetConfig, Box) { - let (mut cfg, notification_service) = sc_network::config::NonDefaultSetConfig::new( - gossip_protocol_name, - Vec::new(), - 1024 * 1024, - None, - Default::default(), - ); +) -> sc_network::config::NonDefaultSetConfig { + let mut cfg = sc_network::config::NonDefaultSetConfig::new(gossip_protocol_name, 1024 * 1024); cfg.allow_non_reserved(25, 25); - (cfg, notification_service) + cfg } // cost scalars for reporting peers. diff --git a/substrate/client/consensus/beefy/src/lib.rs b/substrate/client/consensus/beefy/src/lib.rs index b3ff11add27..3d104f13250 100644 --- a/substrate/client/consensus/beefy/src/lib.rs +++ b/substrate/client/consensus/beefy/src/lib.rs @@ -38,7 +38,7 @@ use parking_lot::Mutex; use prometheus::Registry; use sc_client_api::{Backend, BlockBackend, BlockchainEvents, FinalityNotifications, Finalizer}; use sc_consensus::BlockImport; -use sc_network::{NetworkRequest, NotificationService, ProtocolName}; +use sc_network::{NetworkRequest, ProtocolName}; use sc_network_gossip::{GossipEngine, Network as GossipNetwork, Syncing as GossipSyncing}; use sp_api::ProvideRuntimeApi; use sp_blockchain::{ @@ -178,8 +178,6 @@ pub struct BeefyNetworkParams { pub network: Arc, /// Syncing service implementing a sync oracle and an event stream for peers. pub sync: Arc, - /// Handle for receiving notification events. - pub notification_service: Box, /// Chain specific BEEFY gossip protocol name. See /// [`communication::beefy_protocol_name::gossip_protocol_name`]. pub gossip_protocol_name: ProtocolName, @@ -245,7 +243,6 @@ pub async fn start_beefy_gadget( let BeefyNetworkParams { network, sync, - notification_service, gossip_protocol_name, justifications_protocol_name, .. @@ -267,7 +264,6 @@ pub async fn start_beefy_gadget( let gossip_engine = GossipEngine::new( network.clone(), sync.clone(), - notification_service, gossip_protocol_name.clone(), gossip_validator.clone(), None, diff --git a/substrate/client/consensus/beefy/src/tests.rs b/substrate/client/consensus/beefy/src/tests.rs index 3f800166e26..3aaa59cbfa1 100644 --- a/substrate/client/consensus/beefy/src/tests.rs +++ b/substrate/client/consensus/beefy/src/tests.rs @@ -72,7 +72,7 @@ use substrate_test_runtime_client::{BlockBuilderExt, ClientExt}; use tokio::time::Duration; const GENESIS_HASH: H256 = H256::zero(); -pub(crate) fn beefy_gossip_proto_name() -> ProtocolName { +fn beefy_gossip_proto_name() -> ProtocolName { gossip_protocol_name(GENESIS_HASH, None) } @@ -371,7 +371,6 @@ async fn voter_init_setup( let mut gossip_engine = sc_network_gossip::GossipEngine::new( net.peer(0).network_service().clone(), net.peer(0).sync_service().clone(), - net.peer(0).take_notification_service(&beefy_gossip_proto_name()).unwrap(), "/beefy/whatever", gossip_validator, None, @@ -393,14 +392,6 @@ where { let tasks = FuturesUnordered::new(); - let mut notification_services = peers - .iter() - .map(|(peer_id, _, _)| { - let peer = &mut net.peers[*peer_id]; - (*peer_id, peer.take_notification_service(&beefy_gossip_proto_name()).unwrap()) - }) - .collect::>(); - for (peer_id, key, api) in peers.into_iter() { let peer = &net.peers[peer_id]; @@ -418,7 +409,6 @@ where let network_params = crate::BeefyNetworkParams { network: peer.network_service().clone(), sync: peer.sync_service().clone(), - notification_service: notification_services.remove(&peer_id).unwrap(), gossip_protocol_name: beefy_gossip_proto_name(), justifications_protocol_name: on_demand_justif_handler.protocol_name(), _phantom: PhantomData, @@ -1055,25 +1045,7 @@ async fn should_initialize_voter_at_custom_genesis() { net.peer(0).client().as_client().finalize_block(hashes[8], None).unwrap(); // load persistent state - nothing in DB, should init at genesis - // - // NOTE: code from `voter_init_setup()` is moved here because the new network event system - // doesn't allow creating a new `GossipEngine` as the notification handle is consumed by the - // first `GossipEngine` - let known_peers = Arc::new(Mutex::new(KnownPeers::new())); - let (gossip_validator, _) = GossipValidator::new(known_peers); - let gossip_validator = Arc::new(gossip_validator); - let mut gossip_engine = sc_network_gossip::GossipEngine::new( - net.peer(0).network_service().clone(), - net.peer(0).sync_service().clone(), - net.peer(0).take_notification_service(&beefy_gossip_proto_name()).unwrap(), - "/beefy/whatever", - gossip_validator, - None, - ); - let (beefy_genesis, best_grandpa) = - wait_for_runtime_pallet(&api, &mut gossip_engine, &mut finality).await.unwrap(); - let persisted_state = - load_or_init_voter_state(&*backend, &api, beefy_genesis, best_grandpa, 1).unwrap(); + let persisted_state = voter_init_setup(&mut net, &mut finality, &api).await.unwrap(); // Test initialization at session boundary. // verify voter initialized with single session starting at block `custom_pallet_genesis` (7) @@ -1103,11 +1075,7 @@ async fn should_initialize_voter_at_custom_genesis() { net.peer(0).client().as_client().finalize_block(hashes[10], None).unwrap(); // load persistent state - state preset in DB, but with different pallet genesis - // the network state persists and uses the old `GossipEngine` initialized for `peer(0)` - let (beefy_genesis, best_grandpa) = - wait_for_runtime_pallet(&api, &mut gossip_engine, &mut finality).await.unwrap(); - let new_persisted_state = - load_or_init_voter_state(&*backend, &api, beefy_genesis, best_grandpa, 1).unwrap(); + let new_persisted_state = voter_init_setup(&mut net, &mut finality, &api).await.unwrap(); // verify voter initialized with single session starting at block `new_pallet_genesis` (10) let sessions = new_persisted_state.voting_oracle().sessions(); @@ -1403,7 +1371,7 @@ async fn gossipped_finality_proofs() { let api = Arc::new(TestApi::with_validator_set(&validator_set)); let beefy_peers = peers.iter().enumerate().map(|(id, key)| (id, key, api.clone())).collect(); - let charlie = &mut net.peers[2]; + let charlie = &net.peers[2]; let known_peers = Arc::new(Mutex::new(KnownPeers::::new())); // Charlie will run just the gossip engine and not the full voter. let (gossip_validator, _) = GossipValidator::new(known_peers); @@ -1416,7 +1384,6 @@ async fn gossipped_finality_proofs() { let mut charlie_gossip_engine = sc_network_gossip::GossipEngine::new( charlie.network_service().clone(), charlie.sync_service().clone(), - charlie.take_notification_service(&beefy_gossip_proto_name()).unwrap(), beefy_gossip_proto_name(), charlie_gossip_validator.clone(), None, diff --git a/substrate/client/consensus/beefy/src/worker.rs b/substrate/client/consensus/beefy/src/worker.rs index 1fbda974053..0eea5647e51 100644 --- a/substrate/client/consensus/beefy/src/worker.rs +++ b/substrate/client/consensus/beefy/src/worker.rs @@ -1145,16 +1145,12 @@ pub(crate) mod tests { let api = Arc::new(TestApi::with_validator_set(&genesis_validator_set)); let network = peer.network_service().clone(); let sync = peer.sync_service().clone(); - let notification_service = peer - .take_notification_service(&crate::tests::beefy_gossip_proto_name()) - .unwrap(); let known_peers = Arc::new(Mutex::new(KnownPeers::new())); let (gossip_validator, gossip_report_stream) = GossipValidator::new(known_peers.clone()); let gossip_validator = Arc::new(gossip_validator); let gossip_engine = GossipEngine::new( network.clone(), sync.clone(), - notification_service, "/beefy/1", gossip_validator.clone(), None, diff --git a/substrate/client/consensus/common/Cargo.toml b/substrate/client/consensus/common/Cargo.toml index 9c0305bb8c9..f269e3752d4 100644 --- a/substrate/client/consensus/common/Cargo.toml +++ b/substrate/client/consensus/common/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Collection of common consensus specific imlementations for Substrate (client)" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,7 +16,7 @@ targets = ["x86_64-unknown-linux-gnu"] async-trait = "0.1.57" futures = { version = "0.3.21", features = ["thread-pool"] } futures-timer = "3.0.1" -libp2p-identity = { version = "0.1.3", features = ["ed25519", "peerid"] } +libp2p-identity = { version = "0.1.3", features = ["peerid", "ed25519"] } log = "0.4.17" mockall = "0.11.3" parking_lot = "0.12.1" diff --git a/substrate/client/consensus/epochs/Cargo.toml b/substrate/client/consensus/epochs/Cargo.toml index 76e4c05a673..07de83980bc 100644 --- a/substrate/client/consensus/epochs/Cargo.toml +++ b/substrate/client/consensus/epochs/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/consensus/grandpa/Cargo.toml b/substrate/client/consensus/grandpa/Cargo.toml index 14ce52f2729..85f98e7546e 100644 --- a/substrate/client/consensus/grandpa/Cargo.toml +++ b/substrate/client/consensus/grandpa/Cargo.toml @@ -10,9 +10,6 @@ description = "Integration of the GRANDPA finality gadget into substrate." documentation = "https://docs.rs/sc-consensus-grandpa" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -56,7 +53,7 @@ sp-runtime = { path = "../../../primitives/runtime" } [dev-dependencies] assert_matches = "1.3.0" finality-grandpa = { version = "0.16.2", features = ["derive-codec", "test-helpers"] } -serde = "1.0.193" +serde = "1.0.188" tokio = "1.22.0" sc-network = { path = "../../network" } sc-network-test = { path = "../../network/test" } diff --git a/substrate/client/consensus/grandpa/rpc/Cargo.toml b/substrate/client/consensus/grandpa/rpc/Cargo.toml index 983f7a4339b..e2f9e40afb2 100644 --- a/substrate/client/consensus/grandpa/rpc/Cargo.toml +++ b/substrate/client/consensus/grandpa/rpc/Cargo.toml @@ -9,16 +9,13 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" readme = "README.md" homepage = "https://substrate.io" -[lints] -workspace = true - [dependencies] finality-grandpa = { version = "0.16.2", features = ["derive-codec"] } futures = "0.3.16" -jsonrpsee = { version = "0.16.2", features = ["client-core", "macros", "server"] } +jsonrpsee = { version = "0.16.2", features = ["client-core", "server", "macros"] } log = "0.4.8" parity-scale-codec = { version = "3.6.1", features = ["derive"] } -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } thiserror = "1.0" sc-client-api = { path = "../../../api" } sc-consensus-grandpa = { path = ".." } @@ -29,7 +26,7 @@ sp-runtime = { path = "../../../../primitives/runtime" } [dev-dependencies] sc-block-builder = { path = "../../../block-builder" } -sc-rpc = { path = "../../../rpc", features = ["test-helpers"] } +sc-rpc = { path = "../../../rpc", features = ["test-helpers"]} sp-core = { path = "../../../../primitives/core" } sp-consensus-grandpa = { path = "../../../../primitives/consensus/grandpa" } sp-keyring = { path = "../../../../primitives/keyring" } diff --git a/substrate/client/consensus/grandpa/src/communication/mod.rs b/substrate/client/consensus/grandpa/src/communication/mod.rs index 5c7e1276297..6d9e956b41b 100644 --- a/substrate/client/consensus/grandpa/src/communication/mod.rs +++ b/substrate/client/consensus/grandpa/src/communication/mod.rs @@ -46,7 +46,7 @@ use finality_grandpa::{ Message::{Precommit, Prevote, PrimaryPropose}, }; use parity_scale_codec::{Decode, DecodeAll, Encode}; -use sc_network::{NetworkBlock, NetworkSyncForkRequest, NotificationService, ReputationChange}; +use sc_network::{NetworkBlock, NetworkSyncForkRequest, ReputationChange}; use sc_network_gossip::{GossipEngine, Network as GossipNetwork}; use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_INFO}; use sp_keystore::KeystorePtr; @@ -247,7 +247,6 @@ impl, S: Syncing> NetworkBridge { pub(crate) fn new( service: N, sync: S, - notification_service: Box, config: crate::Config, set_state: crate::environment::SharedVoterSetState, prometheus_registry: Option<&Registry>, @@ -261,7 +260,6 @@ impl, S: Syncing> NetworkBridge { let gossip_engine = Arc::new(Mutex::new(GossipEngine::new( service.clone(), sync.clone(), - notification_service, protocol, validator.clone(), prometheus_registry, diff --git a/substrate/client/consensus/grandpa/src/communication/tests.rs b/substrate/client/consensus/grandpa/src/communication/tests.rs index fe24fb3cb20..4a869d0f515 100644 --- a/substrate/client/consensus/grandpa/src/communication/tests.rs +++ b/substrate/client/consensus/grandpa/src/communication/tests.rs @@ -24,17 +24,16 @@ use super::{ }; use crate::{communication::grandpa_protocol_name, environment::SharedVoterSetState}; use futures::prelude::*; -use parity_scale_codec::{DecodeAll, Encode}; +use parity_scale_codec::Encode; use sc_network::{ config::{MultiaddrWithPeerId, Role}, event::Event as NetworkEvent, - service::traits::{Direction, MessageSink, NotificationEvent, NotificationService}, types::ProtocolName, Multiaddr, NetworkBlock, NetworkEventStream, NetworkNotification, NetworkPeers, NetworkSyncForkRequest, NotificationSenderError, NotificationSenderT as NotificationSender, PeerId, ReputationChange, }; -use sc_network_common::role::{ObservedRole, Roles}; +use sc_network_common::role::ObservedRole; use sc_network_gossip::Validator; use sc_network_sync::{SyncEvent as SyncStreamEvent, SyncEventStream}; use sc_network_test::{Block, Hash}; @@ -75,15 +74,11 @@ impl NetworkPeers for TestNetwork { unimplemented!(); } - fn report_peer(&self, peer_id: PeerId, cost_benefit: ReputationChange) { - let _ = self.sender.unbounded_send(Event::Report(peer_id, cost_benefit)); + fn report_peer(&self, who: PeerId, cost_benefit: ReputationChange) { + let _ = self.sender.unbounded_send(Event::Report(who, cost_benefit)); } - fn peer_reputation(&self, _peer_id: &PeerId) -> i32 { - unimplemented!() - } - - fn disconnect_peer(&self, _peer_id: PeerId, _protocol: ProtocolName) {} + fn disconnect_peer(&self, _who: PeerId, _protocol: ProtocolName) {} fn accept_unreserved_peers(&self) { unimplemented!(); @@ -128,12 +123,6 @@ impl NetworkPeers for TestNetwork { fn sync_num_connected(&self) -> usize { unimplemented!(); } - - fn peer_role(&self, _peer_id: PeerId, handshake: Vec) -> Option { - Roles::decode_all(&mut &handshake[..]) - .ok() - .and_then(|role| Some(ObservedRole::from(role))) - } } impl NetworkEventStream for TestNetwork { @@ -222,70 +211,10 @@ impl NetworkSyncForkRequest> for TestSync { fn set_sync_fork_request(&self, _peers: Vec, _hash: Hash, _number: NumberFor) {} } -#[derive(Debug)] -pub(crate) struct TestNotificationService { - sender: TracingUnboundedSender, - rx: TracingUnboundedReceiver, -} - -#[async_trait::async_trait] -impl NotificationService for TestNotificationService { - /// Instruct `Notifications` to open a new substream for `peer`. - async fn open_substream(&mut self, _peer: PeerId) -> Result<(), ()> { - unimplemented!(); - } - - /// Instruct `Notifications` to close substream for `peer`. - async fn close_substream(&mut self, _peer: PeerId) -> Result<(), ()> { - unimplemented!(); - } - - /// Send synchronous `notification` to `peer`. - fn send_sync_notification(&self, peer: &PeerId, notification: Vec) { - let _ = self.sender.unbounded_send(Event::WriteNotification(*peer, notification)); - } - - /// Send asynchronous `notification` to `peer`, allowing sender to exercise backpressure. - async fn send_async_notification( - &self, - _peer: &PeerId, - _notification: Vec, - ) -> Result<(), sc_network::error::Error> { - unimplemented!(); - } - - /// Set handshake for the notification protocol replacing the old handshake. - async fn set_handshake(&mut self, _handshake: Vec) -> Result<(), ()> { - unimplemented!(); - } - - fn try_set_handshake(&mut self, _handshake: Vec) -> Result<(), ()> { - unimplemented!(); - } - - /// Get next event from the `Notifications` event stream. - async fn next_event(&mut self) -> Option { - self.rx.next().await - } - - fn clone(&mut self) -> Result, ()> { - unimplemented!(); - } - - fn protocol(&self) -> &ProtocolName { - unimplemented!(); - } - - fn message_sink(&self, _peer: &PeerId) -> Option> { - unimplemented!(); - } -} - pub(crate) struct Tester { pub(crate) net_handle: super::NetworkBridge, gossip_validator: Arc>, pub(crate) events: TracingUnboundedReceiver, - pub(crate) notification_tx: TracingUnboundedSender, } impl Tester { @@ -350,9 +279,6 @@ fn voter_set_state() -> SharedVoterSetState { // needs to run in a tokio runtime. pub(crate) fn make_test_network() -> (impl Future, TestNetwork) { let (tx, rx) = tracing_unbounded("test", 100_000); - let (notification_tx, notification_rx) = tracing_unbounded("test-notification", 100_000); - - let notification_service = TestNotificationService { rx: notification_rx, sender: tx.clone() }; let net = TestNetwork { sender: tx }; let sync = TestSync {}; @@ -367,22 +293,14 @@ pub(crate) fn make_test_network() -> (impl Future, TestNetwork) } } - let bridge = super::NetworkBridge::new( - net.clone(), - sync, - Box::new(notification_service), - config(), - voter_set_state(), - None, - None, - ); + let bridge = + super::NetworkBridge::new(net.clone(), sync, config(), voter_set_state(), None, None); ( futures::future::ready(Tester { gossip_validator: bridge.validator.clone(), net_handle: bridge, events: rx, - notification_tx, }), net, ) @@ -467,62 +385,63 @@ fn good_commit_leads_to_relay() { let commit_to_send = encoded_commit.clone(); let network_bridge = tester.net_handle.clone(); - // `NetworkBridge` will be operational as soon as it's created and it's - // waiting for events from the network. Send it events that inform that - // a notification stream was opened and that a notification was received. - // - // Since each protocol has its own notification stream, events need not be filtered. + // asking for global communication will cause the test network + // to send us an event asking us for a stream. use it to + // send a message. let sender_id = id; - - let send_message = async move { - let _ = tester.notification_tx.unbounded_send( - NotificationEvent::NotificationStreamOpened { - peer: sender_id, - direction: Direction::Inbound, + let send_message = tester.filter_network_events(move |event| match event { + Event::EventStream(sender) => { + // Add the sending peer and send the commit + let _ = sender.unbounded_send(NetworkEvent::NotificationStreamOpened { + remote: sender_id, + protocol: grandpa_protocol_name::NAME.into(), negotiated_fallback: None, - handshake: Roles::FULL.encode(), - }, - ); - let _ = tester.notification_tx.unbounded_send( - NotificationEvent::NotificationReceived { - peer: sender_id, - notification: commit_to_send.clone(), - }, - ); - - // Add a random peer which will be the recipient of this message - let receiver_id = PeerId::random(); - let _ = tester.notification_tx.unbounded_send( - NotificationEvent::NotificationStreamOpened { - peer: receiver_id, - direction: Direction::Inbound, - negotiated_fallback: None, - handshake: Roles::FULL.encode(), - }, - ); - - // Announce its local set being on the current set id through a neighbor - // packet, otherwise it won't be eligible to receive the commit - let _ = { - let update = gossip::VersionedNeighborPacket::V1(gossip::NeighborPacket { - round: Round(round), - set_id: SetId(set_id), - commit_finalized_height: 1, + role: ObservedRole::Full, + received_handshake: vec![], }); - let msg = gossip::GossipMessage::::Neighbor(update); + let _ = sender.unbounded_send(NetworkEvent::NotificationsReceived { + remote: sender_id, + messages: vec![( + grandpa_protocol_name::NAME.into(), + commit_to_send.clone().into(), + )], + }); - let _ = tester.notification_tx.unbounded_send( - NotificationEvent::NotificationReceived { - peer: receiver_id, - notification: msg.encode(), - }, - ); - }; + // Add a random peer which will be the recipient of this message + let receiver_id = PeerId::random(); + let _ = sender.unbounded_send(NetworkEvent::NotificationStreamOpened { + remote: receiver_id, + protocol: grandpa_protocol_name::NAME.into(), + negotiated_fallback: None, + role: ObservedRole::Full, + received_handshake: vec![], + }); - tester - } - .boxed(); + // Announce its local set has being on the current set id through a neighbor + // packet, otherwise it won't be eligible to receive the commit + let _ = { + let update = gossip::VersionedNeighborPacket::V1(gossip::NeighborPacket { + round: Round(round), + set_id: SetId(set_id), + commit_finalized_height: 1, + }); + + let msg = gossip::GossipMessage::::Neighbor(update); + + sender.unbounded_send(NetworkEvent::NotificationsReceived { + remote: receiver_id, + messages: vec![( + grandpa_protocol_name::NAME.into(), + msg.encode().into(), + )], + }) + }; + + true + }, + _ => false, + }); // when the commit comes in, we'll tell the callback it was good. let handle_commit = commits_in.into_future().map(|(item, _)| match item.unwrap() { @@ -618,32 +537,31 @@ fn bad_commit_leads_to_report() { let commit_to_send = encoded_commit.clone(); let network_bridge = tester.net_handle.clone(); - // `NetworkBridge` will be operational as soon as it's created and it's - // waiting for events from the network. Send it events that inform that - // a notification stream was opened and that a notification was received. - // - // Since each protocol has its own notification stream, events need not be filtered. + // asking for global communication will cause the test network + // to send us an event asking us for a stream. use it to + // send a message. let sender_id = id; - - let send_message = async move { - let _ = tester.notification_tx.unbounded_send( - NotificationEvent::NotificationStreamOpened { - peer: sender_id, - direction: Direction::Inbound, + let send_message = tester.filter_network_events(move |event| match event { + Event::EventStream(sender) => { + let _ = sender.unbounded_send(NetworkEvent::NotificationStreamOpened { + remote: sender_id, + protocol: grandpa_protocol_name::NAME.into(), negotiated_fallback: None, - handshake: Roles::FULL.encode(), - }, - ); - let _ = tester.notification_tx.unbounded_send( - NotificationEvent::NotificationReceived { - peer: sender_id, - notification: commit_to_send.clone(), - }, - ); + role: ObservedRole::Full, + received_handshake: vec![], + }); + let _ = sender.unbounded_send(NetworkEvent::NotificationsReceived { + remote: sender_id, + messages: vec![( + grandpa_protocol_name::NAME.into(), + commit_to_send.clone().into(), + )], + }); - tester - } - .boxed(); + true + }, + _ => false, + }); // when the commit comes in, we'll tell the callback it was bad. let handle_commit = commits_in.into_future().map(|(item, _)| match item.unwrap() { diff --git a/substrate/client/consensus/grandpa/src/lib.rs b/substrate/client/consensus/grandpa/src/lib.rs index b7cfc9f5b60..a4584e6fc80 100644 --- a/substrate/client/consensus/grandpa/src/lib.rs +++ b/substrate/client/consensus/grandpa/src/lib.rs @@ -67,7 +67,7 @@ use sc_client_api::{ BlockchainEvents, CallExecutor, ExecutorProvider, Finalizer, LockImportRun, StorageProvider, }; use sc_consensus::BlockImport; -use sc_network::{types::ProtocolName, NotificationService}; +use sc_network::types::ProtocolName; use sc_telemetry::{telemetry, TelemetryHandle, CONSENSUS_DEBUG, CONSENSUS_INFO}; use sc_transaction_pool_api::OffchainTransactionPoolFactory; use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver}; @@ -687,8 +687,6 @@ pub struct GrandpaParams { pub network: N, /// Event stream for syncing-related events. pub sync: S, - /// Handle for interacting with `Notifications`. - pub notification_service: Box, /// A voting rule used to potentially restrict target votes. pub voting_rule: VR, /// The prometheus metrics registry. @@ -709,21 +707,21 @@ pub struct GrandpaParams { /// For standard protocol name see [`crate::protocol_standard_name`]. pub fn grandpa_peers_set_config( protocol_name: ProtocolName, -) -> (sc_network::config::NonDefaultSetConfig, Box) { +) -> sc_network::config::NonDefaultSetConfig { use communication::grandpa_protocol_name; - sc_network::config::NonDefaultSetConfig::new( - protocol_name, - grandpa_protocol_name::LEGACY_NAMES.iter().map(|&n| n.into()).collect(), + sc_network::config::NonDefaultSetConfig { + notifications_protocol: protocol_name, + fallback_names: grandpa_protocol_name::LEGACY_NAMES.iter().map(|&n| n.into()).collect(), // Notifications reach ~256kiB in size at the time of writing on Kusama and Polkadot. - 1024 * 1024, - None, - sc_network::config::SetConfig { + max_notification_size: 1024 * 1024, + handshake: None, + set_config: sc_network::config::SetConfig { in_peers: 0, out_peers: 0, reserved_nodes: Vec::new(), non_reserved_mode: sc_network::config::NonReservedPeerMode::Deny, }, - ) + } } /// Run a GRANDPA voter as a task. Provide configuration and a link to a @@ -746,7 +744,6 @@ where link, network, sync, - notification_service, voting_rule, prometheus_registry, shared_voter_state, @@ -773,7 +770,6 @@ where let network = NetworkBridge::new( network, sync, - notification_service, config.clone(), persistent_data.set_state.clone(), prometheus_registry.as_ref(), diff --git a/substrate/client/consensus/grandpa/src/observer.rs b/substrate/client/consensus/grandpa/src/observer.rs index 608ff5e46a0..8541baa822b 100644 --- a/substrate/client/consensus/grandpa/src/observer.rs +++ b/substrate/client/consensus/grandpa/src/observer.rs @@ -28,7 +28,6 @@ use futures::prelude::*; use log::{debug, info, warn}; use sc_client_api::backend::Backend; -use sc_network::NotificationService; use sc_telemetry::TelemetryHandle; use sc_utils::mpsc::TracingUnboundedReceiver; use sp_blockchain::HeaderMetadata; @@ -169,7 +168,6 @@ pub fn run_grandpa_observer( link: LinkHalf, network: N, sync: S, - notification_service: Box, ) -> sp_blockchain::Result + Send> where BE: Backend + Unpin + 'static, @@ -191,7 +189,6 @@ where let network = NetworkBridge::new( network, sync, - notification_service, config.clone(), persistent_data.set_state.clone(), None, @@ -417,14 +414,14 @@ mod tests { use futures::executor; - /// Ensure `Future` implementation of `ObserverWork` is polling its `NetworkBridge`. - /// Regression test for bug introduced in d4fbb897c and fixed in b7af8b339. + /// Ensure `Future` implementation of `ObserverWork` is polling its `NetworkBridge`. Regression + /// test for bug introduced in d4fbb897c and fixed in b7af8b339. /// - /// When polled, `NetworkBridge` forwards reputation change requests from the - /// `GossipValidator` to the underlying `dyn Network`. This test triggers a reputation change - /// by calling `GossipValidator::validate` with an invalid gossip message. After polling the - /// `ObserverWork` which should poll the `NetworkBridge`, the reputation change should be - /// forwarded to the test network. + /// When polled, `NetworkBridge` forwards reputation change requests from the `GossipValidator` + /// to the underlying `dyn Network`. This test triggers a reputation change by calling + /// `GossipValidator::validate` with an invalid gossip message. After polling the `ObserverWork` + /// which should poll the `NetworkBridge`, the reputation change should be forwarded to the test + /// network. #[test] fn observer_work_polls_underlying_network_bridge() { // Create a test network. @@ -466,6 +463,12 @@ mod tests { // validator to the test network. assert!(observer.now_or_never().is_none()); + // Ignore initial event stream request by gossip engine. + match tester.events.next().now_or_never() { + Some(Some(Event::EventStream(_))) => {}, + _ => panic!("expected event stream request"), + }; + assert_matches!(tester.events.next().now_or_never(), Some(Some(Event::Report(_, _)))); }); } diff --git a/substrate/client/consensus/grandpa/src/tests.rs b/substrate/client/consensus/grandpa/src/tests.rs index 7e42c2d45c7..644befe9885 100644 --- a/substrate/client/consensus/grandpa/src/tests.rs +++ b/substrate/client/consensus/grandpa/src/tests.rs @@ -317,9 +317,6 @@ fn initialize_grandpa( (net.peers[peer_id].network_service().clone(), link) }; let sync = net.peers[peer_id].sync_service().clone(); - let notification_service = net.peers[peer_id] - .take_notification_service(&grandpa_protocol_name::NAME.into()) - .unwrap(); let grandpa_params = GrandpaParams { config: Config { @@ -335,7 +332,6 @@ fn initialize_grandpa( link, network: net_service, sync, - notification_service, voting_rule: (), prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), @@ -476,9 +472,6 @@ async fn finalize_3_voters_1_full_observer() { let net_service = net.peers[peer_id].network_service().clone(); let sync = net.peers[peer_id].sync_service().clone(); let link = net.peers[peer_id].data.lock().take().expect("link initialized at startup; qed"); - let notification_service = net.peers[peer_id] - .take_notification_service(&grandpa_protocol_name::NAME.into()) - .unwrap(); let grandpa_params = GrandpaParams { config: Config { @@ -494,7 +487,6 @@ async fn finalize_3_voters_1_full_observer() { link, network: net_service, sync, - notification_service, voting_rule: (), prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), @@ -565,17 +557,14 @@ async fn transition_3_voters_twice_1_full_observer() { for (peer_id, local_key) in all_peers.clone().into_iter().enumerate() { let keystore = create_keystore(local_key); - let (net_service, link, sync, notification_service) = { - let mut net = net.lock(); + let (net_service, link, sync) = { + let net = net.lock(); let link = net.peers[peer_id].data.lock().take().expect("link initialized at startup; qed"); ( net.peers[peer_id].network_service().clone(), link, net.peers[peer_id].sync_service().clone(), - net.peers[peer_id] - .take_notification_service(&grandpa_protocol_name::NAME.into()) - .unwrap(), ) }; @@ -593,7 +582,6 @@ async fn transition_3_voters_twice_1_full_observer() { link, network: net_service, sync, - notification_service, voting_rule: (), prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), @@ -1037,9 +1025,6 @@ async fn voter_persists_its_votes() { communication::NetworkBridge::new( net.peers[1].network_service().clone(), net.peers[1].sync_service().clone(), - net.peers[1] - .take_notification_service(&grandpa_protocol_name::NAME.into()) - .unwrap(), config.clone(), set_state, None, @@ -1058,9 +1043,6 @@ async fn voter_persists_its_votes() { (net.peers[0].network_service().clone(), link) }; let sync = net.peers[0].sync_service().clone(); - let notification_service = net.peers[0] - .take_notification_service(&grandpa_protocol_name::NAME.into()) - .unwrap(); let grandpa_params = GrandpaParams { config: Config { @@ -1076,7 +1058,6 @@ async fn voter_persists_its_votes() { link, network: net_service, sync, - notification_service, voting_rule: VotingRulesBuilder::default().build(), prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), @@ -1101,9 +1082,6 @@ async fn voter_persists_its_votes() { net.add_authority_peer(); let net_service = net.peers[2].network_service().clone(); let sync = net.peers[2].sync_service().clone(); - let notification_service = net.peers[2] - .take_notification_service(&grandpa_protocol_name::NAME.into()) - .unwrap(); // but we'll reuse the client from the first peer (alice_voter1) // since we want to share the same database, so that we can // read the persisted state after aborting alice_voter1. @@ -1126,7 +1104,6 @@ async fn voter_persists_its_votes() { link, network: net_service, sync, - notification_service, voting_rule: VotingRulesBuilder::default().build(), prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), @@ -1278,9 +1255,6 @@ async fn finalize_3_voters_1_light_observer() { let mut net = GrandpaTestNet::new(TestApi::new(voters), 3, 1); let voters = initialize_grandpa(&mut net, authorities); - let notification_service = net.peers[3] - .take_notification_service(&grandpa_protocol_name::NAME.into()) - .unwrap(); let observer = observer::run_grandpa_observer( Config { gossip_duration: TEST_GOSSIP_DURATION, @@ -1295,7 +1269,6 @@ async fn finalize_3_voters_1_light_observer() { net.peers[3].data.lock().take().expect("link initialized at startup; qed"), net.peers[3].network_service().clone(), net.peers[3].sync_service().clone(), - notification_service, ) .unwrap(); net.peer(0).push_blocks(20, false); @@ -1344,10 +1317,6 @@ async fn voter_catches_up_to_latest_round_when_behind() { link, network: net.peer(peer_id).network_service().clone(), sync: net.peer(peer_id).sync_service().clone(), - notification_service: net - .peer(peer_id) - .take_notification_service(&grandpa_protocol_name::NAME.into()) - .unwrap(), voting_rule: (), prometheus_registry: None, shared_voter_state: SharedVoterState::empty(), @@ -1440,7 +1409,6 @@ fn test_environment_with_select_chain( keystore: Option, network_service: N, sync_service: S, - notification_service: Box, select_chain: SC, voting_rule: VR, ) -> TestEnvironment @@ -1465,7 +1433,6 @@ where let network = NetworkBridge::new( network_service.clone(), sync_service, - notification_service, config.clone(), set_state.clone(), None, @@ -1495,7 +1462,6 @@ fn test_environment( keystore: Option, network_service: N, sync_service: S, - notification_service: Box, voting_rule: VR, ) -> TestEnvironment, VR> where @@ -1508,7 +1474,6 @@ where keystore, network_service, sync_service, - notification_service, link.select_chain.clone(), voting_rule, ) @@ -1525,22 +1490,14 @@ async fn grandpa_environment_respects_voting_rules() { let peer = net.peer(0); let network_service = peer.network_service().clone(); let sync_service = peer.sync_service().clone(); - let mut notification_service = - peer.take_notification_service(&grandpa_protocol_name::NAME.into()).unwrap(); let link = peer.data.lock().take().unwrap(); // add 21 blocks let hashes = peer.push_blocks(21, false); // create an environment with no voting rule restrictions - let unrestricted_env = test_environment( - &link, - None, - network_service.clone(), - sync_service.clone(), - notification_service.clone().unwrap(), - (), - ); + let unrestricted_env = + test_environment(&link, None, network_service.clone(), sync_service.clone(), ()); // another with 3/4 unfinalized chain voting rule restriction let three_quarters_env = test_environment( @@ -1548,7 +1505,6 @@ async fn grandpa_environment_respects_voting_rules() { None, network_service.clone(), sync_service.clone(), - notification_service.clone().unwrap(), voting_rule::ThreeQuartersOfTheUnfinalizedChain, ); @@ -1559,7 +1515,6 @@ async fn grandpa_environment_respects_voting_rules() { None, network_service.clone(), sync_service, - notification_service, VotingRulesBuilder::default().build(), ); @@ -1653,8 +1608,6 @@ async fn grandpa_environment_passes_actual_best_block_to_voting_rules() { let peer = net.peer(0); let network_service = peer.network_service().clone(); let sync_service = peer.sync_service().clone(); - let notification_service = - peer.take_notification_service(&grandpa_protocol_name::NAME.into()).unwrap(); let link = peer.data.lock().take().unwrap(); let client = peer.client().as_client().clone(); let select_chain = MockSelectChain::default(); @@ -1669,7 +1622,6 @@ async fn grandpa_environment_passes_actual_best_block_to_voting_rules() { None, network_service.clone(), sync_service, - notification_service, select_chain.clone(), voting_rule::BeforeBestBlockBy(5), ); @@ -1717,8 +1669,6 @@ async fn grandpa_environment_checks_if_best_block_is_descendent_of_finality_targ let peer = net.peer(0); let network_service = peer.network_service().clone(); let sync_service = peer.sync_service().clone(); - let notification_service = - peer.take_notification_service(&grandpa_protocol_name::NAME.into()).unwrap(); let link = peer.data.lock().take().unwrap(); let client = peer.client().as_client().clone(); let select_chain = MockSelectChain::default(); @@ -1728,7 +1678,6 @@ async fn grandpa_environment_checks_if_best_block_is_descendent_of_finality_targ None, network_service.clone(), sync_service.clone(), - notification_service, select_chain.clone(), voting_rule.clone(), ); @@ -1831,19 +1780,11 @@ async fn grandpa_environment_never_overwrites_round_voter_state() { let peer = net.peer(0); let network_service = peer.network_service().clone(); let sync_service = peer.sync_service().clone(); - let notification_service = - peer.take_notification_service(&grandpa_protocol_name::NAME.into()).unwrap(); let link = peer.data.lock().take().unwrap(); let keystore = create_keystore(peers[0]); - let environment = test_environment( - &link, - Some(keystore), - network_service.clone(), - sync_service, - notification_service, - (), - ); + let environment = + test_environment(&link, Some(keystore), network_service.clone(), sync_service, ()); let round_state = || finality_grandpa::round::State::genesis(Default::default()); let base = || Default::default(); @@ -2071,18 +2012,9 @@ async fn grandpa_environment_doesnt_send_equivocation_reports_for_itself() { let peer = net.peer(0); let network_service = peer.network_service().clone(); let sync_service = peer.sync_service().clone(); - let notification_service = - peer.take_notification_service(&grandpa_protocol_name::NAME.into()).unwrap(); let link = peer.data.lock().take().unwrap(); let keystore = create_keystore(alice); - test_environment( - &link, - Some(keystore), - network_service.clone(), - sync_service, - notification_service, - (), - ) + test_environment(&link, Some(keystore), network_service.clone(), sync_service, ()) }; let signed_prevote = { diff --git a/substrate/client/consensus/manual-seal/Cargo.toml b/substrate/client/consensus/manual-seal/Cargo.toml index c111f0494de..a6430fdf1de 100644 --- a/substrate/client/consensus/manual-seal/Cargo.toml +++ b/substrate/client/consensus/manual-seal/Cargo.toml @@ -9,14 +9,11 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -jsonrpsee = { version = "0.16.2", features = ["client-core", "macros", "server"] } +jsonrpsee = { version = "0.16.2", features = ["client-core", "server", "macros"] } assert_matches = "1.3.0" async-trait = "0.1.57" codec = { package = "parity-scale-codec", version = "3.6.1" } @@ -46,7 +43,7 @@ sp-runtime = { path = "../../../primitives/runtime" } sp-timestamp = { path = "../../../primitives/timestamp" } [dev-dependencies] -tokio = { version = "1.22.0", features = ["macros", "rt-multi-thread"] } +tokio = { version = "1.22.0", features = ["rt-multi-thread", "macros"] } 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" } diff --git a/substrate/client/consensus/pow/Cargo.toml b/substrate/client/consensus/pow/Cargo.toml index d5eebb23e13..ef32425685b 100644 --- a/substrate/client/consensus/pow/Cargo.toml +++ b/substrate/client/consensus/pow/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/consensus/slots/Cargo.toml b/substrate/client/consensus/slots/Cargo.toml index 29206004c23..52c528c3028 100644 --- a/substrate/client/consensus/slots/Cargo.toml +++ b/substrate/client/consensus/slots/Cargo.toml @@ -10,9 +10,6 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/db/Cargo.toml b/substrate/client/db/Cargo.toml index e833b90b3ed..cb9560b6cb6 100644 --- a/substrate/client/db/Cargo.toml +++ b/substrate/client/db/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Client backend that uses RocksDB database as storage." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -25,7 +22,7 @@ kvdb-memorydb = "0.13.0" kvdb-rocksdb = { version = "0.19.0", optional = true } linked-hash-map = "0.5.4" log = "0.4.17" -parity-db = "0.4.12" +parity-db = "0.4.8" parking_lot = "0.12.1" sc-client-api = { path = "../api" } sc-state-db = { path = "../state-db" } @@ -56,7 +53,7 @@ runtime-benchmarks = [ "kitchensink-runtime/runtime-benchmarks", "sp-runtime/runtime-benchmarks", ] -rocksdb = ["kvdb-rocksdb"] +rocksdb = [ "kvdb-rocksdb" ] [[bench]] name = "state_access" diff --git a/substrate/client/executor/Cargo.toml b/substrate/client/executor/Cargo.toml index aa8e8c9abf2..9f41b742373 100644 --- a/substrate/client/executor/Cargo.toml +++ b/substrate/client/executor/Cargo.toml @@ -10,9 +10,6 @@ description = "A crate that provides means of executing/dispatching calls into t documentation = "https://docs.rs/sc-executor" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -58,7 +55,7 @@ name = "bench" harness = false [features] -default = ["std"] +default = [ "std" ] # This crate does not have `no_std` support, we just require this for tests std = [ "sc-runtime-test/std", diff --git a/substrate/client/executor/common/Cargo.toml b/substrate/client/executor/common/Cargo.toml index b3db6a86a20..5118279b43b 100644 --- a/substrate/client/executor/common/Cargo.toml +++ b/substrate/client/executor/common/Cargo.toml @@ -10,9 +10,6 @@ description = "A set of common definitions that are needed for defining executio documentation = "https://docs.rs/sc-executor-common/" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/executor/runtime-test/Cargo.toml b/substrate/client/executor/runtime-test/Cargo.toml index 82610c4f50c..046e59c08e0 100644 --- a/substrate/client/executor/runtime-test/Cargo.toml +++ b/substrate/client/executor/runtime-test/Cargo.toml @@ -9,24 +9,21 @@ publish = false homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] 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 = { 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} [build-dependencies] substrate-wasm-builder = { path = "../../../utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "sp-core/std", "sp-io/std", diff --git a/substrate/client/executor/src/executor.rs b/substrate/client/executor/src/executor.rs index 499bb704b16..7c292a83da0 100644 --- a/substrate/client/executor/src/executor.rs +++ b/substrate/client/executor/src/executor.rs @@ -492,6 +492,7 @@ where runtime_code: &RuntimeCode, method: &str, data: &[u8], + _use_native: bool, context: CallContext, ) -> (Result>, bool) { tracing::trace!( @@ -564,8 +565,6 @@ pub struct NativeElseWasmExecutor { /// Fallback wasm executor. wasm: WasmExecutor>, - - use_native: bool, } impl NativeElseWasmExecutor { @@ -602,7 +601,7 @@ impl NativeElseWasmExecutor { .with_runtime_cache_size(runtime_cache_size) .build(); - NativeElseWasmExecutor { native_version: D::native_version(), wasm, use_native: true } + NativeElseWasmExecutor { native_version: D::native_version(), wasm } } /// Create a new instance using the given [`WasmExecutor`]. @@ -611,14 +610,7 @@ impl NativeElseWasmExecutor { ExtendedHostFunctions, >, ) -> Self { - Self { native_version: D::native_version(), wasm: executor, use_native: true } - } - - /// Disable to use native runtime when possible just behave like `WasmExecutor`. - /// - /// Default to enabled. - pub fn disable_use_native(&mut self) { - self.use_native = false; + Self { native_version: D::native_version(), wasm: executor } } /// Ignore missing function imports if set true. @@ -653,10 +645,9 @@ impl CodeExecutor for NativeElseWasmExecut runtime_code: &RuntimeCode, method: &str, data: &[u8], + use_native: bool, context: CallContext, ) -> (Result>, bool) { - let use_native = self.use_native; - tracing::trace!( target: "executor", function = %method, @@ -720,11 +711,7 @@ impl CodeExecutor for NativeElseWasmExecut impl Clone for NativeElseWasmExecutor { fn clone(&self) -> Self { - NativeElseWasmExecutor { - native_version: D::native_version(), - wasm: self.wasm.clone(), - use_native: self.use_native, - } + NativeElseWasmExecutor { native_version: D::native_version(), wasm: self.wasm.clone() } } } diff --git a/substrate/client/executor/src/lib.rs b/substrate/client/executor/src/lib.rs index 25bad81938f..6ee0ab3512a 100644 --- a/substrate/client/executor/src/lib.rs +++ b/substrate/client/executor/src/lib.rs @@ -58,7 +58,7 @@ pub use sc_executor_wasmtime::InstantiationStrategy as WasmtimeInstantiationStra /// Extracts the runtime version of a given runtime code. pub trait RuntimeVersionOf { - /// Extract [`RuntimeVersion`] of the given `runtime_code`. + /// Extract [`RuntimeVersion`](sp_version::RuntimeVersion) of the given `runtime_code`. fn runtime_version( &self, ext: &mut dyn Externalities, diff --git a/substrate/client/executor/wasmtime/Cargo.toml b/substrate/client/executor/wasmtime/Cargo.toml index f8df23a026e..261d52c0ede 100644 --- a/substrate/client/executor/wasmtime/Cargo.toml +++ b/substrate/client/executor/wasmtime/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Defines a `WasmRuntime` that uses the Wasmtime JIT to execute." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -28,7 +25,7 @@ wasmtime = { version = "8.0.1", default-features = false, features = [ "cranelift", "jitdump", "parallel-compilation", - "pooling-allocator", + "pooling-allocator" ] } anyhow = "1.0.68" sc-allocator = { path = "../../allocator" } @@ -42,7 +39,7 @@ 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 = { version = "0.36.7", default-features = false, features = ["std", "mm", "fs", "param", "use-libc"] } [dev-dependencies] wat = "1.0" diff --git a/substrate/client/executor/wasmtime/src/tests.rs b/substrate/client/executor/wasmtime/src/tests.rs index 1c06da1e3c1..e185754b076 100644 --- a/substrate/client/executor/wasmtime/src/tests.rs +++ b/substrate/client/executor/wasmtime/src/tests.rs @@ -384,9 +384,7 @@ fn test_max_memory_pages( ) (i32.const -1) ) - (then - (unreachable) - ) + (unreachable) ) (i64.const 0) @@ -423,9 +421,7 @@ fn test_max_memory_pages( ) (i32.const -1) ) - (then - (unreachable) - ) + (unreachable) ) (i64.const 0) diff --git a/substrate/client/informant/Cargo.toml b/substrate/client/informant/Cargo.toml index 8373e5a54c1..47e65df3cc1 100644 --- a/substrate/client/informant/Cargo.toml +++ b/substrate/client/informant/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/keystore/Cargo.toml b/substrate/client/keystore/Cargo.toml index 7671aac0bd7..3fd88ae8b87 100644 --- a/substrate/client/keystore/Cargo.toml +++ b/substrate/client/keystore/Cargo.toml @@ -10,9 +10,6 @@ description = "Keystore (and session key management) for ed25519 based chains li documentation = "https://docs.rs/sc-keystore" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/keystore/src/local.rs b/substrate/client/keystore/src/local.rs index 3b29f435e2a..8089dbba035 100644 --- a/substrate/client/keystore/src/local.rs +++ b/substrate/client/keystore/src/local.rs @@ -120,18 +120,18 @@ impl LocalKeystore { Ok(sig) } - fn vrf_pre_output( + fn vrf_output( &self, key_type: KeyTypeId, public: &T::Public, input: &T::VrfInput, - ) -> std::result::Result, TraitError> { - let pre_output = self + ) -> std::result::Result, TraitError> { + let preout = self .0 .read() .key_pair_by_type::(public, key_type)? - .map(|pair| pair.vrf_pre_output(input)); - Ok(pre_output) + .map(|pair| pair.vrf_output(input)); + Ok(preout) } } @@ -188,13 +188,13 @@ impl Keystore for LocalKeystore { self.vrf_sign::(key_type, public, data) } - fn sr25519_vrf_pre_output( + fn sr25519_vrf_output( &self, key_type: KeyTypeId, public: &sr25519::Public, input: &sr25519::vrf::VrfInput, - ) -> std::result::Result, TraitError> { - self.vrf_pre_output::(key_type, public, input) + ) -> std::result::Result, TraitError> { + self.vrf_output::(key_type, public, input) } fn ed25519_public_keys(&self, key_type: KeyTypeId) -> Vec { @@ -293,13 +293,13 @@ impl Keystore for LocalKeystore { self.vrf_sign::(key_type, public, data) } - fn bandersnatch_vrf_pre_output( + fn bandersnatch_vrf_output( &self, key_type: KeyTypeId, public: &bandersnatch::Public, input: &bandersnatch::vrf::VrfInput, - ) -> std::result::Result, TraitError> { - self.vrf_pre_output::(key_type, public, input) + ) -> std::result::Result, TraitError> { + self.vrf_output::(key_type, public, input) } fn bandersnatch_ring_vrf_sign( diff --git a/substrate/client/merkle-mountain-range/Cargo.toml b/substrate/client/merkle-mountain-range/Cargo.toml index f6dbaf86c51..ae60fd1ce89 100644 --- a/substrate/client/merkle-mountain-range/Cargo.toml +++ b/substrate/client/merkle-mountain-range/Cargo.toml @@ -8,9 +8,6 @@ repository.workspace = true description = "MMR Client gadget for substrate" homepage = "https://substrate.io" -[lints] -workspace = true - # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] diff --git a/substrate/client/merkle-mountain-range/rpc/Cargo.toml b/substrate/client/merkle-mountain-range/rpc/Cargo.toml index d4ee0b48522..e75c5f1baa8 100644 --- a/substrate/client/merkle-mountain-range/rpc/Cargo.toml +++ b/substrate/client/merkle-mountain-range/rpc/Cargo.toml @@ -8,16 +8,13 @@ homepage = "https://substrate.io" repository.workspace = true description = "Node-specific RPC methods for interaction with Merkle Mountain Range pallet." -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1" } -jsonrpsee = { version = "0.16.2", features = ["client-core", "macros", "server"] } -serde = { version = "1.0.193", features = ["derive"] } +jsonrpsee = { version = "0.16.2", features = ["client-core", "server", "macros"] } +serde = { version = "1.0.188", features = ["derive"] } sp-api = { path = "../../../primitives/api" } sp-blockchain = { path = "../../../primitives/blockchain" } sp-core = { path = "../../../primitives/core" } diff --git a/substrate/client/mixnet/Cargo.toml b/substrate/client/mixnet/Cargo.toml index e8543b5bdf2..86c5a37754a 100644 --- a/substrate/client/mixnet/Cargo.toml +++ b/substrate/client/mixnet/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository = "https://github.com/paritytech/substrate/" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,7 +16,6 @@ targets = ["x86_64-unknown-linux-gnu"] array-bytes = "4.1" arrayvec = "0.7.2" blake2 = "0.10.4" -bytes = "1" codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } futures = "0.3.25" futures-timer = "3.0.2" diff --git a/substrate/client/mixnet/src/packet_dispatcher.rs b/substrate/client/mixnet/src/packet_dispatcher.rs index 420e0c68847..856208ecb34 100644 --- a/substrate/client/mixnet/src/packet_dispatcher.rs +++ b/substrate/client/mixnet/src/packet_dispatcher.rs @@ -24,7 +24,7 @@ use libp2p_identity::PeerId; use log::{debug, warn}; use mixnet::core::{AddressedPacket, NetworkStatus, Packet, PeerId as CorePeerId}; use parking_lot::Mutex; -use sc_network::NotificationService; +use sc_network::{NetworkNotification, ProtocolName}; use std::{collections::HashMap, future::Future, sync::Arc}; const LOG_TARGET: &str = "mixnet"; @@ -77,37 +77,41 @@ pub struct ReadyPeer { } impl ReadyPeer { - /// If a future is returned, and if that future returns `Some`, this function should be - /// called again to send the next packet queued for the peer; `self` is placed in the `Some` - /// to make this straightforward. Otherwise, we have either sent or dropped all packets - /// queued for the peer, and it can be forgotten about for the time being. + /// If a future is returned, and if that future returns `Some`, this function should be called + /// again to send the next packet queued for the peer; `self` is placed in the `Some` to make + /// this straightforward. Otherwise, we have either sent or dropped all packets queued for the + /// peer, and it can be forgotten about for the time being. pub fn send_packet( self, - notification_service: &Box, + network: &impl NetworkNotification, + protocol_name: ProtocolName, ) -> Option>> { - match notification_service.message_sink(&self.id) { - None => { + match network.notification_sender(self.id, protocol_name) { + Err(err) => { debug!( target: LOG_TARGET, - "Failed to get message sink for peer ID {}", self.id, + "Failed to get notification sender for peer ID {}: {err}", self.id ); self.queue.clear(); None }, - Some(sink) => Some(async move { - let (packet, more_packets) = self.queue.pop(); - let packet = packet.expect("Should only be called if there is a packet to send"); - - match sink.send_async_notification((packet as Box<[_]>).into()).await { - Ok(_) => more_packets.then_some(self), + Ok(sender) => Some(async move { + match sender.ready().await.and_then(|mut ready| { + let (packet, more_packets) = self.queue.pop(); + let packet = + packet.expect("Should only be called if there is a packet to send"); + ready.send((packet as Box<[_]>).into())?; + Ok(more_packets) + }) { Err(err) => { debug!( target: LOG_TARGET, - "Failed to send packet to peer ID {}: {err}", self.id, + "Notification sender for peer ID {} failed: {err}", self.id ); self.queue.clear(); None }, + Ok(more_packets) => more_packets.then(|| self), } }), } diff --git a/substrate/client/mixnet/src/protocol.rs b/substrate/client/mixnet/src/protocol.rs index 955502a4856..555c267b86e 100644 --- a/substrate/client/mixnet/src/protocol.rs +++ b/substrate/client/mixnet/src/protocol.rs @@ -18,10 +18,7 @@ use super::config::Config; use mixnet::core::PACKET_SIZE; -use sc_network::{ - config::{NonDefaultSetConfig, NonReservedPeerMode, SetConfig}, - NotificationService, ProtocolName, -}; +use sc_network::{config::NonDefaultSetConfig, ProtocolName}; /// Returns the protocol name to use for the mixnet controlled by the given chain. pub fn protocol_name(genesis_hash: &[u8], fork_id: Option<&str>) -> ProtocolName { @@ -34,26 +31,12 @@ pub fn protocol_name(genesis_hash: &[u8], fork_id: Option<&str>) -> ProtocolName } /// Returns the peers set configuration for the mixnet protocol. -pub fn peers_set_config( - name: ProtocolName, - config: &Config, -) -> (NonDefaultSetConfig, Box) { - let (mut set_config, service) = NonDefaultSetConfig::new( - name, - Vec::new(), - PACKET_SIZE as u64, - None, - SetConfig { - in_peers: 0, - out_peers: 0, - reserved_nodes: Vec::new(), - non_reserved_mode: NonReservedPeerMode::Deny, - }, - ); +pub fn peers_set_config(name: ProtocolName, config: &Config) -> NonDefaultSetConfig { + let mut set_config = NonDefaultSetConfig::new(name, PACKET_SIZE as u64); if config.substrate.num_gateway_slots != 0 { // out_peers is always 0; we are only interested in connecting to mixnodes, which we do by // setting them as reserved nodes set_config.allow_non_reserved(config.substrate.num_gateway_slots, 0); } - (set_config, service) + set_config } diff --git a/substrate/client/mixnet/src/run.rs b/substrate/client/mixnet/src/run.rs index 14d188df097..09020469d5e 100644 --- a/substrate/client/mixnet/src/run.rs +++ b/substrate/client/mixnet/src/run.rs @@ -29,12 +29,11 @@ use super::{ request::{extrinsic_delay, Request, SUBMIT_EXTRINSIC}, sync_with_runtime::sync_with_runtime, }; -use bytes::Bytes; use codec::{Decode, DecodeAll, Encode}; use futures::{ future::{pending, Either}, stream::FuturesUnordered, - FutureExt, StreamExt, + StreamExt, }; use log::{debug, error, trace, warn}; use mixnet::{ @@ -44,8 +43,8 @@ use mixnet::{ }; use sc_client_api::{BlockchainEvents, HeaderBackend}; use sc_network::{ - service::traits::{NotificationEvent, ValidationResult}, - NetworkNotification, NetworkPeers, NetworkStateInfo, NotificationService, ProtocolName, + Event::{NotificationStreamClosed, NotificationStreamOpened, NotificationsReceived}, + NetworkEventStream, NetworkNotification, NetworkPeers, NetworkStateInfo, ProtocolName, }; use sc_transaction_pool_api::{ LocalTransactionPool, OffchainTransactionPoolFactory, TransactionPool, @@ -155,13 +154,12 @@ pub async fn run( protocol_name: ProtocolName, transaction_pool: Arc

, keystore: Option, - mut notification_service: Box, ) where B: Block, C: BlockchainEvents + ProvideRuntimeApi + HeaderBackend, C::Api: MixnetApi, S: SyncOracle, - N: NetworkStateInfo + NetworkNotification + NetworkPeers, + N: NetworkStateInfo + NetworkEventStream + NetworkNotification + NetworkPeers, P: TransactionPool + LocalTransactionPool + 'static, { let local_peer_id = network.local_peer_id(); @@ -191,6 +189,7 @@ pub async fn run( } else { None }; + let mut network_events = network.event_stream("mixnet").fuse(); let mut next_forward_packet_delay = MaybeInfDelay::new(None); let mut next_authored_packet_delay = MaybeInfDelay::new(None); let mut ready_peers = FuturesUnordered::new(); @@ -249,36 +248,33 @@ pub async fn run( } } - event = notification_service.next_event().fuse() => match event { - None => todo!(), - Some(NotificationEvent::ValidateInboundSubstream { result_tx, .. }) => { - let _ = result_tx.send(ValidationResult::Accept); - }, - Some(NotificationEvent::NotificationStreamOpened { peer, .. }) => { - packet_dispatcher.add_peer(&peer); - }, - Some(NotificationEvent::NotificationStreamClosed { peer }) => { - packet_dispatcher.remove_peer(&peer); - }, - Some(NotificationEvent::NotificationReceived { peer, notification }) => { - let notification: Bytes = notification.into(); - - match notification.as_ref().try_into() { - Ok(packet) => handle_packet(packet, - &mut mixnet, &mut request_manager, &mut reply_manager, - &mut extrinsic_queue, &config.substrate), - Err(_) => debug!(target: LOG_TARGET, - "Dropped incorrectly sized packet ({} bytes) from {peer}", - notification.len(), - ), + event = network_events.select_next_some() => match event { + NotificationStreamOpened { remote, protocol, .. } + if protocol == protocol_name => packet_dispatcher.add_peer(&remote), + NotificationStreamClosed { remote, protocol } + if protocol == protocol_name => packet_dispatcher.remove_peer(&remote), + NotificationsReceived { remote, messages } => { + for message in messages { + if message.0 == protocol_name { + match message.1.as_ref().try_into() { + Ok(packet) => handle_packet(packet, + &mut mixnet, &mut request_manager, &mut reply_manager, + &mut extrinsic_queue, &config.substrate), + Err(_) => debug!(target: LOG_TARGET, + "Dropped incorrectly sized packet ({} bytes) from {remote}", + message.1.len(), + ), + } + } } - }, + } + _ => () }, _ = next_forward_packet_delay => { if let Some(packet) = mixnet.pop_next_forward_packet() { if let Some(ready_peer) = packet_dispatcher.dispatch(packet) { - if let Some(fut) = ready_peer.send_packet(¬ification_service) { + if let Some(fut) = ready_peer.send_packet(&*network, protocol_name.clone()) { ready_peers.push(fut); } } @@ -292,7 +288,7 @@ pub async fn run( _ = next_authored_packet_delay => { if let Some(packet) = mixnet.pop_next_authored_packet(&packet_dispatcher) { if let Some(ready_peer) = packet_dispatcher.dispatch(packet) { - if let Some(fut) = ready_peer.send_packet(¬ification_service) { + if let Some(fut) = ready_peer.send_packet(&*network, protocol_name.clone()) { ready_peers.push(fut); } } @@ -301,7 +297,7 @@ pub async fn run( ready_peer = ready_peers.select_next_some() => { if let Some(ready_peer) = ready_peer { - if let Some(fut) = ready_peer.send_packet(¬ification_service) { + if let Some(fut) = ready_peer.send_packet(&*network, protocol_name.clone()) { ready_peers.push(fut); } } diff --git a/substrate/client/mixnet/src/sync_with_runtime.rs b/substrate/client/mixnet/src/sync_with_runtime.rs index f3be9602541..4a80b3c75f4 100644 --- a/substrate/client/mixnet/src/sync_with_runtime.rs +++ b/substrate/client/mixnet/src/sync_with_runtime.rs @@ -196,7 +196,6 @@ where #[cfg(test)] mod tests { use super::*; - use multiaddr::multiaddr; #[test] fn fixup_empty_external_addresses() { diff --git a/substrate/client/network-gossip/Cargo.toml b/substrate/client/network-gossip/Cargo.toml index d4fb416a4a0..95e26a232c1 100644 --- a/substrate/client/network-gossip/Cargo.toml +++ b/substrate/client/network-gossip/Cargo.toml @@ -10,9 +10,6 @@ repository.workspace = true documentation = "https://docs.rs/sc-network-gossip" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -32,7 +29,5 @@ sp-runtime = { path = "../../primitives/runtime" } [dev-dependencies] tokio = "1.22.0" -async-trait = "0.1.73" -codec = { package = "parity-scale-codec", version = "3.0.0", features = ["derive"] } quickcheck = { version = "1.0.3", default-features = false } substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } diff --git a/substrate/client/network-gossip/src/bridge.rs b/substrate/client/network-gossip/src/bridge.rs index 1d6a4bdd0c0..8f7d490757b 100644 --- a/substrate/client/network-gossip/src/bridge.rs +++ b/substrate/client/network-gossip/src/bridge.rs @@ -21,11 +21,7 @@ use crate::{ Network, Syncing, Validator, }; -use sc_network::{ - service::traits::{NotificationEvent, ValidationResult}, - types::ProtocolName, - NotificationService, ReputationChange, -}; +use sc_network::{event::Event, types::ProtocolName, ReputationChange}; use sc_network_sync::SyncEvent; use futures::{ @@ -52,10 +48,10 @@ pub struct GossipEngine { periodic_maintenance_interval: futures_timer::Delay, protocol: ProtocolName, + /// Incoming events from the network. + network_event_stream: Pin + Send>>, /// Incoming events from the syncing service. sync_event_stream: Pin + Send>>, - /// Handle for polling notification-related events. - notification_service: Box, /// Outgoing events to the consumer. message_sinks: HashMap>>, /// Buffered messages (see [`ForwardingState`]). @@ -85,7 +81,6 @@ impl GossipEngine { pub fn new( network: N, sync: S, - notification_service: Box, protocol: impl Into, validator: Arc>, metrics_registry: Option<&Registry>, @@ -96,16 +91,17 @@ impl GossipEngine { S: Syncing + Send + Clone + 'static, { let protocol = protocol.into(); + let network_event_stream = network.event_stream("network-gossip"); let sync_event_stream = sync.event_stream("network-gossip"); GossipEngine { state_machine: ConsensusGossip::new(validator, protocol.clone(), metrics_registry), network: Box::new(network), sync: Box::new(sync), - notification_service, periodic_maintenance_interval: futures_timer::Delay::new(PERIODIC_MAINTENANCE_INTERVAL), protocol, + network_event_stream, sync_event_stream, message_sinks: HashMap::new(), forwarding_state: ForwardingState::Idle, @@ -129,7 +125,7 @@ impl GossipEngine { /// Broadcast all messages with given topic. pub fn broadcast_topic(&mut self, topic: B::Hash, force: bool) { - self.state_machine.broadcast_topic(&mut self.notification_service, topic, force); + self.state_machine.broadcast_topic(&mut *self.network, topic, force); } /// Get data of valid, incoming messages for a topic (but might have expired meanwhile). @@ -154,21 +150,19 @@ impl GossipEngine { /// Send all messages with given topic to a peer. pub fn send_topic(&mut self, who: &PeerId, topic: B::Hash, force: bool) { - self.state_machine.send_topic(&mut self.notification_service, who, topic, force) + self.state_machine.send_topic(&mut *self.network, who, topic, force) } /// Multicast a message to all peers. pub fn gossip_message(&mut self, topic: B::Hash, message: Vec, force: bool) { - self.state_machine - .multicast(&mut self.notification_service, topic, message, force) + self.state_machine.multicast(&mut *self.network, topic, message, force) } /// Send addressed message to the given peers. The message is not kept or multicast /// later on. pub fn send_message(&mut self, who: Vec, data: Vec) { for who in &who { - self.state_machine - .send_message(&mut self.notification_service, who, data.clone()); + self.state_machine.send_message(&mut *self.network, who, data.clone()); } } @@ -179,11 +173,6 @@ impl GossipEngine { pub fn announce(&self, block: B::Hash, associated_data: Option>) { self.sync.announce_block(block, associated_data); } - - /// Consume [`GossipEngine`] and return the notification service. - pub fn take_notification_service(self) -> Box { - self.notification_service - } } impl Future for GossipEngine { @@ -195,56 +184,46 @@ impl Future for GossipEngine { 'outer: loop { match &mut this.forwarding_state { ForwardingState::Idle => { - let next_notification_event = - this.notification_service.next_event().poll_unpin(cx); + let net_event_stream = this.network_event_stream.poll_next_unpin(cx); let sync_event_stream = this.sync_event_stream.poll_next_unpin(cx); - if next_notification_event.is_pending() && sync_event_stream.is_pending() { + if net_event_stream.is_pending() && sync_event_stream.is_pending() { break } - match next_notification_event { + match net_event_stream { Poll::Ready(Some(event)) => match event { - NotificationEvent::ValidateInboundSubstream { - peer, - handshake, - result_tx, - .. - } => { - // only accept peers whose role can be determined - let result = this - .network - .peer_role(peer, handshake) - .map_or(ValidationResult::Reject, |_| ValidationResult::Accept); - let _ = result_tx.send(result); - }, - NotificationEvent::NotificationStreamOpened { - peer, handshake, .. - } => { - let Some(role) = this.network.peer_role(peer, handshake) else { - log::debug!(target: "gossip", "role for {peer} couldn't be determined"); - continue - }; - - this.state_machine.new_peer( - &mut this.notification_service, - peer, - role, - ); - }, - NotificationEvent::NotificationStreamClosed { peer } => { - this.state_machine - .peer_disconnected(&mut this.notification_service, peer); + Event::NotificationStreamOpened { remote, protocol, role, .. } => + if protocol == this.protocol { + this.state_machine.new_peer(&mut *this.network, remote, role); + }, + Event::NotificationStreamClosed { remote, protocol } => { + if protocol == this.protocol { + this.state_machine + .peer_disconnected(&mut *this.network, remote); + } }, - NotificationEvent::NotificationReceived { peer, notification } => { + Event::NotificationsReceived { remote, messages } => { + let messages = messages + .into_iter() + .filter_map(|(engine, data)| { + if engine == this.protocol { + Some(data.to_vec()) + } else { + None + } + }) + .collect(); + let to_forward = this.state_machine.on_incoming( &mut *this.network, - &mut this.notification_service, - peer, - vec![notification], + remote, + messages, ); + this.forwarding_state = ForwardingState::Busy(to_forward.into()); }, + Event::Dht(_) => {}, }, // The network event stream closed. Do the same for [`GossipValidator`]. Poll::Ready(None) => { @@ -327,7 +306,7 @@ impl Future for GossipEngine { while let Poll::Ready(()) = this.periodic_maintenance_interval.poll_unpin(cx) { this.periodic_maintenance_interval.reset(PERIODIC_MAINTENANCE_INTERVAL); - this.state_machine.tick(&mut this.notification_service); + this.state_machine.tick(&mut *this.network); this.message_sinks.retain(|_, sinks| { sinks.retain(|sink| !sink.is_closed()); @@ -349,19 +328,15 @@ impl futures::future::FusedFuture for GossipEngine { mod tests { use super::*; use crate::{multiaddr::Multiaddr, ValidationResult, ValidatorContext}; - use codec::{DecodeAll, Encode}; use futures::{ - channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender}, + channel::mpsc::{unbounded, UnboundedSender}, executor::{block_on, block_on_stream}, future::poll_fn, }; use quickcheck::{Arbitrary, Gen, QuickCheck}; use sc_network::{ - config::MultiaddrWithPeerId, - service::traits::{Direction, MessageSink, NotificationEvent}, - Event, NetworkBlock, NetworkEventStream, NetworkNotification, NetworkPeers, - NotificationSenderError, NotificationSenderT as NotificationSender, NotificationService, - Roles, + config::MultiaddrWithPeerId, NetworkBlock, NetworkEventStream, NetworkNotification, + NetworkPeers, NotificationSenderError, NotificationSenderT as NotificationSender, }; use sc_network_common::role::ObservedRole; use sc_network_sync::SyncEventStream; @@ -376,10 +351,14 @@ mod tests { use substrate_test_runtime_client::runtime::Block; #[derive(Clone, Default)] - struct TestNetwork {} + struct TestNetwork { + inner: Arc>, + } #[derive(Clone, Default)] - struct TestNetworkInner {} + struct TestNetworkInner { + event_senders: Vec>, + } impl NetworkPeers for TestNetwork { fn set_authorized_peers(&self, _peers: HashSet) { @@ -394,13 +373,9 @@ mod tests { unimplemented!(); } - fn report_peer(&self, _peer_id: PeerId, _cost_benefit: ReputationChange) {} - - fn peer_reputation(&self, _peer_id: &PeerId) -> i32 { - unimplemented!() - } + fn report_peer(&self, _who: PeerId, _cost_benefit: ReputationChange) {} - fn disconnect_peer(&self, _peer_id: PeerId, _protocol: ProtocolName) { + fn disconnect_peer(&self, _who: PeerId, _protocol: ProtocolName) { unimplemented!(); } @@ -447,17 +422,14 @@ mod tests { fn sync_num_connected(&self) -> usize { unimplemented!(); } - - fn peer_role(&self, _peer_id: PeerId, handshake: Vec) -> Option { - Roles::decode_all(&mut &handshake[..]) - .ok() - .and_then(|role| Some(ObservedRole::from(role))) - } } impl NetworkEventStream for TestNetwork { fn event_stream(&self, _name: &'static str) -> Pin + Send>> { - unimplemented!(); + let (tx, rx) = unbounded(); + self.inner.lock().unwrap().event_senders.push(tx); + + Box::pin(rx) } } @@ -529,58 +501,6 @@ mod tests { } } - #[derive(Debug)] - pub(crate) struct TestNotificationService { - rx: UnboundedReceiver, - } - - #[async_trait::async_trait] - impl sc_network::service::traits::NotificationService for TestNotificationService { - async fn open_substream(&mut self, _peer: PeerId) -> Result<(), ()> { - unimplemented!(); - } - - async fn close_substream(&mut self, _peer: PeerId) -> Result<(), ()> { - unimplemented!(); - } - - fn send_sync_notification(&self, _peer: &PeerId, _notification: Vec) { - unimplemented!(); - } - - async fn send_async_notification( - &self, - _peer: &PeerId, - _notification: Vec, - ) -> Result<(), sc_network::error::Error> { - unimplemented!(); - } - - async fn set_handshake(&mut self, _handshake: Vec) -> Result<(), ()> { - unimplemented!(); - } - - fn try_set_handshake(&mut self, _handshake: Vec) -> Result<(), ()> { - unimplemented!(); - } - - async fn next_event(&mut self) -> Option { - self.rx.next().await - } - - fn clone(&mut self) -> Result, ()> { - unimplemented!(); - } - - fn protocol(&self) -> &ProtocolName { - unimplemented!(); - } - - fn message_sink(&self, _peer: &PeerId) -> Option> { - unimplemented!(); - } - } - struct AllowAll; impl Validator for AllowAll { fn validate( @@ -601,19 +521,16 @@ mod tests { fn returns_when_network_event_stream_closes() { let network = TestNetwork::default(); let sync = Arc::new(TestSync::default()); - let (tx, rx) = unbounded(); - let notification_service = Box::new(TestNotificationService { rx }); let mut gossip_engine = GossipEngine::::new( network.clone(), sync, - notification_service, "/my_protocol", Arc::new(AllowAll {}), None, ); - // drop notification service sender side. - drop(tx); + // Drop network event stream sender side. + drop(network.inner.lock().unwrap().event_senders.pop()); block_on(poll_fn(move |ctx| { if let Poll::Pending = gossip_engine.poll_unpin(ctx) { @@ -633,37 +550,42 @@ mod tests { let remote_peer = PeerId::random(); let network = TestNetwork::default(); let sync = Arc::new(TestSync::default()); - let (mut tx, rx) = unbounded(); - let notification_service = Box::new(TestNotificationService { rx }); let mut gossip_engine = GossipEngine::::new( network.clone(), sync.clone(), - notification_service, protocol.clone(), Arc::new(AllowAll {}), None, ); + let mut event_sender = network.inner.lock().unwrap().event_senders.pop().unwrap(); + // Register the remote peer. - tx.send(NotificationEvent::NotificationStreamOpened { - peer: remote_peer, - direction: Direction::Inbound, - negotiated_fallback: None, - handshake: Roles::FULL.encode(), - }) - .await - .unwrap(); + event_sender + .start_send(Event::NotificationStreamOpened { + remote: remote_peer, + protocol: protocol.clone(), + negotiated_fallback: None, + role: ObservedRole::Authority, + received_handshake: vec![], + }) + .expect("Event stream is unbounded; qed."); let messages = vec![vec![1], vec![2]]; + let events = messages + .iter() + .cloned() + .map(|m| Event::NotificationsReceived { + remote: remote_peer, + messages: vec![(protocol.clone(), m.into())], + }) + .collect::>(); // Send first event before subscribing. - tx.send(NotificationEvent::NotificationReceived { - peer: remote_peer, - notification: messages[0].clone().into(), - }) - .await - .unwrap(); + event_sender + .start_send(events[0].clone()) + .expect("Event stream is unbounded; qed."); let mut subscribers = vec![]; for _ in 0..2 { @@ -671,12 +593,9 @@ mod tests { } // Send second event after subscribing. - tx.send(NotificationEvent::NotificationReceived { - peer: remote_peer, - notification: messages[1].clone().into(), - }) - .await - .unwrap(); + event_sender + .start_send(events[1].clone()) + .expect("Event stream is unbounded; qed."); tokio::spawn(gossip_engine); @@ -753,8 +672,6 @@ mod tests { let remote_peer = PeerId::random(); let network = TestNetwork::default(); let sync = Arc::new(TestSync::default()); - let (mut tx, rx) = unbounded(); - let notification_service = Box::new(TestNotificationService { rx }); let num_channels_per_topic = channels.iter().fold( HashMap::new(), @@ -782,7 +699,6 @@ mod tests { let mut gossip_engine = GossipEngine::::new( network.clone(), sync.clone(), - notification_service, protocol.clone(), Arc::new(TestValidator {}), None, @@ -808,18 +724,22 @@ mod tests { } } + let mut event_sender = network.inner.lock().unwrap().event_senders.pop().unwrap(); + // Register the remote peer. - tx.start_send(NotificationEvent::NotificationStreamOpened { - peer: remote_peer, - direction: Direction::Inbound, - negotiated_fallback: None, - handshake: Roles::FULL.encode(), - }) - .unwrap(); + event_sender + .start_send(Event::NotificationStreamOpened { + remote: remote_peer, + protocol: protocol.clone(), + negotiated_fallback: None, + role: ObservedRole::Authority, + received_handshake: vec![], + }) + .expect("Event stream is unbounded; qed."); // Send messages into the network event stream. for (i_notification, messages) in notifications.iter().enumerate() { - let messages: Vec> = messages + let messages = messages .into_iter() .enumerate() .map(|(i_message, Message { topic })| { @@ -832,17 +752,13 @@ mod tests { message.push(i_notification.try_into().unwrap()); message.push(i_message.try_into().unwrap()); - message.into() + (protocol.clone(), message.into()) }) .collect(); - for message in messages { - tx.start_send(NotificationEvent::NotificationReceived { - peer: remote_peer, - notification: message, - }) - .unwrap(); - } + event_sender + .start_send(Event::NotificationsReceived { remote: remote_peer, messages }) + .expect("Event stream is unbounded; qed."); } let mut received_msgs_per_topic_all_chan = HashMap::::new(); diff --git a/substrate/client/network-gossip/src/state_machine.rs b/substrate/client/network-gossip/src/state_machine.rs index 069d7cdba16..4bfb5a7d37f 100644 --- a/substrate/client/network-gossip/src/state_machine.rs +++ b/substrate/client/network-gossip/src/state_machine.rs @@ -23,7 +23,7 @@ use libp2p::PeerId; use schnellru::{ByLength, LruMap}; use prometheus_endpoint::{register, Counter, PrometheusError, Registry, U64}; -use sc_network::{types::ProtocolName, NotificationService}; +use sc_network::types::ProtocolName; use sc_network_common::role::ObservedRole; use sp_runtime::traits::{Block as BlockT, Hash, HashingFor}; use std::{collections::HashMap, iter, sync::Arc, time, time::Instant}; @@ -74,33 +74,33 @@ struct MessageEntry { /// Local implementation of `ValidatorContext`. struct NetworkContext<'g, 'p, B: BlockT> { gossip: &'g mut ConsensusGossip, - notification_service: &'p mut Box, + network: &'p mut dyn Network, } impl<'g, 'p, B: BlockT> ValidatorContext for NetworkContext<'g, 'p, B> { /// Broadcast all messages with given topic to peers that do not have it yet. fn broadcast_topic(&mut self, topic: B::Hash, force: bool) { - self.gossip.broadcast_topic(self.notification_service, topic, force); + self.gossip.broadcast_topic(self.network, topic, force); } /// Broadcast a message to all peers that have not received it previously. fn broadcast_message(&mut self, topic: B::Hash, message: Vec, force: bool) { - self.gossip.multicast(self.notification_service, topic, message, force); + self.gossip.multicast(self.network, topic, message, force); } /// Send addressed message to a peer. fn send_message(&mut self, who: &PeerId, message: Vec) { - self.notification_service.send_sync_notification(who, message); + self.network.write_notification(*who, self.gossip.protocol.clone(), message); } /// Send all messages with given topic to a peer. fn send_topic(&mut self, who: &PeerId, topic: B::Hash, force: bool) { - self.gossip.send_topic(self.notification_service, who, topic, force); + self.gossip.send_topic(self.network, who, topic, force); } } fn propagate<'a, B: BlockT, I>( - notification_service: &mut Box, + network: &mut dyn Network, protocol: ProtocolName, messages: I, intent: MessageIntent, @@ -147,7 +147,7 @@ where ?message, "Propagating message", ); - notification_service.send_sync_notification(id, message.clone()); + network.write_notification(*id, protocol.clone(), message.clone()); } } } @@ -191,12 +191,7 @@ impl ConsensusGossip { } /// Handle new connected peer. - pub fn new_peer( - &mut self, - notification_service: &mut Box, - who: PeerId, - role: ObservedRole, - ) { + pub fn new_peer(&mut self, network: &mut dyn Network, who: PeerId, role: ObservedRole) { tracing::trace!( target:"gossip", %who, @@ -207,7 +202,7 @@ impl ConsensusGossip { self.peers.insert(who, PeerConsensus { known_messages: Default::default() }); let validator = self.validator.clone(); - let mut context = NetworkContext { gossip: self, notification_service }; + let mut context = NetworkContext { gossip: self, network }; validator.new_peer(&mut context, &who, role); } @@ -238,35 +233,30 @@ impl ConsensusGossip { } /// Call when a peer has been disconnected to stop tracking gossip status. - pub fn peer_disconnected( - &mut self, - notification_service: &mut Box, - who: PeerId, - ) { + pub fn peer_disconnected(&mut self, network: &mut dyn Network, who: PeerId) { let validator = self.validator.clone(); - let mut context = NetworkContext { gossip: self, notification_service }; + let mut context = NetworkContext { gossip: self, network }; validator.peer_disconnected(&mut context, &who); self.peers.remove(&who); } /// Perform periodic maintenance - pub fn tick(&mut self, notification_service: &mut Box) { + pub fn tick(&mut self, network: &mut dyn Network) { self.collect_garbage(); if Instant::now() >= self.next_broadcast { - self.rebroadcast(notification_service); + self.rebroadcast(network); self.next_broadcast = Instant::now() + REBROADCAST_INTERVAL; } } /// Rebroadcast all messages to all peers. - fn rebroadcast(&mut self, notification_service: &mut Box) { + fn rebroadcast(&mut self, network: &mut dyn Network) { let messages = self .messages .iter() .map(|entry| (&entry.message_hash, &entry.topic, &entry.message)); - propagate( - notification_service, + network, self.protocol.clone(), messages, MessageIntent::PeriodicRebroadcast, @@ -276,12 +266,7 @@ impl ConsensusGossip { } /// Broadcast all messages with given topic. - pub fn broadcast_topic( - &mut self, - notification_service: &mut Box, - topic: B::Hash, - force: bool, - ) { + pub fn broadcast_topic(&mut self, network: &mut dyn Network, topic: B::Hash, force: bool) { let messages = self.messages.iter().filter_map(|entry| { if entry.topic == topic { Some((&entry.message_hash, &entry.topic, &entry.message)) @@ -291,7 +276,7 @@ impl ConsensusGossip { }); let intent = if force { MessageIntent::ForcedBroadcast } else { MessageIntent::Broadcast }; propagate( - notification_service, + network, self.protocol.clone(), messages, intent, @@ -342,7 +327,6 @@ impl ConsensusGossip { pub fn on_incoming( &mut self, network: &mut dyn Network, - notification_service: &mut Box, who: PeerId, messages: Vec>, ) -> Vec<(B::Hash, TopicNotification)> { @@ -383,7 +367,7 @@ impl ConsensusGossip { // validate the message let validation = { let validator = self.validator.clone(); - let mut context = NetworkContext { gossip: self, notification_service }; + let mut context = NetworkContext { gossip: self, network }; validator.validate(&mut context, &who, &message) }; @@ -430,7 +414,7 @@ impl ConsensusGossip { /// Send all messages with given topic to a peer. pub fn send_topic( &mut self, - notification_service: &mut Box, + network: &mut dyn Network, who: &PeerId, topic: B::Hash, force: bool, @@ -459,7 +443,7 @@ impl ConsensusGossip { ?entry.message, "Sending topic message", ); - notification_service.send_sync_notification(who, entry.message.clone()); + network.write_notification(*who, self.protocol.clone(), entry.message.clone()); } } } @@ -467,7 +451,7 @@ impl ConsensusGossip { /// Multicast a message to all peers. pub fn multicast( &mut self, - notification_service: &mut Box, + network: &mut dyn Network, topic: B::Hash, message: Vec, force: bool, @@ -476,7 +460,7 @@ impl ConsensusGossip { self.register_message_hashed(message_hash, topic, message.clone(), None); let intent = if force { MessageIntent::ForcedBroadcast } else { MessageIntent::Broadcast }; propagate( - notification_service, + network, self.protocol.clone(), iter::once((&message_hash, &topic, &message)), intent, @@ -487,12 +471,7 @@ impl ConsensusGossip { /// Send addressed message to a peer. The message is not kept or multicast /// later on. - pub fn send_message( - &mut self, - notification_service: &mut Box, - who: &PeerId, - message: Vec, - ) { + pub fn send_message(&mut self, network: &mut dyn Network, who: &PeerId, message: Vec) { let peer = match self.peers.get_mut(who) { None => return, Some(peer) => peer, @@ -509,7 +488,7 @@ impl ConsensusGossip { ); peer.known_messages.insert(message_hash); - notification_service.send_sync_notification(who, message) + network.write_notification(*who, self.protocol.clone(), message); } } @@ -545,9 +524,9 @@ mod tests { use crate::multiaddr::Multiaddr; use futures::prelude::*; use sc_network::{ - config::MultiaddrWithPeerId, event::Event, service::traits::NotificationEvent, MessageSink, - NetworkBlock, NetworkEventStream, NetworkNotification, NetworkPeers, - NotificationSenderError, NotificationSenderT as NotificationSender, ReputationChange, + config::MultiaddrWithPeerId, event::Event, NetworkBlock, NetworkEventStream, + NetworkNotification, NetworkPeers, NotificationSenderError, + NotificationSenderT as NotificationSender, ReputationChange, }; use sp_runtime::{ testing::{Block as RawBlock, ExtrinsicWrapper, H256}, @@ -621,15 +600,11 @@ mod tests { unimplemented!(); } - fn report_peer(&self, peer_id: PeerId, cost_benefit: ReputationChange) { - self.inner.lock().unwrap().peer_reports.push((peer_id, cost_benefit)); - } - - fn peer_reputation(&self, _peer_id: &PeerId) -> i32 { - unimplemented!() + fn report_peer(&self, who: PeerId, cost_benefit: ReputationChange) { + self.inner.lock().unwrap().peer_reports.push((who, cost_benefit)); } - fn disconnect_peer(&self, _peer_id: PeerId, _protocol: ProtocolName) { + fn disconnect_peer(&self, _who: PeerId, _protocol: ProtocolName) { unimplemented!(); } @@ -676,10 +651,6 @@ mod tests { fn sync_num_connected(&self) -> usize { unimplemented!(); } - - fn peer_role(&self, _peer_id: PeerId, _handshake: Vec) -> Option { - None - } } impl NetworkEventStream for NoOpNetwork { @@ -720,62 +691,6 @@ mod tests { } } - #[derive(Debug, Default)] - struct NoOpNotificationService {} - - #[async_trait::async_trait] - impl NotificationService for NoOpNotificationService { - /// Instruct `Notifications` to open a new substream for `peer`. - async fn open_substream(&mut self, _peer: PeerId) -> Result<(), ()> { - unimplemented!(); - } - - /// Instruct `Notifications` to close substream for `peer`. - async fn close_substream(&mut self, _peer: PeerId) -> Result<(), ()> { - unimplemented!(); - } - - /// Send synchronous `notification` to `peer`. - fn send_sync_notification(&self, _peer: &PeerId, _notification: Vec) { - unimplemented!(); - } - - /// Send asynchronous `notification` to `peer`, allowing sender to exercise backpressure. - async fn send_async_notification( - &self, - _peer: &PeerId, - _notification: Vec, - ) -> Result<(), sc_network::error::Error> { - unimplemented!(); - } - - /// Set handshake for the notification protocol replacing the old handshake. - async fn set_handshake(&mut self, _handshake: Vec) -> Result<(), ()> { - unimplemented!(); - } - - fn try_set_handshake(&mut self, _handshake: Vec) -> Result<(), ()> { - unimplemented!(); - } - - /// Get next event from the `Notifications` event stream. - async fn next_event(&mut self) -> Option { - None - } - - fn clone(&mut self) -> Result, ()> { - unimplemented!(); - } - - fn protocol(&self) -> &ProtocolName { - unimplemented!(); - } - - fn message_sink(&self, _peer: &PeerId) -> Option> { - unimplemented!(); - } - } - #[test] fn collects_garbage() { struct AllowOne; @@ -858,28 +773,20 @@ mod tests { fn peer_is_removed_on_disconnect() { let mut consensus = ConsensusGossip::::new(Arc::new(AllowAll), "/foo".into(), None); - let mut notification_service: Box = - Box::new(NoOpNotificationService::default()); + let mut network = NoOpNetwork::default(); let peer_id = PeerId::random(); - consensus.new_peer(&mut notification_service, peer_id, ObservedRole::Full); + consensus.new_peer(&mut network, peer_id, ObservedRole::Full); assert!(consensus.peers.contains_key(&peer_id)); - consensus.peer_disconnected(&mut notification_service, peer_id); + consensus.peer_disconnected(&mut network, peer_id); assert!(!consensus.peers.contains_key(&peer_id)); } #[test] fn on_incoming_ignores_discarded_messages() { - let mut notification_service: Box = - Box::new(NoOpNotificationService::default()); let to_forward = ConsensusGossip::::new(Arc::new(DiscardAll), "/foo".into(), None) - .on_incoming( - &mut NoOpNetwork::default(), - &mut notification_service, - PeerId::random(), - vec![vec![1, 2, 3]], - ); + .on_incoming(&mut NoOpNetwork::default(), PeerId::random(), vec![vec![1, 2, 3]]); assert!( to_forward.is_empty(), @@ -891,14 +798,11 @@ mod tests { #[test] fn on_incoming_ignores_unregistered_peer() { let mut network = NoOpNetwork::default(); - let mut notification_service: Box = - Box::new(NoOpNotificationService::default()); let remote = PeerId::random(); let to_forward = ConsensusGossip::::new(Arc::new(AllowAll), "/foo".into(), None) .on_incoming( &mut network, - &mut notification_service, // Unregistered peer. remote, vec![vec![1, 2, 3]], @@ -918,20 +822,18 @@ mod tests { let mut consensus = ConsensusGossip::::new(Arc::new(AllowAll), "/foo".into(), None); let mut network = NoOpNetwork::default(); - let mut notification_service: Box = - Box::new(NoOpNotificationService::default()); let peer_id = PeerId::random(); - consensus.new_peer(&mut notification_service, peer_id, ObservedRole::Full); + consensus.new_peer(&mut network, peer_id, ObservedRole::Full); assert!(consensus.peers.contains_key(&peer_id)); let peer_id2 = PeerId::random(); - consensus.new_peer(&mut notification_service, peer_id2, ObservedRole::Full); + consensus.new_peer(&mut network, peer_id2, ObservedRole::Full); assert!(consensus.peers.contains_key(&peer_id2)); let message = vec![vec![1, 2, 3]]; - consensus.on_incoming(&mut network, &mut notification_service, peer_id, message.clone()); - consensus.on_incoming(&mut network, &mut notification_service, peer_id2, message.clone()); + consensus.on_incoming(&mut network, peer_id, message.clone()); + consensus.on_incoming(&mut network, peer_id2, message.clone()); assert_eq!( vec![(peer_id, rep::GOSSIP_SUCCESS)], diff --git a/substrate/client/network/Cargo.toml b/substrate/client/network/Cargo.toml index abad2c80917..7b0536addda 100644 --- a/substrate/client/network/Cargo.toml +++ b/substrate/client/network/Cargo.toml @@ -10,9 +10,6 @@ repository.workspace = true documentation = "https://docs.rs/sc-network" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -28,7 +25,7 @@ fnv = "1.0.6" futures = "0.3.21" futures-timer = "3.0.2" ip_network = "0.4.1" -libp2p = { version = "0.51.3", features = ["dns", "identify", "kad", "macros", "mdns", "noise", "ping", "request-response", "tcp", "tokio", "websocket", "yamux"] } +libp2p = { version = "0.51.3", features = ["dns", "identify", "kad", "macros", "mdns", "noise", "ping", "tcp", "tokio", "yamux", "websocket", "request-response"] } linked_hash_set = "0.1.3" log = "0.4.17" mockall = "0.11.3" @@ -36,13 +33,11 @@ parking_lot = "0.12.1" partial_sort = "0.2.0" pin-project = "1.0.12" rand = "0.8.5" -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.108" smallvec = "1.11.0" thiserror = "1.0" -tokio = { version = "1.22.0", features = ["macros", "sync"] } -tokio-stream = "0.1.7" -unsigned-varint = { version = "0.7.1", features = ["asynchronous_codec", "futures"] } +unsigned-varint = { version = "0.7.1", features = ["futures", "asynchronous_codec"] } zeroize = "1.4.3" prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } sc-client-api = { path = "../api" } diff --git a/substrate/client/network/bitswap/Cargo.toml b/substrate/client/network/bitswap/Cargo.toml index cc919d2977e..412d603163d 100644 --- a/substrate/client/network/bitswap/Cargo.toml +++ b/substrate/client/network/bitswap/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true documentation = "https://docs.rs/sc-network-bitswap" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -26,7 +23,7 @@ libp2p-identity = { version = "0.1.3", features = ["peerid"] } log = "0.4.17" prost = "0.11" thiserror = "1.0" -unsigned-varint = { version = "0.7.1", features = ["asynchronous_codec", "futures"] } +unsigned-varint = { version = "0.7.1", features = ["futures", "asynchronous_codec"] } sc-client-api = { path = "../../api" } sc-network = { path = ".." } sp-blockchain = { path = "../../../primitives/blockchain" } diff --git a/substrate/client/network/common/Cargo.toml b/substrate/client/network/common/Cargo.toml index 5b0eb5510a5..65c8e1d71c7 100644 --- a/substrate/client/network/common/Cargo.toml +++ b/substrate/client/network/common/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true documentation = "https://docs.rs/sc-network-sync" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/network/common/src/role.rs b/substrate/client/network/common/src/role.rs index 11b7a7924c4..fd02c00e232 100644 --- a/substrate/client/network/common/src/role.rs +++ b/substrate/client/network/common/src/role.rs @@ -28,7 +28,7 @@ use codec::{self, Encode, EncodeLike, Input, Output}; /// > **Note**: This enum is different from the `Role` enum. The `Role` enum indicates what a /// > node says about itself, while `ObservedRole` is a `Role` merged with the /// > information known locally about that node. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Clone)] pub enum ObservedRole { /// Full node. Full, @@ -45,18 +45,6 @@ impl ObservedRole { } } -impl From for ObservedRole { - fn from(roles: Roles) -> Self { - if roles.is_authority() { - ObservedRole::Authority - } else if roles.is_full() { - ObservedRole::Full - } else { - ObservedRole::Light - } - } -} - /// Role of the local node. #[derive(Debug, Clone)] pub enum Role { diff --git a/substrate/client/network/light/Cargo.toml b/substrate/client/network/light/Cargo.toml index c75d14f0deb..f426cda7fc8 100644 --- a/substrate/client/network/light/Cargo.toml +++ b/substrate/client/network/light/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true documentation = "https://docs.rs/sc-network-light" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -22,7 +19,7 @@ prost-build = "0.11" async-channel = "1.8.0" array-bytes = "6.1" codec = { package = "parity-scale-codec", version = "3.6.1", features = [ - "derive", + "derive", ] } futures = "0.3.21" libp2p-identity = { version = "0.1.3", features = ["peerid"] } diff --git a/substrate/client/network/src/behaviour.rs b/substrate/client/network/src/behaviour.rs index 745550412fc..0aa724818e0 100644 --- a/substrate/client/network/src/behaviour.rs +++ b/substrate/client/network/src/behaviour.rs @@ -22,13 +22,12 @@ use crate::{ peer_info, peer_store::PeerStoreHandle, protocol::{CustomMessageOutcome, NotificationsSink, Protocol}, - protocol_controller::SetId, request_responses::{self, IfDisconnected, ProtocolConfig, RequestFailure}, - service::traits::Direction, types::ProtocolName, ReputationChange, }; +use bytes::Bytes; use futures::channel::oneshot; use libp2p::{ core::Multiaddr, identify::Info as IdentifyInfo, identity::PublicKey, kad::RecordKey, @@ -36,10 +35,11 @@ use libp2p::{ }; use parking_lot::Mutex; +use sc_network_common::role::{ObservedRole, Roles}; use sp_runtime::traits::Block as BlockT; use std::{collections::HashSet, sync::Arc, time::Duration}; -pub use crate::request_responses::{InboundFailure, OutboundFailure, ResponseFailure}; +pub use crate::request_responses::{InboundFailure, OutboundFailure, RequestId, ResponseFailure}; /// General behaviour of the network. Combines all protocols together. #[derive(NetworkBehaviour)] @@ -97,10 +97,8 @@ pub enum BehaviourOut { NotificationStreamOpened { /// Node we opened the substream with. remote: PeerId, - /// Set ID. - set_id: SetId, - /// Direction of the stream. - direction: Direction, + /// The concerned protocol. Each protocol uses a different substream. + protocol: ProtocolName, /// If the negotiation didn't use the main name of the protocol (the one in /// `notifications_protocol`), then this field contains which name has actually been /// used. @@ -108,6 +106,8 @@ pub enum BehaviourOut { negotiated_fallback: Option, /// Object that permits sending notifications to the peer. notifications_sink: NotificationsSink, + /// Role of the remote. + role: ObservedRole, /// Received handshake. received_handshake: Vec, }, @@ -120,8 +120,8 @@ pub enum BehaviourOut { NotificationStreamReplaced { /// Id of the peer we are connected to. remote: PeerId, - /// Set ID. - set_id: SetId, + /// The concerned protocol. Each protocol uses a different substream. + protocol: ProtocolName, /// Replacement for the previous [`NotificationsSink`]. notifications_sink: NotificationsSink, }, @@ -131,18 +131,16 @@ pub enum BehaviourOut { NotificationStreamClosed { /// Node we closed the substream with. remote: PeerId, - /// Set ID. - set_id: SetId, + /// The concerned protocol. Each protocol uses a different substream. + protocol: ProtocolName, }, /// Received one or more messages from the given node using the given protocol. NotificationsReceived { /// Node we received the message from. remote: PeerId, - /// Set ID. - set_id: SetId, /// Concerned protocol and associated message. - notification: Vec, + messages: Vec<(ProtocolName, Bytes)>, }, /// We have obtained identity information from a peer, including the addresses it is listening @@ -274,33 +272,44 @@ impl Behaviour { } } +fn reported_roles_to_observed_role(roles: Roles) -> ObservedRole { + if roles.is_authority() { + ObservedRole::Authority + } else if roles.is_full() { + ObservedRole::Full + } else { + ObservedRole::Light + } +} + impl From for BehaviourOut { fn from(event: CustomMessageOutcome) -> Self { match event { CustomMessageOutcome::NotificationStreamOpened { remote, - set_id, - direction, + protocol, negotiated_fallback, + roles, received_handshake, notifications_sink, } => BehaviourOut::NotificationStreamOpened { remote, - set_id, - direction, + protocol, negotiated_fallback, + role: reported_roles_to_observed_role(roles), received_handshake, notifications_sink, }, CustomMessageOutcome::NotificationStreamReplaced { remote, - set_id, + protocol, notifications_sink, - } => BehaviourOut::NotificationStreamReplaced { remote, set_id, notifications_sink }, - CustomMessageOutcome::NotificationStreamClosed { remote, set_id } => - BehaviourOut::NotificationStreamClosed { remote, set_id }, - CustomMessageOutcome::NotificationsReceived { remote, set_id, notification } => - BehaviourOut::NotificationsReceived { remote, set_id, notification }, + } => BehaviourOut::NotificationStreamReplaced { remote, protocol, notifications_sink }, + CustomMessageOutcome::NotificationStreamClosed { remote, protocol } => + BehaviourOut::NotificationStreamClosed { remote, protocol }, + CustomMessageOutcome::NotificationsReceived { remote, messages } => + BehaviourOut::NotificationsReceived { remote, messages }, + CustomMessageOutcome::None => BehaviourOut::None, } } } diff --git a/substrate/client/network/src/config.rs b/substrate/client/network/src/config.rs index 24e96843c32..124d73a74db 100644 --- a/substrate/client/network/src/config.rs +++ b/substrate/client/network/src/config.rs @@ -23,11 +23,10 @@ pub use crate::{ discovery::DEFAULT_KADEMLIA_REPLICATION_FACTOR, - protocol::{notification_service, NotificationsSink, ProtocolHandlePair}, + protocol::NotificationsSink, request_responses::{ IncomingRequest, OutgoingResponse, ProtocolConfig as RequestResponseConfig, }, - service::traits::NotificationService, types::ProtocolName, }; @@ -48,6 +47,7 @@ pub use sc_network_common::{ ExHashT, }; +use sc_utils::mpsc::TracingUnboundedSender; use sp_runtime::traits::Block as BlockT; use std::{ @@ -454,14 +454,14 @@ impl Default for SetConfig { /// /// > **Note**: As new fields might be added in the future, please consider using the `new` method /// > and modifiers instead of creating this struct manually. -#[derive(Debug)] +#[derive(Clone, Debug)] pub struct NonDefaultSetConfig { /// Name of the notifications protocols of this set. A substream on this set will be /// considered established once this protocol is open. /// /// > **Note**: This field isn't present for the default set, as this is handled internally /// > by the networking code. - protocol_name: ProtocolName, + pub notifications_protocol: ProtocolName, /// If the remote reports that it doesn't support the protocol indicated in the /// `notifications_protocol` field, then each of these fallback names will be tried one by @@ -469,84 +469,37 @@ pub struct NonDefaultSetConfig { /// /// If a fallback is used, it will be reported in /// `sc_network::protocol::event::Event::NotificationStreamOpened::negotiated_fallback` - fallback_names: Vec, + pub fallback_names: Vec, /// Handshake of the protocol /// /// NOTE: Currently custom handshakes are not fully supported. See issue #5685 for more /// details. This field is temporarily used to allow moving the hardcoded block announcement /// protocol out of `protocol.rs`. - handshake: Option, + pub handshake: Option, /// Maximum allowed size of single notifications. - max_notification_size: u64, + pub max_notification_size: u64, /// Base configuration. - set_config: SetConfig, - - /// Notification handle. - /// - /// Notification handle is created during `NonDefaultSetConfig` creation and its other half, - /// `Box` is given to the protocol created the config and - /// `ProtocolHandle` is given to `Notifications` when it initializes itself. This handle allows - /// `Notifications ` to communicate with the protocol directly without relaying events through - /// `sc-network.` - protocol_handle_pair: ProtocolHandlePair, + pub set_config: SetConfig, } impl NonDefaultSetConfig { /// Creates a new [`NonDefaultSetConfig`]. Zero slots and accepts only reserved nodes. - /// Also returns an object which allows the protocol to communicate with `Notifications`. - pub fn new( - protocol_name: ProtocolName, - fallback_names: Vec, - max_notification_size: u64, - handshake: Option, - set_config: SetConfig, - ) -> (Self, Box) { - let (protocol_handle_pair, notification_service) = - notification_service(protocol_name.clone()); - ( - Self { - protocol_name, - max_notification_size, - fallback_names, - handshake, - set_config, - protocol_handle_pair, + pub fn new(notifications_protocol: ProtocolName, max_notification_size: u64) -> Self { + Self { + notifications_protocol, + max_notification_size, + fallback_names: Vec::new(), + handshake: None, + set_config: SetConfig { + in_peers: 0, + out_peers: 0, + reserved_nodes: Vec::new(), + non_reserved_mode: NonReservedPeerMode::Deny, }, - notification_service, - ) - } - - /// Get reference to protocol name. - pub fn protocol_name(&self) -> &ProtocolName { - &self.protocol_name - } - - /// Get reference to fallback protocol names. - pub fn fallback_names(&self) -> impl Iterator { - self.fallback_names.iter() - } - - /// Get reference to handshake. - pub fn handshake(&self) -> &Option { - &self.handshake - } - - /// Get maximum notification size. - pub fn max_notification_size(&self) -> u64 { - self.max_notification_size - } - - /// Get reference to `SetConfig`. - pub fn set_config(&self) -> &SetConfig { - &self.set_config - } - - /// Take `ProtocolHandlePair` from `NonDefaultSetConfig` - pub fn take_protocol_handle(self) -> ProtocolHandlePair { - self.protocol_handle_pair + } } /// Modifies the configuration to allow non-reserved nodes. @@ -750,6 +703,9 @@ pub struct Params { /// Block announce protocol configuration pub block_announce_config: NonDefaultSetConfig, + + /// TX channel for direct communication with `SyncingEngine` and `Protocol`. + pub tx: TracingUnboundedSender>, } /// Full network configuration. diff --git a/substrate/client/network/src/error.rs b/substrate/client/network/src/error.rs index 01e8356fb55..f0828fb821f 100644 --- a/substrate/client/network/src/error.rs +++ b/substrate/client/network/src/error.rs @@ -68,15 +68,6 @@ pub enum Error { /// Name of the protocol registered multiple times. protocol: ProtocolName, }, - /// Peer does not exist. - #[error("Peer `{0}` does not exist.")] - PeerDoesntExist(PeerId), - /// Channel closed. - #[error("Channel closed")] - ChannelClosed, - /// Connection closed. - #[error("Connection closed")] - ConnectionClosed, } // Make `Debug` use the `Display` implementation. diff --git a/substrate/client/network/src/event.rs b/substrate/client/network/src/event.rs index dc4fd53a49a..2913f0b5522 100644 --- a/substrate/client/network/src/event.rs +++ b/substrate/client/network/src/event.rs @@ -19,12 +19,14 @@ //! Network event types. These are 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; +use crate::{types::ProtocolName, NotificationsSink}; use bytes::Bytes; +use futures::channel::oneshot; use libp2p::{kad::record::Key, PeerId}; -use sc_network_common::role::ObservedRole; +use sc_network_common::{role::ObservedRole, sync::message::BlockAnnouncesHandshake}; +use sp_runtime::traits::Block as BlockT; /// Events generated by DHT as a response to get_value and put_value requests. #[derive(Debug, Clone)] @@ -90,3 +92,46 @@ pub enum Event { messages: Vec<(ProtocolName, Bytes)>, }, } + +/// Event sent to `SyncingEngine` +// TODO: remove once `NotificationService` is implemented. +pub enum SyncEvent { + /// Opened a substream with the given node with the given notifications protocol. + /// + /// The protocol is always one of the notification protocols that have been registered. + NotificationStreamOpened { + /// Node we opened the substream with. + remote: PeerId, + /// Received handshake. + received_handshake: BlockAnnouncesHandshake, + /// Notification sink. + sink: NotificationsSink, + /// Is the connection inbound. + inbound: bool, + /// Channel for reporting accept/reject of the substream. + tx: oneshot::Sender, + }, + + /// Closed a substream with the given node. Always matches a corresponding previous + /// `NotificationStreamOpened` message. + NotificationStreamClosed { + /// Node we closed the substream with. + remote: PeerId, + }, + + /// Notification sink was replaced. + NotificationSinkReplaced { + /// Node we closed the substream with. + remote: PeerId, + /// Notification sink. + sink: NotificationsSink, + }, + + /// Received one or more messages from the given node using the given protocol. + NotificationsReceived { + /// Node we received the message from. + remote: PeerId, + /// Concerned protocol and associated message. + messages: Vec, + }, +} diff --git a/substrate/client/network/src/lib.rs b/substrate/client/network/src/lib.rs index 4c39c57e8df..4dc9bdb4cc1 100644 --- a/substrate/client/network/src/lib.rs +++ b/substrate/client/network/src/lib.rs @@ -244,6 +244,7 @@ mod behaviour; mod protocol; +mod service; #[cfg(test)] mod mock; @@ -257,30 +258,25 @@ pub mod peer_info; pub mod peer_store; pub mod protocol_controller; pub mod request_responses; -pub mod service; pub mod transport; pub mod types; pub mod utils; -pub use event::{DhtEvent, Event}; +pub use event::{DhtEvent, Event, SyncEvent}; #[doc(inline)] pub use libp2p::{multiaddr, Multiaddr, PeerId}; pub use request_responses::{Config, IfDisconnected, RequestFailure}; -pub use sc_network_common::{ - role::{ObservedRole, Roles}, - types::ReputationChange, -}; +pub use sc_network_common::{role::ObservedRole, types::ReputationChange}; pub use service::{ signature::Signature, traits::{ - KademliaKey, MessageSink, NetworkBlock, NetworkDHTProvider, NetworkEventStream, - NetworkNotification, NetworkPeers, NetworkRequest, NetworkSigner, NetworkStateInfo, - NetworkStatus, NetworkStatusProvider, NetworkSyncForkRequest, - NotificationSender as NotificationSenderT, NotificationSenderError, - NotificationSenderReady, NotificationService, + KademliaKey, NetworkBlock, NetworkDHTProvider, NetworkEventStream, NetworkNotification, + NetworkPeers, NetworkRequest, NetworkSigner, NetworkStateInfo, NetworkStatus, + NetworkStatusProvider, NetworkSyncForkRequest, NotificationSender as NotificationSenderT, + NotificationSenderError, NotificationSenderReady, }, - DecodingError, Keypair, NetworkService, NetworkWorker, NotificationSender, OutboundFailure, - PublicKey, + DecodingError, Keypair, NetworkService, NetworkWorker, NotificationSender, NotificationsSink, + OutboundFailure, PublicKey, }; pub use types::ProtocolName; diff --git a/substrate/client/network/src/mock.rs b/substrate/client/network/src/mock.rs index 534b8118970..bc596b0fa57 100644 --- a/substrate/client/network/src/mock.rs +++ b/substrate/client/network/src/mock.rs @@ -20,7 +20,6 @@ use crate::{peer_store::PeerStoreProvider, protocol_controller::ProtocolHandle, ReputationChange}; use libp2p::PeerId; -use sc_network_common::role::ObservedRole; use std::collections::HashSet; /// No-op `PeerStore`. @@ -50,14 +49,6 @@ impl PeerStoreProvider for MockPeerStore { 0 } - fn peer_role(&self, _peer_id: &PeerId) -> Option { - None - } - - fn set_peer_role(&mut self, _peer_id: &PeerId, _role: ObservedRole) { - unimplemented!(); - } - fn outgoing_candidates(&self, _count: usize, _ignored: HashSet<&PeerId>) -> Vec { unimplemented!() } diff --git a/substrate/client/network/src/peer_store.rs b/substrate/client/network/src/peer_store.rs index 4b28b8e7544..35d17e588cb 100644 --- a/substrate/client/network/src/peer_store.rs +++ b/substrate/client/network/src/peer_store.rs @@ -23,7 +23,7 @@ use libp2p::PeerId; use log::trace; use parking_lot::Mutex; use partial_sort::PartialSort; -use sc_network_common::{role::ObservedRole, types::ReputationChange}; +use sc_network_common::types::ReputationChange; use std::{ cmp::{Ord, Ordering, PartialOrd}, collections::{hash_map::Entry, HashMap, HashSet}, @@ -66,15 +66,9 @@ pub trait PeerStoreProvider: Debug + Send { /// Adjust peer reputation. fn report_peer(&mut self, peer_id: PeerId, change: ReputationChange); - /// Set peer role. - fn set_peer_role(&mut self, peer_id: &PeerId, role: ObservedRole); - /// Get peer reputation. fn peer_reputation(&self, peer_id: &PeerId) -> i32; - /// Get peer role, if available. - fn peer_role(&self, peer_id: &PeerId) -> Option; - /// Get candidates with highest reputations for initiating outgoing connections. fn outgoing_candidates(&self, count: usize, ignored: HashSet<&PeerId>) -> Vec; } @@ -102,18 +96,10 @@ impl PeerStoreProvider for PeerStoreHandle { self.inner.lock().report_peer(peer_id, change) } - fn set_peer_role(&mut self, peer_id: &PeerId, role: ObservedRole) { - self.inner.lock().set_peer_role(peer_id, role) - } - fn peer_reputation(&self, peer_id: &PeerId) -> i32 { self.inner.lock().peer_reputation(peer_id) } - fn peer_role(&self, peer_id: &PeerId) -> Option { - self.inner.lock().peer_role(peer_id) - } - fn outgoing_candidates(&self, count: usize, ignored: HashSet<&PeerId>) -> Vec { self.inner.lock().outgoing_candidates(count, ignored) } @@ -136,19 +122,13 @@ impl PeerStoreHandle { #[derive(Debug, Clone, Copy)] struct PeerInfo { - /// Reputation of the peer. reputation: i32, - - /// Instant when the peer was last updated. last_updated: Instant, - - /// Role of the peer, if known. - role: Option, } impl Default for PeerInfo { fn default() -> Self { - Self { reputation: 0, last_updated: Instant::now(), role: None } + Self { reputation: 0, last_updated: Instant::now() } } } @@ -262,27 +242,10 @@ impl PeerStoreInner { } } - fn set_peer_role(&mut self, peer_id: &PeerId, role: ObservedRole) { - log::trace!(target: LOG_TARGET, "Set {peer_id} role to {role:?}"); - - match self.peers.entry(*peer_id) { - Entry::Occupied(mut entry) => { - entry.get_mut().role = Some(role); - }, - Entry::Vacant(entry) => { - entry.insert(PeerInfo { role: Some(role), ..Default::default() }); - }, - } - } - fn peer_reputation(&self, peer_id: &PeerId) -> i32 { self.peers.get(peer_id).map_or(0, |info| info.reputation) } - fn peer_role(&self, peer_id: &PeerId) -> Option { - self.peers.get(peer_id).map_or(None, |info| info.role) - } - fn outgoing_candidates(&self, count: usize, ignored: HashSet<&PeerId>) -> Vec { let mut candidates = self .peers diff --git a/substrate/client/network/src/protocol.rs b/substrate/client/network/src/protocol.rs index 73b1cd97279..9b94f288352 100644 --- a/substrate/client/network/src/protocol.rs +++ b/substrate/client/network/src/protocol.rs @@ -20,11 +20,12 @@ use crate::{ config, error, peer_store::{PeerStoreHandle, PeerStoreProvider}, protocol_controller::{self, SetId}, - service::traits::Direction, types::ProtocolName, }; -use codec::Encode; +use bytes::Bytes; +use codec::{DecodeAll, Encode}; +use futures::{channel::oneshot, stream::FuturesUnordered, StreamExt}; use libp2p::{ core::Endpoint, swarm::{ @@ -33,23 +34,24 @@ use libp2p::{ }, Multiaddr, PeerId, }; -use log::warn; +use log::{debug, error, warn}; -use codec::DecodeAll; -use prometheus_endpoint::Registry; -use sc_network_common::role::Roles; -use sc_utils::mpsc::TracingUnboundedReceiver; +use sc_network_common::{role::Roles, sync::message::BlockAnnouncesHandshake}; +use sc_utils::mpsc::{TracingUnboundedReceiver, TracingUnboundedSender}; use sp_runtime::traits::Block as BlockT; -use std::{collections::HashSet, iter, task::Poll}; - -use notifications::{metrics, Notifications, NotificationsOut}; +use std::{ + collections::{HashMap, HashSet}, + future::Future, + iter, + pin::Pin, + task::Poll, +}; -pub(crate) use notifications::ProtocolHandle; +use message::{generic::Message as GenericMessage, Message}; +use notifications::{Notifications, NotificationsOut}; -pub use notifications::{ - notification_service, NotificationsSink, NotifsHandlerError, ProtocolHandlePair, Ready, -}; +pub use notifications::{NotificationsSink, NotifsHandlerError, Ready}; mod notifications; @@ -62,98 +64,85 @@ pub(crate) const BLOCK_ANNOUNCES_TRANSACTIONS_SUBSTREAM_SIZE: u64 = 16 * 1024 * /// Identifier of the peerset for the block announces protocol. const HARDCODED_PEERSETS_SYNC: SetId = SetId::from(0); +mod rep { + use crate::ReputationChange as Rep; + /// We received a message that failed to decode. + pub const BAD_MESSAGE: Rep = Rep::new(-(1 << 12), "Bad message"); +} + +type PendingSyncSubstreamValidation = + Pin> + Send>>; + // Lock must always be taken in order declared here. pub struct Protocol { + /// Used to report reputation changes. + peer_store_handle: PeerStoreHandle, /// Handles opening the unique substream and sending and receiving raw messages. behaviour: Notifications, /// List of notifications protocols that have been registered. notification_protocols: Vec, - /// Handle to `PeerStore`. - peer_store_handle: PeerStoreHandle, - /// Streams for peers whose handshake couldn't be determined. - bad_handshake_streams: HashSet, - sync_handle: ProtocolHandle, + /// If we receive a new "substream open" event that contains an invalid handshake, we ask the + /// inner layer to force-close the substream. Force-closing the substream will generate a + /// "substream closed" event. This is a problem: since we can't propagate the "substream open" + /// event to the outer layers, we also shouldn't propagate this "substream closed" event. To + /// solve this, an entry is added to this map whenever an invalid handshake is received. + /// Entries are removed when the corresponding "substream closed" is later received. + bad_handshake_substreams: HashSet<(PeerId, SetId)>, + /// Connected peers on sync protocol. + peers: HashMap, + sync_substream_validations: FuturesUnordered, + tx: TracingUnboundedSender>, _marker: std::marker::PhantomData, } impl Protocol { /// Create a new instance. - pub(crate) fn new( + pub fn new( roles: Roles, - registry: &Option, notification_protocols: Vec, block_announces_protocol: config::NonDefaultSetConfig, peer_store_handle: PeerStoreHandle, protocol_controller_handles: Vec, from_protocol_controllers: TracingUnboundedReceiver, - ) -> error::Result<(Self, Vec)> { - let (behaviour, notification_protocols, handles) = { - let installed_protocols = iter::once(block_announces_protocol.protocol_name().clone()) - .chain(notification_protocols.iter().map(|p| p.protocol_name().clone())) - .collect::>(); - - // NOTE: Block announcement protocol is still very much hardcoded into - // `Protocol`. This protocol must be the first notification protocol given to - // `Notifications` - let (protocol_configs, mut handles): (Vec<_>, Vec<_>) = iter::once({ - let config = notifications::ProtocolConfig { - name: block_announces_protocol.protocol_name().clone(), - fallback_names: block_announces_protocol.fallback_names().cloned().collect(), - handshake: block_announces_protocol.handshake().as_ref().unwrap().to_vec(), - max_notification_size: block_announces_protocol.max_notification_size(), - }; - - let (handle, command_stream) = - block_announces_protocol.take_protocol_handle().split(); - - ((config, handle.clone(), command_stream), handle) - }) - .chain(notification_protocols.into_iter().map(|s| { - let config = notifications::ProtocolConfig { - name: s.protocol_name().clone(), - fallback_names: s.fallback_names().cloned().collect(), - handshake: s.handshake().as_ref().map_or(roles.encode(), |h| (*h).to_vec()), - max_notification_size: s.max_notification_size(), - }; - - let (handle, command_stream) = s.take_protocol_handle().split(); - - ((config, handle.clone(), command_stream), handle) - })) - .unzip(); - - let metrics = registry.as_ref().and_then(|registry| metrics::register(®istry).ok()); - handles.iter_mut().for_each(|handle| { - handle.set_metrics(metrics.clone()); - }); - - ( - Notifications::new( - protocol_controller_handles, - from_protocol_controllers, - metrics, - protocol_configs.into_iter(), - ), - installed_protocols, - handles, + tx: TracingUnboundedSender>, + ) -> error::Result { + let behaviour = { + Notifications::new( + protocol_controller_handles, + from_protocol_controllers, + // NOTE: Block announcement protocol is still very much hardcoded into `Protocol`. + // This protocol must be the first notification protocol given to + // `Notifications` + iter::once(notifications::ProtocolConfig { + name: block_announces_protocol.notifications_protocol.clone(), + fallback_names: block_announces_protocol.fallback_names.clone(), + handshake: block_announces_protocol.handshake.as_ref().unwrap().to_vec(), + max_notification_size: block_announces_protocol.max_notification_size, + }) + .chain(notification_protocols.iter().map(|s| notifications::ProtocolConfig { + name: s.notifications_protocol.clone(), + fallback_names: s.fallback_names.clone(), + handshake: s.handshake.as_ref().map_or(roles.encode(), |h| (*h).to_vec()), + max_notification_size: s.max_notification_size, + })), ) }; let protocol = Self { - behaviour, - sync_handle: handles[0].clone(), peer_store_handle, - notification_protocols, - bad_handshake_streams: HashSet::new(), + behaviour, + notification_protocols: iter::once(block_announces_protocol.notifications_protocol) + .chain(notification_protocols.iter().map(|s| s.notifications_protocol.clone())) + .collect(), + bad_handshake_substreams: Default::default(), + peers: HashMap::new(), + sync_substream_validations: FuturesUnordered::new(), + tx, // TODO: remove when `BlockAnnouncesHandshake` is moved away from `Protocol` _marker: Default::default(), }; - Ok((protocol, handles)) - } - - pub fn num_sync_peers(&self) -> usize { - self.sync_handle.num_peers() + Ok(protocol) } /// Returns the list of all the peers we have an open channel to. @@ -174,12 +163,21 @@ impl Protocol { } } - /// Check if role is available for `peer_id` by attempt to decode the handshake to roles and if - /// that fails, check if the role has been registered to `PeerStore`. - fn role_available(&self, peer_id: &PeerId, handshake: &Vec) -> bool { - match Roles::decode_all(&mut &handshake[..]) { - Ok(_) => true, - Err(_) => self.peer_store_handle.peer_role(&peer_id).is_some(), + /// Returns the number of peers we're connected to on sync protocol. + pub fn num_connected_peers(&self) -> usize { + self.peers.len() + } + + /// Set handshake for the notification protocol. + pub fn set_notification_handshake(&mut self, protocol: ProtocolName, handshake: Vec) { + if let Some(index) = self.notification_protocols.iter().position(|p| *p == protocol) { + self.behaviour.set_notif_protocol_handshake(SetId::from(index), handshake); + } else { + error!( + target: "sub-libp2p", + "set_notification_handshake with unknown protocol: {}", + protocol + ); } } } @@ -191,42 +189,25 @@ pub enum CustomMessageOutcome { /// Notification protocols have been opened with a remote. NotificationStreamOpened { remote: PeerId, - // protocol: ProtocolName, - set_id: SetId, - /// Direction of the stream. - direction: Direction, + protocol: ProtocolName, /// See [`crate::Event::NotificationStreamOpened::negotiated_fallback`]. negotiated_fallback: Option, - /// Received handshake. + roles: Roles, received_handshake: Vec, - /// Notification sink. notifications_sink: NotificationsSink, }, /// The [`NotificationsSink`] of some notification protocols need an update. NotificationStreamReplaced { - // Peer ID. remote: PeerId, - /// Set ID. - set_id: SetId, - /// New notification sink. + protocol: ProtocolName, notifications_sink: NotificationsSink, }, /// Notification protocols have been closed with a remote. - NotificationStreamClosed { - // Peer ID. - remote: PeerId, - /// Set ID. - set_id: SetId, - }, + NotificationStreamClosed { remote: PeerId, protocol: ProtocolName }, /// Messages have been received on one or more notifications protocols. - NotificationsReceived { - // Peer ID. - remote: PeerId, - /// Set ID. - set_id: SetId, - /// Received notification. - notification: Vec, - }, + NotificationsReceived { remote: PeerId, messages: Vec<(ProtocolName, Bytes)> }, + /// Now connected to a new peer for syncing purposes. + None, } impl NetworkBehaviour for Protocol { @@ -293,6 +274,23 @@ impl NetworkBehaviour for Protocol { cx: &mut std::task::Context, params: &mut impl PollParameters, ) -> Poll>> { + while let Poll::Ready(Some(validation_result)) = + self.sync_substream_validations.poll_next_unpin(cx) + { + match validation_result { + Ok((peer, roles)) => { + self.peers.insert(peer, roles); + }, + Err(peer) => { + log::debug!( + target: "sub-libp2p", + "`SyncingEngine` rejected stream" + ); + self.behaviour.disconnect_peer(&peer, HARDCODED_PEERSETS_SYNC); + }, + } + } + let event = match self.behaviour.poll(cx, params) { Poll::Pending => return Poll::Pending, Poll::Ready(ToSwarm::GenerateEvent(ev)) => ev, @@ -309,86 +307,204 @@ impl NetworkBehaviour for Protocol { NotificationsOut::CustomProtocolOpen { peer_id, set_id, - direction, received_handshake, notifications_sink, negotiated_fallback, - .. - } => + inbound, + } => { + // Set number 0 is hardcoded the default set of peers we sync from. if set_id == HARDCODED_PEERSETS_SYNC { - let _ = self.sync_handle.report_substream_opened( - peer_id, - direction, - received_handshake, - negotiated_fallback, - notifications_sink, - ); - None + // `received_handshake` can be either a `Status` message if received from the + // legacy substream ,or a `BlockAnnouncesHandshake` if received from the block + // announces substream. + match as DecodeAll>::decode_all(&mut &received_handshake[..]) { + Ok(GenericMessage::Status(handshake)) => { + let roles = handshake.roles; + let handshake = BlockAnnouncesHandshake:: { + roles: handshake.roles, + best_number: handshake.best_number, + best_hash: handshake.best_hash, + genesis_hash: handshake.genesis_hash, + }; + + let (tx, rx) = oneshot::channel(); + let _ = self.tx.unbounded_send( + crate::SyncEvent::NotificationStreamOpened { + inbound, + remote: peer_id, + received_handshake: handshake, + sink: notifications_sink, + tx, + }, + ); + self.sync_substream_validations.push(Box::pin(async move { + match rx.await { + Ok(accepted) => + if accepted { + Ok((peer_id, roles)) + } else { + Err(peer_id) + }, + Err(_) => Err(peer_id), + } + })); + + CustomMessageOutcome::None + }, + Ok(msg) => { + debug!( + target: "sync", + "Expected Status message from {}, but got {:?}", + peer_id, + msg, + ); + self.peer_store_handle.report_peer(peer_id, rep::BAD_MESSAGE); + CustomMessageOutcome::None + }, + Err(err) => { + match as DecodeAll>::decode_all( + &mut &received_handshake[..], + ) { + Ok(handshake) => { + let roles = handshake.roles; + + let (tx, rx) = oneshot::channel(); + let _ = self.tx.unbounded_send( + crate::SyncEvent::NotificationStreamOpened { + inbound, + remote: peer_id, + received_handshake: handshake, + sink: notifications_sink, + tx, + }, + ); + self.sync_substream_validations.push(Box::pin(async move { + match rx.await { + Ok(accepted) => + if accepted { + Ok((peer_id, roles)) + } else { + Err(peer_id) + }, + Err(_) => Err(peer_id), + } + })); + CustomMessageOutcome::None + }, + Err(err2) => { + log::debug!( + target: "sync", + "Couldn't decode handshake sent by {}: {:?}: {} & {}", + peer_id, + received_handshake, + err, + err2, + ); + self.peer_store_handle.report_peer(peer_id, rep::BAD_MESSAGE); + CustomMessageOutcome::None + }, + } + }, + } } else { - match self.role_available(&peer_id, &received_handshake) { - true => Some(CustomMessageOutcome::NotificationStreamOpened { + match ( + Roles::decode_all(&mut &received_handshake[..]), + self.peers.get(&peer_id), + ) { + (Ok(roles), _) => CustomMessageOutcome::NotificationStreamOpened { remote: peer_id, - set_id, - direction, + protocol: self.notification_protocols[usize::from(set_id)].clone(), negotiated_fallback, + roles, received_handshake, notifications_sink, - }), - false => { - self.bad_handshake_streams.insert(peer_id); - None + }, + (Err(_), Some(roles)) if received_handshake.is_empty() => { + // As a convenience, we allow opening substreams for "external" + // notification protocols with an empty handshake. This fetches the + // roles from the locally-known roles. + // TODO: remove this after https://github.com/paritytech/substrate/issues/5685 + CustomMessageOutcome::NotificationStreamOpened { + remote: peer_id, + protocol: self.notification_protocols[usize::from(set_id)].clone(), + negotiated_fallback, + roles: *roles, + received_handshake, + notifications_sink, + } + }, + (Err(err), _) => { + debug!(target: "sync", "Failed to parse remote handshake: {}", err); + self.bad_handshake_substreams.insert((peer_id, set_id)); + self.behaviour.disconnect_peer(&peer_id, set_id); + self.peer_store_handle.report_peer(peer_id, rep::BAD_MESSAGE); + CustomMessageOutcome::None }, } - }, + } + }, NotificationsOut::CustomProtocolReplaced { peer_id, notifications_sink, set_id } => - if set_id == HARDCODED_PEERSETS_SYNC { - let _ = self - .sync_handle - .report_notification_sink_replaced(peer_id, notifications_sink); - None + if self.bad_handshake_substreams.contains(&(peer_id, set_id)) { + CustomMessageOutcome::None + } else if set_id == HARDCODED_PEERSETS_SYNC { + let _ = self.tx.unbounded_send(crate::SyncEvent::NotificationSinkReplaced { + remote: peer_id, + sink: notifications_sink, + }); + CustomMessageOutcome::None } else { - (!self.bad_handshake_streams.contains(&peer_id)).then_some( - CustomMessageOutcome::NotificationStreamReplaced { - remote: peer_id, - set_id, - notifications_sink, - }, - ) + CustomMessageOutcome::NotificationStreamReplaced { + remote: peer_id, + protocol: self.notification_protocols[usize::from(set_id)].clone(), + notifications_sink, + } }, NotificationsOut::CustomProtocolClosed { peer_id, set_id } => { - if set_id == HARDCODED_PEERSETS_SYNC { - let _ = self.sync_handle.report_substream_closed(peer_id); - None + if self.bad_handshake_substreams.remove(&(peer_id, set_id)) { + // The substream that has just been closed had been opened with a bad + // handshake. The outer layers have never received an opening event about this + // substream, and consequently shouldn't receive a closing event either. + CustomMessageOutcome::None + } else if set_id == HARDCODED_PEERSETS_SYNC { + let _ = self.tx.unbounded_send(crate::SyncEvent::NotificationStreamClosed { + remote: peer_id, + }); + self.peers.remove(&peer_id); + CustomMessageOutcome::None } else { - (!self.bad_handshake_streams.remove(&peer_id)).then_some( - CustomMessageOutcome::NotificationStreamClosed { remote: peer_id, set_id }, - ) + CustomMessageOutcome::NotificationStreamClosed { + remote: peer_id, + protocol: self.notification_protocols[usize::from(set_id)].clone(), + } } }, NotificationsOut::Notification { peer_id, set_id, message } => { - if set_id == HARDCODED_PEERSETS_SYNC { - let _ = self - .sync_handle - .report_notification_received(peer_id, message.freeze().into()); - None + if self.bad_handshake_substreams.contains(&(peer_id, set_id)) { + CustomMessageOutcome::None + } else if set_id == HARDCODED_PEERSETS_SYNC { + let _ = self.tx.unbounded_send(crate::SyncEvent::NotificationsReceived { + remote: peer_id, + messages: vec![message.freeze()], + }); + CustomMessageOutcome::None } else { - (!self.bad_handshake_streams.contains(&peer_id)).then_some( - CustomMessageOutcome::NotificationsReceived { - remote: peer_id, - set_id, - notification: message.freeze().into(), - }, - ) + let protocol_name = self.notification_protocols[usize::from(set_id)].clone(); + CustomMessageOutcome::NotificationsReceived { + remote: peer_id, + messages: vec![(protocol_name, message.freeze())], + } } }, }; - match outcome { - Some(event) => Poll::Ready(ToSwarm::GenerateEvent(event)), - None => { - cx.waker().wake_by_ref(); - Poll::Pending - }, + if !matches!(outcome, CustomMessageOutcome::None) { + return Poll::Ready(ToSwarm::GenerateEvent(outcome)) } + + // This block can only be reached if an event was pulled from the behaviour and that + // resulted in `CustomMessageOutcome::None`. Since there might be another pending + // message from the behaviour, the task is scheduled again. + cx.waker().wake_by_ref(); + Poll::Pending } } diff --git a/substrate/client/network/src/protocol/message.rs b/substrate/client/network/src/protocol/message.rs index 5f2511fd6dd..66dca297537 100644 --- a/substrate/client/network/src/protocol/message.rs +++ b/substrate/client/network/src/protocol/message.rs @@ -19,13 +19,16 @@ //! Network packet message types. These get serialized and put into the lower level protocol //! payload. +pub use self::generic::{ + RemoteCallRequest, RemoteChangesRequest, RemoteChangesResponse, RemoteHeaderRequest, + RemoteHeaderResponse, RemoteReadChildRequest, RemoteReadRequest, +}; use codec::{Decode, Encode}; use sc_client_api::StorageProof; use sc_network_common::message::RequestId; use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; /// Type alias for using the message type using block type parameters. -#[allow(unused)] pub type Message = generic::Message< ::Header, ::Hash, diff --git a/substrate/client/network/src/protocol/notifications.rs b/substrate/client/network/src/protocol/notifications.rs index 8becc1390e7..aa49cfcf9d4 100644 --- a/substrate/client/network/src/protocol/notifications.rs +++ b/substrate/client/network/src/protocol/notifications.rs @@ -22,13 +22,9 @@ pub use self::{ behaviour::{Notifications, NotificationsOut, ProtocolConfig}, handler::{NotificationsSink, NotifsHandlerError, Ready}, - service::{notification_service, ProtocolHandlePair}, }; -pub(crate) use self::service::{metrics, ProtocolHandle}; - mod behaviour; mod handler; -mod service; mod tests; mod upgrade; diff --git a/substrate/client/network/src/protocol/notifications/behaviour.rs b/substrate/client/network/src/protocol/notifications/behaviour.rs index cdbf2a71b93..b78f15f8529 100644 --- a/substrate/client/network/src/protocol/notifications/behaviour.rs +++ b/substrate/client/network/src/protocol/notifications/behaviour.rs @@ -17,18 +17,16 @@ // along with this program. If not, see . use crate::{ - protocol::notifications::{ - handler::{self, NotificationsSink, NotifsHandler, NotifsHandlerIn, NotifsHandlerOut}, - service::{metrics, NotificationCommand, ProtocolHandle, ValidationCallResult}, + protocol::notifications::handler::{ + self, NotificationsSink, NotifsHandler, NotifsHandlerIn, NotifsHandlerOut, }, protocol_controller::{self, IncomingIndex, Message, SetId}, - service::traits::{Direction, ValidationResult}, types::ProtocolName, }; use bytes::BytesMut; use fnv::FnvHashMap; -use futures::{future::BoxFuture, prelude::*, stream::FuturesUnordered}; +use futures::prelude::*; use libp2p::{ core::{ConnectedPoint, Endpoint, Multiaddr}, swarm::{ @@ -38,14 +36,11 @@ use libp2p::{ }, PeerId, }; -use log::{debug, error, trace, warn}; +use log::{debug, error, info, trace, warn}; use parking_lot::RwLock; use rand::distributions::{Distribution as _, Uniform}; use sc_utils::mpsc::TracingUnboundedReceiver; use smallvec::SmallVec; -use tokio::sync::oneshot::error::RecvError; -use tokio_stream::StreamMap; - use std::{ cmp, collections::{hash_map::Entry, VecDeque}, @@ -56,13 +51,6 @@ use std::{ time::{Duration, Instant}, }; -/// Type representing a pending substream validation. -type PendingInboundValidation = - BoxFuture<'static, (Result, IncomingIndex)>; - -/// Logging target for the file. -const LOG_TARGET: &str = "sub-libp2p"; - /// Network behaviour that handles opening substreams for custom protocols with other peers. /// /// # How it works @@ -118,12 +106,6 @@ pub struct Notifications { /// Notification protocols. Entries never change after initialization. notif_protocols: Vec, - /// Protocol handles. - protocol_handles: Vec, - - // Command streams. - command_streams: StreamMap + Send + Unpin>>, - /// Protocol controllers are responsible for peer connections management. protocol_controller_handles: Vec, @@ -156,18 +138,6 @@ pub struct Notifications { /// Events to produce from `poll()`. events: VecDeque>, - - /// Pending inbound substream validations. - // - // NOTE: it's possible to read a stale response from `pending_inbound_validations` - // as the substream may get closed by the remote peer before the protocol has had - // a chance to validate it. [`Notifications`] must compare the `crate::peerset::IncomingIndex` - // returned by the completed future against the `crate::peerset::IncomingIndex` stored in - // `PeerState::Incoming` to check whether the completed future is stale or not. - pending_inbound_validations: FuturesUnordered, - - /// Metrics for notifications. - metrics: Option, } /// Configuration for a notifications protocol. @@ -265,9 +235,6 @@ enum PeerState { /// Incoming index tracking this connection. incoming_index: IncomingIndex, - /// Peerset has signaled it wants the substream closed. - peerset_rejected: bool, - /// List of connections with this peer, and their state. connections: SmallVec<[(ConnectionId, ConnectionState); crate::MAX_CONNECTIONS_PER_PEER]>, }, @@ -336,8 +303,6 @@ struct IncomingPeer { alive: bool, /// Id that the we sent to the peerset. incoming_id: IncomingIndex, - /// Received handshake. - handshake: Vec, } /// Event that can be emitted by the `Notifications`. @@ -349,8 +314,6 @@ pub enum NotificationsOut { peer_id: PeerId, /// Peerset set ID the substream is tied to. set_id: SetId, - /// Direction of the stream. - direction: Direction, /// If `Some`, a fallback protocol name has been used rather the main protocol name. /// Always matches one of the fallback names passed at initialization. negotiated_fallback: Option, @@ -401,51 +364,24 @@ pub enum NotificationsOut { impl Notifications { /// Creates a `CustomProtos`. - pub(crate) fn new( + pub fn new( protocol_controller_handles: Vec, from_protocol_controllers: TracingUnboundedReceiver, - metrics: Option, - notif_protocols: impl Iterator< - Item = ( - ProtocolConfig, - ProtocolHandle, - Box + Send + Unpin>, - ), - >, + notif_protocols: impl Iterator, ) -> Self { - let (notif_protocols, protocol_handles): (Vec<_>, Vec<_>) = notif_protocols - .map(|(cfg, protocol_handle, command_stream)| { - ( - handler::ProtocolConfig { - name: cfg.name, - fallback_names: cfg.fallback_names, - handshake: Arc::new(RwLock::new(cfg.handshake)), - max_notification_size: cfg.max_notification_size, - }, - (protocol_handle, command_stream), - ) - }) - .unzip(); - assert!(!notif_protocols.is_empty()); - - let (mut protocol_handles, command_streams): (Vec<_>, Vec<_>) = protocol_handles - .into_iter() - .enumerate() - .map(|(set_id, (mut protocol_handle, command_stream))| { - protocol_handle.set_metrics(metrics.clone()); - - (protocol_handle, (set_id, command_stream)) + let notif_protocols = notif_protocols + .map(|cfg| handler::ProtocolConfig { + name: cfg.name, + fallback_names: cfg.fallback_names, + handshake: Arc::new(RwLock::new(cfg.handshake)), + max_notification_size: cfg.max_notification_size, }) - .unzip(); + .collect::>(); - protocol_handles.iter_mut().skip(1).for_each(|handle| { - handle.delegate_to_peerset(true); - }); + assert!(!notif_protocols.is_empty()); Self { notif_protocols, - protocol_handles, - command_streams: StreamMap::from_iter(command_streams.into_iter()), protocol_controller_handles, from_protocol_controllers, peers: FnvHashMap::default(), @@ -454,8 +390,6 @@ impl Notifications { incoming: SmallVec::new(), next_incoming_index: IncomingIndex(0), events: VecDeque::new(), - pending_inbound_validations: FuturesUnordered::new(), - metrics, } } @@ -873,21 +807,14 @@ impl Notifications { *entry.into_mut() = PeerState::Backoff { timer, timer_deadline } }, - // `ProtocolController` disconnected peer while it was still being validated by the - // protocol, mark the connection as rejected and once the validation is received from - // the protocol, reject the substream - PeerState::Incoming { backoff_until, connections, incoming_index, .. } => { - debug!( + // Invalid state transitions. + st @ PeerState::Incoming { .. } => { + info!( target: "sub-libp2p", "PSM => Drop({}, {:?}): Ignoring obsolete disconnect, we are awaiting accept/reject.", entry.key().0, set_id, ); - *entry.into_mut() = PeerState::Incoming { - backoff_until, - connections, - incoming_index, - peerset_rejected: true, - }; + *entry.into_mut() = st; }, PeerState::Poisoned => { error!(target: "sub-libp2p", "State of {:?} is poisoned", entry.key()); @@ -896,71 +823,20 @@ impl Notifications { } } - /// Substream has been accepted by the `ProtocolController` and must now be sent - /// to the protocol for validation. - fn peerset_report_preaccept(&mut self, index: IncomingIndex) { - let Some(pos) = self.incoming.iter().position(|i| i.incoming_id == index) else { - error!(target: LOG_TARGET, "PSM => Preaccept({:?}): Invalid index", index); - return - }; - - trace!( - target: LOG_TARGET, - "PSM => Preaccept({:?}): Sent to protocol for validation", - index - ); - let incoming = &self.incoming[pos]; - - match self.protocol_handles[usize::from(incoming.set_id)] - .report_incoming_substream(incoming.peer_id, incoming.handshake.clone()) - { - Ok(ValidationCallResult::Delegated) => { - self.protocol_report_accept(index); - }, - Ok(ValidationCallResult::WaitForValidation(rx)) => { - self.pending_inbound_validations - .push(Box::pin(async move { (rx.await, index) })); - }, - Err(err) => { - // parachain collators enable the syncing protocol but `NotificationService` for - // `SyncingEngine` is not created which causes `report_incoming_substream()` to - // fail. This is not a fatal error and should be ignored even though in typical - // cases the `NotificationService` not existing is a fatal error and indicates that - // the protocol has exited. Until the parachain collator issue is fixed, just report - // and error and reject the peer. - debug!(target: LOG_TARGET, "protocol has exited: {err:?} {:?}", incoming.set_id); - - self.protocol_report_reject(index); - }, - } - } - /// Function that is called when the peerset wants us to accept a connection /// request from a peer. - fn protocol_report_accept(&mut self, index: IncomingIndex) { - let (pos, incoming) = - if let Some(pos) = self.incoming.iter().position(|i| i.incoming_id == index) { - (pos, self.incoming.get(pos)) - } else { - error!(target: "sub-libp2p", "PSM => Accept({:?}): Invalid index", index); - return - }; - - let Some(incoming) = incoming else { - error!(target: "sub-libp2p", "Incoming connection ({:?}) doesn't exist", index); - debug_assert!(false); - return; + fn peerset_report_accept(&mut self, index: IncomingIndex) { + let incoming = if let Some(pos) = self.incoming.iter().position(|i| i.incoming_id == index) + { + self.incoming.remove(pos) + } else { + error!(target: "sub-libp2p", "PSM => Accept({:?}): Invalid index", index); + return }; if !incoming.alive { - trace!( - target: "sub-libp2p", - "PSM => Accept({:?}, {}, {:?}): Obsolete incoming", - index, - incoming.peer_id, - incoming.set_id, - ); - + trace!(target: "sub-libp2p", "PSM => Accept({:?}, {}, {:?}): Obsolete incoming", + index, incoming.peer_id, incoming.set_id); match self.peers.get_mut(&(incoming.peer_id, incoming.set_id)) { Some(PeerState::DisabledPendingEnable { .. }) | Some(PeerState::Enabled { .. }) => { }, @@ -971,42 +847,26 @@ impl Notifications { .dropped(incoming.peer_id); }, } - - self.incoming.remove(pos); return } let state = match self.peers.get_mut(&(incoming.peer_id, incoming.set_id)) { Some(s) => s, None => { - log::debug!( - target: "sub-libp2p", - "Connection to {:?} closed, ({:?} {:?}), ignoring accept", - incoming.peer_id, - incoming.set_id, - index, - ); - self.incoming.remove(pos); + debug_assert!(false); return }, }; match mem::replace(state, PeerState::Poisoned) { // Incoming => Enabled - PeerState::Incoming { - mut connections, - incoming_index, - peerset_rejected, - backoff_until, - } => { + PeerState::Incoming { mut connections, incoming_index, .. } => { if index < incoming_index { warn!( target: "sub-libp2p", "PSM => Accept({:?}, {}, {:?}): Ignoring obsolete incoming index, we are already awaiting {:?}.", index, incoming.peer_id, incoming.set_id, incoming_index ); - - self.incoming.remove(pos); return } else if index > incoming_index { error!( @@ -1014,39 +874,12 @@ impl Notifications { "PSM => Accept({:?}, {}, {:?}): Ignoring incoming index from the future, we are awaiting {:?}.", index, incoming.peer_id, incoming.set_id, incoming_index ); - - self.incoming.remove(pos); debug_assert!(false); return } - // while the substream was being validated by the protocol, `Peerset` had request - // for the it to be closed so reject the substream now - if peerset_rejected { - trace!( - target: "sub-libp2p", - "Protocol accepted ({:?} {:?} {:?}) but Peerset had request disconnection, rejecting", - index, - incoming.peer_id, - incoming.set_id - ); - - *state = PeerState::Incoming { - connections, - backoff_until, - peerset_rejected, - incoming_index, - }; - return self.report_reject(index).map_or((), |_| ()); - } - - trace!( - target: "sub-libp2p", - "PSM => Accept({:?}, {}, {:?}): Enabling connections.", - index, - incoming.peer_id, - incoming.set_id - ); + trace!(target: "sub-libp2p", "PSM => Accept({:?}, {}, {:?}): Enabling connections.", + index, incoming.peer_id, incoming.set_id); debug_assert!(connections .iter() @@ -1065,85 +898,53 @@ impl Notifications { *connec_state = ConnectionState::Opening; } - self.incoming.remove(pos); *state = PeerState::Enabled { connections }; }, - st @ PeerState::Disabled { .. } | st @ PeerState::Backoff { .. } => { - self.incoming.remove(pos); - *state = st; - }, + // Any state other than `Incoming` is invalid. peer => { - error!( - target: "sub-libp2p", + error!(target: "sub-libp2p", "State mismatch in libp2p: Expected alive incoming. Got {:?}.", - peer - ); - - self.incoming.remove(pos); + peer); debug_assert!(false); }, } } - /// Function that is called when `ProtocolController` wants us to reject an incoming peer. - fn peerset_report_reject(&mut self, index: IncomingIndex) { - let _ = self.report_reject(index); - } - - /// Function that is called when the protocol wants us to reject an incoming peer. - fn protocol_report_reject(&mut self, index: IncomingIndex) { - if let Some((set_id, peer_id)) = self.report_reject(index) { - self.protocol_controller_handles[usize::from(set_id)].dropped(peer_id) - } - } - /// Function that is called when the peerset wants us to reject an incoming peer. - fn report_reject(&mut self, index: IncomingIndex) -> Option<(SetId, PeerId)> { + fn peerset_report_reject(&mut self, index: IncomingIndex) { let incoming = if let Some(pos) = self.incoming.iter().position(|i| i.incoming_id == index) { self.incoming.remove(pos) } else { error!(target: "sub-libp2p", "PSM => Reject({:?}): Invalid index", index); - return None + return }; if !incoming.alive { - trace!( - target: "sub-libp2p", - "PSM => Reject({:?}, {}, {:?}): Obsolete incoming, ignoring", - index, - incoming.peer_id, - incoming.set_id, - ); - - return None + trace!(target: "sub-libp2p", "PSM => Reject({:?}, {}, {:?}): Obsolete incoming, \ + ignoring", index, incoming.peer_id, incoming.set_id); + return } let state = match self.peers.get_mut(&(incoming.peer_id, incoming.set_id)) { Some(s) => s, None => { - log::debug!( - target: "sub-libp2p", - "Connection to {:?} closed, ({:?} {:?}), ignoring accept", - incoming.peer_id, - incoming.set_id, - index, - ); - return None + debug_assert!(false); + return }, }; match mem::replace(state, PeerState::Poisoned) { // Incoming => Disabled - PeerState::Incoming { mut connections, backoff_until, incoming_index, .. } => { + PeerState::Incoming { mut connections, backoff_until, incoming_index } => { if index < incoming_index { warn!( target: "sub-libp2p", "PSM => Reject({:?}, {}, {:?}): Ignoring obsolete incoming index, we are already awaiting {:?}.", index, incoming.peer_id, incoming.set_id, incoming_index ); - return None + return } else if index > incoming_index { error!( target: "sub-libp2p", @@ -1151,7 +952,7 @@ impl Notifications { index, incoming.peer_id, incoming.set_id, incoming_index ); debug_assert!(false); - return None + return } trace!(target: "sub-libp2p", "PSM => Reject({:?}, {}, {:?}): Rejecting connections.", @@ -1175,20 +976,10 @@ impl Notifications { } *state = PeerState::Disabled { connections, backoff_until }; - Some((incoming.set_id, incoming.peer_id)) - }, - // connection to peer may have been closed already - st @ PeerState::Disabled { .. } | st @ PeerState::Backoff { .. } => { - *state = st; - None - }, - peer => { - error!( - target: LOG_TARGET, - "State mismatch in libp2p: Expected alive incoming. Got {peer:?}.", - ); - None }, + peer => error!(target: "sub-libp2p", + "State mismatch in libp2p: Expected alive incoming. Got {:?}.", + peer), } } } @@ -1230,7 +1021,6 @@ impl NetworkBehaviour for Notifications { send_back_addr: remote_addr.clone(), }, self.notif_protocols.clone(), - self.metrics.clone(), )) } @@ -1245,7 +1035,6 @@ impl NetworkBehaviour for Notifications { peer, ConnectedPoint::Dialer { address: addr.clone(), role_override }, self.notif_protocols.clone(), - self.metrics.clone(), )) } @@ -1406,12 +1195,7 @@ impl NetworkBehaviour for Notifications { }, // Incoming => Incoming | Disabled | Backoff | Ø - PeerState::Incoming { - mut connections, - backoff_until, - incoming_index, - peerset_rejected, - } => { + PeerState::Incoming { mut connections, backoff_until, incoming_index } => { trace!( target: "sub-libp2p", "Libp2p => Disconnected({}, {:?}, {:?}): OpenDesiredByRemote.", @@ -1490,7 +1274,6 @@ impl NetworkBehaviour for Notifications { connections, backoff_until, incoming_index, - peerset_rejected, }; } }, @@ -1530,7 +1313,7 @@ impl NetworkBehaviour for Notifications { let event = NotificationsOut::CustomProtocolReplaced { peer_id, set_id, - notifications_sink: replacement_sink.clone(), + notifications_sink: replacement_sink, }; self.events.push_back(ToSwarm::GenerateEvent(event)); } @@ -1691,7 +1474,7 @@ impl NetworkBehaviour for Notifications { event: THandlerOutEvent, ) { match event { - NotifsHandlerOut::OpenDesiredByRemote { protocol_index, handshake } => { + NotifsHandlerOut::OpenDesiredByRemote { protocol_index } => { let set_id = SetId::from(protocol_index); trace!(target: "sub-libp2p", @@ -1712,12 +1495,7 @@ impl NetworkBehaviour for Notifications { match mem::replace(entry.get_mut(), PeerState::Poisoned) { // Incoming => Incoming - PeerState::Incoming { - mut connections, - backoff_until, - incoming_index, - peerset_rejected, - } => { + PeerState::Incoming { mut connections, backoff_until, incoming_index } => { debug_assert!(connections .iter() .any(|(_, s)| matches!(s, ConnectionState::OpenDesiredByRemote))); @@ -1745,12 +1523,8 @@ impl NetworkBehaviour for Notifications { debug_assert!(false); } - *entry.into_mut() = PeerState::Incoming { - connections, - backoff_until, - incoming_index, - peerset_rejected, - }; + *entry.into_mut() = + PeerState::Incoming { connections, backoff_until, incoming_index }; }, PeerState::Enabled { mut connections } => { @@ -1814,13 +1588,11 @@ impl NetworkBehaviour for Notifications { set_id, alive: true, incoming_id, - handshake, }); *entry.into_mut() = PeerState::Incoming { connections, backoff_until, - peerset_rejected: false, incoming_index: incoming_id, }; } else { @@ -1953,7 +1725,7 @@ impl NetworkBehaviour for Notifications { let event = NotificationsOut::CustomProtocolReplaced { peer_id, set_id, - notifications_sink: replacement_sink.clone(), + notifications_sink: replacement_sink, }; self.events.push_back(ToSwarm::GenerateEvent(event)); } @@ -2058,13 +1830,8 @@ impl NetworkBehaviour for Notifications { peer_id, set_id, inbound, - direction: if inbound { - Direction::Inbound - } else { - Direction::Outbound - }, - received_handshake: received_handshake.clone(), - negotiated_fallback: negotiated_fallback.clone(), + negotiated_fallback, + received_handshake, notifications_sink: notifications_sink.clone(), }; self.events.push_back(ToSwarm::GenerateEvent(event)); @@ -2212,11 +1979,8 @@ impl NetworkBehaviour for Notifications { peer_id, set_id, ); - let event = NotificationsOut::Notification { - peer_id, - set_id, - message: message.clone(), - }; + let event = NotificationsOut::Notification { peer_id, set_id, message }; + self.events.push_back(ToSwarm::GenerateEvent(event)); } else { trace!( @@ -2245,10 +2009,10 @@ impl NetworkBehaviour for Notifications { loop { match futures::Stream::poll_next(Pin::new(&mut self.from_protocol_controllers), cx) { Poll::Ready(Some(Message::Accept(index))) => { - self.peerset_report_preaccept(index); + self.peerset_report_accept(index); }, Poll::Ready(Some(Message::Reject(index))) => { - let _ = self.peerset_report_reject(index); + self.peerset_report_reject(index); }, Poll::Ready(Some(Message::Connect { peer_id, set_id, .. })) => { self.peerset_report_connect(peer_id, set_id); @@ -2267,43 +2031,6 @@ impl NetworkBehaviour for Notifications { } } - // poll commands from protocols - loop { - match futures::Stream::poll_next(Pin::new(&mut self.command_streams), cx) { - Poll::Ready(Some((set_id, command))) => match command { - NotificationCommand::SetHandshake(handshake) => { - self.set_notif_protocol_handshake(set_id.into(), handshake); - }, - NotificationCommand::OpenSubstream(_peer) | - NotificationCommand::CloseSubstream(_peer) => { - todo!("substream control not implemented"); - }, - }, - Poll::Ready(None) => { - error!(target: LOG_TARGET, "Protocol command streams have been shut down"); - break - }, - Poll::Pending => break, - } - } - - while let Poll::Ready(Some((result, index))) = - self.pending_inbound_validations.poll_next_unpin(cx) - { - match result { - Ok(ValidationResult::Accept) => { - self.protocol_report_accept(index); - }, - Ok(ValidationResult::Reject) => { - self.protocol_report_reject(index); - }, - Err(_) => { - error!(target: LOG_TARGET, "Protocol has shut down"); - break - }, - } - } - while let Poll::Ready(Some((delay_id, peer_id, set_id))) = Pin::new(&mut self.delays).poll_next(cx) { @@ -2426,10 +2153,7 @@ mod tests { } } - fn development_notifs( - ) -> (Notifications, ProtocolController, Box) { - let (protocol_handle_pair, notif_service) = - crate::protocol::notifications::service::notification_service("/proto/1".into()); + fn development_notifs() -> (Notifications, ProtocolController) { let (to_notifications, from_controller) = tracing_unbounded("test_controller_to_notifications", 10_000); @@ -2445,31 +2169,24 @@ mod tests { Box::new(MockPeerStore {}), ); - let (notif_handle, command_stream) = protocol_handle_pair.split(); ( Notifications::new( vec![handle], from_controller, - None, - iter::once(( - ProtocolConfig { - name: "/foo".into(), - fallback_names: Vec::new(), - handshake: vec![1, 2, 3, 4], - max_notification_size: u64::MAX, - }, - notif_handle, - command_stream, - )), + iter::once(ProtocolConfig { + name: "/foo".into(), + fallback_names: Vec::new(), + handshake: vec![1, 2, 3, 4], + max_notification_size: u64::MAX, + }), ), controller, - notif_service, ) } #[test] fn update_handshake() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let inner = notif.notif_protocols.get_mut(0).unwrap().handshake.read().clone(); assert_eq!(inner, vec![1, 2, 3, 4]); @@ -2484,14 +2201,14 @@ mod tests { #[should_panic] #[cfg(debug_assertions)] fn update_unknown_handshake() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); notif.set_notif_protocol_handshake(1337.into(), vec![5, 6, 7, 8]); } #[test] fn disconnect_backoff_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); notif.peers.insert( @@ -2508,7 +2225,7 @@ mod tests { #[test] fn disconnect_pending_request() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); notif.peers.insert( @@ -2525,7 +2242,7 @@ mod tests { #[test] fn disconnect_requested_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); notif.peers.insert((peer, 0.into()), PeerState::Requested); @@ -2536,7 +2253,7 @@ mod tests { #[test] fn disconnect_disabled_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); notif.peers.insert( (peer, 0.into()), @@ -2552,7 +2269,7 @@ mod tests { #[test] fn remote_opens_connection_and_substream() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let connected = ConnectedPoint::Listener { @@ -2582,10 +2299,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); if let Some(&PeerState::Incoming { ref connections, backoff_until: None, .. }) = @@ -2605,7 +2319,7 @@ mod tests { #[tokio::test] async fn disconnect_remote_substream_before_handled_by_controller() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let connected = ConnectedPoint::Listener { @@ -2625,10 +2339,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); notif.disconnect_peer(&peer, 0.into()); @@ -2644,7 +2355,7 @@ mod tests { #[test] fn peerset_report_connect_backoff() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let set_id = SetId::from(0); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); @@ -2682,7 +2393,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -2709,7 +2420,7 @@ mod tests { #[test] fn peerset_connect_incoming() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -2733,22 +2444,19 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); // attempt to connect to the peer and verify that the peer state is `Enabled`; // we rely on implementation detail that incoming indices are counted from 0 // to not mock the `Peerset` - notif.protocol_report_accept(IncomingIndex(0)); + notif.peerset_report_accept(IncomingIndex(0)); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Enabled { .. }))); } #[test] fn peerset_disconnect_disable_pending_enable() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let set_id = SetId::from(0); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); @@ -2795,7 +2503,7 @@ mod tests { #[test] fn peerset_disconnect_enabled() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -2817,14 +2525,11 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); // we rely on the implementation detail that incoming indices are counted from 0 // to not mock the `Peerset` - notif.protocol_report_accept(IncomingIndex(0)); + notif.peerset_report_accept(IncomingIndex(0)); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Enabled { .. }))); // disconnect peer and verify that the state is `Disabled` @@ -2834,7 +2539,7 @@ mod tests { #[test] fn peerset_disconnect_requested() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let set_id = SetId::from(0); @@ -2849,7 +2554,7 @@ mod tests { #[test] fn peerset_disconnect_pending_request() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let set_id = SetId::from(0); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); @@ -2882,7 +2587,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -2902,7 +2607,7 @@ mod tests { #[test] fn peerset_accept_peer_not_alive() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -2926,10 +2631,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); @@ -2945,14 +2647,14 @@ mod tests { IncomingPeer { alive: false, incoming_id: IncomingIndex(0), .. }, )); - notif.protocol_report_accept(IncomingIndex(0)); + notif.peerset_report_accept(IncomingIndex(0)); assert_eq!(notif.incoming.len(), 0); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(PeerState::Disabled { .. }))); } #[test] fn secondary_connection_peer_state_incoming() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let conn2 = ConnectionId::new_unchecked(1); @@ -2976,10 +2678,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); if let Some(PeerState::Incoming { connections, .. }) = notif.peers.get(&(peer, set_id)) { assert_eq!(connections.len(), 1); @@ -3010,7 +2709,7 @@ mod tests { #[test] fn close_connection_for_disabled_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -3035,7 +2734,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -3044,7 +2743,7 @@ mod tests { #[test] fn close_connection_for_incoming_peer_one_connection() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -3067,10 +2766,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); @@ -3079,7 +2775,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -3092,7 +2788,7 @@ mod tests { #[test] fn close_connection_for_incoming_peer_two_connections() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let conn1 = ConnectionId::new_unchecked(1); @@ -3119,10 +2815,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); @@ -3149,7 +2842,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -3164,7 +2857,7 @@ mod tests { #[test] fn connection_and_substream_open() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -3189,16 +2882,13 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); // We rely on the implementation detail that incoming indices are counted // from 0 to not mock the `Peerset`. - notif.protocol_report_accept(IncomingIndex(0)); + notif.peerset_report_accept(IncomingIndex(0)); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Enabled { .. }))); // open new substream @@ -3221,7 +2911,7 @@ mod tests { #[test] fn connection_closed_sink_replaced() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn1 = ConnectionId::new_unchecked(0); let conn2 = ConnectionId::new_unchecked(1); @@ -3257,10 +2947,7 @@ mod tests { notif.on_connection_handler_event( peer, conn2, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); if let Some(PeerState::Enabled { connections, .. }) = notif.peers.get(&(peer, set_id)) { @@ -3297,7 +2984,7 @@ mod tests { peer_id: peer, connection_id: conn1, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -3318,7 +3005,7 @@ mod tests { #[test] fn dial_failure_for_requested_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let set_id = SetId::from(0); @@ -3341,7 +3028,7 @@ mod tests { #[tokio::test] async fn write_notification() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -3390,7 +3077,7 @@ mod tests { #[test] fn peerset_report_connect_backoff_expired() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let set_id = SetId::from(0); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); @@ -3423,7 +3110,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -3438,7 +3125,7 @@ mod tests { #[test] fn peerset_report_disconnect_disabled() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let set_id = SetId::from(0); let conn = ConnectionId::new_unchecked(0); @@ -3464,7 +3151,7 @@ mod tests { #[test] fn peerset_report_disconnect_backoff() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let set_id = SetId::from(0); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); @@ -3497,7 +3184,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -3510,7 +3197,7 @@ mod tests { #[test] fn peer_is_backed_off_if_both_connections_get_closed_while_peer_is_disabled_with_back_off() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let set_id = SetId::from(0); let peer = PeerId::random(); let conn1 = ConnectionId::new_unchecked(0); @@ -3560,7 +3247,7 @@ mod tests { peer_id: peer, connection_id: conn1, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected.clone(), vec![], None), + handler: NotifsHandler::new(peer, connected.clone(), vec![]), remaining_established: 0usize, }, )); @@ -3574,7 +3261,7 @@ mod tests { peer_id: peer, connection_id: conn2, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -3583,7 +3270,7 @@ mod tests { #[test] fn inject_connection_closed_incoming_with_backoff() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let set_id = SetId::from(0); let conn = ConnectionId::new_unchecked(0); @@ -3607,10 +3294,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); // manually add backoff for the entry @@ -3628,7 +3312,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -3637,7 +3321,7 @@ mod tests { #[test] fn two_connections_inactive_connection_gets_closed_peer_state_is_still_incoming() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn1 = ConnectionId::new_unchecked(0); let conn2 = ConnectionId::new_unchecked(1); @@ -3671,10 +3355,7 @@ mod tests { notif.on_connection_handler_event( peer, conn1, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!( notif.peers.get_mut(&(peer, 0.into())), @@ -3686,7 +3367,7 @@ mod tests { peer_id: peer, connection_id: conn2, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -3695,7 +3376,7 @@ mod tests { #[test] fn two_connections_active_connection_gets_closed_peer_state_is_disabled() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn1 = ConnectionId::new_unchecked(0); let conn2 = ConnectionId::new_unchecked(1); @@ -3732,10 +3413,7 @@ mod tests { notif.on_connection_handler_event( peer, conn1, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!( notif.peers.get_mut(&(peer, 0.into())), @@ -3747,7 +3425,7 @@ mod tests { peer_id: peer, connection_id: conn1, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -3756,7 +3434,7 @@ mod tests { #[test] fn inject_connection_closed_for_active_connection() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn1 = ConnectionId::new_unchecked(0); let conn2 = ConnectionId::new_unchecked(1); @@ -3816,7 +3494,7 @@ mod tests { peer_id: peer, connection_id: conn1, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -3824,7 +3502,7 @@ mod tests { #[test] fn inject_dial_failure_for_pending_request() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let set_id = SetId::from(0); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); @@ -3857,7 +3535,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -3887,7 +3565,7 @@ mod tests { #[test] fn peerstate_incoming_open_desired_by_remote() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let set_id = SetId::from(0); let conn1 = ConnectionId::new_unchecked(0); @@ -3921,10 +3599,7 @@ mod tests { notif.on_connection_handler_event( peer, conn1, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); @@ -3932,10 +3607,7 @@ mod tests { notif.on_connection_handler_event( peer, conn2, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); if let Some(PeerState::Incoming { ref connections, .. }) = notif.peers.get(&(peer, set_id)) @@ -3947,7 +3619,7 @@ mod tests { #[tokio::test] async fn remove_backoff_peer_after_timeout() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let set_id = SetId::from(0); let conn = ConnectionId::new_unchecked(0); @@ -3980,7 +3652,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -4025,7 +3697,7 @@ mod tests { #[tokio::test] async fn reschedule_disabled_pending_enable_when_connection_not_closed() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -4054,16 +3726,13 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); // we rely on the implementation detail that incoming indices are counted from 0 // to not mock the `Peerset` - notif.protocol_report_accept(IncomingIndex(0)); + notif.peerset_report_accept(IncomingIndex(0)); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Enabled { .. }))); let event = conn_yielder.open_substream(peer, 0, connected, vec![1, 2, 3, 4]); @@ -4146,7 +3815,7 @@ mod tests { #[should_panic] #[cfg(debug_assertions)] fn peerset_report_connect_with_enabled_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -4171,10 +3840,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); @@ -4199,7 +3865,7 @@ mod tests { #[test] #[cfg(debug_assertions)] fn peerset_report_connect_with_disabled_pending_enable_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let set_id = SetId::from(0); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); @@ -4245,7 +3911,7 @@ mod tests { #[test] #[cfg(debug_assertions)] fn peerset_report_connect_with_requested_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let set_id = SetId::from(0); @@ -4261,7 +3927,7 @@ mod tests { #[test] #[cfg(debug_assertions)] fn peerset_report_connect_with_pending_requested() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let set_id = SetId::from(0); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); @@ -4294,7 +3960,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -4318,7 +3984,7 @@ mod tests { #[test] #[cfg(debug_assertions)] fn peerset_report_connect_with_incoming_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let set_id = SetId::from(0); let conn = ConnectionId::new_unchecked(0); @@ -4342,10 +4008,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); @@ -4356,7 +4019,7 @@ mod tests { #[test] #[cfg(debug_assertions)] fn peerset_report_disconnect_with_incoming_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let set_id = SetId::from(0); let conn = ConnectionId::new_unchecked(0); @@ -4380,10 +4043,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); @@ -4392,170 +4052,13 @@ mod tests { } #[test] + #[should_panic] #[cfg(debug_assertions)] - fn peerset_report_disconnect_with_incoming_peer_protocol_accepts() { - let (mut notif, _controller, _notif_service) = development_notifs(); - let peer = PeerId::random(); - let set_id = SetId::from(0); - let conn = ConnectionId::new_unchecked(0); - let connected = ConnectedPoint::Listener { - local_addr: Multiaddr::empty(), - send_back_addr: Multiaddr::empty(), - }; - - notif.on_swarm_event(FromSwarm::ConnectionEstablished( - libp2p::swarm::behaviour::ConnectionEstablished { - peer_id: peer, - connection_id: conn, - endpoint: &connected, - failed_addresses: &[], - other_established: 0usize, - }, - )); - assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Disabled { .. }))); - - // remote opens a substream, verify that peer state is updated to `Incoming` - notif.on_connection_handler_event( - peer, - conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, - ); - assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); - - // `Peerset` wants to disconnect the peer but since it's still under validation, - // it won't be disabled automatically - notif.peerset_report_disconnect(peer, set_id); - - let incoming_index = match notif.peers.get(&(peer, set_id)) { - Some(&PeerState::Incoming { peerset_rejected, incoming_index, .. }) => { - assert!(peerset_rejected); - incoming_index - }, - state => panic!("invalid state: {state:?}"), - }; - - // protocol accepted peer but since `Peerset` wanted to disconnect it, the peer will be - // disabled - notif.protocol_report_accept(incoming_index); - - match notif.peers.get(&(peer, set_id)) { - Some(&PeerState::Disabled { .. }) => {}, - state => panic!("invalid state: {state:?}"), - }; - } - - #[test] - #[cfg(debug_assertions)] - fn peer_disconnected_protocol_accepts() { - let (mut notif, _controller, _notif_service) = development_notifs(); - let peer = PeerId::random(); - let set_id = SetId::from(0); - let conn = ConnectionId::new_unchecked(0); - let connected = ConnectedPoint::Listener { - local_addr: Multiaddr::empty(), - send_back_addr: Multiaddr::empty(), - }; - - notif.on_swarm_event(FromSwarm::ConnectionEstablished( - libp2p::swarm::behaviour::ConnectionEstablished { - peer_id: peer, - connection_id: conn, - endpoint: &connected, - failed_addresses: &[], - other_established: 0usize, - }, - )); - assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Disabled { .. }))); - - // remote opens a substream, verify that peer state is updated to `Incoming` - notif.on_connection_handler_event( - peer, - conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, - ); - assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); - - assert!(notif.incoming.iter().any(|entry| entry.incoming_id == IncomingIndex(0))); - notif.disconnect_peer(&peer, set_id); - - // since the connection was closed, nothing happens for the peer state because - // there is nothing actionable - notif.protocol_report_accept(IncomingIndex(0)); - - match notif.peers.get(&(peer, set_id)) { - Some(&PeerState::Disabled { .. }) => {}, - state => panic!("invalid state: {state:?}"), - }; - - assert!(!notif.incoming.iter().any(|entry| entry.incoming_id == IncomingIndex(0))); - } - - #[test] - #[cfg(debug_assertions)] - fn connection_closed_protocol_accepts() { - let (mut notif, _controller, _notif_service) = development_notifs(); + fn peerset_report_accept_incoming_peer() { + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); - let set_id = SetId::from(0); let conn = ConnectionId::new_unchecked(0); - let connected = ConnectedPoint::Listener { - local_addr: Multiaddr::empty(), - send_back_addr: Multiaddr::empty(), - }; - - notif.on_swarm_event(FromSwarm::ConnectionEstablished( - libp2p::swarm::behaviour::ConnectionEstablished { - peer_id: peer, - connection_id: conn, - endpoint: &connected, - failed_addresses: &[], - other_established: 0usize, - }, - )); - assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Disabled { .. }))); - - // remote opens a substream, verify that peer state is updated to `Incoming` - notif.on_connection_handler_event( - peer, - conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, - ); - assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); - - notif.on_swarm_event(FromSwarm::ConnectionClosed( - libp2p::swarm::behaviour::ConnectionClosed { - peer_id: peer, - connection_id: ConnectionId::new_unchecked(0), - endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), - remaining_established: 0usize, - }, - )); - - // connection closed, nothing to do - notif.protocol_report_accept(IncomingIndex(0)); - - match notif.peers.get(&(peer, set_id)) { - None => {}, - state => panic!("invalid state: {state:?}"), - }; - } - - #[test] - #[cfg(debug_assertions)] - fn peer_disconnected_protocol_reject() { - let (mut notif, _controller, _notif_service) = development_notifs(); - let peer = PeerId::random(); let set_id = SetId::from(0); - let conn = ConnectionId::new_unchecked(0); let connected = ConnectedPoint::Listener { local_addr: Multiaddr::empty(), send_back_addr: Multiaddr::empty(), @@ -4576,86 +4079,24 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); - assert!(notif.incoming.iter().any(|entry| entry.incoming_id == IncomingIndex(0))); - notif.disconnect_peer(&peer, set_id); - - // since the connection was closed, nothing happens for the peer state because - // there is nothing actionable - notif.protocol_report_reject(IncomingIndex(0)); - - match notif.peers.get(&(peer, set_id)) { - Some(&PeerState::Disabled { .. }) => {}, - state => panic!("invalid state: {state:?}"), - }; - - assert!(!notif.incoming.iter().any(|entry| entry.incoming_id == IncomingIndex(0))); - } - - #[test] - #[cfg(debug_assertions)] - fn connection_closed_protocol_rejects() { - let (mut notif, _controller, _notif_service) = development_notifs(); - let peer = PeerId::random(); - let set_id = SetId::from(0); - let conn = ConnectionId::new_unchecked(0); - let connected = ConnectedPoint::Listener { - local_addr: Multiaddr::empty(), - send_back_addr: Multiaddr::empty(), - }; - - notif.on_swarm_event(FromSwarm::ConnectionEstablished( - libp2p::swarm::behaviour::ConnectionEstablished { - peer_id: peer, - connection_id: conn, - endpoint: &connected, - failed_addresses: &[], - other_established: 0usize, - }, - )); - assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Disabled { .. }))); - - // remote opens a substream, verify that peer state is updated to `Incoming` - notif.on_connection_handler_event( - peer, - conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, - ); - assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); - - notif.on_swarm_event(FromSwarm::ConnectionClosed( - libp2p::swarm::behaviour::ConnectionClosed { - peer_id: peer, - connection_id: ConnectionId::new_unchecked(0), - endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), - remaining_established: 0usize, - }, + assert!(std::matches!( + notif.incoming[0], + IncomingPeer { alive: true, incoming_id: IncomingIndex(0), .. }, )); - // connection closed, nothing to do - notif.protocol_report_reject(IncomingIndex(0)); - - match notif.peers.get(&(peer, set_id)) { - None => {}, - state => panic!("invalid state: {state:?}"), - }; + notif.peers.remove(&(peer, set_id)); + notif.peerset_report_accept(IncomingIndex(0)); } #[test] #[should_panic] #[cfg(debug_assertions)] - fn protocol_report_accept_not_incoming_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + fn peerset_report_accept_not_incoming_peer() { + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -4680,10 +4121,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); @@ -4700,14 +4138,14 @@ mod tests { assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Enabled { .. }))); notif.incoming[0].alive = true; - notif.protocol_report_accept(IncomingIndex(0)); + notif.peerset_report_accept(IncomingIndex(0)); } #[test] #[should_panic] #[cfg(debug_assertions)] fn inject_connection_closed_non_existent_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let endpoint = ConnectedPoint::Listener { local_addr: Multiaddr::empty(), @@ -4719,7 +4157,7 @@ mod tests { peer_id: peer, connection_id: ConnectionId::new_unchecked(0), endpoint: &endpoint.clone(), - handler: NotifsHandler::new(peer, endpoint, vec![], None), + handler: NotifsHandler::new(peer, endpoint, vec![]), remaining_established: 0usize, }, )); @@ -4727,7 +4165,7 @@ mod tests { #[test] fn disconnect_non_existent_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let set_id = SetId::from(0); @@ -4739,9 +4177,9 @@ mod tests { #[test] fn accept_non_existent_connection() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); - notif.protocol_report_accept(0.into()); + notif.peerset_report_accept(0.into()); assert!(notif.peers.is_empty()); assert!(notif.incoming.is_empty()); @@ -4749,9 +4187,9 @@ mod tests { #[test] fn reject_non_existent_connection() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); - notif.protocol_report_reject(0.into()); + notif.peerset_report_reject(0.into()); assert!(notif.peers.is_empty()); assert!(notif.incoming.is_empty()); @@ -4759,7 +4197,7 @@ mod tests { #[test] fn reject_non_active_connection() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -4783,15 +4221,12 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); notif.incoming[0].alive = false; - notif.protocol_report_reject(0.into()); + notif.peerset_report_reject(0.into()); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); } @@ -4799,8 +4234,8 @@ mod tests { #[test] #[should_panic] #[cfg(debug_assertions)] - fn inject_non_existent_connection_closed_for_incoming_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + fn reject_non_existent_peer_but_alive_connection() { + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -4824,10 +4259,47 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, + ); + assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); + assert!(std::matches!( + notif.incoming[0], + IncomingPeer { alive: true, incoming_id: IncomingIndex(0), .. }, + )); + + notif.peers.remove(&(peer, set_id)); + notif.peerset_report_reject(0.into()); + } + + #[test] + #[should_panic] + #[cfg(debug_assertions)] + fn inject_non_existent_connection_closed_for_incoming_peer() { + let (mut notif, _controller) = development_notifs(); + let peer = PeerId::random(); + let conn = ConnectionId::new_unchecked(0); + let set_id = SetId::from(0); + let connected = ConnectedPoint::Listener { + local_addr: Multiaddr::empty(), + send_back_addr: Multiaddr::empty(), + }; + + notif.on_swarm_event(FromSwarm::ConnectionEstablished( + libp2p::swarm::behaviour::ConnectionEstablished { + peer_id: peer, + connection_id: conn, + endpoint: &connected, + failed_addresses: &[], + other_established: 0usize, }, + )); + assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Disabled { .. }))); + + // remote opens a substream, verify that peer state is updated to `Incoming` + notif.on_connection_handler_event( + peer, + conn, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); @@ -4836,7 +4308,7 @@ mod tests { peer_id: peer, connection_id: ConnectionId::new_unchecked(1337), endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -4846,7 +4318,7 @@ mod tests { #[should_panic] #[cfg(debug_assertions)] fn inject_non_existent_connection_closed_for_disabled_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let set_id = SetId::from(0); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); @@ -4871,7 +4343,7 @@ mod tests { peer_id: peer, connection_id: ConnectionId::new_unchecked(1337), endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -4881,7 +4353,7 @@ mod tests { #[should_panic] #[cfg(debug_assertions)] fn inject_non_existent_connection_closed_for_disabled_pending_enable() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let set_id = SetId::from(0); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); @@ -4922,7 +4394,7 @@ mod tests { peer_id: peer, connection_id: ConnectionId::new_unchecked(1337), endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -4932,7 +4404,7 @@ mod tests { #[should_panic] #[cfg(debug_assertions)] fn inject_connection_closed_for_incoming_peer_state_mismatch() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -4956,10 +4428,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); notif.incoming[0].alive = false; @@ -4969,7 +4438,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -4979,7 +4448,7 @@ mod tests { #[should_panic] #[cfg(debug_assertions)] fn inject_connection_closed_for_enabled_state_mismatch() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); let set_id = SetId::from(0); @@ -5003,10 +4472,7 @@ mod tests { notif.on_connection_handler_event( peer, conn, - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index: 0, - handshake: vec![1, 3, 3, 7], - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, ); assert!(std::matches!(notif.peers.get(&(peer, set_id)), Some(&PeerState::Incoming { .. }))); @@ -5019,7 +4485,7 @@ mod tests { peer_id: peer, connection_id: ConnectionId::new_unchecked(1337), endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -5029,7 +4495,7 @@ mod tests { #[should_panic] #[cfg(debug_assertions)] fn inject_connection_closed_for_backoff_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let set_id = SetId::from(0); let peer = PeerId::random(); let conn = ConnectionId::new_unchecked(0); @@ -5062,7 +4528,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected.clone(), vec![], None), + handler: NotifsHandler::new(peer, connected.clone(), vec![]), remaining_established: 0usize, }, )); @@ -5073,7 +4539,7 @@ mod tests { peer_id: peer, connection_id: conn, endpoint: &connected.clone(), - handler: NotifsHandler::new(peer, connected, vec![], None), + handler: NotifsHandler::new(peer, connected, vec![]), remaining_established: 0usize, }, )); @@ -5083,7 +4549,7 @@ mod tests { #[should_panic] #[cfg(debug_assertions)] fn open_result_ok_non_existent_peer() { - let (mut notif, _controller, _notif_service) = development_notifs(); + let (mut notif, _controller) = development_notifs(); let conn = ConnectionId::new_unchecked(0); let connected = ConnectedPoint::Listener { local_addr: Multiaddr::empty(), diff --git a/substrate/client/network/src/protocol/notifications/handler.rs b/substrate/client/network/src/protocol/notifications/handler.rs index 28662be29fe..cffdec7d71e 100644 --- a/substrate/client/network/src/protocol/notifications/handler.rs +++ b/substrate/client/network/src/protocol/notifications/handler.rs @@ -58,12 +58,9 @@ //! [`NotifsHandlerIn::Open`] has gotten an answer. use crate::{ - protocol::notifications::{ - service::metrics, - upgrade::{ - NotificationsIn, NotificationsInSubstream, NotificationsOut, NotificationsOutSubstream, - UpgradeCollec, - }, + protocol::notifications::upgrade::{ + NotificationsIn, NotificationsInSubstream, NotificationsOut, NotificationsOutSubstream, + UpgradeCollec, }, types::ProtocolName, }; @@ -95,7 +92,7 @@ use std::{ /// Number of pending notifications in asynchronous contexts. /// See [`NotificationsSink::reserve_notification`] for context. -pub(crate) const ASYNC_NOTIFICATIONS_BUFFER_SIZE: usize = 8; +const ASYNC_NOTIFICATIONS_BUFFER_SIZE: usize = 8; /// Number of pending notifications in synchronous contexts. const SYNC_NOTIFICATIONS_BUFFER_SIZE: usize = 2048; @@ -129,19 +126,11 @@ pub struct NotifsHandler { events_queue: VecDeque< ConnectionHandlerEvent, >, - - /// Metrics. - metrics: Option>, } impl NotifsHandler { /// Creates new [`NotifsHandler`]. - pub fn new( - peer_id: PeerId, - endpoint: ConnectedPoint, - protocols: Vec, - metrics: Option, - ) -> Self { + pub fn new(peer_id: PeerId, endpoint: ConnectedPoint, protocols: Vec) -> Self { Self { protocols: protocols .into_iter() @@ -159,7 +148,6 @@ impl NotifsHandler { endpoint, when_connection_open: Instant::now(), events_queue: VecDeque::with_capacity(16), - metrics: metrics.map_or(None, |metrics| Some(Arc::new(metrics))), } } } @@ -315,8 +303,6 @@ pub enum NotifsHandlerOut { OpenDesiredByRemote { /// Index of the protocol in the list of protocols passed at initialization. protocol_index: usize, - /// Received handshake. - handshake: Vec, }, /// The remote would like the substreams to be closed. Send a [`NotifsHandlerIn::Close`] in @@ -345,36 +331,6 @@ pub enum NotifsHandlerOut { #[derive(Debug, Clone)] pub struct NotificationsSink { inner: Arc, - metrics: Option>, -} - -impl NotificationsSink { - /// Create new [`NotificationsSink`]. - /// NOTE: only used for testing but must be `pub` as other crates in `client/network` use this. - pub fn new( - peer_id: PeerId, - ) -> (Self, mpsc::Receiver, mpsc::Receiver) - { - let (async_tx, async_rx) = mpsc::channel(ASYNC_NOTIFICATIONS_BUFFER_SIZE); - let (sync_tx, sync_rx) = mpsc::channel(SYNC_NOTIFICATIONS_BUFFER_SIZE); - ( - NotificationsSink { - inner: Arc::new(NotificationsSinkInner { - peer_id, - async_channel: FuturesMutex::new(async_tx), - sync_channel: Mutex::new(Some(sync_tx)), - }), - metrics: None, - }, - async_rx, - sync_rx, - ) - } - - /// Get reference to metrics. - pub fn metrics(&self) -> &Option> { - &self.metrics - } } #[derive(Debug)] @@ -394,8 +350,8 @@ struct NotificationsSinkInner { /// Message emitted through the [`NotificationsSink`] and processed by the background task /// dedicated to the peer. -#[derive(Debug, PartialEq, Eq)] -pub enum NotificationsSinkMessage { +#[derive(Debug)] +enum NotificationsSinkMessage { /// Message emitted by [`NotificationsSink::reserve_notification`] and /// [`NotificationsSink::write_notification_now`]. Notification { message: Vec }, @@ -423,8 +379,8 @@ impl NotificationsSink { let mut lock = self.inner.sync_channel.lock(); if let Some(tx) = lock.as_mut() { - let message = message.into(); - let result = tx.try_send(NotificationsSinkMessage::Notification { message }); + let result = + tx.try_send(NotificationsSinkMessage::Notification { message: message.into() }); if result.is_err() { // Cloning the `mpsc::Sender` guarantees the allocation of an extra spot in the @@ -520,10 +476,7 @@ impl ConnectionHandler for NotifsHandler { match protocol_info.state { State::Closed { pending_opening } => { self.events_queue.push_back(ConnectionHandlerEvent::Custom( - NotifsHandlerOut::OpenDesiredByRemote { - protocol_index, - handshake: in_substream_open.handshake, - }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index }, )); protocol_info.state = State::OpenDesiredByRemote { @@ -578,7 +531,6 @@ impl ConnectionHandler for NotifsHandler { async_channel: FuturesMutex::new(async_tx), sync_channel: Mutex::new(Some(sync_tx)), }), - metrics: self.metrics.clone(), }; self.protocols[protocol_index].state = State::Open { @@ -929,7 +881,6 @@ pub mod tests { async_channel: FuturesMutex::new(async_tx), sync_channel: Mutex::new(Some(sync_tx)), }), - metrics: None, }; let (in_substream, out_substream) = MockSubstream::new(); @@ -1089,7 +1040,6 @@ pub mod tests { }, peer_id: PeerId::random(), events_queue: VecDeque::new(), - metrics: None, } } @@ -1595,7 +1545,6 @@ pub mod tests { async_channel: FuturesMutex::new(async_tx), sync_channel: Mutex::new(Some(sync_tx)), }), - metrics: None, }; handler.protocols[0].state = State::Open { @@ -1648,7 +1597,7 @@ pub mod tests { assert!(std::matches!( handler.poll(cx), Poll::Ready(ConnectionHandlerEvent::Custom( - NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0, .. }, + NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0 }, )) )); assert!(std::matches!( diff --git a/substrate/client/network/src/protocol/notifications/service/metrics.rs b/substrate/client/network/src/protocol/notifications/service/metrics.rs deleted file mode 100644 index 2a57d57c175..00000000000 --- a/substrate/client/network/src/protocol/notifications/service/metrics.rs +++ /dev/null @@ -1,130 +0,0 @@ -// 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 crate::types::ProtocolName; - -use prometheus_endpoint::{ - self as prometheus, CounterVec, HistogramOpts, HistogramVec, Opts, PrometheusError, Registry, - U64, -}; - -use std::sync::Arc; - -/// Notification metrics. -#[derive(Debug, Clone)] -pub struct Metrics { - // Total number of opened substreams. - pub notifications_streams_opened_total: CounterVec, - - /// Total number of closed substreams. - pub notifications_streams_closed_total: CounterVec, - - /// In/outbound notification sizes. - pub notifications_sizes: HistogramVec, -} - -impl Metrics { - fn register(registry: &Registry) -> Result { - Ok(Self { - notifications_sizes: prometheus::register( - HistogramVec::new( - HistogramOpts { - common_opts: Opts::new( - "substrate_sub_libp2p_notifications_sizes", - "Sizes of the notifications send to and received from all nodes", - ), - buckets: prometheus::exponential_buckets(64.0, 4.0, 8) - .expect("parameters are always valid values; qed"), - }, - &["direction", "protocol"], - )?, - registry, - )?, - notifications_streams_closed_total: prometheus::register( - CounterVec::new( - Opts::new( - "substrate_sub_libp2p_notifications_streams_closed_total", - "Total number of notification substreams that have been closed", - ), - &["protocol"], - )?, - registry, - )?, - notifications_streams_opened_total: prometheus::register( - CounterVec::new( - Opts::new( - "substrate_sub_libp2p_notifications_streams_opened_total", - "Total number of notification substreams that have been opened", - ), - &["protocol"], - )?, - registry, - )?, - }) - } -} - -/// Register metrics. -pub fn register(registry: &Registry) -> Result { - Metrics::register(registry) -} - -/// Register opened substream to Prometheus. -pub fn register_substream_opened(metrics: &Option, protocol: &ProtocolName) { - if let Some(metrics) = metrics { - metrics.notifications_streams_opened_total.with_label_values(&[&protocol]).inc(); - } -} - -/// Register closed substream to Prometheus. -pub fn register_substream_closed(metrics: &Option, protocol: &ProtocolName) { - if let Some(metrics) = metrics { - metrics - .notifications_streams_closed_total - .with_label_values(&[&protocol[..]]) - .inc(); - } -} - -/// Register sent notification to Prometheus. -pub fn register_notification_sent( - metrics: &Option>, - protocol: &ProtocolName, - size: usize, -) { - if let Some(metrics) = metrics { - metrics - .notifications_sizes - .with_label_values(&["out", protocol]) - .observe(size as f64); - } -} - -/// Register received notification to Prometheus. -pub fn register_notification_received( - metrics: &Option, - protocol: &ProtocolName, - size: usize, -) { - if let Some(metrics) = metrics { - metrics - .notifications_sizes - .with_label_values(&["in", protocol]) - .observe(size as f64); - } -} diff --git a/substrate/client/network/src/protocol/notifications/service/mod.rs b/substrate/client/network/src/protocol/notifications/service/mod.rs deleted file mode 100644 index 62e6d88a3d5..00000000000 --- a/substrate/client/network/src/protocol/notifications/service/mod.rs +++ /dev/null @@ -1,634 +0,0 @@ -// 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 . - -//! Notification service implementation. - -use crate::{ - error, - protocol::notifications::handler::NotificationsSink, - service::traits::{ - Direction, MessageSink, NotificationEvent, NotificationService, ValidationResult, - }, - types::ProtocolName, -}; - -use futures::{ - stream::{FuturesUnordered, Stream}, - StreamExt, -}; -use libp2p::PeerId; -use parking_lot::Mutex; -use tokio::sync::{mpsc, oneshot}; -use tokio_stream::wrappers::ReceiverStream; - -use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender}; - -use std::{collections::HashMap, fmt::Debug, sync::Arc}; - -pub(crate) mod metrics; - -#[cfg(test)] -mod tests; - -/// Logging target for the file. -const LOG_TARGET: &str = "sub-libp2p"; - -/// Default command queue size. -const COMMAND_QUEUE_SIZE: usize = 64; - -/// Type representing subscribers of a notification protocol. -type Subscribers = Arc>>>; - -/// Type represending a distributable message sink. -/// Detached message sink must carry the protocol name for registering metrics. -/// -/// See documentation for [`PeerContext`] for more details. -type NotificationSink = Arc>; - -#[async_trait::async_trait] -impl MessageSink for NotificationSink { - /// Send synchronous `notification` to the peer associated with this [`MessageSink`]. - fn send_sync_notification(&self, notification: Vec) { - let sink = self.lock(); - - metrics::register_notification_sent(&sink.0.metrics(), &sink.1, notification.len()); - sink.0.send_sync_notification(notification); - } - - /// Send an asynchronous `notification` to the peer associated with this [`MessageSink`], - /// allowing sender to exercise backpressure. - /// - /// Returns an error if the peer does not exist. - async fn send_async_notification(&self, notification: Vec) -> Result<(), error::Error> { - // notification sink must be cloned because the lock cannot be held across `.await` - // this makes the implementation less efficient but not prohibitively so as the same - // method is also used by `NetworkService` when sending notifications. - let notification_len = notification.len(); - let sink = self.lock().clone(); - let permit = sink - .0 - .reserve_notification() - .await - .map_err(|_| error::Error::ConnectionClosed)?; - - permit.send(notification).map_err(|_| error::Error::ChannelClosed).map(|res| { - metrics::register_notification_sent(&sink.0.metrics(), &sink.1, notification_len); - res - }) - } -} - -/// Inner notification event to deal with `NotificationsSinks` without exposing that -/// implementation detail to [`NotificationService`] consumers. -#[derive(Debug)] -enum InnerNotificationEvent { - /// Validate inbound substream. - ValidateInboundSubstream { - /// Peer ID. - peer: PeerId, - - /// Received handshake. - handshake: Vec, - - /// `oneshot::Sender` for sending validation result back to `Notifications` - result_tx: oneshot::Sender, - }, - - /// Notification substream open to `peer`. - NotificationStreamOpened { - /// Peer ID. - peer: PeerId, - - /// Direction of the substream. - direction: Direction, - - /// Received handshake. - handshake: Vec, - - /// Negotiated fallback. - negotiated_fallback: Option, - - /// Notification sink. - sink: NotificationsSink, - }, - - /// Substream was closed. - NotificationStreamClosed { - /// Peer ID. - peer: PeerId, - }, - - /// Notification was received from the substream. - NotificationReceived { - /// Peer ID. - peer: PeerId, - - /// Received notification. - notification: Vec, - }, - - /// Notification sink has been replaced. - NotificationSinkReplaced { - /// Peer ID. - peer: PeerId, - - /// Notification sink. - sink: NotificationsSink, - }, -} - -/// Notification commands. -/// -/// Sent by the installed protocols to `Notifications` to open/close/modify substreams. -#[derive(Debug)] -pub enum NotificationCommand { - /// Instruct `Notifications` to open a substream to peer. - #[allow(unused)] - OpenSubstream(PeerId), - - /// Instruct `Notifications` to close the substream to peer. - #[allow(unused)] - CloseSubstream(PeerId), - - /// Set handshake for the notifications protocol. - SetHandshake(Vec), -} - -/// Context assigned to each peer. -/// -/// Contains `NotificationsSink` used by [`NotificationService`] to send notifications -/// and an additional, distributable `NotificationsSink` which the protocol may acquire -/// if it wishes to send notifications through `NotificationsSink` directly. -/// -/// The distributable `NoticationsSink` is wrapped in an `Arc>` to allow -/// `NotificationsService` to swap the underlying sink in case it's replaced. -#[derive(Debug, Clone)] -struct PeerContext { - /// Sink for sending notificaitons. - sink: NotificationsSink, - - /// Distributable notification sink. - shared_sink: NotificationSink, -} - -/// Handle that is passed on to the notifications protocol. -#[derive(Debug)] -pub struct NotificationHandle { - /// Protocol name. - protocol: ProtocolName, - - /// TX channel for sending commands to `Notifications`. - tx: mpsc::Sender, - - /// RX channel for receiving events from `Notifications`. - rx: TracingUnboundedReceiver, - - /// All subscribers of `NotificationEvent`s. - subscribers: Subscribers, - - /// Connected peers. - peers: HashMap, -} - -impl NotificationHandle { - /// Create new [`NotificationHandle`]. - fn new( - protocol: ProtocolName, - tx: mpsc::Sender, - rx: TracingUnboundedReceiver, - subscribers: Arc>>>, - ) -> Self { - Self { protocol, tx, rx, subscribers, peers: HashMap::new() } - } -} - -#[async_trait::async_trait] -impl NotificationService for NotificationHandle { - /// Instruct `Notifications` to open a new substream for `peer`. - async fn open_substream(&mut self, _peer: PeerId) -> Result<(), ()> { - todo!("support for opening substreams not implemented yet"); - } - - /// Instruct `Notifications` to close substream for `peer`. - async fn close_substream(&mut self, _peer: PeerId) -> Result<(), ()> { - todo!("support for closing substreams not implemented yet, call `NetworkService::disconnect_peer()` instead"); - } - - /// Send synchronous `notification` to `peer`. - fn send_sync_notification(&self, peer: &PeerId, notification: Vec) { - if let Some(info) = self.peers.get(&peer) { - metrics::register_notification_sent( - &info.sink.metrics(), - &self.protocol, - notification.len(), - ); - - let _ = info.sink.send_sync_notification(notification); - } - } - - /// Send asynchronous `notification` to `peer`, allowing sender to exercise backpressure. - async fn send_async_notification( - &self, - peer: &PeerId, - notification: Vec, - ) -> Result<(), error::Error> { - let notification_len = notification.len(); - let sink = &self.peers.get(&peer).ok_or_else(|| error::Error::PeerDoesntExist(*peer))?.sink; - - sink.reserve_notification() - .await - .map_err(|_| error::Error::ConnectionClosed)? - .send(notification) - .map_err(|_| error::Error::ChannelClosed) - .map(|res| { - metrics::register_notification_sent( - &sink.metrics(), - &self.protocol, - notification_len, - ); - res - }) - } - - /// Set handshake for the notification protocol replacing the old handshake. - async fn set_handshake(&mut self, handshake: Vec) -> Result<(), ()> { - log::trace!(target: LOG_TARGET, "{}: set handshake to {handshake:?}", self.protocol); - - self.tx.send(NotificationCommand::SetHandshake(handshake)).await.map_err(|_| ()) - } - - /// Non-blocking variant of `set_handshake()` that attempts to update the handshake - /// and returns an error if the channel is blocked. - /// - /// Technically the function can return an error if the channel to `Notifications` is closed - /// but that doesn't happen under normal operation. - fn try_set_handshake(&mut self, handshake: Vec) -> Result<(), ()> { - self.tx.try_send(NotificationCommand::SetHandshake(handshake)).map_err(|_| ()) - } - - /// Get next event from the `Notifications` event stream. - async fn next_event(&mut self) -> Option { - loop { - match self.rx.next().await? { - InnerNotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx } => - return Some(NotificationEvent::ValidateInboundSubstream { - peer, - handshake, - result_tx, - }), - InnerNotificationEvent::NotificationStreamOpened { - peer, - handshake, - negotiated_fallback, - direction, - sink, - } => { - self.peers.insert( - peer, - PeerContext { - sink: sink.clone(), - shared_sink: Arc::new(Mutex::new((sink, self.protocol.clone()))), - }, - ); - return Some(NotificationEvent::NotificationStreamOpened { - peer, - handshake, - direction, - negotiated_fallback, - }) - }, - InnerNotificationEvent::NotificationStreamClosed { peer } => { - self.peers.remove(&peer); - return Some(NotificationEvent::NotificationStreamClosed { peer }) - }, - InnerNotificationEvent::NotificationReceived { peer, notification } => - return Some(NotificationEvent::NotificationReceived { peer, notification }), - InnerNotificationEvent::NotificationSinkReplaced { peer, sink } => { - match self.peers.get_mut(&peer) { - None => log::error!( - "{}: notification sink replaced for {peer} but peer does not exist", - self.protocol - ), - Some(context) => { - context.sink = sink.clone(); - *context.shared_sink.lock() = (sink.clone(), self.protocol.clone()); - }, - } - }, - } - } - } - - // Clone [`NotificationService`] - fn clone(&mut self) -> Result, ()> { - let mut subscribers = self.subscribers.lock(); - let (event_tx, event_rx) = tracing_unbounded("mpsc-notification-to-protocol", 100_000); - subscribers.push(event_tx); - - Ok(Box::new(NotificationHandle { - protocol: self.protocol.clone(), - tx: self.tx.clone(), - rx: event_rx, - peers: self.peers.clone(), - subscribers: self.subscribers.clone(), - })) - } - - /// Get protocol name. - fn protocol(&self) -> &ProtocolName { - &self.protocol - } - - /// Get message sink of the peer. - fn message_sink(&self, peer: &PeerId) -> Option> { - match self.peers.get(peer) { - Some(context) => Some(Box::new(context.shared_sink.clone())), - None => None, - } - } -} - -/// Channel pair which allows `Notifications` to interact with a protocol. -#[derive(Debug)] -pub struct ProtocolHandlePair { - /// Protocol name. - protocol: ProtocolName, - - /// Subscribers of the notification protocol events. - subscribers: Subscribers, - - // Receiver for notification commands received from the protocol implementation. - rx: mpsc::Receiver, -} - -impl ProtocolHandlePair { - /// Create new [`ProtocolHandlePair`]. - fn new( - protocol: ProtocolName, - subscribers: Subscribers, - rx: mpsc::Receiver, - ) -> Self { - Self { protocol, subscribers, rx } - } - - /// Consume `self` and split [`ProtocolHandlePair`] into a handle which allows it to send events - /// to the protocol and a stream of commands received from the protocol. - pub(crate) fn split( - self, - ) -> (ProtocolHandle, Box + Send + Unpin>) { - ( - ProtocolHandle::new(self.protocol, self.subscribers), - Box::new(ReceiverStream::new(self.rx)), - ) - } -} - -/// Handle that is passed on to `Notifications` and allows it to directly communicate -/// with the protocol. -#[derive(Debug, Clone)] -pub(crate) struct ProtocolHandle { - /// Protocol name. - protocol: ProtocolName, - - /// Subscribers of the notification protocol. - subscribers: Subscribers, - - /// Number of connected peers. - num_peers: usize, - - /// Delegate validation to `Peerset`. - delegate_to_peerset: bool, - - /// Prometheus metrics. - metrics: Option, -} - -pub(crate) enum ValidationCallResult { - WaitForValidation(oneshot::Receiver), - Delegated, -} - -impl ProtocolHandle { - /// Create new [`ProtocolHandle`]. - fn new(protocol: ProtocolName, subscribers: Subscribers) -> Self { - Self { protocol, subscribers, num_peers: 0usize, metrics: None, delegate_to_peerset: false } - } - - /// Set metrics. - pub fn set_metrics(&mut self, metrics: Option) { - self.metrics = metrics; - } - - /// Delegate validation to `Peerset`. - /// - /// Protocols that do not do any validation themselves and only rely on `Peerset` handling - /// validation can disable protocol-side validation entirely by delegating all validation to - /// `Peerset`. - pub fn delegate_to_peerset(&mut self, delegate: bool) { - self.delegate_to_peerset = delegate; - } - - /// Report to the protocol that a substream has been opened and it must be validated by the - /// protocol. - /// - /// Return `oneshot::Receiver` which allows `Notifications` to poll for the validation result - /// from protocol. - pub fn report_incoming_substream( - &self, - peer: PeerId, - handshake: Vec, - ) -> Result { - let subscribers = self.subscribers.lock(); - - log::trace!( - target: LOG_TARGET, - "{}: report incoming substream for {peer}, handshake {handshake:?}", - self.protocol - ); - - if self.delegate_to_peerset { - return Ok(ValidationCallResult::Delegated) - } - - // if there is only one subscriber, `Notifications` can wait directly on the - // `oneshot::channel()`'s RX half without indirection - if subscribers.len() == 1 { - let (result_tx, rx) = oneshot::channel(); - return subscribers[0] - .unbounded_send(InnerNotificationEvent::ValidateInboundSubstream { - peer, - handshake, - result_tx, - }) - .map(|_| ValidationCallResult::WaitForValidation(rx)) - .map_err(|_| ()) - } - - // if there are multiple subscribers, create a task which waits for all of the - // validations to finish and returns the combined result to `Notifications` - let mut results: FuturesUnordered<_> = subscribers - .iter() - .filter_map(|subscriber| { - let (result_tx, rx) = oneshot::channel(); - - subscriber - .unbounded_send(InnerNotificationEvent::ValidateInboundSubstream { - peer, - handshake: handshake.clone(), - result_tx, - }) - .is_ok() - .then_some(rx) - }) - .collect(); - - let (tx, rx) = oneshot::channel(); - tokio::spawn(async move { - while let Some(event) = results.next().await { - match event { - Err(_) | Ok(ValidationResult::Reject) => - return tx.send(ValidationResult::Reject), - Ok(ValidationResult::Accept) => {}, - } - } - - return tx.send(ValidationResult::Accept) - }); - - Ok(ValidationCallResult::WaitForValidation(rx)) - } - - /// Report to the protocol that a substream has been opened and that it can now use the handle - /// to send notifications to the remote peer. - pub fn report_substream_opened( - &mut self, - peer: PeerId, - direction: Direction, - handshake: Vec, - negotiated_fallback: Option, - sink: NotificationsSink, - ) -> Result<(), ()> { - metrics::register_substream_opened(&self.metrics, &self.protocol); - - let mut subscribers = self.subscribers.lock(); - log::trace!(target: LOG_TARGET, "{}: substream opened for {peer:?}", self.protocol); - - subscribers.retain(|subscriber| { - subscriber - .unbounded_send(InnerNotificationEvent::NotificationStreamOpened { - peer, - direction, - handshake: handshake.clone(), - negotiated_fallback: negotiated_fallback.clone(), - sink: sink.clone(), - }) - .is_ok() - }); - self.num_peers += 1; - - Ok(()) - } - - /// Substream was closed. - pub fn report_substream_closed(&mut self, peer: PeerId) -> Result<(), ()> { - metrics::register_substream_closed(&self.metrics, &self.protocol); - - let mut subscribers = self.subscribers.lock(); - log::trace!(target: LOG_TARGET, "{}: substream closed for {peer:?}", self.protocol); - - subscribers.retain(|subscriber| { - subscriber - .unbounded_send(InnerNotificationEvent::NotificationStreamClosed { peer }) - .is_ok() - }); - self.num_peers -= 1; - - Ok(()) - } - - /// Notification was received from the substream. - pub fn report_notification_received( - &mut self, - peer: PeerId, - notification: Vec, - ) -> Result<(), ()> { - metrics::register_notification_received(&self.metrics, &self.protocol, notification.len()); - - let mut subscribers = self.subscribers.lock(); - log::trace!(target: LOG_TARGET, "{}: notification received from {peer:?}", self.protocol); - - subscribers.retain(|subscriber| { - subscriber - .unbounded_send(InnerNotificationEvent::NotificationReceived { - peer, - notification: notification.clone(), - }) - .is_ok() - }); - - Ok(()) - } - - /// Notification sink was replaced. - pub fn report_notification_sink_replaced( - &mut self, - peer: PeerId, - sink: NotificationsSink, - ) -> Result<(), ()> { - let mut subscribers = self.subscribers.lock(); - - log::trace!( - target: LOG_TARGET, - "{}: notification sink replaced for {peer:?}", - self.protocol - ); - - subscribers.retain(|subscriber| { - subscriber - .unbounded_send(InnerNotificationEvent::NotificationSinkReplaced { - peer, - sink: sink.clone(), - }) - .is_ok() - }); - - Ok(()) - } - - /// Get the number of connected peers. - pub fn num_peers(&self) -> usize { - self.num_peers - } -} - -/// Create new (protocol, notification) handle pair. -/// -/// Handle pair allows `Notifications` and the protocol to communicate with each other directly. -pub fn notification_service( - protocol: ProtocolName, -) -> (ProtocolHandlePair, Box) { - let (cmd_tx, cmd_rx) = mpsc::channel(COMMAND_QUEUE_SIZE); - let (event_tx, event_rx) = tracing_unbounded("mpsc-notification-to-protocol", 100_000); - let subscribers = Arc::new(Mutex::new(vec![event_tx])); - - ( - ProtocolHandlePair::new(protocol.clone(), subscribers.clone(), cmd_rx), - Box::new(NotificationHandle::new(protocol.clone(), cmd_tx, event_rx, subscribers)), - ) -} diff --git a/substrate/client/network/src/protocol/notifications/service/tests.rs b/substrate/client/network/src/protocol/notifications/service/tests.rs deleted file mode 100644 index 02ba9e1711c..00000000000 --- a/substrate/client/network/src/protocol/notifications/service/tests.rs +++ /dev/null @@ -1,839 +0,0 @@ -// 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::*; -use crate::protocol::notifications::handler::{ - NotificationsSinkMessage, ASYNC_NOTIFICATIONS_BUFFER_SIZE, -}; - -use std::future::Future; - -#[tokio::test] -async fn validate_and_accept_substream() { - let (proto, mut notif) = notification_service("/proto/1".into()); - let (handle, _stream) = proto.split(); - - let peer_id = PeerId::random(); - let ValidationCallResult::WaitForValidation(result_rx) = - handle.report_incoming_substream(peer_id, vec![1, 3, 3, 7]).unwrap() - else { - panic!("peerset not enabled"); - }; - - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - - assert_eq!(result_rx.await.unwrap(), ValidationResult::Accept); -} - -#[tokio::test] -async fn substream_opened() { - let (proto, mut notif) = notification_service("/proto/1".into()); - let (sink, _, _) = NotificationsSink::new(PeerId::random()); - let (mut handle, _stream) = proto.split(); - - let peer_id = PeerId::random(); - handle - .report_substream_opened(peer_id, Direction::Inbound, vec![1, 3, 3, 7], None, sink) - .unwrap(); - - if let Some(NotificationEvent::NotificationStreamOpened { - peer, - negotiated_fallback, - handshake, - direction, - }) = notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(negotiated_fallback, None); - assert_eq!(handshake, vec![1, 3, 3, 7]); - assert_eq!(direction, Direction::Inbound); - } else { - panic!("invalid event received"); - } -} - -#[tokio::test] -async fn send_sync_notification() { - let (proto, mut notif) = notification_service("/proto/1".into()); - let (sink, _, mut sync_rx) = NotificationsSink::new(PeerId::random()); - let (mut handle, _stream) = proto.split(); - let peer_id = PeerId::random(); - - // validate inbound substream - let ValidationCallResult::WaitForValidation(result_rx) = - handle.report_incoming_substream(peer_id, vec![1, 3, 3, 7]).unwrap() - else { - panic!("peerset not enabled"); - }; - - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - assert_eq!(result_rx.await.unwrap(), ValidationResult::Accept); - - // report that a substream has been opened - handle - .report_substream_opened(peer_id, Direction::Inbound, vec![1, 3, 3, 7], None, sink) - .unwrap(); - - if let Some(NotificationEvent::NotificationStreamOpened { - peer, - negotiated_fallback, - handshake, - direction, - }) = notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(negotiated_fallback, None); - assert_eq!(handshake, vec![1, 3, 3, 7]); - assert_eq!(direction, Direction::Inbound); - } else { - panic!("invalid event received"); - } - - notif.send_sync_notification(&peer_id, vec![1, 3, 3, 8]); - assert_eq!( - sync_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 8] }) - ); -} - -#[tokio::test] -async fn send_async_notification() { - let (proto, mut notif) = notification_service("/proto/1".into()); - let (sink, mut async_rx, _) = NotificationsSink::new(PeerId::random()); - let (mut handle, _stream) = proto.split(); - let peer_id = PeerId::random(); - - // validate inbound substream - let ValidationCallResult::WaitForValidation(result_rx) = - handle.report_incoming_substream(peer_id, vec![1, 3, 3, 7]).unwrap() - else { - panic!("peerset not enabled"); - }; - - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - assert_eq!(result_rx.await.unwrap(), ValidationResult::Accept); - - // report that a substream has been opened - handle - .report_substream_opened(peer_id, Direction::Inbound, vec![1, 3, 3, 7], None, sink) - .unwrap(); - - if let Some(NotificationEvent::NotificationStreamOpened { - peer, - negotiated_fallback, - handshake, - direction, - }) = notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(negotiated_fallback, None); - assert_eq!(handshake, vec![1, 3, 3, 7]); - assert_eq!(direction, Direction::Inbound); - } else { - panic!("invalid event received"); - } - - notif.send_async_notification(&peer_id, vec![1, 3, 3, 9]).await.unwrap(); - assert_eq!( - async_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 9] }) - ); -} - -#[tokio::test] -async fn send_sync_notification_to_non_existent_peer() { - let (proto, notif) = notification_service("/proto/1".into()); - let (_sink, _, _sync_rx) = NotificationsSink::new(PeerId::random()); - let (_handle, _stream) = proto.split(); - let peer = PeerId::random(); - - // as per the original implementation, the call doesn't fail - notif.send_sync_notification(&peer, vec![1, 3, 3, 7]) -} - -#[tokio::test] -async fn send_async_notification_to_non_existent_peer() { - let (proto, notif) = notification_service("/proto/1".into()); - let (_sink, _, _sync_rx) = NotificationsSink::new(PeerId::random()); - let (_handle, _stream) = proto.split(); - let peer = PeerId::random(); - - if let Err(error::Error::PeerDoesntExist(peer_id)) = - notif.send_async_notification(&peer, vec![1, 3, 3, 7]).await - { - assert_eq!(peer, peer_id); - } else { - panic!("invalid error received from `send_async_notification()`"); - } -} - -#[tokio::test] -async fn receive_notification() { - let (proto, mut notif) = notification_service("/proto/1".into()); - let (sink, _, _sync_rx) = NotificationsSink::new(PeerId::random()); - let (mut handle, _stream) = proto.split(); - let peer_id = PeerId::random(); - - // validate inbound substream - let ValidationCallResult::WaitForValidation(result_rx) = - handle.report_incoming_substream(peer_id, vec![1, 3, 3, 7]).unwrap() - else { - panic!("peerset not enabled"); - }; - - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - assert_eq!(result_rx.await.unwrap(), ValidationResult::Accept); - - // report that a substream has been opened - handle - .report_substream_opened(peer_id, Direction::Inbound, vec![1, 3, 3, 7], None, sink) - .unwrap(); - - if let Some(NotificationEvent::NotificationStreamOpened { - peer, - negotiated_fallback, - handshake, - direction, - }) = notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(negotiated_fallback, None); - assert_eq!(handshake, vec![1, 3, 3, 7]); - assert_eq!(direction, Direction::Inbound); - } else { - panic!("invalid event received"); - } - - // notification is received - handle.report_notification_received(peer_id, vec![1, 3, 3, 8]).unwrap(); - - if let Some(NotificationEvent::NotificationReceived { peer, notification }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(notification, vec![1, 3, 3, 8]); - } else { - panic!("invalid event received"); - } -} - -#[tokio::test] -async fn backpressure_works() { - let (proto, mut notif) = notification_service("/proto/1".into()); - let (sink, mut async_rx, _) = NotificationsSink::new(PeerId::random()); - let (mut handle, _stream) = proto.split(); - let peer_id = PeerId::random(); - - // validate inbound substream - let ValidationCallResult::WaitForValidation(result_rx) = - handle.report_incoming_substream(peer_id, vec![1, 3, 3, 7]).unwrap() - else { - panic!("peerset not enabled"); - }; - - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - assert_eq!(result_rx.await.unwrap(), ValidationResult::Accept); - - // report that a substream has been opened - handle - .report_substream_opened(peer_id, Direction::Inbound, vec![1, 3, 3, 7], None, sink) - .unwrap(); - - if let Some(NotificationEvent::NotificationStreamOpened { - peer, - negotiated_fallback, - handshake, - direction, - }) = notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(negotiated_fallback, None); - assert_eq!(handshake, vec![1, 3, 3, 7]); - assert_eq!(direction, Direction::Inbound); - } else { - panic!("invalid event received"); - } - - // fill the message buffer with messages - for i in 0..=ASYNC_NOTIFICATIONS_BUFFER_SIZE { - assert!(futures::poll!(notif.send_async_notification(&peer_id, vec![1, 3, 3, i as u8])) - .is_ready()); - } - - // try to send one more message and verify that the call blocks - assert!(futures::poll!(notif.send_async_notification(&peer_id, vec![1, 3, 3, 9])).is_pending()); - - // release one slot from the buffer for new message - assert_eq!( - async_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 0] }) - ); - - // verify that a message can be sent - assert!(futures::poll!(notif.send_async_notification(&peer_id, vec![1, 3, 3, 9])).is_ready()); -} - -#[tokio::test] -async fn peer_disconnects_then_sync_notification_is_sent() { - let (proto, mut notif) = notification_service("/proto/1".into()); - let (sink, _, sync_rx) = NotificationsSink::new(PeerId::random()); - let (mut handle, _stream) = proto.split(); - let peer_id = PeerId::random(); - - // validate inbound substream - let ValidationCallResult::WaitForValidation(result_rx) = - handle.report_incoming_substream(peer_id, vec![1, 3, 3, 7]).unwrap() - else { - panic!("peerset not enabled"); - }; - - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - assert_eq!(result_rx.await.unwrap(), ValidationResult::Accept); - - // report that a substream has been opened - handle - .report_substream_opened(peer_id, Direction::Inbound, vec![1, 3, 3, 7], None, sink) - .unwrap(); - - if let Some(NotificationEvent::NotificationStreamOpened { - peer, - negotiated_fallback, - handshake, - direction, - }) = notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(negotiated_fallback, None); - assert_eq!(handshake, vec![1, 3, 3, 7]); - assert_eq!(direction, Direction::Inbound); - } else { - panic!("invalid event received"); - } - - // report that a substream has been closed but don't poll `notif` to receive this - // information - handle.report_substream_closed(peer_id).unwrap(); - drop(sync_rx); - - // as per documentation, error is not reported but the notification is silently dropped - notif.send_sync_notification(&peer_id, vec![1, 3, 3, 7]); -} - -#[tokio::test] -async fn peer_disconnects_then_async_notification_is_sent() { - let (proto, mut notif) = notification_service("/proto/1".into()); - let (sink, async_rx, _) = NotificationsSink::new(PeerId::random()); - let (mut handle, _stream) = proto.split(); - let peer_id = PeerId::random(); - - // validate inbound substream - let ValidationCallResult::WaitForValidation(result_rx) = - handle.report_incoming_substream(peer_id, vec![1, 3, 3, 7]).unwrap() - else { - panic!("peerset not enabled"); - }; - - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - assert_eq!(result_rx.await.unwrap(), ValidationResult::Accept); - - // report that a substream has been opened - handle - .report_substream_opened(peer_id, Direction::Inbound, vec![1, 3, 3, 7], None, sink) - .unwrap(); - - if let Some(NotificationEvent::NotificationStreamOpened { - peer, - negotiated_fallback, - handshake, - direction, - }) = notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(negotiated_fallback, None); - assert_eq!(handshake, vec![1, 3, 3, 7]); - assert_eq!(direction, Direction::Inbound); - } else { - panic!("invalid event received"); - } - - // report that a substream has been closed but don't poll `notif` to receive this - // information - handle.report_substream_closed(peer_id).unwrap(); - drop(async_rx); - - // as per documentation, error is not reported but the notification is silently dropped - if let Err(error::Error::ConnectionClosed) = - notif.send_async_notification(&peer_id, vec![1, 3, 3, 7]).await - { - } else { - panic!("invalid state after calling `send_async_notificatio()` on closed connection") - } -} - -#[tokio::test] -async fn cloned_service_opening_substream_works() { - let (proto, mut notif1) = notification_service("/proto/1".into()); - let (_sink, _async_rx, _) = NotificationsSink::new(PeerId::random()); - let (handle, _stream) = proto.split(); - let mut notif2 = notif1.clone().unwrap(); - let peer_id = PeerId::random(); - - // validate inbound substream - let ValidationCallResult::WaitForValidation(mut result_rx) = - handle.report_incoming_substream(peer_id, vec![1, 3, 3, 7]).unwrap() - else { - panic!("peerset not enabled"); - }; - - // verify that `notif1` gets the event - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif1.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - - // verify that because only one listener has thus far send their result, the result is - // pending - assert!(result_rx.try_recv().is_err()); - - // verify that `notif2` also gets the event - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif2.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - - assert_eq!(result_rx.await.unwrap(), ValidationResult::Accept); -} - -#[tokio::test] -async fn cloned_service_one_service_rejects_substream() { - let (proto, mut notif1) = notification_service("/proto/1".into()); - let (_sink, _async_rx, _) = NotificationsSink::new(PeerId::random()); - let (handle, _stream) = proto.split(); - let mut notif2 = notif1.clone().unwrap(); - let mut notif3 = notif2.clone().unwrap(); - let peer_id = PeerId::random(); - - // validate inbound substream - let ValidationCallResult::WaitForValidation(mut result_rx) = - handle.report_incoming_substream(peer_id, vec![1, 3, 3, 7]).unwrap() - else { - panic!("peerset not enabled"); - }; - - for notif in vec![&mut notif1, &mut notif2] { - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - } - - // `notif3` has not yet sent their validation result - assert!(result_rx.try_recv().is_err()); - - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif3.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Reject).unwrap(); - } else { - panic!("invalid event received"); - } - assert_eq!(result_rx.await.unwrap(), ValidationResult::Reject); -} - -#[tokio::test] -async fn cloned_service_opening_substream_sending_and_receiving_notifications_work() { - let (proto, mut notif1) = notification_service("/proto/1".into()); - let (sink, _, mut sync_rx) = NotificationsSink::new(PeerId::random()); - let (mut handle, _stream) = proto.split(); - let mut notif2 = notif1.clone().unwrap(); - let mut notif3 = notif1.clone().unwrap(); - let peer_id = PeerId::random(); - - // validate inbound substream - let ValidationCallResult::WaitForValidation(result_rx) = - handle.report_incoming_substream(peer_id, vec![1, 3, 3, 7]).unwrap() - else { - panic!("peerset not enabled"); - }; - - for notif in vec![&mut notif1, &mut notif2, &mut notif3] { - // accept the inbound substream for all services - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - } - assert_eq!(result_rx.await.unwrap(), ValidationResult::Accept); - - // report that then notification stream has been opened - handle - .report_substream_opened(peer_id, Direction::Inbound, vec![1, 3, 3, 7], None, sink) - .unwrap(); - - for notif in vec![&mut notif1, &mut notif2, &mut notif3] { - if let Some(NotificationEvent::NotificationStreamOpened { - peer, - negotiated_fallback, - handshake, - direction, - }) = notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(negotiated_fallback, None); - assert_eq!(handshake, vec![1, 3, 3, 7]); - assert_eq!(direction, Direction::Inbound); - } else { - panic!("invalid event received"); - } - } - // receive a notification from peer and verify all services receive it - handle.report_notification_received(peer_id, vec![1, 3, 3, 8]).unwrap(); - - for notif in vec![&mut notif1, &mut notif2, &mut notif3] { - if let Some(NotificationEvent::NotificationReceived { peer, notification }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(notification, vec![1, 3, 3, 8]); - } else { - panic!("invalid event received"); - } - } - - for (i, notif) in vec![&mut notif1, &mut notif2, &mut notif3].iter().enumerate() { - // send notification from each service and verify peer receives it - notif.send_sync_notification(&peer_id, vec![1, 3, 3, i as u8]); - assert_eq!( - sync_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, i as u8] }) - ); - } - - // close the substream for peer and verify all services receive the event - handle.report_substream_closed(peer_id).unwrap(); - - for notif in vec![&mut notif1, &mut notif2, &mut notif3] { - if let Some(NotificationEvent::NotificationStreamClosed { peer }) = notif.next_event().await - { - assert_eq!(peer_id, peer); - } else { - panic!("invalid event received"); - } - } -} - -#[tokio::test] -async fn sending_notifications_using_notifications_sink_works() { - let (proto, mut notif) = notification_service("/proto/1".into()); - let (sink, mut async_rx, mut sync_rx) = NotificationsSink::new(PeerId::random()); - let (mut handle, _stream) = proto.split(); - let peer_id = PeerId::random(); - - // validate inbound substream - let ValidationCallResult::WaitForValidation(result_rx) = - handle.report_incoming_substream(peer_id, vec![1, 3, 3, 7]).unwrap() - else { - panic!("peerset not enabled"); - }; - - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - assert_eq!(result_rx.await.unwrap(), ValidationResult::Accept); - - // report that a substream has been opened - handle - .report_substream_opened(peer_id, Direction::Inbound, vec![1, 3, 3, 7], None, sink) - .unwrap(); - - if let Some(NotificationEvent::NotificationStreamOpened { - peer, - negotiated_fallback, - handshake, - direction, - }) = notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(negotiated_fallback, None); - assert_eq!(handshake, vec![1, 3, 3, 7]); - assert_eq!(direction, Direction::Inbound); - } else { - panic!("invalid event received"); - } - - // get a copy of the notification sink and send a synchronous notification using. - let sink = notif.message_sink(&peer_id).unwrap(); - sink.send_sync_notification(vec![1, 3, 3, 6]); - - // send an asynchronous notification using the acquired notifications sink. - let _ = sink.send_async_notification(vec![1, 3, 3, 7]).await.unwrap(); - - assert_eq!( - sync_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 6] }), - ); - assert_eq!( - async_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 7] }), - ); - - // send notifications using the stored notification sink as well. - notif.send_sync_notification(&peer_id, vec![1, 3, 3, 8]); - notif.send_async_notification(&peer_id, vec![1, 3, 3, 9]).await.unwrap(); - - assert_eq!( - sync_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 8] }), - ); - assert_eq!( - async_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 9] }), - ); -} - -#[test] -fn try_to_get_notifications_sink_for_non_existent_peer() { - let (_proto, notif) = notification_service("/proto/1".into()); - assert!(notif.message_sink(&PeerId::random()).is_none()); -} - -#[tokio::test] -async fn notification_sink_replaced() { - let (proto, mut notif) = notification_service("/proto/1".into()); - let (sink, mut async_rx, mut sync_rx) = NotificationsSink::new(PeerId::random()); - let (mut handle, _stream) = proto.split(); - let peer_id = PeerId::random(); - - // validate inbound substream - let ValidationCallResult::WaitForValidation(result_rx) = - handle.report_incoming_substream(peer_id, vec![1, 3, 3, 7]).unwrap() - else { - panic!("peerset not enabled"); - }; - - if let Some(NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx }) = - notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(handshake, vec![1, 3, 3, 7]); - let _ = result_tx.send(ValidationResult::Accept).unwrap(); - } else { - panic!("invalid event received"); - } - assert_eq!(result_rx.await.unwrap(), ValidationResult::Accept); - - // report that a substream has been opened - handle - .report_substream_opened(peer_id, Direction::Inbound, vec![1, 3, 3, 7], None, sink) - .unwrap(); - - if let Some(NotificationEvent::NotificationStreamOpened { - peer, - negotiated_fallback, - handshake, - direction, - }) = notif.next_event().await - { - assert_eq!(peer_id, peer); - assert_eq!(negotiated_fallback, None); - assert_eq!(handshake, vec![1, 3, 3, 7]); - assert_eq!(direction, Direction::Inbound); - } else { - panic!("invalid event received"); - } - - // get a copy of the notification sink and send a synchronous notification using. - let sink = notif.message_sink(&peer_id).unwrap(); - sink.send_sync_notification(vec![1, 3, 3, 6]); - - // send an asynchronous notification using the acquired notifications sink. - let _ = sink.send_async_notification(vec![1, 3, 3, 7]).await.unwrap(); - - assert_eq!( - sync_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 6] }), - ); - assert_eq!( - async_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 7] }), - ); - - // send notifications using the stored notification sink as well. - notif.send_sync_notification(&peer_id, vec![1, 3, 3, 8]); - notif.send_async_notification(&peer_id, vec![1, 3, 3, 9]).await.unwrap(); - - assert_eq!( - sync_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 8] }), - ); - assert_eq!( - async_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 9] }), - ); - - // the initial connection was closed and `Notifications` switched to secondary connection - // and emitted `CustomProtocolReplaced` which informs the local `NotificationService` that - // the notification sink was replaced. - let (new_sink, mut new_async_rx, mut new_sync_rx) = NotificationsSink::new(PeerId::random()); - handle.report_notification_sink_replaced(peer_id, new_sink).unwrap(); - - // drop the old sinks and poll `notif` once to register the sink replacement - drop(sync_rx); - drop(async_rx); - - futures::future::poll_fn(|cx| { - let _ = std::pin::Pin::new(&mut notif.next_event()).poll(cx); - std::task::Poll::Ready(()) - }) - .await; - - // verify that using the `NotificationService` API automatically results in using the correct - // sink - notif.send_sync_notification(&peer_id, vec![1, 3, 3, 8]); - notif.send_async_notification(&peer_id, vec![1, 3, 3, 9]).await.unwrap(); - - assert_eq!( - new_sync_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 8] }), - ); - assert_eq!( - new_async_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 9] }), - ); - - // now send two notifications using the acquired message sink and verify that - // it's also updated - sink.send_sync_notification(vec![1, 3, 3, 6]); - - // send an asynchronous notification using the acquired notifications sink. - let _ = sink.send_async_notification(vec![1, 3, 3, 7]).await.unwrap(); - - assert_eq!( - new_sync_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 6] }), - ); - assert_eq!( - new_async_rx.next().await, - Some(NotificationsSinkMessage::Notification { message: vec![1, 3, 3, 7] }), - ); -} - -#[tokio::test] -async fn set_handshake() { - let (proto, mut notif) = notification_service("/proto/1".into()); - let (_handle, mut stream) = proto.split(); - - assert!(notif.try_set_handshake(vec![1, 3, 3, 7]).is_ok()); - - match stream.next().await { - Some(NotificationCommand::SetHandshake(handshake)) => { - assert_eq!(handshake, vec![1, 3, 3, 7]); - }, - _ => panic!("invalid event received"), - } - - for _ in 0..COMMAND_QUEUE_SIZE { - assert!(notif.try_set_handshake(vec![1, 3, 3, 7]).is_ok()); - } - - assert!(notif.try_set_handshake(vec![1, 3, 3, 7]).is_err()); -} diff --git a/substrate/client/network/src/protocol/notifications/tests.rs b/substrate/client/network/src/protocol/notifications/tests.rs index 0178bd75e8b..d57c24144f5 100644 --- a/substrate/client/network/src/protocol/notifications/tests.rs +++ b/substrate/client/network/src/protocol/notifications/tests.rs @@ -22,7 +22,6 @@ use crate::{ peer_store::PeerStore, protocol::notifications::{Notifications, NotificationsOut, ProtocolConfig}, protocol_controller::{ProtoSetConfig, ProtocolController, SetId}, - service::traits::{NotificationEvent, ValidationResult}, }; use futures::{future::BoxFuture, prelude::*}; @@ -71,8 +70,6 @@ fn build_nodes() -> (Swarm, Swarm) { .timeout(Duration::from_secs(20)) .boxed(); - let (protocol_handle_pair, mut notif_service) = - crate::protocol::notifications::service::notification_service("/foo".into()); let peer_store = PeerStore::new(if index == 0 { keypairs.iter().skip(1).map(|keypair| keypair.public().to_peer_id()).collect() } else { @@ -94,22 +91,16 @@ fn build_nodes() -> (Swarm, Swarm) { Box::new(peer_store.handle()), ); - let (notif_handle, command_stream) = protocol_handle_pair.split(); let behaviour = CustomProtoWithAddr { inner: Notifications::new( vec![controller_handle], from_controller, - None, - iter::once(( - ProtocolConfig { - name: "/foo".into(), - fallback_names: Vec::new(), - handshake: Vec::new(), - max_notification_size: 1024 * 1024, - }, - notif_handle, - command_stream, - )), + iter::once(ProtocolConfig { + name: "/foo".into(), + fallback_names: Vec::new(), + handshake: Vec::new(), + max_notification_size: 1024 * 1024, + }), ), peer_store_future: peer_store.run().boxed(), protocol_controller_future: controller.run().boxed(), @@ -127,16 +118,6 @@ fn build_nodes() -> (Swarm, Swarm) { }; let runtime = tokio::runtime::Runtime::new().unwrap(); - runtime.spawn(async move { - loop { - if let NotificationEvent::ValidateInboundSubstream { result_tx, .. } = - notif_service.next_event().await.unwrap() - { - result_tx.send(ValidationResult::Accept).unwrap(); - } - } - }); - let mut swarm = SwarmBuilder::with_executor( transport, behaviour, diff --git a/substrate/client/network/src/protocol/notifications/upgrade.rs b/substrate/client/network/src/protocol/notifications/upgrade.rs index 8fd837f949d..70c6023623f 100644 --- a/substrate/client/network/src/protocol/notifications/upgrade.rs +++ b/substrate/client/network/src/protocol/notifications/upgrade.rs @@ -16,14 +16,12 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -#[cfg(test)] -pub(crate) use self::notifications::{ - NotificationsInOpen, NotificationsInSubstreamHandshake, NotificationsOutOpen, -}; pub use self::{ collec::UpgradeCollec, notifications::{ - NotificationsIn, NotificationsInSubstream, NotificationsOut, NotificationsOutSubstream, + NotificationsHandshakeError, NotificationsIn, NotificationsInOpen, + NotificationsInSubstream, NotificationsInSubstreamHandshake, NotificationsOut, + NotificationsOutError, NotificationsOutOpen, NotificationsOutSubstream, }, }; diff --git a/substrate/client/network/src/protocol_controller.rs b/substrate/client/network/src/protocol_controller.rs index 4c8f119baa2..3a305011ded 100644 --- a/substrate/client/network/src/protocol_controller.rs +++ b/substrate/client/network/src/protocol_controller.rs @@ -847,7 +847,6 @@ mod tests { use super::*; use crate::{peer_store::PeerStoreProvider, ReputationChange}; use libp2p::PeerId; - use sc_network_common::role::ObservedRole; use sc_utils::mpsc::{tracing_unbounded, TryRecvError}; use std::collections::HashSet; @@ -859,10 +858,8 @@ mod tests { fn is_banned(&self, peer_id: &PeerId) -> bool; fn register_protocol(&self, protocol_handle: ProtocolHandle); fn report_disconnect(&mut self, peer_id: PeerId); - fn set_peer_role(&mut self, peer_id: &PeerId, role: ObservedRole); fn report_peer(&mut self, peer_id: PeerId, change: ReputationChange); fn peer_reputation(&self, peer_id: &PeerId) -> i32; - fn peer_role(&self, peer_id: &PeerId) -> Option; fn outgoing_candidates<'a>(&self, count: usize, ignored: HashSet<&'a PeerId>) -> Vec; } } diff --git a/substrate/client/network/src/service.rs b/substrate/client/network/src/service.rs index 06db23844d0..c1df48ad785 100644 --- a/substrate/client/network/src/service.rs +++ b/substrate/client/network/src/service.rs @@ -54,7 +54,6 @@ use crate::{ ReputationChange, }; -use codec::DecodeAll; use either::Either; use futures::{channel::oneshot, prelude::*}; #[allow(deprecated)] @@ -72,13 +71,10 @@ use libp2p::{ Multiaddr, PeerId, }; use log::{debug, error, info, trace, warn}; -use metrics::{Histogram, MetricSources, Metrics}; +use metrics::{Histogram, HistogramVec, MetricSources, Metrics}; use parking_lot::Mutex; -use sc_network_common::{ - role::{ObservedRole, Roles}, - ExHashT, -}; +use sc_network_common::ExHashT; use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender}; use sp_runtime::traits::Block as BlockT; @@ -120,10 +116,14 @@ pub struct NetworkService { local_identity: Keypair, /// Bandwidth logging system. Can be queried to know the average bandwidth consumed. bandwidth: Arc, - /// Used to query and report reputation changes. - peer_store_handle: PeerStoreHandle, /// Channel that sends messages to the actual worker. to_worker: TracingUnboundedSender, + /// For each peer and protocol combination, an object that allows sending notifications to + /// that peer. Updated by the [`NetworkWorker`]. + peers_notifications_sinks: Arc>>, + /// Field extracted from the [`Metrics`] struct and necessary to report the + /// notifications-related metrics. + notifications_sizes_metric: Option, /// Protocol name -> `SetId` mapping for notification protocols. The map never changes after /// initialization. notification_protocol_ids: HashMap, @@ -199,7 +199,7 @@ where )?; for notification_protocol in ¬ification_protocols { ensure_addresses_consistent_with_transport( - notification_protocol.set_config().reserved_nodes.iter().map(|x| &x.multiaddr), + notification_protocol.set_config.reserved_nodes.iter().map(|x| &x.multiaddr), &network_config.transport, )?; } @@ -241,7 +241,7 @@ where .map(|cfg| usize::try_from(cfg.max_response_size).unwrap_or(usize::MAX)); let notifs_max = notification_protocols .iter() - .map(|cfg| usize::try_from(cfg.max_notification_size()).unwrap_or(usize::MAX)); + .map(|cfg| usize::try_from(cfg.max_notification_size).unwrap_or(usize::MAX)); // A "default" max is added to cover all the other protocols: ping, identify, // kademlia, block announces, and transactions. @@ -273,7 +273,7 @@ where // We must prepend a hardcoded default peer set to notification protocols. let all_peer_sets_iter = iter::once(&network_config.default_peers_set) - .chain(notification_protocols.iter().map(|protocol| protocol.set_config())); + .chain(notification_protocols.iter().map(|protocol| &protocol.set_config)); let (protocol_handles, protocol_controllers): (Vec<_>, Vec<_>) = all_peer_sets_iter .enumerate() @@ -312,9 +312,21 @@ where iter::once(¶ms.block_announce_config) .chain(notification_protocols.iter()) .enumerate() - .map(|(index, protocol)| (protocol.protocol_name().clone(), SetId::from(index))) + .map(|(index, protocol)| { + (protocol.notifications_protocol.clone(), SetId::from(index)) + }) .collect(); + let protocol = Protocol::new( + From::from(¶ms.role), + notification_protocols.clone(), + params.block_announce_config, + params.peer_store.clone(), + protocol_handles.clone(), + from_protocol_controllers, + params.tx, + )?; + let known_addresses = { // Collect all reserved nodes and bootnodes addresses. let mut addresses: Vec<_> = network_config @@ -324,7 +336,7 @@ where .map(|reserved| (reserved.peer_id, reserved.multiaddr.clone())) .chain(notification_protocols.iter().flat_map(|protocol| { protocol - .set_config() + .set_config .reserved_nodes .iter() .map(|reserved| (reserved.peer_id, reserved.multiaddr.clone())) @@ -377,16 +389,6 @@ where let num_connected = Arc::new(AtomicUsize::new(0)); let external_addresses = Arc::new(Mutex::new(HashSet::new())); - let (protocol, notif_protocol_handles) = Protocol::new( - From::from(¶ms.role), - ¶ms.metrics_registry, - notification_protocols, - params.block_announce_config, - params.peer_store.clone(), - protocol_handles.clone(), - from_protocol_controllers, - )?; - // Build the swarm. let (mut swarm, bandwidth): (Swarm>, _) = { let user_agent = @@ -506,6 +508,7 @@ where } let listen_addresses = Arc::new(Mutex::new(HashSet::new())); + let peers_notifications_sinks = Arc::new(Mutex::new(HashMap::new())); let service = Arc::new(NetworkService { bandwidth, @@ -515,10 +518,13 @@ where local_peer_id, local_identity, to_worker, + peers_notifications_sinks: peers_notifications_sinks.clone(), + notifications_sizes_metric: metrics + .as_ref() + .map(|metrics| metrics.notifications_sizes.clone()), notification_protocol_ids, protocol_handles, sync_protocol_handle, - peer_store_handle: params.peer_store.clone(), _marker: PhantomData, _block: Default::default(), }); @@ -533,8 +539,8 @@ where metrics, boot_node_ids, reported_invalid_boot_nodes: Default::default(), + peers_notifications_sinks, peer_store_handle: params.peer_store, - notif_protocol_handles, _marker: Default::default(), _block: Default::default(), }) @@ -561,7 +567,7 @@ where /// Returns the number of peers we're connected to. pub fn num_connected_peers(&self) -> usize { - self.network_service.behaviour().user_protocol().num_sync_peers() + self.network_service.behaviour().user_protocol().num_connected_peers() } /// Adds an address for a node. @@ -865,18 +871,12 @@ where .unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id, addr)); } - fn report_peer(&self, peer_id: PeerId, cost_benefit: ReputationChange) { - self.peer_store_handle.clone().report_peer(peer_id, cost_benefit); - } - - fn peer_reputation(&self, peer_id: &PeerId) -> i32 { - self.peer_store_handle.peer_reputation(peer_id) + fn report_peer(&self, who: PeerId, cost_benefit: ReputationChange) { + let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::ReportPeer(who, cost_benefit)); } - fn disconnect_peer(&self, peer_id: PeerId, protocol: ProtocolName) { - let _ = self - .to_worker - .unbounded_send(ServiceToWorkerMsg::DisconnectPeer(peer_id, protocol)); + fn disconnect_peer(&self, who: PeerId, protocol: ProtocolName) { + let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::DisconnectPeer(who, protocol)); } fn accept_unreserved_peers(&self) { @@ -991,16 +991,6 @@ where fn sync_num_connected(&self) -> usize { self.num_connected.load(Ordering::Relaxed) } - - fn peer_role(&self, peer_id: PeerId, handshake: Vec) -> Option { - match Roles::decode_all(&mut &handshake[..]) { - Ok(role) => Some(role.into()), - Err(_) => { - log::debug!(target: "sub-libp2p", "handshake doesn't contain peer role: {handshake:?}"); - self.peer_store_handle.peer_role(&peer_id) - }, - } - } } impl NetworkEventStream for NetworkService @@ -1020,20 +1010,68 @@ where B: BlockT + 'static, H: ExHashT, { - fn write_notification(&self, _target: PeerId, _protocol: ProtocolName, _message: Vec) { - unimplemented!(); + fn write_notification(&self, target: PeerId, protocol: ProtocolName, message: Vec) { + // We clone the `NotificationsSink` in order to be able to unlock the network-wide + // `peers_notifications_sinks` mutex as soon as possible. + let sink = { + let peers_notifications_sinks = self.peers_notifications_sinks.lock(); + if let Some(sink) = peers_notifications_sinks.get(&(target, protocol.clone())) { + sink.clone() + } else { + // Notification silently discarded, as documented. + debug!( + target: "sub-libp2p", + "Attempted to send notification on missing or closed substream: {}, {:?}", + target, protocol, + ); + return + } + }; + + if let Some(notifications_sizes_metric) = self.notifications_sizes_metric.as_ref() { + notifications_sizes_metric + .with_label_values(&["out", &protocol]) + .observe(message.len() as f64); + } + + // Sending is communicated to the `NotificationsSink`. + trace!( + target: "sub-libp2p", + "External API => Notification({:?}, {:?}, {} bytes)", + target, protocol, message.len() + ); + trace!(target: "sub-libp2p", "Handler({:?}) <= Sync notification", target); + sink.send_sync_notification(message); } fn notification_sender( &self, - _target: PeerId, - _protocol: ProtocolName, + target: PeerId, + protocol: ProtocolName, ) -> Result, NotificationSenderError> { - unimplemented!(); + // We clone the `NotificationsSink` in order to be able to unlock the network-wide + // `peers_notifications_sinks` mutex as soon as possible. + let sink = { + let peers_notifications_sinks = self.peers_notifications_sinks.lock(); + if let Some(sink) = peers_notifications_sinks.get(&(target, protocol.clone())) { + sink.clone() + } else { + return Err(NotificationSenderError::Closed) + } + }; + + let notification_size_metric = self + .notifications_sizes_metric + .as_ref() + .map(|histogram| histogram.with_label_values(&["out", &protocol])); + + Ok(Box::new(NotificationSender { sink, protocol_name: protocol, notification_size_metric })) } - fn set_notification_handshake(&self, _protocol: ProtocolName, _handshake: Vec) { - unimplemented!(); + fn set_notification_handshake(&self, protocol: ProtocolName, handshake: Vec) { + let _ = self + .to_worker + .unbounded_send(ServiceToWorkerMsg::SetNotificationHandshake(protocol, handshake)); } } @@ -1155,6 +1193,7 @@ enum ServiceToWorkerMsg { GetValue(KademliaKey), PutValue(KademliaKey, Vec), AddKnownAddress(PeerId, Multiaddr), + ReportPeer(PeerId, ReputationChange), EventStream(out_events::Sender), Request { target: PeerId, @@ -1170,6 +1209,7 @@ enum ServiceToWorkerMsg { pending_response: oneshot::Sender>, }, DisconnectPeer(PeerId, ProtocolName), + SetNotificationHandshake(ProtocolName, Vec), } /// Main network worker. Must be polled in order for the network to advance. @@ -1199,10 +1239,11 @@ where boot_node_ids: Arc>>, /// Boot nodes that we already have reported as invalid. reported_invalid_boot_nodes: HashSet, + /// For each peer and protocol combination, an object that allows sending notifications to + /// that peer. Shared with the [`NetworkService`]. + peers_notifications_sinks: Arc>>, /// Peer reputation store handle. peer_store_handle: PeerStoreHandle, - /// Notification protocol handles. - notif_protocol_handles: Vec, /// Marker to pin the `H` generic. Serves no purpose except to not break backwards /// compatibility. _marker: PhantomData, @@ -1241,7 +1282,8 @@ where }; // Update the `num_connected` count shared with the `NetworkService`. - let num_connected_peers = self.network_service.behaviour().user_protocol().num_sync_peers(); + let num_connected_peers = + self.network_service.behaviour_mut().user_protocol_mut().num_connected_peers(); self.num_connected.store(num_connected_peers, Ordering::Relaxed); if let Some(metrics) = self.metrics.as_ref() { @@ -1282,6 +1324,8 @@ where self.network_service.behaviour_mut().put_value(key, value), ServiceToWorkerMsg::AddKnownAddress(peer_id, addr) => self.network_service.behaviour_mut().add_known_address(peer_id, addr), + ServiceToWorkerMsg::ReportPeer(peer_id, reputation_change) => + self.peer_store_handle.report_peer(peer_id, reputation_change), ServiceToWorkerMsg::EventStream(sender) => self.event_streams.push(sender), ServiceToWorkerMsg::Request { target, @@ -1309,6 +1353,11 @@ where .behaviour_mut() .user_protocol_mut() .disconnect_peer(&who, protocol_name), + ServiceToWorkerMsg::SetNotificationHandshake(protocol, handshake) => self + .network_service + .behaviour_mut() + .user_protocol_mut() + .set_notification_handshake(protocol, handshake), } } @@ -1423,27 +1472,47 @@ where }, SwarmEvent::Behaviour(BehaviourOut::NotificationStreamOpened { remote, - set_id, - direction, + protocol, negotiated_fallback, notifications_sink, + role, received_handshake, }) => { - let _ = self.notif_protocol_handles[usize::from(set_id)].report_substream_opened( + if let Some(metrics) = self.metrics.as_ref() { + metrics + .notifications_streams_opened_total + .with_label_values(&[&protocol]) + .inc(); + } + { + let mut peers_notifications_sinks = self.peers_notifications_sinks.lock(); + let _previous_value = peers_notifications_sinks + .insert((remote, protocol.clone()), notifications_sink); + debug_assert!(_previous_value.is_none()); + } + self.event_streams.send(Event::NotificationStreamOpened { remote, - direction, - received_handshake, + protocol, negotiated_fallback, - notifications_sink, - ); + role, + received_handshake, + }); }, SwarmEvent::Behaviour(BehaviourOut::NotificationStreamReplaced { remote, - set_id, + protocol, notifications_sink, }) => { - let _ = self.notif_protocol_handles[usize::from(set_id)] - .report_notification_sink_replaced(remote, notifications_sink); + let mut peers_notifications_sinks = self.peers_notifications_sinks.lock(); + if let Some(s) = peers_notifications_sinks.get_mut(&(remote, protocol)) { + *s = notifications_sink; + } else { + error!( + target: "sub-libp2p", + "NotificationStreamReplaced for non-existing substream" + ); + debug_assert!(false); + } // TODO: Notifications might have been lost as a result of the previous // connection being dropped, and as a result it would be preferable to notify @@ -1466,17 +1535,31 @@ where // role, // }); }, - SwarmEvent::Behaviour(BehaviourOut::NotificationStreamClosed { remote, set_id }) => { - let _ = self.notif_protocol_handles[usize::from(set_id)] - .report_substream_closed(remote); + SwarmEvent::Behaviour(BehaviourOut::NotificationStreamClosed { remote, protocol }) => { + if let Some(metrics) = self.metrics.as_ref() { + metrics + .notifications_streams_closed_total + .with_label_values(&[&protocol[..]]) + .inc(); + } + self.event_streams + .send(Event::NotificationStreamClosed { remote, protocol: protocol.clone() }); + { + let mut peers_notifications_sinks = self.peers_notifications_sinks.lock(); + let _previous_value = peers_notifications_sinks.remove(&(remote, protocol)); + debug_assert!(_previous_value.is_some()); + } }, - SwarmEvent::Behaviour(BehaviourOut::NotificationsReceived { - remote, - set_id, - notification, - }) => { - let _ = self.notif_protocol_handles[usize::from(set_id)] - .report_notification_received(remote, notification); + SwarmEvent::Behaviour(BehaviourOut::NotificationsReceived { remote, messages }) => { + if let Some(metrics) = self.metrics.as_ref() { + for (protocol, message) in &messages { + metrics + .notifications_sizes + .with_label_values(&["in", protocol]) + .observe(message.len() as f64); + } + } + self.event_streams.send(Event::NotificationsReceived { remote, messages }); }, SwarmEvent::Behaviour(BehaviourOut::Dht(event, duration)) => { if let Some(metrics) = self.metrics.as_ref() { diff --git a/substrate/client/network/src/service/metrics.rs b/substrate/client/network/src/service/metrics.rs index c349fd98c76..13bc4b4e7af 100644 --- a/substrate/client/network/src/service/metrics.rs +++ b/substrate/client/network/src/service/metrics.rs @@ -61,6 +61,9 @@ pub struct Metrics { pub kbuckets_num_nodes: GaugeVec, pub listeners_local_addresses: Gauge, pub listeners_errors_total: Counter, + pub notifications_sizes: HistogramVec, + pub notifications_streams_closed_total: CounterVec, + pub notifications_streams_opened_total: CounterVec, pub peerset_num_discovered: Gauge, pub pending_connections: Gauge, pub pending_connections_errors_total: CounterVec, @@ -150,6 +153,31 @@ impl Metrics { "substrate_sub_libp2p_listeners_errors_total", "Total number of non-fatal errors reported by a listener" )?, registry)?, + notifications_sizes: prometheus::register(HistogramVec::new( + HistogramOpts { + common_opts: Opts::new( + "substrate_sub_libp2p_notifications_sizes", + "Sizes of the notifications send to and received from all nodes" + ), + buckets: prometheus::exponential_buckets(64.0, 4.0, 8) + .expect("parameters are always valid values; qed"), + }, + &["direction", "protocol"] + )?, registry)?, + notifications_streams_closed_total: prometheus::register(CounterVec::new( + Opts::new( + "substrate_sub_libp2p_notifications_streams_closed_total", + "Total number of notification substreams that have been closed" + ), + &["protocol"] + )?, registry)?, + notifications_streams_opened_total: prometheus::register(CounterVec::new( + Opts::new( + "substrate_sub_libp2p_notifications_streams_opened_total", + "Total number of notification substreams that have been opened" + ), + &["protocol"] + )?, registry)?, peerset_num_discovered: prometheus::register(Gauge::new( "substrate_sub_libp2p_peerset_num_discovered", "Number of nodes stored in the peerset manager", diff --git a/substrate/client/network/src/service/signature.rs b/substrate/client/network/src/service/signature.rs index 5b2ba6be8cf..024f60e4c46 100644 --- a/substrate/client/network/src/service/signature.rs +++ b/substrate/client/network/src/service/signature.rs @@ -18,8 +18,6 @@ // // If you read this, you are very thorough, congratulations. -//! Signature-related code - use libp2p::{ identity::{Keypair, PublicKey}, PeerId, diff --git a/substrate/client/network/src/service/traits.rs b/substrate/client/network/src/service/traits.rs index d4d4a05a86f..bed325ede4a 100644 --- a/substrate/client/network/src/service/traits.rs +++ b/substrate/client/network/src/service/traits.rs @@ -18,11 +18,8 @@ // // If you read this, you are very thorough, congratulations. -//! Traits defined by `sc-network`. - use crate::{ config::MultiaddrWithPeerId, - error, event::Event, request_responses::{IfDisconnected, RequestFailure}, service::signature::Signature, @@ -33,9 +30,7 @@ use crate::{ use futures::{channel::oneshot, Stream}; use libp2p::{Multiaddr, PeerId}; -use sc_network_common::role::ObservedRole; - -use std::{collections::HashSet, fmt::Debug, future::Future, pin::Pin, sync::Arc}; +use std::{collections::HashSet, future::Future, pin::Pin, sync::Arc}; pub use libp2p::{identity::SigningError, kad::record::Key as KademliaKey}; @@ -155,15 +150,12 @@ pub trait NetworkPeers { /// Report a given peer as either beneficial (+) or costly (-) according to the /// given scalar. - fn report_peer(&self, peer_id: PeerId, cost_benefit: ReputationChange); - - /// Get peer reputation. - fn peer_reputation(&self, peer_id: &PeerId) -> i32; + fn report_peer(&self, who: PeerId, cost_benefit: ReputationChange); /// Disconnect from a node as soon as possible. /// /// This triggers the same effects as if the connection had closed itself spontaneously. - fn disconnect_peer(&self, peer_id: PeerId, protocol: ProtocolName); + fn disconnect_peer(&self, who: PeerId, protocol: ProtocolName); /// Connect to unreserved peers and allow unreserved peers to connect for syncing purposes. fn accept_unreserved_peers(&self); @@ -229,14 +221,6 @@ pub trait NetworkPeers { /// Returns the number of peers in the sync peer set we're connected to. fn sync_num_connected(&self) -> usize; - - /// Attempt to get peer role. - /// - /// Right now the peer role is decoded from the received handshake for all protocols - /// (`/block-announces/1` has other information as well). If the handshake cannot be - /// decoded into a role, the role queried from `PeerStore` and if the role is not stored - /// there either, `None` is returned and the peer should be discarded. - fn peer_role(&self, peer_id: PeerId, handshake: Vec) -> Option; } // Manual implementation to avoid extra boxing here @@ -257,16 +241,16 @@ where T::add_known_address(self, peer_id, addr) } - fn report_peer(&self, peer_id: PeerId, cost_benefit: ReputationChange) { - T::report_peer(self, peer_id, cost_benefit) + fn report_peer(&self, who: PeerId, cost_benefit: ReputationChange) { + // TODO: when we get rid of `Peerset`, we'll likely need to add some kind of async + // interface to `PeerStore`, otherwise we'll have trouble calling functions accepting + // `&mut self` via `Arc`. + // See https://github.com/paritytech/substrate/issues/14170. + T::report_peer(self, who, cost_benefit) } - fn peer_reputation(&self, peer_id: &PeerId) -> i32 { - T::peer_reputation(self, peer_id) - } - - fn disconnect_peer(&self, peer_id: PeerId, protocol: ProtocolName) { - T::disconnect_peer(self, peer_id, protocol) + fn disconnect_peer(&self, who: PeerId, protocol: ProtocolName) { + T::disconnect_peer(self, who, protocol) } fn accept_unreserved_peers(&self) { @@ -312,10 +296,6 @@ where fn sync_num_connected(&self) -> usize { T::sync_num_connected(self) } - - fn peer_role(&self, peer_id: PeerId, handshake: Vec) -> Option { - T::peer_role(self, peer_id, handshake) - } } /// Provides access to network-level event stream. @@ -631,189 +611,3 @@ where T::new_best_block_imported(self, hash, number) } } - -/// Substream acceptance result. -#[derive(Debug, PartialEq, Eq)] -pub enum ValidationResult { - /// Accept inbound substream. - Accept, - - /// Reject inbound substream. - Reject, -} - -/// Substream direction. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum Direction { - /// Substream opened by the remote node. - Inbound, - - /// Substream opened by the local node. - Outbound, -} - -impl Direction { - /// Is the direction inbound. - pub fn is_inbound(&self) -> bool { - std::matches!(self, Direction::Inbound) - } -} - -/// Events received by the protocol from `Notifications`. -#[derive(Debug)] -pub enum NotificationEvent { - /// Validate inbound substream. - ValidateInboundSubstream { - /// Peer ID. - peer: PeerId, - - /// Received handshake. - handshake: Vec, - - /// `oneshot::Sender` for sending validation result back to `Notifications` - result_tx: tokio::sync::oneshot::Sender, - }, - - /// Remote identified by `PeerId` opened a substream and sent `Handshake`. - /// Validate `Handshake` and report status (accept/reject) to `Notifications`. - NotificationStreamOpened { - /// Peer ID. - peer: PeerId, - - /// Is the substream inbound or outbound. - direction: Direction, - - /// Received handshake. - handshake: Vec, - - /// Negotiated fallback. - negotiated_fallback: Option, - }, - - /// Substream was closed. - NotificationStreamClosed { - /// Peer Id. - peer: PeerId, - }, - - /// Notification was received from the substream. - NotificationReceived { - /// Peer ID. - peer: PeerId, - - /// Received notification. - notification: Vec, - }, -} - -/// Notification service -/// -/// Defines behaviors that both the protocol implementations and `Notifications` can expect from -/// each other. -/// -/// `Notifications` can send two different kinds of information to protocol: -/// * substream-related information -/// * notification-related information -/// -/// When an unvalidated, inbound substream is received by `Notifications`, it sends the inbound -/// stream information (peer ID, handshake) to protocol for validation. Protocol must then verify -/// that the handshake is valid (and in the future that it has a slot it can allocate for the peer) -/// and then report back the `ValidationResult` which is either `Accept` or `Reject`. -/// -/// After the validation result has been received by `Notifications`, it prepares the -/// substream for communication by initializing the necessary sinks and emits -/// `NotificationStreamOpened` which informs the protocol that the remote peer is ready to receive -/// notifications. -/// -/// Two different flavors of sending options are provided: -/// * synchronous sending ([`NotificationService::send_sync_notification()`]) -/// * asynchronous sending ([`NotificationService::send_async_notification()`]) -/// -/// The former is used by the protocols not ready to exercise backpressure and the latter by the -/// protocols that can do it. -/// -/// Both local and remote peer can close the substream at any time. Local peer can do so by calling -/// [`NotificationService::close_substream()`] which instructs `Notifications` to close the -/// substream. Remote closing the substream is indicated to the local peer by receiving -/// [`NotificationEvent::NotificationStreamClosed`] event. -/// -/// In case the protocol must update its handshake while it's operating (such as updating the best -/// block information), it can do so by calling [`NotificationService::set_handshake()`] -/// which instructs `Notifications` to update the handshake it stored during protocol -/// initialization. -/// -/// All peer events are multiplexed on the same incoming event stream from `Notifications` and thus -/// each event carries a `PeerId` so the protocol knows whose information to update when receiving -/// an event. -#[async_trait::async_trait] -pub trait NotificationService: Debug + Send { - /// Instruct `Notifications` to open a new substream for `peer`. - /// - /// `dial_if_disconnected` informs `Notifications` whether to dial - // the peer if there is currently no active connection to it. - // - // NOTE: not offered by the current implementation - async fn open_substream(&mut self, peer: PeerId) -> Result<(), ()>; - - /// Instruct `Notifications` to close substream for `peer`. - // - // NOTE: not offered by the current implementation - async fn close_substream(&mut self, peer: PeerId) -> Result<(), ()>; - - /// Send synchronous `notification` to `peer`. - fn send_sync_notification(&self, peer: &PeerId, notification: Vec); - - /// Send asynchronous `notification` to `peer`, allowing sender to exercise backpressure. - /// - /// Returns an error if the peer doesn't exist. - async fn send_async_notification( - &self, - peer: &PeerId, - notification: Vec, - ) -> Result<(), error::Error>; - - /// Set handshake for the notification protocol replacing the old handshake. - async fn set_handshake(&mut self, handshake: Vec) -> Result<(), ()>; - - /// Non-blocking variant of `set_handshake()` that attempts to update the handshake - /// and returns an error if the channel is blocked. - /// - /// Technically the function can return an error if the channel to `Notifications` is closed - /// but that doesn't happen under normal operation. - fn try_set_handshake(&mut self, handshake: Vec) -> Result<(), ()>; - - /// Get next event from the `Notifications` event stream. - async fn next_event(&mut self) -> Option; - - /// Make a copy of the object so it can be shared between protocol components - /// who wish to have access to the same underlying notification protocol. - fn clone(&mut self) -> Result, ()>; - - /// Get protocol name of the `NotificationService`. - fn protocol(&self) -> &ProtocolName; - - /// Get message sink of the peer. - fn message_sink(&self, peer: &PeerId) -> Option>; -} - -/// Message sink for peers. -/// -/// If protocol cannot use [`NotificationService`] to send notifications to peers and requires, -/// e.g., notifications to be sent in another task, the protocol may acquire a [`MessageSink`] -/// object for each peer by calling [`NotificationService::message_sink()`]. Calling this -/// function returns an object which allows the protocol to send notifications to the remote peer. -/// -/// Use of this API is discouraged as it's not as performant as sending notifications through -/// [`NotificationService`] due to synchronization required to keep the underlying notification -/// sink up to date with possible sink replacement events. -#[async_trait::async_trait] -pub trait MessageSink: Send + Sync { - /// Send synchronous `notification` to the peer associated with this [`MessageSink`]. - fn send_sync_notification(&self, notification: Vec); - - /// Send an asynchronous `notification` to to the peer associated with this [`MessageSink`], - /// allowing sender to exercise backpressure. - /// - /// Returns an error if the peer does not exist. - async fn send_async_notification(&self, notification: Vec) -> Result<(), error::Error>; -} diff --git a/substrate/client/network/statement/Cargo.toml b/substrate/client/network/statement/Cargo.toml index e07eb939ea3..ef974b4f33f 100644 --- a/substrate/client/network/statement/Cargo.toml +++ b/substrate/client/network/statement/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true documentation = "https://docs.rs/sc-network-statement" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/network/statement/src/lib.rs b/substrate/client/network/statement/src/lib.rs index 5187e681d83..69d4faa13ef 100644 --- a/substrate/client/network/statement/src/lib.rs +++ b/substrate/client/network/statement/src/lib.rs @@ -21,13 +21,12 @@ //! Usage: //! //! - Use [`StatementHandlerPrototype::new`] to create a prototype. -//! - Pass the `NonDefaultSetConfig` returned from [`StatementHandlerPrototype::new`] to the network -//! configuration as an extra peers set. +//! - Pass the return value of [`StatementHandlerPrototype::set_config`] to the network +//! configuration as an extra peers set. //! - Use [`StatementHandlerPrototype::build`] then [`StatementHandler::run`] to obtain a //! `Future` that processes statements. use crate::config::*; - use codec::{Decode, Encode}; use futures::{channel::oneshot, prelude::*, stream::FuturesUnordered, FutureExt}; use libp2p::{multiaddr, PeerId}; @@ -35,7 +34,7 @@ use prometheus_endpoint::{register, Counter, PrometheusError, Registry, U64}; use sc_network::{ config::{NonDefaultSetConfig, NonReservedPeerMode, SetConfig}, error, - service::traits::{NotificationEvent, NotificationService, ValidationResult}, + event::Event, types::ProtocolName, utils::{interval, LruHashSet}, NetworkEventStream, NetworkNotification, NetworkPeers, @@ -102,35 +101,35 @@ impl Metrics { /// Prototype for a [`StatementHandler`]. pub struct StatementHandlerPrototype { protocol_name: ProtocolName, - notification_service: Box, } impl StatementHandlerPrototype { /// Create a new instance. - pub fn new>( - genesis_hash: Hash, - fork_id: Option<&str>, - ) -> (Self, NonDefaultSetConfig) { + pub fn new>(genesis_hash: Hash, fork_id: Option<&str>) -> Self { let genesis_hash = genesis_hash.as_ref(); let protocol_name = if let Some(fork_id) = fork_id { format!("/{}/{}/statement/1", array_bytes::bytes2hex("", genesis_hash), fork_id) } else { format!("/{}/statement/1", array_bytes::bytes2hex("", genesis_hash)) }; - let (config, notification_service) = NonDefaultSetConfig::new( - protocol_name.clone().into(), - Vec::new(), - MAX_STATEMENT_SIZE, - None, - SetConfig { + + Self { protocol_name: protocol_name.into() } + } + + /// Returns the configuration of the set to put in the network configuration. + pub fn set_config(&self) -> NonDefaultSetConfig { + NonDefaultSetConfig { + notifications_protocol: self.protocol_name.clone(), + fallback_names: Vec::new(), + max_notification_size: MAX_STATEMENT_SIZE, + handshake: None, + set_config: SetConfig { in_peers: 0, out_peers: 0, reserved_nodes: Vec::new(), non_reserved_mode: NonReservedPeerMode::Deny, }, - ); - - (Self { protocol_name: protocol_name.into(), notification_service }, config) + } } /// Turns the prototype into the actual handler. @@ -148,6 +147,7 @@ impl StatementHandlerPrototype { metrics_registry: Option<&Registry>, executor: impl Fn(Pin + Send>>) + Send, ) -> error::Result> { + let net_event_stream = network.event_stream("statement-handler-net"); let sync_event_stream = sync.event_stream("statement-handler-sync"); let (queue_sender, mut queue_receiver) = async_channel::bounded(100_000); @@ -176,7 +176,6 @@ impl StatementHandlerPrototype { let handler = StatementHandler { protocol_name: self.protocol_name, - notification_service: self.notification_service, propagate_timeout: (Box::pin(interval(PROPAGATE_TIMEOUT)) as Pin + Send>>) .fuse(), @@ -184,6 +183,7 @@ impl StatementHandlerPrototype { pending_statements_peers: HashMap::new(), network, sync, + net_event_stream: net_event_stream.fuse(), sync_event_stream: sync_event_stream.fuse(), peers: HashMap::new(), statement_store, @@ -219,10 +219,10 @@ pub struct StatementHandler< network: N, /// Syncing service. sync: S, + /// Stream of networking events. + net_event_stream: stream::Fuse + Send>>>, /// Receiver for syncing-related events. sync_event_stream: stream::Fuse + Send>>>, - /// Notification service. - notification_service: Box, // All connected peers peers: HashMap, statement_store: Arc, @@ -261,6 +261,14 @@ where log::warn!(target: LOG_TARGET, "Inconsistent state, no peers for pending statement!"); } }, + network_event = self.net_event_stream.next() => { + if let Some(network_event) = network_event { + self.handle_network_event(network_event).await; + } else { + // Networking has seemingly closed. Closing as well. + return; + } + }, sync_event = self.sync_event_stream.next() => { if let Some(sync_event) = sync_event { self.handle_sync_event(sync_event); @@ -269,14 +277,6 @@ where return; } } - event = self.notification_service.next_event().fuse() => { - if let Some(event) = event { - self.handle_notification_event(event) - } else { - // `Notifications` has seemingly closed. Closing as well. - return - } - } } } } @@ -306,24 +306,14 @@ where } } - fn handle_notification_event(&mut self, event: NotificationEvent) { + async fn handle_network_event(&mut self, event: Event) { match event { - NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx, .. } => { - // only accept peers whose role can be determined - let result = self - .network - .peer_role(peer, handshake) - .map_or(ValidationResult::Reject, |_| ValidationResult::Accept); - let _ = result_tx.send(result); - }, - NotificationEvent::NotificationStreamOpened { peer, handshake, .. } => { - let Some(role) = self.network.peer_role(peer, handshake) else { - log::debug!(target: LOG_TARGET, "role for {peer} couldn't be determined"); - return - }; - + Event::Dht(_) => {}, + Event::NotificationStreamOpened { remote, protocol, role, .. } + if protocol == self.protocol_name => + { let _was_in = self.peers.insert( - peer, + remote, Peer { known_statements: LruHashSet::new( NonZeroUsize::new(MAX_KNOWN_STATEMENTS).expect("Constant is nonzero"), @@ -333,26 +323,39 @@ where ); debug_assert!(_was_in.is_none()); }, - NotificationEvent::NotificationStreamClosed { peer } => { - let _peer = self.peers.remove(&peer); + Event::NotificationStreamClosed { remote, protocol } + if protocol == self.protocol_name => + { + let _peer = self.peers.remove(&remote); debug_assert!(_peer.is_some()); }, - NotificationEvent::NotificationReceived { peer, notification } => { - // Accept statements only when node is not major syncing - if self.sync.is_major_syncing() { - log::trace!( - target: LOG_TARGET, - "{peer}: Ignoring statements while major syncing or offline" - ); - return - } - if let Ok(statements) = ::decode(&mut notification.as_ref()) { - self.on_statements(peer, statements); - } else { - log::debug!(target: LOG_TARGET, "Failed to decode statement list from {peer}"); + Event::NotificationsReceived { remote, messages } => { + for (protocol, message) in messages { + if protocol != self.protocol_name { + continue + } + // Accept statements only when node is not major syncing + if self.sync.is_major_syncing() { + log::trace!( + target: LOG_TARGET, + "{remote}: Ignoring statements while major syncing or offline" + ); + continue + } + if let Ok(statements) = ::decode(&mut message.as_ref()) { + self.on_statements(remote, statements); + } else { + log::debug!( + target: LOG_TARGET, + "Failed to decode statement list from {remote}" + ); + } } }, + + // Not our concern. + Event::NotificationStreamOpened { .. } | Event::NotificationStreamClosed { .. } => {}, } } diff --git a/substrate/client/network/sync/Cargo.toml b/substrate/client/network/sync/Cargo.toml index f20592d5f25..a1ea39a852f 100644 --- a/substrate/client/network/sync/Cargo.toml +++ b/substrate/client/network/sync/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true documentation = "https://docs.rs/sc-network-sync" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -33,7 +30,7 @@ schnellru = "0.2.1" smallvec = "1.11.0" thiserror = "1.0" tokio-stream = "0.1.14" -tokio = { version = "1.32.0", features = ["macros", "time"] } +tokio = { version = "1.32.0", features = ["time", "macros"] } fork-tree = { path = "../../../utils/fork-tree" } prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus" } sc-client-api = { path = "../../api" } diff --git a/substrate/client/network/sync/src/engine.rs b/substrate/client/network/sync/src/engine.rs index d7b024cd801..2cb8eab22f7 100644 --- a/substrate/client/network/sync/src/engine.rs +++ b/substrate/client/network/sync/src/engine.rs @@ -38,7 +38,7 @@ use crate::{ warp::{EncodedProof, WarpProofRequest, WarpSyncParams}, }; -use codec::{Decode, DecodeAll, Encode}; +use codec::{Decode, Encode}; use futures::{ channel::oneshot, future::{BoxFuture, Fuse}, @@ -61,12 +61,9 @@ use sc_network::{ FullNetworkConfiguration, NonDefaultSetConfig, NonReservedPeerMode, NotificationHandshake, ProtocolId, SetConfig, }, - peer_store::{PeerStoreHandle, PeerStoreProvider}, request_responses::{IfDisconnected, RequestFailure}, - service::traits::{Direction, NotificationEvent, ValidationResult}, - types::ProtocolName, utils::LruHashSet, - NotificationService, ReputationChange, + NotificationsSink, ProtocolName, ReputationChange, }; use sc_network_common::{ role::Roles, @@ -91,15 +88,15 @@ use std::{ time::{Duration, Instant}, }; +/// Log target for this file. +const LOG_TARGET: &'static str = "sync"; + /// Interval at which we perform time based maintenance const TICK_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(1100); /// Maximum number of known block hashes to keep for a peer. const MAX_KNOWN_BLOCKS: usize = 1024; // ~32kb per peer + LruHashSet overhead -/// Logging target for the file. -const LOG_TARGET: &str = "sync"; - /// If the block announces stream to peer has been inactive for 30 seconds meaning local node /// has not sent or received block announcements to/from the peer, report the node for inactivity, /// disconnect it and attempt to establish connection to some other peer. @@ -229,6 +226,8 @@ pub struct Peer { pub info: ExtendedPeerInfo, /// Holds a set of blocks known to this peer. pub known_blocks: LruHashSet, + /// Notification sink. + sink: NotificationsSink, /// Is the peer inbound. inbound: bool, } @@ -253,6 +252,9 @@ pub struct SyncingEngine { /// Channel for receiving service commands service_rx: TracingUnboundedReceiver>, + /// Channel for receiving inbound connections from `Protocol`. + sync_events_rx: sc_utils::mpsc::TracingUnboundedReceiver>, + /// Assigned roles. roles: Roles, @@ -310,18 +312,12 @@ pub struct SyncingEngine { /// Prometheus metrics. metrics: Option, - /// Handle that is used to communicate with `sc_network::Notifications`. - notification_service: Box, - /// When the syncing was started. /// /// Stored as an `Option` so once the initial wait has passed, `SyncingEngine` /// can reset the peer timers and continue with the normal eviction process. syncing_started: Option, - /// Handle to `PeerStore`. - peer_store_handle: PeerStoreHandle, - /// Instant when the last notification was sent or received. last_notification_io: Instant, @@ -366,7 +362,7 @@ where block_downloader: Arc>, state_request_protocol_name: ProtocolName, warp_sync_protocol_name: Option, - peer_store_handle: PeerStoreHandle, + sync_events_rx: sc_utils::mpsc::TracingUnboundedReceiver>, ) -> Result<(Self, SyncingService, NonDefaultSetConfig), ClientError> { let mode = net_config.network_config.sync_mode; let max_parallel_downloads = net_config.network_config.max_parallel_downloads; @@ -391,7 +387,7 @@ where } for config in net_config.notification_protocols() { let peer_ids = config - .set_config() + .set_config .reserved_nodes .iter() .map(|info| info.peer_id) @@ -442,7 +438,7 @@ where let warp_sync_target_block_header_rx_fused = warp_sync_target_block_header_rx .map_or(futures::future::pending().boxed().fuse(), |rx| rx.boxed().fuse()); - let (block_announce_config, notification_service) = Self::get_block_announce_proto_config( + let block_announce_config = Self::get_block_announce_proto_config( protocol_id, fork_id, roles, @@ -454,6 +450,7 @@ where .flatten() .expect("Genesis block exists; qed"), ); + let block_announce_protocol_name = block_announce_config.notifications_protocol.clone(); let chain_sync = ChainSync::new( mode, @@ -463,7 +460,6 @@ where warp_sync_config, )?; - let block_announce_protocol_name = block_announce_config.protocol_name().clone(); let (tx, service_rx) = tracing_unbounded("mpsc_chain_sync", 100_000); let num_connected = Arc::new(AtomicUsize::new(0)); let is_major_syncing = Arc::new(AtomicBool::new(false)); @@ -500,6 +496,7 @@ where num_connected: num_connected.clone(), is_major_syncing: is_major_syncing.clone(), service_rx, + sync_events_rx, genesis_hash, important_peers, default_peers_set_no_slot_connected_peers: HashSet::new(), @@ -511,10 +508,8 @@ where num_in_peers: 0usize, max_in_peers, event_streams: Vec::new(), - notification_service, tick_timeout, syncing_started: None, - peer_store_handle, last_notification_io: Instant::now(), metrics: if let Some(r) = metrics_registry { match Metrics::register(r, is_major_syncing.clone()) { @@ -678,11 +673,23 @@ where }; self.last_notification_io = Instant::now(); - let _ = self.notification_service.send_sync_notification(peer_id, message.encode()); + peer.sink.send_sync_notification(message.encode()); } } } + /// Inform sync about new best imported block. + pub fn new_best_block_imported(&mut self, hash: B::Hash, number: NumberFor) { + log::debug!(target: LOG_TARGET, "New best block imported {hash:?}/#{number}"); + + self.chain_sync.update_chain_info(&hash, number); + self.network_service.set_notification_handshake( + self.block_announce_protocol_name.clone(), + BlockAnnouncesHandshake::::build(self.roles, number, hash, self.genesis_hash) + .encode(), + ) + } + pub async fn run(mut self) { self.syncing_started = Some(Instant::now()); @@ -691,10 +698,8 @@ where _ = self.tick_timeout.tick() => self.perform_periodic_actions(), command = self.service_rx.select_next_some() => self.process_service_command(command), - notification_event = self.notification_service.next_event() => match notification_event { - Some(event) => self.process_notification_event(event), - None => return, - }, + sync_event = self.sync_events_rx.select_next_some() => + self.process_sync_event(sync_event), warp_target_block_header = &mut self.warp_sync_target_block_header_rx_fused => self.pass_warp_sync_target_block_header(warp_target_block_header), response_event = self.pending_responses.select_next_some() => @@ -848,20 +853,8 @@ where } }, ToServiceCommand::AnnounceBlock(hash, data) => self.announce_block(hash, data), - ToServiceCommand::NewBestBlockImported(hash, number) => { - log::debug!(target: "sync", "New best block imported {:?}/#{}", hash, number); - - self.chain_sync.update_chain_info(&hash, number); - let _ = self.notification_service.try_set_handshake( - BlockAnnouncesHandshake::::build( - self.roles, - number, - hash, - self.genesis_hash, - ) - .encode(), - ); - }, + ToServiceCommand::NewBestBlockImported(hash, number) => + self.new_best_block_imported(hash, number), ToServiceCommand::Status(tx) => { let mut status = self.chain_sync.status(); status.num_connected_peers = self.peers.len() as u32; @@ -901,60 +894,56 @@ where } } - fn process_notification_event(&mut self, event: NotificationEvent) { + fn process_sync_event(&mut self, event: sc_network::SyncEvent) { match event { - NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx } => { - let validation_result = self - .validate_connection(&peer, handshake, Direction::Inbound) - .map_or(ValidationResult::Reject, |_| ValidationResult::Accept); - - let _ = result_tx.send(validation_result); + sc_network::SyncEvent::NotificationStreamOpened { + remote, + received_handshake, + sink, + inbound, + tx, + } => match self.on_sync_peer_connected(remote, &received_handshake, sink, inbound) { + Ok(()) => { + let _ = tx.send(true); + }, + Err(()) => { + log::debug!( + target: LOG_TARGET, + "Failed to register peer {remote:?}: {received_handshake:?}", + ); + let _ = tx.send(false); + }, }, - NotificationEvent::NotificationStreamOpened { peer, handshake, direction, .. } => { - log::debug!( - target: LOG_TARGET, - "Substream opened for {peer}, handshake {handshake:?}" - ); - - match self.validate_connection(&peer, handshake, direction) { - Ok(handshake) => { - if self.on_sync_peer_connected(peer, &handshake, direction).is_err() { - log::debug!(target: LOG_TARGET, "Failed to register peer {peer}"); - self.network_service - .disconnect_peer(peer, self.block_announce_protocol_name.clone()); - } - }, - Err(wrong_genesis) => { - log::debug!(target: LOG_TARGET, "`SyncingEngine` rejected {peer}"); - - if wrong_genesis { - self.peer_store_handle.report_peer(peer, rep::GENESIS_MISMATCH); - } - - self.network_service - .disconnect_peer(peer, self.block_announce_protocol_name.clone()); - }, + sc_network::SyncEvent::NotificationStreamClosed { remote } => { + if self.on_sync_peer_disconnected(remote).is_err() { + log::trace!( + target: LOG_TARGET, + "Disconnected peer which had earlier been refused by on_sync_peer_connected {}", + remote + ); } }, - NotificationEvent::NotificationStreamClosed { peer } => { - self.on_sync_peer_disconnected(peer); + sc_network::SyncEvent::NotificationsReceived { remote, messages } => { + for message in messages { + if self.peers.contains_key(&remote) { + if let Ok(announce) = BlockAnnounce::decode(&mut message.as_ref()) { + self.last_notification_io = Instant::now(); + self.push_block_announce_validation(remote, announce); + } else { + log::warn!(target: "sub-libp2p", "Failed to decode block announce"); + } + } else { + log::trace!( + target: LOG_TARGET, + "Received sync for peer earlier refused by sync layer: {remote}", + ); + } + } }, - NotificationEvent::NotificationReceived { peer, notification } => { - if !self.peers.contains_key(&peer) { - log::error!( - target: LOG_TARGET, - "received notification from {peer} who had been earlier refused by `SyncingEngine`", - ); - return + sc_network::SyncEvent::NotificationSinkReplaced { remote, sink } => { + if let Some(peer) = self.peers.get_mut(&remote) { + peer.sink = sink; } - - let Ok(announce) = BlockAnnounce::decode(&mut notification.as_ref()) else { - log::warn!(target: LOG_TARGET, "failed to decode block announce"); - return - }; - - self.last_notification_io = Instant::now(); - self.push_block_announce_validation(peer, announce); }, } } @@ -976,167 +965,129 @@ where /// Called by peer when it is disconnecting. /// /// Returns a result if the handshake of this peer was indeed accepted. - fn on_sync_peer_disconnected(&mut self, peer_id: PeerId) { - let Some(info) = self.peers.remove(&peer_id) else { - log::debug!(target: LOG_TARGET, "{peer_id} does not exist in `SyncingEngine`"); - return - }; + fn on_sync_peer_disconnected(&mut self, peer_id: PeerId) -> Result<(), ()> { + if let Some(info) = self.peers.remove(&peer_id) { + if self.important_peers.contains(&peer_id) { + log::warn!(target: LOG_TARGET, "Reserved peer {peer_id} disconnected"); + } else { + log::debug!(target: LOG_TARGET, "{peer_id} disconnected"); + } - if self.important_peers.contains(&peer_id) { - log::warn!(target: LOG_TARGET, "Reserved peer {peer_id} disconnected"); + if !self.default_peers_set_no_slot_connected_peers.remove(&peer_id) && + info.inbound && info.info.roles.is_full() + { + match self.num_in_peers.checked_sub(1) { + Some(value) => { + self.num_in_peers = value; + }, + None => { + log::error!( + target: LOG_TARGET, + "trying to disconnect an inbound node which is not counted as inbound" + ); + debug_assert!(false); + }, + } + } + + self.chain_sync.peer_disconnected(&peer_id); + + self.pending_responses.remove(&peer_id); + self.event_streams.retain(|stream| { + stream.unbounded_send(SyncEvent::PeerDisconnected(peer_id)).is_ok() + }); + Ok(()) } else { - log::debug!(target: LOG_TARGET, "{peer_id} disconnected"); + Err(()) } + } - if !self.default_peers_set_no_slot_connected_peers.remove(&peer_id) && - info.inbound && info.info.roles.is_full() - { - match self.num_in_peers.checked_sub(1) { - Some(value) => { - self.num_in_peers = value; - }, - None => { - log::error!( - target: LOG_TARGET, - "trying to disconnect an inbound node which is not counted as inbound" - ); - debug_assert!(false); - }, - } + /// Called on the first connection between two peers on the default set, after their exchange + /// of handshake. + /// + /// Returns `Ok` if the handshake is accepted and the peer added to the list of peers we sync + /// from. + fn on_sync_peer_connected( + &mut self, + peer_id: PeerId, + status: &BlockAnnouncesHandshake, + sink: NotificationsSink, + inbound: bool, + ) -> Result<(), ()> { + log::trace!(target: LOG_TARGET, "New peer {peer_id} {status:?}"); + + if self.peers.contains_key(&peer_id) { + log::error!( + target: LOG_TARGET, + "Called on_sync_peer_connected with already connected peer {peer_id}", + ); + debug_assert!(false); + return Err(()) } - self.chain_sync.peer_disconnected(&peer_id); - self.pending_responses.remove(&peer_id); - self.event_streams - .retain(|stream| stream.unbounded_send(SyncEvent::PeerDisconnected(peer_id)).is_ok()); - } + if status.genesis_hash != self.genesis_hash { + self.network_service.report_peer(peer_id, rep::GENESIS_MISMATCH); - /// Validate received handshake. - fn validate_handshake( - &mut self, - peer_id: &PeerId, - handshake: Vec, - ) -> Result, bool> { - log::trace!(target: LOG_TARGET, "Validate handshake for {peer_id}"); - - let handshake = as DecodeAll>::decode_all(&mut &handshake[..]) - .map_err(|error| { - log::debug!(target: LOG_TARGET, "Failed to decode handshake for {peer_id}: {error:?}"); - false - })?; - - if handshake.genesis_hash != self.genesis_hash { if self.important_peers.contains(&peer_id) { log::error!( target: LOG_TARGET, - "Reserved peer id `{peer_id}` is on a different chain (our genesis: {} theirs: {})", + "Reserved peer id `{}` is on a different chain (our genesis: {} theirs: {})", + peer_id, self.genesis_hash, - handshake.genesis_hash, + status.genesis_hash, ); } else if self.boot_node_ids.contains(&peer_id) { log::error!( target: LOG_TARGET, - "Bootnode with peer id `{peer_id}` is on a different chain (our genesis: {} theirs: {})", + "Bootnode with peer id `{}` is on a different chain (our genesis: {} theirs: {})", + peer_id, self.genesis_hash, - handshake.genesis_hash, + status.genesis_hash, ); } else { log::debug!( target: LOG_TARGET, "Peer is on different chain (our genesis: {} theirs: {})", - self.genesis_hash, - handshake.genesis_hash + self.genesis_hash, status.genesis_hash ); } - return Err(true) + return Err(()) } - Ok(handshake) - } - - /// Validate connection. - // NOTE Returning `Err(bool)` is a really ugly hack to work around the issue - // that `ProtocolController` thinks the peer is connected when in fact it can - // still be under validation. If the peer has different genesis than the - // local node the validation fails but the peer cannot be reported in - // `validate_connection()` as that is also called by - // `ValiateInboundSubstream` which means that the peer is still being - // validated and banning the peer when handling that event would - // result in peer getting dropped twice. - // - // The proper way to fix this is to integrate `ProtocolController` more - // tightly with `NotificationService` or add an additional API call for - // banning pre-accepted peers (which is not desirable) - fn validate_connection( - &mut self, - peer_id: &PeerId, - handshake: Vec, - direction: Direction, - ) -> Result, bool> { - log::trace!(target: LOG_TARGET, "New peer {peer_id} {handshake:?}"); - - let handshake = self.validate_handshake(peer_id, handshake)?; + let no_slot_peer = self.default_peers_set_no_slot_peers.contains(&peer_id); + let this_peer_reserved_slot: usize = if no_slot_peer { 1 } else { 0 }; - if self.peers.contains_key(&peer_id) { - log::error!( + // make sure to accept no more than `--in-peers` many full nodes + if !no_slot_peer && + status.roles.is_full() && + inbound && self.num_in_peers == self.max_in_peers + { + log::debug!( target: LOG_TARGET, - "Called `validate_connection()` with already connected peer {peer_id}", + "All inbound slots have been consumed, rejecting {peer_id}", ); - debug_assert!(false); - return Err(false) + return Err(()) } - let no_slot_peer = self.default_peers_set_no_slot_peers.contains(&peer_id); - let this_peer_reserved_slot: usize = if no_slot_peer { 1 } else { 0 }; - - if handshake.roles.is_full() && + if status.roles.is_full() && self.chain_sync.num_peers() >= self.default_peers_set_num_full + self.default_peers_set_no_slot_connected_peers.len() + this_peer_reserved_slot { log::debug!(target: LOG_TARGET, "Too many full nodes, rejecting {peer_id}"); - return Err(false) + return Err(()) } - // make sure to accept no more than `--in-peers` many full nodes - if !no_slot_peer && - handshake.roles.is_full() && - direction.is_inbound() && - self.num_in_peers == self.max_in_peers - { - log::debug!(target: LOG_TARGET, "All inbound slots have been consumed, rejecting {peer_id}"); - return Err(false) - } - - // make sure that all slots are not occupied by light peers - // - // `ChainSync` only accepts full peers whereas `SyncingEngine` accepts both full and light - // peers. Verify that there is a slot in `SyncingEngine` for the inbound light peer - if handshake.roles.is_light() && + if status.roles.is_light() && (self.peers.len() - self.chain_sync.num_peers()) >= self.default_peers_set_num_light { + // Make sure that not all slots are occupied by light clients. log::debug!(target: LOG_TARGET, "Too many light nodes, rejecting {peer_id}"); - return Err(false) + return Err(()) } - Ok(handshake) - } - - /// Called on the first connection between two peers on the default set, after their exchange - /// of handshake. - /// - /// Returns `Ok` if the handshake is accepted and the peer added to the list of peers we sync - /// from. - fn on_sync_peer_connected( - &mut self, - peer_id: PeerId, - status: &BlockAnnouncesHandshake, - direction: Direction, - ) -> Result<(), ()> { - log::trace!(target: LOG_TARGET, "New peer {peer_id} {status:?}"); - let peer = Peer { info: ExtendedPeerInfo { roles: status.roles, @@ -1146,7 +1097,8 @@ where known_blocks: LruHashSet::new( NonZeroUsize::new(MAX_KNOWN_BLOCKS).expect("Constant is nonzero"), ), - inbound: direction.is_inbound(), + sink, + inbound, }; self.chain_sync.new_peer(peer_id, peer.info.best_hash, peer.info.best_number); @@ -1154,11 +1106,10 @@ where log::debug!(target: LOG_TARGET, "Connected {peer_id}"); self.peers.insert(peer_id, peer); - self.peer_store_handle.set_peer_role(&peer_id, status.roles.into()); - if self.default_peers_set_no_slot_peers.contains(&peer_id) { + if no_slot_peer { self.default_peers_set_no_slot_connected_peers.insert(peer_id); - } else if direction.is_inbound() && status.roles.is_full() { + } else if inbound && status.roles.is_full() { self.num_in_peers += 1; } @@ -1382,7 +1333,7 @@ where best_number: NumberFor, best_hash: B::Hash, genesis_hash: B::Hash, - ) -> (NonDefaultSetConfig, Box) { + ) -> NonDefaultSetConfig { let block_announces_protocol = { let genesis_hash = genesis_hash.as_ref(); if let Some(ref fork_id) = fork_id { @@ -1396,11 +1347,14 @@ where } }; - NonDefaultSetConfig::new( - block_announces_protocol.into(), - iter::once(format!("/{}/block-announces/1", protocol_id.as_ref()).into()).collect(), - MAX_BLOCK_ANNOUNCE_SIZE, - Some(NotificationHandshake::new(BlockAnnouncesHandshake::::build( + NonDefaultSetConfig { + notifications_protocol: block_announces_protocol.into(), + fallback_names: iter::once( + format!("/{}/block-announces/1", protocol_id.as_ref()).into(), + ) + .collect(), + max_notification_size: MAX_BLOCK_ANNOUNCE_SIZE, + handshake: Some(NotificationHandshake::new(BlockAnnouncesHandshake::::build( roles, best_number, best_hash, @@ -1408,13 +1362,13 @@ where ))), // NOTE: `set_config` will be ignored by `protocol.rs` as the block announcement // protocol is still hardcoded into the peerset. - SetConfig { + set_config: SetConfig { in_peers: 0, out_peers: 0, reserved_nodes: Vec::new(), non_reserved_mode: NonReservedPeerMode::Deny, }, - ) + } } /// Import blocks. diff --git a/substrate/client/network/sync/src/service/mock.rs b/substrate/client/network/sync/src/service/mock.rs index 6e307d86984..885eb1f8da5 100644 --- a/substrate/client/network/sync/src/service/mock.rs +++ b/substrate/client/network/sync/src/service/mock.rs @@ -27,7 +27,6 @@ use sc_network::{ NetworkNotification, NetworkPeers, NetworkRequest, NetworkSyncForkRequest, NotificationSenderError, NotificationSenderT, ReputationChange, }; -use sc_network_common::role::ObservedRole; use sp_runtime::traits::{Block as BlockT, NumberFor}; use std::collections::HashSet; @@ -84,9 +83,8 @@ mockall::mock! { fn set_authorized_peers(&self, peers: HashSet); fn set_authorized_only(&self, reserved_only: bool); fn add_known_address(&self, peer_id: PeerId, addr: Multiaddr); - fn report_peer(&self, peer_id: PeerId, cost_benefit: ReputationChange); - fn peer_reputation(&self, peer_id: &PeerId) -> i32; - fn disconnect_peer(&self, peer_id: PeerId, protocol: ProtocolName); + fn report_peer(&self, who: PeerId, cost_benefit: ReputationChange); + fn disconnect_peer(&self, who: PeerId, protocol: ProtocolName); fn accept_unreserved_peers(&self); fn deny_unreserved_peers(&self); fn add_reserved_peer(&self, peer: MultiaddrWithPeerId) -> Result<(), String>; @@ -107,7 +105,6 @@ mockall::mock! { peers: Vec ) -> Result<(), String>; fn sync_num_connected(&self) -> usize; - fn peer_role(&self, peer_id: PeerId, handshake: Vec) -> Option; } #[async_trait::async_trait] diff --git a/substrate/client/network/test/Cargo.toml b/substrate/client/network/test/Cargo.toml index cd66c701660..09f8f1fa9ef 100644 --- a/substrate/client/network/test/Cargo.toml +++ b/substrate/client/network/test/Cargo.toml @@ -9,9 +9,6 @@ publish = false homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -32,7 +29,7 @@ sc-network-common = { path = "../common" } sc-utils = { path = "../../utils" } sc-network-light = { path = "../light" } sc-network-sync = { path = "../sync" } -sc-service = { path = "../../service", default-features = false, features = ["test-helpers"] } +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" } diff --git a/substrate/client/network/test/src/lib.rs b/substrate/client/network/test/src/lib.rs index 71f13b74a53..cfc3cb7af3f 100644 --- a/substrate/client/network/test/src/lib.rs +++ b/substrate/client/network/test/src/lib.rs @@ -58,7 +58,7 @@ use sc_network::{ request_responses::ProtocolConfig as RequestResponseConfig, types::ProtocolName, Multiaddr, NetworkBlock, NetworkService, NetworkStateInfo, NetworkSyncForkRequest, - NetworkWorker, NotificationService, + NetworkWorker, }; use sc_network_common::role::Roles; use sc_network_light::light_client_requests::handler::LightClientRequestHandler; @@ -239,7 +239,6 @@ pub struct Peer { imported_blocks_stream: Pin> + Send>>, finality_notification_stream: Pin> + Send>>, listen_addr: Multiaddr, - notification_services: HashMap>, } impl Peer @@ -264,8 +263,8 @@ where } /// Returns the number of peers we're connected to. - pub async fn num_peers(&self) -> usize { - self.sync_service.status().await.unwrap().num_connected_peers as usize + pub fn num_peers(&self) -> usize { + self.network.num_connected_peers() } /// Returns the number of downloaded blocks. @@ -503,19 +502,10 @@ where self.network.service() } - /// Get `SyncingService`. pub fn sync_service(&self) -> &Arc> { &self.sync_service } - /// Take notification handle for enabled protocol. - pub fn take_notification_service( - &mut self, - protocol: &ProtocolName, - ) -> Option> { - self.notification_services.remove(protocol) - } - /// Get a reference to the network worker. pub fn network(&self) -> &NetworkWorker::Hash> { &self.network @@ -788,23 +778,6 @@ pub trait TestNetFactory: Default + Sized + Send { network_config.transport = TransportConfig::MemoryOnly; network_config.listen_addresses = vec![listen_addr.clone()]; network_config.allow_non_globals_in_dht = true; - - let (notif_configs, notif_handles): (Vec<_>, Vec<_>) = config - .notifications_protocols - .into_iter() - .map(|p| { - let (config, handle) = NonDefaultSetConfig::new( - p.clone(), - Vec::new(), - 1024 * 1024, - None, - Default::default(), - ); - - (config, (p, handle)) - }) - .unzip(); - if let Some(connect_to) = config.connect_to_peers { let addrs = connect_to .iter() @@ -876,16 +849,11 @@ pub trait TestNetFactory: Default + Sized + Send { protocol_config }; - let peer_store = PeerStore::new( - network_config.boot_nodes.iter().map(|bootnode| bootnode.peer_id).collect(), - ); - let peer_store_handle = peer_store.handle(); - self.spawn_task(peer_store.run().boxed()); - let block_announce_validator = config .block_announce_validator .unwrap_or_else(|| Box::new(DefaultBlockAnnounceValidator)); + let (tx, rx) = sc_utils::mpsc::tracing_unbounded("mpsc_syncing_engine_protocol", 100_000); let (engine, sync_service, block_announce_config) = sc_network_sync::engine::SyncingEngine::new( Roles::from(if config.is_authority { &Role::Authority } else { &Role::Full }), @@ -901,7 +869,7 @@ pub trait TestNetFactory: Default + Sized + Send { block_relay_params.downloader, state_request_protocol_config.name.clone(), Some(warp_protocol_config.name.clone()), - peer_store_handle.clone(), + rx, ) .unwrap(); let sync_service_import_queue = Box::new(sync_service.clone()); @@ -919,10 +887,22 @@ pub trait TestNetFactory: Default + Sized + Send { full_net_config.add_request_response_protocol(config); } - for config in notif_configs { - full_net_config.add_notification_protocol(config); + for protocol in config.notifications_protocols { + full_net_config.add_notification_protocol(NonDefaultSetConfig { + notifications_protocol: protocol, + fallback_names: Vec::new(), + max_notification_size: 1024 * 1024, + handshake: None, + set_config: Default::default(), + }); } + let peer_store = PeerStore::new( + network_config.boot_nodes.iter().map(|bootnode| bootnode.peer_id).collect(), + ); + let peer_store_handle = peer_store.handle(); + self.spawn_task(peer_store.run().boxed()); + let genesis_hash = client.hash(Zero::zero()).ok().flatten().expect("Genesis block exists; qed"); let network = NetworkWorker::new(sc_network::config::Params { @@ -937,6 +917,7 @@ pub trait TestNetFactory: Default + Sized + Send { fork_id, metrics_registry: None, block_announce_config, + tx, }) .unwrap(); @@ -972,7 +953,6 @@ pub trait TestNetFactory: Default + Sized + Send { backend: Some(backend), imported_blocks_stream, finality_notification_stream, - notification_services: HashMap::from_iter(notif_handles.into_iter()), block_import, verifier, network, @@ -987,6 +967,20 @@ pub trait TestNetFactory: Default + Sized + Send { tokio::spawn(f); } + /// Polls the testnet until all peers are connected to each other. + /// + /// Must be executed in a task context. + fn poll_until_connected(&mut self, cx: &mut FutureContext) -> Poll<()> { + self.poll(cx); + + let num_peers = self.peers().len(); + if self.peers().iter().all(|p| p.num_peers() == num_peers - 1) { + return Poll::Ready(()) + } + + Poll::Pending + } + async fn is_in_sync(&mut self) -> bool { let mut highest = None; let peers = self.peers_mut(); @@ -1064,27 +1058,10 @@ pub trait TestNetFactory: Default + Sized + Send { } /// Run the network until all peers are connected to each other. + /// + /// Calls `poll_until_connected` repeatedly with the runtime passed as parameter. async fn run_until_connected(&mut self) { - let num_peers = self.peers().len(); - let sync_services = - self.peers().iter().map(|info| info.sync_service.clone()).collect::>(); - - 'outer: loop { - for sync_service in &sync_services { - if sync_service.status().await.unwrap().num_connected_peers as usize != - num_peers - 1 - { - futures::future::poll_fn::<(), _>(|cx| { - self.poll(cx); - Poll::Ready(()) - }) - .await; - continue 'outer - } - } - - break - } + futures::future::poll_fn::<(), _>(|cx| self.poll_until_connected(cx)).await; } /// Polls the testnet. Processes all the pending actions. diff --git a/substrate/client/network/test/src/service.rs b/substrate/client/network/test/src/service.rs index 800c0d4369c..62d7f9f9d1b 100644 --- a/substrate/client/network/test/src/service.rs +++ b/substrate/client/network/test/src/service.rs @@ -24,9 +24,8 @@ use sc_network::{ config::{self, FullNetworkConfiguration, MultiaddrWithPeerId, ProtocolId, TransportConfig}, event::Event, peer_store::PeerStore, - service::traits::{NotificationEvent, ValidationResult}, - NetworkEventStream, NetworkPeers, NetworkService, NetworkStateInfo, NetworkWorker, - NotificationService, + NetworkEventStream, NetworkNotification, NetworkPeers, NetworkService, NetworkStateInfo, + NetworkWorker, }; use sc_network_common::role::Roles; use sc_network_light::light_client_requests::handler::LightClientRequestHandler; @@ -117,7 +116,7 @@ impl TestNetworkBuilder { self } - pub fn build(mut self) -> (TestNetwork, Option>) { + pub fn build(mut self) -> TestNetwork { let client = self.client.as_mut().map_or( Arc::new(TestClientBuilder::with_default_backend().build_with_longest_chain().0), |v| v.clone(), @@ -184,12 +183,7 @@ impl TestNetworkBuilder { protocol_config }; - let peer_store = PeerStore::new( - network_config.boot_nodes.iter().map(|bootnode| bootnode.peer_id).collect(), - ); - let peer_store_handle = peer_store.handle(); - tokio::spawn(peer_store.run().boxed()); - + let (tx, rx) = sc_utils::mpsc::tracing_unbounded("mpsc_syncing_engine_protocol", 100_000); let (engine, chain_sync_service, block_announce_config) = SyncingEngine::new( Roles::from(&config::Role::Full), client.clone(), @@ -204,27 +198,24 @@ impl TestNetworkBuilder { block_relay_params.downloader, state_request_protocol_config.name.clone(), None, - peer_store_handle.clone(), + rx, ) .unwrap(); let mut link = self.link.unwrap_or(Box::new(chain_sync_service.clone())); - let handle = if !self.notification_protocols.is_empty() { + if !self.notification_protocols.is_empty() { for config in self.notification_protocols { full_net_config.add_notification_protocol(config); } - None } else { - let (config, handle) = config::NonDefaultSetConfig::new( - PROTOCOL_NAME.into(), - Vec::new(), - 1024 * 1024, - None, - self.set_config.unwrap_or_default(), - ); - full_net_config.add_notification_protocol(config); - Some(handle) - }; + full_net_config.add_notification_protocol(config::NonDefaultSetConfig { + notifications_protocol: PROTOCOL_NAME.into(), + fallback_names: Vec::new(), + max_notification_size: 1024 * 1024, + handshake: None, + set_config: self.set_config.unwrap_or_default(), + }); + } for config in [ block_relay_params.request_response_config, @@ -234,6 +225,12 @@ impl TestNetworkBuilder { full_net_config.add_request_response_protocol(config); } + let peer_store = PeerStore::new( + network_config.boot_nodes.iter().map(|bootnode| bootnode.peer_id).collect(), + ); + let peer_store_handle = peer_store.handle(); + tokio::spawn(peer_store.run().boxed()); + let genesis_hash = client.hash(Zero::zero()).ok().flatten().expect("Genesis block exists; qed"); let worker = NetworkWorker::< @@ -251,6 +248,7 @@ impl TestNetworkBuilder { protocol_id, fork_id, metrics_registry: None, + tx, }) .unwrap(); @@ -270,7 +268,7 @@ impl TestNetworkBuilder { }); tokio::spawn(engine.run()); - (TestNetwork::new(worker), handle) + TestNetwork::new(worker) } } @@ -278,18 +276,18 @@ impl TestNetworkBuilder { /// The nodes are connected together and have the `PROTOCOL_NAME` protocol registered. fn build_nodes_one_proto() -> ( Arc, - Option>, + impl Stream, Arc, - Option>, + impl Stream, ) { let listen_addr = config::build_multiaddr![Memory(rand::random::())]; - let (network1, handle1) = TestNetworkBuilder::new() + let (node1, events_stream1) = TestNetworkBuilder::new() .with_listen_addresses(vec![listen_addr.clone()]) - .build(); - let (node1, _) = network1.start_network(); + .build() + .start_network(); - let (network2, handle2) = TestNetworkBuilder::new() + let (node2, events_stream2) = TestNetworkBuilder::new() .with_set_config(config::SetConfig { reserved_nodes: vec![MultiaddrWithPeerId { multiaddr: listen_addr, @@ -297,11 +295,10 @@ fn build_nodes_one_proto() -> ( }], ..Default::default() }) - .build(); - - let (node2, _) = network2.start_network(); + .build() + .start_network(); - (node1, handle1, node2, handle2) + (node1, events_stream1, node2, events_stream2) } #[tokio::test] @@ -309,15 +306,22 @@ async fn notifications_state_consistent() { // Runs two nodes and ensures that events are propagated out of the API in a consistent // correct order, which means no notification received on a closed substream. - let (node1, handle1, node2, handle2) = build_nodes_one_proto(); - let (mut handle1, mut handle2) = (handle1.unwrap(), handle2.unwrap()); + let (node1, mut events_stream1, node2, mut events_stream2) = build_nodes_one_proto(); // Write some initial notifications that shouldn't get through. for _ in 0..(rand::random::() % 5) { - let _ = handle1.send_sync_notification(&node2.local_peer_id(), b"hello world".to_vec()); + node1.write_notification( + node2.local_peer_id(), + PROTOCOL_NAME.into(), + b"hello world".to_vec(), + ); } for _ in 0..(rand::random::() % 5) { - let _ = handle2.send_sync_notification(&node1.local_peer_id(), b"hello world".to_vec()); + node2.write_notification( + node1.local_peer_id(), + PROTOCOL_NAME.into(), + b"hello world".to_vec(), + ); } // True if we have an active substream from node1 to node2. @@ -339,10 +343,18 @@ async fn notifications_state_consistent() { // Start by sending a notification from node1 to node2 and vice-versa. Part of the // test consists in ensuring that notifications get ignored if the stream isn't open. if rand::random::() % 5 >= 3 { - let _ = handle1.send_sync_notification(&node2.local_peer_id(), b"hello world".to_vec()); + node1.write_notification( + node2.local_peer_id(), + PROTOCOL_NAME.into(), + b"hello world".to_vec(), + ); } if rand::random::() % 5 >= 3 { - let _ = handle2.send_sync_notification(&node1.local_peer_id(), b"hello world".to_vec()); + node2.write_notification( + node1.local_peer_id(), + PROTOCOL_NAME.into(), + b"hello world".to_vec(), + ); } // Also randomly disconnect the two nodes from time to time. @@ -355,8 +367,8 @@ async fn notifications_state_consistent() { // Grab next event from either `events_stream1` or `events_stream2`. let next_event = { - let next1 = handle1.next_event(); - let next2 = handle2.next_event(); + let next1 = events_stream1.next(); + let next2 = events_stream2.next(); // We also await on a small timer, otherwise it is possible for the test to wait // forever while nothing at all happens on the network. let continue_test = futures_timer::Delay::new(Duration::from_millis(20)); @@ -371,55 +383,58 @@ async fn notifications_state_consistent() { }; match next_event { - future::Either::Left(NotificationEvent::ValidateInboundSubstream { - result_tx, .. - }) => { - result_tx.send(ValidationResult::Accept).unwrap(); - }, - future::Either::Right(NotificationEvent::ValidateInboundSubstream { - result_tx, - .. - }) => { - result_tx.send(ValidationResult::Accept).unwrap(); - }, - future::Either::Left(NotificationEvent::NotificationStreamOpened { peer, .. }) => { - something_happened = true; - assert!(!node1_to_node2_open); - node1_to_node2_open = true; - assert_eq!(peer, node2.local_peer_id()); - }, - future::Either::Right(NotificationEvent::NotificationStreamOpened { peer, .. }) => { - something_happened = true; - assert!(!node2_to_node1_open); - node2_to_node1_open = true; - assert_eq!(peer, node1.local_peer_id()); - }, - future::Either::Left(NotificationEvent::NotificationStreamClosed { peer, .. }) => { - assert!(node1_to_node2_open); - node1_to_node2_open = false; - assert_eq!(peer, node2.local_peer_id()); - }, - future::Either::Right(NotificationEvent::NotificationStreamClosed { peer, .. }) => { - assert!(node2_to_node1_open); - node2_to_node1_open = false; - assert_eq!(peer, node1.local_peer_id()); - }, - future::Either::Left(NotificationEvent::NotificationReceived { peer, .. }) => { + future::Either::Left(Event::NotificationStreamOpened { remote, protocol, .. }) => + if protocol == PROTOCOL_NAME.into() { + something_happened = true; + assert!(!node1_to_node2_open); + node1_to_node2_open = true; + assert_eq!(remote, node2.local_peer_id()); + }, + future::Either::Right(Event::NotificationStreamOpened { remote, protocol, .. }) => + if protocol == PROTOCOL_NAME.into() { + something_happened = true; + assert!(!node2_to_node1_open); + node2_to_node1_open = true; + assert_eq!(remote, node1.local_peer_id()); + }, + future::Either::Left(Event::NotificationStreamClosed { remote, protocol, .. }) => + if protocol == PROTOCOL_NAME.into() { + assert!(node1_to_node2_open); + node1_to_node2_open = false; + assert_eq!(remote, node2.local_peer_id()); + }, + future::Either::Right(Event::NotificationStreamClosed { remote, protocol, .. }) => + if protocol == PROTOCOL_NAME.into() { + assert!(node2_to_node1_open); + node2_to_node1_open = false; + assert_eq!(remote, node1.local_peer_id()); + }, + future::Either::Left(Event::NotificationsReceived { remote, .. }) => { assert!(node1_to_node2_open); - assert_eq!(peer, node2.local_peer_id()); + assert_eq!(remote, node2.local_peer_id()); if rand::random::() % 5 >= 4 { - let _ = handle1 - .send_sync_notification(&node2.local_peer_id(), b"hello world".to_vec()); + node1.write_notification( + node2.local_peer_id(), + PROTOCOL_NAME.into(), + b"hello world".to_vec(), + ); } }, - future::Either::Right(NotificationEvent::NotificationReceived { peer, .. }) => { + future::Either::Right(Event::NotificationsReceived { remote, .. }) => { assert!(node2_to_node1_open); - assert_eq!(peer, node1.local_peer_id()); + assert_eq!(remote, node1.local_peer_id()); if rand::random::() % 5 >= 4 { - let _ = handle2 - .send_sync_notification(&node1.local_peer_id(), b"hello world".to_vec()); + node2.write_notification( + node1.local_peer_id(), + PROTOCOL_NAME.into(), + b"hello world".to_vec(), + ); } }, + + // Add new events here. + future::Either::Left(Event::Dht(_)) => {}, + future::Either::Right(Event::Dht(_)) => {}, }; } } @@ -429,29 +444,20 @@ async fn lots_of_incoming_peers_works() { sp_tracing::try_init_simple(); let listen_addr = config::build_multiaddr![Memory(rand::random::())]; - let (main_node, handle1) = TestNetworkBuilder::new() + let (main_node, _) = TestNetworkBuilder::new() .with_listen_addresses(vec![listen_addr.clone()]) .with_set_config(config::SetConfig { in_peers: u32::MAX, ..Default::default() }) - .build(); - let mut handle1 = handle1.unwrap(); - let (main_node, _) = main_node.start_network(); + .build() + .start_network(); let main_node_peer_id = main_node.local_peer_id(); - tokio::spawn(async move { - while let Some(event) = handle1.next_event().await { - if let NotificationEvent::ValidateInboundSubstream { result_tx, .. } = event { - result_tx.send(ValidationResult::Accept).unwrap(); - } - } - }); - // We spawn background tasks and push them in this `Vec`. They will all be waited upon before // this test ends. let mut background_tasks_to_wait = Vec::new(); for _ in 0..32 { - let (dialing_node, handle) = TestNetworkBuilder::new() + let (_dialing_node, event_stream) = TestNetworkBuilder::new() .with_set_config(config::SetConfig { reserved_nodes: vec![MultiaddrWithPeerId { multiaddr: listen_addr.clone(), @@ -459,9 +465,8 @@ async fn lots_of_incoming_peers_works() { }], ..Default::default() }) - .build(); - let mut handle = handle.unwrap(); - let (_, _) = dialing_node.start_network(); + .build() + .start_network(); background_tasks_to_wait.push(tokio::spawn(async move { // Create a dummy timer that will "never" fire, and that will be overwritten when we @@ -469,23 +474,34 @@ async fn lots_of_incoming_peers_works() { // make the code below way more complicated. let mut timer = futures_timer::Delay::new(Duration::from_secs(3600 * 24 * 7)).fuse(); + let mut event_stream = event_stream.fuse(); + let mut sync_protocol_name = None; loop { futures::select! { _ = timer => { // Test succeeds when timer fires. return; } - ev = handle.next_event().fuse() => match ev.unwrap() { - NotificationEvent::ValidateInboundSubstream { result_tx, .. } => { - result_tx.send(ValidationResult::Accept).unwrap(); + ev = event_stream.next() => { + match ev.unwrap() { + Event::NotificationStreamOpened { protocol, remote, .. } => { + if let None = sync_protocol_name { + sync_protocol_name = Some(protocol.clone()); + } + + assert_eq!(remote, main_node_peer_id); + // Test succeeds after 5 seconds. This timer is here in order to + // detect a potential problem after opening. + timer = futures_timer::Delay::new(Duration::from_secs(5)).fuse(); + } + Event::NotificationStreamClosed { protocol, .. } => { + if Some(protocol) != sync_protocol_name { + // Test failed. + panic!(); + } + } + _ => {} } - NotificationEvent::NotificationStreamOpened { peer, .. } => { - assert_eq!(peer, main_node_peer_id); - // Test succeeds after 5 seconds. This timer is here in order to - // detect a potential problem after opening. - timer = futures_timer::Delay::new(Duration::from_secs(5)).fuse(); - } - _ => {} } } } @@ -502,27 +518,33 @@ async fn notifications_back_pressure() { const TOTAL_NOTIFS: usize = 10_000; - let (_node1, handle1, node2, handle2) = build_nodes_one_proto(); - let (mut handle1, mut handle2) = (handle1.unwrap(), handle2.unwrap()); + let (node1, mut events_stream1, node2, mut events_stream2) = build_nodes_one_proto(); let node2_id = node2.local_peer_id(); let receiver = tokio::spawn(async move { let mut received_notifications = 0; + let mut sync_protocol_name = None; while received_notifications < TOTAL_NOTIFS { - match handle2.next_event().await.unwrap() { - NotificationEvent::ValidateInboundSubstream { result_tx, .. } => { - result_tx.send(ValidationResult::Accept).unwrap(); + match events_stream2.next().await.unwrap() { + Event::NotificationStreamOpened { protocol, .. } => { + if let None = sync_protocol_name { + sync_protocol_name = Some(protocol); + } }, - NotificationEvent::NotificationReceived { notification, .. } => { - assert_eq!( - notification, - format!("hello #{}", received_notifications).into_bytes() - ); - received_notifications += 1; + Event::NotificationStreamClosed { protocol, .. } => { + if Some(&protocol) != sync_protocol_name.as_ref() { + panic!() + } }, + Event::NotificationsReceived { messages, .. } => + for message in messages { + assert_eq!(message.0, PROTOCOL_NAME.into()); + assert_eq!(message.1, format!("hello #{}", received_notifications)); + received_notifications += 1; + }, _ => {}, - } + }; if rand::random::() < 2 { tokio::time::sleep(Duration::from_millis(rand::random::() % 750)).await; @@ -532,20 +554,20 @@ async fn notifications_back_pressure() { // Wait for the `NotificationStreamOpened`. loop { - match handle1.next_event().await.unwrap() { - NotificationEvent::ValidateInboundSubstream { result_tx, .. } => { - result_tx.send(ValidationResult::Accept).unwrap(); - }, - NotificationEvent::NotificationStreamOpened { .. } => break, + match events_stream1.next().await.unwrap() { + Event::NotificationStreamOpened { .. } => break, _ => {}, }; } // Sending! for num in 0..TOTAL_NOTIFS { - handle1 - .send_async_notification(&node2_id, format!("hello #{}", num).into_bytes()) + let notif = node1.notification_sender(node2_id, PROTOCOL_NAME.into()).unwrap(); + notif + .ready() .await + .unwrap() + .send(format!("hello #{}", num).into_bytes()) .unwrap(); } @@ -554,31 +576,28 @@ async fn notifications_back_pressure() { #[tokio::test] async fn fallback_name_working() { - sp_tracing::try_init_simple(); // Node 1 supports the protocols "new" and "old". Node 2 only supports "old". Checks whether // they can connect. const NEW_PROTOCOL_NAME: &str = "/new-shiny-protocol-that-isnt-PROTOCOL_NAME"; let listen_addr = config::build_multiaddr![Memory(rand::random::())]; - let (config, mut handle1) = config::NonDefaultSetConfig::new( - NEW_PROTOCOL_NAME.into(), - vec![PROTOCOL_NAME.into()], - 1024 * 1024, - None, - Default::default(), - ); - let (network1, _) = TestNetworkBuilder::new() - .with_notification_protocol(config) + let (node1, mut events_stream1) = TestNetworkBuilder::new() + .with_notification_protocol(config::NonDefaultSetConfig { + notifications_protocol: NEW_PROTOCOL_NAME.into(), + fallback_names: vec![PROTOCOL_NAME.into()], + max_notification_size: 1024 * 1024, + handshake: None, + set_config: Default::default(), + }) .with_config(config::NetworkConfiguration { listen_addresses: vec![listen_addr.clone()], transport: TransportConfig::MemoryOnly, ..config::NetworkConfiguration::new_local() }) - .build(); - - let (node1, _) = network1.start_network(); + .build() + .start_network(); - let (network2, handle2) = TestNetworkBuilder::new() + let (_, mut events_stream2) = TestNetworkBuilder::new() .with_set_config(config::SetConfig { reserved_nodes: vec![MultiaddrWithPeerId { multiaddr: listen_addr, @@ -586,38 +605,34 @@ async fn fallback_name_working() { }], ..Default::default() }) - .build(); - let mut handle2 = handle2.unwrap(); - let _ = network2.start_network(); + .build() + .start_network(); let receiver = tokio::spawn(async move { // Wait for the `NotificationStreamOpened`. loop { - match handle2.next_event().await.unwrap() { - NotificationEvent::ValidateInboundSubstream { result_tx, .. } => { - result_tx.send(ValidationResult::Accept).unwrap(); - }, - NotificationEvent::NotificationStreamOpened { negotiated_fallback, .. } => { + match events_stream2.next().await.unwrap() { + Event::NotificationStreamOpened { protocol, negotiated_fallback, .. } => { + assert_eq!(protocol, PROTOCOL_NAME.into()); assert_eq!(negotiated_fallback, None); break }, _ => {}, - } + }; } }); // Wait for the `NotificationStreamOpened`. loop { - match handle1.next_event().await.unwrap() { - NotificationEvent::ValidateInboundSubstream { result_tx, .. } => { - result_tx.send(ValidationResult::Accept).unwrap(); - }, - NotificationEvent::NotificationStreamOpened { negotiated_fallback, .. } => { + match events_stream1.next().await.unwrap() { + Event::NotificationStreamOpened { protocol, negotiated_fallback, .. } + if protocol == NEW_PROTOCOL_NAME.into() => + { assert_eq!(negotiated_fallback, Some(PROTOCOL_NAME.into())); break }, _ => {}, - } + }; } receiver.await.unwrap(); @@ -640,7 +655,6 @@ async fn ensure_listen_addresses_consistent_with_transport_memory() { ) }) .build() - .0 .start_network(); } @@ -660,7 +674,6 @@ async fn ensure_listen_addresses_consistent_with_transport_not_memory() { ) }) .build() - .0 .start_network(); } @@ -686,7 +699,6 @@ async fn ensure_boot_node_addresses_consistent_with_transport_memory() { ) }) .build() - .0 .start_network(); } @@ -711,7 +723,6 @@ async fn ensure_boot_node_addresses_consistent_with_transport_not_memory() { ) }) .build() - .0 .start_network(); } @@ -740,7 +751,6 @@ async fn ensure_reserved_node_addresses_consistent_with_transport_memory() { ) }) .build() - .0 .start_network(); } @@ -768,7 +778,6 @@ async fn ensure_reserved_node_addresses_consistent_with_transport_not_memory() { ) }) .build() - .0 .start_network(); } @@ -791,7 +800,6 @@ async fn ensure_public_addresses_consistent_with_transport_memory() { ) }) .build() - .0 .start_network(); } @@ -813,6 +821,5 @@ async fn ensure_public_addresses_consistent_with_transport_not_memory() { ) }) .build() - .0 .start_network(); } diff --git a/substrate/client/network/test/src/sync.rs b/substrate/client/network/test/src/sync.rs index f2be662ada1..389177b4aaf 100644 --- a/substrate/client/network/test/src/sync.rs +++ b/substrate/client/network/test/src/sync.rs @@ -44,16 +44,16 @@ async fn sync_peers_works() { sp_tracing::try_init_simple(); let mut net = TestNet::new(3); - while net.peer(0).num_peers().await != 2 && - net.peer(1).num_peers().await != 2 && - net.peer(2).num_peers().await != 2 - { - futures::future::poll_fn::<(), _>(|cx| { - net.poll(cx); - Poll::Ready(()) - }) - .await; - } + futures::future::poll_fn::<(), _>(|cx| { + net.poll(cx); + for peer in 0..3 { + if net.peer(peer).num_peers() != 2 { + return Poll::Pending + } + } + Poll::Ready(()) + }) + .await; } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -412,13 +412,15 @@ async fn can_sync_small_non_best_forks() { assert!(net.peer(1).client().header(small_hash).unwrap().is_none()); // poll until the two nodes connect, otherwise announcing the block will not work - while net.peer(0).num_peers().await == 0 || net.peer(1).num_peers().await == 0 { - futures::future::poll_fn::<(), _>(|cx| { - net.poll(cx); + futures::future::poll_fn::<(), _>(|cx| { + net.poll(cx); + if net.peer(0).num_peers() == 0 || net.peer(1).num_peers() == 0 { + Poll::Pending + } else { Poll::Ready(()) - }) - .await; - } + } + }) + .await; // synchronization: 0 synced to longer chain and 1 didn't sync to small chain. @@ -463,7 +465,6 @@ async fn can_sync_forks_ahead_of_the_best_chain() { net.peer(1).push_blocks(1, false); net.run_until_connected().await; - // Peer 0 is on 2-block fork which is announced with is_best=false let fork_hash = net .peer(0) @@ -515,13 +516,15 @@ async fn can_sync_explicit_forks() { assert!(net.peer(1).client().header(small_hash).unwrap().is_none()); // poll until the two nodes connect, otherwise announcing the block will not work - while net.peer(0).num_peers().await == 0 || net.peer(1).num_peers().await == 0 { - futures::future::poll_fn::<(), _>(|cx| { - net.poll(cx); + futures::future::poll_fn::<(), _>(|cx| { + net.poll(cx); + if net.peer(0).num_peers() == 0 || net.peer(1).num_peers() == 0 { + Poll::Pending + } else { Poll::Ready(()) - }) - .await; - } + } + }) + .await; // synchronization: 0 synced to longer chain and 1 didn't sync to small chain. @@ -610,14 +613,15 @@ async fn full_sync_requires_block_body() { net.peer(0).push_headers(1); // Wait for nodes to connect - while net.peer(0).num_peers().await == 0 || net.peer(1).num_peers().await == 0 { - futures::future::poll_fn::<(), _>(|cx| { - net.poll(cx); + futures::future::poll_fn::<(), _>(|cx| { + net.poll(cx); + if net.peer(0).num_peers() == 0 || net.peer(1).num_peers() == 0 { + Poll::Pending + } else { Poll::Ready(()) - }) - .await; - } - + } + }) + .await; net.run_until_idle().await; assert_eq!(net.peer(1).client.info().best_number, 0); } @@ -913,16 +917,18 @@ async fn block_announce_data_is_propagated() { }); // Wait until peer 1 is connected to both nodes. - while net.peer(1).num_peers().await != 2 || - net.peer(0).num_peers().await != 1 || - net.peer(2).num_peers().await != 1 - { - futures::future::poll_fn::<(), _>(|cx| { - net.poll(cx); + futures::future::poll_fn::<(), _>(|cx| { + net.poll(cx); + if net.peer(1).num_peers() == 2 && + net.peer(0).num_peers() == 1 && + net.peer(2).num_peers() == 1 + { Poll::Ready(()) - }) - .await; - } + } else { + Poll::Pending + } + }) + .await; let block_hash = net .peer(0) @@ -1004,7 +1010,7 @@ async fn multiple_requests_are_accepted_as_long_as_they_are_not_fulfilled() { tokio::time::sleep(tokio::time::Duration::from_secs(10)).await; net.peer(0).push_blocks(1, false); net.run_until_sync().await; - assert_eq!(1, net.peer(0).num_peers().await); + assert_eq!(1, net.peer(0).num_peers()); } let hashof10 = hashes[9]; diff --git a/substrate/client/network/transactions/Cargo.toml b/substrate/client/network/transactions/Cargo.toml index 8acd4531de8..2a6aa4b3a40 100644 --- a/substrate/client/network/transactions/Cargo.toml +++ b/substrate/client/network/transactions/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true documentation = "https://docs.rs/sc-network-transactions" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/network/transactions/src/lib.rs b/substrate/client/network/transactions/src/lib.rs index 9758ea4c4fc..1b97d4b96c9 100644 --- a/substrate/client/network/transactions/src/lib.rs +++ b/substrate/client/network/transactions/src/lib.rs @@ -21,8 +21,8 @@ //! Usage: //! //! - Use [`TransactionsHandlerPrototype::new`] to create a prototype. -//! - Pass the `NonDefaultSetConfig` returned from [`TransactionsHandlerPrototype::new`] to the -//! network configuration as an extra peers set. +//! - Pass the return value of [`TransactionsHandlerPrototype::set_config`] to the network +//! configuration as an extra peers set. //! - Use [`TransactionsHandlerPrototype::build`] then [`TransactionsHandler::run`] to obtain a //! `Future` that processes transactions. @@ -37,7 +37,7 @@ use prometheus_endpoint::{register, Counter, PrometheusError, Registry, U64}; use sc_network::{ config::{NonDefaultSetConfig, NonReservedPeerMode, ProtocolId, SetConfig}, error, - service::traits::{NotificationEvent, NotificationService, ValidationResult}, + event::Event, types::ProtocolName, utils::{interval, LruHashSet}, NetworkEventStream, NetworkNotification, NetworkPeers, @@ -115,11 +115,8 @@ impl Future for PendingTransaction { /// Prototype for a [`TransactionsHandler`]. pub struct TransactionsHandlerPrototype { - /// Name of the transaction protocol. protocol_name: ProtocolName, - - /// Handle that is used to communicate with `sc_network::Notifications`. - notification_service: Box, + fallback_protocol_names: Vec, } impl TransactionsHandlerPrototype { @@ -128,28 +125,35 @@ impl TransactionsHandlerPrototype { protocol_id: ProtocolId, genesis_hash: Hash, fork_id: Option<&str>, - ) -> (Self, NonDefaultSetConfig) { + ) -> Self { let genesis_hash = genesis_hash.as_ref(); - let protocol_name: ProtocolName = if let Some(fork_id) = fork_id { + let protocol_name = if let Some(fork_id) = fork_id { format!("/{}/{}/transactions/1", array_bytes::bytes2hex("", genesis_hash), fork_id) } else { format!("/{}/transactions/1", array_bytes::bytes2hex("", genesis_hash)) + }; + let legacy_protocol_name = format!("/{}/transactions/1", protocol_id.as_ref()); + + Self { + protocol_name: protocol_name.into(), + fallback_protocol_names: iter::once(legacy_protocol_name.into()).collect(), } - .into(); - let (config, notification_service) = NonDefaultSetConfig::new( - protocol_name.clone(), - vec![format!("/{}/transactions/1", protocol_id.as_ref()).into()], - MAX_TRANSACTIONS_SIZE, - None, - SetConfig { + } + + /// Returns the configuration of the set to put in the network configuration. + pub fn set_config(&self) -> NonDefaultSetConfig { + NonDefaultSetConfig { + notifications_protocol: self.protocol_name.clone(), + fallback_names: self.fallback_protocol_names.clone(), + max_notification_size: MAX_TRANSACTIONS_SIZE, + handshake: None, + set_config: SetConfig { in_peers: 0, out_peers: 0, reserved_nodes: Vec::new(), non_reserved_mode: NonReservedPeerMode::Deny, }, - ); - - (Self { protocol_name, notification_service }, config) + } } /// Turns the prototype into the actual handler. Returns a controller that allows controlling @@ -169,12 +173,12 @@ impl TransactionsHandlerPrototype { transaction_pool: Arc>, metrics_registry: Option<&Registry>, ) -> error::Result<(TransactionsHandler, TransactionsHandlerController)> { + let net_event_stream = network.event_stream("transactions-handler-net"); let sync_event_stream = sync.event_stream("transactions-handler-sync"); let (to_handler, from_controller) = tracing_unbounded("mpsc_transactions_handler", 100_000); let handler = TransactionsHandler { protocol_name: self.protocol_name, - notification_service: self.notification_service, propagate_timeout: (Box::pin(interval(PROPAGATE_TIMEOUT)) as Pin + Send>>) .fuse(), @@ -182,6 +186,7 @@ impl TransactionsHandlerPrototype { pending_transactions_peers: HashMap::new(), network, sync, + net_event_stream: net_event_stream.fuse(), sync_event_stream: sync_event_stream.fuse(), peers: HashMap::new(), transaction_pool, @@ -248,6 +253,8 @@ pub struct TransactionsHandler< network: N, /// Syncing service. sync: S, + /// Stream of networking events. + net_event_stream: stream::Fuse + Send>>>, /// Receiver for syncing-related events. sync_event_stream: stream::Fuse + Send>>>, // All connected peers @@ -256,8 +263,6 @@ pub struct TransactionsHandler< from_controller: TracingUnboundedReceiver>, /// Prometheus metrics. metrics: Option, - /// Handle that is used to communicate with `sc_network::Notifications`. - notification_service: Box, } /// Peer information @@ -290,6 +295,14 @@ where warn!(target: "sub-libp2p", "Inconsistent state, no peers for pending transaction!"); } }, + network_event = self.net_event_stream.next() => { + if let Some(network_event) = network_event { + self.handle_network_event(network_event).await; + } else { + // Networking has seemingly closed. Closing as well. + return; + } + }, sync_event = self.sync_event_stream.next() => { if let Some(sync_event) = sync_event { self.handle_sync_event(sync_event); @@ -304,61 +317,10 @@ where ToHandler::PropagateTransactions => self.propagate_transactions(), } }, - event = self.notification_service.next_event().fuse() => { - if let Some(event) = event { - self.handle_notification_event(event) - } else { - // `Notifications` has seemingly closed. Closing as well. - return - } - } } } } - fn handle_notification_event(&mut self, event: NotificationEvent) { - match event { - NotificationEvent::ValidateInboundSubstream { peer, handshake, result_tx, .. } => { - // only accept peers whose role can be determined - let result = self - .network - .peer_role(peer, handshake) - .map_or(ValidationResult::Reject, |_| ValidationResult::Accept); - let _ = result_tx.send(result); - }, - NotificationEvent::NotificationStreamOpened { peer, handshake, .. } => { - let Some(role) = self.network.peer_role(peer, handshake) else { - log::debug!(target: "sub-libp2p", "role for {peer} couldn't be determined"); - return - }; - - let _was_in = self.peers.insert( - peer, - Peer { - known_transactions: LruHashSet::new( - NonZeroUsize::new(MAX_KNOWN_TRANSACTIONS).expect("Constant is nonzero"), - ), - role, - }, - ); - debug_assert!(_was_in.is_none()); - }, - NotificationEvent::NotificationStreamClosed { peer } => { - let _peer = self.peers.remove(&peer); - debug_assert!(_peer.is_some()); - }, - NotificationEvent::NotificationReceived { peer, notification } => { - if let Ok(m) = - as Decode>::decode(&mut notification.as_ref()) - { - self.on_transactions(peer, m); - } else { - warn!(target: "sub-libp2p", "Failed to decode transactions list"); - } - }, - } - } - fn handle_sync_event(&mut self, event: SyncEvent) { match event { SyncEvent::PeerConnected(remote) => { @@ -384,6 +346,51 @@ where } } + async fn handle_network_event(&mut self, event: Event) { + match event { + Event::Dht(_) => {}, + Event::NotificationStreamOpened { remote, protocol, role, .. } + if protocol == self.protocol_name => + { + let _was_in = self.peers.insert( + remote, + Peer { + known_transactions: LruHashSet::new( + NonZeroUsize::new(MAX_KNOWN_TRANSACTIONS).expect("Constant is nonzero"), + ), + role, + }, + ); + debug_assert!(_was_in.is_none()); + }, + Event::NotificationStreamClosed { remote, protocol } + if protocol == self.protocol_name => + { + let _peer = self.peers.remove(&remote); + debug_assert!(_peer.is_some()); + }, + + Event::NotificationsReceived { remote, messages } => { + for (protocol, message) in messages { + if protocol != self.protocol_name { + continue + } + + if let Ok(m) = + as Decode>::decode(&mut message.as_ref()) + { + self.on_transactions(remote, m); + } else { + warn!(target: "sub-libp2p", "Failed to decode transactions list"); + } + } + }, + + // Not our concern. + Event::NotificationStreamOpened { .. } | Event::NotificationStreamClosed { .. } => {}, + } + } + /// Called when peer sends us new transactions fn on_transactions(&mut self, who: PeerId, transactions: Transactions) { // Accept transactions only when node is not major syncing @@ -475,7 +482,8 @@ where propagated_to.entry(hash).or_default().push(who.to_base58()); } trace!(target: "sync", "Sending {} transactions to {}", to_send.len(), who); - let _ = self.notification_service.send_sync_notification(who, to_send.encode()); + self.network + .write_notification(*who, self.protocol_name.clone(), to_send.encode()); } } diff --git a/substrate/client/offchain/Cargo.toml b/substrate/client/offchain/Cargo.toml index 9f9731ba8de..83397f52879 100644 --- a/substrate/client/offchain/Cargo.toml +++ b/substrate/client/offchain/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -22,7 +19,7 @@ codec = { package = "parity-scale-codec", version = "3.6.1", features = ["derive fnv = "1.0.6" futures = "0.3.21" futures-timer = "3.0.2" -hyper = { version = "0.14.16", features = ["http2", "stream"] } +hyper = { version = "0.14.16", features = ["stream", "http2"] } hyper-rustls = { version = "0.24.0", features = ["http2"] } libp2p = "0.51.3" num_cpus = "1.13" @@ -48,7 +45,7 @@ log = "0.4.17" lazy_static = "1.4.0" tokio = "1.22.0" sc-block-builder = { path = "../block-builder" } -sc-client-db = { path = "../db", default-features = true } +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" } diff --git a/substrate/client/offchain/src/api.rs b/substrate/client/offchain/src/api.rs index 65e2f3ba64d..c7df5784d32 100644 --- a/substrate/client/offchain/src/api.rs +++ b/substrate/client/offchain/src/api.rs @@ -30,6 +30,7 @@ use sp_core::{ }, OpaquePeerId, }; +pub use sp_offchain::STORAGE_PREFIX; mod http; @@ -222,7 +223,7 @@ mod tests { use sc_client_db::offchain::LocalStorage; use sc_network::{ config::MultiaddrWithPeerId, types::ProtocolName, NetworkPeers, NetworkStateInfo, - ObservedRole, ReputationChange, + ReputationChange, }; use sp_core::offchain::{storage::OffchainDb, DbExternalities, Externalities, StorageKind}; use std::time::SystemTime; @@ -242,15 +243,11 @@ mod tests { unimplemented!(); } - fn report_peer(&self, _peer_id: PeerId, _cost_benefit: ReputationChange) { + fn report_peer(&self, _who: PeerId, _cost_benefit: ReputationChange) { unimplemented!(); } - fn peer_reputation(&self, _peer_id: &PeerId) -> i32 { - unimplemented!() - } - - fn disconnect_peer(&self, _peer_id: PeerId, _protocol: ProtocolName) { + fn disconnect_peer(&self, _who: PeerId, _protocol: ProtocolName) { unimplemented!(); } @@ -297,10 +294,6 @@ mod tests { fn sync_num_connected(&self) -> usize { unimplemented!(); } - - fn peer_role(&self, _peer_id: PeerId, _handshake: Vec) -> Option { - None - } } impl NetworkStateInfo for TestNetwork { diff --git a/substrate/client/offchain/src/lib.rs b/substrate/client/offchain/src/lib.rs index eb3436432f3..756ab77ff94 100644 --- a/substrate/client/offchain/src/lib.rs +++ b/substrate/client/offchain/src/lib.rs @@ -330,9 +330,7 @@ mod tests { use libp2p::{Multiaddr, PeerId}; use sc_block_builder::BlockBuilderBuilder; use sc_client_api::Backend as _; - use sc_network::{ - config::MultiaddrWithPeerId, types::ProtocolName, ObservedRole, ReputationChange, - }; + use sc_network::{config::MultiaddrWithPeerId, types::ProtocolName, ReputationChange}; use sc_transaction_pool::BasicPool; use sc_transaction_pool_api::{InPoolTransaction, TransactionPool}; use sp_consensus::BlockOrigin; @@ -374,15 +372,11 @@ mod tests { unimplemented!(); } - fn report_peer(&self, _peer_id: PeerId, _cost_benefit: ReputationChange) { + fn report_peer(&self, _who: PeerId, _cost_benefit: ReputationChange) { unimplemented!(); } - fn peer_reputation(&self, _peer_id: &PeerId) -> i32 { - unimplemented!() - } - - fn disconnect_peer(&self, _peer_id: PeerId, _protocol: ProtocolName) { + fn disconnect_peer(&self, _who: PeerId, _protocol: ProtocolName) { unimplemented!(); } @@ -429,10 +423,6 @@ mod tests { fn sync_num_connected(&self) -> usize { unimplemented!(); } - - fn peer_role(&self, _peer_id: PeerId, _handshake: Vec) -> Option { - None - } } #[test] diff --git a/substrate/client/proposer-metrics/Cargo.toml b/substrate/client/proposer-metrics/Cargo.toml index 664b72764a3..b6b4452ecc6 100644 --- a/substrate/client/proposer-metrics/Cargo.toml +++ b/substrate/client/proposer-metrics/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Basic metrics for block production." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/rpc-api/Cargo.toml b/substrate/client/rpc-api/Cargo.toml index 6b1270fc370..e72bbe48ee3 100644 --- a/substrate/client/rpc-api/Cargo.toml +++ b/substrate/client/rpc-api/Cargo.toml @@ -9,16 +9,13 @@ repository.workspace = true description = "Substrate RPC interfaces." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1" } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.108" thiserror = "1.0" sc-chain-spec = { path = "../chain-spec" } @@ -28,4 +25,4 @@ sp-core = { path = "../../primitives/core" } sp-rpc = { path = "../../primitives/rpc" } sp-runtime = { path = "../../primitives/runtime" } sp-version = { path = "../../primitives/version" } -jsonrpsee = { version = "0.16.2", features = ["client-core", "macros", "server"] } +jsonrpsee = { version = "0.16.2", features = ["server", "client-core", "macros"] } diff --git a/substrate/client/rpc-servers/Cargo.toml b/substrate/client/rpc-servers/Cargo.toml index 5bb7317264c..a7cc374f97a 100644 --- a/substrate/client/rpc-servers/Cargo.toml +++ b/substrate/client/rpc-servers/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Substrate RPC servers." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/rpc-spec-v2/Cargo.toml b/substrate/client/rpc-spec-v2/Cargo.toml index b5fb8b5b204..8ca4f321f71 100644 --- a/substrate/client/rpc-spec-v2/Cargo.toml +++ b/substrate/client/rpc-spec-v2/Cargo.toml @@ -9,14 +9,11 @@ repository.workspace = true description = "Substrate RPC interface v2." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -jsonrpsee = { version = "0.16.2", features = ["client-core", "macros", "server"] } +jsonrpsee = { version = "0.16.2", features = ["client-core", "server", "macros"] } # Internal chain structures for "chain_spec". sc-chain-spec = { path = "../chain-spec" } # Pool for submitting extrinsics required by "transaction" @@ -50,6 +47,6 @@ 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"] } +sc-service = { path = "../service", features = ["test-helpers"]} assert_matches = "1.3.0" pretty_assertions = "1.2.1" 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 8e04ac7b177..866701a7dbf 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 @@ -198,9 +198,7 @@ where let sub_id = match self.accept_subscription(&mut sink) { Ok(sub_id) => sub_id, Err(err) => { - sink.close(ChainHeadRpcError::InternalError( - "Cannot generate subscription ID".into(), - )); + sink.close(ChainHeadRpcError::InvalidSubscriptionID); return Err(err) }, }; @@ -308,7 +306,7 @@ where self.client .header(hash) .map(|opt_header| opt_header.map(|h| hex_string(&h.encode()))) - .map_err(|err| ChainHeadRpcError::InternalError(err.to_string())) + .map_err(ChainHeadRpcError::FetchBlockHeader) .map_err(Into::into) } @@ -395,7 +393,7 @@ where // Reject subscription if with_runtime is false. if !block_guard.has_runtime() { - return Err(ChainHeadRpcError::InvalidRuntimeCall( + return Err(ChainHeadRpcError::InvalidParam( "The runtime updates flag must be set".to_string(), ) .into()) diff --git a/substrate/client/rpc-spec-v2/src/chain_head/error.rs b/substrate/client/rpc-spec-v2/src/chain_head/error.rs index a9b7d7f96e4..811666428c5 100644 --- a/substrate/client/rpc-spec-v2/src/chain_head/error.rs +++ b/substrate/client/rpc-spec-v2/src/chain_head/error.rs @@ -22,6 +22,7 @@ use jsonrpsee::{ core::Error as RpcError, types::error::{CallError, ErrorObject}, }; +use sp_blockchain::Error as BlockchainError; /// ChainHead RPC errors. #[derive(Debug, thiserror::Error)] @@ -29,55 +30,44 @@ pub enum Error { /// The provided block hash is invalid. #[error("Invalid block hash")] InvalidBlock, - /// The follow subscription was started with `withRuntime` set to `false`. - #[error("The `chainHead_follow` subscription was started with `withRuntime` set to `false`")] - InvalidRuntimeCall(String), - /// Wait-for-continue event not generated. - #[error("Wait for continue event was not generated for the subscription")] - InvalidContinue, + /// Fetch block header error. + #[error("Could not fetch block header: {0}")] + FetchBlockHeader(BlockchainError), /// Invalid parameter provided to the RPC method. #[error("Invalid parameter: {0}")] InvalidParam(String), - /// Internal error. - #[error("Internal error: {0}")] - InternalError(String), -} - -/// Errors for `chainHead` RPC module, as defined in -/// . -pub mod rpc_spec_v2 { - /// The provided block hash is invalid. - pub const INVALID_BLOCK_ERROR: i32 = -32801; - /// The follow subscription was started with `withRuntime` set to `false`. - pub const INVALID_RUNTIME_CALL: i32 = -32802; + /// Invalid subscription ID provided by the RPC server. + #[error("Invalid subscription ID")] + InvalidSubscriptionID, /// Wait-for-continue event not generated. - pub const INVALID_CONTINUE: i32 = -32803; + #[error("Wait for continue event was not generated for the subscription")] + InvalidContinue, } -/// General purpose errors, as defined in -/// . -pub mod json_rpc_spec { - /// Invalid parameter error. - pub const INVALID_PARAM_ERROR: i32 = -32602; - /// Internal error. - pub const INTERNAL_ERROR: i32 = -32603; -} +// Base code for all `chainHead` errors. +const BASE_ERROR: i32 = 2000; +/// The provided block hash is invalid. +const INVALID_BLOCK_ERROR: i32 = BASE_ERROR + 1; +/// Fetch block header error. +const FETCH_BLOCK_HEADER_ERROR: i32 = BASE_ERROR + 2; +/// Invalid parameter error. +const INVALID_PARAM_ERROR: i32 = BASE_ERROR + 3; +/// Invalid subscription ID. +const INVALID_SUB_ID: i32 = BASE_ERROR + 4; +/// Wait-for-continue event not generated. +const INVALID_CONTINUE: i32 = BASE_ERROR + 5; impl From for ErrorObject<'static> { fn from(e: Error) -> Self { let msg = e.to_string(); match e { - Error::InvalidBlock => - ErrorObject::owned(rpc_spec_v2::INVALID_BLOCK_ERROR, msg, None::<()>), - Error::InvalidRuntimeCall(_) => - ErrorObject::owned(rpc_spec_v2::INVALID_RUNTIME_CALL, msg, None::<()>), - Error::InvalidContinue => - ErrorObject::owned(rpc_spec_v2::INVALID_CONTINUE, msg, None::<()>), - Error::InvalidParam(_) => - ErrorObject::owned(json_rpc_spec::INVALID_PARAM_ERROR, msg, None::<()>), - Error::InternalError(_) => - ErrorObject::owned(json_rpc_spec::INTERNAL_ERROR, msg, None::<()>), + Error::InvalidBlock => ErrorObject::owned(INVALID_BLOCK_ERROR, msg, None::<()>), + Error::FetchBlockHeader(_) => + ErrorObject::owned(FETCH_BLOCK_HEADER_ERROR, msg, None::<()>), + Error::InvalidParam(_) => ErrorObject::owned(INVALID_PARAM_ERROR, msg, None::<()>), + Error::InvalidSubscriptionID => ErrorObject::owned(INVALID_SUB_ID, msg, None::<()>), + Error::InvalidContinue => ErrorObject::owned(INVALID_CONTINUE, msg, None::<()>), } } } diff --git a/substrate/client/rpc-spec-v2/src/chain_head/tests.rs b/substrate/client/rpc-spec-v2/src/chain_head/tests.rs index c8f2362b9eb..518b7da432b 100644 --- a/substrate/client/rpc-spec-v2/src/chain_head/tests.rs +++ b/substrate/client/rpc-spec-v2/src/chain_head/tests.rs @@ -360,7 +360,7 @@ async fn get_header() { .await .unwrap_err(); assert_matches!(err, - Error::Call(CallError::Custom(ref err)) if err.code() == super::error::rpc_spec_v2::INVALID_BLOCK_ERROR && err.message() == "Invalid block hash" + Error::Call(CallError::Custom(ref err)) if err.code() == 2001 && err.message() == "Invalid block hash" ); // Obtain the valid header. @@ -389,7 +389,7 @@ async fn get_body() { .await .unwrap_err(); assert_matches!(err, - Error::Call(CallError::Custom(ref err)) if err.code() == super::error::rpc_spec_v2::INVALID_BLOCK_ERROR && err.message() == "Invalid block hash" + Error::Call(CallError::Custom(ref err)) if err.code() == 2001 && err.message() == "Invalid block hash" ); // Valid call. @@ -474,7 +474,7 @@ async fn call_runtime() { .await .unwrap_err(); assert_matches!(err, - Error::Call(CallError::Custom(ref err)) if err.code() == super::error::rpc_spec_v2::INVALID_BLOCK_ERROR && err.message() == "Invalid block hash" + Error::Call(CallError::Custom(ref err)) if err.code() == 2001 && err.message() == "Invalid block hash" ); // Pass an invalid parameters that cannot be decode. @@ -487,7 +487,7 @@ async fn call_runtime() { .await .unwrap_err(); assert_matches!(err, - Error::Call(CallError::Custom(ref err)) if err.code() == super::error::json_rpc_spec::INVALID_PARAM_ERROR && err.message().contains("Invalid parameter") + Error::Call(CallError::Custom(ref err)) if err.code() == 2003 && err.message().contains("Invalid parameter") ); // Valid call. @@ -590,7 +590,7 @@ async fn call_runtime_without_flag() { .unwrap_err(); assert_matches!(err, - Error::Call(CallError::Custom(ref err)) if err.code() == super::error::rpc_spec_v2::INVALID_RUNTIME_CALL && err.message().contains("subscription was started with `withRuntime` set to `false`") + Error::Call(CallError::Custom(ref err)) if err.code() == 2003 && err.message().contains("The runtime updates flag must be set") ); } @@ -628,7 +628,7 @@ async fn get_storage_hash() { .await .unwrap_err(); assert_matches!(err, - Error::Call(CallError::Custom(ref err)) if err.code() == super::error::rpc_spec_v2::INVALID_BLOCK_ERROR && err.message() == "Invalid block hash" + Error::Call(CallError::Custom(ref err)) if err.code() == 2001 && err.message() == "Invalid block hash" ); // Valid call without storage at the key. @@ -896,7 +896,7 @@ async fn get_storage_value() { .await .unwrap_err(); assert_matches!(err, - Error::Call(CallError::Custom(ref err)) if err.code() == super::error::rpc_spec_v2::INVALID_BLOCK_ERROR && err.message() == "Invalid block hash" + Error::Call(CallError::Custom(ref err)) if err.code() == 2001 && err.message() == "Invalid block hash" ); // Valid call without storage at the key. @@ -1571,7 +1571,7 @@ async fn follow_with_unpin() { .await .unwrap_err(); assert_matches!(err, - Error::Call(CallError::Custom(ref err)) if err.code() == super::error::rpc_spec_v2::INVALID_BLOCK_ERROR && err.message() == "Invalid block hash" + Error::Call(CallError::Custom(ref err)) if err.code() == 2001 && err.message() == "Invalid block hash" ); // To not exceed the number of pinned blocks, we need to unpin before the next import. @@ -1720,7 +1720,7 @@ async fn follow_with_multiple_unpin_hashes() { .await .unwrap_err(); assert_matches!(err, - Error::Call(CallError::Custom(ref err)) if err.code() == super::error::rpc_spec_v2::INVALID_BLOCK_ERROR && err.message() == "Invalid block hash" + Error::Call(CallError::Custom(ref err)) if err.code() == 2001 && err.message() == "Invalid block hash" ); let _res: () = api @@ -1737,7 +1737,7 @@ async fn follow_with_multiple_unpin_hashes() { .await .unwrap_err(); assert_matches!(err, - Error::Call(CallError::Custom(ref err)) if err.code() == super::error::rpc_spec_v2::INVALID_BLOCK_ERROR && err.message() == "Invalid block hash" + Error::Call(CallError::Custom(ref err)) if err.code() == 2001 && err.message() == "Invalid block hash" ); // Unpin multiple blocks. @@ -1755,7 +1755,7 @@ async fn follow_with_multiple_unpin_hashes() { .await .unwrap_err(); assert_matches!(err, - Error::Call(CallError::Custom(ref err)) if err.code() == super::error::rpc_spec_v2::INVALID_BLOCK_ERROR && err.message() == "Invalid block hash" + Error::Call(CallError::Custom(ref err)) if err.code() == 2001 && err.message() == "Invalid block hash" ); let err = api @@ -1766,7 +1766,7 @@ async fn follow_with_multiple_unpin_hashes() { .await .unwrap_err(); assert_matches!(err, - Error::Call(CallError::Custom(ref err)) if err.code() == super::error::rpc_spec_v2::INVALID_BLOCK_ERROR && err.message() == "Invalid block hash" + Error::Call(CallError::Custom(ref err)) if err.code() == 2001 && err.message() == "Invalid block hash" ); } diff --git a/substrate/client/rpc/Cargo.toml b/substrate/client/rpc/Cargo.toml index 361d98a6b10..1cedcb3a6d0 100644 --- a/substrate/client/rpc/Cargo.toml +++ b/substrate/client/rpc/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Substrate Client RPC" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/service/Cargo.toml b/substrate/client/service/Cargo.toml index 4c03b59a663..de69c50702a 100644 --- a/substrate/client/service/Cargo.toml +++ b/substrate/client/service/Cargo.toml @@ -9,17 +9,14 @@ repository.workspace = true description = "Substrate service. Starts a thread that spins up the network, client, and extrinsic pool. Manages communication between them." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [features] -default = ["rocksdb"] +default = [ "rocksdb" ] # The RocksDB feature activates the RocksDB database backend. If it is not activated, and you pass # a path to a database, an error will be produced at runtime. -rocksdb = ["sc-client-db/rocksdb"] +rocksdb = [ "sc-client-db/rocksdb" ] # exposes the client type test-helpers = [] runtime-benchmarks = [ @@ -37,7 +34,7 @@ log = "0.4.17" futures-timer = "3.0.1" exit-future = "0.2.0" pin-project = "1.0.12" -serde = "1.0.193" +serde = "1.0.188" serde_json = "1.0.108" sc-keystore = { path = "../keystore" } sp-runtime = { path = "../../primitives/runtime" } @@ -62,7 +59,7 @@ 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 } +sc-client-db = { path = "../db", default-features = false} codec = { package = "parity-scale-codec", version = "3.6.1" } sc-executor = { path = "../executor" } sc-transaction-pool = { path = "../transaction-pool" } @@ -80,7 +77,7 @@ sc-sysinfo = { path = "../sysinfo" } tracing = "0.1.29" tracing-futures = { version = "0.2.4" } async-trait = "0.1.57" -tokio = { version = "1.22.0", features = ["parking_lot", "rt-multi-thread", "time"] } +tokio = { version = "1.22.0", features = ["time", "rt-multi-thread", "parking_lot"] } tempfile = "3.1.0" directories = "5.0.1" static_init = "1.0.3" diff --git a/substrate/client/service/src/builder.rs b/substrate/client/service/src/builder.rs index 1a3a679c519..25f998385ba 100644 --- a/substrate/client/service/src/builder.rs +++ b/substrate/client/service/src/builder.rs @@ -130,11 +130,10 @@ where } /// Create the initial parts of a full node with the default genesis block builder. -pub fn new_full_parts_record_import( +pub fn new_full_parts( config: &Configuration, telemetry: Option, executor: TExec, - enable_import_proof_recording: bool, ) -> Result, Error> where TBl: BlockT, @@ -149,26 +148,7 @@ where executor.clone(), )?; - new_full_parts_with_genesis_builder( - config, - telemetry, - executor, - backend, - genesis_block_builder, - enable_import_proof_recording, - ) -} -/// Create the initial parts of a full node with the default genesis block builder. -pub fn new_full_parts( - config: &Configuration, - telemetry: Option, - executor: TExec, -) -> Result, Error> -where - TBl: BlockT, - TExec: CodeExecutor + RuntimeVersionOf + Clone, -{ - new_full_parts_record_import(config, telemetry, executor, false) + new_full_parts_with_genesis_builder(config, telemetry, executor, backend, genesis_block_builder) } /// Create the initial parts of a full node. @@ -178,7 +158,6 @@ pub fn new_full_parts_with_genesis_builder>, genesis_block_builder: TBuildGenesisBlock, - enable_import_proof_recording: bool, ) -> Result, Error> where TBl: BlockT, @@ -246,7 +225,6 @@ where SyncMode::LightState { .. } | SyncMode::Warp { .. } ), wasm_runtime_substitutes, - enable_import_proof_recording, }, )?; @@ -775,11 +753,6 @@ where } let protocol_id = config.protocol_id(); - let genesis_hash = client - .block_hash(0u32.into()) - .ok() - .flatten() - .expect("Genesis block exists; qed"); let block_announce_validator = if let Some(f) = block_announce_validator_builder { f(client.clone()) @@ -829,7 +802,11 @@ where // Allow both outgoing and incoming requests. let (handler, protocol_config) = WarpSyncRequestHandler::new( protocol_id.clone(), - genesis_hash, + client + .block_hash(0u32.into()) + .ok() + .flatten() + .expect("Genesis block exists; qed"), config.chain_spec.fork_id(), warp_with_provider.clone(), ); @@ -868,13 +845,17 @@ where } // create transactions protocol and add it to the list of supported protocols of - let (transactions_handler_proto, transactions_config) = - sc_network_transactions::TransactionsHandlerPrototype::new( - protocol_id.clone(), - genesis_hash, - config.chain_spec.fork_id(), - ); - net_config.add_notification_protocol(transactions_config); + // `network_params` + let transactions_handler_proto = sc_network_transactions::TransactionsHandlerPrototype::new( + protocol_id.clone(), + client + .block_hash(0u32.into()) + .ok() + .flatten() + .expect("Genesis block exists; qed"), + config.chain_spec.fork_id(), + ); + net_config.add_notification_protocol(transactions_handler_proto.set_config()); // Create `PeerStore` and initialize it with bootnode peer ids. let peer_store = PeerStore::new( @@ -888,6 +869,7 @@ where let peer_store_handle = peer_store.handle(); spawn_handle.spawn("peer-store", Some("networking"), peer_store.run()); + let (tx, rx) = sc_utils::mpsc::tracing_unbounded("mpsc_syncing_engine_protocol", 100_000); let (engine, sync_service, block_announce_config) = SyncingEngine::new( Roles::from(&config.role), client.clone(), @@ -902,7 +884,7 @@ where block_downloader, state_request_protocol_name, warp_request_protocol_name, - peer_store_handle.clone(), + rx, )?; let sync_service_import_queue = sync_service.clone(); let sync_service = Arc::new(sync_service); @@ -923,6 +905,7 @@ where fork_id: config.chain_spec.fork_id().map(ToOwned::to_owned), metrics_registry: config.prometheus_config.as_ref().map(|config| config.registry.clone()), block_announce_config, + tx, }; let has_bootnodes = !network_params.network_config.network_config.boot_nodes.is_empty(); diff --git a/substrate/client/service/src/client/client.rs b/substrate/client/service/src/client/client.rs index aa9c1b80a29..9d51aae55b2 100644 --- a/substrate/client/service/src/client/client.rs +++ b/substrate/client/service/src/client/client.rs @@ -77,7 +77,7 @@ use sp_state_machine::{ ChildStorageCollection, KeyValueStates, KeyValueStorageLevel, StorageCollection, MAX_NESTED_TRIE_DEPTH, }; -use sp_trie::{proof_size_extension::ProofSizeExt, CompactProof, MerkleValue, StorageProof}; +use sp_trie::{CompactProof, MerkleValue, StorageProof}; use std::{ collections::{HashMap, HashSet}, marker::PhantomData, @@ -184,7 +184,7 @@ where ) } -/// Client configuration items. +/// Relevant client configuration items relevant for the client. #[derive(Debug, Clone)] pub struct ClientConfig { /// Enable the offchain worker db. @@ -198,8 +198,6 @@ pub struct ClientConfig { /// Map of WASM runtime substitute starting at the child of the given block until the runtime /// version doesn't match anymore. pub wasm_runtime_substitutes: HashMap, Vec>, - /// Enable recording of storage proofs during block import - pub enable_import_proof_recording: bool, } impl Default for ClientConfig { @@ -210,7 +208,6 @@ impl Default for ClientConfig { wasm_runtime_overrides: None, no_genesis: false, wasm_runtime_substitutes: HashMap::new(), - enable_import_proof_recording: false, } } } @@ -861,14 +858,6 @@ where runtime_api.set_call_context(CallContext::Onchain); - if self.config.enable_import_proof_recording { - runtime_api.record_proof(); - let recorder = runtime_api - .proof_recorder() - .expect("Proof recording is enabled in the line above; qed."); - runtime_api.register_extension(ProofSizeExt::new(recorder)); - } - runtime_api.execute_block( *parent_hash, Block::new(import_block.header.clone(), body.clone()), diff --git a/substrate/client/service/src/lib.rs b/substrate/client/service/src/lib.rs index 0c7e138ce90..ff9eb982b86 100644 --- a/substrate/client/service/src/lib.rs +++ b/substrate/client/service/src/lib.rs @@ -53,10 +53,9 @@ use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; pub use self::{ builder::{ build_network, new_client, new_db_backend, new_full_client, new_full_parts, - new_full_parts_record_import, new_full_parts_with_genesis_builder, - new_native_or_wasm_executor, new_wasm_executor, spawn_tasks, BuildNetworkParams, - KeystoreContainer, NetworkStarter, SpawnTasksParams, TFullBackend, TFullCallExecutor, - TFullClient, + new_full_parts_with_genesis_builder, new_native_or_wasm_executor, new_wasm_executor, + spawn_tasks, BuildNetworkParams, KeystoreContainer, NetworkStarter, SpawnTasksParams, + TFullBackend, TFullCallExecutor, TFullClient, }, client::{ClientConfig, LocalCallExecutor}, error::Error, diff --git a/substrate/client/service/test/Cargo.toml b/substrate/client/service/test/Cargo.toml index 625d8286396..c6091f97d63 100644 --- a/substrate/client/service/test/Cargo.toml +++ b/substrate/client/service/test/Cargo.toml @@ -8,9 +8,6 @@ publish = false homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -26,12 +23,12 @@ 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-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-service = { path = "..", features = ["test-helpers"]} sc-transaction-pool-api = { path = "../../transaction-pool/api" } sp-api = { path = "../../../primitives/api" } sp-blockchain = { path = "../../../primitives/blockchain" } diff --git a/substrate/client/state-db/Cargo.toml b/substrate/client/state-db/Cargo.toml index 001ada02ef2..c5e8272637d 100644 --- a/substrate/client/state-db/Cargo.toml +++ b/substrate/client/state-db/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "State database maintenance. Handles canonicalization and pruning in the database." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/client/state-db/src/lib.rs b/substrate/client/state-db/src/lib.rs index 41c231c31aa..c656f126ae6 100644 --- a/substrate/client/state-db/src/lib.rs +++ b/substrate/client/state-db/src/lib.rs @@ -474,7 +474,7 @@ impl StateDbSync { if have_block { let refs = self.pinned.entry(hash.clone()).or_default(); if *refs == 0 { - trace!(target: LOG_TARGET_PIN, "Pinned block: {:?}", hash); + trace!(target: "state-db-pin", "Pinned block: {:?}", hash); self.non_canonical.pin(hash); } *refs += 1; @@ -491,11 +491,11 @@ impl StateDbSync { Entry::Occupied(mut entry) => { *entry.get_mut() -= 1; if *entry.get() == 0 { - trace!(target: LOG_TARGET_PIN, "Unpinned block: {:?}", hash); + trace!(target: "state-db-pin", "Unpinned block: {:?}", hash); entry.remove(); self.non_canonical.unpin(hash); } else { - trace!(target: LOG_TARGET_PIN, "Releasing reference for {:?}", hash); + trace!(target: "state-db-pin", "Releasing reference for {:?}", hash); } }, Entry::Vacant(_) => {}, diff --git a/substrate/client/state-db/src/pruning.rs b/substrate/client/state-db/src/pruning.rs index ae8a9a12490..623d30b098b 100644 --- a/substrate/client/state-db/src/pruning.rs +++ b/substrate/client/state-db/src/pruning.rs @@ -385,7 +385,7 @@ impl RefWindow { /// Prune next block. Expects at least one block in the window. Adds changes to `commit`. pub fn prune_one(&mut self, commit: &mut CommitSet) -> Result<(), Error> { if let Some(pruned) = self.queue.pop_front(self.base)? { - trace!(target: LOG_TARGET, "Pruning {:?} ({} deleted)", pruned.hash, pruned.deleted.len()); + trace!(target: "state-db", "Pruning {:?} ({} deleted)", pruned.hash, pruned.deleted.len()); let index = self.base; commit.data.deleted.extend(pruned.deleted.into_iter()); commit.meta.inserted.push((to_meta_key(LAST_PRUNED, &()), index.encode())); @@ -393,7 +393,7 @@ impl RefWindow { self.base += 1; Ok(()) } else { - trace!(target: LOG_TARGET, "Trying to prune when there's nothing to prune"); + trace!(target: "state-db", "Trying to prune when there's nothing to prune"); Err(Error::StateDb(StateDbError::BlockUnavailable)) } } @@ -418,7 +418,7 @@ impl RefWindow { return Err(Error::StateDb(StateDbError::InvalidBlockNumber)) } trace!( - target: LOG_TARGET, + target: "state-db", "Adding to pruning window: {:?} ({} inserted, {} deleted)", hash, commit.data.inserted.len(), diff --git a/substrate/client/statement-store/Cargo.toml b/substrate/client/statement-store/Cargo.toml index adfd27a1705..371d6736916 100644 --- a/substrate/client/statement-store/Cargo.toml +++ b/substrate/client/statement-store/Cargo.toml @@ -9,16 +9,13 @@ repository.workspace = true description = "Substrate statement store." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] log = "0.4.17" parking_lot = "0.12.1" -parity-db = "0.4.12" +parity-db = "0.4.8" tokio = { version = "1.22.0", features = ["time"] } sp-statement-store = { path = "../../primitives/statement-store" } prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } diff --git a/substrate/client/storage-monitor/Cargo.toml b/substrate/client/storage-monitor/Cargo.toml index 1c4a136ade6..021ee76240b 100644 --- a/substrate/client/storage-monitor/Cargo.toml +++ b/substrate/client/storage-monitor/Cargo.toml @@ -8,14 +8,11 @@ repository.workspace = true description = "Storage monitor service for substrate" homepage = "https://substrate.io" -[lints] -workspace = true - [dependencies] -clap = { version = "4.4.11", features = ["derive", "string"] } +clap = { version = "4.4.6", features = ["derive", "string"] } log = "0.4.17" -fs4 = "0.7.0" -sc-client-db = { path = "../db", default-features = false } +fs4 = "0.6.3" +sc-client-db = { path = "../db", default-features = false} sp-core = { path = "../../primitives/core" } tokio = "1.22.0" thiserror = "1.0.48" diff --git a/substrate/client/sync-state-rpc/Cargo.toml b/substrate/client/sync-state-rpc/Cargo.toml index c839a4210e4..569cd067f27 100644 --- a/substrate/client/sync-state-rpc/Cargo.toml +++ b/substrate/client/sync-state-rpc/Cargo.toml @@ -8,16 +8,13 @@ license = "Apache-2.0" homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1" } -jsonrpsee = { version = "0.16.2", features = ["client-core", "macros", "server"] } -serde = { version = "1.0.193", features = ["derive"] } +jsonrpsee = { version = "0.16.2", features = ["client-core", "server", "macros"] } +serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.108" thiserror = "1.0.48" sc-chain-spec = { path = "../chain-spec" } diff --git a/substrate/client/sysinfo/Cargo.toml b/substrate/client/sysinfo/Cargo.toml index e5d5987c90e..86f03050c44 100644 --- a/substrate/client/sysinfo/Cargo.toml +++ b/substrate/client/sysinfo/Cargo.toml @@ -10,9 +10,6 @@ description = "A crate that provides basic hardware and software telemetry infor documentation = "https://docs.rs/sc-sysinfo" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -24,7 +21,7 @@ rand = "0.8.5" rand_pcg = "0.3.1" derive_more = "0.99" regex = "1" -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.108" sc-telemetry = { path = "../telemetry" } sp-core = { path = "../../primitives/core" } diff --git a/substrate/client/telemetry/Cargo.toml b/substrate/client/telemetry/Cargo.toml index 0f7f8ab33ee..a693a2884b5 100644 --- a/substrate/client/telemetry/Cargo.toml +++ b/substrate/client/telemetry/Cargo.toml @@ -10,9 +10,6 @@ repository.workspace = true documentation = "https://docs.rs/sc-telemetry" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -25,7 +22,7 @@ parking_lot = "0.12.1" pin-project = "1.0.12" sc-utils = { path = "../utils" } rand = "0.8.5" -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } serde_json = "1.0.108" thiserror = "1.0.48" wasm-timer = "0.2.5" diff --git a/substrate/client/tracing/Cargo.toml b/substrate/client/tracing/Cargo.toml index 94dd6e89231..796d4f1d826 100644 --- a/substrate/client/tracing/Cargo.toml +++ b/substrate/client/tracing/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Instrumentation implementation for substrate." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -26,7 +23,7 @@ log = { version = "0.4.17" } parking_lot = "0.12.1" regex = "1.6.0" rustc-hash = "1.1.0" -serde = "1.0.193" +serde = "1.0.188" thiserror = "1.0.48" tracing = "0.1.29" tracing-log = "0.1.3" diff --git a/substrate/client/tracing/proc-macro/Cargo.toml b/substrate/client/tracing/proc-macro/Cargo.toml index d85a4a7468a..b134cbce3cc 100644 --- a/substrate/client/tracing/proc-macro/Cargo.toml +++ b/substrate/client/tracing/proc-macro/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "Helper macros for Substrate's client CLI" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -18,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -proc-macro-crate = "2.0.1" +proc-macro-crate = "1.1.3" proc-macro2 = "1.0.56" quote = { version = "1.0.28", features = ["proc-macro"] } -syn = { version = "2.0.40", features = ["extra-traits", "full", "parsing", "proc-macro"] } +syn = { version = "2.0.38", features = ["proc-macro", "full", "extra-traits", "parsing"] } diff --git a/substrate/client/transaction-pool/Cargo.toml b/substrate/client/transaction-pool/Cargo.toml index 493f6680c4c..b893dc839ed 100644 --- a/substrate/client/transaction-pool/Cargo.toml +++ b/substrate/client/transaction-pool/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Substrate transaction pool implementation." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -23,7 +20,7 @@ futures-timer = "3.0.2" linked-hash-map = "0.5.4" log = "0.4.17" parking_lot = "0.12.1" -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } thiserror = "1.0.48" prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } sc-client-api = { path = "../api" } diff --git a/substrate/client/transaction-pool/api/Cargo.toml b/substrate/client/transaction-pool/api/Cargo.toml index 29e402c34f8..f5760c271ad 100644 --- a/substrate/client/transaction-pool/api/Cargo.toml +++ b/substrate/client/transaction-pool/api/Cargo.toml @@ -8,19 +8,16 @@ homepage = "https://substrate.io" repository.workspace = true description = "Transaction pool client facing API." -[lints] -workspace = true - [dependencies] async-trait = "0.1.57" codec = { package = "parity-scale-codec", version = "3.6.1" } futures = "0.3.21" log = "0.4.17" -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } thiserror = "1.0.48" sp-blockchain = { path = "../../../primitives/blockchain" } -sp-core = { path = "../../../primitives/core", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } +sp-core = { path = "../../../primitives/core", default-features = false} +sp-runtime = { path = "../../../primitives/runtime", default-features = false} [dev-dependencies] serde_json = "1.0.108" diff --git a/substrate/client/transaction-pool/src/graph/mod.rs b/substrate/client/transaction-pool/src/graph/mod.rs index 484a6d6cf9f..5afdddb7402 100644 --- a/substrate/client/transaction-pool/src/graph/mod.rs +++ b/substrate/client/transaction-pool/src/graph/mod.rs @@ -39,6 +39,9 @@ pub mod watcher; pub use self::{ base_pool::Transaction, - pool::{BlockHash, ChainApi, ExtrinsicFor, ExtrinsicHash, NumberFor, Options, Pool}, + pool::{ + BlockHash, ChainApi, EventStream, ExtrinsicFor, ExtrinsicHash, NumberFor, Options, Pool, + TransactionFor, + }, }; pub use validated_pool::{IsValidator, ValidatedTransaction}; diff --git a/substrate/client/utils/Cargo.toml b/substrate/client/utils/Cargo.toml index a19457ac3d0..885b1d26a8e 100644 --- a/substrate/client/utils/Cargo.toml +++ b/substrate/client/utils/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "I/O for Substrate runtimes" readme = "README.md" -[lints] -workspace = true - [dependencies] async-channel = "1.8.0" futures = "0.3.21" @@ -20,10 +17,10 @@ lazy_static = "1.4.0" log = "0.4" parking_lot = "0.12.1" prometheus = { version = "0.13.0", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } +sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false} [features] -default = ["metered"] +default = [ "metered" ] metered = [] [dev-dependencies] diff --git a/substrate/docs/STYLE_GUIDE.md b/substrate/docs/STYLE_GUIDE.md index d5e703b3fdf..6ea0755d080 100644 --- a/substrate/docs/STYLE_GUIDE.md +++ b/substrate/docs/STYLE_GUIDE.md @@ -157,7 +157,7 @@ format looks like this: - The feature is written as a single line if it fits within 80 chars: ```toml [features] -default = ["std"] +default = [ "std" ] ``` - Otherwise the feature is broken down into multiple lines with one entry per line. Each line is padded with one tab and diff --git a/substrate/frame/Cargo.toml b/substrate/frame/Cargo.toml index 083d098b22a..9f2f73ffb15 100644 --- a/substrate/frame/Cargo.toml +++ b/substrate/frame/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "The single package to get you started with building frame pallets and runtimes" publish = false -[lints] -workspace = true - [package.metadata.docs.rs] # enable `experimental` feature for docs features = ["experimental"] @@ -20,7 +17,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # external deps parity-scale-codec = { version = "3.2.2", default-features = false, features = ["derive"] } -scale-info = { version = "2.6.0", default-features = false, features = ["derive"] } +scale-info = { version = "2.6.0", default-features = false, features = ["derive"] } # primitive deps, used for developing FRAME pallets. sp-runtime = { default-features = false, path = "../primitives/runtime" } @@ -30,8 +27,8 @@ sp-core = { default-features = false, path = "../primitives/core" } sp-arithmetic = { default-features = false, path = "../primitives/arithmetic" } # frame deps, for developing FRAME pallets. -frame-support = { default-features = false, path = "support" } -frame-system = { default-features = false, path = "system" } +frame-support = { default-features = false, path = "support" } +frame-system = { default-features = false, path = "system" } # primitive types used for developing FRAME runtimes. sp-version = { default-features = false, path = "../primitives/version", optional = true } @@ -55,8 +52,8 @@ log = { version = "0.4.20", default-features = false } pallet-examples = { path = "./examples" } [features] -default = ["runtime", "std"] -experimental = ["frame-support/experimental"] +default = [ "runtime", "std" ] +experimental = [ "frame-support/experimental", "frame-system/experimental" ] runtime = [ "frame-executive", "frame-system-rpc-runtime-api", diff --git a/substrate/frame/alliance/Cargo.toml b/substrate/frame/alliance/Cargo.toml index 39f5a6ceb75..d7d7352975a 100644 --- a/substrate/frame/alliance/Cargo.toml +++ b/substrate/frame/alliance/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "The Alliance pallet provides a collective for standard-setting industry collaboration." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -22,27 +19,27 @@ log = { version = "0.4.14", default-features = false } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -sp-std = { path = "../../primitives/std", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } +sp-std = { path = "../../primitives/std", default-features = false} +sp-core = { path = "../../primitives/core", default-features = false} sp-core-hashing = { path = "../../primitives/core/hashing", default-features = false, optional = true } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } +sp-io = { path = "../../primitives/io", 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 } +frame-support = { path = "../support", default-features = false} +frame-system = { path = "../system", default-features = false} pallet-identity = { path = "../identity", default-features = false } pallet-collective = { path = "../collective", default-features = false, optional = true } [dev-dependencies] array-bytes = "6.1" -sp-core-hashing = { path = "../../primitives/core/hashing", default-features = false } +sp-core-hashing = { path = "../../primitives/core/hashing", default-features = false} pallet-balances = { path = "../balances" } pallet-collective = { path = "../collective" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/asset-conversion/Cargo.toml b/substrate/frame/asset-conversion/Cargo.toml index 0c7b06abf55..de898d4ccde 100644 --- a/substrate/frame/asset-conversion/Cargo.toml +++ b/substrate/frame/asset-conversion/Cargo.toml @@ -9,32 +9,29 @@ repository.workspace = true description = "FRAME asset conversion pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", 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.10.0", 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 } +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} [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"] } +primitive-types = { version = "0.12.0", default-features = false, features = ["codec", "scale-info", "num-traits"] } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/asset-conversion/src/mock.rs b/substrate/frame/asset-conversion/src/mock.rs index c84263b0796..4eee701f193 100644 --- a/substrate/frame/asset-conversion/src/mock.rs +++ b/substrate/frame/asset-conversion/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_asset_conversion; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, instances::{Instance1, Instance2}, ord_parameter_types, parameter_types, traits::{AsEnsureOriginWithArg, ConstU128, ConstU32, ConstU64}, @@ -48,7 +48,6 @@ construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/asset-rate/Cargo.toml b/substrate/frame/asset-rate/Cargo.toml index 835a15e8c55..734bc5ef43f 100644 --- a/substrate/frame/asset-rate/Cargo.toml +++ b/substrate/frame/asset-rate/Cargo.toml @@ -8,9 +8,6 @@ edition.workspace = true license = "Apache-2.0" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,20 +16,20 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = "derive", ] } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } sp-io = { path = "../../primitives/io" } -sp-core = { path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/asset-rate/src/mock.rs b/substrate/frame/asset-rate/src/mock.rs index 041f3740952..9ca0f0f3cc3 100644 --- a/substrate/frame/asset-rate/src/mock.rs +++ b/substrate/frame/asset-rate/src/mock.rs @@ -18,10 +18,7 @@ //! The crate's mock. use crate as pallet_asset_rate; -use frame_support::{ - derive_impl, - traits::{ConstU16, ConstU64}, -}; +use frame_support::traits::{ConstU16, ConstU64}; use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -39,7 +36,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/assets/Cargo.toml b/substrate/frame/assets/Cargo.toml index 7b0af2421ea..a48964f1366 100644 --- a/substrate/frame/assets/Cargo.toml +++ b/substrate/frame/assets/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME asset management pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,15 +16,15 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -sp-std = { path = "../../primitives/std", default-features = false } +sp-std = { path = "../../primitives/std", default-features = false} # Needed for various traits. In our case, `OnFinalize`. -sp-runtime = { path = "../../primitives/runtime", default-features = false } +sp-runtime = { path = "../../primitives/runtime", default-features = false} # Needed for type-safe access to storage DB. -frame-support = { path = "../support", default-features = false } +frame-support = { path = "../support", default-features = false} # `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-system = { path = "../system", default-features = false} frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -sp-core = { path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false} [dev-dependencies] sp-std = { path = "../../primitives/std" } @@ -35,7 +32,7 @@ sp-io = { path = "../../primitives/io" } pallet-balances = { path = "../balances" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/assets/src/benchmarking.rs b/substrate/frame/assets/src/benchmarking.rs index f8495a1c8f2..c9b0825542d 100644 --- a/substrate/frame/assets/src/benchmarking.rs +++ b/substrate/frame/assets/src/benchmarking.rs @@ -54,7 +54,7 @@ fn create_default_asset, I: 'static>( (asset_id, caller, caller_lookup) } -pub fn create_default_minted_asset, I: 'static>( +fn create_default_minted_asset, I: 'static>( is_sufficient: bool, amount: T::Balance, ) -> (T::AssetIdParameter, T::AccountId, AccountIdLookupOf) { diff --git a/substrate/frame/assets/src/lib.rs b/substrate/frame/assets/src/lib.rs index 13aee138ad3..79e4fe30018 100644 --- a/substrate/frame/assets/src/lib.rs +++ b/substrate/frame/assets/src/lib.rs @@ -141,7 +141,7 @@ #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "runtime-benchmarks")] -pub mod benchmarking; +mod benchmarking; pub mod migration; #[cfg(test)] pub mod mock; diff --git a/substrate/frame/assets/src/mock.rs b/substrate/frame/assets/src/mock.rs index a4d85b64922..2c2203bcdad 100644 --- a/substrate/frame/assets/src/mock.rs +++ b/substrate/frame/assets/src/mock.rs @@ -22,7 +22,7 @@ use crate as pallet_assets; use codec::Encode; use frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, parameter_types, traits::{AsEnsureOriginWithArg, ConstU32, ConstU64}, }; use sp_core::H256; @@ -46,7 +46,6 @@ construct_runtime!( type AccountId = u64; type AssetId = u32; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/atomic-swap/Cargo.toml b/substrate/frame/atomic-swap/Cargo.toml index d34779d8bc0..8315330d7fe 100644 --- a/substrate/frame/atomic-swap/Cargo.toml +++ b/substrate/frame/atomic-swap/Cargo.toml @@ -9,27 +9,24 @@ repository.workspace = true description = "FRAME atomic swap pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/atomic-swap/src/tests.rs b/substrate/frame/atomic-swap/src/tests.rs index 7e2f22b1836..92eb9a04458 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::traits::{ConstU32, ConstU64}; use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -41,7 +38,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/aura/Cargo.toml b/substrate/frame/aura/Cargo.toml index e2419933a20..bfe9193e9b5 100644 --- a/substrate/frame/aura/Cargo.toml +++ b/substrate/frame/aura/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME AURA consensus pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,20 +16,20 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] -sp-core = { path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false} sp-io = { path = "../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/aura/src/mock.rs b/substrate/frame/aura/src/mock.rs index 14b87089ce3..39b798c2f68 100644 --- a/substrate/frame/aura/src/mock.rs +++ b/substrate/frame/aura/src/mock.rs @@ -21,7 +21,7 @@ use crate as pallet_aura; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64, DisabledValidators}, }; use sp_consensus_aura::{ed25519::AuthorityId, AuthorityIndex}; @@ -41,7 +41,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/authority-discovery/Cargo.toml b/substrate/frame/authority-discovery/Cargo.toml index a1819965744..eb30ed3007c 100644 --- a/substrate/frame/authority-discovery/Cargo.toml +++ b/substrate/frame/authority-discovery/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet for authority discovery" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,22 +17,22 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = "derive", ] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", 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 = [ "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 } +]} +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} [dev-dependencies] sp-core = { path = "../../primitives/core" } sp-io = { path = "../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/authority-discovery/src/lib.rs b/substrate/frame/authority-discovery/src/lib.rs index 3044b41e31d..87b743ae196 100644 --- a/substrate/frame/authority-discovery/src/lib.rs +++ b/substrate/frame/authority-discovery/src/lib.rs @@ -169,7 +169,7 @@ mod tests { use super::*; use crate as pallet_authority_discovery; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64}, }; use sp_application_crypto::Pair; @@ -225,7 +225,6 @@ mod tests { pub const Offset: BlockNumber = 0; } - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/authorship/Cargo.toml b/substrate/frame/authorship/Cargo.toml index 41d4cf13972..bc1e6221a45 100644 --- a/substrate/frame/authorship/Cargo.toml +++ b/substrate/frame/authorship/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,17 +18,17 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = ] } impl-trait-for-tuples = "0.2.2" scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] sp-core = { path = "../../primitives/core" } sp-io = { path = "../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/babe/Cargo.toml b/substrate/frame/babe/Cargo.toml index 639b9544b0c..2dc414a784d 100644 --- a/substrate/frame/babe/Cargo.toml +++ b/substrate/frame/babe/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Consensus extension module for BABE consensus. Collects on-chain randomness from VRF outputs and manages epoch transitions." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,20 +16,20 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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-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-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-std = { path = "../../primitives/std", default-features = false} [dev-dependencies] frame-election-provider-support = { path = "../election-provider-support" } @@ -43,7 +40,7 @@ pallet-staking-reward-curve = { path = "../staking/reward-curve" } sp-core = { path = "../../primitives/core" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/babe/src/lib.rs b/substrate/frame/babe/src/lib.rs index a6e44390dbc..57e1dbb6b53 100644 --- a/substrate/frame/babe/src/lib.rs +++ b/substrate/frame/babe/src/lib.rs @@ -384,11 +384,7 @@ pub mod pallet { }); public - .make_bytes( - RANDOMNESS_VRF_CONTEXT, - &transcript, - &signature.pre_output, - ) + .make_bytes(RANDOMNESS_VRF_CONTEXT, &transcript, &signature.output) .ok() }); diff --git a/substrate/frame/babe/src/mock.rs b/substrate/frame/babe/src/mock.rs index 72abbc805db..0003c6f9f11 100644 --- a/substrate/frame/babe/src/mock.rs +++ b/substrate/frame/babe/src/mock.rs @@ -183,7 +183,6 @@ impl pallet_staking::Config for Test { 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; diff --git a/substrate/frame/bags-list/Cargo.toml b/substrate/frame/bags-list/Cargo.toml index 198af21be81..cb07ef94ff5 100644 --- a/substrate/frame/bags-list/Cargo.toml +++ b/substrate/frame/bags-list/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME pallet bags list" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -53,7 +50,7 @@ frame-election-provider-support = { path = "../election-provider-support" } frame-benchmarking = { path = "../benchmarking" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/bags-list/fuzzer/Cargo.toml b/substrate/frame/bags-list/fuzzer/Cargo.toml index 20760141b23..9944c886554 100644 --- a/substrate/frame/bags-list/fuzzer/Cargo.toml +++ b/substrate/frame/bags-list/fuzzer/Cargo.toml @@ -9,14 +9,11 @@ repository.workspace = true description = "Fuzzer for FRAME pallet bags list" publish = false -[lints] -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"] } +rand = { version = "0.8", features = ["std", "small_rng"] } +frame-election-provider-support = { path = "../../election-provider-support", features = ["fuzz"]} +pallet-bags-list = { path = "..", features = ["fuzz"]} [[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 fb61a986778..b7408e08d55 100644 --- a/substrate/frame/bags-list/remote-tests/Cargo.toml +++ b/substrate/frame/bags-list/remote-tests/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet bags list remote test" publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -31,7 +28,7 @@ sp-runtime = { path = "../../../primitives/runtime" } sp-std = { path = "../../../primitives/std" } # utils -remote-externalities = { package = "frame-remote-externalities", path = "../../../utils/frame/remote-externalities" } +remote-externalities = { package = "frame-remote-externalities" , path = "../../../utils/frame/remote-externalities" } # others log = "0.4.17" diff --git a/substrate/frame/balances/Cargo.toml b/substrate/frame/balances/Cargo.toml index 23fe6e58322..b91257df7b2 100644 --- a/substrate/frame/balances/Cargo.toml +++ b/substrate/frame/balances/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet to manage balances" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,11 +16,11 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-transaction-payment = { path = "../transaction-payment" } @@ -32,7 +29,7 @@ sp-io = { path = "../../primitives/io" } paste = "1.0.12" [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/balances/src/lib.rs b/substrate/frame/balances/src/lib.rs index 843bc351494..d518f933df8 100644 --- a/substrate/frame/balances/src/lib.rs +++ b/substrate/frame/balances/src/lib.rs @@ -49,7 +49,8 @@ //! - **Total Issuance:** The total number of units in existence in a system. //! //! - **Reaping an account:** The act of removing an account by resetting its nonce. Happens after -//! its total balance has become zero (or, strictly speaking, less than the Existential Deposit). +//! its +//! total balance has become zero (or, strictly speaking, less than the Existential Deposit). //! //! - **Free Balance:** The portion of a balance that is not reserved. The free balance is the only //! balance that matters for most operations. @@ -58,23 +59,24 @@ //! Reserved balance can still be slashed, but only after all the free balance has been slashed. //! //! - **Imbalance:** A condition when some funds were credited or debited without equal and opposite -//! accounting (i.e. a difference between total issuance and account balances). Functions that -//! result in an imbalance will return an object of the `Imbalance` trait that can be managed within -//! your runtime logic. (If an imbalance is simply dropped, it should automatically maintain any -//! book-keeping such as total issuance.) +//! accounting +//! (i.e. a difference between total issuance and account balances). Functions that result in an +//! imbalance will return an object of the `Imbalance` trait that can be managed within your runtime +//! logic. (If an imbalance is simply dropped, it should automatically maintain any book-keeping +//! such as total issuance.) //! //! - **Lock:** A freeze on a specified amount of an account's free balance until a specified block -//! number. Multiple locks always operate over the same funds, so they "overlay" rather than -//! "stack". +//! number. Multiple +//! locks always operate over the same funds, so they "overlay" rather than "stack". //! //! ### Implementations //! //! The Balances pallet provides implementations for the following traits. If these traits provide //! the functionality that you need, then you can avoid coupling with the Balances pallet. //! -//! - [`Currency`]: Functions for dealing with a +//! - [`Currency`](frame_support::traits::Currency): Functions for dealing with a //! fungible assets system. -//! - [`ReservableCurrency`] +//! - [`ReservableCurrency`](frame_support::traits::ReservableCurrency): //! - [`NamedReservableCurrency`](frame_support::traits::NamedReservableCurrency): //! Functions for dealing with assets that can be reserved from an account. //! - [`LockableCurrency`](frame_support::traits::LockableCurrency): Functions for @@ -103,7 +105,7 @@ //! ``` //! use frame_support::traits::Currency; //! # pub trait Config: frame_system::Config { -//! # type Currency: Currency; +//! # type Currency: Currency; //! # } //! //! pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; @@ -118,26 +120,26 @@ //! use frame_support::traits::{WithdrawReasons, LockableCurrency}; //! use sp_runtime::traits::Bounded; //! pub trait Config: frame_system::Config { -//! type Currency: LockableCurrency>; +//! type Currency: LockableCurrency>; //! } //! # struct StakingLedger { -//! # stash: ::AccountId, -//! # total: <::Currency as frame_support::traits::Currency<::AccountId>>::Balance, -//! # phantom: std::marker::PhantomData, +//! # stash: ::AccountId, +//! # total: <::Currency as frame_support::traits::Currency<::AccountId>>::Balance, +//! # phantom: std::marker::PhantomData, //! # } //! # const STAKING_ID: [u8; 8] = *b"staking "; //! //! fn update_ledger( -//! controller: &T::AccountId, -//! ledger: &StakingLedger +//! controller: &T::AccountId, +//! ledger: &StakingLedger //! ) { -//! T::Currency::set_lock( -//! STAKING_ID, -//! &ledger.stash, -//! ledger.total, -//! WithdrawReasons::all() -//! ); -//! // >::insert(controller, ledger); // Commented out as we don't have access to Staking's storage here. +//! T::Currency::set_lock( +//! STAKING_ID, +//! &ledger.stash, +//! ledger.total, +//! WithdrawReasons::all() +//! ); +//! // >::insert(controller, ledger); // Commented out as we don't have access to Staking's storage here. //! } //! # fn main() {} //! ``` diff --git a/substrate/frame/balances/src/tests/mod.rs b/substrate/frame/balances/src/tests/mod.rs index e5c7038547e..a4c8510c654 100644 --- a/substrate/frame/balances/src/tests/mod.rs +++ b/substrate/frame/balances/src/tests/mod.rs @@ -22,7 +22,7 @@ use crate::{self as pallet_balances, AccountData, Config, CreditOf, Error, Pallet}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ - assert_err, assert_noop, assert_ok, assert_storage_noop, derive_impl, + assert_err, assert_noop, assert_ok, assert_storage_noop, dispatch::{DispatchInfo, GetDispatchInfo}, parameter_types, traits::{ @@ -90,8 +90,6 @@ parameter_types! { ); pub static ExistentialDeposit: u64 = 1; } - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = BlockWeights; diff --git a/substrate/frame/beefy-mmr/Cargo.toml b/substrate/frame/beefy-mmr/Cargo.toml index 7f647305456..fe0321bea51 100644 --- a/substrate/frame/beefy-mmr/Cargo.toml +++ b/substrate/frame/beefy-mmr/Cargo.toml @@ -8,35 +8,32 @@ description = "BEEFY + MMR runtime utilities" repository.workspace = true homepage = "https://substrate.io" -[lints] -workspace = true - [dependencies] array-bytes = { version = "6.1", optional = true } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", optional = 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 } +serde = { version = "1.0.188", optional = 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} [dev-dependencies] array-bytes = "6.1" sp-staking = { path = "../../primitives/staking" } [features] -default = ["std"] +default = [ "std" ] std = [ "array-bytes", "binary-merkle-tree/std", diff --git a/substrate/frame/beefy/Cargo.toml b/substrate/frame/beefy/Cargo.toml index 185e5487414..1da09321342 100644 --- a/substrate/frame/beefy/Cargo.toml +++ b/substrate/frame/beefy/Cargo.toml @@ -8,23 +8,20 @@ repository.workspace = true description = "BEEFY FRAME pallet" homepage = "https://substrate.io" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive", "serde"] } -serde = { version = "1.0.193", 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 } +serde = { version = "1.0.188", 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-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-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-std = { path = "../../primitives/std", default-features = false} [dev-dependencies] frame-election-provider-support = { path = "../election-provider-support" } @@ -36,10 +33,10 @@ 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 } +sp-state-machine = { path = "../../primitives/state-machine", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-election-provider-support/std", diff --git a/substrate/frame/beefy/src/mock.rs b/substrate/frame/beefy/src/mock.rs index 8dc30614c33..53d523cf724 100644 --- a/substrate/frame/beefy/src/mock.rs +++ b/substrate/frame/beefy/src/mock.rs @@ -201,7 +201,6 @@ impl pallet_staking::Config for Test { 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; diff --git a/substrate/frame/benchmarking/Cargo.toml b/substrate/frame/benchmarking/Cargo.toml index 980f70a5774..79f35f62625 100644 --- a/substrate/frame/benchmarking/Cargo.toml +++ b/substrate/frame/benchmarking/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Macro for benchmarking a FRAME runtime." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,18 +18,18 @@ linregress = { version = "0.5.1", optional = true } log = { version = "0.4.17", default-features = false } paste = "1.0" scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", optional = 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 } +serde = { version = "1.0.188", optional = 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" [dev-dependencies] @@ -41,7 +38,7 @@ rusty-fork = { version = "0.3.0", default-features = false } sp-keystore = { path = "../../primitives/keystore" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support-procedural/std", diff --git a/substrate/frame/benchmarking/pov/Cargo.toml b/substrate/frame/benchmarking/pov/Cargo.toml index 7c36b2f8eec..0d935063e9e 100644 --- a/substrate/frame/benchmarking/pov/Cargo.toml +++ b/substrate/frame/benchmarking/pov/Cargo.toml @@ -8,24 +8,21 @@ homepage = "https://substrate.io" repository.workspace = true description = "Pallet for testing FRAME PoV benchmarking" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking/std", diff --git a/substrate/frame/benchmarking/pov/src/benchmarking.rs b/substrate/frame/benchmarking/pov/src/benchmarking.rs index a24b772ade0..473947b171a 100644 --- a/substrate/frame/benchmarking/pov/src/benchmarking.rs +++ b/substrate/frame/benchmarking/pov/src/benchmarking.rs @@ -339,7 +339,6 @@ frame_benchmarking::benchmarks! { #[cfg(test)] mod mock { - use frame_support::derive_impl; use sp_runtime::{testing::H256, BuildStorage}; type AccountId = u64; @@ -355,7 +354,6 @@ mod mock { } ); - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/benchmarking/pov/src/tests.rs b/substrate/frame/benchmarking/pov/src/tests.rs index dda29c071de..f09e37a5288 100644 --- a/substrate/frame/benchmarking/pov/src/tests.rs +++ b/substrate/frame/benchmarking/pov/src/tests.rs @@ -162,7 +162,6 @@ fn noop_is_free() { } mod mock { - use frame_support::derive_impl; use sp_runtime::testing::H256; type Block = frame_system::mocking::MockBlock; @@ -175,7 +174,6 @@ mod mock { } ); - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/benchmarking/src/baseline.rs b/substrate/frame/benchmarking/src/baseline.rs index 6451284e012..6cd23ebe028 100644 --- a/substrate/frame/benchmarking/src/baseline.rs +++ b/substrate/frame/benchmarking/src/baseline.rs @@ -110,7 +110,6 @@ benchmarks! { #[cfg(test)] pub mod mock { - use frame_support::derive_impl; use sp_runtime::{testing::H256, BuildStorage}; type AccountId = u64; @@ -125,7 +124,6 @@ pub mod mock { } ); - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/benchmarking/src/tests.rs b/substrate/frame/benchmarking/src/tests.rs index 7d6cfaad609..e5bacbdb236 100644 --- a/substrate/frame/benchmarking/src/tests.rs +++ b/substrate/frame/benchmarking/src/tests.rs @@ -19,7 +19,7 @@ #![cfg(test)] -use frame_support::{derive_impl, parameter_types, traits::ConstU32}; +use frame_support::{parameter_types, traits::ConstU32}; use sp_runtime::{ testing::H256, traits::{BlakeTwo256, IdentityLookup}, @@ -75,7 +75,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/benchmarking/src/tests_instance.rs b/substrate/frame/benchmarking/src/tests_instance.rs index 55010840896..f2c721c8114 100644 --- a/substrate/frame/benchmarking/src/tests_instance.rs +++ b/substrate/frame/benchmarking/src/tests_instance.rs @@ -19,7 +19,7 @@ #![cfg(test)] -use frame_support::{derive_impl, traits::ConstU32}; +use frame_support::traits::ConstU32; use sp_runtime::{ testing::H256, traits::{BlakeTwo256, IdentityLookup}, @@ -85,7 +85,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/bounties/Cargo.toml b/substrate/frame/bounties/Cargo.toml index 16da862d488..7da21140542 100644 --- a/substrate/frame/bounties/Cargo.toml +++ b/substrate/frame/bounties/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet to manage bounties" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,20 +18,20 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = ] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/bounties/src/migrations/v4.rs b/substrate/frame/bounties/src/migrations/v4.rs index 4e6ba934481..936bac11700 100644 --- a/substrate/frame/bounties/src/migrations/v4.rs +++ b/substrate/frame/bounties/src/migrations/v4.rs @@ -110,7 +110,7 @@ pub fn migrate< } /// Some checks prior to migration. This can be linked to -/// `frame_support::traits::OnRuntimeUpgrade::pre_upgrade` for further testing. +/// [`frame_support::traits::OnRuntimeUpgrade::pre_upgrade`] for further testing. /// /// Panics if anything goes wrong. pub fn pre_migration>( @@ -164,7 +164,7 @@ pub fn pre_migration>( diff --git a/substrate/frame/bounties/src/tests.rs b/substrate/frame/bounties/src/tests.rs index 22e608cce63..233e41b474c 100644 --- a/substrate/frame/bounties/src/tests.rs +++ b/substrate/frame/bounties/src/tests.rs @@ -23,7 +23,7 @@ use super::*; use crate as pallet_bounties; use frame_support::{ - assert_noop, assert_ok, derive_impl, parameter_types, + assert_noop, assert_ok, parameter_types, traits::{ tokens::{PayFromAccount, UnityAssetBalanceConversion}, ConstU32, ConstU64, OnInitialize, @@ -59,7 +59,6 @@ parameter_types! { type Balance = u64; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/broker/Cargo.toml b/substrate/frame/broker/Cargo.toml index 77757c30463..142d0a0e35e 100644 --- a/substrate/frame/broker/Cargo.toml +++ b/substrate/frame/broker/Cargo.toml @@ -8,29 +8,26 @@ edition.workspace = true license = "Apache-2.0" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } bitvec = { version = "1.0.0", 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 } +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} [dev-dependencies] sp-io = { path = "../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "bitvec/std", diff --git a/substrate/frame/broker/src/lib.rs b/substrate/frame/broker/src/lib.rs index 42895512ec0..4abd041f5f3 100644 --- a/substrate/frame/broker/src/lib.rs +++ b/substrate/frame/broker/src/lib.rs @@ -716,51 +716,55 @@ pub mod pallet { /// Drop an expired Region from the chain. /// - /// - `origin`: Can be any kind of origin. + /// - `origin`: Must be a Signed origin. /// - `region_id`: The Region which has expired. #[pallet::call_index(14)] pub fn drop_region( - _origin: OriginFor, + origin: OriginFor, region_id: RegionId, ) -> DispatchResultWithPostInfo { + let _ = ensure_signed(origin)?; Self::do_drop_region(region_id)?; Ok(Pays::No.into()) } /// Drop an expired Instantaneous Pool Contribution record from the chain. /// - /// - `origin`: Can be any kind of origin. + /// - `origin`: Must be a Signed origin. /// - `region_id`: The Region identifying the Pool Contribution which has expired. #[pallet::call_index(15)] pub fn drop_contribution( - _origin: OriginFor, + origin: OriginFor, region_id: RegionId, ) -> DispatchResultWithPostInfo { + let _ = ensure_signed(origin)?; Self::do_drop_contribution(region_id)?; Ok(Pays::No.into()) } /// Drop an expired Instantaneous Pool History record from the chain. /// - /// - `origin`: Can be any kind of origin. + /// - `origin`: Must be a Signed origin. /// - `region_id`: The time of the Pool History record which has expired. #[pallet::call_index(16)] - pub fn drop_history(_origin: OriginFor, when: Timeslice) -> DispatchResultWithPostInfo { + pub fn drop_history(origin: OriginFor, when: Timeslice) -> DispatchResultWithPostInfo { + let _ = ensure_signed(origin)?; Self::do_drop_history(when)?; Ok(Pays::No.into()) } /// Drop an expired Allowed Renewal record from the chain. /// - /// - `origin`: Can be any kind of origin. + /// - `origin`: Must be a Signed origin of the account which owns the Region `region_id`. /// - `core`: The core to which the expired renewal refers. /// - `when`: The timeslice to which the expired renewal refers. This must have passed. #[pallet::call_index(17)] pub fn drop_renewal( - _origin: OriginFor, + origin: OriginFor, core: CoreIndex, when: Timeslice, ) -> DispatchResultWithPostInfo { + let _ = ensure_signed(origin)?; Self::do_drop_renewal(core, when)?; Ok(Pays::No.into()) } diff --git a/substrate/frame/broker/src/mock.rs b/substrate/frame/broker/src/mock.rs index d8bea484909..cab6b7389c0 100644 --- a/substrate/frame/broker/src/mock.rs +++ b/substrate/frame/broker/src/mock.rs @@ -19,7 +19,7 @@ use crate::{test_fungibles::TestFungibles, *}; use frame_support::{ - assert_ok, derive_impl, ensure, ord_parameter_types, parameter_types, + assert_ok, ensure, ord_parameter_types, parameter_types, traits::{ fungible::{Balanced, Credit, Inspect, ItemOf, Mutate}, nonfungible::Inspect as NftInspect, @@ -29,8 +29,11 @@ use frame_support::{ }; use frame_system::{EnsureRoot, EnsureSignedBy}; use sp_arithmetic::Perbill; -use sp_core::{ConstU32, ConstU64}; -use sp_runtime::{traits::Identity, BuildStorage, Saturating}; +use sp_core::{ConstU16, ConstU32, ConstU64, H256}; +use sp_runtime::{ + traits::{BlakeTwo256, Identity, IdentityLookup}, + BuildStorage, Saturating, +}; use sp_std::collections::btree_map::BTreeMap; type Block = frame_system::mocking::MockBlock; @@ -44,9 +47,30 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Nonce = u64; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup; type Block = Block; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = ConstU64<250>; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = ConstU16<42>; + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; } #[derive(Debug, Clone, Eq, PartialEq)] diff --git a/substrate/frame/child-bounties/Cargo.toml b/substrate/frame/child-bounties/Cargo.toml index 6c1c362dc56..ac29bc4997b 100644 --- a/substrate/frame/child-bounties/Cargo.toml +++ b/substrate/frame/child-bounties/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet to manage child bounties" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,21 +18,21 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = ] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/child-bounties/src/tests.rs b/substrate/frame/child-bounties/src/tests.rs index 7de45c73127..46f8fa65dd3 100644 --- a/substrate/frame/child-bounties/src/tests.rs +++ b/substrate/frame/child-bounties/src/tests.rs @@ -23,7 +23,7 @@ use super::*; use crate as pallet_child_bounties; use frame_support::{ - assert_noop, assert_ok, derive_impl, parameter_types, + assert_noop, assert_ok, parameter_types, traits::{ tokens::{PayFromAccount, UnityAssetBalanceConversion}, ConstU32, ConstU64, OnInitialize, @@ -62,7 +62,6 @@ parameter_types! { type Balance = u64; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/collective/Cargo.toml b/substrate/frame/collective/Cargo.toml index fb0bace740c..7f5e305e4f5 100644 --- a/substrate/frame/collective/Cargo.toml +++ b/substrate/frame/collective/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Collective system: Members of a set of account IDs can make their collective feelings known through dispatched calls from one of two specialized origins." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,16 +16,16 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/collective/src/migrations/v4.rs b/substrate/frame/collective/src/migrations/v4.rs index 300dff23d8e..b3326b4251c 100644 --- a/substrate/frame/collective/src/migrations/v4.rs +++ b/substrate/frame/collective/src/migrations/v4.rs @@ -76,7 +76,7 @@ pub fn migrate>(old_pallet_name: N) { @@ -104,7 +104,7 @@ pub fn pre_migrate>(old_p } /// Some checks for after migration. This can be linked to -/// `frame_support::traits::OnRuntimeUpgrade::post_upgrade` for further testing. +/// [`frame_support::traits::OnRuntimeUpgrade::post_upgrade`] for further testing. /// /// Panics if anything goes wrong. pub fn post_migrate>(old_pallet_name: N) { diff --git a/substrate/frame/collective/src/tests.rs b/substrate/frame/collective/src/tests.rs index 4095552b1de..35091b1f7b2 100644 --- a/substrate/frame/collective/src/tests.rs +++ b/substrate/frame/collective/src/tests.rs @@ -18,7 +18,7 @@ use super::{Event as CollectiveEvent, *}; use crate as pallet_collective; use frame_support::{ - assert_noop, assert_ok, derive_impl, + assert_noop, assert_ok, dispatch::Pays, parameter_types, traits::{ConstU32, ConstU64, StorageVersion}, @@ -90,8 +90,6 @@ parameter_types! { frame_system::limits::BlockWeights::simple_max(Weight::MAX); pub static MaxProposalWeight: Weight = default_max_proposal_weight(); } - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = BlockWeights; diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 4c6ca41ed56..239b0865e0f 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -9,10 +9,7 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME pallet for WASM contracts" readme = "README.md" -include = ["CHANGELOG.md", "README.md", "benchmarks/**", "build.rs", "src/**/*"] - -[lints] -workspace = true +include = ["src/**/*", "benchmarks/**", "build.rs", "README.md", "CHANGELOG.md"] [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -40,19 +37,19 @@ rand_pcg = { version = "0.3", optional = 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" } +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-primitives = { path = "primitives", default-features = false} 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 } +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} -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 = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false} +xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder", default-features = false} [dev-dependencies] array-bytes = "6.1" @@ -63,7 +60,7 @@ wat = "1" pallet-contracts-fixtures = { path = "./fixtures" } # Polkadot Dependencies -xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder" } +xcm-builder = {package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder"} # Substrate Dependencies pallet-balances = { path = "../balances" } @@ -77,7 +74,7 @@ sp-keystore = { path = "../../primitives/keystore" } sp-tracing = { path = "../../primitives/tracing" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "environmental/std", @@ -86,12 +83,14 @@ std = [ "frame-system/std", "log/std", "pallet-balances?/std", + "pallet-contracts-fixtures/std", + "pallet-contracts-primitives/std", "pallet-contracts-proc-macro/full", "pallet-insecure-randomness-collective-flip/std", "pallet-proxy/std", "pallet-timestamp/std", "pallet-utility/std", - "rand?/std", + "rand/std", "scale-info/std", "serde", "sp-api/std", @@ -100,7 +99,7 @@ std = [ "sp-keystore/std", "sp-runtime/std", "sp-std/std", - "wasm-instrument?/std", + "wasm-instrument/std", "wasmi/std", "xcm-builder/std", "xcm/std", diff --git a/substrate/frame/contracts/build.rs b/substrate/frame/contracts/build.rs index 83d5d368d4b..42bc45d563d 100644 --- a/substrate/frame/contracts/build.rs +++ b/substrate/frame/contracts/build.rs @@ -68,5 +68,6 @@ fn main() -> Result<(), Box> { version - 1, )?; + println!("cargo:rerun-if-changed=src/migration"); Ok(()) } diff --git a/substrate/frame/contracts/fixtures/Cargo.toml b/substrate/frame/contracts/fixtures/Cargo.toml index 97606479f25..b44f36f2a5f 100644 --- a/substrate/frame/contracts/fixtures/Cargo.toml +++ b/substrate/frame/contracts/fixtures/Cargo.toml @@ -7,19 +7,12 @@ edition.workspace = true license.workspace = true description = "Fixtures for testing contracts pallet." -[lints] -workspace = true - [dependencies] wat = "1" -frame-system = { path = "../../system" } -sp-runtime = { path = "../../../primitives/runtime" } -anyhow = "1.0.0" +frame-system = { path = "../../system", default-features = false} +sp-runtime = { path = "../../../primitives/runtime", default-features = false} + +[features] +default = [ "std" ] +std = [ "frame-system/std", "sp-runtime/std" ] -[build-dependencies] -parity-wasm = "0.45.0" -tempfile = "3.8.1" -toml = "0.8.2" -twox-hash = "1.6.3" -anyhow = "1.0.0" -cfg-if = { version = "1.0", default-features = false } diff --git a/substrate/frame/contracts/fixtures/build.rs b/substrate/frame/contracts/fixtures/build.rs deleted file mode 100644 index 49deb94a7fa..00000000000 --- a/substrate/frame/contracts/fixtures/build.rs +++ /dev/null @@ -1,277 +0,0 @@ -// 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. - -//! Compile contracts to wasm and RISC-V binaries. -use anyhow::Result; -use parity_wasm::elements::{deserialize_file, serialize_to_file, Internal}; -use std::{ - env, fs, - hash::Hasher, - path::{Path, PathBuf}, - process::Command, -}; -use twox_hash::XxHash32; - -/// Read the file at `path` and return its hash as a hex string. -fn file_hash(path: &Path) -> String { - let data = fs::read(path).expect("file exists; qed"); - let mut hasher = XxHash32::default(); - hasher.write(&data); - hasher.write(include_bytes!("build.rs")); - let hash = hasher.finish(); - format!("{:x}", hash) -} - -/// A contract entry. -struct Entry { - /// The path to the contract source file. - path: PathBuf, - /// The hash of the contract source file. - hash: String, -} - -impl Entry { - /// Create a new contract entry from the given path. - fn new(path: PathBuf) -> Self { - let hash = file_hash(&path); - Self { path, hash } - } - - /// Return the path to the contract source file. - fn path(&self) -> &str { - self.path.to_str().expect("path is valid unicode; qed") - } - - /// Return the name of the contract. - fn name(&self) -> &str { - self.path - .file_stem() - .expect("file exits; qed") - .to_str() - .expect("name is valid unicode; qed") - } - - /// Return the name of the output wasm file. - fn out_wasm_filename(&self) -> String { - format!("{}.wasm", self.name()) - } -} - -/// Collect all contract entries from the given source directory. -/// Contracts that have already been compiled are filtered out. -fn collect_entries(contracts_dir: &Path, out_dir: &Path) -> Vec { - fs::read_dir(&contracts_dir) - .expect("src dir exists; qed") - .filter_map(|file| { - let path = file.expect("file exists; qed").path(); - if path.extension().map_or(true, |ext| ext != "rs") { - return None; - } - - let entry = Entry::new(path); - if out_dir.join(&entry.hash).exists() { - None - } else { - Some(entry) - } - }) - .collect::>() -} - -/// Create a `Cargo.toml` to compile the given contract entries. -fn create_cargo_toml<'a>( - fixtures_dir: &Path, - entries: impl Iterator, - output_dir: &Path, -) -> Result<()> { - let uapi_path = fixtures_dir.join("../uapi").canonicalize()?; - let common_path = fixtures_dir.join("./contracts/common").canonicalize()?; - let mut cargo_toml: toml::Value = toml::from_str(&format!( - " -[package] -name = 'contracts' -version = '0.1.0' -edition = '2021' - -# Binary targets are injected below. -[[bin]] - -[dependencies] -uapi = {{ package = 'pallet-contracts-uapi', default-features = false, path = {uapi_path:?}}} -common = {{ package = 'pallet-contracts-fixtures-common', path = {common_path:?}}} - -[profile.release] -opt-level = 3 -lto = true -codegen-units = 1 -" - ))?; - - let binaries = entries - .map(|entry| { - let name = entry.name(); - let path = entry.path(); - toml::Value::Table(toml::toml! { - name = name - path = path - }) - }) - .collect::>(); - - cargo_toml["bin"] = toml::Value::Array(binaries); - let cargo_toml = toml::to_string_pretty(&cargo_toml)?; - fs::write(output_dir.join("Cargo.toml"), cargo_toml).map_err(Into::into) -} - -/// Invoke `cargo fmt` to check that fixtures files are formatted. -fn invoke_cargo_fmt<'a>( - config_path: &Path, - files: impl Iterator, - contract_dir: &Path, -) -> Result<()> { - // If rustfmt is not installed, skip the check. - if !Command::new("rustup") - .args(&["run", "nightly", "rustfmt", "--version"]) - .output() - .map_or(false, |o| o.status.success()) - { - return Ok(()) - } - - let fmt_res = Command::new("rustup") - .args(&["run", "nightly", "rustfmt", "--check", "--config-path"]) - .arg(config_path) - .args(files) - .output() - .expect("failed to execute process"); - - if fmt_res.status.success() { - return Ok(()) - } - - let stdout = String::from_utf8_lossy(&fmt_res.stdout); - let stderr = String::from_utf8_lossy(&fmt_res.stderr); - eprintln!("{}\n{}", stdout, stderr); - eprintln!( - "Fixtures files are not formatted.\n - Please run `rustup run nightly rustfmt --config-path {} {}/*.rs`", - config_path.display(), - contract_dir.display() - ); - - anyhow::bail!("Fixtures files are not formatted") -} - -/// Invoke `cargo build` to compile the contracts. -fn invoke_build(current_dir: &Path) -> Result<()> { - let encoded_rustflags = [ - "-Clink-arg=-zstack-size=65536", - "-Clink-arg=--import-memory", - "-Clinker-plugin-lto", - "-Ctarget-cpu=mvp", - "-Dwarnings", - ] - .join("\x1f"); - - let build_res = Command::new(env::var("CARGO")?) - .current_dir(current_dir) - .env("CARGO_ENCODED_RUSTFLAGS", encoded_rustflags) - .args(&["build", "--release", "--target=wasm32-unknown-unknown"]) - .output() - .expect("failed to execute process"); - - if build_res.status.success() { - return Ok(()) - } - - let stderr = String::from_utf8_lossy(&build_res.stderr); - eprintln!("{}", stderr); - anyhow::bail!("Failed to build contracts"); -} - -/// Post-process the compiled wasm contracts. -fn post_process_wasm(input_path: &Path, output_path: &Path) -> Result<()> { - let mut module = deserialize_file(input_path)?; - if let Some(section) = module.export_section_mut() { - section.entries_mut().retain(|entry| { - matches!(entry.internal(), Internal::Function(_)) && - (entry.field() == "call" || entry.field() == "deploy") - }); - } - - serialize_to_file(output_path, module).map_err(Into::into) -} - -/// Write the compiled contracts to the given output directory. -fn write_output(build_dir: &Path, out_dir: &Path, entries: Vec) -> Result<()> { - for entry in entries { - let wasm_output = entry.out_wasm_filename(); - post_process_wasm( - &build_dir.join("target/wasm32-unknown-unknown/release").join(&wasm_output), - &out_dir.join(&wasm_output), - )?; - fs::write(out_dir.join(&entry.hash), "")?; - } - - Ok(()) -} - -/// Returns the root path of the wasm workspace. -fn find_workspace_root(current_dir: &Path) -> Option { - let mut current_dir = current_dir.to_path_buf(); - - while current_dir.parent().is_some() { - if current_dir.join("Cargo.toml").exists() { - let cargo_toml_contents = - std::fs::read_to_string(current_dir.join("Cargo.toml")).ok()?; - if cargo_toml_contents.contains("[workspace]") { - return Some(current_dir); - } - } - - current_dir.pop(); - } - - None -} - -fn main() -> Result<()> { - let fixtures_dir: PathBuf = env::var("CARGO_MANIFEST_DIR")?.into(); - let contracts_dir = fixtures_dir.join("contracts"); - let out_dir: PathBuf = env::var("OUT_DIR")?.into(); - let workspace_root = find_workspace_root(&fixtures_dir).expect("workspace root exists; qed"); - - let entries = collect_entries(&contracts_dir, &out_dir); - if entries.is_empty() { - return Ok(()); - } - - let tmp_dir = tempfile::tempdir()?; - let tmp_dir_path = tmp_dir.path(); - - create_cargo_toml(&fixtures_dir, entries.iter(), tmp_dir.path())?; - invoke_cargo_fmt( - &workspace_root.join(".rustfmt.toml"), - entries.iter().map(|entry| &entry.path as _), - &contracts_dir, - )?; - - invoke_build(tmp_dir_path)?; - write_output(tmp_dir_path, &out_dir, entries)?; - - Ok(()) -} diff --git a/substrate/frame/contracts/fixtures/contracts/call.rs b/substrate/frame/contracts/fixtures/contracts/call.rs deleted file mode 100644 index 396b71d5e96..00000000000 --- a/substrate/frame/contracts/fixtures/contracts/call.rs +++ /dev/null @@ -1,48 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! This calls another contract as passed as its account id. -#![no_std] -#![no_main] - -extern crate common; -use uapi::{CallFlags, HostFn, HostFnImpl as api}; - -#[no_mangle] -pub extern "C" fn deploy() {} - -#[no_mangle] -pub extern "C" fn call() { - let mut buffer = [0u8; 40]; - let callee_input = 0..4; - let callee_addr = 4..36; - let value = 36..40; - - // Read the input data. - api::input(&mut &mut buffer[..]); - - // Call the callee - api::call_v1( - CallFlags::empty(), - &buffer[callee_addr], - 0u64, // How much gas to devote for the execution. 0 = all. - &buffer[value], - &buffer[callee_input], - None, - ) - .unwrap(); -} diff --git a/substrate/frame/contracts/fixtures/contracts/common/Cargo.toml b/substrate/frame/contracts/fixtures/contracts/common/Cargo.toml deleted file mode 100644 index 377e8bc9dd5..00000000000 --- a/substrate/frame/contracts/fixtures/contracts/common/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "pallet-contracts-fixtures-common" -publish = false -version = "1.0.0" -authors.workspace = true -edition.workspace = true -license.workspace = true -description = "Common utilities for pallet-contracts-fixtures." - -[lints] -workspace = true diff --git a/substrate/frame/contracts/fixtures/data/account_reentrance_count_call.wat b/substrate/frame/contracts/fixtures/data/account_reentrance_count_call.wat index e6d6ba8bb81..ab678906648 100644 --- a/substrate/frame/contracts/fixtures/data/account_reentrance_count_call.wat +++ b/substrate/frame/contracts/fixtures/data/account_reentrance_count_call.wat @@ -14,7 +14,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/add_remove_delegate_dependency.wat b/substrate/frame/contracts/fixtures/data/add_remove_delegate_dependency.wat index dac7736244d..ef456b6d620 100644 --- a/substrate/frame/contracts/fixtures/data/add_remove_delegate_dependency.wat +++ b/substrate/frame/contracts/fixtures/data/add_remove_delegate_dependency.wat @@ -16,7 +16,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -44,8 +44,8 @@ ;; [0..4) - size of the call ;; [4..8) - action to perform ;; [8..42) - code hash of the callee - (local.set $action (i32.load (i32.const 4))) - (local.set $code_hash_ptr (i32.const 8)) + (set_local $action (i32.load (i32.const 4))) + (set_local $code_hash_ptr (i32.const 8)) ;; Assert input size == 36 (4 for action + 32 for code_hash). (call $assert @@ -56,25 +56,25 @@ ) ;; Call add_delegate_dependency when action == 1. - (if (i32.eq (local.get $action) (i32.const 1)) + (if (i32.eq (get_local $action) (i32.const 1)) (then - (call $add_delegate_dependency (local.get $code_hash_ptr)) + (call $add_delegate_dependency (get_local $code_hash_ptr)) ) (else) ) ;; Call remove_delegate_dependency when action == 2. - (if (i32.eq (local.get $action) (i32.const 2)) + (if (i32.eq (get_local $action) (i32.const 2)) (then (call $remove_delegate_dependency - (local.get $code_hash_ptr) + (get_local $code_hash_ptr) ) ) (else) ) ;; Call terminate when action == 3. - (if (i32.eq (local.get $action) (i32.const 3)) + (if (i32.eq (get_local $action) (i32.const 3)) (then (call $terminate (i32.const 100) ;; Pointer to beneficiary address diff --git a/substrate/frame/contracts/fixtures/data/balance.wat b/substrate/frame/contracts/fixtures/data/balance.wat index d7970c92e41..d86d5c4b1c6 100644 --- a/substrate/frame/contracts/fixtures/data/balance.wat +++ b/substrate/frame/contracts/fixtures/data/balance.wat @@ -12,7 +12,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/call.wat b/substrate/frame/contracts/fixtures/data/call.wat new file mode 100644 index 00000000000..4558b2c6409 --- /dev/null +++ b/substrate/frame/contracts/fixtures/data/call.wat @@ -0,0 +1,39 @@ +;; This calls another contract as passed as its account id. +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal1" "seal_call" (func $seal_call (param i32 i32 i64 i32 i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + (func $assert (param i32) + (block $ok + (br_if $ok + (get_local 0) + ) + (unreachable) + ) + ) + + (func (export "deploy")) + + (func (export "call") + ;; Store length of input buffer. + (i32.store (i32.const 0) (i32.const 512)) + + ;; Copy input at address 4. + (call $seal_input (i32.const 4) (i32.const 0)) + + ;; Call passed contract. + (call $assert (i32.eqz + (call $seal_call + (i32.const 0) ;; No flags + (i32.const 8) ;; Pointer to "callee" address. + (i64.const 0) ;; How much gas to devote for the execution. 0 = all. + (i32.const 512) ;; Pointer to the buffer with value to transfer + (i32.const 4) ;; Pointer to input data buffer address + (i32.const 4) ;; Length of input data buffer + (i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output + (i32.const 0) ;; Length is ignored in this case + ) + )) + ) +) diff --git a/substrate/frame/contracts/fixtures/data/call_runtime_and_call.wat b/substrate/frame/contracts/fixtures/data/call_runtime_and_call.wat index 5d76e19a74c..3320922d9e2 100644 --- a/substrate/frame/contracts/fixtures/data/call_runtime_and_call.wat +++ b/substrate/frame/contracts/fixtures/data/call_runtime_and_call.wat @@ -7,7 +7,7 @@ (func $assert (param i32) (block $ok - (br_if $ok (local.get 0)) + (br_if $ok (get_local 0)) (unreachable) ) ) diff --git a/substrate/frame/contracts/fixtures/data/caller_contract.wat b/substrate/frame/contracts/fixtures/data/caller_contract.wat index 43eb8ccfd54..929171b9a26 100644 --- a/substrate/frame/contracts/fixtures/data/caller_contract.wat +++ b/substrate/frame/contracts/fixtures/data/caller_contract.wat @@ -10,7 +10,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -37,10 +37,10 @@ ) ;; Read current balance into local variable. - (local.set $sp (i32.const 1024)) + (set_local $sp (i32.const 1024)) ;; Fail to deploy the contract since it returns a non-zero exit status. - (local.set $exit_code + (set_local $exit_code (call $seal_instantiate (i32.const 24) ;; Pointer to the code hash. (i64.const 0) ;; How much ref_time weight to devote for the execution. 0 = all. @@ -60,11 +60,11 @@ ;; Check non-zero exit status. (call $assert - (i32.eq (local.get $exit_code) (i32.const 2)) ;; ReturnCode::CalleeReverted + (i32.eq (get_local $exit_code) (i32.const 2)) ;; ReturnCode::CalleeReverted ) ;; Fail to deploy the contract due to insufficient ref_time weight. - (local.set $exit_code + (set_local $exit_code (call $seal_instantiate (i32.const 24) ;; Pointer to the code hash. (i64.const 1) ;; Supply too little ref_time weight @@ -85,11 +85,11 @@ ;; Check for special trap exit status. (call $assert - (i32.eq (local.get $exit_code) (i32.const 1)) ;; ReturnCode::CalleeTrapped + (i32.eq (get_local $exit_code) (i32.const 1)) ;; ReturnCode::CalleeTrapped ) ;; Fail to deploy the contract due to insufficient ref_time weight. - (local.set $exit_code + (set_local $exit_code (call $seal_instantiate (i32.const 24) ;; Pointer to the code hash. (i64.const 0) ;; How much ref_time weight to devote for the execution. 0 = all. @@ -110,17 +110,17 @@ ;; Check for special trap exit status. (call $assert - (i32.eq (local.get $exit_code) (i32.const 1)) ;; ReturnCode::CalleeTrapped + (i32.eq (get_local $exit_code) (i32.const 1)) ;; ReturnCode::CalleeTrapped ) ;; Length of the output buffer (i32.store - (i32.sub (local.get $sp) (i32.const 4)) + (i32.sub (get_local $sp) (i32.const 4)) (i32.const 256) ) ;; Deploy the contract successfully. - (local.set $exit_code + (set_local $exit_code (call $seal_instantiate (i32.const 24) ;; Pointer to the code hash. (i64.const 0) ;; How much ref_time weight to devote for the execution. 0 = all. @@ -130,7 +130,7 @@ (i32.const 8) ;; Pointer to input data buffer address (i32.const 8) ;; Length of input data buffer (i32.const 16) ;; Pointer to the address output buffer - (i32.sub (local.get $sp) (i32.const 4)) ;; Pointer to the address buffer length + (i32.sub (get_local $sp) (i32.const 4)) ;; Pointer to the address buffer length (i32.const 4294967295) ;; u32 max sentinel value: do not copy output (i32.const 0) ;; Length is ignored in this case (i32.const 0) ;; salt_ptr @@ -141,28 +141,28 @@ ;; Check for success exit status. (call $assert - (i32.eq (local.get $exit_code) (i32.const 0)) ;; ReturnCode::Success + (i32.eq (get_local $exit_code) (i32.const 0)) ;; ReturnCode::Success ) ;; Check that address has the expected length (call $assert - (i32.eq (i32.load (i32.sub (local.get $sp) (i32.const 4))) (i32.const 32)) + (i32.eq (i32.load (i32.sub (get_local $sp) (i32.const 4))) (i32.const 32)) ) ;; Zero out destination buffer of output (i32.store - (i32.sub (local.get $sp) (i32.const 4)) + (i32.sub (get_local $sp) (i32.const 4)) (i32.const 0) ) ;; Length of the output buffer (i32.store - (i32.sub (local.get $sp) (i32.const 8)) + (i32.sub (get_local $sp) (i32.const 8)) (i32.const 4) ) ;; Call the new contract and expect it to return failing exit code. - (local.set $exit_code + (set_local $exit_code (call $seal_call (i32.const 0) ;; Set no flag (i32.const 16) ;; Pointer to "callee" address. @@ -172,29 +172,29 @@ (i32.const 0) ;; Pointer to the buffer with value to transfer (i32.const 9) ;; Pointer to input data buffer address (i32.const 7) ;; Length of input data buffer - (i32.sub (local.get $sp) (i32.const 4)) ;; Ptr to output buffer - (i32.sub (local.get $sp) (i32.const 8)) ;; Ptr to output buffer len + (i32.sub (get_local $sp) (i32.const 4)) ;; Ptr to output buffer + (i32.sub (get_local $sp) (i32.const 8)) ;; Ptr to output buffer len ) ) ;; Check non-zero exit status. (call $assert - (i32.eq (local.get $exit_code) (i32.const 2)) ;; ReturnCode::CalleeReverted + (i32.eq (get_local $exit_code) (i32.const 2)) ;; ReturnCode::CalleeReverted ) ;; Check that output buffer contains the expected return data. (call $assert - (i32.eq (i32.load (i32.sub (local.get $sp) (i32.const 8))) (i32.const 3)) + (i32.eq (i32.load (i32.sub (get_local $sp) (i32.const 8))) (i32.const 3)) ) (call $assert (i32.eq - (i32.load (i32.sub (local.get $sp) (i32.const 4))) + (i32.load (i32.sub (get_local $sp) (i32.const 4))) (i32.const 0x00776655) ) ) ;; Fail to call the contract due to insufficient ref_time weight. - (local.set $exit_code + (set_local $exit_code (call $seal_call (i32.const 0) ;; Set no flag (i32.const 16) ;; Pointer to "callee" address. @@ -211,11 +211,11 @@ ;; Check for special trap exit status. (call $assert - (i32.eq (local.get $exit_code) (i32.const 1)) ;; ReturnCode::CalleeTrapped + (i32.eq (get_local $exit_code) (i32.const 1)) ;; ReturnCode::CalleeTrapped ) ;; Fail to call the contract due to insufficient proof_size weight. - (local.set $exit_code + (set_local $exit_code (call $seal_call (i32.const 0) ;; Set no flag (i32.const 16) ;; Pointer to "callee" address. @@ -232,23 +232,23 @@ ;; Check for special trap exit status. (call $assert - (i32.eq (local.get $exit_code) (i32.const 1)) ;; ReturnCode::CalleeTrapped + (i32.eq (get_local $exit_code) (i32.const 1)) ;; ReturnCode::CalleeTrapped ) ;; Zero out destination buffer of output (i32.store - (i32.sub (local.get $sp) (i32.const 4)) + (i32.sub (get_local $sp) (i32.const 4)) (i32.const 0) ) ;; Length of the output buffer (i32.store - (i32.sub (local.get $sp) (i32.const 8)) + (i32.sub (get_local $sp) (i32.const 8)) (i32.const 4) ) ;; Call the contract successfully. - (local.set $exit_code + (set_local $exit_code (call $seal_call (i32.const 0) ;; Set no flag (i32.const 16) ;; Pointer to "callee" address. @@ -258,23 +258,23 @@ (i32.const 0) ;; Pointer to the buffer with value to transfer (i32.const 8) ;; Pointer to input data buffer address (i32.const 8) ;; Length of input data buffer - (i32.sub (local.get $sp) (i32.const 4)) ;; Ptr to output buffer - (i32.sub (local.get $sp) (i32.const 8)) ;; Ptr to output buffer len + (i32.sub (get_local $sp) (i32.const 4)) ;; Ptr to output buffer + (i32.sub (get_local $sp) (i32.const 8)) ;; Ptr to output buffer len ) ) ;; Check for success exit status. (call $assert - (i32.eq (local.get $exit_code) (i32.const 0)) ;; ReturnCode::Success + (i32.eq (get_local $exit_code) (i32.const 0)) ;; ReturnCode::Success ) ;; Check that the output buffer contains the expected return data. (call $assert - (i32.eq (i32.load (i32.sub (local.get $sp) (i32.const 8))) (i32.const 4)) + (i32.eq (i32.load (i32.sub (get_local $sp) (i32.const 8))) (i32.const 4)) ) (call $assert (i32.eq - (i32.load (i32.sub (local.get $sp) (i32.const 4))) + (i32.load (i32.sub (get_local $sp) (i32.const 4))) (i32.const 0x77665544) ) ) diff --git a/substrate/frame/contracts/fixtures/data/chain_extension.wat b/substrate/frame/contracts/fixtures/data/chain_extension.wat index c24ca286ff8..670f8e70172 100644 --- a/substrate/frame/contracts/fixtures/data/chain_extension.wat +++ b/substrate/frame/contracts/fixtures/data/chain_extension.wat @@ -9,7 +9,7 @@ (func $assert (param i32) (block $ok - (br_if $ok (local.get 0)) + (br_if $ok (get_local 0)) (unreachable) ) ) diff --git a/substrate/frame/contracts/fixtures/data/chain_extension_temp_storage.wat b/substrate/frame/contracts/fixtures/data/chain_extension_temp_storage.wat index 504646df1b0..b481abb5bc7 100644 --- a/substrate/frame/contracts/fixtures/data/chain_extension_temp_storage.wat +++ b/substrate/frame/contracts/fixtures/data/chain_extension_temp_storage.wat @@ -11,7 +11,7 @@ (func $assert (param i32) (block $ok - (br_if $ok (local.get 0)) + (br_if $ok (get_local 0)) (unreachable) ) ) diff --git a/substrate/frame/contracts/fixtures/data/create_storage_and_call.wat b/substrate/frame/contracts/fixtures/data/create_storage_and_call.wat index 2bff53b638f..5592e7e96a9 100644 --- a/substrate/frame/contracts/fixtures/data/create_storage_and_call.wat +++ b/substrate/frame/contracts/fixtures/data/create_storage_and_call.wat @@ -8,7 +8,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/create_storage_and_instantiate.wat b/substrate/frame/contracts/fixtures/data/create_storage_and_instantiate.wat index 00c9a657f39..cd720247843 100644 --- a/substrate/frame/contracts/fixtures/data/create_storage_and_instantiate.wat +++ b/substrate/frame/contracts/fixtures/data/create_storage_and_instantiate.wat @@ -14,7 +14,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/crypto_hashes.wat b/substrate/frame/contracts/fixtures/data/crypto_hashes.wat index 9d86b02f419..c2b4d6b81ed 100644 --- a/substrate/frame/contracts/fixtures/data/crypto_hashes.wat +++ b/substrate/frame/contracts/fixtures/data/crypto_hashes.wat @@ -59,10 +59,8 @@ (call $seal_input (local.get $input_ptr) (local.get $input_len_ptr)) (local.set $chosen_hash_fn (i32.load8_u (local.get $input_ptr))) (if (i32.gt_u (local.get $chosen_hash_fn) (i32.const 7)) - (then - ;; We check that the chosen hash fn identifier is within bounds: [0,7] - (unreachable) - ) + ;; We check that the chosen hash fn identifier is within bounds: [0,7] + (unreachable) ) (local.set $input_ptr (i32.add (local.get $input_ptr) (i32.const 1))) (local.set $input_len (i32.sub (i32.load (local.get $input_len_ptr)) (i32.const 1))) diff --git a/substrate/frame/contracts/fixtures/data/debug_message_invalid_utf8.wat b/substrate/frame/contracts/fixtures/data/debug_message_invalid_utf8.wat index dae0de88418..e8c447b42fc 100644 --- a/substrate/frame/contracts/fixtures/data/debug_message_invalid_utf8.wat +++ b/substrate/frame/contracts/fixtures/data/debug_message_invalid_utf8.wat @@ -8,7 +8,7 @@ (func $assert_eq (param i32 i32) (block $ok (br_if $ok - (i32.eq (local.get 0) (local.get 1)) + (i32.eq (get_local 0) (get_local 1)) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/debug_message_logging_disabled.wat b/substrate/frame/contracts/fixtures/data/debug_message_logging_disabled.wat index e9ce20ba42b..fc6ee72df8b 100644 --- a/substrate/frame/contracts/fixtures/data/debug_message_logging_disabled.wat +++ b/substrate/frame/contracts/fixtures/data/debug_message_logging_disabled.wat @@ -8,7 +8,7 @@ (func $assert_eq (param i32 i32) (block $ok (br_if $ok - (i32.eq (local.get 0) (local.get 1)) + (i32.eq (get_local 0) (get_local 1)) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/debug_message_works.wat b/substrate/frame/contracts/fixtures/data/debug_message_works.wat index 44a7b6db1be..61933c23296 100644 --- a/substrate/frame/contracts/fixtures/data/debug_message_works.wat +++ b/substrate/frame/contracts/fixtures/data/debug_message_works.wat @@ -8,7 +8,7 @@ (func $assert_eq (param i32 i32) (block $ok (br_if $ok - (i32.eq (local.get 0) (local.get 1)) + (i32.eq (get_local 0) (get_local 1)) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/delegate_call.wat b/substrate/frame/contracts/fixtures/data/delegate_call.wat index b8d4f0d47f0..7fe422af455 100644 --- a/substrate/frame/contracts/fixtures/data/delegate_call.wat +++ b/substrate/frame/contracts/fixtures/data/delegate_call.wat @@ -24,7 +24,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -70,7 +70,7 @@ ) ;; Call deployed library contract code. - (local.set $exit_code + (set_local $exit_code (call $seal_delegate_call (i32.const 0) ;; Set no call flags (i32.const 64) ;; Pointer to "callee" code_hash. @@ -83,7 +83,7 @@ ;; Check for success exit status. (call $assert - (i32.eq (local.get $exit_code) (i32.const 0)) ;; ReturnCode::Success + (i32.eq (get_local $exit_code) (i32.const 0)) ;; ReturnCode::Success ) (call $assert diff --git a/substrate/frame/contracts/fixtures/data/delegate_call_lib.wat b/substrate/frame/contracts/fixtures/data/delegate_call_lib.wat index 62eea32800a..340b9699f87 100644 --- a/substrate/frame/contracts/fixtures/data/delegate_call_lib.wat +++ b/substrate/frame/contracts/fixtures/data/delegate_call_lib.wat @@ -20,7 +20,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/delegate_call_simple.wat b/substrate/frame/contracts/fixtures/data/delegate_call_simple.wat index ba0a8fcc8ae..24ae5a13e33 100644 --- a/substrate/frame/contracts/fixtures/data/delegate_call_simple.wat +++ b/substrate/frame/contracts/fixtures/data/delegate_call_simple.wat @@ -12,7 +12,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/destroy_and_transfer.wat b/substrate/frame/contracts/fixtures/data/destroy_and_transfer.wat index 2afd3b2fbac..25554795552 100644 --- a/substrate/frame/contracts/fixtures/data/destroy_and_transfer.wat +++ b/substrate/frame/contracts/fixtures/data/destroy_and_transfer.wat @@ -33,7 +33,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/drain.wat b/substrate/frame/contracts/fixtures/data/drain.wat index 18a21cca803..cb8ff0aed61 100644 --- a/substrate/frame/contracts/fixtures/data/drain.wat +++ b/substrate/frame/contracts/fixtures/data/drain.wat @@ -19,7 +19,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/dummy.wat b/substrate/frame/contracts/fixtures/data/dummy.wat new file mode 100644 index 00000000000..a6435e49df2 --- /dev/null +++ b/substrate/frame/contracts/fixtures/data/dummy.wat @@ -0,0 +1,6 @@ +;; A valid contract which does nothing at all +(module + (import "env" "memory" (memory 1 1)) + (func (export "deploy")) + (func (export "call")) +) diff --git a/substrate/frame/contracts/fixtures/data/ecdsa_recover.wat b/substrate/frame/contracts/fixtures/data/ecdsa_recover.wat index 4910e706069..d694b3215e8 100644 --- a/substrate/frame/contracts/fixtures/data/ecdsa_recover.wat +++ b/substrate/frame/contracts/fixtures/data/ecdsa_recover.wat @@ -12,7 +12,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/event_size.wat b/substrate/frame/contracts/fixtures/data/event_size.wat index 1c1f34b24d7..4bd6158d72f 100644 --- a/substrate/frame/contracts/fixtures/data/event_size.wat +++ b/substrate/frame/contracts/fixtures/data/event_size.wat @@ -9,7 +9,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/multi_store.wat b/substrate/frame/contracts/fixtures/data/multi_store.wat index c334ed54c4e..2592baf6183 100644 --- a/substrate/frame/contracts/fixtures/data/multi_store.wat +++ b/substrate/frame/contracts/fixtures/data/multi_store.wat @@ -19,7 +19,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/reentrance_count_call.wat b/substrate/frame/contracts/fixtures/data/reentrance_count_call.wat index 44db8d041b1..c6b529e2aff 100644 --- a/substrate/frame/contracts/fixtures/data/reentrance_count_call.wat +++ b/substrate/frame/contracts/fixtures/data/reentrance_count_call.wat @@ -20,7 +20,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -36,11 +36,11 @@ (call $seal_input (i32.const 32) (i32.const 36)) ;; reading manually passed reentrant count - (local.set $expected_reentrance_count (i32.load (i32.const 32))) + (set_local $expected_reentrance_count (i32.load (i32.const 32))) ;; reentrance count is calculated correctly (call $assert - (i32.eq (call $reentrance_count) (local.get $expected_reentrance_count)) + (i32.eq (call $reentrance_count) (get_local $expected_reentrance_count)) ) ;; re-enter 5 times in a row and assert that the reentrant counter works as expected @@ -52,7 +52,7 @@ (i32.store (i32.const 32) (i32.add (i32.load (i32.const 32)) (i32.const 1))) ;; Call to itself - (local.set $seal_call_exit_code + (set_local $seal_call_exit_code (call $seal_call (i32.const 8) ;; Allow reentrancy flag set (i32.const 0) ;; Pointer to "callee" address @@ -66,7 +66,7 @@ ) (call $assert - (i32.eq (local.get $seal_call_exit_code) (i32.const 0)) + (i32.eq (get_local $seal_call_exit_code) (i32.const 0)) ) ) ) diff --git a/substrate/frame/contracts/fixtures/data/reentrance_count_delegated_call.wat b/substrate/frame/contracts/fixtures/data/reentrance_count_delegated_call.wat index 49e0193bcdb..b8219a8462e 100644 --- a/substrate/frame/contracts/fixtures/data/reentrance_count_delegated_call.wat +++ b/substrate/frame/contracts/fixtures/data/reentrance_count_delegated_call.wat @@ -17,7 +17,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -30,7 +30,7 @@ (call $seal_input (i32.const 0) (i32.const 36)) ;; reading passed callstack height - (local.set $callstack_height (i32.load (i32.const 32))) + (set_local $callstack_height (i32.load (i32.const 32))) ;; incrementing callstack height (i32.store (i32.const 32) (i32.add (i32.load (i32.const 32)) (i32.const 1))) @@ -40,12 +40,12 @@ (i32.eq (call $reentrance_count) (i32.const 0)) ) - (i32.eq (local.get $callstack_height) (i32.const 5)) + (i32.eq (get_local $callstack_height) (i32.const 5)) (if (then) ;; exit recursion case (else ;; Call to itself - (local.set $delegate_call_exit_code + (set_local $delegate_call_exit_code (call $seal_delegate_call (i32.const 0) ;; Set no call flags (i32.const 0) ;; Pointer to "callee" code_hash. @@ -57,13 +57,13 @@ ) (call $assert - (i32.eq (local.get $delegate_call_exit_code) (i32.const 0)) + (i32.eq (get_local $delegate_call_exit_code) (i32.const 0)) ) ) ) (call $assert - (i32.le_s (local.get $callstack_height) (i32.const 5)) + (i32.le_s (get_local $callstack_height) (i32.const 5)) ) ) diff --git a/substrate/frame/contracts/fixtures/data/self_destruct.wat b/substrate/frame/contracts/fixtures/data/self_destruct.wat index 00c3895fdde..b8a37306e20 100644 --- a/substrate/frame/contracts/fixtures/data/self_destruct.wat +++ b/substrate/frame/contracts/fixtures/data/self_destruct.wat @@ -26,7 +26,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/self_destructing_constructor.wat b/substrate/frame/contracts/fixtures/data/self_destructing_constructor.wat index 628f283a19f..85fce511e21 100644 --- a/substrate/frame/contracts/fixtures/data/self_destructing_constructor.wat +++ b/substrate/frame/contracts/fixtures/data/self_destructing_constructor.wat @@ -5,7 +5,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/set_code_hash.wat b/substrate/frame/contracts/fixtures/data/set_code_hash.wat index c0a9557b4d0..b4df1b13318 100644 --- a/substrate/frame/contracts/fixtures/data/set_code_hash.wat +++ b/substrate/frame/contracts/fixtures/data/set_code_hash.wat @@ -16,7 +16,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -27,11 +27,11 @@ (call $seal_input (i32.const 0) (i32.const 32)) - (local.set $exit_code + (set_local $exit_code (call $seal_set_code_hash (i32.const 0)) ;; Pointer to the input data. ) (call $assert - (i32.eq (local.get $exit_code) (i32.const 0)) ;; ReturnCode::Success + (i32.eq (get_local $exit_code) (i32.const 0)) ;; ReturnCode::Success ) ;; we return 1 after setting new code_hash diff --git a/substrate/frame/contracts/fixtures/data/storage_size.wat b/substrate/frame/contracts/fixtures/data/storage_size.wat index 728bb4fcf3c..293a656d4f6 100644 --- a/substrate/frame/contracts/fixtures/data/storage_size.wat +++ b/substrate/frame/contracts/fixtures/data/storage_size.wat @@ -20,7 +20,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/store_call.wat b/substrate/frame/contracts/fixtures/data/store_call.wat index 746b7a48b55..9e090d31801 100644 --- a/substrate/frame/contracts/fixtures/data/store_call.wat +++ b/substrate/frame/contracts/fixtures/data/store_call.wat @@ -15,7 +15,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/store_deploy.wat b/substrate/frame/contracts/fixtures/data/store_deploy.wat index 7f115cba977..cc428e9623b 100644 --- a/substrate/frame/contracts/fixtures/data/store_deploy.wat +++ b/substrate/frame/contracts/fixtures/data/store_deploy.wat @@ -15,7 +15,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/xcm_execute.wat b/substrate/frame/contracts/fixtures/data/xcm_execute.wat index 72ef14ed82c..b3459996a2e 100644 --- a/substrate/frame/contracts/fixtures/data/xcm_execute.wat +++ b/substrate/frame/contracts/fixtures/data/xcm_execute.wat @@ -12,7 +12,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/data/xcm_send.wat b/substrate/frame/contracts/fixtures/data/xcm_send.wat index fe29ddf0f14..9eec6388de9 100644 --- a/substrate/frame/contracts/fixtures/data/xcm_send.wat +++ b/substrate/frame/contracts/fixtures/data/xcm_send.wat @@ -12,7 +12,7 @@ (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/fixtures/src/lib.rs b/substrate/frame/contracts/fixtures/src/lib.rs index fbc2647709d..48117f7ca94 100644 --- a/substrate/frame/contracts/fixtures/src/lib.rs +++ b/substrate/frame/contracts/fixtures/src/lib.rs @@ -16,9 +16,9 @@ // limitations under the License. use sp_runtime::traits::Hash; -use std::{env::var, fs, path::PathBuf}; +use std::{env::var, path::PathBuf}; -fn wat_root_dir() -> PathBuf { +fn fixtures_root_dir() -> PathBuf { match (var("CARGO_MANIFEST_DIR"), var("CARGO_PKG_NAME")) { // When `CARGO_MANIFEST_DIR` is not set, Rust resolves relative paths from the root folder (Err(_), _) => "substrate/frame/contracts/fixtures/data".into(), @@ -33,44 +33,12 @@ fn wat_root_dir() -> PathBuf { /// with it's hash. /// /// The fixture files are located under the `fixtures/` directory. -fn legacy_compile_module( - fixture_name: &str, -) -> anyhow::Result<(Vec, ::Output)> +pub fn compile_module(fixture_name: &str) -> wat::Result<(Vec, ::Output)> where T: frame_system::Config, { - let fixture_path = wat_root_dir().join(format!("{fixture_name}.wat")); + let fixture_path = fixtures_root_dir().join(format!("{fixture_name}.wat")); let wasm_binary = wat::parse_file(fixture_path)?; let code_hash = T::Hashing::hash(&wasm_binary); Ok((wasm_binary, code_hash)) } - -/// Load a given wasm module and returns a wasm binary contents along with it's hash. -/// Use the legacy compile_module as fallback, if the rust fixture does not exist yet. -pub fn compile_module( - fixture_name: &str, -) -> anyhow::Result<(Vec, ::Output)> -where - T: frame_system::Config, -{ - let out_dir: std::path::PathBuf = env!("OUT_DIR").into(); - let fixture_path = out_dir.join(format!("{fixture_name}.wasm")); - match fs::read(fixture_path) { - Ok(wasm_binary) => { - let code_hash = T::Hashing::hash(&wasm_binary); - Ok((wasm_binary, code_hash)) - }, - Err(_) => legacy_compile_module::(fixture_name), - } -} - -#[cfg(test)] -mod test { - #[test] - fn out_dir_should_have_compiled_mocks() { - let out_dir: std::path::PathBuf = env!("OUT_DIR").into(); - let dummy_wasm = out_dir.join("dummy.wasm"); - println!("dummy_wasm: {:?}", dummy_wasm); - assert!(dummy_wasm.exists()); - } -} diff --git a/substrate/frame/contracts/mock-network/Cargo.toml b/substrate/frame/contracts/mock-network/Cargo.toml index 7b570eed155..9d5fe1aaf4e 100644 --- a/substrate/frame/contracts/mock-network/Cargo.toml +++ b/substrate/frame/contracts/mock-network/Cargo.toml @@ -8,40 +8,37 @@ homepage = "https://substrate.io" repository.workspace = true description = "A mock network for testing pallet-contracts" -[lints] -workspace = true - [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } +codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = [ "derive", "max-encoded-len"] } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } +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-primitives = { path = "../primitives", 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" } +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.10.0", 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-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-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" } +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"} [dev-dependencies] assert_matches = "1" @@ -49,12 +46,13 @@ pretty_assertions = "1" pallet-contracts-fixtures = { path = "../fixtures" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", "frame-system/std", "pallet-balances/std", + "pallet-contracts-primitives/std", "pallet-contracts-proc-macro/full", "pallet-contracts/std", "pallet-insecure-randomness-collective-flip/std", diff --git a/substrate/frame/contracts/mock-network/src/parachain.rs b/substrate/frame/contracts/mock-network/src/parachain.rs index a79b7e4e2d6..1465b02f903 100644 --- a/substrate/frame/contracts/mock-network/src/parachain.rs +++ b/substrate/frame/contracts/mock-network/src/parachain.rs @@ -23,7 +23,7 @@ use crate::{ }; use core::marker::PhantomData; use frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, parameter_types, traits::{AsEnsureOriginWithArg, Contains, ContainsPair, Everything, EverythingBut, Nothing}, weights::{ constants::{WEIGHT_PROOF_SIZE_PER_MB, WEIGHT_REF_TIME_PER_SECOND}, @@ -37,13 +37,12 @@ use sp_runtime::traits::{Get, IdentityLookup, MaybeEquivalence}; use sp_std::prelude::*; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter as XcmCurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, - ConvertedConcreteId, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, FungiblesAdapter, - IsConcrete, NativeAsset, NoChecking, ParentAsSuperuser, ParentIsPreset, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, + ConvertedConcreteId, CurrencyAdapter as XcmCurrencyAdapter, EnsureXcmOrigin, + FixedRateOfFungible, FixedWeightBounds, FungiblesAdapter, IsConcrete, NativeAsset, NoChecking, + ParentAsSuperuser, ParentIsPreset, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, WithComputedOrigin, }; use xcm_executor::{traits::JustTry, Config, XcmExecutor}; @@ -54,7 +53,6 @@ parameter_types! { pub const BlockHashCount: u64 = 250; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; @@ -184,7 +182,6 @@ pub fn estimate_fee_for_weight(weight: Weight) -> u128 { units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128) } -#[allow(deprecated)] pub type LocalBalancesTransactor = XcmCurrencyAdapter, SovereignAccountOf, AccountId, ()>; diff --git a/substrate/frame/contracts/mock-network/src/relay_chain.rs b/substrate/frame/contracts/mock-network/src/relay_chain.rs index 136cc2e3ed6..c59c8e4bfa8 100644 --- a/substrate/frame/contracts/mock-network/src/relay_chain.rs +++ b/substrate/frame/contracts/mock-network/src/relay_chain.rs @@ -17,7 +17,7 @@ //! Relay chain runtime mock. use frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, parameter_types, traits::{Contains, Everything, Nothing}, weights::Weight, }; @@ -29,14 +29,12 @@ use sp_runtime::traits::IdentityLookup; use polkadot_parachain_primitives::primitives::Id as ParaId; use polkadot_runtime_parachains::{configuration, origin, shared}; use xcm::latest::prelude::*; -#[allow(deprecated)] -use xcm_builder::CurrencyAdapter as XcmCurrencyAdapter; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, ChildParachainConvertsVia, - ChildSystemParachainAsSuperuser, DescribeAllTerminal, DescribeFamily, FixedRateOfFungible, - FixedWeightBounds, HashedDescription, IsConcrete, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, + ChildSystemParachainAsSuperuser, CurrencyAdapter as XcmCurrencyAdapter, DescribeAllTerminal, + DescribeFamily, FixedRateOfFungible, FixedWeightBounds, HashedDescription, IsConcrete, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, }; use xcm_executor::{Config, XcmExecutor}; @@ -49,7 +47,6 @@ parameter_types! { pub const BlockHashCount: u64 = 250; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; @@ -118,7 +115,6 @@ pub type SovereignAccountOf = ( ChildParachainConvertsVia, ); -#[allow(deprecated)] pub type LocalBalancesTransactor = XcmCurrencyAdapter, SovereignAccountOf, AccountId, ()>; diff --git a/substrate/frame/contracts/mock-network/src/tests.rs b/substrate/frame/contracts/mock-network/src/tests.rs index a66b2b08019..5193f657055 100644 --- a/substrate/frame/contracts/mock-network/src/tests.rs +++ b/substrate/frame/contracts/mock-network/src/tests.rs @@ -29,8 +29,9 @@ use frame_support::{ traits::{fungibles::Mutate, Currency}, }; use pallet_balances::{BalanceLock, Reasons}; -use pallet_contracts::{Code, CollectEvents, DebugInfo, Determinism}; +use pallet_contracts::{CollectEvents, DebugInfo, Determinism}; use pallet_contracts_fixtures::compile_module; +use pallet_contracts_primitives::Code; use xcm::{v3::prelude::*, VersionedMultiLocation, VersionedXcm}; use xcm_simulator::TestExt; diff --git a/substrate/frame/contracts/primitives/Cargo.toml b/substrate/frame/contracts/primitives/Cargo.toml index d1db766ce81..0394841aa1f 100644 --- a/substrate/frame/contracts/primitives/Cargo.toml +++ b/substrate/frame/contracts/primitives/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "A crate that hosts a common definitions that are relevant for the pallet-contracts." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,12 +18,12 @@ scale-info = { version = "2.10.0", default-features = false, features = ["derive codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } # Substrate Dependencies (This crate should not rely on frame) -sp-std = { path = "../../../primitives/std", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-weights = { path = "../../../primitives/weights", default-features = false } +sp-std = { path = "../../../primitives/std", default-features = false} +sp-runtime = { path = "../../../primitives/runtime", default-features = false} +sp-weights = { path = "../../../primitives/weights", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "scale-info/std", diff --git a/substrate/frame/contracts/primitives/README.md b/substrate/frame/contracts/primitives/README.md new file mode 100644 index 00000000000..c84cfbfe1a8 --- /dev/null +++ b/substrate/frame/contracts/primitives/README.md @@ -0,0 +1,3 @@ +A crate that hosts a common definitions that are relevant for the pallet-contracts. + +License: Apache-2.0 diff --git a/substrate/frame/contracts/src/primitives.rs b/substrate/frame/contracts/primitives/src/lib.rs similarity index 96% rename from substrate/frame/contracts/src/primitives.rs rename to substrate/frame/contracts/primitives/src/lib.rs index ab73b28e8c4..c3314928500 100644 --- a/substrate/frame/contracts/src/primitives.rs +++ b/substrate/frame/contracts/primitives/src/lib.rs @@ -17,15 +17,17 @@ //! A crate that hosts a common definitions that are relevant for the pallet-contracts. +#![cfg_attr(not(feature = "std"), no_std)] + +use bitflags::bitflags; use codec::{Decode, Encode, MaxEncodedLen}; -use frame_support::weights::Weight; -use pallet_contracts_uapi::ReturnFlags; use scale_info::TypeInfo; use sp_runtime::{ traits::{Saturating, Zero}, DispatchError, RuntimeDebug, }; use sp_std::prelude::*; +use sp_weights::Weight; /// Result type of a `bare_call` or `bare_instantiate` call as well as `ContractsApi::call` and /// `ContractsApi::instantiate`. @@ -107,6 +109,15 @@ pub enum ContractAccessError { MigrationInProgress, } +bitflags! { + /// Flags used by a contract to customize exit behaviour. + #[derive(Encode, Decode, TypeInfo)] + pub struct ReturnFlags: u32 { + /// If this bit is set all changes made by the contract execution are rolled back. + const REVERT = 0x0000_0001; + } +} + /// Output of a contract call or instantiation which ran to completion. #[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug, TypeInfo)] pub struct ExecReturnValue { diff --git a/substrate/frame/contracts/proc-macro/Cargo.toml b/substrate/frame/contracts/proc-macro/Cargo.toml index 573cd96d3ab..3ada9e0c23d 100644 --- a/substrate/frame/contracts/proc-macro/Cargo.toml +++ b/substrate/frame/contracts/proc-macro/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "Procedural macros used in pallet_contracts" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,7 +17,7 @@ proc-macro = true [dependencies] proc-macro2 = "1.0.56" quote = "1.0.28" -syn = { version = "2.0.40", features = ["full"] } +syn = { version = "2.0.38", features = ["full"] } [dev-dependencies] diff --git a/substrate/frame/contracts/proc-macro/src/lib.rs b/substrate/frame/contracts/proc-macro/src/lib.rs index 9dc34d5223b..ad9cd2dadec 100644 --- a/substrate/frame/contracts/proc-macro/src/lib.rs +++ b/substrate/frame/contracts/proc-macro/src/lib.rs @@ -74,7 +74,7 @@ fn derive_debug(input: TokenStream, fmt: impl Fn(&Ident) -> TokenStream2) -> Tok #[cfg(not(feature = "full"))] let fields = { drop(fmt); - let _ = data; + drop(data); TokenStream2::new() }; @@ -271,7 +271,7 @@ impl HostFn { // process return type let msg = r#"Should return one of the following: - Result<(), TrapReason>, - - Result, + - Result, - Result, - Result"#; let ret_ty = match item.clone().sig.output { @@ -336,7 +336,7 @@ impl HostFn { "()" => Ok(HostFnReturn::Unit), "u32" => Ok(HostFnReturn::U32), "u64" => Ok(HostFnReturn::U64), - "ReturnErrorCode" => Ok(HostFnReturn::ReturnCode), + "ReturnCode" => Ok(HostFnReturn::ReturnCode), _ => Err(err(arg1.span(), &msg)), }?; @@ -550,7 +550,7 @@ fn expand_env(def: &EnvDef, docs: bool) -> TokenStream2 { /// consumed by humans through rustdoc. #[cfg(doc)] pub mod api_doc { - use super::{TrapReason, ReturnErrorCode}; + use super::{TrapReason, ReturnCode}; #docs } } @@ -767,7 +767,7 @@ fn expand_functions(def: &EnvDef, expand_blocks: bool, host_state: TokenStream2) /// #[define_env] /// pub mod some_env { /// #[version(2)] -/// fn foo(ctx: _, memory: _, key_ptr: u32, value_ptr: u32, value_len: u32) -> Result { +/// fn foo(ctx: _, memory: _, key_ptr: u32, value_ptr: u32, value_len: u32) -> Result { /// ctx.some_host_fn(KeyType::Fix, key_ptr, value_ptr, value_len).map(|_| ()) /// } /// @@ -793,7 +793,7 @@ fn expand_functions(def: &EnvDef, expand_blocks: bool, host_state: TokenStream2) /// pub mod some_env { /// #[version(1)] /// #[prefixed_alias] -/// fn foo(ctx: _, memory: _, key_ptr: u32, value_ptr: u32, value_len: u32) -> Result { +/// fn foo(ctx: _, memory: _, key_ptr: u32, value_ptr: u32, value_len: u32) -> Result { /// ctx.some_host_fn(KeyType::Fix, key_ptr, value_ptr, value_len).map(|_| ()) /// } /// @@ -811,7 +811,7 @@ fn expand_functions(def: &EnvDef, expand_blocks: bool, host_state: TokenStream2) /// /// Only following return types are allowed for the host functions defined with the macro: /// - `Result<(), TrapReason>`, -/// - `Result`, +/// - `Result`, /// - `Result`. /// /// The macro expands to `pub struct Env` declaration, with the following traits implementations: diff --git a/substrate/frame/contracts/src/benchmarking/mod.rs b/substrate/frame/contracts/src/benchmarking/mod.rs index c532b354ab6..ac5787e2340 100644 --- a/substrate/frame/contracts/src/benchmarking/mod.rs +++ b/substrate/frame/contracts/src/benchmarking/mod.rs @@ -33,6 +33,7 @@ use crate::{ migration::{ codegen::LATEST_MIGRATION_VERSION, v09, v10, v11, v12, v13, v14, v15, MigrationStep, }, + wasm::CallFlags, Pallet as Contracts, *, }; use codec::{Encode, MaxEncodedLen}; @@ -45,7 +46,6 @@ use frame_support::{ }; use frame_system::RawOrigin; use pallet_balances; -use pallet_contracts_uapi::CallFlags; use sp_runtime::traits::{Bounded, Hash}; use sp_std::prelude::*; use wasm_instrument::parity_wasm::elements::{BlockType, Instruction, ValueType}; diff --git a/substrate/frame/contracts/src/chain_extension.rs b/substrate/frame/contracts/src/chain_extension.rs index 8a7243d6bb3..664504d207f 100644 --- a/substrate/frame/contracts/src/chain_extension.rs +++ b/substrate/frame/contracts/src/chain_extension.rs @@ -81,7 +81,7 @@ use sp_std::{marker::PhantomData, vec::Vec}; pub use crate::{exec::Ext, gas::ChargedAmount, storage::meter::Diff, Config}; pub use frame_system::Config as SysConfig; -pub use pallet_contracts_uapi::ReturnFlags; +pub use pallet_contracts_primitives::ReturnFlags; /// Result that returns a [`DispatchError`] on error. pub type Result = sp_std::result::Result; diff --git a/substrate/frame/contracts/src/debug.rs b/substrate/frame/contracts/src/debug.rs index 6cdca7aa4c7..e22a841e6fb 100644 --- a/substrate/frame/contracts/src/debug.rs +++ b/substrate/frame/contracts/src/debug.rs @@ -15,11 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -pub use crate::{ - exec::{ExecResult, ExportedFunction}, - primitives::ExecReturnValue, -}; +pub use crate::exec::{ExecResult, ExportedFunction}; use crate::{Config, LOG_TARGET}; +pub use pallet_contracts_primitives::ExecReturnValue; /// Umbrella trait for all interfaces that serves for debugging. pub trait Debugger: Tracing + CallInterceptor {} diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index 2183d6b96cc..c26d82f7f11 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -18,7 +18,6 @@ use crate::{ debug::{CallInterceptor, CallSpan, Tracing}, gas::GasMeter, - primitives::{ExecReturnValue, StorageDeposit}, storage::{self, meter::Diff, WriteOutcome}, BalanceOf, CodeHash, CodeInfo, CodeInfoOf, Config, ContractInfo, ContractInfoOf, DebugBufferVec, Determinism, Error, Event, Nonce, Origin, Pallet as Contracts, Schedule, @@ -38,6 +37,7 @@ use frame_support::{ Blake2_128Concat, BoundedVec, StorageHasher, }; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; +use pallet_contracts_primitives::{ExecReturnValue, StorageDeposit}; use smallvec::{Array, SmallVec}; use sp_core::{ ecdsa::Public as ECDSAPublic, @@ -1618,7 +1618,7 @@ mod tests { use codec::{Decode, Encode}; use frame_support::{assert_err, assert_ok, parameter_types}; use frame_system::{EventRecord, Phase}; - use pallet_contracts_uapi::ReturnFlags; + use pallet_contracts_primitives::ReturnFlags; use pretty_assertions::assert_eq; use sp_runtime::{traits::Hash, DispatchError}; use std::{cell::RefCell, collections::hash_map::HashMap, rc::Rc}; diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index a15006e6388..188679dbf49 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -91,9 +91,6 @@ mod address; mod benchmarking; mod exec; mod gas; -mod primitives; -pub use primitives::*; - mod schedule; mod storage; mod wasm; @@ -131,6 +128,11 @@ use frame_system::{ pallet_prelude::{BlockNumberFor, OriginFor}, EventRecord, Pallet as System, }; +use pallet_contracts_primitives::{ + Code, CodeUploadResult, CodeUploadReturnValue, ContractAccessError, ContractExecResult, + ContractInstantiateResult, ContractResult, ExecReturnValue, GetStorageResult, + InstantiateReturnValue, StorageDeposit, +}; use scale_info::TypeInfo; use smallvec::Array; use sp_runtime::{ diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index 4f63104ef26..76fd012852a 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -30,10 +30,9 @@ use crate::{ }, exec::{Frame, Key}, migration::codegen::LATEST_MIGRATION_VERSION, - primitives::CodeUploadReturnValue, storage::DeletionQueueManager, tests::test_utils::{get_contract, get_contract_checked}, - wasm::{Determinism, ReturnErrorCode as RuntimeReturnCode}, + wasm::{Determinism, ReturnCode as RuntimeReturnCode}, weights::WeightInfo, BalanceOf, Code, CodeHash, CodeInfoOf, CollectEvents, Config, ContractInfo, ContractInfoOf, DebugInfo, DefaultAddressGenerator, DeletionQueueCounter, Error, HoldReason, @@ -43,7 +42,6 @@ use assert_matches::assert_matches; use codec::Encode; use frame_support::{ assert_err, assert_err_ignore_postinfo, assert_err_with_weight, assert_noop, assert_ok, - derive_impl, dispatch::{DispatchErrorWithPostInfo, PostDispatchInfo}, parameter_types, storage::child, @@ -56,6 +54,7 @@ use frame_support::{ }; use frame_system::{EventRecord, Phase}; use pallet_contracts_fixtures::compile_module; +use pallet_contracts_primitives::CodeUploadReturnValue; use pretty_assertions::{assert_eq, assert_ne}; use sp_core::ByteArray; use sp_io::hashing::blake2_256; @@ -333,8 +332,6 @@ parameter_types! { ); pub static ExistentialDeposit: u64 = 1; } - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = BlockWeights; diff --git a/substrate/frame/contracts/src/tests/test_debug.rs b/substrate/frame/contracts/src/tests/test_debug.rs index c9b6557bbb9..2d7ed474365 100644 --- a/substrate/frame/contracts/src/tests/test_debug.rs +++ b/substrate/frame/contracts/src/tests/test_debug.rs @@ -18,10 +18,10 @@ use super::*; use crate::{ debug::{CallInterceptor, CallSpan, ExecResult, ExportedFunction, Tracing}, - primitives::ExecReturnValue, AccountIdOf, }; use frame_support::traits::Currency; +use pallet_contracts_primitives::ExecReturnValue; use pretty_assertions::assert_eq; use std::cell::RefCell; diff --git a/substrate/frame/contracts/src/wasm/mod.rs b/substrate/frame/contracts/src/wasm/mod.rs index 448c0dd7496..77e94b16777 100644 --- a/substrate/frame/contracts/src/wasm/mod.rs +++ b/substrate/frame/contracts/src/wasm/mod.rs @@ -24,13 +24,13 @@ mod runtime; #[cfg(doc)] pub use crate::wasm::runtime::api_doc; +#[cfg(test)] +pub use tests::MockExt; + pub use crate::wasm::runtime::{ - AllowDeprecatedInterface, AllowUnstableInterface, Environment, ReturnErrorCode, Runtime, + AllowDeprecatedInterface, AllowUnstableInterface, CallFlags, Environment, ReturnCode, Runtime, RuntimeCosts, }; -pub use pallet_contracts_uapi::ReturnFlags; -#[cfg(test)] -pub use tests::MockExt; use crate::{ exec::{ExecResult, Executable, ExportedFunction, Ext}, @@ -436,7 +436,6 @@ mod tests { use crate::{ exec::{AccountIdOf, ErrorOrigin, ExecError, Executable, Ext, Key, SeedOf}, gas::GasMeter, - primitives::ExecReturnValue, storage::WriteOutcome, tests::{RuntimeCall, Test, ALICE, BOB}, BalanceOf, CodeHash, Error, Origin, Pallet as Contracts, @@ -446,7 +445,7 @@ mod tests { assert_err, assert_ok, dispatch::DispatchResultWithPostInfo, weights::Weight, }; use frame_system::pallet_prelude::BlockNumberFor; - use pallet_contracts_uapi::ReturnFlags; + use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags}; use pretty_assertions::assert_eq; use sp_core::H256; use sp_runtime::DispatchError; @@ -1507,7 +1506,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -1532,7 +1531,7 @@ mod tests { ) ;; Find out the size of the buffer - (local.set $buf_size + (set_local $buf_size (i32.load (i32.const 32)) ) @@ -1540,7 +1539,7 @@ mod tests { (call $seal_return (i32.const 0) (i32.const 36) - (local.get $buf_size) + (get_local $buf_size) ) ;; env:seal_return doesn't return, so this is effectively unreachable. @@ -1576,7 +1575,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -1634,7 +1633,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -1681,7 +1680,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -1727,7 +1726,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -1774,7 +1773,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -1837,7 +1836,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -1926,7 +1925,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -1967,7 +1966,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -2014,7 +2013,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -2068,7 +2067,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -2138,7 +2137,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -2328,7 +2327,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -2740,7 +2739,7 @@ mod tests { let result = execute(CODE, input, &mut ext).unwrap(); assert_eq!( u32::from_le_bytes(result.data[0..4].try_into().unwrap()), - ReturnErrorCode::KeyNotFound as u32 + ReturnCode::KeyNotFound as u32 ); // value exists @@ -2748,7 +2747,7 @@ mod tests { let result = execute(CODE, input, &mut ext).unwrap(); assert_eq!( u32::from_le_bytes(result.data[0..4].try_into().unwrap()), - ReturnErrorCode::Success as u32 + ReturnCode::Success as u32 ); assert_eq!(ext.storage.get(&[1u8; 64].to_vec()).unwrap(), &[42u8]); assert_eq!(&result.data[4..], &[42u8]); @@ -2758,7 +2757,7 @@ mod tests { let result = execute(CODE, input, &mut ext).unwrap(); assert_eq!( u32::from_le_bytes(result.data[0..4].try_into().unwrap()), - ReturnErrorCode::Success as u32 + ReturnCode::Success as u32 ); assert_eq!(ext.storage.get(&[2u8; 19].to_vec()), Some(&vec![])); assert_eq!(&result.data[4..], &([] as [u8; 0])); @@ -2921,7 +2920,7 @@ mod tests { let result = execute(CODE, input, &mut ext).unwrap(); assert_eq!( u32::from_le_bytes(result.data[0..4].try_into().unwrap()), - ReturnErrorCode::KeyNotFound as u32 + ReturnCode::KeyNotFound as u32 ); // value did exist -> value returned @@ -2929,7 +2928,7 @@ mod tests { let result = execute(CODE, input, &mut ext).unwrap(); assert_eq!( u32::from_le_bytes(result.data[0..4].try_into().unwrap()), - ReturnErrorCode::Success as u32 + ReturnCode::Success as u32 ); assert_eq!(ext.storage.get(&[1u8; 64].to_vec()), None); assert_eq!(&result.data[4..], &[42u8]); @@ -2939,7 +2938,7 @@ mod tests { let result = execute(CODE, input, &mut ext).unwrap(); assert_eq!( u32::from_le_bytes(result.data[0..4].try_into().unwrap()), - ReturnErrorCode::Success as u32 + ReturnCode::Success as u32 ); assert_eq!(ext.storage.get(&[2u8; 19].to_vec()), None); assert_eq!(&result.data[4..], &[0u8; 0]); @@ -2996,7 +2995,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -3048,7 +3047,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) @@ -3163,18 +3162,18 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) ) (func (export "call") (local $exit_code i32) - (local.set $exit_code + (set_local $exit_code (call $seal_set_code_hash (i32.const 0)) ) (call $assert - (i32.eq (local.get $exit_code) (i32.const 0)) ;; ReturnCode::Success + (i32.eq (get_local $exit_code) (i32.const 0)) ;; ReturnCode::Success ) ) @@ -3203,18 +3202,18 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) ) (func (export "call") (local $return_val i32) - (local.set $return_val + (set_local $return_val (call $reentrance_count) ) (call $assert - (i32.eq (local.get $return_val) (i32.const 12)) + (i32.eq (get_local $return_val) (i32.const 12)) ) ) @@ -3235,18 +3234,18 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) ) (func (export "call") (local $return_val i32) - (local.set $return_val + (set_local $return_val (call $account_reentrance_count (i32.const 0)) ) (call $assert - (i32.eq (local.get $return_val) (i32.const 12)) + (i32.eq (get_local $return_val) (i32.const 12)) ) ) @@ -3268,7 +3267,7 @@ mod tests { (func $assert (param i32) (block $ok (br_if $ok - (local.get 0) + (get_local 0) ) (unreachable) ) diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 871ef05c37e..b3013adb790 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -20,10 +20,10 @@ use crate::{ exec::{ExecError, ExecResult, Ext, Key, TopicOf}, gas::{ChargedAmount, Token}, - primitives::ExecReturnValue, schedule::HostFnWeights, BalanceOf, CodeHash, Config, DebugBufferVec, Error, SENTINEL, }; +use bitflags::bitflags; use codec::{Decode, DecodeLimit, Encode, MaxEncodedLen}; use frame_support::{ dispatch::DispatchInfo, @@ -33,8 +33,8 @@ use frame_support::{ traits::Get, weights::Weight, }; +use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags}; use pallet_contracts_proc_macro::define_env; -use pallet_contracts_uapi::{CallFlags, ReturnFlags}; use sp_io::hashing::{blake2_128, blake2_256, keccak_256, sha2_256}; use sp_runtime::{ traits::{Bounded, Zero}, @@ -87,16 +87,55 @@ enum KeyType { Var(u32), } -pub use pallet_contracts_uapi::ReturnErrorCode; +/// Every error that can be returned to a contract when it calls any of the host functions. +/// +/// # Note +/// +/// This enum can be extended in the future: New codes can be added but existing codes +/// will not be changed or removed. This means that any contract **must not** exhaustively +/// match return codes. Instead, contracts should prepare for unknown variants and deal with +/// those errors gracefully in order to be forward compatible. +#[derive(Debug)] +#[repr(u32)] +pub enum ReturnCode { + /// API call successful. + Success = 0, + /// The called function trapped and has its state changes reverted. + /// In this case no output buffer is returned. + CalleeTrapped = 1, + /// The called function ran to completion but decided to revert its state. + /// An output buffer is returned when one was supplied. + CalleeReverted = 2, + /// The passed key does not exist in storage. + KeyNotFound = 3, + /// See [`Error::TransferFailed`]. + TransferFailed = 5, + /// No code could be found at the supplied code hash. + CodeNotFound = 7, + /// The contract that was called is no contract (a plain account). + NotCallable = 8, + /// The call dispatched by `seal_call_runtime` was executed but returned an error. + CallRuntimeFailed = 10, + /// ECDSA pubkey recovery failed (most probably wrong recovery id or signature), or + /// ECDSA compressed pubkey conversion into Ethereum address failed (most probably + /// wrong pubkey provided). + EcdsaRecoverFailed = 11, + /// sr25519 signature verification failed. + Sr25519VerifyFailed = 12, + /// The `xcm_execute` call failed. + XcmExecutionFailed = 13, + /// The `xcm_send` call failed. + XcmSendFailed = 14, +} parameter_types! { /// Getter types used by [`crate::api_doc::Current::call_runtime`] - const CallRuntimeFailed: ReturnErrorCode = ReturnErrorCode::CallRuntimeFailed; + const CallRuntimeFailed: ReturnCode = ReturnCode::CallRuntimeFailed; /// Getter types used by [`crate::api_doc::Current::xcm_execute`] - const XcmExecutionFailed: ReturnErrorCode = ReturnErrorCode::XcmExecutionFailed; + const XcmExecutionFailed: ReturnCode = ReturnCode::XcmExecutionFailed; } -impl From for ReturnErrorCode { +impl From for ReturnCode { fn from(from: ExecReturnValue) -> Self { if from.flags.contains(ReturnFlags::REVERT) { Self::CalleeReverted @@ -106,6 +145,12 @@ impl From for ReturnErrorCode { } } +impl From for u32 { + fn from(code: ReturnCode) -> u32 { + code as u32 + } +} + /// The data passed through when a contract uses `seal_return`. #[derive(RuntimeDebug)] pub struct ReturnData { @@ -366,6 +411,52 @@ impl Token for RuntimeToken { } } +bitflags! { + /// Flags used to change the behaviour of `seal_call` and `seal_delegate_call`. + pub struct CallFlags: u32 { + /// Forward the input of current function to the callee. + /// + /// Supplied input pointers are ignored when set. + /// + /// # Note + /// + /// A forwarding call will consume the current contracts input. Any attempt to + /// access the input after this call returns will lead to [`Error::InputForwarded`]. + /// It does not matter if this is due to calling `seal_input` or trying another + /// forwarding call. Consider using [`Self::CLONE_INPUT`] in order to preserve + /// the input. + const FORWARD_INPUT = 0b0000_0001; + /// Identical to [`Self::FORWARD_INPUT`] but without consuming the input. + /// + /// This adds some additional weight costs to the call. + /// + /// # Note + /// + /// This implies [`Self::FORWARD_INPUT`] and takes precedence when both are set. + const CLONE_INPUT = 0b0000_0010; + /// Do not return from the call but rather return the result of the callee to the + /// callers caller. + /// + /// # Note + /// + /// This makes the current contract completely transparent to its caller by replacing + /// this contracts potential output by the callee ones. Any code after `seal_call` + /// can be safely considered unreachable. + const TAIL_CALL = 0b0000_0100; + /// Allow the callee to reenter into the current contract. + /// + /// Without this flag any reentrancy into the current contract that originates from + /// the callee (or any of its callees) is denied. This includes the first callee: + /// You cannot call into yourself with this flag set. + /// + /// # Note + /// + /// For `seal_delegate_call` should be always unset, otherwise + /// [`Error::InvalidCallFlags`] is returned. + const ALLOW_REENTRY = 0b0000_1000; + } +} + /// The kind of call that should be performed. enum CallType { /// Execute another instantiated contract @@ -512,20 +603,20 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { /// Charge, Run and adjust gas, for executing the given dispatchable. fn call_dispatchable< - ErrorReturnCode: Get, + ErrorReturnCode: Get, F: FnOnce(&mut Self) -> DispatchResultWithPostInfo, >( &mut self, dispatch_info: DispatchInfo, run: F, - ) -> Result { + ) -> Result { use frame_support::dispatch::extract_actual_weight; let charged = self.charge_gas(RuntimeCosts::CallRuntime(dispatch_info.weight))?; let result = run(self); let actual_weight = extract_actual_weight(&result, &dispatch_info); self.adjust_gas(charged, RuntimeCosts::CallRuntime(actual_weight)); match result { - Ok(_) => Ok(ReturnErrorCode::Success), + Ok(_) => Ok(ReturnCode::Success), Err(e) => { if self.ext.append_debug_buffer("") { self.ext.append_debug_buffer("call failed with: "); @@ -716,9 +807,9 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { Ok(()) } - /// Fallible conversion of `DispatchError` to `ReturnErrorCode`. - fn err_into_return_code(from: DispatchError) -> Result { - use ReturnErrorCode::*; + /// Fallible conversion of `DispatchError` to `ReturnCode`. + fn err_into_return_code(from: DispatchError) -> Result { + use ReturnCode::*; let transfer_failed = Error::::TransferFailed.into(); let no_code = Error::::CodeNotFound.into(); @@ -732,8 +823,8 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { } } - /// Fallible conversion of a `ExecResult` to `ReturnErrorCode`. - fn exec_into_return_code(from: ExecResult) -> Result { + /// Fallible conversion of a `ExecResult` to `ReturnCode`. + fn exec_into_return_code(from: ExecResult) -> Result { use crate::exec::ErrorOrigin::Callee; let ExecError { error, origin } = match from { @@ -742,7 +833,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { }; match (error, origin) { - (_, Callee) => Ok(ReturnErrorCode::CalleeTrapped), + (_, Callee) => Ok(ReturnCode::CalleeTrapped), (err, _) => Self::err_into_return_code(err), } } @@ -816,7 +907,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { key_ptr: u32, out_ptr: u32, out_len_ptr: u32, - ) -> Result { + ) -> Result { let charged = self.charge_gas(RuntimeCosts::GetStorage(self.ext.max_value_size()))?; let key = self.decode_key(memory, key_type, key_ptr)?; let outcome = self.ext.get_storage(&key); @@ -831,10 +922,10 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { false, already_charged, )?; - Ok(ReturnErrorCode::Success) + Ok(ReturnCode::Success) } else { self.adjust_gas(charged, RuntimeCosts::GetStorage(0)); - Ok(ReturnErrorCode::KeyNotFound) + Ok(ReturnCode::KeyNotFound) } } @@ -861,7 +952,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { input_data_len: u32, output_ptr: u32, output_len_ptr: u32, - ) -> Result { + ) -> Result { self.charge_gas(call_type.cost())?; let input_data = if flags.contains(CallFlags::CLONE_INPUT) { let input = self.input_data.as_ref().ok_or(Error::::InputForwarded)?; @@ -945,7 +1036,7 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { output_len_ptr: u32, salt_ptr: u32, salt_len: u32, - ) -> Result { + ) -> Result { self.charge_gas(RuntimeCosts::InstantiateBase { input_data_len, salt_len })?; let deposit_limit: BalanceOf<::T> = if deposit_ptr == SENTINEL { BalanceOf::<::T>::zero() @@ -1005,7 +1096,10 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { pub mod env { /// Set the value at the given key in the contract storage. - /// See [`pallet_contracts_uapi::HostFn::set_storage`] + /// + /// Equivalent to the newer [`seal1`][`super::api_doc::Version1::set_storage`] version with the + /// exception of the return type. Still a valid thing to call when not interested in the return + /// value. #[prefixed_alias] fn set_storage( ctx: _, @@ -1018,7 +1112,23 @@ pub mod env { } /// Set the value at the given key in the contract storage. - /// See [`pallet_contracts_uapi::HostFn::set_storage_v1`] + /// + /// This version is to be used with a fixed sized storage key. For runtimes supporting + /// transparent hashing, please use the newer version of this function. + /// + /// The value length must not exceed the maximum defined by the contracts module parameters. + /// Specifying a `value_len` of zero will store an empty value. + /// + /// # Parameters + /// + /// - `key_ptr`: pointer into the linear memory where the location to store the value is placed. + /// - `value_ptr`: pointer into the linear memory where the value to set is placed. + /// - `value_len`: the length of the value in bytes. + /// + /// # Return Value + /// + /// Returns the size of the pre-existing value at the specified key if any. Otherwise + /// `SENTINEL` is returned as a sentinel value. #[version(1)] #[prefixed_alias] fn set_storage( @@ -1032,7 +1142,21 @@ pub mod env { } /// Set the value at the given key in the contract storage. - /// See [`pallet_contracts_uapi::HostFn::set_storage_v2`] + /// + /// The key and value lengths must not exceed the maximums defined by the contracts module + /// parameters. Specifying a `value_len` of zero will store an empty value. + /// + /// # Parameters + /// + /// - `key_ptr`: pointer into the linear memory where the location to store the value is placed. + /// - `key_len`: the length of the key in bytes. + /// - `value_ptr`: pointer into the linear memory where the value to set is placed. + /// - `value_len`: the length of the value in bytes. + /// + /// # Return Value + /// + /// Returns the size of the pre-existing value at the specified key if any. Otherwise + /// `SENTINEL` is returned as a sentinel value. #[version(2)] #[prefixed_alias] fn set_storage( @@ -1047,14 +1171,26 @@ pub mod env { } /// Clear the value at the given key in the contract storage. - /// See [`pallet_contracts_uapi::HostFn::clear_storage`] + /// + /// Equivalent to the newer [`seal1`][`super::api_doc::Version1::clear_storage`] version with + /// the exception of the return type. Still a valid thing to call when not interested in the + /// return value. #[prefixed_alias] fn clear_storage(ctx: _, memory: _, key_ptr: u32) -> Result<(), TrapReason> { ctx.clear_storage(memory, KeyType::Fix, key_ptr).map(|_| ()) } /// Clear the value at the given key in the contract storage. - /// See [`pallet_contracts_uapi::HostFn::clear_storage_v1`] + /// + /// # Parameters + /// + /// - `key_ptr`: pointer into the linear memory where the key is placed. + /// - `key_len`: the length of the key in bytes. + /// + /// # Return Value + /// + /// Returns the size of the pre-existing value at the specified key if any. Otherwise + /// `SENTINEL` is returned as a sentinel value. #[version(1)] #[prefixed_alias] fn clear_storage(ctx: _, memory: _, key_ptr: u32, key_len: u32) -> Result { @@ -1062,7 +1198,20 @@ pub mod env { } /// Retrieve the value under the given key from storage. - /// See [`pallet_contracts_uapi::HostFn::get_storage`] + /// + /// This version is to be used with a fixed sized storage key. For runtimes supporting + /// transparent hashing, please use the newer version of this function. + /// + /// # Parameters + /// + /// - `key_ptr`: pointer into the linear memory where the key of the requested value is placed. + /// - `out_ptr`: pointer to the linear memory where the value is written to. + /// - `out_len_ptr`: in-out pointer into linear memory where the buffer length is read from and + /// the value length is written to. + /// + /// # Errors + /// + /// `ReturnCode::KeyNotFound` #[prefixed_alias] fn get_storage( ctx: _, @@ -1070,12 +1219,28 @@ pub mod env { key_ptr: u32, out_ptr: u32, out_len_ptr: u32, - ) -> Result { + ) -> Result { ctx.get_storage(memory, KeyType::Fix, key_ptr, out_ptr, out_len_ptr) } /// Retrieve the value under the given key from storage. - /// See [`pallet_contracts_uapi::HostFn::get_storage_v1`] + /// + /// This version is to be used with a fixed sized storage key. For runtimes supporting + /// transparent hashing, please use the newer version of this function. + /// + /// The key length must not exceed the maximum defined by the contracts module parameter. + /// + /// # Parameters + /// + /// - `key_ptr`: pointer into the linear memory where the key of the requested value is placed. + /// - `key_len`: the length of the key in bytes. + /// - `out_ptr`: pointer to the linear memory where the value is written to. + /// - `out_len_ptr`: in-out pointer into linear memory where the buffer length is read from and + /// the value length is written to. + /// + /// # Errors + /// + /// - `ReturnCode::KeyNotFound` #[version(1)] #[prefixed_alias] fn get_storage( @@ -1085,19 +1250,41 @@ pub mod env { key_len: u32, out_ptr: u32, out_len_ptr: u32, - ) -> Result { + ) -> Result { ctx.get_storage(memory, KeyType::Var(key_len), key_ptr, out_ptr, out_len_ptr) } /// Checks whether there is a value stored under the given key. - /// See [`pallet_contracts_uapi::HostFn::contains_storage`] + /// + /// This version is to be used with a fixed sized storage key. For runtimes supporting + /// transparent hashing, please use the newer version of this function. + /// + /// # Parameters + /// + /// - `key_ptr`: pointer into the linear memory where the key of the requested value is placed. + /// + /// # Return Value + /// + /// Returns the size of the pre-existing value at the specified key if any. Otherwise + /// `SENTINEL` is returned as a sentinel value. #[prefixed_alias] fn contains_storage(ctx: _, memory: _, key_ptr: u32) -> Result { ctx.contains_storage(memory, KeyType::Fix, key_ptr) } /// Checks whether there is a value stored under the given key. - /// See [`pallet_contracts_uapi::HostFn::contains_storage_v1`] + /// + /// The key length must not exceed the maximum defined by the contracts module parameter. + /// + /// # Parameters + /// + /// - `key_ptr`: pointer into the linear memory where the key of the requested value is placed. + /// - `key_len`: the length of the key in bytes. + /// + /// # Return Value + /// + /// Returns the size of the pre-existing value at the specified key if any. Otherwise + /// `SENTINEL` is returned as a sentinel value. #[version(1)] #[prefixed_alias] fn contains_storage(ctx: _, memory: _, key_ptr: u32, key_len: u32) -> Result { @@ -1105,7 +1292,18 @@ pub mod env { } /// Retrieve and remove the value under the given key from storage. - /// See [`pallet_contracts_uapi::HostFn::take_storage`] + /// + /// # Parameters + /// + /// - `key_ptr`: pointer into the linear memory where the key of the requested value is placed. + /// - `key_len`: the length of the key in bytes. + /// - `out_ptr`: pointer to the linear memory where the value is written to. + /// - `out_len_ptr`: in-out pointer into linear memory where the buffer length is read from and + /// the value length is written to. + /// + /// # Errors + /// + /// - `ReturnCode::KeyNotFound` #[prefixed_alias] fn take_storage( ctx: _, @@ -1114,7 +1312,7 @@ pub mod env { key_len: u32, out_ptr: u32, out_len_ptr: u32, - ) -> Result { + ) -> Result { let charged = ctx.charge_gas(RuntimeCosts::TakeStorage(ctx.ext.max_value_size()))?; ensure!( key_len <= <::T as Config>::MaxStorageKeyLen::get(), @@ -1128,15 +1326,27 @@ pub mod env { )? { ctx.adjust_gas(charged, RuntimeCosts::TakeStorage(value.len() as u32)); ctx.write_sandbox_output(memory, out_ptr, out_len_ptr, &value, false, already_charged)?; - Ok(ReturnErrorCode::Success) + Ok(ReturnCode::Success) } else { ctx.adjust_gas(charged, RuntimeCosts::TakeStorage(0)); - Ok(ReturnErrorCode::KeyNotFound) + Ok(ReturnCode::KeyNotFound) } } /// Transfer some value to another account. - /// See [`pallet_contracts_uapi::HostFn::transfer`]. + /// + /// # Parameters + /// + /// - `account_ptr`: a pointer to the address of the beneficiary account Should be decodable as + /// an `T::AccountId`. Traps otherwise. + /// - `account_len`: length of the address buffer. + /// - `value_ptr`: a pointer to the buffer with value, how much value to send. Should be + /// decodable as a `T::Balance`. Traps otherwise. + /// - `value_len`: length of the value buffer. + /// + /// # Errors + /// + /// - `ReturnCode::TransferFailed` #[prefixed_alias] fn transfer( ctx: _, @@ -1145,14 +1355,14 @@ pub mod env { _account_len: u32, value_ptr: u32, _value_len: u32, - ) -> Result { + ) -> Result { ctx.charge_gas(RuntimeCosts::Transfer)?; let callee: <::T as frame_system::Config>::AccountId = ctx.read_sandbox_memory_as(memory, account_ptr)?; let value: BalanceOf<::T> = ctx.read_sandbox_memory_as(memory, value_ptr)?; let result = ctx.ext.transfer(&callee, value); match result { - Ok(()) => Ok(ReturnErrorCode::Success), + Ok(()) => Ok(ReturnCode::Success), Err(err) => { let code = Runtime::::err_into_return_code(err)?; Ok(code) @@ -1162,11 +1372,17 @@ pub mod env { /// Make a call to another contract. /// + /// # New version available + /// + /// This is equivalent to calling the newer version of this function with + /// `flags` set to `ALLOW_REENTRY`. See the newer version for documentation. + /// /// # Note /// - /// The values `_callee_len` and `_value_len` are ignored because the encoded sizes of those - /// types are fixed through [`codec::MaxEncodedLen`]. The fields exist for backwards - /// compatibility. Consider switching to the newest version of this function. + /// The values `_callee_len` and `_value_len` are ignored because the encoded sizes + /// of those types are fixed through + /// [`codec::MaxEncodedLen`]. The fields exist + /// for backwards compatibility. Consider switching to the newest version of this function. #[prefixed_alias] fn call( ctx: _, @@ -1180,7 +1396,7 @@ pub mod env { input_data_len: u32, output_ptr: u32, output_len_ptr: u32, - ) -> Result { + ) -> Result { ctx.call( memory, CallFlags::ALLOW_REENTRY, @@ -1198,7 +1414,10 @@ pub mod env { } /// Make a call to another contract. - /// See [`pallet_contracts_uapi::HostFn::call_v1`]. + /// + /// Equivalent to the newer [`seal2`][`super::api_doc::Version2::call`] version but works with + /// *ref_time* Weight only. It is recommended to switch to the latest version, once it's + /// stabilized. #[version(1)] #[prefixed_alias] fn call( @@ -1212,7 +1431,7 @@ pub mod env { input_data_len: u32, output_ptr: u32, output_len_ptr: u32, - ) -> Result { + ) -> Result { ctx.call( memory, CallFlags::from_bits(flags).ok_or(Error::::InvalidCallFlags)?, @@ -1230,7 +1449,39 @@ pub mod env { } /// Make a call to another contract. - /// See [`pallet_contracts_uapi::HostFn::call_v2`]. + /// + /// The callees output buffer is copied to `output_ptr` and its length to `output_len_ptr`. + /// The copy of the output buffer can be skipped by supplying the sentinel value + /// of `SENTINEL` to `output_ptr`. + /// + /// # Parameters + /// + /// - `flags`: See `crate::wasm::runtime::CallFlags` for a documentation of the supported flags. + /// - `callee_ptr`: a pointer to the address of the callee contract. Should be decodable as an + /// `T::AccountId`. Traps otherwise. + /// - `ref_time_limit`: how much *ref_time* Weight to devote to the execution. + /// - `proof_size_limit`: how much *proof_size* Weight to devote to the execution. + /// - `deposit_ptr`: a pointer to the buffer with value of the storage deposit limit for the + /// call. Should be decodable as a `T::Balance`. Traps otherwise. Passing `SENTINEL` means + /// setting no specific limit for the call, which implies storage usage up to the limit of the + /// parent call. + /// - `value_ptr`: a pointer to the buffer with value, how much value to send. Should be + /// decodable as a `T::Balance`. Traps otherwise. + /// - `input_data_ptr`: a pointer to a buffer to be used as input data to the callee. + /// - `input_data_len`: length of the input data buffer. + /// - `output_ptr`: a pointer where the output buffer is copied to. + /// - `output_len_ptr`: in-out pointer to where the length of the buffer is read from and the + /// actual length is written to. + /// + /// # Errors + /// + /// An error means that the call wasn't successful output buffer is returned unless + /// stated otherwise. + /// + /// - `ReturnCode::CalleeReverted`: Output buffer is returned. + /// - `ReturnCode::CalleeTrapped` + /// - `ReturnCode::TransferFailed` + /// - `ReturnCode::NotCallable` #[version(2)] #[unstable] fn call( @@ -1246,7 +1497,7 @@ pub mod env { input_data_len: u32, output_ptr: u32, output_len_ptr: u32, - ) -> Result { + ) -> Result { ctx.call( memory, CallFlags::from_bits(flags).ok_or(Error::::InvalidCallFlags)?, @@ -1264,7 +1515,29 @@ pub mod env { } /// Execute code in the context (storage, caller, value) of the current contract. - /// See [`pallet_contracts_uapi::HostFn::delegate_call`]. + /// + /// Reentrancy protection is always disabled since the callee is allowed + /// to modify the callers storage. This makes going through a reentrancy attack + /// unnecessary for the callee when it wants to exploit the caller. + /// + /// # Parameters + /// + /// - `flags`: see `crate::wasm::runtime::CallFlags` for a documentation of the supported flags. + /// - `code_hash`: a pointer to the hash of the code to be called. + /// - `input_data_ptr`: a pointer to a buffer to be used as input data to the callee. + /// - `input_data_len`: length of the input data buffer. + /// - `output_ptr`: a pointer where the output buffer is copied to. + /// - `output_len_ptr`: in-out pointer to where the length of the buffer is read from and the + /// actual length is written to. + /// + /// # Errors + /// + /// An error means that the call wasn't successful and no output buffer is returned unless + /// stated otherwise. + /// + /// - `ReturnCode::CalleeReverted`: Output buffer is returned. + /// - `ReturnCode::CalleeTrapped` + /// - `ReturnCode::CodeNotFound` #[prefixed_alias] fn delegate_call( ctx: _, @@ -1275,7 +1548,7 @@ pub mod env { input_data_len: u32, output_ptr: u32, output_len_ptr: u32, - ) -> Result { + ) -> Result { ctx.call( memory, CallFlags::from_bits(flags).ok_or(Error::::InvalidCallFlags)?, @@ -1288,7 +1561,11 @@ pub mod env { } /// Instantiate a contract with the specified code hash. - /// See [`pallet_contracts_uapi::HostFn::instantiate`]. + /// + /// # New version available + /// + /// This is equivalent to calling the newer version of this function. The newer version + /// drops the now unnecessary length fields. /// /// # Note /// @@ -1312,7 +1589,7 @@ pub mod env { output_len_ptr: u32, salt_ptr: u32, salt_len: u32, - ) -> Result { + ) -> Result { ctx.instantiate( memory, code_hash_ptr, @@ -1331,7 +1608,10 @@ pub mod env { } /// Instantiate a contract with the specified code hash. - /// See [`pallet_contracts_uapi::HostFn::instantiate_v1`]. + /// + /// Equivalent to the newer [`seal2`][`super::api_doc::Version2::instantiate`] version but works + /// with *ref_time* Weight only. It is recommended to switch to the latest version, once it's + /// stabilized. #[version(1)] #[prefixed_alias] fn instantiate( @@ -1348,7 +1628,7 @@ pub mod env { output_len_ptr: u32, salt_ptr: u32, salt_len: u32, - ) -> Result { + ) -> Result { ctx.instantiate( memory, code_hash_ptr, @@ -1367,7 +1647,48 @@ pub mod env { } /// Instantiate a contract with the specified code hash. - /// See [`pallet_contracts_uapi::HostFn::instantiate_v2`]. + /// + /// This function creates an account and executes the constructor defined in the code specified + /// by the code hash. The address of this new account is copied to `address_ptr` and its length + /// to `address_len_ptr`. The constructors output buffer is copied to `output_ptr` and its + /// length to `output_len_ptr`. The copy of the output buffer and address can be skipped by + /// supplying the sentinel value of `SENTINEL` to `output_ptr` or `address_ptr`. + /// + /// # Parameters + /// + /// - `code_hash_ptr`: a pointer to the buffer that contains the initializer code. + /// - `ref_time_limit`: how much *ref_time* Weight to devote to the execution. + /// - `proof_size_limit`: how much *proof_size* Weight to devote to the execution. + /// - `deposit_ptr`: a pointer to the buffer with value of the storage deposit limit for + /// instantiation. Should be decodable as a `T::Balance`. Traps otherwise. Passing `SENTINEL` + /// means setting no specific limit for the call, which implies storage usage up to the limit + /// of the parent call. + /// - `value_ptr`: a pointer to the buffer with value, how much value to send. Should be + /// decodable as a `T::Balance`. Traps otherwise. + /// - `input_data_ptr`: a pointer to a buffer to be used as input data to the initializer code. + /// - `input_data_len`: length of the input data buffer. + /// - `address_ptr`: a pointer where the new account's address is copied to. `SENTINEL` means + /// not to copy. + /// - `address_len_ptr`: pointer to where put the length of the address. + /// - `output_ptr`: a pointer where the output buffer is copied to. `SENTINEL` means not to + /// copy. + /// - `output_len_ptr`: in-out pointer to where the length of the buffer is read from and the + /// actual length is written to. + /// - `salt_ptr`: Pointer to raw bytes used for address derivation. See `fn contract_address`. + /// - `salt_len`: length in bytes of the supplied salt. + /// + /// # Errors + /// + /// Please consult the `ReturnCode` enum declaration for more information on those + /// errors. Here we only note things specific to this function. + /// + /// An error means that the account wasn't created and no address or output buffer + /// is returned unless stated otherwise. + /// + /// - `ReturnCode::CalleeReverted`: Output buffer is returned. + /// - `ReturnCode::CalleeTrapped` + /// - `ReturnCode::TransferFailed` + /// - `ReturnCode::CodeNotFound` #[version(2)] #[unstable] fn instantiate( @@ -1386,7 +1707,7 @@ pub mod env { output_len_ptr: u32, salt_ptr: u32, salt_len: u32, - ) -> Result { + ) -> Result { ctx.instantiate( memory, code_hash_ptr, @@ -1405,7 +1726,11 @@ pub mod env { } /// Remove the calling account and transfer remaining balance. - /// See [`pallet_contracts_uapi::HostFn::terminate`]. + /// + /// # New version available + /// + /// This is equivalent to calling the newer version of this function. The newer version + /// drops the now unnecessary length fields. /// /// # Note /// @@ -1423,7 +1748,20 @@ pub mod env { } /// Remove the calling account and transfer remaining **free** balance. - /// See [`pallet_contracts_uapi::HostFn::terminate_v1`]. + /// + /// This function never returns. Either the termination was successful and the + /// execution of the destroyed contract is halted. Or it failed during the termination + /// which is considered fatal and results in a trap + rollback. + /// + /// - `beneficiary_ptr`: a pointer to the address of the beneficiary account where all where all + /// remaining funds of the caller are transferred. Should be decodable as an `T::AccountId`. + /// Traps otherwise. + /// + /// # Traps + /// + /// - The contract is live i.e is already on the call stack. + /// - Failed to send the balance to the beneficiary. + /// - The deletion queue is full. #[version(1)] #[prefixed_alias] fn terminate(ctx: _, memory: _, beneficiary_ptr: u32) -> Result<(), TrapReason> { @@ -1431,7 +1769,15 @@ pub mod env { } /// Stores the input passed by the caller into the supplied buffer. - /// See [`pallet_contracts_uapi::HostFn::input`]. + /// + /// The value is stored to linear memory at the address pointed to by `out_ptr`. + /// `out_len_ptr` must point to a u32 value that describes the available space at + /// `out_ptr`. This call overwrites it with the size of the value. If the available + /// space at `out_ptr` is less than the size of the value a trap is triggered. + /// + /// # Note + /// + /// This function traps if the input was previously forwarded by a [`call()`][`Self::call()`]. #[prefixed_alias] fn input(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { ctx.charge_gas(RuntimeCosts::InputBase)?; @@ -1447,7 +1793,22 @@ pub mod env { } /// Cease contract execution and save a data buffer as a result of the execution. - /// See [`pallet_contracts_uapi::HostFn::return_value`]. + /// + /// This function never returns as it stops execution of the caller. + /// This is the only way to return a data buffer to the caller. Returning from + /// execution without calling this function is equivalent to calling: + /// ```nocompile + /// seal_return(0, 0, 0); + /// ``` + /// + /// The flags argument is a bitfield that can be used to signal special return + /// conditions to the supervisor: + /// --- lsb --- + /// bit 0 : REVERT - Revert all storage changes made by the caller. + /// bit [1, 31]: Reserved for future use. + /// --- msb --- + /// + /// Using a reserved bit triggers a trap. fn seal_return( ctx: _, memory: _, @@ -1463,7 +1824,18 @@ pub mod env { } /// Stores the address of the caller into the supplied buffer. - /// See [`pallet_contracts_uapi::HostFn::caller`]. + /// + /// The value is stored to linear memory at the address pointed to by `out_ptr`. + /// `out_len_ptr` must point to a u32 value that describes the available space at + /// `out_ptr`. This call overwrites it with the size of the value. If the available + /// space at `out_ptr` is less than the size of the value a trap is triggered. + /// + /// If this is a top-level call (i.e. initiated by an extrinsic) the origin address of the + /// extrinsic will be returned. Otherwise, if this call is initiated by another contract then + /// the address of the contract will be returned. The value is encoded as T::AccountId. + /// + /// If there is no address associated with the caller (e.g. because the caller is root) then + /// it traps with `BadOrigin`. #[prefixed_alias] fn caller(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { ctx.charge_gas(RuntimeCosts::Caller)?; @@ -1479,7 +1851,13 @@ pub mod env { } /// Checks whether a specified address belongs to a contract. - /// See [`pallet_contracts_uapi::HostFn::is_contract`]. + /// + /// # Parameters + /// + /// - `account_ptr`: a pointer to the address of the beneficiary account Should be decodable as + /// an `T::AccountId`. Traps otherwise. + /// + /// Returned value is a `u32`-encoded boolean: (0 = false, 1 = true). #[prefixed_alias] fn is_contract(ctx: _, memory: _, account_ptr: u32) -> Result { ctx.charge_gas(RuntimeCosts::IsContract)?; @@ -1490,7 +1868,18 @@ pub mod env { } /// Retrieve the code hash for a specified contract address. - /// See [`pallet_contracts_uapi::HostFn::code_hash`]. + /// + /// # Parameters + /// + /// - `account_ptr`: a pointer to the address in question. Should be decodable as an + /// `T::AccountId`. Traps otherwise. + /// - `out_ptr`: pointer to the linear memory where the returning value is written to. + /// - `out_len_ptr`: in-out pointer into linear memory where the buffer length is read from and + /// the value length is written to. + /// + /// # Errors + /// + /// - `ReturnCode::KeyNotFound` #[prefixed_alias] fn code_hash( ctx: _, @@ -1498,7 +1887,7 @@ pub mod env { account_ptr: u32, out_ptr: u32, out_len_ptr: u32, - ) -> Result { + ) -> Result { ctx.charge_gas(RuntimeCosts::CodeHash)?; let address: <::T as frame_system::Config>::AccountId = ctx.read_sandbox_memory_as(memory, account_ptr)?; @@ -1511,14 +1900,19 @@ pub mod env { false, already_charged, )?; - Ok(ReturnErrorCode::Success) + Ok(ReturnCode::Success) } else { - Ok(ReturnErrorCode::KeyNotFound) + Ok(ReturnCode::KeyNotFound) } } /// Retrieve the code hash of the currently executing contract. - /// See [`pallet_contracts_uapi::HostFn::own_code_hash`]. + /// + /// # Parameters + /// + /// - `out_ptr`: pointer to the linear memory where the returning value is written to. + /// - `out_len_ptr`: in-out pointer into linear memory where the buffer length is read from and + /// the value length is written to. #[prefixed_alias] fn own_code_hash(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { ctx.charge_gas(RuntimeCosts::OwnCodeHash)?; @@ -1534,7 +1928,15 @@ pub mod env { } /// Checks whether the caller of the current contract is the origin of the whole call stack. - /// See [`pallet_contracts_uapi::HostFn::caller_is_origin`]. + /// + /// Prefer this over [`is_contract()`][`Self::is_contract`] when checking whether your contract + /// is being called by a contract or a plain account. The reason is that it performs better + /// since it does not need to do any storage lookups. + /// + /// A return value of `true` indicates that this contract is being called by a plain account + /// and `false` indicates that the caller is another contract. + /// + /// Returned value is a `u32`-encoded boolean: (`0 = false`, `1 = true`). #[prefixed_alias] fn caller_is_origin(ctx: _, _memory: _) -> Result { ctx.charge_gas(RuntimeCosts::CallerIsOrigin)?; @@ -1542,7 +1944,14 @@ pub mod env { } /// Checks whether the caller of the current contract is root. - /// See [`pallet_contracts_uapi::HostFn::caller_is_root`]. + /// + /// Note that only the origin of the call stack can be root. Hence this function returning + /// `true` implies that the contract is being called by the origin. + /// + /// A return value of `true` indicates that this contract is being called by a root origin, + /// and `false` indicates that the caller is a signed origin. + /// + /// Returned value is a `u32`-encoded boolean: (`0 = false`, `1 = true`). #[unstable] fn caller_is_root(ctx: _, _memory: _) -> Result { ctx.charge_gas(RuntimeCosts::CallerIsRoot)?; @@ -1550,7 +1959,11 @@ pub mod env { } /// Stores the address of the current contract into the supplied buffer. - /// See [`pallet_contracts_uapi::HostFn::address`]. + /// + /// The value is stored to linear memory at the address pointed to by `out_ptr`. + /// `out_len_ptr` must point to a u32 value that describes the available space at + /// `out_ptr`. This call overwrites it with the size of the value. If the available + /// space at `out_ptr` is less than the size of the value a trap is triggered. #[prefixed_alias] fn address(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { ctx.charge_gas(RuntimeCosts::Address)?; @@ -1565,7 +1978,10 @@ pub mod env { } /// Stores the price for the specified amount of gas into the supplied buffer. - /// See [`pallet_contracts_uapi::HostFn::weight_to_fee`]. + /// + /// Equivalent to the newer [`seal1`][`super::api_doc::Version2::weight_to_fee`] version but + /// works with *ref_time* Weight only. It is recommended to switch to the latest version, once + /// it's stabilized. #[prefixed_alias] fn weight_to_fee( ctx: _, @@ -1587,7 +2003,21 @@ pub mod env { } /// Stores the price for the specified amount of weight into the supplied buffer. - /// See [`pallet_contracts_uapi::HostFn::weight_to_fee_v1`]. + /// + /// # Parameters + /// + /// - `out_ptr`: pointer to the linear memory where the returning value is written to. If the + /// available space at `out_ptr` is less than the size of the value a trap is triggered. + /// - `out_len_ptr`: in-out pointer into linear memory where the buffer length is read from and + /// the value length is written to. + /// + /// The data is encoded as `T::Balance`. + /// + /// # Note + /// + /// It is recommended to avoid specifying very small values for `ref_time_limit` and + /// `proof_size_limit` as the prices for a single gas can be smaller than the basic balance + /// unit. #[version(1)] #[unstable] fn weight_to_fee( @@ -1611,7 +2041,10 @@ pub mod env { } /// Stores the weight left into the supplied buffer. - /// See [`pallet_contracts_uapi::HostFn::gas_left`]. + /// + /// Equivalent to the newer [`seal1`][`super::api_doc::Version2::gas_left`] version but + /// works with *ref_time* Weight only. It is recommended to switch to the latest version, once + /// it's stabilized. #[prefixed_alias] fn gas_left(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { ctx.charge_gas(RuntimeCosts::GasLeft)?; @@ -1627,7 +2060,13 @@ pub mod env { } /// Stores the amount of weight left into the supplied buffer. - /// See [`pallet_contracts_uapi::HostFn::gas_left_v1`]. + /// + /// The value is stored to linear memory at the address pointed to by `out_ptr`. + /// `out_len_ptr` must point to a u32 value that describes the available space at + /// `out_ptr`. This call overwrites it with the size of the value. If the available + /// space at `out_ptr` is less than the size of the value a trap is triggered. + /// + /// The data is encoded as Weight. #[version(1)] #[unstable] fn gas_left(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { @@ -1644,7 +2083,13 @@ pub mod env { } /// Stores the *free* balance of the current account into the supplied buffer. - /// See [`pallet_contracts_uapi::HostFn::balance`]. + /// + /// The value is stored to linear memory at the address pointed to by `out_ptr`. + /// `out_len_ptr` must point to a u32 value that describes the available space at + /// `out_ptr`. This call overwrites it with the size of the value. If the available + /// space at `out_ptr` is less than the size of the value a trap is triggered. + /// + /// The data is encoded as `T::Balance`. #[prefixed_alias] fn balance(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { ctx.charge_gas(RuntimeCosts::Balance)?; @@ -1659,7 +2104,13 @@ pub mod env { } /// Stores the value transferred along with this call/instantiate into the supplied buffer. - /// See [`pallet_contracts_uapi::HostFn::value_transferred`]. + /// + /// The value is stored to linear memory at the address pointed to by `out_ptr`. + /// `out_len_ptr` must point to a `u32` value that describes the available space at + /// `out_ptr`. This call overwrites it with the size of the value. If the available + /// space at `out_ptr` is less than the size of the value a trap is triggered. + /// + /// The data is encoded as `T::Balance`. #[prefixed_alias] fn value_transferred( ctx: _, @@ -1759,7 +2210,11 @@ pub mod env { } /// Load the latest block timestamp into the supplied buffer - /// See [`pallet_contracts_uapi::HostFn::now`]. + /// + /// The value is stored to linear memory at the address pointed to by `out_ptr`. + /// `out_len_ptr` must point to a u32 value that describes the available space at + /// `out_ptr`. This call overwrites it with the size of the value. If the available + /// space at `out_ptr` is less than the size of the value a trap is triggered. #[prefixed_alias] fn now(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { ctx.charge_gas(RuntimeCosts::Now)?; @@ -1774,7 +2229,8 @@ pub mod env { } /// Stores the minimum balance (a.k.a. existential deposit) into the supplied buffer. - /// See [`pallet_contracts_uapi::HostFn::minimum_balance`]. + /// + /// The data is encoded as `T::Balance`. #[prefixed_alias] fn minimum_balance( ctx: _, @@ -1922,8 +2378,15 @@ pub mod env { )?) } - /// Deposit a contract event with the data buffer and optional list of topics. - /// See [pallet_contracts_uapi::HostFn::deposit_event] + /// Deposit a contract event with the data buffer and optional list of topics. There is a limit + /// on the maximum number of topics specified by `event_topics`. + /// + /// - `topics_ptr`: a pointer to the buffer of topics encoded as `Vec`. The value of + /// this is ignored if `topics_len` is set to `0`. The topics list can't contain duplicates. + /// - `topics_len`: the length of the topics buffer. Pass 0 if you want to pass an empty + /// vector. + /// - `data_ptr`: a pointer to a raw data buffer which will saved along the event. + /// - `data_len`: the length of the data buffer. #[prefixed_alias] fn deposit_event( ctx: _, @@ -1959,7 +2422,11 @@ pub mod env { } /// Stores the current block number of the current contract into the supplied buffer. - /// See [`pallet_contracts_uapi::HostFn::block_number`]. + /// + /// The value is stored to linear memory at the address pointed to by `out_ptr`. + /// `out_len_ptr` must point to a u32 value that describes the available space at + /// `out_ptr`. This call overwrites it with the size of the value. If the available + /// space at `out_ptr` is less than the size of the value a trap is triggered. #[prefixed_alias] fn block_number(ctx: _, memory: _, out_ptr: u32, out_len_ptr: u32) -> Result<(), TrapReason> { ctx.charge_gas(RuntimeCosts::BlockNumber)?; @@ -1974,7 +2441,22 @@ pub mod env { } /// Computes the SHA2 256-bit hash on the given input buffer. - /// See [`pallet_contracts_uapi::HostFn::hash_sha2_256`]. + /// + /// Returns the result directly into the given output buffer. + /// + /// # Note + /// + /// - The `input` and `output` buffer may overlap. + /// - The output buffer is expected to hold at least 32 bytes (256 bits). + /// - It is the callers responsibility to provide an output buffer that is large enough to hold + /// the expected amount of bytes returned by the chosen hash function. + /// + /// # Parameters + /// + /// - `input_ptr`: the pointer into the linear memory where the input data is placed. + /// - `input_len`: the length of the input data in bytes. + /// - `output_ptr`: the pointer into the linear memory where the output data is placed. The + /// function will write the result directly into this buffer. #[prefixed_alias] fn hash_sha2_256( ctx: _, @@ -1990,7 +2472,22 @@ pub mod env { } /// Computes the KECCAK 256-bit hash on the given input buffer. - /// See [`pallet_contracts_uapi::HostFn::hash_keccak_256`]. + /// + /// Returns the result directly into the given output buffer. + /// + /// # Note + /// + /// - The `input` and `output` buffer may overlap. + /// - The output buffer is expected to hold at least 32 bytes (256 bits). + /// - It is the callers responsibility to provide an output buffer that is large enough to hold + /// the expected amount of bytes returned by the chosen hash function. + /// + /// # Parameters + /// + /// - `input_ptr`: the pointer into the linear memory where the input data is placed. + /// - `input_len`: the length of the input data in bytes. + /// - `output_ptr`: the pointer into the linear memory where the output data is placed. The + /// function will write the result directly into this buffer. #[prefixed_alias] fn hash_keccak_256( ctx: _, @@ -2006,7 +2503,22 @@ pub mod env { } /// Computes the BLAKE2 256-bit hash on the given input buffer. - /// See [`pallet_contracts_uapi::HostFn::hash_blake2_256`]. + /// + /// Returns the result directly into the given output buffer. + /// + /// # Note + /// + /// - The `input` and `output` buffer may overlap. + /// - The output buffer is expected to hold at least 32 bytes (256 bits). + /// - It is the callers responsibility to provide an output buffer that is large enough to hold + /// the expected amount of bytes returned by the chosen hash function. + /// + /// # Parameters + /// + /// - `input_ptr`: the pointer into the linear memory where the input data is placed. + /// - `input_len`: the length of the input data in bytes. + /// - `output_ptr`: the pointer into the linear memory where the output data is placed. The + /// function will write the result directly into this buffer. #[prefixed_alias] fn hash_blake2_256( ctx: _, @@ -2022,7 +2534,22 @@ pub mod env { } /// Computes the BLAKE2 128-bit hash on the given input buffer. - /// See [`pallet_contracts_uapi::HostFn::hash_blake2_128`]. + /// + /// Returns the result directly into the given output buffer. + /// + /// # Note + /// + /// - The `input` and `output` buffer may overlap. + /// - The output buffer is expected to hold at least 16 bytes (128 bits). + /// - It is the callers responsibility to provide an output buffer that is large enough to hold + /// the expected amount of bytes returned by the chosen hash function. + /// + /// # Parameters + /// + /// - `input_ptr`: the pointer into the linear memory where the input data is placed. + /// - `input_len`: the length of the input data in bytes. + /// - `output_ptr`: the pointer into the linear memory where the output data is placed. The + /// function will write the result directly into this buffer. #[prefixed_alias] fn hash_blake2_128( ctx: _, @@ -2038,7 +2565,16 @@ pub mod env { } /// Call into the chain extension provided by the chain if any. - /// See [`pallet_contracts_uapi::HostFn::call_chain_extension`]. + /// + /// Handling of the input values is up to the specific chain extension and so is the + /// return value. The extension can decide to use the inputs as primitive inputs or as + /// in/out arguments by interpreting them as pointers. Any caller of this function + /// must therefore coordinate with the chain that it targets. + /// + /// # Note + /// + /// If no chain extension exists the contract will trap with the `NoChainExtension` + /// module error. #[prefixed_alias] fn call_chain_extension( ctx: _, @@ -2091,7 +2627,7 @@ pub mod env { memory: _, str_ptr: u32, str_len: u32, - ) -> Result { + ) -> Result { let str_len = str_len.min(DebugBufferVec::::bound() as u32); ctx.charge_gas(RuntimeCosts::DebugMessage(str_len))?; if ctx.ext.append_debug_buffer("") { @@ -2100,17 +2636,47 @@ pub mod env { ctx.ext.append_debug_buffer(msg); } } - Ok(ReturnErrorCode::Success) + Ok(ReturnCode::Success) } /// Call some dispatchable of the runtime. - /// See [`frame_support::traits::call_runtime`]. + /// + /// This function decodes the passed in data as the overarching `Call` type of the + /// runtime and dispatches it. The weight as specified in the runtime is charged + /// from the gas meter. Any weight refunds made by the dispatchable are considered. + /// + /// The filter specified by `Config::CallFilter` is attached to the origin of + /// the dispatched call. + /// + /// # Parameters + /// + /// - `call_ptr`: the pointer into the linear memory where the input data is placed. + /// - `call_len`: the length of the input data in bytes. + /// + /// # Return Value + /// + /// Returns `ReturnCode::Success` when the dispatchable was successfully executed and + /// returned `Ok`. When the dispatchable was executed but returned an error + /// `ReturnCode::CallRuntimeFailed` is returned. The full error is not + /// provided because it is not guaranteed to be stable. + /// + /// # Comparison with `ChainExtension` + /// + /// Just as a chain extension this API allows the runtime to extend the functionality + /// of contracts. While making use of this function is generally easier it cannot be + /// used in all cases. Consider writing a chain extension if you need to do perform + /// one of the following tasks: + /// + /// - Return data. + /// - Provide functionality **exclusively** to contracts. + /// - Provide custom weights. + /// - Avoid the need to keep the `Call` data structure stable. fn call_runtime( ctx: _, memory: _, call_ptr: u32, call_len: u32, - ) -> Result { + ) -> Result { use frame_support::dispatch::GetDispatchInfo; ctx.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; let call: ::RuntimeCall = @@ -2121,7 +2687,21 @@ pub mod env { } /// Execute an XCM program locally, using the contract's address as the origin. - /// See [`pallet_contracts_uapi::HostFn::execute_xcm`]. + /// This is equivalent to dispatching `pallet_xcm::execute` through call_runtime, except that + /// the function is called directly instead of being dispatched. + /// + /// # Parameters + /// + /// - `msg_ptr`: the pointer into the linear memory where the [`xcm::prelude::VersionedXcm`] is + /// placed. + /// - `msg_len`: the length of the message in bytes. + /// - `output_ptr`: the pointer into the linear memory where the [`xcm::prelude::Outcome`] + /// message id is placed. + /// + /// # Return Value + /// + /// Returns `ReturnCode::Success` when the XCM was successfully executed. When the XCM + /// execution fails, `ReturnCode::XcmExecutionFailed` is returned. #[unstable] fn xcm_execute( ctx: _, @@ -2129,7 +2709,7 @@ pub mod env { msg_ptr: u32, msg_len: u32, output_ptr: u32, - ) -> Result { + ) -> Result { use frame_support::dispatch::DispatchInfo; use xcm::VersionedXcm; use xcm_builder::{ExecuteController, ExecuteControllerWeightInfo}; @@ -2160,7 +2740,23 @@ pub mod env { } /// Send an XCM program from the contract to the specified destination. - /// See [`pallet_contracts_uapi::HostFn::send_xcm`]. + /// This is equivalent to dispatching `pallet_xcm::send` through `call_runtime`, except that + /// the function is called directly instead of being dispatched. + /// + /// # Parameters + /// + /// - `dest_ptr`: the pointer into the linear memory where the + /// [`xcm::prelude::VersionedMultiLocation`] is placed. + /// - `msg_ptr`: the pointer into the linear memory where the [`xcm::prelude::VersionedXcm`] is + /// placed. + /// - `msg_len`: the length of the message in bytes. + /// - `output_ptr`: the pointer into the linear memory where the [`xcm::v3::XcmHash`] message id + /// is placed. + /// + /// # Return Value + /// + /// Returns `ReturnCode::Success` when the message was successfully sent. When the XCM + /// execution fails, `ReturnCode::CallRuntimeFailed` is returned. #[unstable] fn xcm_send( ctx: _, @@ -2169,7 +2765,7 @@ pub mod env { msg_ptr: u32, msg_len: u32, output_ptr: u32, - ) -> Result { + ) -> Result { use xcm::{VersionedMultiLocation, VersionedXcm}; use xcm_builder::{SendController, SendControllerWeightInfo}; @@ -2185,20 +2781,35 @@ pub mod env { match <::Xcm>::send(origin, dest.into(), message.into()) { Ok(message_id) => { ctx.write_sandbox_memory(memory, output_ptr, &message_id.encode())?; - Ok(ReturnErrorCode::Success) + Ok(ReturnCode::Success) }, Err(e) => { if ctx.ext.append_debug_buffer("") { ctx.ext.append_debug_buffer("seal0::xcm_send failed with: "); ctx.ext.append_debug_buffer(e.into()); }; - Ok(ReturnErrorCode::XcmSendFailed) + Ok(ReturnCode::XcmSendFailed) }, } } /// Recovers the ECDSA public key from the given message hash and signature. - /// See [`pallet_contracts_uapi::HostFn::ecdsa_recover`]. + /// + /// Writes the public key into the given output buffer. + /// Assumes the secp256k1 curve. + /// + /// # Parameters + /// + /// - `signature_ptr`: the pointer into the linear memory where the signature is placed. Should + /// be decodable as a 65 bytes. Traps otherwise. + /// - `message_hash_ptr`: the pointer into the linear memory where the message hash is placed. + /// Should be decodable as a 32 bytes. Traps otherwise. + /// - `output_ptr`: the pointer into the linear memory where the output data is placed. The + /// buffer should be 33 bytes. The function will write the result directly into this buffer. + /// + /// # Errors + /// + /// - `ReturnCode::EcdsaRecoverFailed` #[prefixed_alias] fn ecdsa_recover( ctx: _, @@ -2206,7 +2817,7 @@ pub mod env { signature_ptr: u32, message_hash_ptr: u32, output_ptr: u32, - ) -> Result { + ) -> Result { ctx.charge_gas(RuntimeCosts::EcdsaRecovery)?; let mut signature: [u8; 65] = [0; 65]; @@ -2222,14 +2833,26 @@ pub mod env { // buffer. ctx.write_sandbox_memory(memory, output_ptr, pub_key.as_ref())?; - Ok(ReturnErrorCode::Success) + Ok(ReturnCode::Success) }, - Err(_) => Ok(ReturnErrorCode::EcdsaRecoveryFailed), + Err(_) => Ok(ReturnCode::EcdsaRecoverFailed), } } /// Verify a sr25519 signature - /// See [`pallet_contracts_uapi::HostFn::sr25519_verify`]. + /// + /// # Parameters + /// + /// - `signature_ptr`: the pointer into the linear memory where the signature is placed. Should + /// be a value of 64 bytes. + /// - `pub_key_ptr`: the pointer into the linear memory where the public key is placed. Should + /// be a value of 32 bytes. + /// - `message_len`: the length of the message payload. + /// - `message_ptr`: the pointer into the linear memory where the message is placed. + /// + /// # Errors + /// + /// - `ReturnCode::Sr25519VerifyFailed #[unstable] fn sr25519_verify( ctx: _, @@ -2238,7 +2861,7 @@ pub mod env { pub_key_ptr: u32, message_len: u32, message_ptr: u32, - ) -> Result { + ) -> Result { ctx.charge_gas(RuntimeCosts::Sr25519Verify(message_len))?; let mut signature: [u8; 64] = [0; 64]; @@ -2250,16 +2873,41 @@ pub mod env { let message: Vec = ctx.read_sandbox_memory(memory, message_ptr, message_len)?; if ctx.ext.sr25519_verify(&signature, &message, &pub_key) { - Ok(ReturnErrorCode::Success) + Ok(ReturnCode::Success) } else { - Ok(ReturnErrorCode::Sr25519VerifyFailed) + Ok(ReturnCode::Sr25519VerifyFailed) } } /// Replace the contract code at the specified address with new code. - /// See [`pallet_contracts_uapi::HostFn::set_code_hash`]. + /// + /// # Note + /// + /// There are a couple of important considerations which must be taken into account when + /// using this API: + /// + /// 1. The storage at the code address will remain untouched. This means that contract + /// developers must ensure that the storage layout of the new code is compatible with that of + /// the old code. + /// + /// 2. Contracts using this API can't be assumed as having deterministic addresses. Said another + /// way, when using this API you lose the guarantee that an address always identifies a specific + /// code hash. + /// + /// 3. If a contract calls into itself after changing its code the new call would use + /// the new code. However, if the original caller panics after returning from the sub call it + /// would revert the changes made by [`set_code_hash()`][`Self::set_code_hash`] and the next + /// caller would use the old code. + /// + /// # Parameters + /// + /// - `code_hash_ptr`: A pointer to the buffer that contains the new code hash. + /// + /// # Errors + /// + /// - `ReturnCode::CodeNotFound` #[prefixed_alias] - fn set_code_hash(ctx: _, memory: _, code_hash_ptr: u32) -> Result { + fn set_code_hash(ctx: _, memory: _, code_hash_ptr: u32) -> Result { ctx.charge_gas(RuntimeCosts::SetCodeHash)?; let code_hash: CodeHash<::T> = ctx.read_sandbox_memory_as(memory, code_hash_ptr)?; @@ -2268,19 +2916,33 @@ pub mod env { let code = Runtime::::err_into_return_code(err)?; Ok(code) }, - Ok(()) => Ok(ReturnErrorCode::Success), + Ok(()) => Ok(ReturnCode::Success), } } /// Calculates Ethereum address from the ECDSA compressed public key and stores - /// See [`pallet_contracts_uapi::HostFn::ecdsa_to_eth_address`]. + /// it into the supplied buffer. + /// + /// # Parameters + /// + /// - `key_ptr`: a pointer to the ECDSA compressed public key. Should be decodable as a 33 bytes + /// value. Traps otherwise. + /// - `out_ptr`: the pointer into the linear memory where the output data is placed. The + /// function will write the result directly into this buffer. + /// + /// The value is stored to linear memory at the address pointed to by `out_ptr`. + /// If the available space at `out_ptr` is less than the size of the value a trap is triggered. + /// + /// # Errors + /// + /// - `ReturnCode::EcdsaRecoverFailed` #[prefixed_alias] fn ecdsa_to_eth_address( ctx: _, memory: _, key_ptr: u32, out_ptr: u32, - ) -> Result { + ) -> Result { ctx.charge_gas(RuntimeCosts::EcdsaToEthAddress)?; let mut compressed_key: [u8; 33] = [0; 33]; ctx.read_sandbox_memory_into_buf(memory, key_ptr, &mut compressed_key)?; @@ -2288,15 +2950,18 @@ pub mod env { match result { Ok(eth_address) => { ctx.write_sandbox_memory(memory, out_ptr, eth_address.as_ref())?; - Ok(ReturnErrorCode::Success) + Ok(ReturnCode::Success) }, - Err(_) => Ok(ReturnErrorCode::EcdsaRecoveryFailed), + Err(_) => Ok(ReturnCode::EcdsaRecoverFailed), } } /// Returns the number of times the currently executing contract exists on the call stack in /// addition to the calling instance. - /// See [`pallet_contracts_uapi::HostFn::reentrance_count`]. + /// + /// # Return Value + /// + /// Returns `0` when there is no reentrancy. #[unstable] fn reentrance_count(ctx: _, memory: _) -> Result { ctx.charge_gas(RuntimeCosts::ReentrantCount)?; @@ -2305,7 +2970,14 @@ pub mod env { /// Returns the number of times specified contract exists on the call stack. Delegated calls are /// not counted as separate calls. - /// See [`pallet_contracts_uapi::HostFn::account_reentrance_count`]. + /// + /// # Parameters + /// + /// - `account_ptr`: a pointer to the contract address. + /// + /// # Return Value + /// + /// Returns `0` when the contract does not exist on the call stack. #[unstable] fn account_reentrance_count(ctx: _, memory: _, account_ptr: u32) -> Result { ctx.charge_gas(RuntimeCosts::AccountEntranceCount)?; @@ -2315,14 +2987,19 @@ pub mod env { } /// Returns a nonce that is unique per contract instantiation. - /// See [`pallet_contracts_uapi::HostFn::instantiation_nonce`]. + /// + /// The nonce is incremented for each successful contract instantiation. This is a + /// sensible default salt for contract instantiations. fn instantiation_nonce(ctx: _, _memory: _) -> Result { ctx.charge_gas(RuntimeCosts::InstantationNonce)?; Ok(ctx.ext.nonce()) } /// Adds a new delegate dependency to the contract. - /// See [`pallet_contracts_uapi::HostFn::add_delegate_dependency`]. + /// + /// # Parameters + /// + /// - `code_hash_ptr`: A pointer to the code hash of the dependency. #[unstable] fn add_delegate_dependency(ctx: _, memory: _, code_hash_ptr: u32) -> Result<(), TrapReason> { ctx.charge_gas(RuntimeCosts::AddDelegateDependency)?; @@ -2332,7 +3009,10 @@ pub mod env { } /// Removes the delegate dependency from the contract. - /// see [`pallet_contracts_uapi::HostFn::remove_delegate_dependency`]. + /// + /// # Parameters + /// + /// - `code_hash_ptr`: A pointer to the code hash of the dependency. #[unstable] fn remove_delegate_dependency(ctx: _, memory: _, code_hash_ptr: u32) -> Result<(), TrapReason> { ctx.charge_gas(RuntimeCosts::RemoveDelegateDependency)?; diff --git a/substrate/frame/contracts/uapi/Cargo.toml b/substrate/frame/contracts/uapi/Cargo.toml deleted file mode 100644 index f2901427282..00000000000 --- a/substrate/frame/contracts/uapi/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "pallet-contracts-uapi" -version = "4.0.0-dev" -authors.workspace = true -edition.workspace = true -license = "Apache-2.0" -homepage = "https://substrate.io" -repository.workspace = true -description = "Exposes all the host functions that a contract can import." - -[lints] -workspace = true - -[dependencies] -paste = { version = "1.0", default-features = false } -bitflags = "1.0" -scale-info = { version = "2.10.0", default-features = false, features = ["derive"], optional = true } -scale = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = [ - "derive", - "max-encoded-len", -], optional = true } - -[features] -default = ["scale"] -scale = ["dep:scale", "scale-info"] diff --git a/substrate/frame/contracts/uapi/src/flags.rs b/substrate/frame/contracts/uapi/src/flags.rs deleted file mode 100644 index 32553817fb7..00000000000 --- a/substrate/frame/contracts/uapi/src/flags.rs +++ /dev/null @@ -1,73 +0,0 @@ -// 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 bitflags::bitflags; - -bitflags! { - /// Flags used by a contract to customize exit behaviour. - #[cfg_attr(feature = "scale", derive(scale::Encode, scale::Decode, scale_info::TypeInfo))] - pub struct ReturnFlags: u32 { - /// If this bit is set all changes made by the contract execution are rolled back. - const REVERT = 0x0000_0001; - } -} - -bitflags! { - /// Flags used to change the behaviour of `seal_call` and `seal_delegate_call`. - pub struct CallFlags: u32 { - /// Forward the input of current function to the callee. - /// - /// Supplied input pointers are ignored when set. - /// - /// # Note - /// - /// A forwarding call will consume the current contracts input. Any attempt to - /// access the input after this call returns will lead to [`Error::InputForwarded`]. - /// It does not matter if this is due to calling `seal_input` or trying another - /// forwarding call. Consider using [`Self::CLONE_INPUT`] in order to preserve - /// the input. - const FORWARD_INPUT = 0b0000_0001; - /// Identical to [`Self::FORWARD_INPUT`] but without consuming the input. - /// - /// This adds some additional weight costs to the call. - /// - /// # Note - /// - /// This implies [`Self::FORWARD_INPUT`] and takes precedence when both are set. - const CLONE_INPUT = 0b0000_0010; - /// Do not return from the call but rather return the result of the callee to the - /// callers caller. - /// - /// # Note - /// - /// This makes the current contract completely transparent to its caller by replacing - /// this contracts potential output by the callee ones. Any code after `seal_call` - /// can be safely considered unreachable. - const TAIL_CALL = 0b0000_0100; - /// Allow the callee to reenter into the current contract. - /// - /// Without this flag any reentrancy into the current contract that originates from - /// the callee (or any of its callees) is denied. This includes the first callee: - /// You cannot call into yourself with this flag set. - /// - /// # Note - /// - /// For `seal_delegate_call` should be always unset, otherwise - /// [`Error::InvalidCallFlags`] is returned. - const ALLOW_REENTRY = 0b0000_1000; - } -} diff --git a/substrate/frame/contracts/uapi/src/host.rs b/substrate/frame/contracts/uapi/src/host.rs deleted file mode 100644 index f8b55d3822e..00000000000 --- a/substrate/frame/contracts/uapi/src/host.rs +++ /dev/null @@ -1,793 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -use crate::{CallFlags, Result, ReturnFlags, SENTINEL}; -use paste::paste; - -#[cfg(target_arch = "wasm32")] -mod wasm32; - -#[cfg(target_arch = "riscv32")] -mod riscv32; - -macro_rules! hash_fn { - ( $name:ident, $bytes:literal ) => { - paste! { - #[doc = "Computes the " $name " " $bytes "-bit hash on the given input buffer."] - #[doc = "\n# Notes\n"] - #[doc = "- The `input` and `output` buffer may overlap."] - #[doc = "- The output buffer is expected to hold at least " $bytes " bits."] - #[doc = "- It is the callers responsibility to provide an output buffer that is large enough to hold the expected amount of bytes returned by the hash function."] - #[doc = "\n# Parameters\n"] - #[doc = "- `input`: The input data buffer."] - #[doc = "- `output`: The output buffer to write the hash result to."] - fn [](input: &[u8], output: &mut [u8; $bytes]); - } - }; -} - -fn extract_from_slice(output: &mut &mut [u8], new_len: usize) { - debug_assert!(new_len <= output.len()); - let tmp = core::mem::take(output); - *output = &mut tmp[..new_len]; -} - -fn ptr_len_or_sentinel(data: &mut Option<&mut [u8]>) -> (*mut u8, u32) { - match data { - Some(ref mut data) => (data.as_mut_ptr(), data.len() as _), - None => (SENTINEL as _, 0), - } -} - -fn ptr_or_sentinel(data: &Option<&[u8]>) -> *const u8 { - match data { - Some(ref data) => data.as_ptr(), - None => SENTINEL as _, - } -} - -/// Implements [`HostFn`] for each supported target architecture. -pub enum HostFnImpl {} - -/// Defines all the host apis implemented by both wasm and RISC-V vms. -pub trait HostFn { - /// Returns the number of times specified contract exists on the call stack. Delegated calls are - /// not counted as separate calls. - /// - /// # Parameters - /// - /// - `account`: The contract address. Should be decodable as an `T::AccountId`. Traps - /// otherwise. - /// - /// # Return - /// - /// Returns the number of times specified contract exists on the call stack. - #[deprecated( - note = "Unstable function. Behaviour can change without further notice. Use only for testing." - )] - fn account_reentrance_count(account: &[u8]) -> u32; - - /// Stores the address of the current contract into the supplied buffer. - /// - /// If the available space in `output` is less than the size of the value a trap is triggered. - /// - /// # Parameters - /// - /// - `output`: A reference to the output data buffer to write the address. - fn address(output: &mut &mut [u8]); - - /// Adds a new delegate dependency to the contract. - /// - /// Traps if the maximum number of delegate_dependencies is reached or if - /// the delegate dependency already exists. - /// - /// # Parameters - /// - /// - `code_hash`: The code hash of the dependency. Should be decodable as an `T::Hash`. Traps - /// otherwise. - #[deprecated( - note = "Unstable function. Behaviour can change without further notice. Use only for testing." - )] - fn add_delegate_dependency(code_hash: &[u8]); - - /// Stores the *free* balance of the current account into the supplied buffer. - /// - /// If the available space in `output` is less than the size of the value a trap is triggered. - /// - /// # Parameters - /// - /// - `output`: A reference to the output data buffer to write the balance. - fn balance(output: &mut &mut [u8]); - - /// Stores the current block number of the current contract into the supplied buffer. - /// - /// If the available space in `output` is less than the size of the value a trap is triggered. - /// - /// # Parameters - /// - /// - `output`: A reference to the output data buffer to write the block number. - fn block_number(output: &mut &mut [u8]); - - /// Make a call to another contract. - /// - /// This is equivalent to calling the newer version of this function with - /// `flags` set to [`CallFlags::ALLOW_REENTRY`]. See the newer version for documentation. - #[deprecated(note = "Deprecated, use newer version instead")] - fn call( - callee: &[u8], - gas: u64, - value: &[u8], - input_data: &[u8], - output: Option<&mut [u8]>, - ) -> Result; - - /// Make a call to another contract. - /// - /// Equivalent to the newer [`Self::call_v2`] version but works with - /// *ref_time* Weight only - fn call_v1( - flags: CallFlags, - callee: &[u8], - gas: u64, - value: &[u8], - input_data: &[u8], - output: Option<&mut [u8]>, - ) -> Result; - - /// Call (possibly transferring some amount of funds) into the specified account. - /// - /// # Parameters - /// - /// - `flags`: See [`CallFlags`] for a documentation of the supported flags. - /// - `callee`: The address of the callee. Should be decodable as an `T::AccountId`. Traps - /// otherwise. - /// - `ref_time_limit`: how much *ref_time* Weight to devote to the execution. - /// - `proof_size_limit`: how much *proof_size* Weight to devote to the execution. - /// - `deposit`: The storage deposit limit for instantiation. Should be decodable as a - /// `Option`. Traps otherwise. Passing `None` means setting no specific limit for - /// the call, which implies storage usage up to the limit of the parent call. - /// - `value`: The value to transfer into the contract. Should be decodable as a `T::Balance`. - /// Traps otherwise. - /// - `input`: The input data buffer used to call the contract. - /// - `output`: A reference to the output data buffer to write the call output buffer. If `None` - /// is provided then the output buffer is not copied. - /// - /// # Errors - /// - /// An error means that the call wasn't successful output buffer is returned unless - /// stated otherwise. - /// - /// - [CalleeReverted][`crate::ReturnErrorCode::CalleeReverted]: Output buffer is returned. - /// - [CalleeTrapped][`crate::ReturnErrorCode::CalleeTrapped] - /// - [TransferFailed][`crate::ReturnErrorCode::TransferFailed] - /// - [NotCallable][`crate::ReturnErrorCode::NotCallable] - #[deprecated( - note = "Unstable function. Behaviour can change without further notice. Use only for testing." - )] - fn call_v2( - flags: CallFlags, - callee: &[u8], - ref_time_limit: u64, - proof_time_limit: u64, - deposit: Option<&[u8]>, - value: &[u8], - input_data: &[u8], - output: Option<&mut [u8]>, - ) -> Result; - - /// Call into the chain extension provided by the chain if any. - /// - /// Handling of the input values is up to the specific chain extension and so is the - /// return value. The extension can decide to use the inputs as primitive inputs or as - /// in/out arguments by interpreting them as pointers. Any caller of this function - /// must therefore coordinate with the chain that it targets. - /// - /// # Note - /// - /// If no chain extension exists the contract will trap with the `NoChainExtension` - /// module error. - /// - /// # Parameters - /// - /// - `func_id`: The function id of the chain extension. - /// - `input`: The input data buffer. - /// - `output`: A reference to the output data buffer to write the output data. - /// - /// # Return - /// - /// The chain extension returned value, if executed successfully. - fn call_chain_extension(func_id: u32, input: &[u8], output: &mut &mut [u8]) -> u32; - - /// Call some dispatchable of the runtime. - /// - /// # Parameters - /// - /// - `call`: The call data. - /// - /// # Return - /// - /// Returns `Error::Success` when the dispatchable was successfully executed and - /// returned `Ok`. When the dispatchable was executed but returned an error - /// `Error::CallRuntimeFailed` is returned. The full error is not - /// provided because it is not guaranteed to be stable. - /// - /// # Comparison with `ChainExtension` - /// - /// Just as a chain extension this API allows the runtime to extend the functionality - /// of contracts. While making use of this function is generally easier it cannot be - /// used in all cases. Consider writing a chain extension if you need to do perform - /// one of the following tasks: - /// - /// - Return data. - /// - Provide functionality **exclusively** to contracts. - /// - Provide custom weights. - /// - Avoid the need to keep the `Call` data structure stable. - fn call_runtime(call: &[u8]) -> Result; - - /// Stores the address of the caller into the supplied buffer. - /// - /// If the available space in `output` is less than the size of the value a trap is triggered. - /// - /// If this is a top-level call (i.e. initiated by an extrinsic) the origin address of the - /// extrinsic will be returned. Otherwise, if this call is initiated by another contract then - /// the address of the contract will be returned. - /// - /// If there is no address associated with the caller (e.g. because the caller is root) then - /// it traps with `BadOrigin`. - /// - /// # Parameters - /// - /// - `output`: A reference to the output data buffer to write the caller address. - fn caller(output: &mut &mut [u8]); - - /// Checks whether the caller of the current contract is the origin of the whole call stack. - /// - /// Prefer this over [`is_contract()`][`Self::is_contract`] when checking whether your contract - /// is being called by a contract or a plain account. The reason is that it performs better - /// since it does not need to do any storage lookups. - /// - /// # Return - /// - /// A return value of `true` indicates that this contract is being called by a plain account - /// and `false` indicates that the caller is another contract. - fn caller_is_origin() -> bool; - - /// Checks whether the caller of the current contract is root. - /// - /// Note that only the origin of the call stack can be root. Hence this function returning - /// `true` implies that the contract is being called by the origin. - /// - /// A return value of `true` indicates that this contract is being called by a root origin, - /// and `false` indicates that the caller is a signed origin. - #[deprecated( - note = "Unstable function. Behaviour can change without further notice. Use only for testing." - )] - fn caller_is_root() -> u32; - - /// Clear the value at the given key in the contract storage. - /// - /// Equivalent to the newer [`Self::clear_storage_v1`] version with - /// the exception of the return type. Still a valid thing to call when not interested in the - /// return value. - fn clear_storage(key: &[u8]); - - /// Clear the value at the given key in the contract storage. - /// - /// # Parameters - /// - /// - `key`: The storage key. - /// - /// # Return - /// - /// Returns the size of the pre-existing value at the specified key if any. - fn clear_storage_v1(key: &[u8]) -> Option; - - /// Retrieve the code hash for a specified contract address. - /// - /// # Parameters - /// - /// - `account_id`: The address of the contract.Should be decodable as an `T::AccountId`. Traps - /// otherwise. - /// - `output`: A reference to the output data buffer to write the code hash. - /// - /// - /// # Errors - /// - /// - [CodeNotFound][`crate::ReturnErrorCode::CodeNotFound] - fn code_hash(account_id: &[u8], output: &mut [u8]) -> Result; - - /// Checks whether there is a value stored under the given key. - /// - /// This version is to be used with a fixed sized storage key. For runtimes supporting - /// transparent hashing, please use the newer version of this function. - fn contains_storage(key: &[u8]) -> Option; - - /// Checks whether there is a value stored under the given key. - /// - /// The key length must not exceed the maximum defined by the contracts module parameter. - /// - /// # Parameters - /// - `key`: The storage key. - /// - /// # Return - /// - /// Returns the size of the pre-existing value at the specified key if any. - fn contains_storage_v1(key: &[u8]) -> Option; - - /// Execute code in the context (storage, caller, value) of the current contract. - /// - /// Reentrancy protection is always disabled since the callee is allowed - /// to modify the callers storage. This makes going through a reentrancy attack - /// unnecessary for the callee when it wants to exploit the caller. - /// - /// # Parameters - /// - /// - `flags`: See [`CallFlags`] for a documentation of the supported flags. - /// - `code_hash`: The hash of the code to be executed. - /// - `input`: The input data buffer used to call the contract. - /// - `output`: A reference to the output data buffer to write the call output buffer. If `None` - /// is provided then the output buffer is not copied. - /// - /// # Errors - /// - /// An error means that the call wasn't successful and no output buffer is returned unless - /// stated otherwise. - /// - /// - [CalleeReverted][`crate::ReturnErrorCode::CalleeReverted]: Output buffer is returned. - /// - [CalleeTrapped][`crate::ReturnErrorCode::CalleeTrapped] - /// - [CodeNotFound][`crate::ReturnErrorCode::CodeNotFound] - fn delegate_call( - flags: CallFlags, - code_hash: &[u8], - input_data: &[u8], - output: Option<&mut [u8]>, - ) -> Result; - - /// Deposit a contract event with the data buffer and optional list of topics. There is a limit - /// on the maximum number of topics specified by `event_topics`. - /// - /// There should not be any duplicates in `topics`. - /// - /// # Parameters - /// - /// - `topics`: The topics list encoded as `Vec`. It can't contain duplicates. - fn deposit_event(topics: &[u8], data: &[u8]); - - /// Recovers the ECDSA public key from the given message hash and signature. - /// - /// Writes the public key into the given output buffer. - /// Assumes the secp256k1 curve. - /// - /// # Parameters - /// - /// - `signature`: The signature bytes. - /// - `message_hash`: The message hash bytes. - /// - `output`: A reference to the output data buffer to write the public key. - /// - /// # Errors - /// - /// - [EcdsaRecoveryFailed][`crate::ReturnErrorCode::EcdsaRecoveryFailed] - fn ecdsa_recover( - signature: &[u8; 65], - message_hash: &[u8; 32], - output: &mut [u8; 33], - ) -> Result; - - /// Calculates Ethereum address from the ECDSA compressed public key and stores - /// it into the supplied buffer. - /// - /// # Parameters - /// - /// - `pubkey`: The public key bytes. - /// - `output`: A reference to the output data buffer to write the address. - /// - /// # Errors - /// - /// - [EcdsaRecoveryFailed][`crate::ReturnErrorCode::EcdsaRecoveryFailed] - fn ecdsa_to_eth_address(pubkey: &[u8; 33], output: &mut [u8; 20]) -> Result; - - /// Stores the weight left into the supplied buffer. - /// - /// Equivalent to the newer [`Self::gas_left_v1`] version but - /// works with *ref_time* Weight only. - fn gas_left(out: &mut &mut [u8]); - - /// Stores the amount of weight left into the supplied buffer. - /// The data is encoded as Weight. - /// - /// If the available space in `output` is less than the size of the value a trap is triggered. - /// - /// # Parameters - /// - /// - `output`: A reference to the output data buffer to write the weight left. - #[deprecated( - note = "Unstable function. Behaviour can change without further notice. Use only for testing." - )] - fn gas_left_v1(output: &mut &mut [u8]); - - /// Retrieve the value under the given key from storage. - /// - /// This version is to be used with a fixed sized storage key. For runtimes supporting - /// transparent hashing, please use the newer version of this function. - fn get_storage(key: &[u8], output: &mut &mut [u8]) -> Result; - - /// Retrieve the value under the given key from storage. - /// - /// The key length must not exceed the maximum defined by the contracts module parameter. - /// - /// # Parameters - /// - `key`: The storage key. - /// - `output`: A reference to the output data buffer to write the storage entry. - /// - /// # Errors - /// - /// [KeyNotFound][`crate::ReturnErrorCode::KeyNotFound] - fn get_storage_v1(key: &[u8], output: &mut &mut [u8]) -> Result; - - hash_fn!(sha2_256, 32); - hash_fn!(keccak_256, 32); - hash_fn!(blake2_256, 32); - hash_fn!(blake2_128, 16); - - /// Stores the input passed by the caller into the supplied buffer. - /// - /// # Note - /// - /// This function traps if: - /// - the input is larger than the available space. - /// - the input was previously forwarded by a [`call()`][`Self::call()`]. - /// - /// # Parameters - /// - /// - `output`: A reference to the output data buffer to write the input data. - fn input(output: &mut &mut [u8]); - - /// Instantiate a contract with the specified code hash. - /// - /// Equivalent to the newer [`Self::instantiate_v2`] version but works - /// with *ref_time* Weight only. - fn instantiate_v1( - code_hash: &[u8], - gas: u64, - value: &[u8], - input: &[u8], - address: Option<&mut [u8]>, - output: Option<&mut [u8]>, - salt: &[u8], - ) -> Result; - - /// Instantiate a contract with the specified code hash. - /// - /// This function creates an account and executes the constructor defined in the code specified - /// by the code hash. - /// - /// # Parameters - /// - /// - `code_hash`: The hash of the code to be instantiated. - /// - `ref_time_limit`: how much *ref_time* Weight to devote to the execution. - /// - `proof_size_limit`: how much *proof_size* Weight to devote to the execution. - /// - `deposit`: The storage deposit limit for instantiation. Should be decodable as a - /// `Option`. Traps otherwise. Passing `None` means setting no specific limit for - /// the call, which implies storage usage up to the limit of the parent call. - /// - `value`: The value to transfer into the contract. Should be decodable as a `T::Balance`. - /// Traps otherwise. - /// - `input`: The input data buffer. - /// - `address`: A reference to the address buffer to write the address of the contract. If - /// `None` is provided then the output buffer is not copied. - /// - `output`: A reference to the return value buffer to write the constructor output buffer. - /// If `None` is provided then the output buffer is not copied. - /// - `salt`: The salt bytes to use for this instantiation. - /// - /// # Errors - /// - /// Please consult the [ReturnErrorCode][`crate::ReturnErrorCode`] enum declaration for more - /// information on those errors. Here we only note things specific to this function. - /// - /// An error means that the account wasn't created and no address or output buffer - /// is returned unless stated otherwise. - /// - /// - [CalleeReverted][`crate::ReturnErrorCode::CalleeReverted]: Output buffer is returned. - /// - [CalleeTrapped][`crate::ReturnErrorCode::CalleeTrapped] - /// - [TransferFailed][`crate::ReturnErrorCode::TransferFailed] - /// - [CodeNotFound][`crate::ReturnErrorCode::CodeNotFound] - #[deprecated( - note = "Unstable function. Behaviour can change without further notice. Use only for testing." - )] - fn instantiate_v2( - code_hash: &[u8], - ref_time_limit: u64, - proof_size_limit: u64, - deposit: Option<&[u8]>, - value: &[u8], - input: &[u8], - address: Option<&mut [u8]>, - output: Option<&mut [u8]>, - salt: &[u8], - ) -> Result; - - /// Returns a nonce that is unique per contract instantiation. - /// - /// The nonce is incremented for each successful contract instantiation. This is a - /// sensible default salt for contract instantiations. - fn instantiation_nonce() -> u64; - - /// Checks whether a specified address belongs to a contract. - /// - /// # Parameters - /// - /// - `account_id`: The address to check. Should be decodable as an `T::AccountId`. Traps - /// otherwise. - /// - /// # Return - /// - /// Returns `true` if the address belongs to a contract. - fn is_contract(account_id: &[u8]) -> bool; - - /// Stores the minimum balance (a.k.a. existential deposit) into the supplied buffer. - /// The data is encoded as `T::Balance`. - /// - /// If the available space in `output` is less than the size of the value a trap is triggered. - /// - /// # Parameters - /// - /// - `output`: A reference to the output data buffer to write the minimum balance. - fn minimum_balance(output: &mut &mut [u8]); - - /// Retrieve the code hash of the currently executing contract. - /// - /// # Parameters - /// - /// - `output`: A reference to the output data buffer to write the code hash. - fn own_code_hash(output: &mut [u8]); - - /// Load the latest block timestamp into the supplied buffer - /// - /// If the available space in `output` is less than the size of the value a trap is triggered. - /// - /// # Parameters - /// - /// - `output`: A reference to the output data buffer to write the timestamp. - fn now(output: &mut &mut [u8]); - - /// Returns the number of times the currently executing contract exists on the call stack in - /// addition to the calling instance. - /// - /// # Return - /// - /// Returns `0` when there is no reentrancy. - #[deprecated( - note = "Unstable function. Behaviour can change without further notice. Use only for testing." - )] - fn reentrance_count() -> u32; - - /// Removes the delegate dependency from the contract. - /// - /// Traps if the delegate dependency does not exist. - /// - /// # Parameters - /// - /// - `code_hash`: The code hash of the dependency. Should be decodable as an `T::Hash`. Traps - /// otherwise. - #[deprecated( - note = "Unstable function. Behaviour can change without further notice. Use only for testing." - )] - fn remove_delegate_dependency(code_hash: &[u8]); - - /// Cease contract execution and save a data buffer as a result of the execution. - /// - /// This function never returns as it stops execution of the caller. - /// This is the only way to return a data buffer to the caller. Returning from - /// execution without calling this function is equivalent to calling: - /// ```nocompile - /// return_value(ReturnFlags::empty(), &[]) - /// ``` - /// - /// Using an unnamed non empty `ReturnFlags` triggers a trap. - /// - /// # Parameters - /// - /// - `flags`: Flag used to signal special return conditions to the supervisor. See - /// [`ReturnFlags`] for a documentation of the supported flags. - /// - `return_value`: The return value buffer. - fn return_value(flags: ReturnFlags, return_value: &[u8]) -> !; - - /// Replace the contract code at the specified address with new code. - /// - /// # Note - /// - /// There are a couple of important considerations which must be taken into account when - /// using this API: - /// - /// 1. The storage at the code address will remain untouched. This means that contract - /// developers must ensure that the storage layout of the new code is compatible with that of - /// the old code. - /// - /// 2. Contracts using this API can't be assumed as having deterministic addresses. Said another - /// way, when using this API you lose the guarantee that an address always identifies a specific - /// code hash. - /// - /// 3. If a contract calls into itself after changing its code the new call would use - /// the new code. However, if the original caller panics after returning from the sub call it - /// would revert the changes made by [`set_code_hash()`][`Self::set_code_hash`] and the next - /// caller would use the old code. - /// - /// # Parameters - /// - /// - `code_hash`: The hash of the new code. Should be decodable as an `T::Hash`. Traps - /// otherwise. - /// - /// # Errors - /// - /// - [CodeNotFound][`crate::ReturnErrorCode::CodeNotFound] - fn set_code_hash(code_hash: &[u8]) -> Result; - - /// Set the value at the given key in the contract storage. - /// - /// Equivalent to [`Self::set_storage_v1`] version with the - /// exception of the return type. Still a valid thing to call for fixed sized storage key, when - /// not interested in the return value. - fn set_storage(key: &[u8], value: &[u8]); - - /// Set the value at the given key in the contract storage. - /// - /// This version is to be used with a fixed sized storage key. For runtimes supporting - /// transparent hashing, please use the newer version of this function. - fn set_storage_v1(key: &[u8], value: &[u8]) -> Option; - - /// Set the value at the given key in the contract storage. - /// - /// The key and value lengths must not exceed the maximums defined by the contracts module - /// parameters. - /// - /// # Parameters - /// - /// - `key`: The storage key. - /// - `encoded_value`: The storage value. - /// - /// # Return - /// - /// Returns the size of the pre-existing value at the specified key if any. - fn set_storage_v2(key: &[u8], value: &[u8]) -> Option; - - /// Verify a sr25519 signature - /// - /// # Parameters - /// - /// - `signature`: The signature bytes. - /// - `message`: The message bytes. - /// - /// # Errors - /// - /// - [Sr25519VerifyFailed][`crate::ReturnErrorCode::Sr25519VerifyFailed] - fn sr25519_verify(signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> Result; - - /// Retrieve and remove the value under the given key from storage. - /// - /// # Parameters - /// - `key`: The storage key. - /// - `output`: A reference to the output data buffer to write the storage entry. - /// - /// # Errors - /// - /// [KeyNotFound][`crate::ReturnErrorCode::KeyNotFound] - fn take_storage(key: &[u8], output: &mut &mut [u8]) -> Result; - - /// Transfer some amount of funds into the specified account. - /// - /// # Parameters - /// - /// - `account_id`: The address of the account to transfer funds to. Should be decodable as an - /// `T::AccountId`. Traps otherwise. - /// - `value`: The value to transfer. Should be decodable as a `T::Balance`. Traps otherwise. - /// - /// # Errors - /// - /// - [TransferFailed][`crate::ReturnErrorCode::TransferFailed] - fn transfer(account_id: &[u8], value: &[u8]) -> Result; - - /// Remove the calling account and transfer remaining balance. - /// - /// This is equivalent to calling the newer version of this function - #[deprecated(note = "Deprecated, use newer version instead")] - fn terminate(beneficiary: &[u8]) -> !; - - /// Remove the calling account and transfer remaining **free** balance. - /// - /// This function never returns. Either the termination was successful and the - /// execution of the destroyed contract is halted. Or it failed during the termination - /// which is considered fatal and results in a trap + rollback. - /// - /// # Parameters - /// - /// - `beneficiary`: The address of the beneficiary account, Should be decodable as an - /// `T::AccountId`. - /// - /// # Traps - /// - /// - The contract is live i.e is already on the call stack. - /// - Failed to send the balance to the beneficiary. - /// - The deletion queue is full. - fn terminate_v1(beneficiary: &[u8]) -> !; - - /// Stores the value transferred along with this call/instantiate into the supplied buffer. - /// The data is encoded as `T::Balance`. - /// - /// If the available space in `output` is less than the size of the value a trap is triggered. - /// - /// # Parameters - /// - /// - `output`: A reference to the output data buffer to write the transferred value. - fn value_transferred(output: &mut &mut [u8]); - - /// Stores the price for the specified amount of gas into the supplied buffer. - /// - /// Equivalent to the newer [`Self::weight_to_fee_v1`] version but - /// works with *ref_time* Weight only. It is recommended to switch to the latest version, once - /// it's stabilized. - fn weight_to_fee(gas: u64, output: &mut &mut [u8]); - - /// Stores the price for the specified amount of gas into the supplied buffer. - /// The data is encoded as `T::Balance`. - /// - /// If the available space in `output` is less than the size of the value a trap is triggered. - /// - /// # Parameters - /// - /// - `ref_time_limit`: The *ref_time* Weight limit to query the price for. - /// - `proof_size_limit`: The *proof_size* Weight limit to query the price for. - /// - `output`: A reference to the output data buffer to write the price. - #[deprecated( - note = "Unstable function. Behaviour can change without further notice. Use only for testing." - )] - fn weight_to_fee_v1(ref_time_limit: u64, proof_size_limit: u64, output: &mut &mut [u8]); - - /// Execute an XCM program locally, using the contract's address as the origin. - /// This is equivalent to dispatching `pallet_xcm::execute` through call_runtime, except that - /// the function is called directly instead of being dispatched. - /// - /// # Parameters - /// - /// - `msg`: The message, should be decodable as a [VersionedXcm](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/enum.VersionedXcm.html), - /// traps otherwise. - /// - `output`: A reference to the output data buffer to write the [Outcome](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/v3/enum.Outcome.html) - /// - /// # Return - /// - /// Returns `Error::Success` when the XCM execution attempt is successful. When the XCM - /// execution fails, `ReturnCode::XcmExecutionFailed` is returned - #[deprecated( - note = "Unstable function. Behaviour can change without further notice. Use only for testing." - )] - fn xcm_execute(msg: &[u8], output: &mut &mut [u8]) -> Result; - - /// Send an XCM program from the contract to the specified destination. - /// This is equivalent to dispatching `pallet_xcm::send` through `call_runtime`, except that - /// the function is called directly instead of being dispatched. - /// - /// # Parameters - /// - /// - `dest`: The XCM destination, should be decodable as [VersionedMultiLocation](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/enum.VersionedMultiLocation.html), - /// traps otherwise. - /// - `msg`: The message, should be decodable as a [VersionedXcm](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/enum.VersionedXcm.html), - /// traps otherwise. - /// - `output`: A reference to the output data buffer to write the [XcmHash](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/v3/type.XcmHash.html) - /// - /// # Return - /// - /// Returns `ReturnCode::Success` when the message was successfully sent. When the XCM - /// execution fails, `ReturnErrorCode::XcmSendFailed` is returned. - #[deprecated( - note = "Unstable function. Behaviour can change without further notice. Use only for testing." - )] - fn xcm_send(dest: &[u8], msg: &[u8], output: &mut &mut [u8]) -> Result; -} diff --git a/substrate/frame/contracts/uapi/src/host/wasm32.rs b/substrate/frame/contracts/uapi/src/host/wasm32.rs deleted file mode 100644 index d30058daf3d..00000000000 --- a/substrate/frame/contracts/uapi/src/host/wasm32.rs +++ /dev/null @@ -1,811 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// -// 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::{ - extract_from_slice, ptr_len_or_sentinel, ptr_or_sentinel, CallFlags, HostFn, HostFnImpl, Result, -}; -use crate::{ReturnCode, ReturnFlags}; - -mod sys { - use super::ReturnCode; - - #[link(wasm_import_module = "seal0")] - extern "C" { - pub fn account_reentrance_count(account_ptr: *const u8) -> u32; - - pub fn add_delegate_dependency(code_hash_ptr: *const u8); - - pub fn address(output_ptr: *mut u8, output_len_ptr: *mut u32); - - pub fn balance(output_ptr: *mut u8, output_len_ptr: *mut u32); - - pub fn block_number(output_ptr: *mut u8, output_len_ptr: *mut u32); - - pub fn call( - callee_ptr: *const u8, - callee_len: u32, - gas: u64, - value_ptr: *const u8, - value_len: u32, - input_data_ptr: *const u8, - input_data_len: u32, - output_ptr: *mut u8, - output_len_ptr: *mut u32, - ) -> ReturnCode; - - pub fn call_chain_extension( - func_id: u32, - input_ptr: *const u8, - input_len: u32, - output_ptr: *mut u8, - output_len_ptr: *mut u32, - ) -> ReturnCode; - - pub fn call_runtime(call_ptr: *const u8, call_len: u32) -> ReturnCode; - - pub fn caller(output_ptr: *mut u8, output_len_ptr: *mut u32); - - pub fn caller_is_origin() -> ReturnCode; - - pub fn caller_is_root() -> ReturnCode; - - pub fn clear_storage(key_ptr: *const u8, key_len: u32) -> ReturnCode; - - pub fn code_hash( - account_id_ptr: *const u8, - output_ptr: *mut u8, - output_len_ptr: *mut u32, - ) -> ReturnCode; - - pub fn contains_storage(key_ptr: *const u8, key_len: u32) -> ReturnCode; - - pub fn delegate_call( - flags: u32, - code_hash_ptr: *const u8, - input_data_ptr: *const u8, - input_data_len: u32, - output_ptr: *mut u8, - output_len_ptr: *mut u32, - ) -> ReturnCode; - - pub fn deposit_event( - topics_ptr: *const u8, - topics_len: u32, - data_ptr: *const u8, - data_len: u32, - ); - - pub fn ecdsa_recover( - signature_ptr: *const u8, - message_hash_ptr: *const u8, - output_ptr: *mut u8, - ) -> ReturnCode; - - pub fn ecdsa_to_eth_address(public_key_ptr: *const u8, output_ptr: *mut u8) -> ReturnCode; - - pub fn gas_left(output_ptr: *mut u8, output_len_ptr: *mut u32); - - pub fn get_storage( - key_ptr: *const u8, - key_len: u32, - out_ptr: *mut u8, - out_len_ptr: *mut u32, - ) -> ReturnCode; - - pub fn hash_blake2_128(input_ptr: *const u8, input_len: u32, output_ptr: *mut u8); - - pub fn hash_blake2_256(input_ptr: *const u8, input_len: u32, output_ptr: *mut u8); - - pub fn hash_keccak_256(input_ptr: *const u8, input_len: u32, output_ptr: *mut u8); - - pub fn hash_sha2_256(input_ptr: *const u8, input_len: u32, output_ptr: *mut u8); - - pub fn input(buf_ptr: *mut u8, buf_len_ptr: *mut u32); - - pub fn instantiation_nonce() -> u64; - - pub fn is_contract(account_id_ptr: *const u8) -> ReturnCode; - - pub fn minimum_balance(output_ptr: *mut u8, output_len_ptr: *mut u32); - - pub fn now(output_ptr: *mut u8, output_len_ptr: *mut u32); - - pub fn own_code_hash(output_ptr: *mut u8, output_len_ptr: *mut u32); - - pub fn reentrance_count() -> u32; - - pub fn remove_delegate_dependency(code_hash_ptr: *const u8); - - pub fn seal_return(flags: u32, data_ptr: *const u8, data_len: u32) -> !; - - pub fn set_code_hash(code_hash_ptr: *const u8) -> ReturnCode; - - pub fn set_storage( - key_ptr: *const u8, - key_len: u32, - value_ptr: *const u8, - value_len: u32, - ) -> ReturnCode; - - pub fn sr25519_verify( - signature_ptr: *const u8, - public_key_ptr: *const u8, - message_len: u32, - message_ptr: *const u8, - ) -> ReturnCode; - - pub fn take_storage( - key_ptr: *const u8, - key_len: u32, - out_ptr: *mut u8, - out_len_ptr: *mut u32, - ) -> ReturnCode; - - pub fn terminate(beneficiary_ptr: *const u8) -> !; - - pub fn transfer( - account_id_ptr: *const u8, - account_id_len: u32, - transferred_value_ptr: *const u8, - transferred_value_len: u32, - ) -> ReturnCode; - - pub fn value_transferred(output_ptr: *mut u8, output_len_ptr: *mut u32); - - pub fn weight_to_fee(gas: u64, output_ptr: *mut u8, output_len_ptr: *mut u32); - - pub fn xcm_execute(msg_ptr: *const u8, msg_len: u32, output_ptr: *mut u8) -> ReturnCode; - - pub fn xcm_send( - dest_ptr: *const u8, - msg_ptr: *const u8, - msg_len: u32, - output_ptr: *mut u8, - ) -> ReturnCode; - } - - pub mod v1 { - use crate::ReturnCode; - - #[link(wasm_import_module = "seal1")] - extern "C" { - pub fn call( - flags: u32, - callee_ptr: *const u8, - gas: u64, - transferred_value_ptr: *const u8, - input_data_ptr: *const u8, - input_data_len: u32, - output_ptr: *mut u8, - output_len_ptr: *mut u32, - ) -> ReturnCode; - - pub fn clear_storage(key_ptr: *const u8, key_len: u32) -> ReturnCode; - - pub fn contains_storage(key_ptr: *const u8, key_len: u32) -> ReturnCode; - - pub fn gas_left(output_ptr: *mut u8, output_len_ptr: *mut u32); - - pub fn get_storage( - key_ptr: *const u8, - key_len: u32, - out_ptr: *mut u8, - out_len_ptr: *mut u32, - ) -> ReturnCode; - - pub fn instantiate( - code_hash_ptr: *const u8, - gas: u64, - value_ptr: *const u8, - input_ptr: *const u8, - input_len: u32, - address_ptr: *mut u8, - address_len_ptr: *mut u32, - output_ptr: *mut u8, - output_len_ptr: *mut u32, - salt_ptr: *const u8, - salt_len: u32, - ) -> ReturnCode; - - pub fn set_storage( - key_ptr: *const u8, - key_len: u32, - value_ptr: *const u8, - value_len: u32, - ) -> ReturnCode; - - pub fn terminate(beneficiary_ptr: *const u8) -> !; - - pub fn weight_to_fee( - ref_time_limit: u64, - proof_time_limit: u64, - output_ptr: *mut u8, - output_len_ptr: *mut u32, - ); - } - } - - pub mod v2 { - use crate::ReturnCode; - - #[link(wasm_import_module = "seal2")] - extern "C" { - pub fn call( - flags: u32, - callee_ptr: *const u8, - ref_time_limit: u64, - proof_time_limit: u64, - deposit_ptr: *const u8, - transferred_value_ptr: *const u8, - input_data_ptr: *const u8, - input_data_len: u32, - output_ptr: *mut u8, - output_len_ptr: *mut u32, - ) -> ReturnCode; - - pub fn instantiate( - code_hash_ptr: *const u8, - ref_time_limit: u64, - proof_time_limit: u64, - deposit_ptr: *const u8, - value_ptr: *const u8, - input_ptr: *const u8, - input_len: u32, - address_ptr: *mut u8, - address_len_ptr: *mut u32, - output_ptr: *mut u8, - output_len_ptr: *mut u32, - salt_ptr: *const u8, - salt_len: u32, - ) -> ReturnCode; - - pub fn set_storage( - key_ptr: *const u8, - key_len: u32, - value_ptr: *const u8, - value_len: u32, - ) -> ReturnCode; - } - } -} - -/// A macro to implement all Host functions with a signature of `fn(&mut &mut [u8])`. -macro_rules! impl_wrapper_for { - (@impl_fn $( $mod:ident )::*, $suffix:literal, $name:ident) => { - paste::paste! { - fn [<$name $suffix>](output: &mut &mut [u8]) { - let mut output_len = output.len() as u32; - unsafe { - $( $mod )::*::$name(output.as_mut_ptr(), &mut output_len); - } - } - } - }; - - () => {}; - - (($mod:ident, $suffix:literal) => [$( $name:ident),*], $($tail:tt)*) => { - $(impl_wrapper_for!(@impl_fn sys::$mod, $suffix, $name);)* - impl_wrapper_for!($($tail)*); - }; - - (() => [$( $name:ident),*], $($tail:tt)*) => { - $(impl_wrapper_for!(@impl_fn sys, "", $name);)* - impl_wrapper_for!($($tail)*); - }; -} - -/// A macro to implement all the hash functions Apis. -macro_rules! impl_hash_fn { - ( $name:ident, $bytes_result:literal ) => { - paste::item! { - fn [](input: &[u8], output: &mut [u8; $bytes_result]) { - unsafe { - sys::[]( - input.as_ptr(), - input.len() as u32, - output.as_mut_ptr(), - ) - } - } - } - }; -} - -/// A macro to implement the get_storage functions. -macro_rules! impl_get_storage { - ($fn_name:ident, $sys_get_storage:path) => { - fn $fn_name(key: &[u8], output: &mut &mut [u8]) -> Result { - let mut output_len = output.len() as u32; - let ret_code = { - unsafe { - $sys_get_storage( - key.as_ptr(), - key.len() as u32, - output.as_mut_ptr(), - &mut output_len, - ) - } - }; - extract_from_slice(output, output_len as usize); - ret_code.into() - } - }; -} - -impl HostFn for HostFnImpl { - fn instantiate_v1( - code_hash: &[u8], - gas: u64, - value: &[u8], - input: &[u8], - mut address: Option<&mut [u8]>, - mut output: Option<&mut [u8]>, - salt: &[u8], - ) -> Result { - let (address_ptr, mut address_len) = ptr_len_or_sentinel(&mut address); - let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); - let ret_code = unsafe { - sys::v1::instantiate( - code_hash.as_ptr(), - gas, - value.as_ptr(), - input.as_ptr(), - input.len() as u32, - address_ptr, - &mut address_len, - output_ptr, - &mut output_len, - salt.as_ptr(), - salt.len() as u32, - ) - }; - - if let Some(ref mut address) = address { - extract_from_slice(address, address_len as usize); - } - if let Some(ref mut output) = output { - extract_from_slice(output, output_len as usize); - } - ret_code.into() - } - - fn instantiate_v2( - code_hash: &[u8], - ref_time_limit: u64, - proof_size_limit: u64, - deposit: Option<&[u8]>, - value: &[u8], - input: &[u8], - mut address: Option<&mut [u8]>, - mut output: Option<&mut [u8]>, - salt: &[u8], - ) -> Result { - let (address_ptr, mut address_len) = ptr_len_or_sentinel(&mut address); - let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); - let deposit_ptr = ptr_or_sentinel(&deposit); - - let ret_code = { - unsafe { - sys::v2::instantiate( - code_hash.as_ptr(), - ref_time_limit, - proof_size_limit, - deposit_ptr, - value.as_ptr(), - input.as_ptr(), - input.len() as u32, - address_ptr, - &mut address_len, - output_ptr, - &mut output_len, - salt.as_ptr(), - salt.len() as u32, - ) - } - }; - - if let Some(ref mut address) = address { - extract_from_slice(address, address_len as usize); - } - - if let Some(ref mut output) = output { - extract_from_slice(output, output_len as usize); - } - - ret_code.into() - } - - fn call( - callee: &[u8], - gas: u64, - value: &[u8], - input_data: &[u8], - mut output: Option<&mut [u8]>, - ) -> Result { - let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); - let ret_code = { - unsafe { - sys::call( - callee.as_ptr(), - callee.len() as u32, - gas, - value.as_ptr(), - value.len() as u32, - input_data.as_ptr(), - input_data.len() as u32, - output_ptr, - &mut output_len, - ) - } - }; - - if let Some(ref mut output) = output { - extract_from_slice(output, output_len as usize); - } - - ret_code.into() - } - - fn call_v1( - flags: CallFlags, - callee: &[u8], - gas: u64, - value: &[u8], - input_data: &[u8], - mut output: Option<&mut [u8]>, - ) -> Result { - let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); - let ret_code = { - unsafe { - sys::v1::call( - flags.bits(), - callee.as_ptr(), - gas, - value.as_ptr(), - input_data.as_ptr(), - input_data.len() as u32, - output_ptr, - &mut output_len, - ) - } - }; - - if let Some(ref mut output) = output { - extract_from_slice(output, output_len as usize); - } - - ret_code.into() - } - - fn call_v2( - flags: CallFlags, - callee: &[u8], - ref_time_limit: u64, - proof_time_limit: u64, - deposit: Option<&[u8]>, - value: &[u8], - input_data: &[u8], - mut output: Option<&mut [u8]>, - ) -> Result { - let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); - let deposit_ptr = ptr_or_sentinel(&deposit); - let ret_code = { - unsafe { - sys::v2::call( - flags.bits(), - callee.as_ptr(), - ref_time_limit, - proof_time_limit, - deposit_ptr, - value.as_ptr(), - input_data.as_ptr(), - input_data.len() as u32, - output_ptr, - &mut output_len, - ) - } - }; - - if let Some(ref mut output) = output { - extract_from_slice(output, output_len as usize); - } - - ret_code.into() - } - - fn caller_is_root() -> u32 { - unsafe { sys::caller_is_root() }.into_u32() - } - - fn delegate_call( - flags: CallFlags, - code_hash: &[u8], - input: &[u8], - mut output: Option<&mut [u8]>, - ) -> Result { - let (output_ptr, mut output_len) = ptr_len_or_sentinel(&mut output); - let ret_code = { - unsafe { - sys::delegate_call( - flags.bits(), - code_hash.as_ptr(), - input.as_ptr(), - input.len() as u32, - output_ptr, - &mut output_len, - ) - } - }; - - if let Some(ref mut output) = output { - extract_from_slice(output, output_len as usize); - } - - ret_code.into() - } - - fn transfer(account_id: &[u8], value: &[u8]) -> Result { - let ret_code = unsafe { - sys::transfer( - account_id.as_ptr(), - account_id.len() as u32, - value.as_ptr(), - value.len() as u32, - ) - }; - ret_code.into() - } - - fn deposit_event(topics: &[u8], data: &[u8]) { - unsafe { - sys::deposit_event( - topics.as_ptr(), - topics.len() as u32, - data.as_ptr(), - data.len() as u32, - ) - } - } - - fn set_storage(key: &[u8], value: &[u8]) { - unsafe { - sys::set_storage(key.as_ptr(), key.len() as u32, value.as_ptr(), value.len() as u32) - }; - } - - fn set_storage_v1(key: &[u8], encoded_value: &[u8]) -> Option { - let ret_code = unsafe { - sys::v1::set_storage( - key.as_ptr(), - key.len() as u32, - encoded_value.as_ptr(), - encoded_value.len() as u32, - ) - }; - ret_code.into() - } - - fn set_storage_v2(key: &[u8], encoded_value: &[u8]) -> Option { - let ret_code = unsafe { - sys::v2::set_storage( - key.as_ptr(), - key.len() as u32, - encoded_value.as_ptr(), - encoded_value.len() as u32, - ) - }; - ret_code.into() - } - - fn clear_storage(key: &[u8]) { - unsafe { sys::clear_storage(key.as_ptr(), key.len() as u32) }; - } - - fn clear_storage_v1(key: &[u8]) -> Option { - let ret_code = unsafe { sys::v1::clear_storage(key.as_ptr(), key.len() as u32) }; - ret_code.into() - } - - impl_get_storage!(get_storage, sys::get_storage); - impl_get_storage!(get_storage_v1, sys::v1::get_storage); - - fn take_storage(key: &[u8], output: &mut &mut [u8]) -> Result { - let mut output_len = output.len() as u32; - let ret_code = { - unsafe { - sys::take_storage( - key.as_ptr(), - key.len() as u32, - output.as_mut_ptr(), - &mut output_len, - ) - } - }; - extract_from_slice(output, output_len as usize); - ret_code.into() - } - - fn contains_storage(key: &[u8]) -> Option { - let ret_code = unsafe { sys::contains_storage(key.as_ptr(), key.len() as u32) }; - ret_code.into() - } - - fn contains_storage_v1(key: &[u8]) -> Option { - let ret_code = unsafe { sys::v1::contains_storage(key.as_ptr(), key.len() as u32) }; - ret_code.into() - } - - fn terminate(beneficiary: &[u8]) -> ! { - unsafe { sys::terminate(beneficiary.as_ptr()) } - } - - fn terminate_v1(beneficiary: &[u8]) -> ! { - unsafe { sys::v1::terminate(beneficiary.as_ptr()) } - } - - fn call_chain_extension(func_id: u32, input: &[u8], output: &mut &mut [u8]) -> u32 { - let mut output_len = output.len() as u32; - let ret_code = { - unsafe { - sys::call_chain_extension( - func_id, - input.as_ptr(), - input.len() as u32, - output.as_mut_ptr(), - &mut output_len, - ) - } - }; - extract_from_slice(output, output_len as usize); - ret_code.into_u32() - } - - fn input(output: &mut &mut [u8]) { - let mut output_len = output.len() as u32; - { - unsafe { sys::input(output.as_mut_ptr(), &mut output_len) }; - } - extract_from_slice(output, output_len as usize); - } - - fn return_value(flags: ReturnFlags, return_value: &[u8]) -> ! { - unsafe { sys::seal_return(flags.bits(), return_value.as_ptr(), return_value.len() as u32) } - } - - fn call_runtime(call: &[u8]) -> Result { - let ret_code = unsafe { sys::call_runtime(call.as_ptr(), call.len() as u32) }; - ret_code.into() - } - - impl_wrapper_for! { - () => [caller, block_number, address, balance, gas_left, value_transferred, now, minimum_balance], - (v1, "_v1") => [gas_left], - } - - fn weight_to_fee(gas: u64, output: &mut &mut [u8]) { - let mut output_len = output.len() as u32; - { - unsafe { sys::weight_to_fee(gas, output.as_mut_ptr(), &mut output_len) }; - } - extract_from_slice(output, output_len as usize); - } - - fn weight_to_fee_v1(ref_time_limit: u64, proof_size_limit: u64, output: &mut &mut [u8]) { - let mut output_len = output.len() as u32; - { - unsafe { - sys::v1::weight_to_fee( - ref_time_limit, - proof_size_limit, - output.as_mut_ptr(), - &mut output_len, - ) - }; - } - extract_from_slice(output, output_len as usize); - } - - impl_hash_fn!(sha2_256, 32); - impl_hash_fn!(keccak_256, 32); - impl_hash_fn!(blake2_256, 32); - impl_hash_fn!(blake2_128, 16); - - fn ecdsa_recover( - signature: &[u8; 65], - message_hash: &[u8; 32], - output: &mut [u8; 33], - ) -> Result { - let ret_code = unsafe { - sys::ecdsa_recover(signature.as_ptr(), message_hash.as_ptr(), output.as_mut_ptr()) - }; - ret_code.into() - } - - fn ecdsa_to_eth_address(pubkey: &[u8; 33], output: &mut [u8; 20]) -> Result { - let ret_code = unsafe { sys::ecdsa_to_eth_address(pubkey.as_ptr(), output.as_mut_ptr()) }; - ret_code.into() - } - - fn sr25519_verify(signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> Result { - let ret_code = unsafe { - sys::sr25519_verify( - signature.as_ptr(), - pub_key.as_ptr(), - message.len() as u32, - message.as_ptr(), - ) - }; - ret_code.into() - } - - fn is_contract(account_id: &[u8]) -> bool { - let ret_val = unsafe { sys::is_contract(account_id.as_ptr()) }; - ret_val.into_bool() - } - - fn caller_is_origin() -> bool { - let ret_val = unsafe { sys::caller_is_origin() }; - ret_val.into_bool() - } - - fn set_code_hash(code_hash: &[u8]) -> Result { - let ret_val = unsafe { sys::set_code_hash(code_hash.as_ptr()) }; - ret_val.into() - } - - fn code_hash(account_id: &[u8], output: &mut [u8]) -> Result { - let mut output_len = output.len() as u32; - let ret_val = - unsafe { sys::code_hash(account_id.as_ptr(), output.as_mut_ptr(), &mut output_len) }; - ret_val.into() - } - - fn own_code_hash(output: &mut [u8]) { - let mut output_len = output.len() as u32; - unsafe { sys::own_code_hash(output.as_mut_ptr(), &mut output_len) } - } - - fn account_reentrance_count(account: &[u8]) -> u32 { - unsafe { sys::account_reentrance_count(account.as_ptr()) } - } - - fn add_delegate_dependency(code_hash: &[u8]) { - unsafe { sys::add_delegate_dependency(code_hash.as_ptr()) } - } - - fn remove_delegate_dependency(code_hash: &[u8]) { - unsafe { sys::remove_delegate_dependency(code_hash.as_ptr()) } - } - - fn instantiation_nonce() -> u64 { - unsafe { sys::instantiation_nonce() } - } - - fn reentrance_count() -> u32 { - unsafe { sys::reentrance_count() } - } - - fn xcm_execute(msg: &[u8], output: &mut &mut [u8]) -> Result { - let ret_code = - unsafe { sys::xcm_execute(msg.as_ptr(), msg.len() as _, output.as_mut_ptr()) }; - ret_code.into() - } - - fn xcm_send(dest: &[u8], msg: &[u8], output: &mut &mut [u8]) -> Result { - let ret_code = unsafe { - sys::xcm_send(dest.as_ptr(), msg.as_ptr(), msg.len() as _, output.as_mut_ptr()) - }; - ret_code.into() - } -} diff --git a/substrate/frame/contracts/uapi/src/lib.rs b/substrate/frame/contracts/uapi/src/lib.rs deleted file mode 100644 index 3d384bbb85d..00000000000 --- a/substrate/frame/contracts/uapi/src/lib.rs +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// -// 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. - -//! External C API to communicate with substrate contracts runtime module. -//! -//! Refer to substrate FRAME contract module for more documentation. - -#![no_std] - -mod flags; -pub use flags::*; - -#[cfg(any(target_arch = "wasm32", target_arch = "riscv32"))] -mod host; - -#[cfg(any(target_arch = "wasm32", target_arch = "riscv32"))] -pub use host::*; - -macro_rules! define_error_codes { - ( - $( - $( #[$attr:meta] )* - $name:ident = $discr:literal, - )* - ) => { - /// Every error that can be returned to a contract when it calls any of the host functions. - #[derive(Debug)] - #[repr(u32)] - pub enum ReturnErrorCode { - /// API call successful. - Success = 0, - $( - $( #[$attr] )* - $name = $discr, - )* - /// Returns if an unknown error was received from the host module. - Unknown, - } - - impl From for Result { - #[inline] - fn from(return_code: ReturnCode) -> Self { - match return_code.0 { - 0 => Ok(()), - $( - $discr => Err(ReturnErrorCode::$name), - )* - _ => Err(ReturnErrorCode::Unknown), - } - } - } - }; -} - -impl From for u32 { - fn from(code: ReturnErrorCode) -> u32 { - code as u32 - } -} - -define_error_codes! { - /// The called function trapped and has its state changes reverted. - /// In this case no output buffer is returned. - /// Can only be returned from `call` and `instantiate`. - CalleeTrapped = 1, - /// The called function ran to completion but decided to revert its state. - /// An output buffer is returned when one was supplied. - /// Can only be returned from `call` and `instantiate`. - CalleeReverted = 2, - /// The passed key does not exist in storage. - KeyNotFound = 3, - /// Deprecated and no longer returned: There is only the minimum balance. - _BelowSubsistenceThreshold = 4, - /// Transfer failed for other not further specified reason. Most probably - /// reserved or locked balance of the sender that was preventing the transfer. - TransferFailed = 5, - /// Deprecated and no longer returned: Endowment is no longer required. - _EndowmentTooLow = 6, - /// No code could be found at the supplied code hash. - CodeNotFound = 7, - /// The account that was called is no contract. - NotCallable = 8, - /// The call to `debug_message` had no effect because debug message - /// recording was disabled. - LoggingDisabled = 9, - /// The call dispatched by `call_runtime` was executed but returned an error. - CallRuntimeFailed = 10, - /// ECDSA public key recovery failed. Most probably wrong recovery id or signature. - EcdsaRecoveryFailed = 11, - /// sr25519 signature verification failed. - Sr25519VerifyFailed = 12, - /// The `xcm_execute` call failed. - XcmExecutionFailed = 13, - /// The `xcm_send` call failed. - XcmSendFailed = 14, -} - -/// The raw return code returned by the host side. -#[repr(transparent)] -pub struct ReturnCode(u32); - -/// Used as a sentinel value when reading and writing contract memory. -/// -/// We use this value to signal `None` to a contract when only a primitive is -/// allowed and we don't want to go through encoding a full Rust type. -/// Using `u32::Max` is a safe sentinel because contracts are never -/// allowed to use such a large amount of resources. So this value doesn't -/// make sense for a memory location or length. -const SENTINEL: u32 = u32::MAX; - -impl From for Option { - fn from(code: ReturnCode) -> Self { - (code.0 < SENTINEL).then_some(code.0) - } -} - -impl ReturnCode { - /// Returns the raw underlying `u32` representation. - pub fn into_u32(self) -> u32 { - self.0 - } - /// Returns the underlying `u32` converted into `bool`. - pub fn into_bool(self) -> bool { - self.0.ne(&0) - } -} - -type Result = core::result::Result<(), ReturnErrorCode>; diff --git a/substrate/frame/conviction-voting/Cargo.toml b/substrate/frame/conviction-voting/Cargo.toml index 6d96dde1aaa..1dc723576dc 100644 --- a/substrate/frame/conviction-voting/Cargo.toml +++ b/substrate/frame/conviction-voting/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet for conviction voting in referenda" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -22,13 +19,13 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = "max-encoded-len", ] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", features = ["derive"], 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 } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +serde = { version = "1.0.188", features = ["derive"], 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} +sp-io = { path = "../../primitives/io", default-features = false} +sp-runtime = { path = "../../primitives/runtime", default-features = false} +sp-std = { path = "../../primitives/std", default-features = false} [dev-dependencies] pallet-balances = { path = "../balances" } @@ -36,7 +33,7 @@ pallet-scheduler = { path = "../scheduler" } sp-core = { path = "../../primitives/core" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/conviction-voting/src/tests.rs b/substrate/frame/conviction-voting/src/tests.rs index 371d0364384..850b98b218b 100644 --- a/substrate/frame/conviction-voting/src/tests.rs +++ b/substrate/frame/conviction-voting/src/tests.rs @@ -20,7 +20,7 @@ use std::collections::BTreeMap; use frame_support::{ - assert_noop, assert_ok, derive_impl, parameter_types, + assert_noop, assert_ok, parameter_types, traits::{ConstU32, ConstU64, Contains, Polling, VoteTally}, }; use sp_core::H256; @@ -51,7 +51,6 @@ impl Contains for BaseFilter { } } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = BaseFilter; type BlockWeights = (); diff --git a/substrate/frame/core-fellowship/Cargo.toml b/substrate/frame/core-fellowship/Cargo.toml index d223ecd4f24..523a5bb90a0 100644 --- a/substrate/frame/core-fellowship/Cargo.toml +++ b/substrate/frame/core-fellowship/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Logic as per the description of The Fellowship for core Polkadot technology" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,17 +16,17 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.16", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/core-fellowship/src/tests.rs b/substrate/frame/core-fellowship/src/tests.rs index 9ac381ab7f5..a02c010718c 100644 --- a/substrate/frame/core-fellowship/src/tests.rs +++ b/substrate/frame/core-fellowship/src/tests.rs @@ -20,7 +20,7 @@ use std::collections::BTreeMap; use frame_support::{ - assert_noop, assert_ok, derive_impl, ord_parameter_types, + assert_noop, assert_ok, ord_parameter_types, pallet_prelude::Weight, parameter_types, traits::{tokens::GetSalary, ConstU32, ConstU64, Everything, IsInVec, TryMapSuccess}, @@ -50,8 +50,6 @@ parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::simple_max(Weight::from_parts(1_000_000, u64::max_value())); } - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = Everything; type BlockWeights = (); diff --git a/substrate/frame/democracy/Cargo.toml b/substrate/frame/democracy/Cargo.toml index 7bfc8c6903b..870bfaa9b89 100644 --- a/substrate/frame/democracy/Cargo.toml +++ b/substrate/frame/democracy/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet for democracy" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,14 +17,14 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = "derive", ] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", features = ["derive"], 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 } -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 } +serde = { version = "1.0.188", features = ["derive"], 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} +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} log = { version = "0.4.17", default-features = false } [dev-dependencies] @@ -36,7 +33,7 @@ pallet-scheduler = { path = "../scheduler" } pallet-preimage = { path = "../preimage" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/democracy/src/tests.rs b/substrate/frame/democracy/src/tests.rs index 00d8fedca0c..07a0ef5c3d5 100644 --- a/substrate/frame/democracy/src/tests.rs +++ b/substrate/frame/democracy/src/tests.rs @@ -20,7 +20,7 @@ use super::*; use crate as pallet_democracy; use frame_support::{ - assert_noop, assert_ok, derive_impl, ord_parameter_types, parameter_types, + assert_noop, assert_ok, ord_parameter_types, parameter_types, traits::{ ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnInitialize, SortedMembers, StorePreimage, @@ -77,8 +77,6 @@ parameter_types! { Weight::from_parts(frame_support::weights::constants::WEIGHT_REF_TIME_PER_SECOND, u64::MAX), ); } - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = BaseFilter; type BlockWeights = BlockWeights; diff --git a/substrate/frame/election-provider-multi-phase/Cargo.toml b/substrate/frame/election-provider-multi-phase/Cargo.toml index be3a77065b4..91be97d3e35 100644 --- a/substrate/frame/election-provider-multi-phase/Cargo.toml +++ b/substrate/frame/election-provider-multi-phase/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "PALLET two phase election providers" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -23,35 +20,35 @@ scale-info = { version = "2.10.0", default-features = false, features = [ ] } log = { version = "0.4.17", default-features = false } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", 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-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 = { 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} # 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.24.1", default-features = false, features = ["derive"], optional = true } +strum = { version = "0.24.1", default-features = false, features = ["derive"], optional = true } [dev-dependencies] parking_lot = "0.12.1" rand = "0.8.5" -sp-core = { path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false} sp-io = { path = "../../primitives/io" } -sp-npos-elections = { path = "../../primitives/npos-elections", default-features = false } +sp-npos-elections = { path = "../../primitives/npos-elections", default-features = false} sp-tracing = { path = "../../primitives/tracing" } pallet-balances = { path = "../balances" } frame-benchmarking = { path = "../benchmarking" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/election-provider-multi-phase/src/lib.rs b/substrate/frame/election-provider-multi-phase/src/lib.rs index 41284f6c78b..05f9b24f8f9 100644 --- a/substrate/frame/election-provider-multi-phase/src/lib.rs +++ b/substrate/frame/election-provider-multi-phase/src/lib.rs @@ -1024,7 +1024,6 @@ pub mod pallet { // ensure solution is timely. ensure!(Self::current_phase().is_signed(), Error::::PreDispatchEarlySubmission); - ensure!(raw_solution.round == Self::round(), Error::::PreDispatchDifferentRound); // NOTE: this is the only case where having separate snapshot would have been better // because could do just decode_len. But we can create abstractions to do this. @@ -1198,8 +1197,6 @@ pub mod pallet { BoundNotMet, /// Submitted solution has too many winners TooManyWinners, - /// Sumission was prepared for a different round. - PreDispatchDifferentRound, } #[pallet::validate_unsigned] diff --git a/substrate/frame/election-provider-multi-phase/src/mock.rs b/substrate/frame/election-provider-multi-phase/src/mock.rs index abad7db037e..92144351e8f 100644 --- a/substrate/frame/election-provider-multi-phase/src/mock.rs +++ b/substrate/frame/election-provider-multi-phase/src/mock.rs @@ -21,7 +21,7 @@ use frame_election_provider_support::{ bounds::{DataProviderBounds, ElectionBounds}, data_provider, onchain, ElectionDataProvider, NposSolution, SequentialPhragmen, }; -pub use frame_support::{assert_noop, assert_ok, derive_impl, pallet_prelude::GetDefault}; +pub use frame_support::{assert_noop, assert_ok, pallet_prelude::GetDefault}; use frame_support::{ parameter_types, traits::{ConstU32, Hooks}, @@ -80,7 +80,11 @@ frame_election_provider_support::generate_solution_type!( /// All events of this pallet. pub(crate) fn multi_phase_events() -> Vec> { - System::read_events_for_pallet::>() + System::events() + .into_iter() + .map(|r| r.event) + .filter_map(|e| if let RuntimeEvent::MultiPhase(inner) = e { Some(inner) } else { None }) + .collect::>() } /// To from `now` to block `n`. @@ -112,15 +116,6 @@ pub fn roll_to_with_ocw(n: BlockNumber) { } } -pub fn roll_to_round(n: u32) { - assert!(MultiPhase::round() <= n); - - while MultiPhase::round() != n { - roll_to_signed(); - assert_ok!(MultiPhase::elect()); - } -} - pub struct TrimHelpers { pub voters: Vec>, pub assignments: Vec>, @@ -209,7 +204,6 @@ pub fn witness() -> SolutionOrSnapshotSize { .unwrap_or_default() } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; diff --git a/substrate/frame/election-provider-multi-phase/src/signed.rs b/substrate/frame/election-provider-multi-phase/src/signed.rs index ae830ed0382..7e4b029ff8c 100644 --- a/substrate/frame/election-provider-multi-phase/src/signed.rs +++ b/substrate/frame/election-provider-multi-phase/src/signed.rs @@ -571,40 +571,6 @@ mod tests { use frame_support::{assert_noop, assert_ok, assert_storage_noop}; use sp_runtime::Percent; - #[test] - fn cannot_submit_on_different_round() { - ExtBuilder::default().build_and_execute(|| { - // roll to a few rounds ahead. - roll_to_round(5); - assert_eq!(MultiPhase::round(), 5); - - roll_to_signed(); - assert_eq!(MultiPhase::current_phase(), Phase::Signed); - - // create a temp snapshot only for this test. - MultiPhase::create_snapshot().unwrap(); - let mut solution = raw_solution(); - - // try a solution prepared in a previous round. - solution.round = MultiPhase::round() - 1; - - assert_noop!( - MultiPhase::submit(RuntimeOrigin::signed(10), Box::new(solution)), - Error::::PreDispatchDifferentRound, - ); - - // try a solution prepared in a later round (not expected to happen, but in any case). - MultiPhase::create_snapshot().unwrap(); - let mut solution = raw_solution(); - solution.round = MultiPhase::round() + 1; - - assert_noop!( - MultiPhase::submit(RuntimeOrigin::signed(10), Box::new(solution)), - Error::::PreDispatchDifferentRound, - ); - }) - } - #[test] fn cannot_submit_too_early() { ExtBuilder::default().build_and_execute(|| { 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 05c6a6d4046..f5d1991d199 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 @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME election provider multi phase pallet tests with staking pallet, bags-list and session pallets" publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -26,7 +23,7 @@ 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-npos-elections = { path = "../../../primitives/npos-elections", default-features = false} sp-tracing = { path = "../../../primitives/tracing" } frame-system = { path = "../../system" } 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 ecb2ae435b8..751ffc07aa5 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 @@ -276,7 +276,6 @@ impl pallet_staking::Config for Runtime { type NominationsQuota = pallet_staking::FixedNominationsQuota; type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; type HistoryDepth = HistoryDepth; type EventListeners = (); type WeightInfo = pallet_staking::weights::SubstrateWeight; diff --git a/substrate/frame/election-provider-support/Cargo.toml b/substrate/frame/election-provider-support/Cargo.toml index 8182863d796..ed36630d0d0 100644 --- a/substrate/frame/election-provider-support/Cargo.toml +++ b/substrate/frame/election-provider-support/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "election provider supporting traits" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -18,13 +15,13 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] rand = { version = "0.8.5", features = ["small_rng"] } @@ -32,8 +29,8 @@ sp-io = { path = "../../primitives/io" } sp-npos-elections = { path = "../../primitives/npos-elections" } [features] -default = ["std"] -fuzz = ["default"] +default = [ "std" ] +fuzz = [ "default" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/election-provider-support/benchmarking/Cargo.toml b/substrate/frame/election-provider-support/benchmarking/Cargo.toml index 7a2ad5cafb4..a8c56b425fd 100644 --- a/substrate/frame/election-provider-support/benchmarking/Cargo.toml +++ b/substrate/frame/election-provider-support/benchmarking/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "Benchmarking for election provider support onchain config trait" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -18,15 +15,15 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, 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 } +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} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/election-provider-support/solution-type/Cargo.toml b/substrate/frame/election-provider-support/solution-type/Cargo.toml index ba36daebec3..1e3002d5dc4 100644 --- a/substrate/frame/election-provider-support/solution-type/Cargo.toml +++ b/substrate/frame/election-provider-support/solution-type/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "NPoS Solution Type" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -18,10 +15,10 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -syn = { version = "2.0.40", features = ["full", "visit"] } +syn = { version = "2.0.38", features = ["full", "visit"] } quote = "1.0.28" proc-macro2 = "1.0.56" -proc-macro-crate = "2.0.1" +proc-macro-crate = "1.1.3" [dev-dependencies] parity-scale-codec = "3.6.1" 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 a7a84b91dba..cc90ed119ad 100644 --- a/substrate/frame/election-provider-support/solution-type/fuzzer/Cargo.toml +++ b/substrate/frame/election-provider-support/solution-type/fuzzer/Cargo.toml @@ -9,16 +9,13 @@ repository.workspace = true description = "Fuzzer for phragmén solution type implementation." publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } honggfuzz = "0.5" -rand = { version = "0.8", features = ["small_rng", "std"] } +rand = { version = "0.8", features = ["std", "small_rng"] } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } @@ -27,7 +24,7 @@ frame-election-provider-support = { path = "../.." } sp-arithmetic = { path = "../../../../primitives/arithmetic" } sp-runtime = { path = "../../../../primitives/runtime" } # used by generate_solution_type: -sp-npos-elections = { path = "../../../../primitives/npos-elections", default-features = false } +sp-npos-elections = { path = "../../../../primitives/npos-elections", default-features = false} frame-support = { path = "../../../support" } [[bin]] diff --git a/substrate/frame/election-provider-support/src/onchain.rs b/substrate/frame/election-provider-support/src/onchain.rs index 412aac45475..8ac245a360b 100644 --- a/substrate/frame/election-provider-support/src/onchain.rs +++ b/substrate/frame/election-provider-support/src/onchain.rs @@ -182,7 +182,7 @@ impl ElectionProvider for OnChainExecution { mod tests { use super::*; use crate::{ElectionProvider, PhragMMS, SequentialPhragmen}; - use frame_support::{assert_noop, derive_impl, parameter_types}; + use frame_support::{assert_noop, parameter_types}; use sp_npos_elections::Support; use sp_runtime::Perbill; type AccountId = u64; @@ -200,7 +200,6 @@ mod tests { } ); - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; diff --git a/substrate/frame/elections-phragmen/Cargo.toml b/substrate/frame/elections-phragmen/Cargo.toml index 3c0bc56a1d0..cb8bc1035a5 100644 --- a/substrate/frame/elections-phragmen/Cargo.toml +++ b/substrate/frame/elections-phragmen/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet based on seq-Phragmén election method." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,15 +18,15 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = ] } log = { version = "0.4.14", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } @@ -38,7 +35,7 @@ sp-tracing = { path = "../../primitives/tracing" } substrate-test-utils = { path = "../../test-utils" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/elections-phragmen/src/lib.rs b/substrate/frame/elections-phragmen/src/lib.rs index 6be07e408fe..89fd296cce8 100644 --- a/substrate/frame/elections-phragmen/src/lib.rs +++ b/substrate/frame/elections-phragmen/src/lib.rs @@ -1307,7 +1307,7 @@ mod tests { use super::*; use crate as elections_phragmen; use frame_support::{ - assert_noop, assert_ok, derive_impl, + assert_noop, assert_ok, dispatch::DispatchResultWithPostInfo, parameter_types, traits::{ConstU32, ConstU64, OnInitialize}, @@ -1321,7 +1321,6 @@ mod tests { }; use substrate_test_utils::assert_eq_uvec; - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/elections-phragmen/src/migrations/v4.rs b/substrate/frame/elections-phragmen/src/migrations/v4.rs index e78465cd618..7e946371f5c 100644 --- a/substrate/frame/elections-phragmen/src/migrations/v4.rs +++ b/substrate/frame/elections-phragmen/src/migrations/v4.rs @@ -69,7 +69,7 @@ pub fn migrate>(new_pallet_name: N) -> Weight { } /// Some checks prior to migration. This can be linked to -/// `frame_support::traits::OnRuntimeUpgrade::pre_upgrade` for further testing. +/// [`frame_support::traits::OnRuntimeUpgrade::pre_upgrade`] for further testing. /// /// Panics if anything goes wrong. pub fn pre_migration>(new: N) { @@ -97,7 +97,7 @@ pub fn pre_migration>(new: N) { } /// Some checks for after migration. This can be linked to -/// `frame_support::traits::OnRuntimeUpgrade::post_upgrade` for further testing. +/// [`frame_support::traits::OnRuntimeUpgrade::post_upgrade`] for further testing. /// /// Panics if anything goes wrong. pub fn post_migration() { diff --git a/substrate/frame/elections-phragmen/src/migrations/v5.rs b/substrate/frame/elections-phragmen/src/migrations/v5.rs index 6e360aa8b8c..6fac923703f 100644 --- a/substrate/frame/elections-phragmen/src/migrations/v5.rs +++ b/substrate/frame/elections-phragmen/src/migrations/v5.rs @@ -71,7 +71,7 @@ pub fn pre_migrate_fn(to_migrate: Vec) -> Box() { diff --git a/substrate/frame/examples/Cargo.toml b/substrate/frame/examples/Cargo.toml index eb6355edd31..1b215022715 100644 --- a/substrate/frame/examples/Cargo.toml +++ b/substrate/frame/examples/Cargo.toml @@ -9,24 +9,20 @@ repository.workspace = true description = "The single package with examples of various types of FRAME pallets" publish = false -[lints] -workspace = true - [package.metadata.docs.rs] 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-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-tasks = { path = "tasks", 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} [features] -default = ["std"] +default = [ "std" ] std = [ "pallet-default-config-example/std", "pallet-dev-mode/std", @@ -35,7 +31,6 @@ std = [ "pallet-example-kitchensink/std", "pallet-example-offchain-worker/std", "pallet-example-split/std", - "pallet-example-tasks/std", ] try-runtime = [ "pallet-default-config-example/try-runtime", @@ -44,5 +39,4 @@ try-runtime = [ "pallet-example-kitchensink/try-runtime", "pallet-example-offchain-worker/try-runtime", "pallet-example-split/try-runtime", - "pallet-example-tasks/try-runtime", ] diff --git a/substrate/frame/examples/basic/Cargo.toml b/substrate/frame/examples/basic/Cargo.toml index 3be1a2e558d..d39a93e7abb 100644 --- a/substrate/frame/examples/basic/Cargo.toml +++ b/substrate/frame/examples/basic/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME example pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,19 +16,19 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] -sp-core = { path = "../../../primitives/core", default-features = false } +sp-core = { path = "../../../primitives/core", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/examples/basic/src/tests.rs b/substrate/frame/examples/basic/src/tests.rs index d223203ad1b..443feb5d96f 100644 --- a/substrate/frame/examples/basic/src/tests.rs +++ b/substrate/frame/examples/basic/src/tests.rs @@ -19,7 +19,7 @@ use crate::*; use frame_support::{ - assert_ok, derive_impl, + assert_ok, dispatch::{DispatchInfo, GetDispatchInfo}, traits::{ConstU64, OnInitialize}, }; @@ -45,7 +45,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/examples/default-config/Cargo.toml b/substrate/frame/examples/default-config/Cargo.toml index 01ddf9d3834..13b6ce74543 100644 --- a/substrate/frame/examples/default-config/Cargo.toml +++ b/substrate/frame/examples/default-config/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME example pallet demonstrating derive_impl / default_config in action" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,15 +16,15 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", 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 } +sp-io = { path = "../../../primitives/io", default-features = false} +sp-runtime = { path = "../../../primitives/runtime", default-features = false} +sp-std = { path = "../../../primitives/std", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/examples/default-config/src/lib.rs b/substrate/frame/examples/default-config/src/lib.rs index f1611bca2ce..8a1f6f9d6a8 100644 --- a/substrate/frame/examples/default-config/src/lib.rs +++ b/substrate/frame/examples/default-config/src/lib.rs @@ -47,10 +47,6 @@ pub mod pallet { #[pallet::no_default] // optional. `RuntimeEvent` is automatically excluded as well. type RuntimeEvent: From> + IsType<::RuntimeEvent>; - /// The overarching task type. - #[pallet::no_default] - type RuntimeTask: Task; - /// An input parameter to this pallet. This value can have a default, because it is not /// reliant on `frame_system::Config` or the overarching runtime in any way. type WithDefaultValue: Get; @@ -197,7 +193,6 @@ pub mod tests { impl pallet_default_config_example::Config for Runtime { // These two both cannot have defaults. type RuntimeEvent = RuntimeEvent; - type RuntimeTask = RuntimeTask; type HasNoDefault = frame_support::traits::ConstU32<1>; type CannotHaveDefault = SomeCall; diff --git a/substrate/frame/examples/dev-mode/Cargo.toml b/substrate/frame/examples/dev-mode/Cargo.toml index f634d21cf2c..806af334bb0 100644 --- a/substrate/frame/examples/dev-mode/Cargo.toml +++ b/substrate/frame/examples/dev-mode/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME example pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,18 +16,18 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] -sp-core = { path = "../../../primitives/core", default-features = false } +sp-core = { path = "../../../primitives/core", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/examples/dev-mode/src/tests.rs b/substrate/frame/examples/dev-mode/src/tests.rs index 3acedcd0fd1..c7722bc0524 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, traits::ConstU64}; use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -39,7 +39,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/examples/frame-crate/Cargo.toml b/substrate/frame/examples/frame-crate/Cargo.toml index 93a46ba7b24..ceb8c7bfb81 100644 --- a/substrate/frame/examples/frame-crate/Cargo.toml +++ b/substrate/frame/examples/frame-crate/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME example pallet with umbrella crate" publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,9 +16,9 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.5.0", default-features = false, features = ["derive"] } -frame = { path = "../..", default-features = false, features = ["experimental", "runtime"] } +frame = { path = "../..", default-features = false, features = ["runtime", "experimental"] } [features] -default = ["std"] -std = ["codec/std", "frame/std", "scale-info/std"] +default = [ "std" ] +std = [ "codec/std", "frame/std", "scale-info/std" ] diff --git a/substrate/frame/examples/kitchensink/Cargo.toml b/substrate/frame/examples/kitchensink/Cargo.toml index 4255ebb66b6..1275ef0b53f 100644 --- a/substrate/frame/examples/kitchensink/Cargo.toml +++ b/substrate/frame/examples/kitchensink/Cargo.toml @@ -7,10 +7,6 @@ license = "MIT-0" homepage = "https://substrate.io" repository.workspace = true description = "FRAME example kitchensink pallet" -publish = false - -[lints] -workspace = true [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,22 +16,22 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", 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 } +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 = { path = "../../benchmarking", default-features = false, optional = true } +frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true} -pallet-balances = { path = "../../balances", default-features = false } +pallet-balances = { path = "../../balances", default-features = false} [dev-dependencies] -sp-core = { path = "../../../primitives/core", default-features = false } +sp-core = { path = "../../../primitives/core", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/examples/kitchensink/src/lib.rs b/substrate/frame/examples/kitchensink/src/lib.rs index 18429bc967d..89759dd0bf6 100644 --- a/substrate/frame/examples/kitchensink/src/lib.rs +++ b/substrate/frame/examples/kitchensink/src/lib.rs @@ -292,8 +292,9 @@ pub mod pallet { } } - /// Allows you to define an enum on the pallet which will then instruct `construct_runtime` to - /// amalgamate all similarly-named enums from other pallets into an aggregate enum. + /// Allows you to define an enum on the pallet which will then instruct + /// `construct_runtime` to amalgamate all similarly-named enums from other + /// pallets into an aggregate enum. #[pallet::composite_enum] pub enum HoldReason { Staking, diff --git a/substrate/frame/examples/offchain-worker/Cargo.toml b/substrate/frame/examples/offchain-worker/Cargo.toml index 464719375c6..e6b7715655d 100644 --- a/substrate/frame/examples/offchain-worker/Cargo.toml +++ b/substrate/frame/examples/offchain-worker/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME example pallet for offchain worker" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,16 +17,16 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = lite-json = { version = "0.2.0", default-features = false } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } -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} +sp-core = { path = "../../../primitives/core", default-features = false} +sp-io = { path = "../../../primitives/io", default-features = false} +sp-keystore = { path = "../../../primitives/keystore", optional = true} +sp-runtime = { path = "../../../primitives/runtime", default-features = false} +sp-std = { path = "../../../primitives/std", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/examples/offchain-worker/src/tests.rs b/substrate/frame/examples/offchain-worker/src/tests.rs index 48a8d86588c..203a59a8af0 100644 --- a/substrate/frame/examples/offchain-worker/src/tests.rs +++ b/substrate/frame/examples/offchain-worker/src/tests.rs @@ -19,7 +19,7 @@ use crate as example_offchain_worker; use crate::*; use codec::Decode; use frame_support::{ - assert_ok, derive_impl, parameter_types, + assert_ok, parameter_types, traits::{ConstU32, ConstU64}, }; use sp_core::{ @@ -46,7 +46,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/examples/split/Cargo.toml b/substrate/frame/examples/split/Cargo.toml index 97f9062f181..db2a75e388d 100644 --- a/substrate/frame/examples/split/Cargo.toml +++ b/substrate/frame/examples/split/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME example splitted pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,19 +17,19 @@ codec = { package = "parity-scale-codec", version = "3.2.2", default-features = log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", 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-std = { path = "../../../primitives/std", default-features = false } +sp-io = { path = "../../../primitives/io", default-features = false} +sp-std = { path = "../../../primitives/std", default-features = false} -frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true } +frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true} [dev-dependencies] -sp-core = { path = "../../../primitives/core", default-features = false } +sp-core = { path = "../../../primitives/core", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", @@ -49,4 +46,4 @@ runtime-benchmarks = [ "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", ] -try-runtime = ["frame-support/try-runtime", "frame-system/try-runtime"] +try-runtime = [ "frame-support/try-runtime", "frame-system/try-runtime" ] diff --git a/substrate/frame/examples/src/lib.rs b/substrate/frame/examples/src/lib.rs index f38bbe52dc1..8d65639f835 100644 --- a/substrate/frame/examples/src/lib.rs +++ b/substrate/frame/examples/src/lib.rs @@ -43,6 +43,4 @@ //! - [`pallet_example_frame_crate`]: Example pallet showcasing how one can be //! built using only the `frame` umbrella crate. //! -//! - [`pallet_example_tasks`]: This pallet demonstrates the use of `Tasks` to execute service work. -//! //! **Tip**: Use `cargo doc --package --open` to view each pallet's documentation. diff --git a/substrate/frame/examples/tasks/Cargo.toml b/substrate/frame/examples/tasks/Cargo.toml deleted file mode 100644 index 046bad908d1..00000000000 --- a/substrate/frame/examples/tasks/Cargo.toml +++ /dev/null @@ -1,55 +0,0 @@ -[package] -name = "pallet-example-tasks" -version = "1.0.0-dev" -authors.workspace = true -edition.workspace = true -license.workspace = true -repository.workspace = true -description = "Pallet to demonstrate the usage of Tasks to recongnize and execute service work" - -[lints] -workspace = true - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } -log = { version = "0.4.17", default-features = false } -scale-info = { version = "2.10.0", 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 } -sp-core = { version = "21.0.0", default-features = false, path = "../../../primitives/core" } - -frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true } - -[features] -default = ["std"] -std = [ - "codec/std", - "frame-benchmarking?/std", - "frame-support/std", - "frame-system/std", - "log/std", - "scale-info/std", - "sp-core/std", - "sp-io/std", - "sp-runtime/std", - "sp-std/std", -] -runtime-benchmarks = [ - "frame-benchmarking/runtime-benchmarks", - "frame-support/runtime-benchmarks", - "frame-system/runtime-benchmarks", - "sp-runtime/runtime-benchmarks", -] -try-runtime = [ - "frame-support/try-runtime", - "frame-system/try-runtime", - "sp-runtime/try-runtime", -] diff --git a/substrate/frame/examples/tasks/src/benchmarking.rs b/substrate/frame/examples/tasks/src/benchmarking.rs deleted file mode 100644 index 81f7d3d3b21..00000000000 --- a/substrate/frame/examples/tasks/src/benchmarking.rs +++ /dev/null @@ -1,42 +0,0 @@ -// 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. - -//! Benchmarking for `pallet-example-tasks`. - -#![cfg(feature = "runtime-benchmarks")] - -use crate::*; -use frame_benchmarking::v2::*; - -#[benchmarks] -mod benchmarks { - use super::*; - - #[benchmark] - fn add_number_into_total() { - Numbers::::insert(0, 1); - - #[block] - { - Task::::add_number_into_total(0).unwrap(); - } - - assert_eq!(Numbers::::get(0), None); - } - - impl_benchmark_test_suite!(Pallet, crate::tests::new_test_ext(), crate::mock::Runtime); -} diff --git a/substrate/frame/examples/tasks/src/lib.rs b/substrate/frame/examples/tasks/src/lib.rs deleted file mode 100644 index c65d8095bcf..00000000000 --- a/substrate/frame/examples/tasks/src/lib.rs +++ /dev/null @@ -1,78 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! This pallet demonstrates the use of the `pallet::task` api for service work. -#![cfg_attr(not(feature = "std"), no_std)] - -use frame_support::dispatch::DispatchResult; -// Re-export pallet items so that they can be accessed from the crate namespace. -pub use pallet::*; - -pub mod mock; -pub mod tests; - -#[cfg(feature = "runtime-benchmarks")] -mod benchmarking; - -pub mod weights; -pub use weights::*; - -#[frame_support::pallet(dev_mode)] -pub mod pallet { - use super::*; - use frame_support::pallet_prelude::*; - - #[pallet::error] - pub enum Error { - /// The referenced task was not found. - NotFound, - } - - #[pallet::tasks_experimental] - impl Pallet { - /// Add a pair of numbers into the totals and remove them. - #[pallet::task_list(Numbers::::iter_keys())] - #[pallet::task_condition(|i| Numbers::::contains_key(i))] - #[pallet::task_weight(T::WeightInfo::add_number_into_total())] - #[pallet::task_index(0)] - pub fn add_number_into_total(i: u32) -> DispatchResult { - let v = Numbers::::take(i).ok_or(Error::::NotFound)?; - Total::::mutate(|(total_keys, total_values)| { - *total_keys += i; - *total_values += v; - }); - Ok(()) - } - } - - #[pallet::config] - pub trait Config: frame_system::Config { - type RuntimeTask: frame_support::traits::Task; - type WeightInfo: WeightInfo; - } - - #[pallet::pallet] - pub struct Pallet(_); - - /// Some running total. - #[pallet::storage] - pub type Total = StorageValue<_, (u32, u32), ValueQuery>; - - /// Numbers to be added into the total. - #[pallet::storage] - pub type Numbers = StorageMap<_, Twox64Concat, u32, u32, OptionQuery>; -} diff --git a/substrate/frame/examples/tasks/src/mock.rs b/substrate/frame/examples/tasks/src/mock.rs deleted file mode 100644 index e0fbec3eb76..00000000000 --- a/substrate/frame/examples/tasks/src/mock.rs +++ /dev/null @@ -1,43 +0,0 @@ -// 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. - -//! Mock runtime for `tasks-example` tests. -#![cfg(test)] - -use crate::{self as tasks_example}; -use frame_support::derive_impl; - -pub type AccountId = u32; -pub type Balance = u32; - -type Block = frame_system::mocking::MockBlock; -frame_support::construct_runtime!( - pub struct Runtime { - System: frame_system, - TasksExample: tasks_example, - } -); - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] -impl frame_system::Config for Runtime { - type Block = Block; -} - -impl tasks_example::Config for Runtime { - type RuntimeTask = RuntimeTask; - type WeightInfo = (); -} diff --git a/substrate/frame/examples/tasks/src/tests.rs b/substrate/frame/examples/tasks/src/tests.rs deleted file mode 100644 index 6b255491091..00000000000 --- a/substrate/frame/examples/tasks/src/tests.rs +++ /dev/null @@ -1,127 +0,0 @@ -// 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-example-tasks`. -#![cfg(test)] - -use crate::{mock::*, Numbers, Total}; -use frame_support::{assert_noop, assert_ok, traits::Task}; -use sp_runtime::BuildStorage; - -// This function basically just builds a genesis storage key/value store according to -// our desired mockup. -pub fn new_test_ext() -> sp_io::TestExternalities { - let t = RuntimeGenesisConfig { - // We use default for brevity, but you can configure as desired if needed. - system: Default::default(), - } - .build_storage() - .unwrap(); - t.into() -} - -#[test] -fn task_enumerate_works() { - new_test_ext().execute_with(|| { - Numbers::::insert(0, 1); - assert_eq!(crate::pallet::Task::::iter().collect::>().len(), 1); - }); -} - -#[test] -fn runtime_task_enumerate_works_via_frame_system_config() { - new_test_ext().execute_with(|| { - Numbers::::insert(0, 1); - Numbers::::insert(1, 4); - assert_eq!( - ::RuntimeTask::iter().collect::>().len(), - 2 - ); - }); -} - -#[test] -fn runtime_task_enumerate_works_via_pallet_config() { - new_test_ext().execute_with(|| { - Numbers::::insert(1, 4); - assert_eq!( - ::RuntimeTask::iter() - .collect::>() - .len(), - 1 - ); - }); -} - -#[test] -fn task_index_works_at_pallet_level() { - new_test_ext().execute_with(|| { - assert_eq!(crate::pallet::Task::::AddNumberIntoTotal { i: 2u32 }.task_index(), 0); - }); -} - -#[test] -fn task_index_works_at_runtime_level() { - new_test_ext().execute_with(|| { - assert_eq!( - ::RuntimeTask::TasksExample(crate::pallet::Task::< - Runtime, - >::AddNumberIntoTotal { - i: 1u32 - }) - .task_index(), - 0 - ); - }); -} - -#[test] -fn task_execution_works() { - new_test_ext().execute_with(|| { - System::set_block_number(1); - Numbers::::insert(0, 1); - Numbers::::insert(1, 4); - - let task = - ::RuntimeTask::TasksExample(crate::pallet::Task::< - Runtime, - >::AddNumberIntoTotal { - i: 1u32, - }); - assert_ok!(System::do_task(RuntimeOrigin::signed(1), task.clone(),)); - assert_eq!(Numbers::::get(0), Some(1)); - assert_eq!(Numbers::::get(1), None); - assert_eq!(Total::::get(), (1, 4)); - System::assert_last_event(frame_system::Event::::TaskCompleted { task }.into()); - }); -} - -#[test] -fn task_execution_fails_for_invalid_task() { - new_test_ext().execute_with(|| { - Numbers::::insert(1, 4); - assert_noop!( - System::do_task( - RuntimeOrigin::signed(1), - ::RuntimeTask::TasksExample( - crate::pallet::Task::::AddNumberIntoTotal { i: 0u32 } - ), - ), - frame_system::Error::::InvalidTask - ); - }); -} diff --git a/substrate/frame/examples/tasks/src/weights.rs b/substrate/frame/examples/tasks/src/weights.rs deleted file mode 100644 index 793af6e9622..00000000000 --- a/substrate/frame/examples/tasks/src/weights.rs +++ /dev/null @@ -1,84 +0,0 @@ -// 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. - -//! Autogenerated weights for `pallet_example_tasks` -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-06-02, STEPS: `20`, REPEAT: `10`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `MacBook.local`, CPU: `` -//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 - -// Executed Command: -// ./target/release/node-template -// benchmark -// pallet -// --chain -// dev -// --pallet -// pallet_example_tasks -// --extrinsic -// * -// --steps -// 20 -// --repeat -// 10 -// --output -// frame/examples/tasks/src/weights.rs - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(missing_docs)] - -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; -use core::marker::PhantomData; - -/// Weight functions needed for pallet_template. -pub trait WeightInfo { - fn add_number_into_total() -> Weight; -} - -/// Weight functions for `pallet_example_kitchensink`. -pub struct SubstrateWeight(PhantomData); -impl WeightInfo for SubstrateWeight { - /// Storage: Kitchensink OtherFoo (r:0 w:1) - /// Proof Skipped: Kitchensink OtherFoo (max_values: Some(1), max_size: None, mode: Measured) - fn add_number_into_total() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 1_000_000 picoseconds. - Weight::from_parts(1_000_000, 0) - .saturating_add(Weight::from_parts(0, 0)) - .saturating_add(T::DbWeight::get().writes(1)) - } -} - -impl WeightInfo for () { - /// Storage: Kitchensink OtherFoo (r:0 w:1) - /// Proof Skipped: Kitchensink OtherFoo (max_values: Some(1), max_size: None, mode: Measured) - fn add_number_into_total() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 1_000_000 picoseconds. - Weight::from_parts(1_000_000, 0) - .saturating_add(Weight::from_parts(0, 0)) - .saturating_add(RocksDbWeight::get().writes(1)) - } -} diff --git a/substrate/frame/executive/Cargo.toml b/substrate/frame/executive/Cargo.toml index b98ceb0ba9a..32983a32c4f 100644 --- a/substrate/frame/executive/Cargo.toml +++ b/substrate/frame/executive/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME executives engine" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,14 +18,14 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = ] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } +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 } +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} [dev-dependencies] array-bytes = "6.1" @@ -40,8 +37,8 @@ sp-io = { path = "../../primitives/io" } sp-version = { path = "../../primitives/version" } [features] -default = ["std"] -with-tracing = ["sp-tracing/with-tracing"] +default = [ "std" ] +with-tracing = [ "sp-tracing/with-tracing" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/executive/README.md b/substrate/frame/executive/README.md index 6151232ecaf..96a412a4537 100644 --- a/substrate/frame/executive/README.md +++ b/substrate/frame/executive/README.md @@ -34,13 +34,14 @@ The default Substrate node template declares the `Executive` type declaration from the node template. ```rust +# /// Executive: handles dispatch to the various modules. pub type Executive = executive::Executive< Runtime, Block, Context, Runtime, - AllPalletsWithSystem, + AllPallets, >; ``` @@ -50,6 +51,7 @@ You can add custom logic that should be called in your runtime on a runtime upgr generic parameter. The custom logic will be called before the on runtime upgrade logic of all modules is called. ```rust +# struct CustomOnRuntimeUpgrade; impl frame_support::traits::OnRuntimeUpgrade for CustomOnRuntimeUpgrade { fn on_runtime_upgrade() -> frame_support::weights::Weight { @@ -63,7 +65,7 @@ pub type Executive = executive::Executive< Block, Context, Runtime, - AllPalletsWithSystem, + AllPallets, CustomOnRuntimeUpgrade, >; ``` diff --git a/substrate/frame/executive/src/lib.rs b/substrate/frame/executive/src/lib.rs index 8efb5bb9e59..625f92ab59a 100644 --- a/substrate/frame/executive/src/lib.rs +++ b/substrate/frame/executive/src/lib.rs @@ -362,13 +362,9 @@ where Ok(frame_system::Pallet::::block_weight().total()) } - /// Execute all Migrations of this runtime. + /// Execute all `OnRuntimeUpgrade` of this runtime. /// /// The `checks` param determines whether to execute `pre/post_upgrade` and `try_state` hooks. - /// - /// [`frame_system::LastRuntimeUpgrade`] is set to the current runtime version after - /// migrations execute. This is important for idempotency checks, because some migrations use - /// this value to determine whether or not they should execute. pub fn try_runtime_upgrade(checks: UpgradeCheckSelect) -> Result { let before_all_weight = ::before_all_runtime_migrations(); @@ -376,13 +372,6 @@ where <(COnRuntimeUpgrade, AllPalletsWithSystem) as OnRuntimeUpgrade>::try_on_runtime_upgrade( checks.pre_and_post(), )?; - - frame_system::LastRuntimeUpgrade::::put( - frame_system::LastRuntimeUpgradeInfo::from( - >::get(), - ), - ); - // Nothing should modify the state after the migrations ran: let _guard = StorageNoopGuard::default(); @@ -761,7 +750,7 @@ mod tests { }; use frame_support::{ - assert_err, derive_impl, parameter_types, + assert_err, parameter_types, traits::{fungible, ConstU32, ConstU64, ConstU8, Currency}, weights::{ConstantMultiplier, IdentityFee, RuntimeDbWeight, Weight, WeightToFee}, }; @@ -917,7 +906,6 @@ mod tests { write: 100, }; } - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = BlockWeights; diff --git a/substrate/frame/fast-unstake/Cargo.toml b/substrate/frame/fast-unstake/Cargo.toml index 673a2f71d6c..2aa2e918f3e 100644 --- a/substrate/frame/fast-unstake/Cargo.toml +++ b/substrate/frame/fast-unstake/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME fast unstake pallet" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,22 +16,22 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", 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 } -sp-staking = { path = "../../primitives/staking", default-features = false } -frame-election-provider-support = { path = "../election-provider-support", 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-staking = { path = "../../primitives/staking", default-features = false} +frame-election-provider-support = { path = "../election-provider-support", default-features = false} -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } +frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true} docify = "0.2.6" [dev-dependencies] pallet-staking-reward-curve = { path = "../staking/reward-curve" } -sp-core = { path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false} substrate-test-utils = { path = "../../test-utils" } sp-tracing = { path = "../../primitives/tracing" } pallet-staking = { path = "../staking" } @@ -42,7 +39,7 @@ pallet-balances = { path = "../balances" } pallet-timestamp = { path = "../timestamp" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking/std", diff --git a/substrate/frame/fast-unstake/src/mock.rs b/substrate/frame/fast-unstake/src/mock.rs index f9326919fd3..09a08f222b6 100644 --- a/substrate/frame/fast-unstake/src/mock.rs +++ b/substrate/frame/fast-unstake/src/mock.rs @@ -142,7 +142,6 @@ impl pallet_staking::Config for Runtime { 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 = (); diff --git a/substrate/frame/fast-unstake/src/types.rs b/substrate/frame/fast-unstake/src/types.rs index 3fb5720861f..15d0a327e91 100644 --- a/substrate/frame/fast-unstake/src/types.rs +++ b/substrate/frame/fast-unstake/src/types.rs @@ -39,7 +39,6 @@ impl frame_support::traits::Get for MaxChecking { } } -#[docify::export] pub(crate) type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; /// An unstake request. diff --git a/substrate/frame/glutton/Cargo.toml b/substrate/frame/glutton/Cargo.toml index 068fb4e821c..368fcab65cc 100644 --- a/substrate/frame/glutton/Cargo.toml +++ b/substrate/frame/glutton/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet for pushing a chain to its weight limits" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,19 +17,19 @@ blake2 = { version = "0.10.4", default-features = false } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } log = { version = "0.4.14", 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-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 = { 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} [dev-dependencies] pallet-balances = { path = "../balances" } [features] -default = ["std"] +default = [ "std" ] std = [ "blake2/std", "codec/std", diff --git a/substrate/frame/glutton/src/mock.rs b/substrate/frame/glutton/src/mock.rs index 31b78efc574..4bc40b54788 100644 --- a/substrate/frame/glutton/src/mock.rs +++ b/substrate/frame/glutton/src/mock.rs @@ -19,7 +19,7 @@ use super::*; use crate as pallet_glutton; use frame_support::{ - assert_ok, derive_impl, + assert_ok, traits::{ConstU32, ConstU64}, }; use sp_core::H256; @@ -38,7 +38,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/grandpa/Cargo.toml b/substrate/frame/grandpa/Cargo.toml index b4f51d88c6d..5eacc21721b 100644 --- a/substrate/frame/grandpa/Cargo.toml +++ b/substrate/frame/grandpa/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet for GRANDPA finality gadget" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,19 +16,19 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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-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-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-std = { path = "../../primitives/std", default-features = false} [dev-dependencies] grandpa = { package = "finality-grandpa", version = "0.16.2", features = ["derive-codec"] } @@ -45,7 +42,7 @@ pallet-timestamp = { path = "../timestamp" } sp-keyring = { path = "../../primitives/keyring" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/grandpa/src/migrations/v4.rs b/substrate/frame/grandpa/src/migrations/v4.rs index 9daa818071f..8604296b6e5 100644 --- a/substrate/frame/grandpa/src/migrations/v4.rs +++ b/substrate/frame/grandpa/src/migrations/v4.rs @@ -63,7 +63,7 @@ pub fn migrate>(new_pallet_name: N) -> Weight { } /// Some checks prior to migration. This can be linked to -/// `frame_support::traits::OnRuntimeUpgrade::pre_upgrade` for further testing. +/// [`frame_support::traits::OnRuntimeUpgrade::pre_upgrade`] for further testing. /// /// Panics if anything goes wrong. pub fn pre_migration>(new: N) { @@ -99,7 +99,7 @@ pub fn pre_migration>(new: N) { } /// Some checks for after migration. This can be linked to -/// `frame_support::traits::OnRuntimeUpgrade::post_upgrade` for further testing. +/// [`frame_support::traits::OnRuntimeUpgrade::post_upgrade`] for further testing. /// /// Panics if anything goes wrong. pub fn post_migration() { diff --git a/substrate/frame/grandpa/src/mock.rs b/substrate/frame/grandpa/src/mock.rs index f1f51e0b118..9afcec1c797 100644 --- a/substrate/frame/grandpa/src/mock.rs +++ b/substrate/frame/grandpa/src/mock.rs @@ -27,7 +27,7 @@ use frame_election_provider_support::{ onchain, SequentialPhragmen, }; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU128, ConstU32, ConstU64, KeyOwnerProofSystem, OnFinalize, OnInitialize}, }; use pallet_session::historical as pallet_session_historical; @@ -66,7 +66,6 @@ impl_opaque_keys! { } } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); @@ -206,7 +205,6 @@ impl pallet_staking::Config for Test { 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; diff --git a/substrate/frame/identity/Cargo.toml b/substrate/frame/identity/Cargo.toml index a562d7607b4..309c0aab550 100644 --- a/substrate/frame/identity/Cargo.toml +++ b/substrate/frame/identity/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME identity management pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,19 +16,19 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } enumflags2 = { version = "0.7.7" } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } sp-core = { path = "../../primitives/core" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "enumflags2/std", diff --git a/substrate/frame/identity/src/tests.rs b/substrate/frame/identity/src/tests.rs index 8ac7b4d66cb..78074df933a 100644 --- a/substrate/frame/identity/src/tests.rs +++ b/substrate/frame/identity/src/tests.rs @@ -25,7 +25,7 @@ use crate::{ use codec::{Decode, Encode}; use frame_support::{ - assert_noop, assert_ok, derive_impl, ord_parameter_types, parameter_types, + assert_noop, assert_ok, ord_parameter_types, parameter_types, traits::{ConstU32, ConstU64, EitherOfDiverse, Get}, BoundedVec, }; @@ -47,7 +47,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/im-online/Cargo.toml b/substrate/frame/im-online/Cargo.toml index b5b01858c89..d83ff540648 100644 --- a/substrate/frame/im-online/Cargo.toml +++ b/substrate/frame/im-online/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME's I'm online pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,22 +16,22 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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-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 } +sp-std = { path = "../../primitives/std", default-features = false} [dev-dependencies] pallet-session = { path = "../session" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/im-online/src/mock.rs b/substrate/frame/im-online/src/mock.rs index 2f4e3922026..85da061fe90 100644 --- a/substrate/frame/im-online/src/mock.rs +++ b/substrate/frame/im-online/src/mock.rs @@ -20,7 +20,7 @@ #![cfg(test)] use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64}, weights::Weight, }; @@ -113,7 +113,6 @@ pub fn new_test_ext() -> sp_io::TestExternalities { result } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/indices/Cargo.toml b/substrate/frame/indices/Cargo.toml index 4f0c780c6af..d392522718a 100644 --- a/substrate/frame/indices/Cargo.toml +++ b/substrate/frame/indices/Cargo.toml @@ -9,29 +9,26 @@ repository.workspace = true description = "FRAME indices management pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", 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 } -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 = { 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} +sp-runtime = { path = "../../primitives/runtime", default-features = false} +sp-std = { path = "../../primitives/std", default-features = false} [dev-dependencies] pallet-balances = { path = "../balances" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/indices/src/mock.rs b/substrate/frame/indices/src/mock.rs index 913a37fe55b..7dc6730d34e 100644 --- a/substrate/frame/indices/src/mock.rs +++ b/substrate/frame/indices/src/mock.rs @@ -20,10 +20,7 @@ #![cfg(test)] use crate::{self as pallet_indices, Config}; -use frame_support::{ - derive_impl, - traits::{ConstU32, ConstU64}, -}; +use frame_support::traits::{ConstU32, ConstU64}; use sp_core::H256; use sp_runtime::BuildStorage; @@ -38,7 +35,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/insecure-randomness-collective-flip/Cargo.toml b/substrate/frame/insecure-randomness-collective-flip/Cargo.toml index fb1447d1045..07c5e3997d2 100644 --- a/substrate/frame/insecure-randomness-collective-flip/Cargo.toml +++ b/substrate/frame/insecure-randomness-collective-flip/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Insecure do not use in production: FRAME randomness collective flip pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,17 +16,17 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } safe-mix = { version = "1.0", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] sp-core = { path = "../../primitives/core" } sp-io = { path = "../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/insecure-randomness-collective-flip/src/lib.rs b/substrate/frame/insecure-randomness-collective-flip/src/lib.rs index c7ed22d1dd5..474087777c4 100644 --- a/substrate/frame/insecure-randomness-collective-flip/src/lib.rs +++ b/substrate/frame/insecure-randomness-collective-flip/src/lib.rs @@ -169,7 +169,7 @@ mod tests { }; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64, OnInitialize, Randomness}, }; use frame_system::limits; @@ -189,7 +189,6 @@ mod tests { ::max(2 * 1024); } - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/lottery/Cargo.toml b/substrate/frame/lottery/Cargo.toml index 49f84b04b25..a4942abf243 100644 --- a/substrate/frame/lottery/Cargo.toml +++ b/substrate/frame/lottery/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME Participation Lottery Pallet" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,11 +16,11 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = "derive", ] } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] frame-support-test = { path = "../support/test" } @@ -32,7 +29,7 @@ sp-core = { path = "../../primitives/core" } sp-io = { path = "../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/lottery/src/mock.rs b/substrate/frame/lottery/src/mock.rs index 6e50529619b..e50ec3441b2 100644 --- a/substrate/frame/lottery/src/mock.rs +++ b/substrate/frame/lottery/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_lottery; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64, OnFinalize, OnInitialize}, }; use frame_support_test::TestRandomness; @@ -47,7 +47,6 @@ parameter_types! { pub const AvailableBlockRatio: Perbill = Perbill::one(); } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/membership/Cargo.toml b/substrate/frame/membership/Cargo.toml index c4c94e202a4..18c771bf72c 100644 --- a/substrate/frame/membership/Cargo.toml +++ b/substrate/frame/membership/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME membership management pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,16 +16,16 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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-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-std = { path = "../../primitives/std", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/membership/src/lib.rs b/substrate/frame/membership/src/lib.rs index 2f4bf4bc4ff..6fb61f0e491 100644 --- a/substrate/frame/membership/src/lib.rs +++ b/substrate/frame/membership/src/lib.rs @@ -531,7 +531,7 @@ mod tests { }; use frame_support::{ - assert_noop, assert_ok, derive_impl, ord_parameter_types, parameter_types, + assert_noop, assert_ok, ord_parameter_types, parameter_types, traits::{ConstU32, ConstU64, StorageVersion}, }; use frame_system::EnsureSignedBy; @@ -551,7 +551,6 @@ mod tests { pub static Prime: Option = None; } - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/membership/src/migrations/v4.rs b/substrate/frame/membership/src/migrations/v4.rs index 9b80aca8684..38e97af51a0 100644 --- a/substrate/frame/membership/src/migrations/v4.rs +++ b/substrate/frame/membership/src/migrations/v4.rs @@ -77,7 +77,7 @@ pub fn migrate>(old_pallet_name: N, new_pallet_name: N) { @@ -105,7 +105,7 @@ pub fn pre_migrate>(old_pallet_name: N, new_ } /// Some checks for after migration. This can be linked to -/// `frame_support::traits::OnRuntimeUpgrade::post_upgrade` for further testing. +/// [`frame_support::traits::OnRuntimeUpgrade::post_upgrade`] for further testing. /// /// Panics if anything goes wrong. pub fn post_migrate>(old_pallet_name: N, new_pallet_name: N) { diff --git a/substrate/frame/merkle-mountain-range/Cargo.toml b/substrate/frame/merkle-mountain-range/Cargo.toml index eaa17d88e99..2c30af43b67 100644 --- a/substrate/frame/merkle-mountain-range/Cargo.toml +++ b/substrate/frame/merkle-mountain-range/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME Merkle Mountain Range pallet." -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -18,14 +15,14 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] array-bytes = "6.1" @@ -33,7 +30,7 @@ env_logger = "0.9" itertools = "0.10.3" [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/message-queue/Cargo.toml b/substrate/frame/message-queue/Cargo.toml index b5162d70ccb..48304cd882c 100644 --- a/substrate/frame/message-queue/Cargo.toml +++ b/substrate/frame/message-queue/Cargo.toml @@ -8,26 +8,22 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME pallet to queue and process messages" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", optional = true, features = ["derive"] } +serde = { version = "1.0.188", optional = true, features = ["derive"] } log = { version = "0.4.17", default-features = false } -environmental = { version = "1.1.4", 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-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -sp-weights = { path = "../../primitives/weights", 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-arithmetic = { path = "../../primitives/arithmetic", default-features = false} +sp-weights = { path = "../../primitives/weights", 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 } +frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true} +frame-support = { path = "../support", default-features = false} +frame-system = { path = "../system", default-features = false} [dev-dependencies] sp-tracing = { path = "../../primitives/tracing" } @@ -35,10 +31,9 @@ rand = "0.8.5" rand_distr = "0.4.3" [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", - "environmental/std", "frame-benchmarking?/std", "frame-support/std", "frame-system/std", diff --git a/substrate/frame/message-queue/src/benchmarking.rs b/substrate/frame/message-queue/src/benchmarking.rs index 7e99bc05858..eedaaebeca9 100644 --- a/substrate/frame/message-queue/src/benchmarking.rs +++ b/substrate/frame/message-queue/src/benchmarking.rs @@ -25,7 +25,6 @@ use super::{mock_helpers::*, Pallet as MessageQueue, *}; use frame_benchmarking::v2::*; use frame_support::traits::Get; use frame_system::RawOrigin; -use sp_io::hashing::blake2_256; use sp_std::prelude::*; #[benchmarks( @@ -143,7 +142,7 @@ mod benchmarks { // Check that it was processed. assert_last_event::( Event::Processed { - id: blake2_256(&msg).into(), + id: sp_io::hashing::blake2_256(&msg), origin: 0.into(), weight_used: 1.into_weight(), success: true, @@ -228,7 +227,7 @@ mod benchmarks { assert_last_event::( Event::Processed { - id: blake2_256(&((msgs - 1) as u32).encode()).into(), + id: sp_io::hashing::blake2_256(&((msgs - 1) as u32).encode()), origin: 0.into(), weight_used: Weight::from_parts(1, 1), success: true, @@ -265,7 +264,7 @@ mod benchmarks { assert_last_event::( Event::Processed { - id: blake2_256(&((msgs - 1) as u32).encode()).into(), + id: sp_io::hashing::blake2_256(&((msgs - 1) as u32).encode()), origin: 0.into(), weight_used: Weight::from_parts(1, 1), success: true, diff --git a/substrate/frame/message-queue/src/integration_test.rs b/substrate/frame/message-queue/src/integration_test.rs index fee5d242135..965b96a99ca 100644 --- a/substrate/frame/message-queue/src/integration_test.rs +++ b/substrate/frame/message-queue/src/integration_test.rs @@ -29,8 +29,8 @@ use crate::{ mock::{ - build_and_execute, gen_seed, Callback, CountingMessageProcessor, IntoWeight, - MessagesProcessed, MockedWeightInfo, NumMessagesProcessed, YieldingQueues, + build_and_execute, CountingMessageProcessor, IntoWeight, MockedWeightInfo, + NumMessagesProcessed, YieldingQueues, }, mock_helpers::MessageOrigin, *, @@ -38,7 +38,7 @@ use crate::{ use crate as pallet_message_queue; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64}, }; use rand::{rngs::StdRng, Rng, SeedableRng}; @@ -57,7 +57,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); @@ -120,13 +119,13 @@ impl Config for Test { /// Processing all remaining 28639 messages /// ``` #[test] -#[ignore] // Only run in the CI, otherwise its too slow. +#[ignore] // Only run in the CI. fn stress_test_enqueue_and_service() { let blocks = 20; let max_queues = 10_000; let max_messages_per_queue = 10_000; let max_msg_len = MaxMessageLenOf::::get(); - let mut rng = StdRng::seed_from_u64(gen_seed()); + let mut rng = StdRng::seed_from_u64(43); build_and_execute::(|| { let mut msgs_remaining = 0; @@ -148,74 +147,6 @@ fn stress_test_enqueue_and_service() { }); } -/// Very similar to `stress_test_enqueue_and_service`, but enqueues messages while processing them. -#[test] -#[ignore] // Only run in the CI, otherwise its too slow. -fn stress_test_recursive() { - let blocks = 20; - let mut rng = StdRng::seed_from_u64(gen_seed()); - - // We need to use thread-locals since the callback cannot capture anything. - parameter_types! { - pub static TotalEnqueued: u32 = 0; - pub static Enqueued: u32 = 0; - pub static Called: u32 = 0; - } - - Called::take(); - Enqueued::take(); - TotalEnqueued::take(); - - Callback::set(Box::new(|_, _| { - let mut rng = StdRng::seed_from_u64(Enqueued::get() as u64); - let max_queues = 1_000; - let max_messages_per_queue = 1_000; - let max_msg_len = MaxMessageLenOf::::get(); - - // Instead of directly enqueueing, we enqueue inside a `service` call. - let enqueued = enqueue_messages(max_queues, max_messages_per_queue, max_msg_len, &mut rng); - TotalEnqueued::set(TotalEnqueued::get() + enqueued); - Enqueued::set(Enqueued::get() + enqueued); - Called::set(Called::get() + 1); - })); - - build_and_execute::(|| { - let mut msgs_remaining = 0; - for b in 0..blocks { - log::info!("Block #{}", b); - MessageQueue::enqueue_message( - BoundedSlice::defensive_truncate_from(format!("callback={b}").as_bytes()), - b.into(), - ); - - msgs_remaining += Enqueued::take() + 1; - // Pick a fraction of all messages currently in queue and process them. - let processed = rng.gen_range(1..=msgs_remaining); - log::info!("Processing {} of all messages {}", processed, msgs_remaining); - process_some_messages(processed); // This also advances the block. - msgs_remaining -= processed; - TotalEnqueued::set(TotalEnqueued::get() - processed + 1); - MessageQueue::do_try_state().unwrap(); - } - while Called::get() < blocks { - msgs_remaining += Enqueued::take(); - // Pick a fraction of all messages currently in queue and process them. - let processed = rng.gen_range(1..=msgs_remaining); - log::info!("Processing {} of all messages {}", processed, msgs_remaining); - process_some_messages(processed); // This also advances the block. - msgs_remaining -= processed; - TotalEnqueued::set(TotalEnqueued::get() - processed); - MessageQueue::do_try_state().unwrap(); - } - - let msgs_remaining = TotalEnqueued::take(); - log::info!("Processing all remaining {} messages", msgs_remaining); - process_all_messages(msgs_remaining); - assert_eq!(Called::get(), blocks); - post_conditions(); - }); -} - /// Simulates heavy usage of the suspension logic via `Yield`. /// /// # Example output @@ -232,14 +163,14 @@ fn stress_test_recursive() { /// Processing all remaining 430 messages /// ``` #[test] -#[ignore] // Only run in the CI, otherwise its too slow. +#[ignore] // Only run in the CI. fn stress_test_queue_suspension() { let blocks = 20; let max_queues = 10_000; let max_messages_per_queue = 10_000; let (max_suspend_per_block, max_resume_per_block) = (100, 50); let max_msg_len = MaxMessageLenOf::::get(); - let mut rng = StdRng::seed_from_u64(gen_seed()); + let mut rng = StdRng::seed_from_u64(43); build_and_execute::(|| { let mut suspended = BTreeSet::::new(); @@ -368,7 +299,6 @@ fn process_all_messages(expected: u32) { assert_eq!(consumed, Weight::from_all(expected as u64)); assert_eq!(NumMessagesProcessed::take(), expected as usize); - MessagesProcessed::take(); } /// Returns the weight consumed by `MessageQueue::on_initialize()`. @@ -396,6 +326,5 @@ fn post_conditions() { assert!(ServiceHead::::get().is_none()); // This still works fine. assert_eq!(MessageQueue::service_queues(Weight::MAX), Weight::zero(), "Nothing left"); - MessageQueue::do_try_state().unwrap(); next_block(); } diff --git a/substrate/frame/message-queue/src/lib.rs b/substrate/frame/message-queue/src/lib.rs index 07eb0041985..12d289478b3 100644 --- a/substrate/frame/message-queue/src/lib.rs +++ b/substrate/frame/message-queue/src/lib.rs @@ -49,21 +49,9 @@ //! **Message Execution** //! //! Executing a message is offloaded to the [`Config::MessageProcessor`] which contains the actual -//! logic of how to handle the message since they are blobs. Storage changes are not rolled back on -//! error. -//! -//! A failed message can be temporarily or permanently overweight. The pallet will perpetually try -//! to execute a temporarily overweight message. A permanently overweight message is skipped and -//! must be executed manually. -//! -//! **Reentrancy** -//! -//! This pallet has two entry points for executing (possibly recursive) logic; -//! [`Pallet::service_queues`] and [`Pallet::execute_overweight`]. Both entry points are guarded by -//! the same mutex to error on reentrancy. The only functions that are explicitly **allowed** to be -//! called by a message processor are: [`Pallet::enqueue_message`] and -//! [`Pallet::enqueue_messages`]. All other functions are forbidden and error with -//! [`Error::RecursiveDisallowed`]. +//! logic of how to handle the message since they are blobs. A message can be temporarily or +//! permanently overweight. The pallet will perpetually try to execute a temporarily overweight +//! message. A permanently overweight message is skipped and must be executed manually. //! //! **Pagination** //! @@ -158,7 +146,6 @@ //! which is the default state for a message after being enqueued. //! - `knitting`/`unknitting`: The means of adding or removing a `Queue` from the `ReadyRing`. //! - `MEL`: The Max Encoded Length of a type, see [`codec::MaxEncodedLen`]. -//! - `Reentrance`: To enter an execution context again before it has completed. //! //! # Properties //! @@ -193,7 +180,6 @@ //! expensive. Currently this is archived by having one queue per para-chain/thread, which keeps the //! number of queues within `O(n)` and should be "good enough". -#![deny(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] mod benchmarking; @@ -208,8 +194,8 @@ use frame_support::{ defensive, pallet_prelude::*, traits::{ - Defensive, DefensiveTruncateFrom, EnqueueMessage, ExecuteOverweightError, Footprint, - ProcessMessage, ProcessMessageError, QueueFootprint, QueuePausedQuery, ServiceQueues, + DefensiveTruncateFrom, EnqueueMessage, ExecuteOverweightError, Footprint, ProcessMessage, + ProcessMessageError, QueueFootprint, QueuePausedQuery, ServiceQueues, }, BoundedSlice, CloneNoBound, DefaultNoBound, }; @@ -217,7 +203,6 @@ use frame_system::pallet_prelude::*; pub use pallet::*; use scale_info::TypeInfo; use sp_arithmetic::traits::{BaseArithmetic, Unsigned}; -use sp_core::{defer, H256}; use sp_runtime::{ traits::{One, Zero}, SaturatedConversion, Saturating, @@ -475,10 +460,6 @@ pub mod pallet { /// Processor for a message. /// - /// Storage changes are not rolled back on error. - /// - /// # Benchmarking - /// /// Must be set to [`mock_helpers::NoopMessageProcessor`] for benchmarking. /// Other message processors that consumes exactly (1, 1) weight for any give message will /// work as well. Otherwise the benchmarking will also measure the weight of the message @@ -535,51 +516,18 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { /// Message discarded due to an error in the `MessageProcessor` (usually a format error). - ProcessingFailed { - /// The `blake2_256` hash of the message. - id: H256, - /// The queue of the message. - origin: MessageOriginOf, - /// The error that occurred. - /// - /// This error is pretty opaque. More fine-grained errors need to be emitted as events - /// by the `MessageProcessor`. - error: ProcessMessageError, - }, + ProcessingFailed { id: [u8; 32], origin: MessageOriginOf, error: ProcessMessageError }, /// Message is processed. - Processed { - /// The `blake2_256` hash of the message. - id: H256, - /// The queue of the message. - origin: MessageOriginOf, - /// How much weight was used to process the message. - weight_used: Weight, - /// Whether the message was processed. - /// - /// Note that this does not mean that the underlying `MessageProcessor` was internally - /// successful. It *solely* means that the MQ pallet will treat this as a success - /// condition and discard the message. Any internal error needs to be emitted as events - /// by the `MessageProcessor`. - success: bool, - }, + Processed { id: [u8; 32], origin: MessageOriginOf, weight_used: Weight, success: bool }, /// Message placed in overweight queue. OverweightEnqueued { - /// The `blake2_256` hash of the message. id: [u8; 32], - /// The queue of the message. origin: MessageOriginOf, - /// The page of the message. page_index: PageIndex, - /// The index of the message within the page. message_index: T::Size, }, /// This page was reaped. - PageReaped { - /// The queue of the page. - origin: MessageOriginOf, - /// The index of the page. - index: PageIndex, - }, + PageReaped { origin: MessageOriginOf, index: PageIndex }, } #[pallet::error] @@ -606,8 +554,6 @@ pub mod pallet { /// /// This can change at any time and may resolve in the future by re-trying. QueuePaused, - /// Another call is in progress and needs to finish before this call can happen. - RecursiveDisallowed, } /// The index of the first and last (non-empty) pages. @@ -922,21 +868,6 @@ impl Pallet { page_index: PageIndex, index: T::Size, weight_limit: Weight, - ) -> Result> { - match with_service_mutex(|| { - Self::do_execute_overweight_inner(origin, page_index, index, weight_limit) - }) { - Err(()) => Err(Error::::RecursiveDisallowed), - Ok(x) => x, - } - } - - /// Same as `do_execute_overweight` but must be called while holding the `service_mutex`. - fn do_execute_overweight_inner( - origin: MessageOriginOf, - page_index: PageIndex, - index: T::Size, - weight_limit: Weight, ) -> Result> { let mut book_state = BookStateFor::::get(&origin); ensure!(!T::QueuePausedQuery::is_paused(&origin), Error::::QueuePaused); @@ -993,14 +924,6 @@ impl Pallet { /// Remove a stale page or one which has no more messages remaining to be processed. fn do_reap_page(origin: &MessageOriginOf, page_index: PageIndex) -> DispatchResult { - match with_service_mutex(|| Self::do_reap_page_inner(origin, page_index)) { - Err(()) => Err(Error::::RecursiveDisallowed.into()), - Ok(x) => x, - } - } - - /// Same as `do_reap_page` but must be called while holding the `service_mutex`. - fn do_reap_page_inner(origin: &MessageOriginOf, page_index: PageIndex) -> DispatchResult { let mut book_state = BookStateFor::::get(origin); // definitely not reapable if the page's index is no less than the `begin`ning of ready // pages. @@ -1189,7 +1112,6 @@ impl Pallet { weight: &mut WeightMeter, overweight_limit: Weight, ) -> ItemExecutionStatus { - use MessageExecutionStatus::*; // This ugly pre-checking is needed for the invariant // "we never bail if a page became complete". if page.is_complete() { @@ -1203,31 +1125,16 @@ impl Pallet { Some(m) => m, None => return ItemExecutionStatus::NoItem, }[..]; - let payload_len = payload.len() as u64; - // Store these for the case that `process_message_payload` is recursive. - Pages::::insert(origin, page_index, &*page); - BookStateFor::::insert(origin, &*book_state); - - let res = Self::process_message_payload( + use MessageExecutionStatus::*; + let is_processed = match Self::process_message_payload( origin.clone(), page_index, page.first_index, payload, weight, overweight_limit, - ); - - // And restore them afterwards to see the changes of a recursive call. - *book_state = BookStateFor::::get(origin); - if let Some(new_page) = Pages::::get(origin, page_index) { - *page = new_page; - } else { - defensive!("page must exist since we just inserted it and recursive calls are not allowed to remove anything"); - return ItemExecutionStatus::NoItem - }; - - let is_processed = match res { + ) { InsufficientWeight => return ItemExecutionStatus::Bailed, Unprocessable { permanent: false } => return ItemExecutionStatus::NoProgress, Processed | Unprocessable { permanent: true } => true, @@ -1236,7 +1143,7 @@ impl Pallet { if is_processed { book_state.message_count.saturating_dec(); - book_state.size.saturating_reduce(payload_len as u64); + book_state.size.saturating_reduce(payload.len() as u64); } page.skip_first(is_processed); ItemExecutionStatus::Executed(is_processed) @@ -1261,7 +1168,7 @@ impl Pallet { /// * `remaining_size` > 0 /// * `first` <= `last` /// * Every page can be decoded into peek_* functions - #[cfg(any(test, feature = "try-runtime", feature = "std"))] + #[cfg(any(test, feature = "try-runtime"))] pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> { // Checking memory corruption for BookStateFor ensure!( @@ -1274,17 +1181,13 @@ impl Pallet { "Memory Corruption in Pages" ); - // Basic checks for each book - for book in BookStateFor::::iter_values() { - ensure!(book.end >= book.begin, "Invariant"); - ensure!(book.end < 1 << 30, "Likely overflow or corruption"); - ensure!(book.message_count < 1 << 30, "Likely overflow or corruption"); - ensure!(book.size < 1 << 30, "Likely overflow or corruption"); - ensure!(book.count < 1 << 30, "Likely overflow or corruption"); + // No state to check + if ServiceHead::::get().is_none() { + return Ok(()) } //loop around this origin - let Some(starting_origin) = ServiceHead::::get() else { return Ok(()) }; + let starting_origin = ServiceHead::::get().unwrap(); while let Some(head) = Self::bump_service_head(&mut WeightMeter::new()) { ensure!( @@ -1317,7 +1220,7 @@ impl Pallet { for page_index in head_book_state.begin..head_book_state.end { let page = Pages::::get(&head, page_index).unwrap(); let remaining_messages = page.remaining; - let mut counted_remaining_messages: u32 = 0; + let mut counted_remaining_messages = 0; ensure!( remaining_messages > 0.into(), "These must be some messages that have not been processed yet!" @@ -1334,7 +1237,7 @@ impl Pallet { } ensure!( - remaining_messages.into() == counted_remaining_messages, + remaining_messages == counted_remaining_messages.into(), "Memory Corruption" ); } @@ -1409,9 +1312,10 @@ impl Pallet { meter: &mut WeightMeter, overweight_limit: Weight, ) -> MessageExecutionStatus { - let mut id = sp_io::hashing::blake2_256(message); + let hash = sp_io::hashing::blake2_256(message); use ProcessMessageError::*; let prev_consumed = meter.consumed(); + let mut id = hash; match T::MessageProcessor::process_message(message, origin.clone(), meter, &mut id) { Err(Overweight(w)) if w.any_gt(overweight_limit) => { @@ -1435,44 +1339,19 @@ impl Pallet { }, Err(error @ BadFormat | error @ Corrupt | error @ Unsupported) => { // Permanent error - drop - Self::deposit_event(Event::::ProcessingFailed { id: id.into(), origin, error }); + Self::deposit_event(Event::::ProcessingFailed { id, origin, error }); MessageExecutionStatus::Unprocessable { permanent: true } }, Ok(success) => { // Success let weight_used = meter.consumed().saturating_sub(prev_consumed); - Self::deposit_event(Event::::Processed { - id: id.into(), - origin, - weight_used, - success, - }); + Self::deposit_event(Event::::Processed { id, origin, weight_used, success }); MessageExecutionStatus::Processed }, } } } -/// Run a closure that errors on re-entrance. Meant to be used by anything that services queues. -pub(crate) fn with_service_mutex R, R>(f: F) -> Result { - // Holds the singelton token instance. - environmental::environmental!(token: Option<()>); - - token::using_once(&mut Some(()), || { - // The first `ok_or` should always be `Ok` since we are inside a `using_once`. - let hold = token::with(|t| t.take()).ok_or(()).defensive()?.ok_or(())?; - - // Put the token back when we're done. - defer! { - token::with(|t| { - *t = Some(hold); - }); - } - - Ok(f()) - }) -} - /// Provides a [`sp_core::Get`] to access the `MEL` of a [`codec::MaxEncodedLen`] type. pub struct MaxEncodedLenOf(sp_std::marker::PhantomData); impl Get for MaxEncodedLenOf { @@ -1528,40 +1407,35 @@ impl ServiceQueues for Pallet { Weight::zero() }); - match with_service_mutex(|| { - let mut next = match Self::bump_service_head(&mut weight) { - Some(h) => h, - None => return weight.consumed(), - }; - // The last queue that did not make any progress. - // The loop aborts as soon as it arrives at this queue again without making any progress - // on other queues in between. - let mut last_no_progress = None; - - loop { - let (progressed, n) = Self::service_queue(next.clone(), &mut weight, max_weight); - next = match n { - Some(n) => - if !progressed { - if last_no_progress == Some(n.clone()) { - break - } - if last_no_progress.is_none() { - last_no_progress = Some(next.clone()) - } - n - } else { - last_no_progress = None; - n - }, - None => break, - } + let mut next = match Self::bump_service_head(&mut weight) { + Some(h) => h, + None => return weight.consumed(), + }; + // The last queue that did not make any progress. + // The loop aborts as soon as it arrives at this queue again without making any progress + // on other queues in between. + let mut last_no_progress = None; + + loop { + let (progressed, n) = Self::service_queue(next.clone(), &mut weight, max_weight); + next = match n { + Some(n) => + if !progressed { + if last_no_progress == Some(n.clone()) { + break + } + if last_no_progress.is_none() { + last_no_progress = Some(next.clone()) + } + n + } else { + last_no_progress = None; + n + }, + None => break, } - weight.consumed() - }) { - Err(()) => weight.consumed(), - Ok(w) => w, } + weight.consumed() } /// Execute a single overweight message. @@ -1589,7 +1463,6 @@ impl ServiceQueues for Pallet { Error::::QueuePaused => ExecuteOverweightError::QueuePaused, Error::::NoPage | Error::::NoMessage | Error::::Queued => ExecuteOverweightError::NotFound, - Error::::RecursiveDisallowed => ExecuteOverweightError::RecursiveDisallowed, _ => ExecuteOverweightError::Other, }, ) diff --git a/substrate/frame/message-queue/src/mock.rs b/substrate/frame/message-queue/src/mock.rs index 89c6e862510..55a64574354 100644 --- a/substrate/frame/message-queue/src/mock.rs +++ b/substrate/frame/message-queue/src/mock.rs @@ -24,7 +24,7 @@ use super::*; use crate as pallet_message_queue; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64}, }; use sp_core::H256; @@ -43,8 +43,6 @@ frame_support::construct_runtime!( MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event}, } ); - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); @@ -108,10 +106,7 @@ impl MockedWeightInfo { impl crate::weights::WeightInfo for MockedWeightInfo { fn reap_page() -> Weight { - WeightForCall::get() - .get("reap_page") - .copied() - .unwrap_or(DefaultWeightForCall::get()) + WeightForCall::get().get("reap_page").copied().unwrap_or_default() } fn execute_overweight_page_updated() -> Weight { WeightForCall::get() @@ -210,10 +205,6 @@ impl ProcessMessage for RecordingMessageProcessor { let required = Weight::from_parts(weight, weight); if meter.try_consume(required).is_ok() { - if let Some(p) = message.strip_prefix(&b"callback="[..]) { - let s = String::from_utf8(p.to_vec()).expect("Need valid UTF8"); - Callback::get()(&origin, s.parse().expect("Expected an u32")); - } let mut m = MessagesProcessed::get(); m.push((message.to_vec(), origin)); MessagesProcessed::set(m); @@ -224,10 +215,6 @@ impl ProcessMessage for RecordingMessageProcessor { } } -parameter_types! { - pub static Callback: Box = Box::new(|_, _| {}); -} - /// Processed a mocked message. Messages that end with `badformat`, `corrupt`, `unsupported` or /// `yield` will fail with an error respectively. fn processing_message(msg: &[u8], origin: &MessageOrigin) -> Result<(), ProcessMessageError> { @@ -275,10 +262,6 @@ impl ProcessMessage for CountingMessageProcessor { let required = Weight::from_parts(1, 1); if meter.try_consume(required).is_ok() { - if let Some(p) = message.strip_prefix(&b"callback="[..]) { - let s = String::from_utf8(p.to_vec()).expect("Need valid UTF8"); - Callback::get()(&origin, s.parse().expect("Expected an u32")); - } NumMessagesProcessed::set(NumMessagesProcessed::get() + 1); Ok(true) } else { @@ -387,16 +370,3 @@ pub fn num_overweight_enqueued_events() -> u32 { pub fn fp(pages: u32, count: u64, size: u64) -> QueueFootprint { QueueFootprint { storage: Footprint { count, size }, pages } } - -/// A random seed that can be overwritten with `MQ_SEED`. -pub fn gen_seed() -> u64 { - use rand::Rng; - let seed = if let Ok(seed) = std::env::var("MQ_SEED") { - seed.parse().expect("Need valid u64 as MQ_SEED env variable") - } else { - rand::thread_rng().gen::() - }; - - println!("Using seed: {}", seed); - seed -} diff --git a/substrate/frame/message-queue/src/mock_helpers.rs b/substrate/frame/message-queue/src/mock_helpers.rs index 28395e27cdd..f6109c127be 100644 --- a/substrate/frame/message-queue/src/mock_helpers.rs +++ b/substrate/frame/message-queue/src/mock_helpers.rs @@ -15,8 +15,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#![allow(missing_docs)] - //! Std setup helpers for testing and benchmarking. //! //! Cannot be put into mock.rs since benchmarks require no-std and mock.rs is std. @@ -90,12 +88,10 @@ pub fn page(msg: &[u8]) -> PageOf { PageOf::::from_message::(msg.try_into().unwrap()) } -/// Create a book with a single message of one byte. pub fn single_page_book() -> BookStateOf { BookState { begin: 0, end: 1, count: 1, message_count: 1, size: 1, ..Default::default() } } -/// Create an empty book. pub fn empty_book() -> BookStateOf { BookState { begin: 0, end: 1, count: 1, ..Default::default() } } diff --git a/substrate/frame/message-queue/src/tests.rs b/substrate/frame/message-queue/src/tests.rs index 9198e65e2f9..d94ad581ea0 100644 --- a/substrate/frame/message-queue/src/tests.rs +++ b/substrate/frame/message-queue/src/tests.rs @@ -181,7 +181,7 @@ fn service_queues_failing_messages_works() { assert_eq!(MessageQueue::service_queues(1.into_weight()), 1.into_weight()); assert_last_event::( Event::ProcessingFailed { - id: blake2_256(b"badformat").into(), + id: blake2_256(b"badformat"), origin: MessageOrigin::Here, error: ProcessMessageError::BadFormat, } @@ -190,7 +190,7 @@ fn service_queues_failing_messages_works() { assert_eq!(MessageQueue::service_queues(1.into_weight()), 1.into_weight()); assert_last_event::( Event::ProcessingFailed { - id: blake2_256(b"corrupt").into(), + id: blake2_256(b"corrupt"), origin: MessageOrigin::Here, error: ProcessMessageError::Corrupt, } @@ -199,7 +199,7 @@ fn service_queues_failing_messages_works() { assert_eq!(MessageQueue::service_queues(1.into_weight()), 1.into_weight()); assert_last_event::( Event::ProcessingFailed { - id: blake2_256(b"unsupported").into(), + id: blake2_256(b"unsupported"), origin: MessageOrigin::Here, error: ProcessMessageError::Unsupported, } @@ -1264,7 +1264,7 @@ fn permanently_overweight_limit_is_valid_basic() { RuntimeEvent::MessageQueue(Event::Processed { origin: Here, weight_used: 200.into(), - id: blake2_256(m.as_bytes()).into(), + id: blake2_256(m.as_bytes()), success: true, }) ); @@ -1321,7 +1321,7 @@ fn permanently_overweight_limit_is_valid_fuzzy() { RuntimeEvent::MessageQueue(Event::Processed { origin: Here, weight_used: 200.into(), - id: blake2_256(m.as_bytes()).into(), + id: blake2_256(m.as_bytes()), success: true, }) ); @@ -1592,7 +1592,7 @@ fn execute_overweight_respects_suspension() { assert_last_event::( Event::Processed { - id: blake2_256(b"weight=5").into(), + id: blake2_256(b"weight=5"), origin, weight_used: 5.into_weight(), success: true, @@ -1619,7 +1619,7 @@ fn service_queue_suspension_ready_ring_works() { MessageQueue::service_queues(Weight::MAX); assert_last_event::( Event::Processed { - id: blake2_256(b"weight=5").into(), + id: blake2_256(b"weight=5"), origin, weight_used: 5.into_weight(), success: true, @@ -1662,174 +1662,3 @@ fn integrity_test_checks_service_weight() { } }); } - -/// Test for . -#[test] -fn regression_issue_2319() { - build_and_execute::(|| { - Callback::set(Box::new(|_, _| { - MessageQueue::enqueue_message(mock_helpers::msg("anothermessage"), There); - })); - - use MessageOrigin::*; - MessageQueue::enqueue_message(msg("callback=0"), Here); - - // while servicing queue Here, "anothermessage" of origin There is enqueued in - // "firstmessage"'s process_message - assert_eq!(MessageQueue::service_queues(1.into_weight()), 1.into_weight()); - assert_eq!(MessagesProcessed::take(), vec![(b"callback=0".to_vec(), Here)]); - - assert_eq!(MessageQueue::service_queues(1.into_weight()), 1.into_weight()); - // It used to fail here but got fixed. - assert_eq!(MessagesProcessed::take(), vec![(b"anothermessage".to_vec(), There)]); - }); -} - -/// Enqueueing a message from within `service_queues` works. -#[test] -fn recursive_enqueue_works() { - build_and_execute::(|| { - Callback::set(Box::new(|o, i| match i { - 0 => { - MessageQueue::enqueue_message(msg(&format!("callback={}", 1)), *o); - }, - 1 => { - for _ in 0..100 { - MessageQueue::enqueue_message(msg(&format!("callback={}", 2)), *o); - } - for i in 0..100 { - MessageQueue::enqueue_message(msg(&format!("callback={}", 3)), i.into()); - } - }, - 2 | 3 => { - MessageQueue::enqueue_message(msg(&format!("callback={}", 4)), *o); - }, - 4 => (), - _ => unreachable!(), - })); - - MessageQueue::enqueue_message(msg("callback=0"), MessageOrigin::Here); - - for _ in 0..402 { - assert_eq!(MessageQueue::service_queues(1.into_weight()), 1.into_weight()); - } - assert_eq!(MessageQueue::service_queues(Weight::MAX), Weight::zero()); - - assert_eq!(MessagesProcessed::take().len(), 402); - }); -} - -/// Calling `service_queues` from within `service_queues` is forbidden. -#[test] -fn recursive_service_is_forbidden() { - use MessageOrigin::*; - build_and_execute::(|| { - Callback::set(Box::new(|_, _| { - MessageQueue::enqueue_message(msg("m1"), There); - // This call will fail since it is recursive. But it will not mess up the state. - assert_storage_noop!(MessageQueue::service_queues(10.into_weight())); - MessageQueue::enqueue_message(msg("m2"), There); - })); - - for _ in 0..5 { - MessageQueue::enqueue_message(msg("callback=0"), Here); - MessageQueue::service_queues(3.into_weight()); - - // All three messages are correctly processed. - assert_eq!( - MessagesProcessed::take(), - vec![ - (b"callback=0".to_vec(), Here), - (b"m1".to_vec(), There), - (b"m2".to_vec(), There) - ] - ); - } - }); -} - -/// Calling `service_queues` from within `service_queues` is forbidden. -#[test] -fn recursive_overweight_while_service_is_forbidden() { - use MessageOrigin::*; - build_and_execute::(|| { - Callback::set(Box::new(|_, _| { - // Check that the message was permanently overweight. - assert_last_event::( - Event::OverweightEnqueued { - id: blake2_256(b"weight=10"), - origin: There, - message_index: 0, - page_index: 0, - } - .into(), - ); - // This call will fail since it is recursive. But it will not mess up the state. - assert_noop!( - ::execute_overweight( - 10.into_weight(), - (There, 0, 0) - ), - ExecuteOverweightError::RecursiveDisallowed - ); - })); - - MessageQueue::enqueue_message(msg("weight=10"), There); - MessageQueue::enqueue_message(msg("callback=0"), Here); - - // Mark it as permanently overweight. - MessageQueue::service_queues(5.into_weight()); - assert_ok!(::execute_overweight( - 10.into_weight(), - (There, 0, 0) - )); - }); -} - -/// Calling `reap_page` from within `service_queues` is forbidden. -#[test] -fn recursive_reap_page_is_forbidden() { - use MessageOrigin::*; - build_and_execute::(|| { - Callback::set(Box::new(|_, _| { - // This call will fail since it is recursive. But it will not mess up the state. - assert_noop!(MessageQueue::do_reap_page(&Here, 0), Error::::RecursiveDisallowed); - })); - - // Create 10 pages more than the stale limit. - let n = (MaxStale::get() + 10) as usize; - for _ in 0..n { - MessageQueue::enqueue_message(msg("weight=2"), Here); - } - - // Mark all pages as stale since their message is permanently overweight. - MessageQueue::service_queues(1.into_weight()); - assert_ok!(MessageQueue::do_reap_page(&Here, 0)); - - assert_last_event::(Event::PageReaped { origin: Here, index: 0 }.into()); - }); -} - -#[test] -fn with_service_mutex_works() { - let mut called = 0; - with_service_mutex(|| called = 1).unwrap(); - assert_eq!(called, 1); - - // The outer one is fine but the inner one errors. - with_service_mutex(|| with_service_mutex(|| unreachable!())) - .unwrap() - .unwrap_err(); - with_service_mutex(|| with_service_mutex(|| unreachable!()).unwrap_err()).unwrap(); - with_service_mutex(|| { - with_service_mutex(|| unreachable!()).unwrap_err(); - with_service_mutex(|| unreachable!()).unwrap_err(); - called = 2; - }) - .unwrap(); - assert_eq!(called, 2); - - // Still works. - with_service_mutex(|| called = 3).unwrap(); - assert_eq!(called, 3); -} diff --git a/substrate/frame/mixnet/Cargo.toml b/substrate/frame/mixnet/Cargo.toml index 949003864a2..665c606fc37 100644 --- a/substrate/frame/mixnet/Cargo.toml +++ b/substrate/frame/mixnet/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository = "https://github.com/paritytech/substrate/" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -22,7 +19,7 @@ frame-support = { default-features = false, path = "../support" } frame-system = { default-features = false, path = "../system" } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, features = ["derive"] } +serde = { version = "1.0.188", default-features = false, features = ["derive"] } 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" } @@ -31,7 +28,7 @@ sp-runtime = { default-features = false, path = "../../primitives/runtime" } sp-std = { default-features = false, path = "../../primitives/std" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/multisig/Cargo.toml b/substrate/frame/multisig/Cargo.toml index 40b0f4973a8..a2ee608c33c 100644 --- a/substrate/frame/multisig/Cargo.toml +++ b/substrate/frame/multisig/Cargo.toml @@ -9,21 +9,18 @@ repository.workspace = true description = "FRAME multi-signature dispatch pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.10.0", 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 } +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} # third party log = { version = "0.4.17", default-features = false } @@ -32,7 +29,7 @@ log = { version = "0.4.17", default-features = false } pallet-balances = { path = "../balances" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/nft-fractionalization/Cargo.toml b/substrate/frame/nft-fractionalization/Cargo.toml index 355bb2a5d3e..a2cb9a4aec9 100644 --- a/substrate/frame/nft-fractionalization/Cargo.toml +++ b/substrate/frame/nft-fractionalization/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet to convert non-fungible to fungible tokens." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,13 +16,13 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } @@ -34,7 +31,7 @@ sp-io = { path = "../../primitives/io" } sp-std = { path = "../../primitives/std" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking/std", diff --git a/substrate/frame/nft-fractionalization/src/mock.rs b/substrate/frame/nft-fractionalization/src/mock.rs index 855109adcbe..987c65a8954 100644 --- a/substrate/frame/nft-fractionalization/src/mock.rs +++ b/substrate/frame/nft-fractionalization/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_nft_fractionalization; use frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, parameter_types, traits::{AsEnsureOriginWithArg, ConstU32, ConstU64}, BoundedVec, PalletId, }; @@ -49,8 +49,6 @@ construct_runtime!( Nfts: pallet_nfts, } ); - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/nfts/Cargo.toml b/substrate/frame/nfts/Cargo.toml index 0d3f542c552..2a3b2921c75 100644 --- a/substrate/frame/nfts/Cargo.toml +++ b/substrate/frame/nfts/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME NFTs pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,20 +17,20 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = enumflags2 = { version = "0.7.7" } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } sp-keystore = { path = "../../primitives/keystore" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "enumflags2/std", diff --git a/substrate/frame/nfts/runtime-api/Cargo.toml b/substrate/frame/nfts/runtime-api/Cargo.toml index 8eb6726552b..092edaaaa89 100644 --- a/substrate/frame/nfts/runtime-api/Cargo.toml +++ b/substrate/frame/nfts/runtime-api/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Runtime API for the FRAME NFTs pallet." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -22,5 +19,5 @@ sp-api = { path = "../../../primitives/api", default-features = false } sp-std = { path = "../../../primitives/std", default-features = false } [features] -default = ["std"] -std = ["codec/std", "pallet-nfts/std", "sp-api/std", "sp-std/std"] +default = [ "std" ] +std = [ "codec/std", "pallet-nfts/std", "sp-api/std", "sp-std/std" ] diff --git a/substrate/frame/nfts/src/features/create_delete_collection.rs b/substrate/frame/nfts/src/features/create_delete_collection.rs index f03df7fdd4f..e343ad18e50 100644 --- a/substrate/frame/nfts/src/features/create_delete_collection.rs +++ b/substrate/frame/nfts/src/features/create_delete_collection.rs @@ -66,13 +66,7 @@ impl, I: 'static> Pallet { CollectionConfigOf::::insert(&collection, config); CollectionAccount::::insert(&owner, &collection, ()); - Self::deposit_event(event); - - if let Some(max_supply) = config.max_supply { - Self::deposit_event(Event::CollectionMaxSupplySet { collection, max_supply }); - } - Ok(()) } diff --git a/substrate/frame/nfts/src/mock.rs b/substrate/frame/nfts/src/mock.rs index 4363eccc7ff..248522aafff 100644 --- a/substrate/frame/nfts/src/mock.rs +++ b/substrate/frame/nfts/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_nfts; use frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, parameter_types, traits::{AsEnsureOriginWithArg, ConstU32, ConstU64}, }; use sp_core::H256; @@ -46,7 +46,6 @@ pub type Signature = MultiSignature; pub type AccountPublic = ::Signer; pub type AccountId = ::AccountId; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/nfts/src/tests.rs b/substrate/frame/nfts/src/tests.rs index 0c32aea2be0..aeebf51b7c7 100644 --- a/substrate/frame/nfts/src/tests.rs +++ b/substrate/frame/nfts/src/tests.rs @@ -2191,10 +2191,6 @@ fn max_supply_should_work() { default_collection_config() )); assert_eq!(CollectionConfigOf::::get(collection_id).unwrap().max_supply, None); - assert!(!events().contains(&Event::::CollectionMaxSupplySet { - collection: collection_id, - max_supply, - })); assert_ok!(Nfts::set_collection_max_supply( RuntimeOrigin::signed(user_id.clone()), @@ -2246,31 +2242,9 @@ fn max_supply_should_work() { None )); assert_noop!( - Nfts::mint( - RuntimeOrigin::signed(user_id.clone()), - collection_id, - 2, - user_id.clone(), - None - ), + Nfts::mint(RuntimeOrigin::signed(user_id.clone()), collection_id, 2, user_id, None), Error::::MaxSupplyReached ); - - // validate the event gets emitted when we set the max supply on collection create - let collection_id = 1; - assert_ok!(Nfts::force_create( - RuntimeOrigin::root(), - user_id.clone(), - CollectionConfig { max_supply: Some(max_supply), ..default_collection_config() } - )); - assert_eq!( - CollectionConfigOf::::get(collection_id).unwrap().max_supply, - Some(max_supply) - ); - assert!(events().contains(&Event::::CollectionMaxSupplySet { - collection: collection_id, - max_supply, - })); }); } diff --git a/substrate/frame/nicks/Cargo.toml b/substrate/frame/nicks/Cargo.toml index 7d43f64cfe2..b8100d07435 100644 --- a/substrate/frame/nicks/Cargo.toml +++ b/substrate/frame/nicks/Cargo.toml @@ -9,27 +9,24 @@ repository.workspace = true description = "FRAME pallet for nick management" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } sp-core = { path = "../../primitives/core" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/nicks/src/lib.rs b/substrate/frame/nicks/src/lib.rs index 540777f87ca..ad30c628adf 100644 --- a/substrate/frame/nicks/src/lib.rs +++ b/substrate/frame/nicks/src/lib.rs @@ -253,7 +253,7 @@ mod tests { use crate as pallet_nicks; use frame_support::{ - assert_noop, assert_ok, derive_impl, ord_parameter_types, + assert_noop, assert_ok, ord_parameter_types, traits::{ConstU32, ConstU64}, }; use frame_system::EnsureSignedBy; @@ -274,7 +274,6 @@ mod tests { } ); - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/nis/Cargo.toml b/substrate/frame/nis/Cargo.toml index f95ebc5864c..986568ea722 100644 --- a/substrate/frame/nis/Cargo.toml +++ b/substrate/frame/nis/Cargo.toml @@ -9,29 +9,26 @@ repository.workspace = true description = "FRAME pallet for rewarding account freezing." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } sp-io = { path = "../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/nis/src/mock.rs b/substrate/frame/nis/src/mock.rs index be6e79ac6f6..30f7ef95f33 100644 --- a/substrate/frame/nis/src/mock.rs +++ b/substrate/frame/nis/src/mock.rs @@ -20,7 +20,7 @@ use crate::{self as pallet_nis, Perquintill, WithMaximumOf}; use frame_support::{ - derive_impl, ord_parameter_types, parameter_types, + ord_parameter_types, parameter_types, traits::{ fungible::Inspect, ConstU16, ConstU32, ConstU64, Everything, OnFinalize, OnInitialize, StorageMapShim, @@ -50,7 +50,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = Everything; type BlockWeights = (); diff --git a/substrate/frame/node-authorization/Cargo.toml b/substrate/frame/node-authorization/Cargo.toml index 46fc0b34514..e5a504e2a0f 100644 --- a/substrate/frame/node-authorization/Cargo.toml +++ b/substrate/frame/node-authorization/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME pallet for node authorization" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -18,15 +15,15 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/node-authorization/src/mock.rs b/substrate/frame/node-authorization/src/mock.rs index 3c99d41b89e..84e3336b3bd 100644 --- a/substrate/frame/node-authorization/src/mock.rs +++ b/substrate/frame/node-authorization/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_node_authorization; use frame_support::{ - derive_impl, ord_parameter_types, + ord_parameter_types, traits::{ConstU32, ConstU64}, }; use frame_system::EnsureSignedBy; @@ -43,7 +43,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type DbWeight = (); diff --git a/substrate/frame/nomination-pools/Cargo.toml b/substrate/frame/nomination-pools/Cargo.toml index 00c90b414de..3c55822b9a5 100644 --- a/substrate/frame/nomination-pools/Cargo.toml +++ b/substrate/frame/nomination-pools/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME nomination pools pallet" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,13 +17,13 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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 = { 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} log = { version = "0.4.0", default-features = false } # Optional: use for testing and/or fuzzing @@ -38,8 +35,8 @@ pallet-balances = { path = "../balances" } sp-tracing = { path = "../../primitives/tracing" } [features] -default = ["std"] -fuzzing = ["pallet-balances", "sp-tracing"] +default = [ "std" ] +fuzzing = [ "pallet-balances", "sp-tracing" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/nomination-pools/benchmarking/Cargo.toml b/substrate/frame/nomination-pools/benchmarking/Cargo.toml index 8a4ee07dd74..e8b18666815 100644 --- a/substrate/frame/nomination-pools/benchmarking/Cargo.toml +++ b/substrate/frame/nomination-pools/benchmarking/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME nomination pools pallet benchmarking" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,29 +18,29 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } # 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-nomination-pools = { path = "..", default-features = false } +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-nomination-pools = { path = "..", default-features = false} # 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 = { 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} [dev-dependencies] -pallet-balances = { path = "../../balances", default-features = false } +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" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", diff --git a/substrate/frame/nomination-pools/benchmarking/src/lib.rs b/substrate/frame/nomination-pools/benchmarking/src/lib.rs index 48d7dae29ef..fc86a6f56c0 100644 --- a/substrate/frame/nomination-pools/benchmarking/src/lib.rs +++ b/substrate/frame/nomination-pools/benchmarking/src/lib.rs @@ -35,9 +35,9 @@ use frame_support::{ use frame_system::RawOrigin as RuntimeOrigin; use pallet_nomination_pools::{ BalanceOf, BondExtra, BondedPoolInner, BondedPools, ClaimPermission, ClaimPermissions, - Commission, CommissionChangeRate, CommissionClaimPermission, ConfigOp, GlobalMaxCommission, - MaxPoolMembers, MaxPoolMembersPerPool, MaxPools, Metadata, MinCreateBond, MinJoinBond, - Pallet as Pools, PoolMembers, PoolRoles, PoolState, RewardPools, SubPoolsStorage, + Commission, CommissionChangeRate, ConfigOp, GlobalMaxCommission, MaxPoolMembers, + MaxPoolMembersPerPool, MaxPools, Metadata, MinCreateBond, MinJoinBond, Pallet as Pools, + PoolMembers, PoolRoles, PoolState, RewardPools, SubPoolsStorage, }; use pallet_staking::MaxNominationsOf; use sp_runtime::{ @@ -706,24 +706,17 @@ frame_benchmarking::benchmarks! { max_increase: Perbill::from_percent(20), min_delay: 0u32.into(), }).unwrap(); - // set a claim permission to an account. - Pools::::set_commission_claim_permission( - RuntimeOrigin::Signed(depositor.clone()).into(), - 1u32.into(), - Some(CommissionClaimPermission::Account(depositor.clone())) - ).unwrap(); }:_(RuntimeOrigin::Signed(depositor.clone()), 1u32.into(), Some((Perbill::from_percent(20), depositor.clone()))) verify { assert_eq!(BondedPools::::get(1).unwrap().commission, Commission { - current: Some((Perbill::from_percent(20), depositor.clone())), + current: Some((Perbill::from_percent(20), depositor)), max: Some(Perbill::from_percent(50)), change_rate: Some(CommissionChangeRate { max_increase: Perbill::from_percent(20), min_delay: 0u32.into() }), throttle_from: Some(1u32.into()), - claim_permission: Some(CommissionClaimPermission::Account(depositor)), }); } @@ -738,7 +731,6 @@ frame_benchmarking::benchmarks! { max: Some(Perbill::from_percent(50)), change_rate: None, throttle_from: Some(0u32.into()), - claim_permission: None, }); } @@ -759,25 +751,9 @@ frame_benchmarking::benchmarks! { min_delay: 1000u32.into(), }), throttle_from: Some(1_u32.into()), - claim_permission: None, }); } - set_commission_claim_permission { - // Create a pool. - let (depositor, pool_account) = create_pool_account::(0, Pools::::depositor_min_bond() * 2u32.into(), None); - }:_(RuntimeOrigin::Signed(depositor.clone()), 1u32.into(), Some(CommissionClaimPermission::Account(depositor.clone()))) - verify { - assert_eq!( - BondedPools::::get(1).unwrap().commission, Commission { - current: None, - max: None, - change_rate: None, - throttle_from: None, - claim_permission: Some(CommissionClaimPermission::Account(depositor)), - }); - } - set_claim_permission { // Create a pool let min_create_bond = Pools::::depositor_min_bond(); @@ -810,13 +786,8 @@ frame_benchmarking::benchmarks! { CurrencyOf::::set_balance(&reward_account, ed + origin_weight); // member claims a payout to make some commission available. - let _ = Pools::::claim_payout(RuntimeOrigin::Signed(claimer.clone()).into()); - // set a claim permission to an account. - let _ = Pools::::set_commission_claim_permission( - RuntimeOrigin::Signed(depositor.clone()).into(), - 1u32.into(), - Some(CommissionClaimPermission::Account(claimer)) - ); + let _ = Pools::::claim_payout(RuntimeOrigin::Signed(claimer).into()); + whitelist_account!(depositor); }:_(RuntimeOrigin::Signed(depositor.clone()), 1u32.into()) verify { diff --git a/substrate/frame/nomination-pools/benchmarking/src/mock.rs b/substrate/frame/nomination-pools/benchmarking/src/mock.rs index c58a66f6163..9a7f2197a7b 100644 --- a/substrate/frame/nomination-pools/benchmarking/src/mock.rs +++ b/substrate/frame/nomination-pools/benchmarking/src/mock.rs @@ -17,7 +17,7 @@ use crate::VoterBagsListInstance; use frame_election_provider_support::VoteWeight; -use frame_support::{derive_impl, pallet_prelude::*, parameter_types, traits::ConstU64, PalletId}; +use frame_support::{pallet_prelude::*, parameter_types, traits::ConstU64, PalletId}; use sp_runtime::{ traits::{Convert, IdentityLookup}, BuildStorage, FixedU128, Perbill, @@ -28,7 +28,6 @@ type Nonce = u32; type BlockNumber = u64; type Balance = u128; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); @@ -119,7 +118,6 @@ impl pallet_staking::Config for Runtime { 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; diff --git a/substrate/frame/nomination-pools/fuzzer/Cargo.toml b/substrate/frame/nomination-pools/fuzzer/Cargo.toml index 52f49b28457..b9d0a6197f8 100644 --- a/substrate/frame/nomination-pools/fuzzer/Cargo.toml +++ b/substrate/frame/nomination-pools/fuzzer/Cargo.toml @@ -10,9 +10,6 @@ description = "Fuzzer for fixed point arithmetic primitives." documentation = "https://docs.rs/sp-arithmetic-fuzzer" publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/frame/nomination-pools/runtime-api/Cargo.toml b/substrate/frame/nomination-pools/runtime-api/Cargo.toml index 12a897cc6b6..c3aa8035c95 100644 --- a/substrate/frame/nomination-pools/runtime-api/Cargo.toml +++ b/substrate/frame/nomination-pools/runtime-api/Cargo.toml @@ -9,18 +9,15 @@ repository.workspace = true description = "Runtime API for nomination-pools FRAME pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", 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 } +sp-api = { path = "../../../primitives/api", default-features = false} +sp-std = { path = "../../../primitives/std", default-features = false} +pallet-nomination-pools = { path = "..", default-features = false} [features] -default = ["std"] -std = ["codec/std", "pallet-nomination-pools/std", "sp-api/std", "sp-std/std"] +default = [ "std" ] +std = [ "codec/std", "pallet-nomination-pools/std", "sp-api/std", "sp-std/std" ] diff --git a/substrate/frame/nomination-pools/src/lib.rs b/substrate/frame/nomination-pools/src/lib.rs index c3fd6a98e88..ab4bd51ffc0 100644 --- a/substrate/frame/nomination-pools/src/lib.rs +++ b/substrate/frame/nomination-pools/src/lib.rs @@ -460,7 +460,7 @@ pub enum ClaimPermission { PermissionlessCompound, /// Anyone can withdraw rewards on a pool member's behalf. PermissionlessWithdraw, - /// Anyone can withdraw and compound rewards on a pool member's behalf. + /// Anyone can withdraw and compound rewards on a member's behalf. PermissionlessAll, } @@ -676,13 +676,6 @@ pub struct PoolRoles { pub bouncer: Option, } -// A pool's possible commission claiming permissions. -#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)] -pub enum CommissionClaimPermission { - Permissionless, - Account(AccountId), -} - /// Pool commission. /// /// The pool `root` can set commission configuration after pool creation. By default, all commission @@ -712,9 +705,6 @@ pub struct Commission { /// The block from where throttling should be checked from. This value will be updated on all /// commission updates and when setting an initial `change_rate`. pub throttle_from: Option>, - // Whether commission can be claimed permissionlessly, or whether an account can claim - // commission. `Root` role can always claim. - pub claim_permission: Option>, } impl Commission { @@ -1088,17 +1078,6 @@ impl BondedPool { self.is_root(who) } - fn can_claim_commission(&self, who: &T::AccountId) -> bool { - if let Some(permission) = self.commission.claim_permission.as_ref() { - match permission { - CommissionClaimPermission::Permissionless => true, - CommissionClaimPermission::Account(account) => account == who || self.is_root(who), - } - } else { - self.is_root(who) - } - } - fn is_destroying(&self) -> bool { matches!(self.state, PoolState::Destroying) } @@ -1593,7 +1572,7 @@ pub mod pallet { use sp_runtime::Perbill; /// The current storage version. - const STORAGE_VERSION: StorageVersion = StorageVersion::new(8); + const STORAGE_VERSION: StorageVersion = StorageVersion::new(7); #[pallet::pallet] #[pallet::storage_version(STORAGE_VERSION)] @@ -1871,11 +1850,6 @@ pub mod pallet { pool_id: PoolId, change_rate: CommissionChangeRate>, }, - /// Pool commission claim permission has been updated. - PoolCommissionClaimPermissionUpdated { - pool_id: PoolId, - permission: Option>, - }, /// Pool commission has been claimed. PoolCommissionClaimed { pool_id: PoolId, commission: BalanceOf }, /// Topped up deficit in frozen ED of the reward pool. @@ -2768,32 +2742,6 @@ pub mod pallet { let who = ensure_signed(origin)?; Self::do_adjust_pool_deposit(who, pool_id) } - - /// Set or remove a pool's commission claim permission. - /// - /// Determines who can claim the pool's pending commission. Only the `Root` role of the pool - /// is able to conifigure commission claim permissions. - #[pallet::call_index(22)] - #[pallet::weight(T::WeightInfo::set_commission_claim_permission())] - pub fn set_commission_claim_permission( - origin: OriginFor, - pool_id: PoolId, - permission: Option>, - ) -> DispatchResult { - let who = ensure_signed(origin)?; - let mut bonded_pool = BondedPool::::get(pool_id).ok_or(Error::::PoolNotFound)?; - ensure!(bonded_pool.can_manage_commission(&who), Error::::DoesNotHavePermission); - - bonded_pool.commission.claim_permission = permission.clone(); - bonded_pool.put(); - - Self::deposit_event(Event::::PoolCommissionClaimPermissionUpdated { - pool_id, - permission, - }); - - Ok(()) - } } #[pallet::hooks] @@ -3158,12 +3106,12 @@ impl Pallet { fn do_claim_commission(who: T::AccountId, pool_id: PoolId) -> DispatchResult { let bonded_pool = BondedPool::::get(pool_id).ok_or(Error::::PoolNotFound)?; - ensure!(bonded_pool.can_claim_commission(&who), Error::::DoesNotHavePermission); + ensure!(bonded_pool.can_manage_commission(&who), Error::::DoesNotHavePermission); let mut reward_pool = RewardPools::::get(pool_id) .defensive_ok_or::>(DefensiveError::RewardPoolNotFound.into())?; - // IMPORTANT: ensure newly pending commission not yet processed is added to + // IMPORTANT: make sure that any newly pending commission not yet processed is added to // `total_commission_pending`. reward_pool.update_records( pool_id, diff --git a/substrate/frame/nomination-pools/src/migration.rs b/substrate/frame/nomination-pools/src/migration.rs index 3adfd926d95..3d68fee1dca 100644 --- a/substrate/frame/nomination-pools/src/migration.rs +++ b/substrate/frame/nomination-pools/src/migration.rs @@ -27,15 +27,6 @@ use sp_runtime::TryRuntimeError; pub mod versioned { use super::*; - /// v8: Adds commission claim permissions to `BondedPools`. - pub type V7ToV8 = frame_support::migrations::VersionedMigration< - 7, - 8, - v8::VersionUncheckedMigrateV7ToV8, - crate::pallet::Pallet, - ::DbWeight, - >; - /// Migration V6 to V7 wrapped in a [`frame_support::migrations::VersionedMigration`], ensuring /// the migration is only performed when on-chain version is 6. pub type V6ToV7 = frame_support::migrations::VersionedMigration< @@ -56,74 +47,6 @@ pub mod versioned { >; } -pub mod v8 { - use super::*; - - #[derive(Decode)] - pub struct OldCommission { - pub current: Option<(Perbill, T::AccountId)>, - pub max: Option, - pub change_rate: Option>>, - pub throttle_from: Option>, - } - - #[derive(Decode)] - pub struct OldBondedPoolInner { - pub commission: OldCommission, - pub member_counter: u32, - pub points: BalanceOf, - pub roles: PoolRoles, - pub state: PoolState, - } - - impl OldBondedPoolInner { - fn migrate_to_v8(self) -> BondedPoolInner { - BondedPoolInner { - commission: Commission { - current: self.commission.current, - max: self.commission.max, - change_rate: self.commission.change_rate, - throttle_from: self.commission.throttle_from, - // `claim_permission` is a new field. - claim_permission: None, - }, - member_counter: self.member_counter, - points: self.points, - roles: self.roles, - state: self.state, - } - } - } - - pub struct VersionUncheckedMigrateV7ToV8(sp_std::marker::PhantomData); - impl OnRuntimeUpgrade for VersionUncheckedMigrateV7ToV8 { - #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, TryRuntimeError> { - Ok(Vec::new()) - } - - fn on_runtime_upgrade() -> Weight { - let mut translated = 0u64; - BondedPools::::translate::, _>(|_key, old_value| { - translated.saturating_inc(); - Some(old_value.migrate_to_v8()) - }); - T::DbWeight::get().reads_writes(translated, translated + 1) - } - - #[cfg(feature = "try-runtime")] - fn post_upgrade(_: Vec) -> Result<(), TryRuntimeError> { - // Check new `claim_permission` field is present. - ensure!( - BondedPools::::iter() - .all(|(_, inner)| inner.commission.claim_permission.is_none()), - "`claim_permission` value has not been set correctly." - ); - Ok(()) - } - } -} - /// This migration accumulates and initializes the [`TotalValueLocked`] for all pools. /// /// WARNING: This migration works under the assumption that the [`BondedPools`] cannot be inflated diff --git a/substrate/frame/nomination-pools/src/mock.rs b/substrate/frame/nomination-pools/src/mock.rs index 1bd969230da..24bea0b87f2 100644 --- a/substrate/frame/nomination-pools/src/mock.rs +++ b/substrate/frame/nomination-pools/src/mock.rs @@ -17,7 +17,7 @@ use super::*; use crate::{self as pools}; -use frame_support::{assert_ok, derive_impl, parameter_types, traits::fungible::Mutate, PalletId}; +use frame_support::{assert_ok, parameter_types, traits::fungible::Mutate, PalletId}; use frame_system::RawOrigin; use sp_runtime::{BuildStorage, FixedU128}; use sp_staking::{OnStakingUpdate, Stake}; @@ -209,7 +209,6 @@ impl sp_staking::StakingInterface for StakingMock { } } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type SS58Prefix = (); type BaseCallFilter = frame_support::traits::Everything; diff --git a/substrate/frame/nomination-pools/src/tests.rs b/substrate/frame/nomination-pools/src/tests.rs index 7fe1e704bb1..2749e89ecff 100644 --- a/substrate/frame/nomination-pools/src/tests.rs +++ b/substrate/frame/nomination-pools/src/tests.rs @@ -5761,13 +5761,7 @@ mod commission { // Then: assert_eq!( BondedPool::::get(1).unwrap().commission, - Commission { - current: None, - max: None, - change_rate: None, - throttle_from: Some(1), - claim_permission: None, - } + Commission { current: None, max: None, change_rate: None, throttle_from: Some(1) } ); assert_eq!( pool_events_since_last_call(), @@ -5962,7 +5956,6 @@ mod commission { min_delay: 2_u64 }), throttle_from: Some(1_u64), - claim_permission: None, } ); assert_eq!( @@ -6014,7 +6007,6 @@ mod commission { min_delay: 2_u64 }), throttle_from: Some(3_u64), - claim_permission: None, } ); assert_eq!( @@ -6090,8 +6082,7 @@ mod commission { max_increase: Perbill::from_percent(1), min_delay: 2 }), - throttle_from: Some(7), - claim_permission: None, + throttle_from: Some(7) } ); assert_eq!( @@ -6192,7 +6183,6 @@ mod commission { max: Some(Perbill::from_percent(50)), change_rate: None, throttle_from: Some(1), - claim_permission: None, } ); @@ -6419,7 +6409,6 @@ mod commission { min_delay: 10_u64 }), throttle_from: Some(11), - claim_permission: None, } ); @@ -6513,8 +6502,7 @@ mod commission { max_increase: Perbill::from_percent(1), min_delay: 0 }), - throttle_from: Some(1), - claim_permission: None, + throttle_from: Some(1) } ); @@ -6897,13 +6885,6 @@ mod commission { #[test] fn claim_commission_works() { ExtBuilder::default().build_and_execute(|| { - /// Deposit rewards into the pool and claim payout. This will set up pending commission - /// to be tested in various scenarios. - fn deposit_rewards_and_claim_payout(caller: AccountId, points: u128) { - deposit_rewards(points); - assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(caller))); - } - let pool_id = 1; let _ = Currency::set_balance(&900, 5); @@ -6924,9 +6905,21 @@ mod commission { ] ); + // Pool earns 80 points, payout is triggered. + deposit_rewards(80); + assert_eq!( + PoolMembers::::get(10).unwrap(), + PoolMember:: { pool_id, points: 10, ..Default::default() } + ); + + assert_ok!(Pools::claim_payout(RuntimeOrigin::signed(10))); + assert_eq!( + pool_events_since_last_call(), + vec![Event::PaidOut { member: 10, pool_id, payout: 40 }] + ); + // Given: - deposit_rewards_and_claim_payout(10, 100); - assert_eq!(RewardPool::::current_balance(pool_id), 50); + assert_eq!(RewardPool::::current_balance(pool_id), 40); // Pool does not exist assert_noop!( @@ -6951,176 +6944,6 @@ mod commission { Pools::claim_commission(RuntimeOrigin::signed(900), pool_id,), Error::::NoPendingCommission ); - - assert_eq!( - pool_events_since_last_call(), - vec![ - Event::PaidOut { member: 10, pool_id, payout: 50 }, - Event::PoolCommissionClaimed { pool_id: 1, commission: 50 } - ] - ); - - // The pool commission's claim_permission field is updated to `Permissionless` by the - // root member, which means anyone can now claim commission for the pool. - - // Given: - // Some random non-pool member to claim commission. - let non_pool_member = 1001; - let _ = Currency::set_balance(&non_pool_member, 5); - - // Set up pending commission. - deposit_rewards_and_claim_payout(10, 100); - assert_ok!(Pools::set_commission_claim_permission( - RuntimeOrigin::signed(900), - pool_id, - Some(CommissionClaimPermission::Permissionless) - )); - - // When: - assert_ok!(Pools::claim_commission(RuntimeOrigin::signed(non_pool_member), pool_id)); - - // Then: - assert_eq!(RewardPool::::current_balance(pool_id), 0); - assert_eq!( - pool_events_since_last_call(), - vec![ - Event::PaidOut { member: 10, pool_id, payout: 50 }, - Event::PoolCommissionClaimPermissionUpdated { - pool_id: 1, - permission: Some(CommissionClaimPermission::Permissionless) - }, - Event::PoolCommissionClaimed { pool_id: 1, commission: 50 }, - ] - ); - - // The pool commission's claim_permission is updated to an adhoc account by the root - // member, which means now only that account (in addition to the root role) can claim - // commission for the pool. - - // Given: - // The account designated to claim commission. - let designated_commission_claimer = 2001; - let _ = Currency::set_balance(&designated_commission_claimer, 5); - - // Set up pending commission. - deposit_rewards_and_claim_payout(10, 100); - assert_ok!(Pools::set_commission_claim_permission( - RuntimeOrigin::signed(900), - pool_id, - Some(CommissionClaimPermission::Account(designated_commission_claimer)) - )); - - // When: - // Previous claimer can no longer claim commission. - assert_noop!( - Pools::claim_commission(RuntimeOrigin::signed(1001), pool_id,), - Error::::DoesNotHavePermission - ); - // Designated claimer can claim commission. - assert_ok!(Pools::claim_commission( - RuntimeOrigin::signed(designated_commission_claimer), - pool_id - )); - - // Then: - assert_eq!( - pool_events_since_last_call(), - vec![ - Event::PaidOut { member: 10, pool_id, payout: 50 }, - Event::PoolCommissionClaimPermissionUpdated { - pool_id: 1, - permission: Some(CommissionClaimPermission::Account(2001)) - }, - Event::PoolCommissionClaimed { pool_id: 1, commission: 50 }, - ] - ); - - // Even with an Account claim permission set, the `root` role of the pool can still - // claim commission. - - // Given: - deposit_rewards_and_claim_payout(10, 100); - - // When: - assert_ok!(Pools::claim_commission(RuntimeOrigin::signed(900), pool_id)); - - // Then: - assert_eq!( - pool_events_since_last_call(), - vec![ - Event::PaidOut { member: 10, pool_id, payout: 50 }, - Event::PoolCommissionClaimed { pool_id: 1, commission: 50 }, - ] - ); - - // The root role updates commission's claim_permission back to `None`, which results in - // only the root member being able to claim commission for the pool. - - // Given: - deposit_rewards_and_claim_payout(10, 100); - - // When: - assert_ok!(Pools::set_commission_claim_permission( - RuntimeOrigin::signed(900), - pool_id, - None - )); - // Previous claimer can no longer claim commission. - assert_noop!( - Pools::claim_commission( - RuntimeOrigin::signed(designated_commission_claimer), - pool_id, - ), - Error::::DoesNotHavePermission - ); - // Root can claim commission. - assert_ok!(Pools::claim_commission(RuntimeOrigin::signed(900), pool_id)); - - // Then: - assert_eq!( - pool_events_since_last_call(), - vec![ - Event::PaidOut { member: 10, pool_id, payout: 50 }, - Event::PoolCommissionClaimPermissionUpdated { pool_id: 1, permission: None }, - Event::PoolCommissionClaimed { pool_id: 1, commission: 50 }, - ] - ); - }) - } - - #[test] - fn set_commission_claim_permission_handles_errors() { - ExtBuilder::default().build_and_execute(|| { - let pool_id = 1; - - let _ = Currency::set_balance(&900, 5); - assert_eq!( - pool_events_since_last_call(), - vec![ - Event::Created { depositor: 10, pool_id }, - Event::Bonded { member: 10, pool_id, bonded: 10, joined: true }, - ] - ); - - // Cannot operate on a non-existing pool. - assert_noop!( - Pools::set_commission_claim_permission( - RuntimeOrigin::signed(10), - 90, - Some(CommissionClaimPermission::Permissionless) - ), - Error::::PoolNotFound - ); - - // Only the root role can change the commission claim permission. - assert_noop!( - Pools::set_commission_claim_permission( - RuntimeOrigin::signed(10), - pool_id, - Some(CommissionClaimPermission::Permissionless) - ), - Error::::DoesNotHavePermission - ); }) } } diff --git a/substrate/frame/nomination-pools/src/weights.rs b/substrate/frame/nomination-pools/src/weights.rs index 047a17c3f9a..2cb414fc2a0 100644 --- a/substrate/frame/nomination-pools/src/weights.rs +++ b/substrate/frame/nomination-pools/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_nomination_pools` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-11-23, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-09-19, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-guclnr1q-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -67,7 +67,6 @@ pub trait WeightInfo { fn set_commission() -> Weight; fn set_commission_max() -> Weight; fn set_commission_change_rate() -> Weight; - fn set_commission_claim_permission() -> Weight; fn set_claim_permission() -> Weight; fn claim_commission() -> Weight; fn adjust_pool_deposit() -> Weight; @@ -81,7 +80,7 @@ impl WeightInfo for SubstrateWeight { /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:1) @@ -106,21 +105,19 @@ impl WeightInfo for SubstrateWeight { /// Proof: `VoterList::ListNodes` (`max_values`: None, `max_size`: Some(154), added: 2629, mode: `MaxEncodedLen`) /// Storage: `VoterList::ListBags` (r:2 w:2) /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn join() -> Weight { // Proof Size summary in bytes: - // Measured: `3425` + // Measured: `3388` // Estimated: `8877` - // Minimum execution time: 184_295_000 picoseconds. - Weight::from_parts(188_860_000, 8877) - .saturating_add(T::DbWeight::get().reads(20_u64)) - .saturating_add(T::DbWeight::get().writes(13_u64)) + // Minimum execution time: 203_377_000 picoseconds. + Weight::from_parts(206_359_000, 8877) + .saturating_add(T::DbWeight::get().reads(19_u64)) + .saturating_add(T::DbWeight::get().writes(12_u64)) } /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -139,23 +136,21 @@ impl WeightInfo for SubstrateWeight { /// Proof: `VoterList::ListNodes` (`max_values`: None, `max_size`: Some(154), added: 2629, mode: `MaxEncodedLen`) /// Storage: `VoterList::ListBags` (r:2 w:2) /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn bond_extra_transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `3435` + // Measured: `3398` // Estimated: `8877` - // Minimum execution time: 188_777_000 picoseconds. - Weight::from_parts(192_646_000, 8877) - .saturating_add(T::DbWeight::get().reads(17_u64)) - .saturating_add(T::DbWeight::get().writes(13_u64)) + // Minimum execution time: 199_792_000 picoseconds. + Weight::from_parts(206_871_000, 8877) + .saturating_add(T::DbWeight::get().reads(16_u64)) + .saturating_add(T::DbWeight::get().writes(12_u64)) } /// Storage: `NominationPools::ClaimPermissions` (r:1 w:0) /// Proof: `NominationPools::ClaimPermissions` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -174,23 +169,21 @@ impl WeightInfo for SubstrateWeight { /// Proof: `VoterList::ListNodes` (`max_values`: None, `max_size`: Some(154), added: 2629, mode: `MaxEncodedLen`) /// Storage: `VoterList::ListBags` (r:2 w:2) /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn bond_extra_other() -> Weight { // Proof Size summary in bytes: - // Measured: `3500` + // Measured: `3463` // Estimated: `8877` - // Minimum execution time: 221_728_000 picoseconds. - Weight::from_parts(227_569_000, 8877) - .saturating_add(T::DbWeight::get().reads(18_u64)) - .saturating_add(T::DbWeight::get().writes(14_u64)) + // Minimum execution time: 246_362_000 picoseconds. + Weight::from_parts(253_587_000, 8877) + .saturating_add(T::DbWeight::get().reads(17_u64)) + .saturating_add(T::DbWeight::get().writes(13_u64)) } /// Storage: `NominationPools::ClaimPermissions` (r:1 w:0) /// Proof: `NominationPools::ClaimPermissions` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -199,17 +192,17 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn claim_payout() -> Weight { // Proof Size summary in bytes: - // Measured: `1172` - // Estimated: `3719` - // Minimum execution time: 75_310_000 picoseconds. - Weight::from_parts(77_709_000, 3719) + // Measured: `1171` + // Estimated: `3702` + // Minimum execution time: 81_115_000 picoseconds. + Weight::from_parts(83_604_000, 3702) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) @@ -240,15 +233,15 @@ impl WeightInfo for SubstrateWeight { /// Proof: `NominationPools::CounterForSubPoolsStorage` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn unbond() -> Weight { // Proof Size summary in bytes: - // Measured: `3622` + // Measured: `3674` // Estimated: `27847` - // Minimum execution time: 170_656_000 picoseconds. - Weight::from_parts(174_950_000, 27847) + // Minimum execution time: 187_210_000 picoseconds. + Weight::from_parts(189_477_000, 27847) .saturating_add(T::DbWeight::get().reads(20_u64)) .saturating_add(T::DbWeight::get().writes(13_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:1) @@ -259,26 +252,24 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:1 w:0) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 100]`. fn pool_withdraw_unbonded(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1817` + // Measured: `1743` // Estimated: `4764` - // Minimum execution time: 68_866_000 picoseconds. - Weight::from_parts(72_312_887, 4764) - // Standard Error: 1_635 - .saturating_add(Weight::from_parts(41_679, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(7_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + // Minimum execution time: 66_384_000 picoseconds. + Weight::from_parts(69_498_267, 4764) + // Standard Error: 2_566 + .saturating_add(Weight::from_parts(34_528, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(6_u64)) + .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `Staking::CurrentEra` (r:1 w:0) /// Proof: `Staking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::SubPoolsStorage` (r:1 w:1) /// Proof: `NominationPools::SubPoolsStorage` (`max_values`: None, `max_size`: Some(24382), added: 26857, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) @@ -291,8 +282,6 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `NominationPools::CounterForPoolMembers` (r:1 w:1) /// Proof: `NominationPools::CounterForPoolMembers` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::ClaimPermissions` (r:0 w:1) @@ -300,21 +289,21 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[0, 100]`. fn withdraw_unbonded_update(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `2207` + // Measured: `2171` // Estimated: `27847` - // Minimum execution time: 131_383_000 picoseconds. - Weight::from_parts(136_595_971, 27847) - // Standard Error: 2_715 - .saturating_add(Weight::from_parts(52_351, 0).saturating_mul(s.into())) - .saturating_add(T::DbWeight::get().reads(11_u64)) - .saturating_add(T::DbWeight::get().writes(9_u64)) + // Minimum execution time: 137_474_000 picoseconds. + Weight::from_parts(142_341_215, 27847) + // Standard Error: 3_468 + .saturating_add(Weight::from_parts(66_597, 0).saturating_mul(s.into())) + .saturating_add(T::DbWeight::get().reads(10_u64)) + .saturating_add(T::DbWeight::get().writes(8_u64)) } /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `Staking::CurrentEra` (r:1 w:0) /// Proof: `Staking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::SubPoolsStorage` (r:1 w:1) /// Proof: `NominationPools::SubPoolsStorage` (`max_values`: None, `max_size`: Some(24382), added: 26857, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:1) @@ -323,18 +312,16 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) /// Storage: `Staking::SlashingSpans` (r:1 w:0) /// Proof: `Staking::SlashingSpans` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `Balances::Locks` (r:2 w:1) - /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) - /// Storage: `Balances::Freezes` (r:2 w:1) - /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Staking::Validators` (r:1 w:0) /// Proof: `Staking::Validators` (`max_values`: None, `max_size`: Some(45), added: 2520, mode: `MaxEncodedLen`) /// Storage: `Staking::Nominators` (r:1 w:0) /// Proof: `Staking::Nominators` (`max_values`: None, `max_size`: Some(558), added: 3033, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:2 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:2 w:1) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) /// Storage: `NominationPools::CounterForPoolMembers` (r:1 w:1) /// Proof: `NominationPools::CounterForPoolMembers` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::ReversePoolIdLookup` (r:1 w:1) @@ -358,12 +345,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `s` is `[0, 100]`. fn withdraw_unbonded_kill(_s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `2525` + // Measured: `2526` // Estimated: `27847` - // Minimum execution time: 233_314_000 picoseconds. - Weight::from_parts(241_694_316, 27847) - .saturating_add(T::DbWeight::get().reads(24_u64)) - .saturating_add(T::DbWeight::get().writes(20_u64)) + // Minimum execution time: 249_135_000 picoseconds. + Weight::from_parts(263_632_571, 27847) + .saturating_add(T::DbWeight::get().reads(23_u64)) + .saturating_add(T::DbWeight::get().writes(19_u64)) } /// Storage: `NominationPools::LastPoolId` (r:1 w:1) /// Proof: `NominationPools::LastPoolId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -389,12 +376,14 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:1) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) + /// Storage: `Staking::Ledger` (r:1 w:1) + /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) + /// Storage: `Staking::CurrentEra` (r:1 w:0) + /// Proof: `Staking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Balances::Locks` (r:2 w:1) /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:2 w:1) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::CounterForRewardPools` (r:1 w:1) @@ -404,22 +393,20 @@ impl WeightInfo for SubstrateWeight { /// Storage: `NominationPools::CounterForReversePoolIdLookup` (r:1 w:1) /// Proof: `NominationPools::CounterForReversePoolIdLookup` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) - /// Storage: `Staking::Ledger` (r:0 w:1) - /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Payee` (r:0 w:1) /// Proof: `Staking::Payee` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn create() -> Weight { // Proof Size summary in bytes: - // Measured: `1169` + // Measured: `1289` // Estimated: `8538` - // Minimum execution time: 171_465_000 picoseconds. - Weight::from_parts(176_478_000, 8538) - .saturating_add(T::DbWeight::get().reads(23_u64)) - .saturating_add(T::DbWeight::get().writes(17_u64)) + // Minimum execution time: 214_207_000 picoseconds. + Weight::from_parts(221_588_000, 8538) + .saturating_add(T::DbWeight::get().reads(24_u64)) + .saturating_add(T::DbWeight::get().writes(16_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:0) @@ -445,34 +432,34 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[1, 16]`. fn nominate(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1808` + // Measured: `1849` // Estimated: `4556 + n * (2520 ±0)` - // Minimum execution time: 63_588_000 picoseconds. - Weight::from_parts(64_930_584, 4556) - // Standard Error: 9_167 - .saturating_add(Weight::from_parts(1_595_779, 0).saturating_mul(n.into())) + // Minimum execution time: 70_626_000 picoseconds. + Weight::from_parts(73_830_182, 4556) + // Standard Error: 24_496 + .saturating_add(Weight::from_parts(1_561_416, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(12_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(5_u64)) .saturating_add(Weight::from_parts(0, 2520).saturating_mul(n.into())) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:0) /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) fn set_state() -> Weight { // Proof Size summary in bytes: - // Measured: `1434` + // Measured: `1438` // Estimated: `4556` - // Minimum execution time: 32_899_000 picoseconds. - Weight::from_parts(33_955_000, 4556) + // Minimum execution time: 36_542_000 picoseconds. + Weight::from_parts(37_644_000, 4556) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::Metadata` (r:1 w:1) /// Proof: `NominationPools::Metadata` (`max_values`: None, `max_size`: Some(270), added: 2745, mode: `MaxEncodedLen`) /// Storage: `NominationPools::CounterForMetadata` (r:1 w:1) @@ -480,12 +467,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `n` is `[1, 256]`. fn set_metadata(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `532` + // Measured: `531` // Estimated: `3735` - // Minimum execution time: 13_778_000 picoseconds. - Weight::from_parts(14_770_006, 3735) - // Standard Error: 151 - .saturating_add(Weight::from_parts(1_900, 0).saturating_mul(n.into())) + // Minimum execution time: 15_130_000 picoseconds. + Weight::from_parts(16_319_671, 3735) + // Standard Error: 351 + .saturating_add(Weight::from_parts(2_024, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -505,23 +492,23 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_550_000 picoseconds. - Weight::from_parts(4_935_000, 0) + // Minimum execution time: 6_819_000 picoseconds. + Weight::from_parts(7_253_000, 0) .saturating_add(T::DbWeight::get().writes(6_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) fn update_roles() -> Weight { // Proof Size summary in bytes: - // Measured: `532` - // Estimated: `3719` - // Minimum execution time: 16_759_000 picoseconds. - Weight::from_parts(17_346_000, 3719) + // Measured: `531` + // Estimated: `3685` + // Minimum execution time: 19_596_000 picoseconds. + Weight::from_parts(20_828_000, 3685) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:0) @@ -540,15 +527,15 @@ impl WeightInfo for SubstrateWeight { /// Proof: `VoterList::CounterForListNodes` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn chill() -> Weight { // Proof Size summary in bytes: - // Measured: `1971` + // Measured: `2012` // Estimated: `4556` - // Minimum execution time: 61_970_000 picoseconds. - Weight::from_parts(63_738_000, 4556) + // Minimum execution time: 68_551_000 picoseconds. + Weight::from_parts(71_768_000, 4556) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -557,45 +544,34 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn set_commission() -> Weight { // Proof Size summary in bytes: - // Measured: `804` - // Estimated: `3719` - // Minimum execution time: 31_950_000 picoseconds. - Weight::from_parts(33_190_000, 3719) + // Measured: `770` + // Estimated: `3685` + // Minimum execution time: 36_128_000 picoseconds. + Weight::from_parts(38_547_000, 3685) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) /// Proof: `NominationPools::GlobalMaxCommission` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn set_commission_max() -> Weight { // Proof Size summary in bytes: - // Measured: `572` - // Estimated: `3719` - // Minimum execution time: 16_807_000 picoseconds. - Weight::from_parts(17_733_000, 3719) + // Measured: `571` + // Estimated: `3685` + // Minimum execution time: 20_067_000 picoseconds. + Weight::from_parts(21_044_000, 3685) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) fn set_commission_change_rate() -> Weight { // Proof Size summary in bytes: - // Measured: `532` - // Estimated: `3719` - // Minimum execution time: 16_710_000 picoseconds. - Weight::from_parts(17_563_000, 3719) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } - /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) - fn set_commission_claim_permission() -> Weight { - // Proof Size summary in bytes: - // Measured: `532` - // Estimated: `3719` - // Minimum execution time: 16_493_000 picoseconds. - Weight::from_parts(17_022_000, 3719) + // Measured: `531` + // Estimated: `3685` + // Minimum execution time: 19_186_000 picoseconds. + Weight::from_parts(20_189_000, 3685) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -607,13 +583,13 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `542` // Estimated: `3702` - // Minimum execution time: 14_248_000 picoseconds. - Weight::from_parts(15_095_000, 3702) + // Minimum execution time: 15_275_000 picoseconds. + Weight::from_parts(15_932_000, 3702) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -622,15 +598,15 @@ impl WeightInfo for SubstrateWeight { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn claim_commission() -> Weight { // Proof Size summary in bytes: - // Measured: `1002` - // Estimated: `3719` - // Minimum execution time: 61_969_000 picoseconds. - Weight::from_parts(63_965_000, 3719) + // Measured: `968` + // Estimated: `3685` + // Minimum execution time: 67_931_000 picoseconds. + Weight::from_parts(72_202_000, 3685) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:1 w:1) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) @@ -639,10 +615,10 @@ impl WeightInfo for SubstrateWeight { /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) fn adjust_pool_deposit() -> Weight { // Proof Size summary in bytes: - // Measured: `901` + // Measured: `900` // Estimated: `4764` - // Minimum execution time: 65_462_000 picoseconds. - Weight::from_parts(67_250_000, 4764) + // Minimum execution time: 72_783_000 picoseconds. + Weight::from_parts(75_841_000, 4764) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -655,7 +631,7 @@ impl WeightInfo for () { /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:1) @@ -680,21 +656,19 @@ impl WeightInfo for () { /// Proof: `VoterList::ListNodes` (`max_values`: None, `max_size`: Some(154), added: 2629, mode: `MaxEncodedLen`) /// Storage: `VoterList::ListBags` (r:2 w:2) /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn join() -> Weight { // Proof Size summary in bytes: - // Measured: `3425` + // Measured: `3388` // Estimated: `8877` - // Minimum execution time: 184_295_000 picoseconds. - Weight::from_parts(188_860_000, 8877) - .saturating_add(RocksDbWeight::get().reads(20_u64)) - .saturating_add(RocksDbWeight::get().writes(13_u64)) + // Minimum execution time: 203_377_000 picoseconds. + Weight::from_parts(206_359_000, 8877) + .saturating_add(RocksDbWeight::get().reads(19_u64)) + .saturating_add(RocksDbWeight::get().writes(12_u64)) } /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -713,23 +687,21 @@ impl WeightInfo for () { /// Proof: `VoterList::ListNodes` (`max_values`: None, `max_size`: Some(154), added: 2629, mode: `MaxEncodedLen`) /// Storage: `VoterList::ListBags` (r:2 w:2) /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn bond_extra_transfer() -> Weight { // Proof Size summary in bytes: - // Measured: `3435` + // Measured: `3398` // Estimated: `8877` - // Minimum execution time: 188_777_000 picoseconds. - Weight::from_parts(192_646_000, 8877) - .saturating_add(RocksDbWeight::get().reads(17_u64)) - .saturating_add(RocksDbWeight::get().writes(13_u64)) + // Minimum execution time: 199_792_000 picoseconds. + Weight::from_parts(206_871_000, 8877) + .saturating_add(RocksDbWeight::get().reads(16_u64)) + .saturating_add(RocksDbWeight::get().writes(12_u64)) } /// Storage: `NominationPools::ClaimPermissions` (r:1 w:0) /// Proof: `NominationPools::ClaimPermissions` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -748,23 +720,21 @@ impl WeightInfo for () { /// Proof: `VoterList::ListNodes` (`max_values`: None, `max_size`: Some(154), added: 2629, mode: `MaxEncodedLen`) /// Storage: `VoterList::ListBags` (r:2 w:2) /// Proof: `VoterList::ListBags` (`max_values`: None, `max_size`: Some(82), added: 2557, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) fn bond_extra_other() -> Weight { // Proof Size summary in bytes: - // Measured: `3500` + // Measured: `3463` // Estimated: `8877` - // Minimum execution time: 221_728_000 picoseconds. - Weight::from_parts(227_569_000, 8877) - .saturating_add(RocksDbWeight::get().reads(18_u64)) - .saturating_add(RocksDbWeight::get().writes(14_u64)) + // Minimum execution time: 246_362_000 picoseconds. + Weight::from_parts(253_587_000, 8877) + .saturating_add(RocksDbWeight::get().reads(17_u64)) + .saturating_add(RocksDbWeight::get().writes(13_u64)) } /// Storage: `NominationPools::ClaimPermissions` (r:1 w:0) /// Proof: `NominationPools::ClaimPermissions` (`max_values`: None, `max_size`: Some(41), added: 2516, mode: `MaxEncodedLen`) /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -773,17 +743,17 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn claim_payout() -> Weight { // Proof Size summary in bytes: - // Measured: `1172` - // Estimated: `3719` - // Minimum execution time: 75_310_000 picoseconds. - Weight::from_parts(77_709_000, 3719) + // Measured: `1171` + // Estimated: `3702` + // Minimum execution time: 81_115_000 picoseconds. + Weight::from_parts(83_604_000, 3702) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) @@ -814,15 +784,15 @@ impl WeightInfo for () { /// Proof: `NominationPools::CounterForSubPoolsStorage` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn unbond() -> Weight { // Proof Size summary in bytes: - // Measured: `3622` + // Measured: `3674` // Estimated: `27847` - // Minimum execution time: 170_656_000 picoseconds. - Weight::from_parts(174_950_000, 27847) + // Minimum execution time: 187_210_000 picoseconds. + Weight::from_parts(189_477_000, 27847) .saturating_add(RocksDbWeight::get().reads(20_u64)) .saturating_add(RocksDbWeight::get().writes(13_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:1) @@ -833,26 +803,24 @@ impl WeightInfo for () { /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:1 w:0) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// The range of component `s` is `[0, 100]`. fn pool_withdraw_unbonded(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1817` + // Measured: `1743` // Estimated: `4764` - // Minimum execution time: 68_866_000 picoseconds. - Weight::from_parts(72_312_887, 4764) - // Standard Error: 1_635 - .saturating_add(Weight::from_parts(41_679, 0).saturating_mul(s.into())) - .saturating_add(RocksDbWeight::get().reads(7_u64)) - .saturating_add(RocksDbWeight::get().writes(3_u64)) + // Minimum execution time: 66_384_000 picoseconds. + Weight::from_parts(69_498_267, 4764) + // Standard Error: 2_566 + .saturating_add(Weight::from_parts(34_528, 0).saturating_mul(s.into())) + .saturating_add(RocksDbWeight::get().reads(6_u64)) + .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `Staking::CurrentEra` (r:1 w:0) /// Proof: `Staking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::SubPoolsStorage` (r:1 w:1) /// Proof: `NominationPools::SubPoolsStorage` (`max_values`: None, `max_size`: Some(24382), added: 26857, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) @@ -865,8 +833,6 @@ impl WeightInfo for () { /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `NominationPools::CounterForPoolMembers` (r:1 w:1) /// Proof: `NominationPools::CounterForPoolMembers` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::ClaimPermissions` (r:0 w:1) @@ -874,21 +840,21 @@ impl WeightInfo for () { /// The range of component `s` is `[0, 100]`. fn withdraw_unbonded_update(s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `2207` + // Measured: `2171` // Estimated: `27847` - // Minimum execution time: 131_383_000 picoseconds. - Weight::from_parts(136_595_971, 27847) - // Standard Error: 2_715 - .saturating_add(Weight::from_parts(52_351, 0).saturating_mul(s.into())) - .saturating_add(RocksDbWeight::get().reads(11_u64)) - .saturating_add(RocksDbWeight::get().writes(9_u64)) + // Minimum execution time: 137_474_000 picoseconds. + Weight::from_parts(142_341_215, 27847) + // Standard Error: 3_468 + .saturating_add(Weight::from_parts(66_597, 0).saturating_mul(s.into())) + .saturating_add(RocksDbWeight::get().reads(10_u64)) + .saturating_add(RocksDbWeight::get().writes(8_u64)) } /// Storage: `NominationPools::PoolMembers` (r:1 w:1) /// Proof: `NominationPools::PoolMembers` (`max_values`: None, `max_size`: Some(237), added: 2712, mode: `MaxEncodedLen`) /// Storage: `Staking::CurrentEra` (r:1 w:0) /// Proof: `Staking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::SubPoolsStorage` (r:1 w:1) /// Proof: `NominationPools::SubPoolsStorage` (`max_values`: None, `max_size`: Some(24382), added: 26857, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:1) @@ -897,18 +863,16 @@ impl WeightInfo for () { /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) /// Storage: `Staking::SlashingSpans` (r:1 w:0) /// Proof: `Staking::SlashingSpans` (`max_values`: None, `max_size`: None, mode: `Measured`) - /// Storage: `Balances::Locks` (r:2 w:1) - /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) - /// Storage: `Balances::Freezes` (r:2 w:1) - /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:2 w:2) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Staking::Validators` (r:1 w:0) /// Proof: `Staking::Validators` (`max_values`: None, `max_size`: Some(45), added: 2520, mode: `MaxEncodedLen`) /// Storage: `Staking::Nominators` (r:1 w:0) /// Proof: `Staking::Nominators` (`max_values`: None, `max_size`: Some(558), added: 3033, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) + /// Storage: `System::Account` (r:2 w:2) + /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) + /// Storage: `Balances::Locks` (r:2 w:1) + /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) + /// Storage: `Balances::Freezes` (r:2 w:1) + /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) /// Storage: `NominationPools::CounterForPoolMembers` (r:1 w:1) /// Proof: `NominationPools::CounterForPoolMembers` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::ReversePoolIdLookup` (r:1 w:1) @@ -932,12 +896,12 @@ impl WeightInfo for () { /// The range of component `s` is `[0, 100]`. fn withdraw_unbonded_kill(_s: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `2525` + // Measured: `2526` // Estimated: `27847` - // Minimum execution time: 233_314_000 picoseconds. - Weight::from_parts(241_694_316, 27847) - .saturating_add(RocksDbWeight::get().reads(24_u64)) - .saturating_add(RocksDbWeight::get().writes(20_u64)) + // Minimum execution time: 249_135_000 picoseconds. + Weight::from_parts(263_632_571, 27847) + .saturating_add(RocksDbWeight::get().reads(23_u64)) + .saturating_add(RocksDbWeight::get().writes(19_u64)) } /// Storage: `NominationPools::LastPoolId` (r:1 w:1) /// Proof: `NominationPools::LastPoolId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -963,12 +927,14 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:1) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) + /// Storage: `Staking::Ledger` (r:1 w:1) + /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) + /// Storage: `Staking::CurrentEra` (r:1 w:0) + /// Proof: `Staking::CurrentEra` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `Balances::Locks` (r:2 w:1) /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:2 w:1) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) - /// Storage: `NominationPools::TotalValueLocked` (r:1 w:1) - /// Proof: `NominationPools::TotalValueLocked` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::CounterForRewardPools` (r:1 w:1) @@ -978,22 +944,20 @@ impl WeightInfo for () { /// Storage: `NominationPools::CounterForReversePoolIdLookup` (r:1 w:1) /// Proof: `NominationPools::CounterForReversePoolIdLookup` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) - /// Storage: `Staking::Ledger` (r:0 w:1) - /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Payee` (r:0 w:1) /// Proof: `Staking::Payee` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) fn create() -> Weight { // Proof Size summary in bytes: - // Measured: `1169` + // Measured: `1289` // Estimated: `8538` - // Minimum execution time: 171_465_000 picoseconds. - Weight::from_parts(176_478_000, 8538) - .saturating_add(RocksDbWeight::get().reads(23_u64)) - .saturating_add(RocksDbWeight::get().writes(17_u64)) + // Minimum execution time: 214_207_000 picoseconds. + Weight::from_parts(221_588_000, 8538) + .saturating_add(RocksDbWeight::get().reads(24_u64)) + .saturating_add(RocksDbWeight::get().writes(16_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:0) @@ -1019,34 +983,34 @@ impl WeightInfo for () { /// The range of component `n` is `[1, 16]`. fn nominate(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `1808` + // Measured: `1849` // Estimated: `4556 + n * (2520 ±0)` - // Minimum execution time: 63_588_000 picoseconds. - Weight::from_parts(64_930_584, 4556) - // Standard Error: 9_167 - .saturating_add(Weight::from_parts(1_595_779, 0).saturating_mul(n.into())) + // Minimum execution time: 70_626_000 picoseconds. + Weight::from_parts(73_830_182, 4556) + // Standard Error: 24_496 + .saturating_add(Weight::from_parts(1_561_416, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(12_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes(5_u64)) .saturating_add(Weight::from_parts(0, 2520).saturating_mul(n.into())) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:0) /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) fn set_state() -> Weight { // Proof Size summary in bytes: - // Measured: `1434` + // Measured: `1438` // Estimated: `4556` - // Minimum execution time: 32_899_000 picoseconds. - Weight::from_parts(33_955_000, 4556) + // Minimum execution time: 36_542_000 picoseconds. + Weight::from_parts(37_644_000, 4556) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::Metadata` (r:1 w:1) /// Proof: `NominationPools::Metadata` (`max_values`: None, `max_size`: Some(270), added: 2745, mode: `MaxEncodedLen`) /// Storage: `NominationPools::CounterForMetadata` (r:1 w:1) @@ -1054,12 +1018,12 @@ impl WeightInfo for () { /// The range of component `n` is `[1, 256]`. fn set_metadata(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `532` + // Measured: `531` // Estimated: `3735` - // Minimum execution time: 13_778_000 picoseconds. - Weight::from_parts(14_770_006, 3735) - // Standard Error: 151 - .saturating_add(Weight::from_parts(1_900, 0).saturating_mul(n.into())) + // Minimum execution time: 15_130_000 picoseconds. + Weight::from_parts(16_319_671, 3735) + // Standard Error: 351 + .saturating_add(Weight::from_parts(2_024, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1079,23 +1043,23 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_550_000 picoseconds. - Weight::from_parts(4_935_000, 0) + // Minimum execution time: 6_819_000 picoseconds. + Weight::from_parts(7_253_000, 0) .saturating_add(RocksDbWeight::get().writes(6_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) fn update_roles() -> Weight { // Proof Size summary in bytes: - // Measured: `532` - // Estimated: `3719` - // Minimum execution time: 16_759_000 picoseconds. - Weight::from_parts(17_346_000, 3719) + // Measured: `531` + // Estimated: `3685` + // Minimum execution time: 19_596_000 picoseconds. + Weight::from_parts(20_828_000, 3685) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Staking::Bonded` (r:1 w:0) /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:0) @@ -1114,15 +1078,15 @@ impl WeightInfo for () { /// Proof: `VoterList::CounterForListNodes` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn chill() -> Weight { // Proof Size summary in bytes: - // Measured: `1971` + // Measured: `2012` // Estimated: `4556` - // Minimum execution time: 61_970_000 picoseconds. - Weight::from_parts(63_738_000, 4556) + // Minimum execution time: 68_551_000 picoseconds. + Weight::from_parts(71_768_000, 4556) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -1131,45 +1095,34 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn set_commission() -> Weight { // Proof Size summary in bytes: - // Measured: `804` - // Estimated: `3719` - // Minimum execution time: 31_950_000 picoseconds. - Weight::from_parts(33_190_000, 3719) + // Measured: `770` + // Estimated: `3685` + // Minimum execution time: 36_128_000 picoseconds. + Weight::from_parts(38_547_000, 3685) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) /// Proof: `NominationPools::GlobalMaxCommission` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn set_commission_max() -> Weight { // Proof Size summary in bytes: - // Measured: `572` - // Estimated: `3719` - // Minimum execution time: 16_807_000 picoseconds. - Weight::from_parts(17_733_000, 3719) + // Measured: `571` + // Estimated: `3685` + // Minimum execution time: 20_067_000 picoseconds. + Weight::from_parts(21_044_000, 3685) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) fn set_commission_change_rate() -> Weight { // Proof Size summary in bytes: - // Measured: `532` - // Estimated: `3719` - // Minimum execution time: 16_710_000 picoseconds. - Weight::from_parts(17_563_000, 3719) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - /// Storage: `NominationPools::BondedPools` (r:1 w:1) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) - fn set_commission_claim_permission() -> Weight { - // Proof Size summary in bytes: - // Measured: `532` - // Estimated: `3719` - // Minimum execution time: 16_493_000 picoseconds. - Weight::from_parts(17_022_000, 3719) + // Measured: `531` + // Estimated: `3685` + // Minimum execution time: 19_186_000 picoseconds. + Weight::from_parts(20_189_000, 3685) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1181,13 +1134,13 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `542` // Estimated: `3702` - // Minimum execution time: 14_248_000 picoseconds. - Weight::from_parts(15_095_000, 3702) + // Minimum execution time: 15_275_000 picoseconds. + Weight::from_parts(15_932_000, 3702) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `NominationPools::RewardPools` (r:1 w:1) /// Proof: `NominationPools::RewardPools` (`max_values`: None, `max_size`: Some(92), added: 2567, mode: `MaxEncodedLen`) /// Storage: `NominationPools::GlobalMaxCommission` (r:1 w:0) @@ -1196,15 +1149,15 @@ impl WeightInfo for () { /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) fn claim_commission() -> Weight { // Proof Size summary in bytes: - // Measured: `1002` - // Estimated: `3719` - // Minimum execution time: 61_969_000 picoseconds. - Weight::from_parts(63_965_000, 3719) + // Measured: `968` + // Estimated: `3685` + // Minimum execution time: 67_931_000 picoseconds. + Weight::from_parts(72_202_000, 3685) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } /// Storage: `NominationPools::BondedPools` (r:1 w:0) - /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(254), added: 2729, mode: `MaxEncodedLen`) + /// Proof: `NominationPools::BondedPools` (`max_values`: None, `max_size`: Some(220), added: 2695, mode: `MaxEncodedLen`) /// Storage: `Balances::Freezes` (r:1 w:1) /// Proof: `Balances::Freezes` (`max_values`: None, `max_size`: Some(67), added: 2542, mode: `MaxEncodedLen`) /// Storage: `System::Account` (r:1 w:1) @@ -1213,10 +1166,10 @@ impl WeightInfo for () { /// Proof: `Balances::Locks` (`max_values`: None, `max_size`: Some(1299), added: 3774, mode: `MaxEncodedLen`) fn adjust_pool_deposit() -> Weight { // Proof Size summary in bytes: - // Measured: `901` + // Measured: `900` // Estimated: `4764` - // Minimum execution time: 65_462_000 picoseconds. - Weight::from_parts(67_250_000, 4764) + // Minimum execution time: 72_783_000 picoseconds. + Weight::from_parts(75_841_000, 4764) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } diff --git a/substrate/frame/nomination-pools/test-staking/Cargo.toml b/substrate/frame/nomination-pools/test-staking/Cargo.toml index 845535ae04f..f0558f83142 100644 --- a/substrate/frame/nomination-pools/test-staking/Cargo.toml +++ b/substrate/frame/nomination-pools/test-staking/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME nomination pools pallet tests with the staking pallet" publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/frame/nomination-pools/test-staking/src/mock.rs b/substrate/frame/nomination-pools/test-staking/src/mock.rs index 491cd619161..0db24e9c244 100644 --- a/substrate/frame/nomination-pools/test-staking/src/mock.rs +++ b/substrate/frame/nomination-pools/test-staking/src/mock.rs @@ -17,7 +17,7 @@ use frame_election_provider_support::VoteWeight; use frame_support::{ - assert_ok, derive_impl, + assert_ok, pallet_prelude::*, parameter_types, traits::{ConstU64, ConstU8}, @@ -38,7 +38,6 @@ pub(crate) type T = Runtime; pub(crate) const POOL1_BONDED: AccountId = 20318131474730217858575332831085u128; pub(crate) const POOL1_REWARD: AccountId = 20397359637244482196168876781421u128; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); @@ -134,7 +133,6 @@ impl pallet_staking::Config for Runtime { 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; diff --git a/substrate/frame/offences/Cargo.toml b/substrate/frame/offences/Cargo.toml index df0fb015e95..ac204a7813a 100644 --- a/substrate/frame/offences/Cargo.toml +++ b/substrate/frame/offences/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME offences pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,20 +16,20 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", 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-staking = { path = "../../primitives/staking", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +serde = { version = "1.0.188", 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-staking = { path = "../../primitives/staking", default-features = false} +sp-std = { path = "../../primitives/std", default-features = false} [dev-dependencies] sp-core = { path = "../../primitives/core" } sp-io = { path = "../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/offences/benchmarking/Cargo.toml b/substrate/frame/offences/benchmarking/Cargo.toml index cddbd6aa4d5..acd8447c054 100644 --- a/substrate/frame/offences/benchmarking/Cargo.toml +++ b/substrate/frame/offences/benchmarking/Cargo.toml @@ -9,29 +9,26 @@ repository.workspace = true description = "FRAME offences pallet benchmarking" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.10.0", 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 } +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} log = { version = "0.4.17", default-features = false } [dev-dependencies] @@ -41,7 +38,7 @@ sp-core = { path = "../../../primitives/core" } sp-io = { path = "../../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking/std", diff --git a/substrate/frame/offences/benchmarking/src/lib.rs b/substrate/frame/offences/benchmarking/src/lib.rs index 563aa4755ce..c190927b84b 100644 --- a/substrate/frame/offences/benchmarking/src/lib.rs +++ b/substrate/frame/offences/benchmarking/src/lib.rs @@ -25,25 +25,30 @@ mod mock; use sp_std::{prelude::*, vec}; use frame_benchmarking::v1::{account, benchmarks}; -use frame_support::traits::{Currency, Get}; +use frame_support::traits::{Currency, Get, ValidatorSet, ValidatorSetWithIdentification}; use frame_system::{Config as SystemConfig, Pallet as System, RawOrigin}; +#[cfg(test)] +use sp_runtime::traits::UniqueSaturatedInto; use sp_runtime::{ traits::{Convert, Saturating, StaticLookup}, Perbill, }; -use sp_staking::offence::ReportOffence; +use sp_staking::offence::{Offence, ReportOffence}; use pallet_babe::EquivocationOffence as BabeEquivocationOffence; use pallet_balances::Config as BalancesConfig; use pallet_grandpa::{ EquivocationOffence as GrandpaEquivocationOffence, TimeSlot as GrandpaTimeSlot, }; +use pallet_im_online::{Config as ImOnlineConfig, Pallet as ImOnline, UnresponsivenessOffence}; use pallet_offences::{Config as OffencesConfig, Pallet as Offences}; use pallet_session::{ historical::{Config as HistoricalConfig, IdentificationTuple}, - Config as SessionConfig, Pallet as Session, SessionManager, + Config as SessionConfig, SessionManager, }; +#[cfg(test)] +use pallet_staking::Event as StakingEvent; use pallet_staking::{ Config as StakingConfig, Exposure, IndividualExposure, MaxNominationsOf, Pallet as Staking, RewardDestination, ValidatorPrefs, @@ -51,6 +56,8 @@ use pallet_staking::{ const SEED: u32 = 0; +const MAX_REPORTERS: u32 = 100; +const MAX_OFFENDERS: u32 = 100; const MAX_NOMINATORS: u32 = 100; pub struct Pallet(Offences); @@ -59,6 +66,7 @@ pub trait Config: SessionConfig + StakingConfig + OffencesConfig + + ImOnlineConfig + HistoricalConfig + BalancesConfig + IdTupleConvert @@ -176,7 +184,220 @@ fn make_offenders( Ok((id_tuples, offenders)) } +fn make_offenders_im_online( + num_offenders: u32, + num_nominators: u32, +) -> Result<(Vec>, Vec>), &'static str> { + Staking::::new_session(0); + + let mut offenders = vec![]; + for i in 0..num_offenders { + let offender = create_offender::(i + 1, num_nominators)?; + offenders.push(offender); + } + + Staking::::start_session(0); + + let id_tuples = offenders + .iter() + .map(|offender| { + < + ::ValidatorSet as ValidatorSet + >::ValidatorIdOf::convert(offender.controller.clone()) + .expect("failed to get validator id from account id") + }) + .map(|validator_id| { + < + ::ValidatorSet as ValidatorSetWithIdentification + >::IdentificationOf::convert(validator_id.clone()) + .map(|full_id| (validator_id, full_id)) + .expect("failed to convert validator id to full identification") + }) + .collect::>>(); + Ok((id_tuples, offenders)) +} + +#[cfg(test)] +fn check_events< + T: Config, + I: Iterator, + Item: sp_std::borrow::Borrow<::RuntimeEvent> + sp_std::fmt::Debug, +>( + expected: I, +) { + let events = System::::events() + .into_iter() + .map(|frame_system::EventRecord { event, .. }| event) + .collect::>(); + let expected = expected.collect::>(); + + fn pretty(header: &str, ev: &[D], offset: usize) { + log::info!("{}", header); + for (idx, ev) in ev.iter().enumerate() { + log::info!("\t[{:04}] {:?}", idx + offset, ev); + } + } + fn print_events( + idx: usize, + events: &[D], + expected: &[E], + ) { + let window = 10; + let start = idx.saturating_sub(window / 2); + let end_got = (idx + window / 2).min(events.len()); + pretty("Got(window):", &events[start..end_got], start); + let end_expected = (idx + window / 2).min(expected.len()); + pretty("Expected(window):", &expected[start..end_expected], start); + log::info!("---------------"); + let start_got = events.len().saturating_sub(window); + pretty("Got(end):", &events[start_got..], start_got); + let start_expected = expected.len().saturating_sub(window); + pretty("Expected(end):", &expected[start_expected..], start_expected); + } + + for (idx, (a, b)) in events.iter().zip(expected.iter()).enumerate() { + if a != sp_std::borrow::Borrow::borrow(b) { + print_events(idx, &events, &expected); + log::info!("Mismatch at: {}", idx); + log::info!(" Got: {:?}", b); + log::info!("Expected: {:?}", a); + if events.len() != expected.len() { + log::info!( + "Mismatching lengths. Got: {}, Expected: {}", + events.len(), + expected.len() + ) + } + panic!("Mismatching events."); + } + } + + if events.len() != expected.len() { + print_events(0, &events, &expected); + panic!("Mismatching lengths. Got: {}, Expected: {}", events.len(), expected.len(),) + } +} + benchmarks! { + report_offence_im_online { + let r in 1 .. MAX_REPORTERS; + // we skip 1 offender, because in such case there is no slashing + let o in 2 .. MAX_OFFENDERS; + let n in 0 .. MAX_NOMINATORS.min(MaxNominationsOf::::get()); + + // Make r reporters + let mut reporters = vec![]; + for i in 0 .. r { + let reporter = account("reporter", i, SEED); + reporters.push(reporter); + } + + // make sure reporters actually get rewarded + Staking::::set_slash_reward_fraction(Perbill::one()); + + let (offenders, raw_offenders) = make_offenders_im_online::(o, n)?; + let keys = ImOnline::::keys(); + let validator_set_count = keys.len() as u32; + let offenders_count = offenders.len() as u32; + let offence = UnresponsivenessOffence { + session_index: 0, + validator_set_count, + offenders, + }; + let slash_fraction = offence.slash_fraction(offenders_count); + assert_eq!(System::::event_count(), 0); + }: { + let _ = ::ReportUnresponsiveness::report_offence( + reporters.clone(), + offence + ); + } + verify { + #[cfg(test)] + { + let bond_amount: u32 = UniqueSaturatedInto::::unique_saturated_into(bond_amount::()); + let slash_amount = slash_fraction * bond_amount; + let reward_amount = slash_amount.saturating_mul(1 + n) / 2; + let reward = reward_amount / r; + let slash_report = |id| core::iter::once( + ::RuntimeEvent::from(StakingEvent::::SlashReported{ validator: id, fraction: slash_fraction, slash_era: 0}) + ); + let slash = |id| core::iter::once( + ::RuntimeEvent::from(StakingEvent::::Slashed{ staker: id, amount: BalanceOf::::from(slash_amount) }) + ); + let balance_slash = |id| core::iter::once( + ::RuntimeEvent::from(pallet_balances::Event::::Slashed{ who: id, amount: slash_amount.into() }) + ); + let balance_locked = |id| core::iter::once( + ::RuntimeEvent::from(pallet_balances::Event::::Locked{ who: id, amount: slash_amount.into() }) + ); + let balance_unlocked = |id| core::iter::once( + ::RuntimeEvent::from(pallet_balances::Event::::Unlocked{ who: id, amount: slash_amount.into() }) + ); + let chill = |id| core::iter::once( + ::RuntimeEvent::from(StakingEvent::::Chilled{ stash: id }) + ); + let balance_deposit = |id, amount: u32| + ::RuntimeEvent::from(pallet_balances::Event::::Deposit{ who: id, amount: amount.into() }); + let mut first = true; + + // We need to box all events to prevent running into too big allocations in wasm. + // The event in FRAME is represented as an enum and the size of the enum depends on the biggest variant. + // So, instead of requiring `size_of() * expected_events` we only need to + // allocate `size_of>() * expected_events`. + let slash_events = raw_offenders.into_iter() + .flat_map(|offender| { + let nom_slashes = offender.nominator_stashes.into_iter().flat_map(|nom| { + balance_slash(nom.clone()).map(Into::into) + .chain(balance_unlocked(nom.clone()).map(Into::into)) + .chain(slash(nom).map(Into::into)).map(Box::new) + }); + + let events = chill(offender.stash.clone()).map(Into::into).map(Box::new) + .chain(slash_report(offender.stash.clone()).map(Into::into).map(Box::new)) + .chain(balance_slash(offender.stash.clone()).map(Into::into).map(Box::new)) + .chain(balance_unlocked(offender.stash.clone()).map(Into::into).map(Box::new)) + .chain(slash(offender.stash).map(Into::into).map(Box::new)) + .chain(nom_slashes) + .collect::>(); + + // the first deposit creates endowed events, see `endowed_reward_events` + if first { + first = false; + let reward_events = reporters.iter() + .flat_map(|reporter| vec![ + Box::new(balance_deposit(reporter.clone(), reward).into()), + Box::new(frame_system::Event::::NewAccount { account: reporter.clone() }.into()), + Box::new(::RuntimeEvent::from( + pallet_balances::Event::::Endowed{ account: reporter.clone(), free_balance: reward.into() } + ).into()), + ]) + .collect::>(); + events.into_iter().chain(reward_events) + } else { + let reward_events = reporters.iter() + .map(|reporter| Box::new(balance_deposit(reporter.clone(), reward).into())) + .collect::>(); + events.into_iter().chain(reward_events) + } + }); + + // In case of error it's useful to see the inputs + log::info!("Inputs: r: {}, o: {}, n: {}", r, o, n); + // make sure that all slashes have been applied + check_events::( + sp_std::iter::empty() + .chain(slash_events) + .chain(sp_std::iter::once(Box::new(::RuntimeEvent::from( + pallet_offences::Event::Offence{ + kind: UnresponsivenessOffence::::ID, + timeslot: 0_u32.to_le_bytes().to_vec(), + } + ).into()))) + ); + } + } + report_offence_grandpa { let n in 0 .. MAX_NOMINATORS.min(MaxNominationsOf::::get()); @@ -188,12 +409,12 @@ benchmarks! { Staking::::set_slash_reward_fraction(Perbill::one()); let (mut offenders, raw_offenders) = make_offenders::(1, n)?; - let validator_set_count = Session::::validators().len() as u32; + let keys = ImOnline::::keys(); let offence = GrandpaEquivocationOffence { time_slot: GrandpaTimeSlot { set_id: 0, round: 0 }, session_index: 0, - validator_set_count, + validator_set_count: keys.len() as u32, offender: T::convert(offenders.pop().unwrap()), }; assert_eq!(System::::event_count(), 0); @@ -225,12 +446,12 @@ benchmarks! { Staking::::set_slash_reward_fraction(Perbill::one()); let (mut offenders, raw_offenders) = make_offenders::(1, n)?; - let validator_set_count = Session::::validators().len() as u32; + let keys = ImOnline::::keys(); let offence = BabeEquivocationOffence { slot: 0u64.into(), session_index: 0, - validator_set_count, + validator_set_count: keys.len() as u32, offender: T::convert(offenders.pop().unwrap()), }; assert_eq!(System::::event_count(), 0); diff --git a/substrate/frame/offences/benchmarking/src/mock.rs b/substrate/frame/offences/benchmarking/src/mock.rs index 1d642b9b498..1a458ec90d5 100644 --- a/substrate/frame/offences/benchmarking/src/mock.rs +++ b/substrate/frame/offences/benchmarking/src/mock.rs @@ -25,7 +25,7 @@ use frame_election_provider_support::{ onchain, SequentialPhragmen, }; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64}, }; use frame_system as system; @@ -40,7 +40,6 @@ type AccountId = u64; type Nonce = u32; type Balance = u64; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); @@ -185,7 +184,6 @@ impl pallet_staking::Config for Test { 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; diff --git a/substrate/frame/offences/src/mock.rs b/substrate/frame/offences/src/mock.rs index 61f680f6db9..990ceae5ac0 100644 --- a/substrate/frame/offences/src/mock.rs +++ b/substrate/frame/offences/src/mock.rs @@ -23,7 +23,7 @@ use crate as offences; use crate::Config; use codec::Encode; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64}, weights::{constants::RocksDbWeight, Weight}, }; @@ -75,7 +75,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/paged-list/Cargo.toml b/substrate/frame/paged-list/Cargo.toml index 2370f84898b..4bc3dd6a3c7 100644 --- a/substrate/frame/paged-list/Cargo.toml +++ b/substrate/frame/paged-list/Cargo.toml @@ -8,29 +8,26 @@ edition.workspace = true license = "Apache-2.0" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive"] } docify = "0.2.6" scale-info = { version = "2.10.0", 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 } +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-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 } +sp-metadata-ir = { path = "../../primitives/metadata-ir", default-features = false, optional = true} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", @@ -58,4 +55,4 @@ try-runtime = [ "sp-runtime/try-runtime", ] -frame-metadata = ["sp-metadata-ir"] +frame-metadata = [ "sp-metadata-ir" ] diff --git a/substrate/frame/paged-list/fuzzer/Cargo.toml b/substrate/frame/paged-list/fuzzer/Cargo.toml index 5c245cc72c7..d96c0348cf4 100644 --- a/substrate/frame/paged-list/fuzzer/Cargo.toml +++ b/substrate/frame/paged-list/fuzzer/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Fuzz storage types of pallet-paged-list" publish = false -[lints] -workspace = true - [[bin]] name = "pallet-paged-list-fuzzer" path = "src/paged_list.rs" @@ -20,6 +17,6 @@ path = "src/paged_list.rs" arbitrary = "1.3.0" honggfuzz = "0.5.49" -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 = { 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" ] } diff --git a/substrate/frame/paged-list/src/mock.rs b/substrate/frame/paged-list/src/mock.rs index 37bdc4f157c..390b4a8530d 100644 --- a/substrate/frame/paged-list/src/mock.rs +++ b/substrate/frame/paged-list/src/mock.rs @@ -20,10 +20,7 @@ #![cfg(feature = "std")] use crate::{paged_list::StoragePagedListMeta, Config, ListPrefix}; -use frame_support::{ - derive_impl, - traits::{ConstU16, ConstU64}, -}; +use frame_support::traits::{ConstU16, ConstU64}; use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -41,7 +38,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/preimage/Cargo.toml b/substrate/frame/preimage/Cargo.toml index 2aa21d2a713..a80ccd5a40d 100644 --- a/substrate/frame/preimage/Cargo.toml +++ b/substrate/frame/preimage/Cargo.toml @@ -8,27 +8,24 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME pallet for storing preimages of hashes" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", 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 } +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} log = { version = "0.4.17", default-features = false } [dev-dependencies] pallet-balances = { path = "../balances" } -sp-core = { path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false} [features] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ "frame-benchmarking", "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/preimage/src/mock.rs b/substrate/frame/preimage/src/mock.rs index 357f088f5ba..0f966312d9e 100644 --- a/substrate/frame/preimage/src/mock.rs +++ b/substrate/frame/preimage/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_preimage; use frame_support::{ - derive_impl, ord_parameter_types, + ord_parameter_types, traits::{fungible::HoldConsideration, ConstU32, ConstU64, Everything}, weights::constants::RocksDbWeight, }; @@ -43,7 +43,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = Everything; type BlockWeights = (); diff --git a/substrate/frame/proxy/Cargo.toml b/substrate/frame/proxy/Cargo.toml index fd163e71bc1..647193fad8a 100644 --- a/substrate/frame/proxy/Cargo.toml +++ b/substrate/frame/proxy/Cargo.toml @@ -9,21 +9,18 @@ repository.workspace = true description = "FRAME proxying pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["max-encoded-len"] } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } @@ -31,7 +28,7 @@ pallet-utility = { path = "../utility" } sp-core = { path = "../../primitives/core" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/ranked-collective/Cargo.toml b/substrate/frame/ranked-collective/Cargo.toml index 39075b2abf9..236489c54b5 100644 --- a/substrate/frame/ranked-collective/Cargo.toml +++ b/substrate/frame/ranked-collective/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Ranked collective system: Members of a set of account IDs can make their collective feelings known through dispatched calls from one of two specialized origins." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,17 +16,17 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.16", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/ranked-collective/src/lib.rs b/substrate/frame/ranked-collective/src/lib.rs index 51ee7d7144b..deb1ccf2357 100644 --- a/substrate/frame/ranked-collective/src/lib.rs +++ b/substrate/frame/ranked-collective/src/lib.rs @@ -663,21 +663,16 @@ pub mod pallet { } fn remove_from_rank(who: &T::AccountId, rank: Rank) -> DispatchResult { - MemberCount::::try_mutate(rank, |last_index| { - last_index.saturating_dec(); - let index = IdToIndex::::get(rank, &who).ok_or(Error::::Corruption)?; - if index != *last_index { - let last = IndexToId::::get(rank, *last_index) - .ok_or(Error::::Corruption)?; - IdToIndex::::insert(rank, &last, index); - IndexToId::::insert(rank, index, &last); - } - - IdToIndex::::remove(rank, who); - IndexToId::::remove(rank, last_index); - - Ok(()) - }) + let last_index = MemberCount::::get(rank).saturating_sub(1); + let index = IdToIndex::::get(rank, &who).ok_or(Error::::Corruption)?; + if index != last_index { + let last = + IndexToId::::get(rank, last_index).ok_or(Error::::Corruption)?; + IdToIndex::::insert(rank, &last, index); + IndexToId::::insert(rank, index, &last); + } + MemberCount::::mutate(rank, |r| r.saturating_dec()); + Ok(()) } /// Adds a member into the ranked collective at level 0. diff --git a/substrate/frame/ranked-collective/src/tests.rs b/substrate/frame/ranked-collective/src/tests.rs index 60c0da3d7ac..ba8c5a0f937 100644 --- a/substrate/frame/ranked-collective/src/tests.rs +++ b/substrate/frame/ranked-collective/src/tests.rs @@ -20,13 +20,16 @@ use std::collections::BTreeMap; use frame_support::{ - assert_noop, assert_ok, derive_impl, + assert_noop, assert_ok, error::BadOrigin, parameter_types, - traits::{ConstU16, EitherOf, MapSuccess, Polling}, + traits::{ConstU16, ConstU32, ConstU64, EitherOf, Everything, MapSuccess, Polling}, +}; +use sp_core::{Get, H256}; +use sp_runtime::{ + traits::{BlakeTwo256, IdentityLookup, ReduceBy}, + BuildStorage, }; -use sp_core::Get; -use sp_runtime::{traits::ReduceBy, BuildStorage}; use super::*; use crate as pallet_ranked_collective; @@ -42,9 +45,30 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { + type BaseCallFilter = Everything; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type RuntimeOrigin = RuntimeOrigin; + type Nonce = u64; + type RuntimeCall = RuntimeCall; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = u64; + type Lookup = IdentityLookup; type Block = Block; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = ConstU64<250>; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = ConstU32<16>; } #[derive(Clone, PartialEq, Eq, Debug)] @@ -417,32 +441,6 @@ fn cleanup_works() { }); } -#[test] -fn remove_member_cleanup_works() { - new_test_ext().execute_with(|| { - assert_ok!(Club::add_member(RuntimeOrigin::root(), 1)); - assert_ok!(Club::promote_member(RuntimeOrigin::root(), 1)); - assert_ok!(Club::add_member(RuntimeOrigin::root(), 2)); - assert_ok!(Club::promote_member(RuntimeOrigin::root(), 2)); - assert_ok!(Club::add_member(RuntimeOrigin::root(), 3)); - assert_ok!(Club::promote_member(RuntimeOrigin::root(), 3)); - - assert_eq!(IdToIndex::::get(1, 2), Some(1)); - assert_eq!(IndexToId::::get(1, 1), Some(2)); - - assert_eq!(IdToIndex::::get(1, 3), Some(2)); - assert_eq!(IndexToId::::get(1, 2), Some(3)); - - assert_ok!(Club::remove_member(RuntimeOrigin::root(), 2, 1)); - - assert_eq!(IdToIndex::::get(1, 2), None); - assert_eq!(IndexToId::::get(1, 1), Some(3)); - - assert_eq!(IdToIndex::::get(1, 3), Some(1)); - assert_eq!(IndexToId::::get(1, 2), None); - }); -} - #[test] fn ensure_ranked_works() { new_test_ext().execute_with(|| { diff --git a/substrate/frame/recovery/Cargo.toml b/substrate/frame/recovery/Cargo.toml index 6afd494bf7e..8e240546fdd 100644 --- a/substrate/frame/recovery/Cargo.toml +++ b/substrate/frame/recovery/Cargo.toml @@ -9,35 +9,32 @@ repository.workspace = true description = "FRAME account recovery pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } sp-core = { path = "../../primitives/core" } [features] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ + 'frame-benchmarking', "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "pallet-balances/runtime-benchmarks", "sp-runtime/runtime-benchmarks", - 'frame-benchmarking', ] std = [ "codec/std", diff --git a/substrate/frame/recovery/src/mock.rs b/substrate/frame/recovery/src/mock.rs index 44cbeec0986..bc81d07bec2 100644 --- a/substrate/frame/recovery/src/mock.rs +++ b/substrate/frame/recovery/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as recovery; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64, OnFinalize, OnInitialize}, }; use sp_core::H256; @@ -41,7 +41,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/referenda/Cargo.toml b/substrate/frame/referenda/Cargo.toml index f76dbece303..4f53e2bc002 100644 --- a/substrate/frame/referenda/Cargo.toml +++ b/substrate/frame/referenda/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet for inclusive on-chain decisions" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,14 +18,14 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = "derive", ] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", features = ["derive"], optional = 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 } +serde = { version = "1.0.188", features = ["derive"], optional = 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} log = { version = "0.4.17", default-features = false } [dev-dependencies] @@ -39,7 +36,7 @@ pallet-scheduler = { path = "../scheduler" } sp-core = { path = "../../primitives/core" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/referenda/src/mock.rs b/substrate/frame/referenda/src/mock.rs index b75558723e9..345accbe268 100644 --- a/substrate/frame/referenda/src/mock.rs +++ b/substrate/frame/referenda/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_referenda; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ - assert_ok, derive_impl, ord_parameter_types, parameter_types, + assert_ok, ord_parameter_types, parameter_types, traits::{ ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnInitialize, OriginTrait, Polling, SortedMembers, @@ -59,7 +59,6 @@ impl Contains for BaseFilter { parameter_types! { pub MaxWeight: Weight = Weight::from_parts(2_000_000_000_000, u64::MAX); } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = BaseFilter; type BlockWeights = (); diff --git a/substrate/frame/remark/Cargo.toml b/substrate/frame/remark/Cargo.toml index 646563bdb08..ad04140ae9f 100644 --- a/substrate/frame/remark/Cargo.toml +++ b/substrate/frame/remark/Cargo.toml @@ -9,29 +9,26 @@ repository.workspace = true description = "Remark storage pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", 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 } -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 } +serde = { version = "1.0.188", 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} +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} [dev-dependencies] -sp-core = { path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false} [features] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", diff --git a/substrate/frame/remark/src/mock.rs b/substrate/frame/remark/src/mock.rs index 0a385c30eac..e597a1ca4df 100644 --- a/substrate/frame/remark/src/mock.rs +++ b/substrate/frame/remark/src/mock.rs @@ -18,10 +18,7 @@ //! Test environment for remarks pallet. use crate as pallet_remark; -use frame_support::{ - derive_impl, - traits::{ConstU16, ConstU32, ConstU64}, -}; +use frame_support::traits::{ConstU16, ConstU32, ConstU64}; use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -39,7 +36,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/root-offences/Cargo.toml b/substrate/frame/root-offences/Cargo.toml index 0f3d3a2883d..8e6fddb4335 100644 --- a/substrate/frame/root-offences/Cargo.toml +++ b/substrate/frame/root-offences/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME root offences pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,13 +16,13 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -pallet-session = { path = "../session", default-features = false, features = ["historical"] } -pallet-staking = { path = "../staking", default-features = false } +pallet-session = { path = "../session", default-features = false , features = [ "historical" ]} +pallet-staking = { path = "../staking", default-features = false} -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } +frame-support = { path = "../support", default-features = false} +frame-system = { path = "../system", default-features = false} sp-runtime = { path = "../../primitives/runtime" } -sp-staking = { path = "../../primitives/staking", default-features = false } +sp-staking = { path = "../../primitives/staking", default-features = false} [dev-dependencies] pallet-balances = { path = "../balances" } @@ -33,8 +30,8 @@ pallet-timestamp = { path = "../timestamp" } pallet-staking-reward-curve = { path = "../staking/reward-curve" } sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +sp-io = { path = "../../primitives/io", default-features = false} +sp-std = { path = "../../primitives/std", default-features = false} frame-election-provider-support = { path = "../election-provider-support" } @@ -59,7 +56,7 @@ try-runtime = [ "pallet-timestamp/try-runtime", "sp-runtime/try-runtime", ] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-election-provider-support/std", diff --git a/substrate/frame/root-offences/src/mock.rs b/substrate/frame/root-offences/src/mock.rs index c0c83dd08d2..82da429e00a 100644 --- a/substrate/frame/root-offences/src/mock.rs +++ b/substrate/frame/root-offences/src/mock.rs @@ -23,7 +23,7 @@ use frame_election_provider_support::{ onchain, SequentialPhragmen, }; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64, Hooks, OneSessionHandler}, }; use pallet_staking::StakerStatus; @@ -84,7 +84,6 @@ impl sp_runtime::BoundToRuntimeAppPublic for OtherSessionHandler { type Public = UintAuthorityId; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); @@ -188,7 +187,6 @@ impl pallet_staking::Config for Test { 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; diff --git a/substrate/frame/root-testing/Cargo.toml b/substrate/frame/root-testing/Cargo.toml index 78aed99a56d..7837289cec5 100644 --- a/substrate/frame/root-testing/Cargo.toml +++ b/substrate/frame/root-testing/Cargo.toml @@ -9,21 +9,18 @@ repository.workspace = true description = "FRAME root testing pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", 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 } +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} [features] try-runtime = [ @@ -31,7 +28,7 @@ try-runtime = [ "frame-system/try-runtime", "sp-runtime/try-runtime", ] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/safe-mode/Cargo.toml b/substrate/frame/safe-mode/Cargo.toml index f86332483c4..f7b4ea4dd8c 100644 --- a/substrate/frame/safe-mode/Cargo.toml +++ b/substrate/frame/safe-mode/Cargo.toml @@ -8,25 +8,22 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME safe-mode pallet" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false, features = ["derive"] } docify = "0.2.6" -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 = { 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.10.0", 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 } +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 } +pallet-utility = { path = "../utility", default-features = false, optional = true } +pallet-proxy = { path = "../proxy", default-features = false, optional = true } [dev-dependencies] sp-core = { path = "../../primitives/core" } @@ -37,7 +34,7 @@ pallet-proxy = { path = "../proxy" } frame-support = { path = "../support", features = ["experimental"] } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking/std", diff --git a/substrate/frame/safe-mode/src/mock.rs b/substrate/frame/safe-mode/src/mock.rs index 7574d64d59d..10afe5bd4b5 100644 --- a/substrate/frame/safe-mode/src/mock.rs +++ b/substrate/frame/safe-mode/src/mock.rs @@ -23,7 +23,7 @@ use super::*; use crate as pallet_safe_mode; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU64, Everything, InsideBoth, InstanceFilter, IsInVec, SafeModeNotify}, }; use frame_system::EnsureSignedBy; @@ -33,7 +33,6 @@ use sp_runtime::{ BuildStorage, }; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = InsideBoth; type BlockWeights = (); diff --git a/substrate/frame/salary/Cargo.toml b/substrate/frame/salary/Cargo.toml index 929151a9c20..6c66f01082d 100644 --- a/substrate/frame/salary/Cargo.toml +++ b/substrate/frame/salary/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Paymaster" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,17 +16,17 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.16", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/salary/src/tests.rs b/substrate/frame/salary/src/tests.rs index fbca1be1188..1136ea746f6 100644 --- a/substrate/frame/salary/src/tests.rs +++ b/substrate/frame/salary/src/tests.rs @@ -20,7 +20,7 @@ use std::collections::BTreeMap; use frame_support::{ - assert_noop, assert_ok, derive_impl, + assert_noop, assert_ok, pallet_prelude::Weight, parameter_types, traits::{tokens::ConvertRank, ConstU32, ConstU64, Everything}, @@ -49,8 +49,6 @@ parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::simple_max(Weight::from_parts(1_000_000, 0)); } - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = Everything; type BlockWeights = (); diff --git a/substrate/frame/sassafras/Cargo.toml b/substrate/frame/sassafras/Cargo.toml deleted file mode 100644 index ad4c0ba12f0..00000000000 --- a/substrate/frame/sassafras/Cargo.toml +++ /dev/null @@ -1,62 +0,0 @@ -[package] -name = "pallet-sassafras" -version = "0.3.5-dev" -authors = ["Parity Technologies "] -edition = "2021" -license = "Apache-2.0" -homepage = "https://substrate.io" -repository = "https://github.com/paritytech/substrate/" -description = "Consensus extension module for Sassafras consensus." -readme = "README.md" -publish = false - -[lints] -workspace = true - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -scale-codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } -scale-info = { version = "2.5.0", 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 } -log = { version = "0.4.17", default-features = false } -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 } - -[dev-dependencies] -array-bytes = "6.1" -sp-core = { path = "../../primitives/core" } - -[features] -default = ["std"] -std = [ - "frame-benchmarking?/std", - "frame-support/std", - "frame-system/std", - "log/std", - "scale-codec/std", - "scale-info/std", - "sp-consensus-sassafras/std", - "sp-io/std", - "sp-runtime/std", - "sp-std/std", -] -runtime-benchmarks = [ - "frame-benchmarking/runtime-benchmarks", - "frame-support/runtime-benchmarks", - "frame-system/runtime-benchmarks", - "sp-runtime/runtime-benchmarks", -] -try-runtime = [ - "frame-support/try-runtime", - "frame-system/try-runtime", - "sp-runtime/try-runtime", -] -# Construct dummy ring context on genesis. -# Mostly used for testing and development. -construct-dummy-ring-context = [] diff --git a/substrate/frame/sassafras/README.md b/substrate/frame/sassafras/README.md deleted file mode 100644 index f0e24a05355..00000000000 --- a/substrate/frame/sassafras/README.md +++ /dev/null @@ -1,8 +0,0 @@ -Runtime module for SASSAFRAS consensus. - -- Tracking issue: https://github.com/paritytech/polkadot-sdk/issues/41 -- Protocol RFC proposal: https://github.com/polkadot-fellows/RFCs/pull/26 - -# ⚠️ WARNING ⚠️ - -The crate interfaces and structures are experimental and may be subject to changes. diff --git a/substrate/frame/sassafras/src/benchmarking.rs b/substrate/frame/sassafras/src/benchmarking.rs deleted file mode 100644 index 95a2b4bbce4..00000000000 --- a/substrate/frame/sassafras/src/benchmarking.rs +++ /dev/null @@ -1,272 +0,0 @@ -// 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. - -//! Benchmarks for the Sassafras pallet. - -use crate::*; -use sp_consensus_sassafras::{vrf::VrfSignature, EphemeralPublic, EpochConfiguration}; - -use frame_benchmarking::v2::*; -use frame_support::traits::Hooks; -use frame_system::RawOrigin; - -const LOG_TARGET: &str = "sassafras::benchmark"; - -const TICKETS_DATA: &[u8] = include_bytes!("data/25_tickets_100_auths.bin"); - -fn make_dummy_vrf_signature() -> VrfSignature { - // This leverages our knowledge about serialized vrf signature structure. - // Mostly to avoid to import all the bandersnatch primitive just for this test. - let buf = [ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xb5, 0x5f, 0x8e, 0xc7, 0x68, 0xf5, 0x05, 0x3f, 0xa9, - 0x18, 0xca, 0x07, 0x13, 0xc7, 0x4b, 0xa3, 0x9a, 0x97, 0xd3, 0x76, 0x8f, 0x0c, 0xbf, 0x2e, - 0xd4, 0xf9, 0x3a, 0xae, 0xc1, 0x96, 0x2a, 0x64, 0x80, - ]; - VrfSignature::decode(&mut &buf[..]).unwrap() -} - -#[benchmarks] -mod benchmarks { - use super::*; - - // For first block (#1) we do some extra operation. - // But is a one shot operation, so we don't account for it here. - // We use 0, as it will be the path used by all the blocks with n != 1 - #[benchmark] - fn on_initialize() { - let block_num = BlockNumberFor::::from(0u32); - - let slot_claim = SlotClaim { - authority_idx: 0, - slot: Default::default(), - vrf_signature: make_dummy_vrf_signature(), - ticket_claim: None, - }; - frame_system::Pallet::::deposit_log((&slot_claim).into()); - - // We currently don't account for the potential weight added by the `on_finalize` - // incremental sorting of the tickets. - - #[block] - { - // According to `Hooks` trait docs, `on_finalize` `Weight` should be bundled - // together with `on_initialize` `Weight`. - Pallet::::on_initialize(block_num); - Pallet::::on_finalize(block_num) - } - } - - // Weight for the default internal epoch change trigger. - // - // Parameters: - // - `x`: number of authorities (1:100). - // - `y`: epoch length in slots (1000:5000) - // - // This accounts for the worst case which includes: - // - load the full ring context. - // - recompute the ring verifier. - // - sorting the epoch tickets in one shot - // (here we account for the very unluky scenario where we haven't done any sort work yet) - // - pending epoch change config. - // - // For this bench we assume a redundancy factor of 2 (suggested value to be used in prod). - #[benchmark] - fn enact_epoch_change(x: Linear<1, 100>, y: Linear<1000, 5000>) { - let authorities_count = x as usize; - let epoch_length = y as u32; - let redundancy_factor = 2; - - let unsorted_tickets_count = epoch_length * redundancy_factor; - - let mut meta = TicketsMetadata { unsorted_tickets_count, tickets_count: [0, 0] }; - let config = EpochConfiguration { redundancy_factor, attempts_number: 32 }; - - // Triggers ring verifier computation for `x` authorities - let mut raw_data = TICKETS_DATA; - let (authorities, _): (Vec, Vec) = - Decode::decode(&mut raw_data).expect("Failed to decode tickets buffer"); - let next_authorities: Vec<_> = authorities[..authorities_count].to_vec(); - let next_authorities = WeakBoundedVec::force_from(next_authorities, None); - NextAuthorities::::set(next_authorities); - - // Triggers JIT sorting tickets - (0..meta.unsorted_tickets_count) - .collect::>() - .chunks(SEGMENT_MAX_SIZE as usize) - .enumerate() - .for_each(|(segment_id, chunk)| { - let segment = chunk - .iter() - .map(|i| { - let id_bytes = crate::hashing::blake2_128(&i.to_le_bytes()); - TicketId::from_le_bytes(id_bytes) - }) - .collect::>(); - UnsortedSegments::::insert( - segment_id as u32, - BoundedVec::truncate_from(segment), - ); - }); - - // Triggers some code related to config change (dummy values) - NextEpochConfig::::set(Some(config)); - PendingEpochConfigChange::::set(Some(config)); - - // Triggers the cleanup of the "just elapsed" epoch tickets (i.e. the current one) - let epoch_tag = EpochIndex::::get() & 1; - meta.tickets_count[epoch_tag as usize] = epoch_length; - (0..epoch_length).for_each(|i| { - let id_bytes = crate::hashing::blake2_128(&i.to_le_bytes()); - let id = TicketId::from_le_bytes(id_bytes); - TicketsIds::::insert((epoch_tag as u8, i), id); - let body = TicketBody { - attempt_idx: i, - erased_public: EphemeralPublic([i as u8; 32]), - revealed_public: EphemeralPublic([i as u8; 32]), - }; - TicketsData::::set(id, Some(body)); - }); - - TicketsMeta::::set(meta); - - #[block] - { - Pallet::::should_end_epoch(BlockNumberFor::::from(3u32)); - let next_authorities = Pallet::::next_authorities(); - // Using a different set of authorities triggers the recomputation of ring verifier. - Pallet::::enact_epoch_change(Default::default(), next_authorities); - } - } - - #[benchmark] - fn submit_tickets(x: Linear<1, 25>) { - let tickets_count = x as usize; - - let mut raw_data = TICKETS_DATA; - let (authorities, tickets): (Vec, Vec) = - Decode::decode(&mut raw_data).expect("Failed to decode tickets buffer"); - - log::debug!(target: LOG_TARGET, "PreBuiltTickets: {} tickets, {} authorities", tickets.len(), authorities.len()); - - // Set `NextRandomness` to the same value used for pre-built tickets - // (see `make_tickets_data` test). - NextRandomness::::set([0; 32]); - - Pallet::::update_ring_verifier(&authorities); - - // Set next epoch config to accept all the tickets - let next_config = EpochConfiguration { attempts_number: 1, redundancy_factor: u32::MAX }; - NextEpochConfig::::set(Some(next_config)); - - // Use the authorities in the pre-build tickets - let authorities = WeakBoundedVec::force_from(authorities, None); - NextAuthorities::::set(authorities); - - let tickets = tickets[..tickets_count].to_vec(); - let tickets = BoundedVec::truncate_from(tickets); - - log::debug!(target: LOG_TARGET, "Submitting {} tickets", tickets_count); - - #[extrinsic_call] - submit_tickets(RawOrigin::None, tickets); - } - - #[benchmark] - fn plan_config_change() { - let config = EpochConfiguration { redundancy_factor: 1, attempts_number: 10 }; - - #[extrinsic_call] - plan_config_change(RawOrigin::Root, config); - } - - // Construction of ring verifier - #[benchmark] - fn update_ring_verifier(x: Linear<1, 100>) { - let authorities_count = x as usize; - - let mut raw_data = TICKETS_DATA; - let (authorities, _): (Vec, Vec) = - Decode::decode(&mut raw_data).expect("Failed to decode tickets buffer"); - let authorities: Vec<_> = authorities[..authorities_count].to_vec(); - - #[block] - { - Pallet::::update_ring_verifier(&authorities); - } - } - - // Bare loading of ring context. - // - // It is interesting to see how this compares to 'update_ring_verifier', which - // also recomputes and stores the new verifier. - #[benchmark] - fn load_ring_context() { - #[block] - { - let _ring_ctx = RingContext::::get().unwrap(); - } - } - - // Tickets segments sorting function benchmark. - #[benchmark] - fn sort_segments(x: Linear<1, 100>) { - let segments_count = x as u32; - let tickets_count = segments_count * SEGMENT_MAX_SIZE; - - // Construct a bunch of dummy tickets - let tickets: Vec<_> = (0..tickets_count) - .map(|i| { - let body = TicketBody { - attempt_idx: i, - erased_public: EphemeralPublic([i as u8; 32]), - revealed_public: EphemeralPublic([i as u8; 32]), - }; - let id_bytes = crate::hashing::blake2_128(&i.to_le_bytes()); - let id = TicketId::from_le_bytes(id_bytes); - (id, body) - }) - .collect(); - - for (chunk_id, chunk) in tickets.chunks(SEGMENT_MAX_SIZE as usize).enumerate() { - let segment: Vec = chunk - .iter() - .map(|(id, body)| { - TicketsData::::set(id, Some(body.clone())); - *id - }) - .collect(); - let segment = BoundedVec::truncate_from(segment); - UnsortedSegments::::insert(chunk_id as u32, segment); - } - - // Update metadata - let mut meta = TicketsMeta::::get(); - meta.unsorted_tickets_count = tickets_count; - TicketsMeta::::set(meta.clone()); - - log::debug!(target: LOG_TARGET, "Before sort: {:?}", meta); - #[block] - { - Pallet::::sort_segments(u32::MAX, 0, &mut meta); - } - log::debug!(target: LOG_TARGET, "After sort: {:?}", meta); - } -} diff --git a/substrate/frame/sassafras/src/data/25_tickets_100_auths.bin b/substrate/frame/sassafras/src/data/25_tickets_100_auths.bin deleted file mode 100644 index 6e81f216455ae9dc61be31a9edef583a652721a8..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 24728 zcmb@NQ+H)+lt52xqhi}h#kOtRb}Bwm#kP%#Z9A#hwr!(t_aCU2-mmj{?lIQ<)`|y_ z!E3ZEM8f*RvMLf+!?96gw=kg$1liS&4$1dALn5*V*akULr*LUn1`=+>m6!ePaO!e` zPA%#m?01WJ+cJKD0npko3ibm0$;`N$e&uGBh!XNTA#fkj%hWT()|s4{i2{sidFO%6 zd4v96=7}Nf^Ei;wU^IP4_P5jcuOa>=IC@i|COiG%Z;XNB^|4Mb0Voy6 znZ#UadJoArKC@1RC@%Jm{`h+7?*>2Pvp58(=0#RuQE1e*(? zA{peioGCr`%q1;Nh>HUfe?_3k0%+ZSe!xP34 zbX_1Nz=zOKgWXB$HTL9Yv^Nmc3`6YZcLDTYb`o0!LcvOUBp}bmBRCJxY@f7+;HJ5R z&OM)TEy2!g?-zpt-XH3+U3NgA!J6E_GsV~d7-dVCNiN=26%6t+W=3gCkkkFWJcKqt zhc0TI@;67Opvnm-R^=Zg0gd*94qY@6+8jO5z)Bb}0Dmf=h>w@#H;PiMN`%6R!*Vvg zaM{SdJEYF3)syM5JOFuaP_f>p!5eYA*rJy3FVmZtk&(Vd-FC#El&2ab4N*W%Oog8} zzq2_6t<->xqmed4Lr}rEi-tr@96tA~D+(*{%;Y-@o{YC53AKCH4U!TA3th!Sokl)P zzjt(1s^|v|@N~svu8F+qJAltpo1GC?V6tSCk*S~X?}$)G{rKb*1W=!K5Owy_5$$o= zS^M-k7X`;EGG8oLf`KDq>3Nn6$`07g5Yvv9ot`f!N|vM=H-t$9Qw=F-jH{HPtq@tK zbb|mii(^Rio?)}irzVbXs-u*0M9ufH;(y~cmr)?B;)#I-e2xeuKg%p7J$9ar@*N`4 zz?9k=Dqzbu>QRNaqZ9c51h&n4?s5a)Q4J_BSIvMNizH>8JnVw)_Qq72Hb$gvmr5p1 z2a&tZ;F;TA?Gq|M%`ICHV_8%cSO%`-Fp6l2OENfoaMIIpFQiE?<-}DZAUb}2giqM4 zj@>4pFnF-YhX(H?tEJ^r zNOG4*LI~J-QE(Nc8R4EEW!t>YrF6I_1ci<3>w>b0C1$DiSVjlDm!afdhij%NaTQaQ zaFiv7W_b>}&jN!lL?EI@K41v}zXi|OdE`8a-EU9}xe5NT`m*UwJpjtWg!IICv8_+F z0L5|(5SWM(Tp0rpP3_dYP+^%%SNw4}T=CuJ41$t$^Z>S8chGEC_hW)ruc7HIWI&8_$?`eR<%U^54Be(YidiGY0$pJ@d--W@XVh>-(4e3-uo8B_cwAfHNOh zw+ZS!jVLg4u@4x!$%83>+YH9qD=`A5&rOLA4A;vK-=jYX5Za21QCYh^Nml`pV=OSv zD*5A)^NS4?9aHJ^>+TXQ8gfzFC#{BO5o-- z%>Ez*oKtUX3+5oE>YYgUYN#7q8DwjDDzQSg-5RtFXdU9H0HyIN3d#Ky*^!w!YzN`) z2ct9(!%B*JxYEbVJ3e`w(1jA4jk%sLXSaTtO6 zF4R-m@{U1z^f>#{{fM$?dWf!G@HoG44I((Rf8!AW1r%@z^o2bY$-#qERTcw~2W-^3 z4Q!;2oQx{2BCbMl0Rg3c{sxj<%9=GRL|QmFa{8txRkQoBI#$YdlMvr&7=U?9SKVBy zo?egFg|85Z-4w!rOd|n3q1@3K5aDF#}$pEkFa6ec0R7 zPD}A22@wr2kM@%?f}9)9%XI*A5<>l_hZ_KFhf}4y??;oUAI_yCFe-!DCv%fiYAW(= zk~5T>=q4+F7RV=Ao-owF+h|fH4^WrcC03M{M($L)t}H7~Fw2XZXa30X_}zkdhf6y2 z#0RKq-J_uwts^K@8zJagAPV>BZ2{r_AUo0nK^wafpJz6XmS|~rjo2pu5v2os80sx}1 zlSe;B^|4@L4|DDV$3`zAdXKs{j8f@L{Lq(l-~cloH%lLmdVXgkFRCKjC#{HwU!=P#q7*#SRP6 zflYs*IO~8sAkRI;dZPRr753*}A289vz;73>EQWBBTubE+HCBe`shw{t3Od^nmbi)a z{cbs05&)DP2TDXh-NV(18N2lQSgBuW6zM}u%eJJ6d`a~Hu_VyC>stUUpBD2KY>Jm( z#0xFFbn9B)3B;riALl-Vh>!y)oL-|!o9Ft>GrGCQZG>o9;k?AI*CJI5sioJ?C0@!6 z7(&M1eD!QK%7{IR|5gyq;7QhSdL>umDzjqfM!ZI#0Ak;~?+1rn4@p($s1Kl^H7E!8zfWsL6{#E4+w6$=(o1o%c8)`H5_2c3p zNOHaVL-NDq_F#SGPW9T39H8RARCe|p83{?Ws#h8KJ;-SmLxUQexRL1h96X`!i40h3 zpQKd4^_4qXWbk_zFef|h3<16$o*vxiTIaSvs@sUgG zA4%kTvYycJTcFeiq6cV&+Ur45l%b%EaB+lTo1{0v@H}W-sEWbAxgbEn0TDt~IcxF{ z%;YL$=%%}-fL#Y3#;v!>mzQ0CXEX50Ddm!G$6V0tPK(=j#l$G)@sCfUUR7+2;sz zg=vCTiyzn`(Xn=p8`!;@9y0*vhl9sYoYUBX1V3@SAKrDh`=SAuP}(*{UQ~uzFI)TE z;w&wx5vOex-}~`Qz;=@0b9=!JBq~7YlPDyw&&o%dX%GG#JEZrY7ne3a{&KU;cyk#s z0^nBD#BEe6eGF1+B;e;G5VM~n>2!*@b>N5doO5yp1`v*H~4I$#a z=>t3$Ffm?p^W{8NjZa-Wl`lX_l)et@ySvCC(E2X@>~Z@R1JE(iER?{GETFanh${Z_ zDz0@=Q5K+no9Q|kql$*Y@UrOtDO1itQ>s-LQIjTBQu4>%r7BOM0j0K*AyHrw5wPcb zanyn8IKb6^vY~_`PYMq;Kf%W*wDGHD={FKj50SdRh=w6`=_T-Ezxg_eB;9 z%?eVoXc16U?KBKmbT1 zKgRca%WXwIwsZgrs9+@ zZwjk^R;VS^aWF4?`s9?D z(Dd+X@$7v(_|H~eS~d`r&0OoRHpG)t#d2;gg!^=51(tpQX*jl61GBS8{!cP!gj{w> z)pG}rn;C3QdpEgy?;^pVr&fll_}`dtn)-@AB^RuUI)kAC2=?%@>Z0`TyriTbnvNOf zNv$5Db0mKzI8B?K8}yrf{6(OAPJHB~QROh< zw}r%Al+5A=)bhg>b0`MR%y#jved>dw*k8By8^$G0`Y+%;sy- zpRt;T_)Np5(qI3-Y}nzl}j=TigCwT1Uty}?qw@z>2?R>_rQ1cLlOh;`qaQmsM~55si;_HxXg z{o`Oo_R$Vg#~F_}gd#`8kP}!#A-z#Jq9-fcu39E0s+eA^;Kje4FtV2tMU8r$ zI5%IJF`~cgOCqXTY}v~{=B{#dTH%;|FpkGd0*8wG1B)YkGftB1k;5l$V)8Vv2;#ZNqX#A5?h7%W&l-!ypZL+beCXcrk-Ks@Nkk@#QV!ayin zgnZ9p{D|LhwK3RubX>fQz9img_#AC8(|TT;2rWFV=5W<|)iNOZzRMV|9WoCCUUMZh z;v~IvE8o}9*+cj~h_>%N`sohm)^|mwX8U>vm#S%wWXy5HaP3^lflGultut zg2TN_6JY`)Opi98B}dJOQ8DB0-0VFkt@H&KiJ)=>w68kdaOxEf)@rZ$cx~ zR@s?*x}MN|y0l)^ZNVp!`{xLzC(kv(%(CxphZw(Blc61h7;+k@%Z%2*6ZL?g{|{mX zwIURxKKjGcJ+cqm$-R7e%Km0a{@l#gH9GBI&@^BLsG9MWkXY2^QN?admE4Gb%4cw! zr(CW5;S2Hv4Zr4xqstFdl7^v$N-zzh0pr2qO)W_U$4g!&KC`K&QVghvv-ghfqBf(K z6Ft@bC`oTS!8(-1N^;7}hpEO)oUOSt1O!_xw!Sm#cRYx5K8w@2E4|lK!!kKFn0w+( z0Ezn<0Dw^ELFUG>4g|YU3UmGWa}zblMo-J{u;`&f`SMlBqI^GEC;X z(WN9*N`(f6NfTgoOZUr?WNPujaHE&LNiS$pZA2;6?vdC2f<#OQ0aMi+yP_x?M106d zk(#2vDZ=$ebkv9KE9kIiOMV_LC2paij2bz&7vNnI!Z2ouCc~*Ja@sQ zp4ZO!z@C&(pSy1^9<8~y1@4hv!Mq{w@Q~n`Je0ZzSu30>cKsV$)2rgbh-Q?eY7D0j{ z@)L=&#$YMQ?Y7mpFlQrfdjbNJB~mRH?HUQAbu7u)r`FS0EcSYtB; zRW>GC6Kp^{6KF3RLLLO0Q-Lsi~immIU{>J2W*BTa9brK>S^p8aF7M}T&@-{H80!32ZRUf8M`t( z{u&z^d$2baNXl;53Nt`o!ku`O5`y3#N7d$2o&uuYVcy+zt*aLfzqKX1*xj1pkq#NB zbzjy#BT{NS+<}xuT3?4Sn^=Brt!)>c|B-m+^lIDLCQ+9U*9Y(|@|Wl+A;)5Sn{Bb}3dV(eSR4;FA&SE<7->~R1>J)19;Im}$?(iRJOz>+<^bW9}KAI*&As9M%Ss{C#O zd`X<}INr$9a}_FYTiO|;;fXX0!@(xux&@o_@T-~9gTNmYXR7JIyd+%%mdTDoLEMqI z%lYaIf|IC*!6Lh3Upi!$*w69j;xkV9pw(E0H)X+5ZiL9dU9Ju~dEw=0J2rx)F25>o zv+r3cRS<2;beO=FusdXN*?`n*_OS@is^5f8mPE^#+?|sk5_#hd%pmv`*gRE3Tys(a z((?EO0g2ub4`fyfR#{tPUo9@%tT*1!zXz++x2#!xs_ne0S?J<<3cg+qRqH+~E>FC4oOwPky{iNfdp>Jo z*(@5U2tqCWX=@fr1N4zQMtv?9Q%Bk=zdI!Rc}2c!P)O+qS&+Mbz-5x;8r@SjhjE(~ zG^@`oFL2Usqxg-lIKvo_$;xx8ntD#k{CSpMY}-@KX`b;Wgu$`q>FCaS_qCS2K;nUS zJ%%8Fr+)A;jzw6WoE1gV9Vl>#CrqT`6oZ};y%E)ip_d>&v_o4AdBOogO$ZoE4 zFd|b(*!Ys<+&eoQJAkGsa_#g+PZxSej;6I}<}HN>H!C>->ZZO%f=74X+!f2WRy1&a z&P*UL%RO4M2^|@*(Ai$&V|%X7&f9sWPQgW$g2!=PW_#G zFGIZB0?n{O+y=@p=g5M1U!26EBEH2IS!xX5AV!yNssG&>K{?j2R0b*{72%c+m$6o( ziv4p(iaG@m**8I=_mu#Fa92QKA6Sk$fpv6<3ZhQnzdd>$GRVyCaALaAi|wA+K8eR5#!)*3V)U0Nayv}McrpT%jwI8Yh8=xK zOO=m++>m9E{wkbg&cU3#ktRxS&3c_1pL0`<@?%I%UK`TMiOk}V$z8D25i%hL|Bg|H zG4M>Uyj;O$_S2xpwfRJm=8j5K(C{r<%iFh?cZz<|7mWY30{rt4_Fs>*H@>Fe+b+^> zw!=_VkC4pUHuFNk%?~g921*S>Q}(Jm=ghM9R9 z(5xPNQlu9gDHsRhp&-t*U2$!`1JeT)72BNkn6(UmA(WmaQAKN>UrUf^DtY;y)-c8S zu1W)T*yc+Tw7#!zIK^2!cI>*GDtn|EsDN3$FQT6wc`D4{`c(0#yTHchof$5le4|W;mR+3O84_ zZjCYly_paQ?oozlx(*~`F{ktsVxs!o1H*5BCC;M;$yO*GKs?#{3g7AtLPbz(WMyxA~q9SCG zM77387NYf?glDArE>52ID?*Y$6ZR0L5^FWjS2*B>>at@+h&z!-tNZskV(V0^-4kwm zL=3-}xOPat_-=k*`v^m)x%N1LGe@(!jz-yh0p?gmagH4&z(g#chh}ucd)%`*^0zpJ z0RI~={w2=8xF310przhJ{WHT7(TwreW@PZpq$SwShDN&JpxoM&4)9WqLYHf=&IDCm zChF(=D`+h`KWI3JE=Of!$dr}9=tRA3!_0B4O9Z5Lh{v4s7Us22- zvigN{L(U!#wu2MO}#h3OZ}Pz-xlfIR0Jyhcm^!7tXIk z_mAX~-hBW?9OS!GTiCe|o9ZXCd(0kk(5=YhAIWI_(&r-*#fv0cTx%H*S!$S2Kr55GpdK~_|P6c&ZR@22o5YNvT6y%zqtG?xiW1M)FzvQLvdpV49;^yYgFC=1hI5t-&HxJM*{7r{{XF z#r%*-B&TP#X#RQZ)XR`cFsUnpy{{nQG!;RjF^{#B99N>c?5qUQI;x-*gz)ixoFjf# zBh_{V8iMI+lujQNQ(nR(Xax18Nf4KJ-~@T^Ifb>OfAyj%u`PjLv1W{jcNByB2grZF zmEb0c^0w?j*nJdFY@%&v}>OsAv!!i68Be9}!!N2mbpPF%T1WM%jGOUaL zz*w7fs|CqP&ezipW(@A)XafE>Ui?d(e{ovB7T+J0Vww)Qf`*Ae%!OE-n5j!GlL@KH zs|EpZT^t}T=z%Bi(Y5>+D!uxX6Zwgo?H}!G=oC5px(f#8{%yF!&J_`--Pz3yEX(67 zo+si-TyuVgtyxsCS&bsW77oZKyO+R}bVF2s6u4_jqB+$XVoH%xk0w5E6=!o{#RN&f zZ;M)I>hljAsnR^kolI1haI7EwMV(S-sdWj&M;H9s!1@5HHJ60YKM^V*n?#=t^vzT` zT4(b;4b$SMiJgxf^<@c@44@0MDNkKs&RUmt``;%^IMFoK{E#oB@YPKHPy*(g`9l`dxQd;3`rarg~;sZr;tAFiWopdh9Iv*ZsM zIJmSG$_zgN$3;z*(~?=GQ+=|kfZyoNC3728*dL9U;YfIJe6mUT;0MKGSoe!h6G09a zmvsMjR!B_5NI^hs)dX9(X76FDgSk&>5lA@!1~AqavpRC|zjn=_!%4eE*C8-KQ2U;; zTm1ViLvjmt2`;UQMJXaWcN7Y&u;mv)BkkCzg3Mb)N_Sqbpuvd4oKoE z`4(VcTDP!vmOlAm)s+5YiJl9!Ow=^gsu{mIe6qgZJ%Fn_PBTkziGsPp9upj1ym~_OE6zbNts>ROI7Z2g;YHjZKJP|5q z&7|p(2yaoy2>Tb7@DN#<5j#OaK4lIg1@Wg&hc#A zlLo*QsyAv#oHKtH;;rhjpoi;tPbf$IDs$V-y7hU~Pb?Dx{%^eampK38L=RL>@5L|r z*lpAfEHp5em=v+9O53<2eqib*Fo^7|0AiP|&5u7BJqUnI-&wK=+MS@`i_;$=8|I3G z%?GUj7zu@zJQZQQN;|&S8E)a%``)c}g&L`+kivuj%|JUUw7;=UFYmhnA6TY-yq}sC z8t#amrRylP!Pkae44*tb1OUu1ib0q8+-OoL_eGff6xw&Dl8-JQ2MHa1`l zT@N%jxRRgtQ&L8(u)`#}_LzD{~p6z{4~L{L7YrLIhi-U>VCW1#67=vl1oANUaYa(yz-Z!2e3 zb~`R=P#PFpq%3&z0(JPOP1z}uy1kTrH~KH%cK*ENi`QsiqD0dV?I9Sds%NH4&<#a@ z&O(8HeUI=ZBpuyXAH47=WSh%lWX|=`($nkdjl<;e}|%(~?e% zUGh0NF=ZM|o!+K`sZt-|(kE9OtjP|OrQwkrTX|(pOr+E{8Y;9{n_c9Q*62;H4tjk0 z1IvfWH4;>c2D8}%6YX%sj_Bcs{*%rYjI&aO z-X11+uj-`B?3k8)4!^d%+P-D-6?uZ`_>U5(p?N21v7}Aj75u`7WzO885rVOf*&y@= zNw_A+B}ScqLS{dwzIE5D4XbUQ4XN__}z)uX9Ts#Xg#TK=yfoZ|vAH1gua! z_^5NhGwV^|*#mcelJ#Z_O?3`9h=_tjWScqPGxuG2*imgD+y`%70Q9ljC0JZQ|1 z?P0nUHkA>XVknMca&KN!=%VGZpb=hZ3m%T+B@M;Y?O0_s)a)^CL0O@kv^!#2S~n#T zKx%LvbT0WS+#DwROb?YHKnpsTq#hXE$=z$x_j8CGp#WGYz`iqt9daeLmw%cz%y(Du zt%1)`Sax-G8hg;{Y&Zi$NgDh9l0+b$%ZOWn&f9d-rS?kD1MJb(-o9<4#g#lrwI^{r zGRLK*@$#*7U9uQs_Kss3lU4f<>%NeW&=^(=fA4zJ*DLMOcWeF7_^W1ylZv-2g1Q_y zIk9l!;wqfm*q~|}G)}u^O6JCG96Jk_L2J$>T|l12@+@{YWV{{{&_c8`UCjAZ>sl(i z;e~l$LHuJj2a|PC>aEbI)yfmW=Y<)98OSO~p}e_1^n1l`n^I{AtwKIhBLb&!b=w8d z8YHPaTuyvtnWqRihM>e6xP2fo@N&%r`%uCn+&qPy`C7kHrLBLJHJkN<7(`xP_wGT~ zG}9?nk;tE^)~hn64*$zEK8hwOdZXU5V_`fb)}EfKuJ-QJDy)Ln^U7#Q>K2PU4%IPR z)oo@7IvyNX(@m`wIs~0n<=z*r=gq4w5mE4d*}2dgVa0Rrj{#BHC;wF``6{_00^|P< zq5nwL@-WCX=<9;jWEH0+a9bI6Cf(-4_2-2FiLJZw`-_j!8qVl}V29M2)f05+B$wYz z{^S?h$@5%R-Kao#FNmE@<3O=gHmBu84@FzuM$R5Tr)+H4sD!SjV0j7v?AO~pp%0x8 z?Ay}MY+K36b&$ABTnZjGbh)hU@jfdd{2r%ElsdQ6ye>lnzSm81v^X&#*Vh~>XiQBkGQvIygarSA%FCX(J zoL1Nj7?t$Q%cRKUFPhsCTP8UEku`qh+P3TZh`{_;E$u^NAN*herUmx6->7EpMb$bP zlrp%+KKoe_#$3cOO?Cr&Lk9StSN~iP|JMRJ#lFBwoY<&cID=fL18o{U7WGc2%}_9B znh+#uB}b4JkRD&_u1QDua9u1*I|tDMKiv&pG6I6YJE7jb!A&|Fd{_yZKPafISad}= z7DlNE(~~?%d?a11TvnQKHLa%>Fouo-Dk-9ypgb^IW#GaIno7Q$xc)Lm(vxt1H6_WW z0Q{O(y?4i9nGm-tNv*x;?)r4ju6y?(%cbEAKQ;HUk^x3*twRsvk`&?Vs@tgaX=QQT zrIR0q+ZYPMAZPgnl%3ZRuv5BFhMi~}wfIV&1@AO6W?&)-lE@Ro@AKJe%pS8Q!kJJ` zq9!m_!Y!t5)p%m#Ek9`Xkvztu_fLIe(a|RNZ--1mewnTbIS4%ZjyvH15rn|+NZN!E zypzSVzka~2l#2|x3T&6t6doT^rNbt_W94*Kgfc!^vAw7m2q#7L@zRlXXJilFq(VjW z&`xum)?IhQqpnYcYRjJa-gfzvE#iBa3`*r9bzFB^)PPTMBliq%Ru%~Lv>U>nzB_)5 z+Zzwf2SGQpQ(@~A0acO5L{Qyag%D(t%qP=By@Zj`_+RG7%*VBiEi660hvJ~YI@kc3 zjbM7x$FO9-B8g)uwu8t8A%W9K%xnS?!(^jSYwCgisAc|PHD}QT`bd%?iEUWd$ZDow zX=HmA4NXsv@pBPNmu^8gY3tkT_$m&I?0Ax;8ic>VIjh+G$cCXs6b;JTi;5s}J5?UC z1%yJE^Ss;iV-^5@?vc|*&m%3tOnG#eGBZCGyv9> zsHxcYKPg^oV+HHojv5>i{6AbYLGsz9=q6BvkAF+&o`4;}^OmzuIbYWP9DM2w>9S0W z!fR+ZM`;XkgxT+KkkQ35rJtmw9!VvY+BY4C}C6UeS$IZHrT+EYB@rIPSnKxzj*O4asI_OjF?;2ZneV6 zsAZ1lK&6?bIiS|niyg!t`tf@cXg{feYG$<6@PkgJe}H% zB5l^-9rQtom=dbBN8cdM62mfjYyW1R`^a2rHx{1n{)*>@oY1%7l*fkwLZyKQ(%;+@ zH{>w~8iMwL=de-JoQ3UU1Ab@tK#e5(%rlkLZI6umPNsM?fIKa15Mg<1vL*Jqg98JS zLFP7)at>{^y7~~BRJW|}!1-`tc@(Zbp1W2Cumd{}(yv<3$JB5`LEc!UF9{3Xo!W=Q zr?f_Nhm?(aAD{FAbzKe&$C(mFE578dUqo{?1@roSDqp{hT&$^J^^SwFpIIL~55?#Z zU$pW{vr@q_LvlPdE~hmZd>uI4dfd(w-7pm4ZAn$y*|=Wcvf`3dxi$yDvs6H6Uhs$) zYqCsK!D$e@D}&VBV+Qg~IA=RdDJFOhT)vV_JWnou7 zX(u32nbaWmUXa<6lm+4Tk%Ak<_NTCvMdGe=nSw)-iYOkTq7QU|Yad4kb7cLcu97uX zj&P>k-f9O?cDx_SM4aBZVx}3|Fg;EA$yd0*% z1`XnNZ z9?mImCKb~}5*W>qZ-k>fAhKn}*luGYjou=q&C@p_9%E=X5jic)Pkv=9SKTmS?l614 z>c3A9P3Ur>4-0CNVcU|}T>s6Ri}L{sg(P;WP9nZ(x8<f0!@(|$TMMLt_Y+y)aRH}C#4XzbM*6RWcYz(i1}iXNNC`n9dg zY>+SNNm5xwFA)cDH%Grjf)R2DetaFUuY?8&KK|fBp=hyhc6fyTvh_^l5u%Hp>|=+7 zfD`eotMQPIvwuU6nR&&U=IG)D)vd>cc{W_`5M+MW2T+PGNJ>;JzC7U}z+>0XeDLm5 zlF0{MG$CsJIm@ZprvuanElLcX;vqw#CHXuT`DK1IVU8Ri5byD}py68@!F@q|CooTl z$H!oyK{!ze4Gpy9c>iegaOd+{r5s~5@g-9?)`Zy=2n@W@NO*$Ae!95pSrOYd6C;OL zYnh_H%K}SYb0qz{DkBH#v(6%{!XaqkNGv%_)Q;)U>;=>iE%i|++TE@c+hV_|;Z-Pl zMm(*&>ECS4GHW>f^ezAnNmAMoN}W-RO7UE38h-0E*$PlK4jj1X8a(+>ks? zQK5w1IE2vCa0s$o=DR@m8GN^I?nKp}-2z_h`7}PqUReYh!g}kJK=>`%mlN~RS}P_F zDhBNxxdqz9iM}!t_u*LOV$1cN{*t6o9#FrTJH4InunaaAFULQR=sc>vDN`T3#y7tP zwkYtcK-N~OWob|_7x5MiKbWIuB(`Eab3qH$E_uG^)nWhjj27Qh`kRWtZ~k3Abw@l- zYQQ#L6VPY+_%(oXen8g75Vrm6CN40^zv3?MY%c&>-B99z1dYr>INh@0;s99K^b;f+ z`vnDlD}(T$jNf+L|9y(*q&;X+I0YJw<|Djc5e4vihTCA!1 zXo>rF2kHhA9A&xI$inUo&+vfmRKQ{j2ZH|QWSy7}KBL4G{1c)|GgZZTjBKrMRN2%u zEbIhHd<9*c{?ih*;9b$VS$%UW4P5H9jNOqu5hbl|s)qyoPZYPIH(OPdDIB_|7~9UOPqgkA~cY$E}_sHkWSfjb(|5+!s&7gb*&u)coh~i zayDTlph@B?u`~=XoF+OEr(V`k2j@uj04d|+FA{&7q;7Hqw2(jE8qkf`X2Y#GAX|Kd zfv(6KdWH>cTIEhZnv%@l(0HGh6f5nR%AkQc67H2po2suIKAl9i9>ZRoBdcM{KLMMN zLxFGdp}~otUed7|&uhhY>N;$hMcj*---$DAQwG4g^OY^=Y+(-Ugx3}@)Gc=smFe5m zqJ}cY_3Ei8_$=a@bjYAIgD}W;S_-s%;j!Z81zN&V>m~sF5?h5uo@RP%-Lu#Cc=(sI zKB%9A_Ad1wH+kXU4 zZB(iVbb3KO4@dBK4Tn`zzJ?J#e&4MeI0YK7s+`}V|74BO9B!f4%hXS(kUZ5Fv9P@H zPrbWz3Co+l(PsU#y`Y>`6FS}pQ<{&@y57XkT0{-n;(=eWB;jB$r=-|N0c87vN#e_$ z=8XMerUgcnBZ?4hg?tHPs(M$3fDAvF!5?J$E-Qhvn$_5NR2J>*z)`bX7>Y^aa_y5p zeNn)f!IC?p)r`mS6l%`4wxOvpkY(M=88j)1^vUqzciJCo@M**3O8qSzf+_dDV|7RM z5V4AQB~#^=Z*-COiRm2#$y7^0>wQkMYNzt-+X2c`{*EyiY})2Pfp?m*YuT7S2_lhI#Xf7cpbD zKP9l{%Mup(Hw{gTPc%*IY;wFyAQ^|$8zxwmsea)YUi8_iWl-2$Cq%zgsj}+}S+Hg0 z?w@*tFj?y}8{4dB2&v)MJ~CDo`WotSv*6~UvxAm-4od-@z;6JCC;20)C!*j|91Ph$ z_$o)(SAq@XLA6XvOK5T&G+ni&jH=MPd1u``rl=nhLt~A?bW?M#ey!VGmMi|HwdB+!(VUrvBCxg6rFR1 zpNsEdg^}sdeySIq@m2tEHt?L3+APKunZW9-#6@MzE@u&Xy(n5UOCUt<>L@LsKn%Be zNpQ*CqQi=6BQjp-vc*M>&#Du34C{Oc%hLJaxoei7ndY3ZE>AJwnDX)=0EQuzYhiUL zK|POOtF_VsGuELCV?N$jd*f19MSltNk#QZbmy20KV#Zd!ZZ^cR_%(`c-x{=S`JvP- z;43*Hq~f{)-e=?&UmszO9C{6Drar?jk$u_)eTjA^yB_V4G+!dQzwohsrVz8g{{<=i_Zn%^3W4uam{A zL9NR(NgNC++A7cu1Z`pADHJpg*f?`=jefIkJ{5_oiQ!vG%ec@<=5*zG(H$(&rU+pJ zhr%aa#K#)cY>e-e@I8@>NU=08rknW)l5uLb7z2LLy>QWFR3~oOuFrmO0#(X#cle z{PTGIU&rkc+WKCQI)iV&Ua^MEJh1CCGOp^j3@6a{P1ZtA# zhvToYzk^N_)sgKG68-D4h3-BPdVe)5V)c`z6;a}=ng_mL+eMB-3^Y}?gMU-HSUq=Q z=o3V(;KAPt7_YP$@Cvr}X~gB?n@QA)+i=nm{t)ct11L)eO&24AJ*w*|+V-zjPC_Gb z_UHUJ>@n!nDa8_$$N=lngX(BdJzN5INz=ii``_5*GL!JYZ-k)2FN>Uv+I5cKjrL`J z10KrPS_DhCWhIq$%iZ)KI5GJv;~RL_zKh07^4k{`{y$A_y*9Wy-*BLsjv$X#@$qe%xFYR$e8B2+PF1h`IR+`{IGmX$z?NV?2HhQEmtz4&C&_P9_{cQ-kRw0b*%kKQ z*u4JvmT>#jTFI0G6%_+C4#R|O2%Ezwra&=?HrQMvlfCSrJ;M>6BH>7Ja}qW-`zct| zw=0b1e~|wDt%GcCq>C!Jm3(fh$lI7KZ_ufn)h`{T5Q|UoiTm2ii_~;_?->$ z)Q30UDrN)A8BoqubQ0DmD-^3~u$LqKy$k(&ATWf70G0t9Z>UliWSF)5)ynqUI%>Yh z;Q2J2DKYhYMu^}yVbreK|HX@ciSsX>4s~@d23+gHzhgs{^U2g)B)gDmQdUbWbVNRW z>QK}KaClJQ`(%LyFpMN&20AJ&K?1aPg^Y~56UFY_6~W7(vfsuJUyD~CHjAF$@8#hC zi$s45SL-97HZY1NmXP}3oyA5-Y@QRCNv<}F; z=L;Y6EVu7i7-HU6=5%D?fL=xlP_qJ4Je4dCN+9b9p(CMf`bm3t(c$N4q9d;h6*#W{ z8A~Ic9?Izi8qFG70mnzXTUk^GJNa}9Jd1~;uA)EHAT3A1ok{+yZFmduz9LT}2j&r^ zwmSqlr`j$(h?D+iKH4m#xXbohHB+dzuej7DeR}Ty6mpIab+~N+&TiSY zY;D=LZJ+E~uGPu5ZQJH@Cu14QT#F~adw>7HK3`v->&x}r_wBqpp@y{6=5Bb-*)FQ> zh`qH30PiAo2I!{dJr?EZgjR5fAf(=8(oo=iQPv+fThs#4hfP6H3gF~cx%&CFCZam# zUp4)(AiJbDZ2Xf<7+V7x#eO2Lmpg2_J<_N@l`Z>mBJ;% z2T8&5aWh&Mvqkt@Yw>L^ep`W~L~$du;pI@04z$Uyjxa4RZ_?g}oLFrRO+B&{-S9f@ zEzznHV)i@-ye~I%it}9+-wQ*|50ji%b?2^n! zX20h2#Z{?spO-8e0V`Axg4%d^r>bmO~OW4>e*G@nGYk;b|snj>1yaU z>*4+B^+_c8T^qP&R374aB@$+ZpmPP!e(Riju?Oh425AB^(WRjL`uKt6KWL&GJL0m*GDjz3; zWOdzwUdE0hD%yqy*>hRe$ibS!*MjA);NP&ka@K(Am`xwLEf-Xw*8l~p;N^tS#|=ZV zx<_U1`2NkvPmbFAuLwd!QZtAXVSna6r(p6nuM)_*KygI6wA|E;E;Bo}Gjzk2*|Nrd zD3dmQJZ124&5aY*2_e4g@4|9>L~FjSogc%Z_)X(0IPP6%nF%84MhL({@jYk-ZEyn@ zu?$V+r{C1syMme1x(VYogvRUyjkUSyNL+PlJ8p;LSg6~z5^agGbGK)dEsojPI1S(U zwQqRKvyC!!$Hdyb5kKXA)!jDnu{1PNH{!go-bR0xuJU`xe`mAs3( zHo=PMwsm=2By&rQKFc%&_w`Bg%(x`79F<#-9>Q26y9fJUIrb{JM z3c~4~D-uF4hN=Z#NOA5>WK3J0{-Vry+|>di@TY!5Xec%Uljhi2K?&>5DHpDU`7yrQ ze7?3cbelqgh*3#l_OhPmy@lTE*U{7hMdhK9;TBjd!e|+A6(z-0!0UKS_FEUFkX+r& z>%n_V0&|0Fe8mv6%Oug=m`oDNzE;mVIr`iB=FUU=#*%2VWX^DL1T!@i@x-bNTdVM;xX%uqcieG%rq#g7mFiLXENt*Tmi>mq z7-nNuDTgcR8L(yaPXGRB>&rv9EVO3?8^e+DMVK;MqI)>UUA@9h^GPjC=GQB}tbzhTBoCj{4cUDNfC?S&)~Wsh6Ly;vZck z@7&6Uoe|lwwMmm)SNhdOVn8>JGPxuY7Q!sHyXNOVwrk$~x1YrFpmMr{>xK?#0m98f zV`tlU=cVOS%?~LzrZvbRZfg=&!CB1=db0ut9Pj-<-Y+Q7BV}e?2J`dd6f?zKbo#5w zdOb%e%n>Ksp;B3Ko)tQKh6K}&>6-jU4)`xUe^-LR?uQxc;G;hB9r60`Hjbuky5?H* zrRZAD3d4jyk~+s2p!+W3o?@Mv{G;3Ng^msi7w^~$+afyz_tqDkA9-;0Ubc1XUm{UCp(;@~vRUWdk%diIa(yrO;i`_LKY*;Hc2siToU zTCAg}8n1W(R>bnR9#W~P_j@btTFlY%w4>1RbK1VED~Mc|IoBU+FsKlL)=T+(fkFh{ zhYw349d&VIxqFLpa5Ft?8OlQ-xEdFT#4ni`lkZOBh&e$N@z^1QeJA1}{(x5do z0)qi2cJ0!wpGxs7%Y+8X@QBpv5wqgPTMoSqq{NN+GXv#Ay3@e8h82{B37H}XLK+Z- zHNTwrGs#K<<~LvKO%#{0b`-H0$->2C+V`UQ!c75A*LBLRia#ru{Z47DMVRo*W%4Jp zbMA_K)ueXU!pgiz^`iC(UK|&8o))t~PPt`20uIN&rDDmy4W|O8oXmqErr}Ny(2yK~ zmZoUa!5{fWLBlx@HyA7x6Rg?4Za(eTbwuh%{lN{u1Oa{;C>ae<@pzHmzH-`6vyO=5 zG|rYNE)m{_UoRzfZHRz}qNRGp`LpiztrX@Z+M$w!t)wyn3wIU@A_QV%@ewNvEneY)#fx|T5Bm%V;QAIgc3Kto? zIA71j--_z@vw8($rmz;1W$hA{7-@{WHT4ACkhR3CEaR_)RqJ1LNs?3{-G(~SQu%L@ zec7g#7TFS7Mxao)muB2nXt<8Rr%9c5=}VL+Uv&c)CdU6<*#EGuDnz-^TK$8v360pk zM4%$ty~kcUVkzKfUP-pW$i}i$6zJ!=|M7YYuMfNEVajZsHwSx|%O6T@XNi z_qF1?#0$fc-_nw*>!4rU8EkTsW?E~I%_kX56_~XQK+0SP7~3pcavSgQ07h1FjqHH^ z0Gm6H6<~-fP1)LOt4fvmSe)GdIbmuE`Wx{7@#0^H_5Q`*QZb_Yco2Kjjn+*E!)G?k zi=bu3wqSqb)mKhYykwdKUHz&Ms(c8;dPlf2Lozfa)L2G3Fwiaxd|13tr~d{UM8CWW zmek64m5Qepyp9q0LQ_mO8%g7^OYSOHvcJFijz?6^q>M9X=fV>R=W*cFEb@ocU%D(+ z^T^j6tM6a*Agt`OQ{~#E4<9*J58Djh#ev-5E#rjc9*iR9hnEt02k<=Ct$|*}4dLJhJ+1Es?KrY`;kI-OMDE z@%fA4_qzhb49*9rkSWcY)V|hK9^LGc;R9P7gvXl&4m`e~QSc-_+I5jU zHksnLZO(huhHr+iEAWz!8cc}dD}71HtAcmk6-*ACkJ1!N%B~j+zK+=sb&iG<5Nf%r zrFtna#5Ok+z7V}=zI*m=(E4rr=30o3H{@~!`=amm@aQibuQ}ad3Gz*&KBO^9>4v?Q z{K;!f4##DQdAFoqG4D4)LRD^CpJCu~4Up?);&BLZ2&$;6Bh_Y0^>z=9_c1-y#_hds zr*+6P0z;6JY%u0xxnwPj^73g*PC?l~9zhJ-DOzXU-BL?1UX8(${B5<4mq;;8UTne~ z;`ndOi|aJlLT9@rf^h)=U9CjMLU~;3RhRfY3;po=LX${tCp^9;+Qc{;536XrSUmx` zQCWg_i*GJUZkWLomQu;7+2cRmrAZpiPt}l9<>>bX1J;{vnaZ^bs|kza8w$oeDi3Rg#xPkf<5@(l#d zp^B>~RPaEF)fSeN(VRviB$e!{Yp_5aW6R_|_wA`P)LEv`e)JKw5D~7vsM86upA*Ng z@!!uyjHvp$;Cz8G?Jv_h-f}--fGo!JZX_+YE@^skR25KD??U7>l-?lw@8-q7#Q7Ju zxWKD^0~}R}FZOi^;!9Vhlwd1&U@tV+Bw|$hR&WtQ*o}^Sm}k}wVl=l|3x24%F;5#l z5V`^CtMS>O;Ww2aTPuab5ch83rr<3wa&Gz8TJB}y=c3GLCOAkx z?J$C;g?T4L8v;El6B;WJ1Np0i6=K}DSh{tMDO5k?7iq!;&p+6LG<#i; zhAy8s^&qMWL>kE}*4GxQ$epk$a8F>9<8TmxqlWQHFF*HMD=8~%q?p7uD>j-R$;nDY zxb}iPipmAmH6G8njivXNVp?b_jYRX?o9Dha9=hB_ka`7)Axpe)-ngd&U>gPBrkNtl z`gk&-e2%=7gXRN3#f;^8^1TzDklBX6r#*9Q4;`N|bHhyal<6QTDxa8H!T!ZwO(u&X zQEG8n<=sz`6SWnAG|4j_9RaSI4ZXY%NqfxL;icO3zMb*6ZXtIz&?qm9Vb9!43A`$q z96NXq6C(?7Q@0M#%EO=8>&SowFw&al-!s`cvwOX`hJ}8262G~nsw$51r*mg2S*Asd zU=Uyi;*0#svRr=TVVAu-!5F}8|AUN6(VK=Eu||^3yHF>;7qG#an$Rv96uJ zYLjcz8NOE_gk2?6u-swNNMXuDlZB$Ary?M^b#Toh_~ewvoG^^mAj2)xt4?_lgm(}q z@+aAKh(}^DnM)4_o=jAaO>j-Tb0YGS53KCdr}b}8?Y}^(KZDvzWWxpv@9!6^ch?0c ze&ixImYISiNxn}IOm*W#XN!iV-h~Byd?XT~ea1C}y~ zB@^MFyST1(DE_W4C|6xYkkvYErKsut$&)s;de;bzhIS~3MeA@XV}qk&@I7%ycC3Vx z2OPVLf-cztPRGlJJ_rPi6R(YUGZ`XZlwLz&dJPmYNf#(nZr3R%h|P`bnTz18__!EL zSV}{%IbR{=fd5|``Ik8V;@6MhfPu}j7^=`8WCH_UiE`5Lw+6#_n|A&S?{U;Ua6tJo zWh81t=u;AgVqW38iufG=Z~CaGX!hJBpHFmlxXM1T;CeP zRCo-RLo!S5$G@wk(_~c*;8@;|{t{7vsL9(SEFlfu^#|XW<0VgZ(wx)>kn>3+(ov?d zx{=}QpHJJqmDmnE?x>$-XW@x91^cf}ugv*b6ji%?v$Nii@)%i_GQYo-67%l7s!uDwIySeHyF} zIF|zC^TiQm(2cihrgNKJSld?bi!aj^t`BFQrq0;2ELGMpiH60@qEdEQ$jveN=TsWH z;OUPY2M1|HT9YyHAOwG}$M(p*Z#ocm^KWg?6*6Z>R~CJzi>!EAtZ@`+0k}9I-_XWk z6AJZ@z_?pOaj*Da5kBMEye(yrm8^e$6{zGbMpNs|wV(v~|50#dXyF=k+MZ zW-&t!X!`45Dcri(F|^D#+or}x3%{9&er1h6>fpZKcR3CsHB9M5Tx#R zaivKLMdtl&KNfEzmc|BrLg%wwyqC@p- zsbIk4dMOD}SD!3SresE|8`WQCkY%gu>nn7V63TnW_%>#& zvCIf`U0!`zO?a}U!B~;n;@q2-=}VX8i0+)_?AHN@){|A}>Og7pg4VKj&w~E6`#w9Q z=W64BD0x5LvOa@bO(1b}855oAeFw`7w!NWTfI9o%FP+vmPKs7WPH++kvQ$5~h&V~r zlQ2?;mNFw!IQ2=jnF-7pEXAE4|KKWtr-ZJ}c8FL<)zfnK(a>}do1!VcDLe1KXB-*U zhPC^BG2@jusCWu@=22gCdbenjdFtg%p#v2yCQ*x;;2RTA80( z?)@3gRXaQ%o0Ij?88@nKUX1|VK-Hj+7n-kxFXL$f)`d<17uw==A(z4h}N4#kIzsE3v;s?346F}9ceYQNRu9cQ0ge=WeIzDmT!qN zv8k!xGuPZno3Y5QLuAQ&&$K2yb@q)ZPt;Ya_Xk48=^)!7g)mwnq|3;4j2nTtK%8HFHalInlQ4x<$XS5-2Zz~A#S?zclx0eHBXq}M&Cs};QQ>& zDbbZ&DKCDZGmM*{-N53Q?P(*ZK2|Pdx~)JWx5&8r;9x+7vyGs~#p=I!@h@@y#T!7l zfE|GQgpgEkGznFkWi!F*EnTAkf0d$fcrE6h6_5=2i8};Vgr5%0pZn(fUGo-#F=sj@ zEtheEJ&amNA*yIDcT$DPBWxd)wiY%CBNx8U)cDz-E%UcdK=grSw8Cn)u2rHU;=k%Qp%YY9ieYyx;Y!CHSqi3t<5irfQ z$P>(hcQqp{yr{tlZ3pYAcWhOpq{j7fop~{7Xi1FM)-HC)H->x6Mi|Z00;ygc!X3Q74H8D;3wJV%--Sd64wZFMXY+Bm51u`wZb3^m z@(&NdeD`?K45OlF-{a`powk(bX&Oj*@$iakZaJo+VOe8#-uw}BkK_Rtrf^@(gHvmp zXF)`YWi;V#6^A2Mtlc_eTRpFguK@ZAbN$QG5>qnrMtUh)7?l)hcugRX%J9BkW@fgHX@}UT_Pea(xr5YgycIL z?)!P}=bZPP^Z9)~=l$>5y7!*zx@OkQtXb>3VrCPst*L~IMUDl5KyX!*p}G(VvL*zA zG=YHz?x=nrUj|=8cE&39Dk^Lc3~&KzBB4T%KuHrB6#ptufE&n2C=e8IKL)%BK^aj8 z@g_&Qb^ZMqlqvoyr-3rdUv&T(2rm*c1Q&egfHxl~6NB$^@OFy5>8k~l5igAEf6AbQ zp#1l@l8S~lEgu&z4;Q}>XwSpPFUHF&#w$q6D=H?)BPPHLY9qb+_lOXbCO8;&CFjrJBBFbjfvC3Z(?j(S}s& zTo;d+a8(i#3l~g0_H3#*7M9*rL{`vZgoeLw6k%;tj=xgF;drIzO&@m;%FDvv|04A@gIID^(8)<4>Eiv|!3$Bev7BzmOJz!% z7$+ikf5)bQ>;GfM;^qzm;H|Yj}z7(iM>$8`LtUx?h!45RShdr znl#}8KF>cQ;o(KZBimK^`TMyCxnJcu9UY^*t@CPih8AZ48T5D3H-;H&sEgUSyK-6C zx?9_E`MY``77QXG?eAe_^Uw}PYi;M?triQXC$b>qv0WM=jfyy=w+uD zsHtxg_|QhwmQGpc9pDDD^5=B(rbm#tp#in?w()ZEfH}Fl(IRMCS-bndBd#K z1SwlU%8Fk|&`Q{jhf~m=j|YrK2oSXr5abjTwY9aj;pev!<+r{jWosj*=IBVzSyQl5~7rJpaCSSvLvw~W|>;Tb!;jsSSILyw&E5>s(d;~cScUvd>fd8-B2<4%b z0QJF=D?53E{sXRW-Ds4ao#)Nf&83UewJOolUMq!|mCel*ysdogY_G=&Xx%)rakO%C zumkAvm$?3Y-|2rR3WA~{HnxaWuJ8|#0qt(?0q_D?$o(%c{EKG@*!e&B`fDxz5B2~^|F@I>5r6;7uK%*@f5d_R zQRV+i*MHgdKjOgusPccM>;E@)Vf{OtvU3AokRJ$^Ue|=wf_60RmPc~pQo0eKOKni z6nfa?m1d?nnZ9i@TI`}r>YhrBL5PY^zyMi#LGhwycjq|tSMT)bs3iXjY!pKNgNsrO zt5g4`)qwe);8oGkl=rapcc{0)t5Vg9hyZ-^iXg83-#>3h5+N%6<8xSpII)*3Cl0)X zi2iZ^pLPB><^ShyT+QoUm(it9kn%!~CUGUhU@+oAi31#|^F4W?6}IBy;=M2YgA2KS zb01iHrTum&^8!}xntk+tnxp}R;%Gh;6cvqk$O}L#(abeDtS-{UjFv-MUbcCn>sEHG z357z1GkTaDCq_pj-9t7_l^F;LCoWr<6pgD=e?io#rK+bLs|o-(P@IiM@zH{_1W%asxQEsc6ua_XKHqiE!duW zEOlW%PD(1!Et65Dy;HMyvaI!n9W_ttg4!bFQ1Ehi?q%h#_RK2&Rs5nsP* zo_}+{Fr40uv5H%L8AhGKZK)_h-HC!P5iY)SqC0H^rm^2c;r<{n5UbH`;nUMj|E=mO z*@?py8>!PZ`W%S>!oxt^v!m_K_Q=>1OlCSdw352dKgIS>mM!H!nDvzD?Jf@GN0L!e zy3D=QEXfX=Zw-@HA4P?HJf8b?5TDRZcezm&iqY%&)_q>8YZ=q5CHSuN#ky9$6S-T{ zcKxQ*V7)8M&rjH0Jm`o6G36g#qBEYoo@UK~xK+(Z5D z;d65qTXW46S;d{l7xlaDl5-))RKJgp7r$2*iiDgBT<+6c-EKW=YE3lbYFM!e{?*5P zGC3HE*8gs3em=$c3oVSEa8+1B3hor`cZ)E>AkV zjJ8@6@!j&(uOJCNSyaN1kGH)1X^95G!N*_jCbfhzrS|0dh2G`o9~B9^q?BHSLc11f z4cB4he)A#tOw7!l8)HFhyEJXHe)Bb3Ht1+*Al@9p5$q3G%}sslimoMjs9zIXW>~Sf z-7w!1fr1V{llq!>K?a$kJ~*0Y9-5s^+6}up(>5T{RXyK}mF{ZV&FiSPX{h?soY8Oh z28GFG3WVP5A>4Vy^911K5m*j^k+$z+6RGH1Z@j`yt;If`1OfC zuG`xG>SAkSjdadr?QB;iCU&(fV z0JLA0U}orea$;iQJV+>8K}iX{xTIvl=P?jtNLxi!%cB(OOR^%}^~RLh8V9ZEO(dB* z6W2K*LBaUT%TThIh`{D#@V~tsDJmZ-_0nC!p1jHLSWun_vNhfCl9coIZC5r;JWKRx zc*Dg5i#|2(=BNydz_LGw!mWQ`-p?(HbdezEOQg(uiIzFWzsv>?(s8Z(^JFwS{aOyV z_r967ww39Xc>MYy&ZB|Sn=&7vL=!?>UJgGyGdrJ3x63!IsN5twp7F--;AzX`ci5|W zd4U5Nnx2mAr3s_FxIl4D5ybKCJ1|v~)n_A7*U(tjy8NM)j#~oJu9}!awuG5QB8JE- zQkhWzrFv-PZzIW@P9k5XACu-au6qjwWyX))SRTooL?FSM7UKYP(@*_0jSs%kr^YNSp=HqxMAte2xWwo<^NvQSe z65ZqK0{?-V+Z`YWA_2b`@`83m&o6hcGB&Yb>2~b`8o?KvT3jEh8X6h`+$eijn6u*I z+}w)4W6u8w<{myd>B6OQc<=xMK)e%Q+W4?qDTTUoqUA^=FK~m^I6b;yKD6mB4`Dni zK*^q-o~Hx$)qcBk^;bftb3W$1mltRId!6`55Ul9)n3h57>Y?+qFJEx5qOHBH-BQz{pmbzpkTwf30c!iR`YinX+}vC;nwO5^ zN2;BX0QxDa=>u~(`a2dDXt^v~9=D$Nw?d7KNF@e4_m_LC!@>mci|hCrTqp8boDb?z z(2wXdHoHQOXJfHRxfXtAShja3W(_fiMp3`!nTUTzIu;sA)2*F zwkaG+3Qr(HKsBSS$N+XoL_u~MH{mN6LB~6t(b%MW!eIv!$_xd^u4H10ii&$cGZq$O zY1%2=KSpF`-tAiEg&+evXJcdY>E}CTrc}U*<9V98Gw;C*$)oM*6gXV-Boxxgvj=#K z5;r%$x5smNT6IN^j!zA(GwB{1BmN7lZqJ|e==mRx8-Y>9^!2F#{gDj1lYZRrP1z*a zl_uj#tXOUbLKjV0qXB>+%P!aeOvrqkSn@KId{F9)!Xqfdg2(yu4ho!K0RlLueuJ z6gtj!U-s#_r8{o84D}LbH|38e#X}-Ni6w37<4EOO1zU5PqBjQzFZ8gI{eeUYH&=pXGPawD?mOdJ7`DF3@PpZ*-N=FJVPq zf00~6#Ava8-DzzWbIPH$Exad&7BS|6amp=CIUUqrf*DD&2zJ42d^^e;BWG1U@(c7< z9%m(sm2)`689vx^L-aYB2`p=t z*474iY`h|_Gn!=O{1okd`*#t(=#4`P2HukUwzmqdSTeb+O?5-&%ZLFaeEXIQ&NYiE zsxO*yILvP`JZQRRDHtuudIAJ>A^LjVa5RM%Be5si`}JUtTh)kGjkqO+BpI=YY#PFdl%wYCg37fPrscf|$K{I> z&EixSs_weL>DlT2(qP!vn)iyVYMo{IqROm`x2}1*SyvR8!)0-f)B1Zz9)da-vdW+78f_e2+UC*?f5-Ltgp~+wA+lI!DZf2S78)zXX4Wc z30W3$K1T8wSQ^*1^bOC(?fPk+jF(As@5`4eESpL9{U1AcCcz9M^2@%b*6`?6Ptsn~ z{K*!(`YzYiaz6BoN*MMrS3n;f({@=5W+3zK8PK@lM%PL)P5MqUs=N0E#u)a8f0O2kG|J5qZC_kVp* zQO~%4l>ij4xqeLBoGr5>RqL`wLvlrvygcZaF?W?e&>@PqKaXbOdY2_03bPQ6>Kr2r zfv9X)jMe2)ZVA7YM=~PdiX1(~{QCSF6qpz7lXqI;;-u#v?p!A`< zR|^>oCX%R9QI90*+4v0>I2tsK-bwH|x&hPSskfasy?-m_cY5GhpCF@pzEH{TLU28` z#ump%=XC{1i<4~Gk#TWrVzpE>cTp#nR|&;pR?9KuJX!#QhOxdcL$%Y^_&!aL0skk? zu%H@~1<;~ATY!HJ%#v8wFt0wW8@v*&07MJ*gFiONtFkLTClyI5PBTwoDeo#nihLSCf z2w+_Ife8BM^#Dp)Nk)+%lB`6IiK;jtss@WU zrf7r;i9nfEfiY{CWpNd*oIt|+M@fVbd4ouzfz7yef&`fwzDU%B`rddD_kbp~Io$ZL z1$aA0IExHP`CM=e;BEmLyqq4=wtF#R0g+)UrcY~g8IMRqpzS-}9Dty;HPyZGaJ4u` zbMt}2zvQOYSlx)0k;lOIfioK|>MBCE1zkSmHR%FNor5}*c z#H_WWWV(;O^MD55ttB;|tCC#1ZqFa52YKQ+jbbXuvM|cA=09YkU1d*1Fg+bh6C@0J zq|eusl#6tSe5il}))=UbXD#*`wLA&=g|5eoWT5?X>Ez{!y-O!w-7lF=Pfwqy zGkG4*`Yk6fTY@3L2%oe)5JE$WC?|TW0{CBV;z3S9)7cLK5o3v%ygX_U7<@b#84S21 z{IpDv3lr%@;P2z`RD=jaT&nXM*UOwFj=tOQ;Lx-2F))VyN`1M<;YO#X2g2^$MP~)T zbWVz#OZCx6}ki|XNu9bi6JfiMEi$_mQhQ6gpOm!1Q2W zBqJ_MMY^YsO&7pDUCjK5iR42qzJi$51COZ&KN_wa=@fLDK#YV1p&;S@_8nAbH~mKo zGJb@5cG*cl$)h-h^c~31TJ{G@?vZ6lSyEO2eL;SEOZblgNlbBeCB551^5vHf-0S;O zS?%#|EwOmMf>)t$#UmCc$tj}a;xJ4-3=p{RucVW!U1PaN)inw-n+Gtv1n^r`|2OArnRJV0YEAi-3|!0J|K*plVc zGqacD)p$xW7f9Mp8jUxAvpHS{>w`^N4`u1 z`~on>B*jCIBVnMmN4@!CCK*a8FnTvfL~|!Kykd8< zwlqRs{v&qIlSSK-p5Ms7tYBu(ih`(Dkh{<>Z+?;#gtoWP4qtKg5jHy@@9yU}_;}JM zD8vBtNfZF}CKE*BZL4?R_QRJy89be`B!Pg{9s;xArmSwXh$ic8kUL$vUi;m$g&%nu zUx>Ko8hjm1zdx_$(eunE={(@fh73}0k9h_<;-z*wUXH5whx*+J>9T%qPkEyqlbCr< zIqef{Np&j>Wla6|lGxXVnCg)@eC9216CST_mWoN?Xhe|K;+S4jp>sVb=w6?C zd>(%p|E_;6pyHx@NY2Y_eB-6)_okcAZQ z53S9C=5S&pJw1?8FBft%egCHCm*Cc}ro0Yu+@EPi0@YV5Xf84!=F+X7NoQxClZvpe z#*m@IkednG4Ov^?u{b!89E^5)A#otw-kwLyVXn}!Q&2_!&DWC4YH7Q_M#qg1!Y&Jp zS>&jO@6pzMkbPW^INL=hIHYdg>o_<$Y6$h&Mz@L`El!BpK&|cZ&xNy<3I{&3XT#$# zkA`#omJw_)w*paH0jHxH?szm`6r9^uQsK61r`+#9dL&@r1QX+%t7GX;1oS+g)Wf25 zg&LfIqD-;X>!*wkPbV*>YDu-9e8*H)W|3ZuG=H{2;;|$0IAQ?4Y$&)80^(S`53R<*ayZ_E(vt6*mRnTIdF+? zQGCZvbERo4m(jZ=qNoamPA@sk83xw8G=CpXyXUz+qVO?fiS%S7qa}*pL2Bv#IdYj? z+n52vmm+zeKUvu3L_@?8f99GWDxj^8#u&IH_67=jH#TR8oHspiS2&d1Bt3h8+ zr?o0&w^aS`9uH{rcWQkF86yzf1mz<@bG=wJc#TIhM+C{hz;k-o<|I-23L6H4?Qw** zpYrp*XhcS$b#i)d@&+Z2=}~sp6k$188Zev>r**x7_utjf+N>S8fXKD`qq!pmi7$)H zd|xn`%!Wr;90PwnSuY4=AAtEbhUMKaLRVa-)_VCnRy-8$L2ou=!4zJ=Uv0dl zL;||W$?*u9tt!Lu_*35s4e+K;BBHhxZt)b^@&aEMC^r>c*tKBg6yr5?;Bff4%j8_K z9i8;*Z(uAUNAGmf%n4_ZM#bIbw8MH0oy7$R{j9kD?FH6N=dkFk*h`n%Nq420aGIzW zEZ^fO*aAoI{4z*Mx=~#3!{SQEQn*f`Q;VK^i?9FY4^K@*v=5LP0O8y8$#Wwk65~d! z3H(XrYehkY7)&eq_5aw5Fw@U^MPF>=#}xCSyi@VI&D4iy#c0A$UQ{;5WpCSc2t;R4 zTmz>dqdG}4jrBWyr5WvvFm0PbO9hORiODLsi}w<6f`K)wXMWIxba^yJwlkIL+El`A zQ*Y*v%xm7QZny4XUcIx3Z`l|goU{ng+Kp2@xSxb;bIPS@ugC@^d71lYZXP_Bbj%+@o{VE9rq4E(m^!^~DE(2oRX;Z*ktofS>L0rB+}K6DS_+OSRS{b!3oa`yj%U_IQl8V9_`` zv>)WcKOfEn0#^n!f1HN0w`KNK4pHhGU6bjIYIXyKhWie|B@*sG;S)CJ;M4 z`2b)dan-IFc451W#-w)i?zj*4O$D|sMn*LMb=UQU>gt`p3*<5cg=K``HZXWS+{VD1 zMi#>#39)wv1Ve~eSRjqGGS52_f+=r)TusRhCHq`j%5)>&WE31rKVqNVco{IY3s|v6 z4ZF?a2(0L$M?o*!Ldp-f%JPN90k7Jds~dr*a!LrVc^|6`K}Jp>*prV>=~X*%DgW3* zull3n?>e|XOd5|lvrsL{&xQ<;%nh_1iQCWpKfd3nR`u2Y_TZgMjn(z&ePd|T$Ud2< zDe6{zF*FL!qfxX8o+-a(l%uI?7I_rGz#QEx-fk7uFB!zGd_=d3>u}mx6WS)EwL9nlH^b1+Of8P*4+(ou2~dJGnvuL{JF*E+#V5KaN&=K^_HB^{LwK0{I0! zBOaYnd5nl@-=e9&XLB@t%VB@|J`|DGLi82d>{XC&7Q^1E)XmC5w`HS1+6D>YYynY# zG&^C}H@rp9T}FSwHBIK6c`RV+;r?nL^1R&?af$05%+Cqozk&;LtP0*2IK2JL_@~kGqcl&FLZf3^% zWO@b=dBE&kexPND>fMWZ#7t_w{9DS<#ojTJ$19uKs1F>mP>0M^NLAzMn{<_XVL6#` z2{zwm5VK2%*P`>@;E*QTJI|cfJI^UFItYsMk@&JuxrmW842H6+Jv`YqJhMJcSUF?8 z^F(>62_3ANg*d6j=CfkR^(is}e z-^uw2;dW7!!czF(X92KH1QoY@iz*p!@hI7E4(a0!5Z)ff!_w^Rls|c1@-oILYk)fX z<@rgkMB=paiq#9;Ua2ExG-I|hE6Ybu!_&%l%@L|8n9BVNg&af{ZY@&~P( zqxN&hHM}QkF)L97j^@U_3V>McU4*xi*Dk4CGRkr%@vSRq8I0UA?3YSjw<|3X|H7%2 z&DW{mf~3n78F@S>9__vQb)Ulx#lG-JchmN&-9=#Qjyo!oh7LqopHh0m z)g(U$>i4dkCatE`(G|`a+=Pu+klzUe0mw6n{D(o!(WD zMncj}*+21M{% z=n`%l^yHb0k~(k)IYceO)$~Yy5GtyD8u2Wvt}^dFyhkBM)xB3h6b8W84F=49F+p4cNPFbcyYbe|O^QPg~ z7S0u=(mQRXEYUuk!laO_nB2UPS3a6X6}Xm1-__M4(+CZiA9MnY0>QDgq|?JbS5`Im zv%nTUe?PYJZ2{?8zdA>HqR|XVH~nK3Iw!Atz^_8sj(k=uVg-)r1A$#_Ei8gz0;;z| z%eDTcUtL^&Z{E7sp)DszYhTJDo}oE1XuZ40 zK{|=7qB1!&X4R8tVRTNW*>+%NTmk_p6X0tHHFKjKbh@T~fD5JFgOR+b7O&z0r zFnUw!3yw(uTZA%PR&J-|jWVic?2{4!*M5oR)EeY=Xz1Lw_V zj-T&})QMuSdhsE*6-wu7Z%tz_2pcYlhQ@s;Z`!);z=l`M{*`nDkKSAG%ea{Z*h9e4 zY#{%N*E$aJbjjPARhyz0RMkBv7H5BEp2y#_^eKdw^q3deQSL3r(;;GcPNL3m2d$K4 zB^vcN_ue68OCq0~D-oUefBcjPQj6{Jj&@gvsY(U3wRwr}dGAZO)mCLq1F3=z_tZU0 zlApz7;KX&Sfg$Y`;`c0~ExzmhGGV4q+4|@EW~S?JRgH9E_ecKY`}<4G6WRyHhrnlP zk6&ZD&)3BaF~BfmpL)WFWhhH~kCDgXO`-nrJ)|#Oc(?ye0u}@456z#JsIRa4e5$uJ?pztmh6#TTvNS;q??(gyd6bU?j=^WG0O>M%bc|WG%jj*ZBc7AbwpHqe=9U3tVHe4W*Q$nO)V0GL`ddhu9ZKM zn~mIz6$z?~6G!JenXr_8e36U!Jv3Y!zFsu_J~R$r5t}Tx!tF$yPmqLFt=A53;)ZL* ze+>MyMnXl|={D?;A!SerS;XUbH9a{7%Hh7N}8lLl7c#9la#9JcQeLmtpl z$mj1Y{({||RUvZnMme)cJo=!mi%fuQB>X-$moBZx>K1#_&8VcR)sfU8YZ}>aVRZq6 z=gTXrJU%7r`cyQjKabcJsd!P6X=u&tl80@F-EgirC9a&SljqW+)$}%L?6X+F-TvD3iWU3#(68&s+uD^qi#OFHJ6rykma`eIQeVf2 zPZl?d(8_myRjh+-1d2K4$CLFRjV&3C6fzUU824VWAt%%PLM6Hu6>52dSFFe%qN)Wb zxerdj+Jd76!1c49?cFnTRe5sfq4GDmxSlZV26Il)?-S44E_Z%3u8JzKBNguUj_9Yk z-f3q*q=*_Z)B8m&?{2m2O8dT@-2B~qcD$f=k-2j5Au6JLQy%g?Tdh{Ip>u>s!qogw zA)0{Y8!7TvvvFCY&t3GfO}u)Z9!tNrvRY%G22N$B^vSw}dWZ7q%>kxo6xCBRQ4g{FmnB+rvPzw)p; zm60MO>8btZe_mdBv@{vUqLm8MBl@%Li+|b#>eXW-oN=U3v zfQzRGrI$eBHz4Jecf$4rG>6SuqX_pNZB{+Qrl@KdhJZ*J1d+n#z#*Us-X3~)JfIcp z6-iK-WL0|{a{viXSeDfZm;B)Gefca$OPgZh&%JXQIx2VE2*j2zVojsZPt7mZ%!<=w zEtTGg3XpzYYZX7`e*qWyG||jr+^6{78K$A}oXWTnS;PEvcxvKq@3?hH_c2{H!AHVk ztX>-`kgWm{JZH}l^83(mZhTv9@8BcntqQL}<(>alZ)eS)@%)#AOYizO^AkTZ!S8m?5)D-2mP zlkWO%hRZ8|3u4@e)}$i_K_>guqvMJENinzh1)M8L0!hZ8;E!%UW)YMHso6)tBCU8K zmXM^^q3Sv>LmFSx>2#sdbY+py> z=X``^xLVG&bLmiF8nTl|6KOxim&9BqVxyuqW4Al~q0ryaL*G%M>;%Z6v^qY>Tdpp2 z60Jz?lgUhho8^!GaQ>X3g?5a={aDr#9N}Z8E^oAZ=Vm$-yH)fei9W3mJQz=kL7CK1 zh5qigN+B9fV8HUhFD{mOm`0^df~05Q;Z&X=`GKsFkZHqB;HuR6Y)!+IozgY>alIMS zv*DSNEQ(h>qSs!PrH2FZu+Mrq@;y`wDdG62vi6bZ^=U-PnC1rAq@zFAv8;Oz6D`XV zWM;H^?|Y>;hY489ixqPx=we5xA+wB`<&j;>vZ!Gm?S;?J6< zq)%yL5+7-aYhWfD!r4KxDjM=6S%IkC&w(Q+m!)pvfr+A} zlFQ@}pPuKdhA)NA7Ws0omQIvkko)>|c?1*(%Fm}R$C3?Bcm^^I5~*L?{SVZVGtI$2 z?&w66?4(Wln)-b<`GeBHQZZQ7lg%>rl&_AloBtL=v6|3Gddyr}yqex~iqp`Kv`_+7 z{hV;-jB5|*fcHs~EC$l>TAe;Q#aR!oPxtEfPF!7dx^&nH=De%u{=ZbDUs;-bh(;~<3^T?_g@d1 zJIp|6r#9HOw-e~$6%|qqCDnvg;&uh>PH#?(Cx1E2Xx~G1D@7ZHO}6KvP)S5Uq2l*M z4A@90#r!eA>BxP5%1ju!oE0b2>7x$4k+wM({kOlA-Ldeg*UUx_bd&BiT8e$g^r;I8 zV}M}5m`{BU^m`jOn51+b}dRH1XmY&O4(tp?(S~pgBQ8zNAPvejc1lP-|l3|VV?hqw@TZfW>OP6 zICZXudbENq{a&Ljhb(!?p<`?I^3cUmqFnfE^xrpSIK@S|+C>Fix* zYK2wwGvcst9_E8|4e@3_{aR0BiEgkTbs@0`Q)SMM6*RawtTiwhdt_l^xOYn^XlN|;NI2c zD9L%YgLGs5QZ~YxzpUwu#Vf3;!tb-iI-c|6);H*u$Cvt2qdYwqyjxn#A>CW1f2>_A ziJElArD3$!7NPkf>(Mi+TP5Wbbj1}s0=F>b2M*xaKWlF3$Q0ym zqhu~10y#y}lWdSf`l=~$vLJslZh0}TAwoV}sb*9#5G81LS=cx<4RdBmS(VO$Kpw9= zgrLUQgFomnjs28IuvD(i38!j&2BM-Diwt&Cz9+`aGW83=zkJ)fI6I;v8uh5OE!;rU zCIPz}ibS6;4lmyQI;b()pEZQOl9YMUS=uRh0$bQd$=5La&dXyTK;t>RCftHl(saH!v)b#fda zHFIAd$e$EjDW92(M#K$k-Xr9Ocra$(Sz}3I2~&mc8;7i@lP zxP{BWgCAf%@UM@_gX!n+lZ^6Mlq!`~@U}Y_9)4ae&*s-Zo>R_aKSOv!iCtc(u!_yy zxJ3%TEoVc9jHIhux^!tWA9z0wC}l)sHk;5og)q}bsKZ(mYv*xsv%GxeSejkJli7IOc`fzJV1wF zm^1-o%}v))*u%TWF^Vg=%%o+EMxbPh@;1CSR)Z3gC-iC9&p#D@(8fkT{o#B!a?<#K z231c_r!)vd9<0==Q-aL+{UFgt-x@@lzvh+yB;J&g%H}wrqXik%!PKsvRcC@(whcE( zEAPBR{Ss}OjF1~`8X>>RKG6k-6W)36JS?t@NkMhbd)p3ru2A0N#D7iEZz|kEv(->57A~dj_ zK+DL-8zR43V|-k|_A@I%Zo9|u+kinKH9IRKTm4{SI1nr;Zr%Dz)Wt22sYf&>j8oR# z_zb>+x_Uz)+&0?WrO{uj7qM9I2L>fhwRawA4OdamFsR8yONNoO)ixDw#gjo4= zQ;q7p3Gz56nDqbs@o|yxL%GWJj5KXI2*Jdp@<}g^*1}BPAzpJl<6#LR26Lmkhf4fh zugMWR%rQF7@N+y1nZ|QU)O%0(d`=>u-Izn!@5tL#qDhtCheCXY`9>loRlXRQpPzg& z`0Ze$Q#}v^JT3grdW&*(Gk180X=3nz{LIjkM2Z1ItV%`uP5<@LK0(}Et#p^)uhjua zJYYmG>JA2(ds6b9eQUiBE zoxrX27kKwjLoaqN8DA0zKfx%1HuCB-(|)t;kmvXq+YNv2LhOpaL*DV-Y&^QC0{GC{ z<=)^3A?PRcsZ)L)&8En3I*CxZKeGnzyJ~AVzncJx=4N^0Y$ll$8E41HSiKDx+eNM? z<(g`T*%L}IMZ=b;9y24gm_Bf!xasQE8nBeH>=_!=OHvK&}KHufc+hE=8nfu7xI0%oWz?WCP+r_3VtVYC6-hJv(6x46Zd9I$_Mi#QB zZ2T}Z$!x~)vf#Em@u*92nIL&?#d2P==x;ycQjzUu*{YoEp6#Ylk(unS_2CbK)H(&? zPWi^}(&;qH->Dm{?*UEAeiWinJML5tHXK2coTqM$UgAa42EPxp2FAUt2BnE$*m!nh zBYYxWIA(2yISGGdX_LI%`+~qz4>)}bbuQ_vv4o^0pTQZAp^WPET#-5IjPPonzTH9tKQcgbS2 zjyABvGtEu4nMo>QcR4xDyJg%Z%O# zX_zHG?|okXKCK9e5ag8|amwP;m!2b2B_faP;9(PNTH*kwwoZ~6oJaMJv}bWPFooAY zGs7^gIx92k5f)2t%&c4FOYh%tme0#$4c%egx!_z!^ z+W6KnDYH@*$!AM3;pnTq&kFvF9kH8R<8*-|_VnR(`1=MfG=#$vZDC^4G_A%gei(Da-MNlKs?v@QnxV%aX;MRK>*)I4pY?cYgS^&NouL;=db0gWgCa zBB>j`91YF^FsW%S>tvrTUOuP|4<6`VGs6{mFA1lTP6OdQN$m7D0@pFTm&;wm3Z`0G zpHXRF2{E~5mydjWcI)kHxs!9riRsfHjaMQZHE~>4My)F<+!?IBOrBk=kst^A93nbz1AD^L?DE*3~AP2uQnBE|LLz}ku$Z^yGXt4=}FW>N; ziA^`-bLb?HAC{LcJR75GrE3ux9%x7JDh(rIizbC0aVgBGJ5d@qz zrHrw!mkiXheJofO{qMo= zh(65&-e9Fk=#oc2$y9>ALIfOx<>AM0;TpqGqmedoqm?NsnS&xoaX%gi!azXzMnSMp zz#w8`?RKN#JI}Yw;~xjLZ#^rH@lO3|XE};1x0YBRHJO^Y{KX&B8*J3d*nIaoXw*5E zk;7;kB1Uch)ho$w(PhZqbXPT=HVycyjIpL;1c2d(B^bkZ(%%Ve?Wzhi$o=^^U|>Ge z#GMGvvqEcg6WLJhE4V(_>F^Fv4qmA)~7_6;jnjCzYGq>%_w0v-I$7xS!X!%>)D_4$fIEb znku;PUCPxn$lDXa@R0o00PwSo0stlpM*!AIT)!9=-s1|<;dv(G?eEyQC1iy9b#pUr zG4g3q(7<>zWI37~ukN=t((vALp;F`YhN$bQAFI)&IlHAduTH6Z*+Yi{$3kuj6jYD8 zHgLod{C=ddOkG2U1Q~z{$e4HrgH=-UEAsFyh|-HJ*(bBXd1Y3OE`>k*d3=2O&O17r zS<_r-!Y+1LfI~I@F$A1yyoY)!o=(kAA-s23D0woWMd{Xb@x}jk*zqM9GOOp(2+rki zQhAn2Z?Y=wgNzHQ6%y$Z%w;`0iZD+vR2%l+F3l%>40AN*({HC?-LgXY!h`4tl}rXc zq%hQo1cc=v@^d%OQE;D<6N1a@g#$PBv_>t_y2pnkAC>9X(X;qv$WS)le(Oa~uK%f8 zla3E*pr>ZakNr)*L(Ai4iQrOfnOa=6fy}DSA4?{EJy(}Yw{pn8qUgGv&?K037}x8| z0?ESaz`%Bx&Ym^EI1-v|N+v>MEI$Rxy>y%>9mtYar(`jvT_kA z1_t<@41C4t#@K|Kqs5LaincN0E*z3~!##+UQMx5VAx<}eLM>O2IMK;&o*0(A!B8$A zug+UwX>JSav&g;TcY>dY_nVC?xPUP3XwdQZy@3fc5!tx8w7MP3WN^CqGEoVCK|1V* zjCV!)Avi}VwmcCwXEuJTYfAjBD|cH^XMkBA+^uw$Tf@N6rK;{yPsrfi)1*yhGV<5Z znmAU(dYz=O-FE%bVn$irqdk4z(*a~XrW^oa*`_|TRxb>7aYIr7SgkCI7krgLf1d@o z;Nkw(EXYhWc>;1`1N*}n@fTOy%??i}S2I`tsF}{y9^(px$1p035Hcu$zZUQ{Io%$b znftt!yrx>biK2;@$nQ4kvFDQ1jDpz=o3B#7@pkSCF+ZO-FCl}Di3)wfYYeR45Lp?B z6~-%y;^y6rU-vTuXx=prMVC8kVKL-cqQ>vQ-w3$d8D1U)MfK6xmcL(CI<^FlF^F0$dI7gW}Z>Jt?vV!aLsS`i!ni#H=V_UBo18zgH77x`Qek zl}d}T+4V7;PoKoxVDBzlc6NpEM$##aa^mN&@07B7Re#P2f2|kgdH0z`eBz@ZYEZgJ zJQd+odQT}SD8uHS`svOd_ui*+{LGmgm5j=VTt;nU8CQp*MmdK<^&OA4hCgs*XLruz zXd1b)rgAGhP7kHy5XmbmDQ77v9@=3enN88cACb;{mMBB82s5JXUVQYHD=Juwi);Ut zaN!O&&3wmG*8#zd-Ew@cfJpbGQ?>uq)mMjA^#$#s2qGY$(jkaQN;eWxDsgC}8>G7% zNof&@LrTLz4&B||-QC>{cj525_xYat$N6WUv-eqR)~uO#X4al}Flw-pI0ffy+*Uot zZZ6YW&;|Z(NsEPi`SCdA@Xf{u0%w-o2wr&3RuMeLB^UEDx>l=G*EKG11vR)ZcwUKK zR$w2KidHkp@+oVavg*%wEMwkhY;)_(P*rE^>fjjI&7rFgcKT)_S<@!N#~qX>IvNK= zbK~u9s&reNCLCu-MyT->a0%0rvV{Rfq-rNth6#)tnYqUO6bEeySvIV?CdfV7W5r{OwmDsvMnS((XPcm*WKp7P!zonKaVyId7rcd zLyJT2(Z`SPjeZuJVT1ymi4~75GmFDDYtAw?f)zRGcbsN!^{3OLhN+#ovELtuc4B8) zNa75CN2=Q9^XXYteo0Y`q&}`uxv7764P(&%$;dTPj`I$ZVPn^Jdto2C*|TKaFewQN zhu!L9O2Jfi*mHF}m6@l?Wj+SgH)}%^B-T=f@8jJX*LonE%TzzCUao?%hQMjxF_#c? zaJcv_=MA>*BHj46nej+BT0e{J&bNjsZv3U0Q><53rHLp#06BHIwLPz>o?o7K_h=wC z(o@Yku1}5D!3D5*ioimK=g2j z(#xzd8chRhF`c?RJ@SI7xQJbvH;d# z^#q(uJeKTS7I`U}J5FfNF!7m)q{PVnvy!;i8>>B;^i#_o zO&&glIG++t#EJtI!v1V#yg|(TO6yh60bN=R)~m5G4mn(*myPVf?P{xg_mW!lE3S<# zPwQzX+pEqk?+*J~`%^YQ863aKo+*)VH1+r|^Dowo`i|rRj?Z4a>Lhkw7OQkZdLiXa z=5|6YgL|0mCq4c}A2t1$qjzvs`tp3!L?yY}`7wAGnN~9E{rmP-*e_KgiIpEnkTN!Z z*_58N&Jjhh!8hH$)A#CNV?Xx)G-3IN`e(-&F2=FwX7S`>U}O9B!fP_%SpHpg(u+-pjQcX62Wh){^qKQlToS-+3GqF`e-D>8Q!vETku z+s;C^kaZtdpxWQV@zPtk&xXl9>R7nA+ar0`qr&~{2#KiMAy#TN_sZ}YdBWaNzKtN( z9tF9_ZM5tPs$t_9B;90OhUQ@2bGp61A492zjU^_7K^q8ufIZ5bK4Qr9O>&XMcPu?x7sbU4LENs>j(Qi?@piISPBSe*^{tt z-grl|uKHNp@@PcMwVcWsab~f&tu7!-bM;1jPO!)q%jKvUkFip5v=;k@R`LmP`v%G= zuo}~Yb1{V$WAdqWtjlhysYrt*x;7IU;Eh5hh~(Pdb z&Ljp>yABJqy@;eJ8gZ|SWd5I0p^y@I2pcfyEpjomp=S2E8Z%{?(Eawxu{C%v#$sq~ z?F1LX?p;Oob<-rIGg43`>*>D>LPp1~A@K9xdKRIYli-*y9a&65DeuhU9REX_YKap+ zuJ~>H^Oiny+IN;8Br|N-{M=h_WjmEIjJp{w zP5A0+{T3(9#MC7-ZS2Maa8aoIeND69?p+j0k+yh1LH)*xJlgr*enz@mQ9ajl?o zxK?d_RiH?sck<4RHqxLkTVCP<2TW~Mg8v#67xOi366s2l0XzC+5u?pPqX;R!3MW>w z%?DYS)tC^5FI3j%2K>C<7NJLS-;OttU7L-Jm-h2*AEyBd)5#u#yrYo`@(_xeY>1=A z&tf0eB!s41G(yM5ysj%kZd;qF!>JpXSj zBLNn>dag75Aa4-VcDJVBfAv$0$56@qF)v%B%GbOpag=L2vvG|fWSykKRQE=GliTeC z>{ipy$2YEsC9O4L2%MQiHnOPXz(!TD20n%4Uwl(!xF3D>#lDs3c6mCUSs~*uk_3F= z54AW%ufsXb7LOL4ds~=)4Tdj$cXq@Tsza(4*9@#l%zJ$7*5F?Wq~cc6pV9L!&cmt@ zxN{v^L=~~s&&PhQpkkm z{Q)~#9=|rz0)0-f)dv}=ofTID<9O_)E%daMIktBt@ac0lQ5}kiG=8(8VQfv=+bFUo zF{~$xZw>0+Nqn9)2@2Pk(v8{=MnY#(%qZs$Df`3Ty`c{Oy?017s?lXX%1Xk-7S&+h zJ%aT7*QCwjZ#ph@0*Rqvd|gwC*c2%GF^RTnng=}OUFY1I#cMRDCLNs?11Apo5Cs|> zd$pW|b&)!zs?3F6NmNl1+p+qk$n7@dm zO2h}v+TV&Qv zw;b~@vJJ=M#^6VpWHZhpH@VlUK~GJy2G8u>MGkG+tmL7NRiqY7!;F5U+GijFSY z{(KsTK@I((Ic(uL!=6b6tew*sKpjLZC0J=uFCd|Tw8+tgf5hq*e&zq-spf{Jro>{{ zN!+Ww6J>sRN;DBxy%U#l>9sP$gBQ@B&-pb(rmXGpM%+4v0JLiu`>Yd*_DhQxmhXqi zvxzQpDHrCy@_F?d6C;;CB=ppxZ+`bpt0#VW$;Pf(&+-VMZaO&S1_x&V^vhh8vmqMB z{rMsP>j~x0u07#!8eez97xl6=FI<Hz*;-VUl5gzXSz6D=HUfr-l^b&_<$~K%1%;bc1plv&ogZbS!zs!CQcHaL z>)OQjqK1;3)N z^q1Z~yIfBop;tc}^^1x;Ov#~i1d%XQoX~*vO0FV1*(-n$HClh0>9weTy^g;8t-_m~ zfBm;AUf#HB8`0M->1}mN&J#DDGDOy#8uf&xS=s~&0V)(nmO(iaGaTaxgA-G0;+V!w zbPtUTU_hlY9F9pbPDj-Fm&OIZm&N8+!Bqbcd7R#%Bu`JviuW1^H3`QPI=MI!A=E;2 zl4b_IwemxPb~i%~_f9vDe5~o}t1^e2(IJ(qgcxkTkhYg9*wmA>2yDJ?zyKi1Z^Aa4 z)_wr5PHRqSIyq4$@m_o2^)V|~VvbACv2JcPgN&kjXurXwWjmaSEmCu7xvCTnuR>_< zHahzd)s>QqN^;mx^j4u;z_SLKlP~lQe{C()|EE}wWrrxu@54fvb(el|0{89f96Qu% zZ9RPCSt5=C=ixQQF3K0O-d0(Qbhz5Nbm-jBxFA?GT7Zd}X`uF`Fq`k~#q&^-yg|{J z9U53Bp|QSE&L{OstIWJcL@d%`YMU}jX+{)0|(U?#0T8ivR0 zv4LtVKYAQtr`vahzBWUn3)~-!$#B^M4Q$ajZquP2rl!6UZ*2`|YKC~+3Cj!veT4?w zvo8qD%z_TWspyDi`c`*_l&MWl4fnMYNRaU~c?G(X`PJ2aXC6!CcqXM%OK^B07ntEG z${GbCcPMYi^T*Ezv=tYS@oI@aQ{J#y&48Mp(Q@C&v1uZIS8un(ZxouWZq!8%9hAk%DJqT}yN}sxb+yLkJgsBIBW&B!ek~j*D)6gQzfQrm zw2&DTdxuz0fKeP|^IMDcRAHBz=XI!TN}3`3ZLIYX_whm(!ha!h+J;VIdA8cJ6&?tFK$KU5_{|vD&|YG z#gNTFd5ba%n^=u$z{xIA6*g6t{=PD!(J|W6iY&e$%~iCw`X*q@*-k!|-T{>Y=KgDu zP(0Vx$*|!5?3+B-G1nh_m##GbO)WPP~I%deX?8bOjdu<}s1 z#jgrf5v4NNurUdP_wo8=4FX9O&l<8EOO}QeEhI-R2onm;9=Ez+3Pw{5H`8iBOBG(oQAYe{8JMnV&RXb&ywpoX>;PqPzw{|>F+c%bPk zbz-pvE{o1EA*{s`^3*}BNLbP8!xZ<+ui<9WH zr<(e`BQS z3G&y(l@uf)?{JxDU3T4>;ubzwp2a*H`s_;NyxZlpX$j(|Q zN7HN0Ot~7+G@W3-)cLMf(1lRwhyKgO5?av6t7oGF|MvElSl~`=Ux+liCZ7yt4!uaA zu0Hp-$yN5naR8^4mELV!RvfhxWs-5OjABZ5koR&Gg{>w`O6w=gH2kSGh_j+{ny!9! z*1K4}4OQ$R0tYQZ`kj}Wtt&@gXF7>U5PWM#M0Q`coe1lm+vB;*qAEXHSo?(VdTOR4 zBVzTmYgp0mPYSc#yHk#Yjst-{^y8sRW``p`H=y zQ&&QQ*s4;^c0a>2J2^ZiE@$_mlk@MJ=tOuIdQp9O1?v=bgf>V4@G3IPQ)gC6`u4>D zD$9fI^B7zyAfL^e-bTpj#7k=+0YbS=>}f}{^(2jRt9|!#>yys{6fxcK!(4GJU+Kq! z^2-hWRpD;c=Oy{`lDPoTQd%xAJ%Da;(Gn`tNh6q?&YzqG9Mk!*oE#j6Wi;d9O9Hx} zs75F{5mBvOa;g)#iB5ghrAwBdrV3mxA#}ZB&aB2?hUPgT8ezJP14LGP3ubuq%m^ml zFoG|k;KE&daYy}JCvwl9%zZgW4i&V@!Es;lH!R|U2XDLdEycmGFykiR!e!d5Oo`+? z^LCS2w(d5YgnyMA{yGx}FIF(f=kQAJnNdbES{b;70hzrLMGKI4TP#sGk3=Z6RwQqa z=3a_QULpcoK2=2ID#4woY}ndZ`+0*6RE}s+y$=Haa4#L3gsC$^hOyw1`R|Ih)yQV> z&zNOe^E(F=&>=dMdJ%HpX1c`Sao;00C0TD~Czcq~-;$*YS}K9;JR(xeM1y z(xNzBIXbsIJH8t*WA^^NG!kl@RGFW6@05;*Egl*|B*gEZ+3nYFL@r#mpk2*SOn@eQ z+@iv(9ZjE$9qz9C9dk5*oK-#M>L(^d{<3=f`f_?4egvI0w;Ov(I}}nLSxijaZXm4Z zTeGXsgYma*T&qgq>N2?xg9X~tng}C2;>yVe_Wl) zNmoJb>i*`5x9n$RVE@VO+NrH~OO1hqF5+0q%j2k%LFt&d5>vA9ONSJYAc~zU=EQiE zk=!2k7EeSETZWp>)yl>(*3J;1s26ro&=5tK0b!gJh>wQ^G&N)MXp@xVC0Cu#r`V9D z4U}9%B;GzNEBz!cx_5sZsWv&WKw>zMwY)G%-9zNvr~jVCxxd3!lZ=KMpp+{rIp13s z8r`x=nx5R4wgTdqO@%P8l&|Ks#g*Je=^Z(uEQZ4xq)YQ8Q$0>Ytot?PtbG^iVe`*> z4kpT?sJ`im zFbN*Z@sJLHW@~okJk>~|Qk^i?JCS6Iv=WcE|(?B8~p z!}u8!IIYrjCYm$nXPO1d zgu$pUp6C6IS#X@IXe*RR3$C-Ys&cp;Y4gW|x}~IU+>~~w-HhWgKDM%8YP=O)zdUpD zO4)1`9gtyOy{i6B;BPpbG!T8A@Gl`F%`$r`cmyPvsrIGOx_c_`FOIxCh{1DTrQT9vgBO=0LQERKMHa5ZJwz@s8 zm``gmiW!pGev%~W6Jvxa0E4fh>G?|LVZW(L{FAf1@QcnVBKADs<<8y@Sv)rUOwH2sMCv8=b4KK! zrShHTP#%ou#9_f1#)Nv$5mHu64)*gm%N|ehJmUy4NDzahY;KFpO1lZ_30{gib zlBCAFh{Kk~s6mR}7Xn0t!hd?Q5H0gqaoJ?BFVgrDc`GV&6i_s~(b;9p`iBJ~T981r zZ5)d9<7uz%u};Q{7S0)gB&BUn`tcK7Cy!A-$xp8ceyN}d(}!0?ZR7M~G+AqSIDGrr zJRJv80bxlsVsj3#ph%EXIP_AnpBK*5Jla<6sKFwF_JR;1C2KO5dmDynqxT)H8V$!{ z1-||AIlgjPvk`fKxA$&^0qa|ko-!5DjrAs*QDO7Dy_sw#%H@ftbK={9m3pesdk7=8 z28Wfj-zvsbGD9=nBj&#Q3`1c^+cG7}1*jDbBDC#`c@W|)bGT~ODE3(t;iiQN`m4ij zx7Ehb;Jy1s$aBf8qnQM8P`Y?guPI)eQG^s1#QLhawdp!XzpiK7)Y6f!ogoyj^~-5T z2#op(B&tv(I(OMN-G;-nAUEp%;^ON|mEiijO_jT2w5V@Ax63rDxCG_yL|aZ-`8DCQ z%H&T`)rqARI7_yKFz_MimyGpw%4g-Kku(?Y3!q%}VLEN1@95hyNQpiyYP8!~ zor6Qk*L=$>rk4y=TPhk-8AoQ7dC}BHCM)Ivz<80Ij>=0N>WWY)r;S2*jeeFAtJm|u zXjjgT#>hl7qFRv}yoA&6QC<-_bGTI@v1r5R3>wdRQsxT^J`f$!`zv|An`z;AfWf&~ znKV>gIP_Amk<{oh%>J(D-H8>UO-9yiEupwtI95!MbEP>v|UzLAkA3mJ3rSCe`ChNl}LkQ z!T3pjLS2MwQk?*Tb-2yuTVo_$p)75XZCd@DuOuT7t@+ufZ>%S5E^G0-_HW?Q>9JCH z;=QTD{E6PnzdEPcL@h-V+^T|L4IO3}^0_37vOy-MY!PqE{;a|1U#Dj=3$<8UnUiZM znvLoT3;%FxSlGJAD`R6N2oB)nJlH#>S$dSFk2Qs#BrOnq+;sT{Vd(O)lq}h30OTXh zrN*=En}RpOWGLQN>#x{qrl`6d#!5T1`4t1u>;>n|n~a^^R}iX*OhnQjQ*w8&h3398 zc#$_Z_GPrKlg{IcaSFfYs*&q{+tA^+!)PQ{IXQhJl05{?PgK&(V1Oq1(REDZO?={uIS+tX?nM+PXmSnoJsmhY9T35Hl1Wai4m>V zVlf(1Mpm}vQK8U2mxwa;#zy;ERW9M&=B(V4GLgcaM>f%jk1GAg&;lRi?-rtL>YEAP zJo4UO%MKqf=RjOs+V_Y3hH5gT8wbvL9sUs;I|_=@yHoRC&6(Z3DR!M26XbH1O}osj zM=)W&+&rdwVEe2q<=MfW=wso7!&21*6{Lnk#F}zI=urs?}fi1 z>qDwUd-rfq(N9>-^7I&l9bjp9<|lr@bDrQ~Z##1OimlRVEYDXnFF(uDC|2I2A*?%~nm*%zn3&&u6jA%viL>S^{HzTDxSGMgbS9+cNI%g)GVy zp2sUuT?{quy*s~e@JB{A>^9%@XM z?qRa^f`UQKqW=^+6hE#C&hZ4TGV5(yBP5jFH=OE=iOP$f&o(Eb4h$e~bGVf_Mx>!Q zF^0Pc3(;YZ5iNeiX_tH(NRD1JfZ+>DSkO^i;5w+xV2A10J#f!4sw`~H6L^?(s zy)EitVO0yit}RVyHS8bFRdO_fvV@kIc1-l72%q> zf99}Rz#qY61cX-?4;%p|=t>E1?FA#Dl1UF3sh*gRp4^15kDK5zsA+^Z#*}7)Y;y0? zDySur!QtkpVY~hNB~P5Q&5{!91K-*LEziS~kb z!^>&}5-TP=^-6k%uIRbitXz>fR$9sJ1ANvz@eG!OLyDv;r*zBe_)-T8nO8yQrLBk| zlq{e?fq&_%{&D*d%hr*!4x9U#_rYP)?T`Ahz3q_WFP8GX<7%lMNfU!YZZ8DOtKatB z>GJHPHM}3=n&nS3H*`%1;7}5X4k%|U$n*F73jK+W&u%y$)uv~N_F*cudv3n1VEnHW zM`FH;0DJN$aK^yZxzPb7j!=4bx({t1^VK22&fZ^asmx4Ji2pT7tonuu@8>_HQ@zUE zAFn@;f8?G%ts%+QJAZPoJ-$@Dyti+B@#TCHv~g*bFlW$LlSp54eLYumVckdM$nl;z zSVjpasWx9v^jZy%ZPPr^%GoY#Zf)y2n;NytyNnT(>?X2`i|O0?%9MNUO<~^Vl_8Wx z7m>m?Z}Jd-!CrwvDgFZIh^`hVRJD#+RqyWIcJx<&&b{42%yxw%+iRW}Y#)C(OJbMa z2L^&}hRQO=Plg&^i%`&=0`08;6;&ILmD1;gmavaN&xq>Y5!WDvyH+pR(d&Jk7N4Ab zaV>LJPP4QQo@1<*UOu~9{$5^-=j_E9!AwG*Q;tIWuUEnk2S1u-TR$sm-&(H^(nGeZ z>RO-lx`4yr;pV0}^s)9h@=D=b zvVix-U)<94Z{4(}^b$`DkReh(3=xz}8FU4GQYO*q2Um$w97bJ@c>-}BDqLXuRtN35 z^v8?Ge5)l-@DTWM2hPf1@$=h_23Vz-yjsq%%IFe%7%mtGq~!(~b%0PUl&m!Um5*r0B z1U&7(e+RcOf)MKALepm2XIL|m;KOkL=UTzu%wh2ss^4S7zJ$fA)9vlLy<)@uRAX8g ztP}ch4~io~rt#6quynAMDm@HVWP7YWd2Z z1&W>`^CKw<(z0w#kih;^JgZ`EzJF)ueH?sna8gu4g070PH&00-MMm4m=toM5AaQ#N z93B?R$M@vs5kZ3D(qnn~$dmKa2=T0E$dApYN}yN%$TTqJ;fjZU7@D7#rc7)jMJaGT z{KgoYK_u1oC+Sb3SN zmD}v?5D>(&A8i#XZS3uRo3C@9slL`cswCb|{y>LVj6CPGY_9+@=uhGUga+Z!(YPLG z!^vF@f4`eiHjm~iO_sTTc#1)+4d^=DtS%A%x@jUCKBrj!rC#k2x;tH7eBbb>%yPc1 z6%Efy<1?~h)Rz|HD8RSj<{|L?BbMlQH-709nV;WPx+5c&wF!~Ge?(A}wIWtaCEo@V z4!+HA?3x?wH6A|_U}Y_4VKODNRJm~Hf86+ovke|>J`Jvfgn-l#6V^vrMdIn|JMgk- zsm47#7;f5Xtq2$|Aj36S$-W69T<*W!?vAwN+9KX2M}JpAlywHc3*dc$GLlH zq4BAVB9y31^>?n)^`5Gr=gEfb1OI`vd;a&7#Wyz|0;l$;HlOkk-QAVM-bDh1sjA}a z@cR3f6Rwq3oAyd0#xS!KNI6iF!~1%Lnk$c5vqL;LSrKOsT* zttiS9MExP?yO>vGz5E(UU5hZK@Y<$>gFj%76`;lKe$6pQrq06o_2%~W@~BdHCr|?g zp5BHA1V9aN16WP;9UP*y?yrzge?8XV6k*H5Bv1J28j&T(6(;PdMS4DekANv~LNmvA z2?tM%jgMbmKzuq`YD%S6X7+7A={h??Z zcxDQop7X6nR(^iCBu{f6$p;Bc z`5^qgXO3|W74fDC9w%vOZfC{0`PSlwLz;qm5#Jjh@qFM}{i})?ZLqkcOQ(h1$xb0WpTm%R#%)Z)3 zIB3iWW?=&NHIX!HXwsBjVI2UDkc-ItJDM^*+oKh+xVShg4QpZ*w7|(H$@fe3WW*S( zOjePOb1ttmIKeDC81LGpH#c@f=reiM|74Vgj*W2uLvwUCZ5h#-9@x5UFi-A!wiDU- z0vz5GVh1)&+vQtal@rNRQm&3pN9iEOHo|959!rLVzr+aG+}UXwVAu3G6g?y1BJ(Lm z#^67pQE$)8sT4)lt8F`3@JZl0!~l#qoxn8kmFS_k@nU5zrO z95KU#B$Gb^+7G}n!P#|prsR35v_0fvps(*cuKA%4a8kh0YHQUldJOL>A8-?J4`VTd zgR*t!wfoi=2RayTKZ^bBHP#Onn-KstLqtTxpuNgIUg1vrbv_>-HNBnb%#ADU$T)pLLtXU_yz;yXKJ>SDtBjt|va+(F!`jQW zcy#m`3aI2#6&A_`C}>)jSfQ@*QYF>Z@xOLE5DX*v(6-tgGg;nmns$8D&1k(hb8TmDFRP^VSxbvl z;IdQt;#lB*yhXQgs0#V%Q)cu?Fgh>rXsJXVQQp^v`*XD;zy?|n++HA52 z3WvjoT+;@r5#ZZ4CmWd1q@|X1VP-!revqeMRbmQxY)nEPQ;u^3r^*fScvf#_nv_alb%6@YNGV84n5%CQ`Xy z=jyx^NEQ6pIAP!8`~w?1dsJS2US25Z2aZrxRkg9Pu`*Gp_b%n<7Ye`^<2G3Z_qk~Ew;dvhJGeIJ6ug{NrE$=w5uCFJn9T^9We!E|vvGVYAbw=(F4GwnJ zxktT7tgPhD%rXRQLaTu1>h??9ZC?3YdQMJYzS}CDQJnvF)lIX&4I-6Pf_{5gVgk3V z|8jeHOzpbb{MFaZ^?Z-hTsBV5n6UNIaZM`RU`0Ou{~&aM6dM~G!a)~Zy$-kywAED- zQ332?%;-LQdloEENwJ%3SkuUef*8dkv+1(hle)}IN}&{)R*vGl)BI^_ zdRl4pwHY@+GoUe?GoW_qSU=9FceJ-ZoO8_zYAT7jx^h7Pd-WZ9Gj;C-Vppm~vfaNt z7m6eL_4$6gwHate*Nw(lgYZ#8g7rbF87^`;6wwBUy_O!uOSh9|xL$TV&p%Qt%n6LJ zDa~Dj2|cy~1U5nAs%qWwhD83d2G8lX%`&%nv;c(^aB!Rtgi4n6w;24%op4aF+Zaf( z$CEj3KL>1UN8t0d#zFbo7y?d367}UUxLT<0?1pzgVI|4@}qRDd`G;DbTpM zm8nwGn%lE!-us*5n`_T|(gC*T$^GG})V$X_#W+F+{6~wUp9DGL)sFcuZ|AD`PjjTB zg32vD%`@6j7PuUG4dUX}oc1c$3*J9~lZUASFNG4&{J>~LH@B9T9jA7DQD(8bI_J8d z>r`8XuTBh+$NPUP+Xpt5jMjX^zyK52-+&|x3;3G7y*0=BYZ5>mMa*NDz2^D|u30PY z>iS`!_ewlVo{phlZ)ZnD5eFE@2Y$1$of@cRVgZkYz`$o< zlm201Wo-tS=k(Oxw^^qlx7^s$a=j(+)l7wTVi<<>L{INK=dGM98Eij5Wu&Sa$8Eht z0=5spxs8n}(_7H!&s@ac?(Yy2xU9V`J+G%vPEHn%FTZ5T@63DtNu6+`0eS|U%gO2K z;qAU>a$DP{_uabVa1HP~upKX289fBq2wR!Z-_!N?#&bT}*xJ$@t#EK~02EPT9%seL zg*wg1EKoM!>j1RELkPemUAtUQUf;jl+n*>hKwGqmRcH7NdNu-MqkMP7OEIRLqlgg>nC13IMk*pz@SAyNC>P_8Z~O8wwL*I+0jN?Ik^N3cI3zC_8qV^ z1!MA8v;b3YO&lOY{e>f*UIh=R2!1fqQ;G?@*wI+hgW*xKaqomp!CMU3B?Y$7={_X=$;UVvgm8ke}VFUow6HZZX|y zjw%ZoC8c&BOn&7!(F!>Z^QjhLOum-M;`-$#KQv#VHxK)`_6~?B0uX`4*VW~&*f`s1 z&=r4Ies(_ZDF9p#CjW&OVBGp+JOvZkPW)kWYLZMB0|U_FK&;)G7<9GBAD*3UUFSb{ zCcsJw`N;HqRdV+K$poCfFK;uR ze39jh=KNn+TODP9mgRSA`Y(vZ;+K6dzt-`W=fCd^$p4G||5vE`AD#hl?H@=&`5#b% k^`E)Px# diff --git a/substrate/frame/sassafras/src/lib.rs b/substrate/frame/sassafras/src/lib.rs deleted file mode 100644 index 0ee8657489b..00000000000 --- a/substrate/frame/sassafras/src/lib.rs +++ /dev/null @@ -1,1081 +0,0 @@ -// 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. - -//! Extension module for Sassafras consensus. -//! -//! [Sassafras](https://research.web3.foundation/Polkadot/protocols/block-production/SASSAFRAS) -//! is a constant-time block production protocol that aims to ensure that there is -//! exactly one block produced with constant time intervals rather than multiple or none. -//! -//! We run a lottery to distribute block production slots in an epoch and to fix the -//! order validators produce blocks in, by the beginning of an epoch. -//! -//! Each validator signs the same VRF input and publishes the output on-chain. This -//! value is their lottery ticket that can be validated against their public key. -//! -//! We want to keep lottery winners secret, i.e. do not publish their public keys. -//! At the beginning of the epoch all the validators tickets are published but not -//! their public keys. -//! -//! A valid tickets is validated when an honest validator reclaims it on block -//! production. -//! -//! To prevent submission of fake tickets, resulting in empty slots, the validator -//! when submitting the ticket accompanies it with a SNARK of the statement: "Here's -//! my VRF output that has been generated using the given VRF input and my secret -//! key. I'm not telling you my keys, but my public key is among those of the -//! nominated validators", that is validated before the lottery. -//! -//! To anonymously publish the ticket to the chain a validator sends their tickets -//! to a random validator who later puts it on-chain as a transaction. - -#![deny(warnings)] -#![warn(unused_must_use, unsafe_code, unused_variables, unused_imports, missing_docs)] -#![cfg_attr(not(feature = "std"), no_std)] - -use log::{debug, error, trace, warn}; -use scale_codec::{Decode, Encode, MaxEncodedLen}; -use scale_info::TypeInfo; - -use frame_support::{ - dispatch::{DispatchResultWithPostInfo, Pays}, - traits::{Defensive, Get}, - weights::Weight, - BoundedVec, WeakBoundedVec, -}; -use frame_system::{ - offchain::{SendTransactionTypes, SubmitTransaction}, - pallet_prelude::BlockNumberFor, -}; -use sp_consensus_sassafras::{ - digests::{ConsensusLog, NextEpochDescriptor, SlotClaim}, - vrf, AuthorityId, Epoch, EpochConfiguration, Randomness, Slot, TicketBody, TicketEnvelope, - TicketId, RANDOMNESS_LENGTH, SASSAFRAS_ENGINE_ID, -}; -use sp_io::hashing; -use sp_runtime::{ - generic::DigestItem, - traits::{One, Zero}, - BoundToRuntimeAppPublic, -}; -use sp_std::prelude::Vec; - -#[cfg(feature = "runtime-benchmarks")] -mod benchmarking; -#[cfg(all(feature = "std", test))] -mod mock; -#[cfg(all(feature = "std", test))] -mod tests; - -pub mod weights; -pub use weights::WeightInfo; - -pub use pallet::*; - -const LOG_TARGET: &str = "sassafras::runtime"; - -// Contextual string used by the VRF to generate per-block randomness. -const RANDOMNESS_VRF_CONTEXT: &[u8] = b"SassafrasOnChainRandomness"; - -// Max length for segments holding unsorted tickets. -const SEGMENT_MAX_SIZE: u32 = 128; - -/// Authorities bounded vector convenience type. -pub type AuthoritiesVec = WeakBoundedVec::MaxAuthorities>; - -/// Epoch length defined by the configuration. -pub type EpochLengthFor = ::EpochLength; - -/// Tickets metadata. -#[derive(Debug, Default, PartialEq, Encode, Decode, TypeInfo, MaxEncodedLen, Clone, Copy)] -pub struct TicketsMetadata { - /// Number of outstanding next epoch tickets requiring to be sorted. - /// - /// These tickets are held by the [`UnsortedSegments`] storage map in segments - /// containing at most `SEGMENT_MAX_SIZE` items. - pub unsorted_tickets_count: u32, - - /// Number of tickets available for current and next epoch. - /// - /// These tickets are held by the [`TicketsIds`] storage map. - /// - /// The array entry to be used for the current epoch is computed as epoch index modulo 2. - pub tickets_count: [u32; 2], -} - -#[frame_support::pallet] -pub mod pallet { - use super::*; - use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; - - /// The Sassafras pallet. - #[pallet::pallet] - pub struct Pallet(_); - - /// Configuration parameters. - #[pallet::config] - pub trait Config: frame_system::Config + SendTransactionTypes> { - /// Amount of slots that each epoch should last. - #[pallet::constant] - type EpochLength: Get; - - /// Max number of authorities allowed. - #[pallet::constant] - type MaxAuthorities: Get; - - /// Epoch change trigger. - /// - /// Logic to be triggered on every block to query for whether an epoch has ended - /// and to perform the transition to the next epoch. - type EpochChangeTrigger: EpochChangeTrigger; - - /// Weight information for all calls of this pallet. - type WeightInfo: WeightInfo; - } - - /// Sassafras runtime errors. - #[pallet::error] - pub enum Error { - /// Submitted configuration is invalid. - InvalidConfiguration, - } - - /// Current epoch index. - #[pallet::storage] - #[pallet::getter(fn epoch_index)] - pub type EpochIndex = StorageValue<_, u64, ValueQuery>; - - /// Current epoch authorities. - #[pallet::storage] - #[pallet::getter(fn authorities)] - pub type Authorities = StorageValue<_, AuthoritiesVec, ValueQuery>; - - /// Next epoch authorities. - #[pallet::storage] - #[pallet::getter(fn next_authorities)] - pub type NextAuthorities = StorageValue<_, AuthoritiesVec, ValueQuery>; - - /// First block slot number. - /// - /// As the slots may not be zero-based, we record the slot value for the fist block. - /// This allows to always compute relative indices for epochs and slots. - #[pallet::storage] - #[pallet::getter(fn genesis_slot)] - pub type GenesisSlot = StorageValue<_, Slot, ValueQuery>; - - /// Current block slot number. - #[pallet::storage] - #[pallet::getter(fn current_slot)] - pub type CurrentSlot = StorageValue<_, Slot, ValueQuery>; - - /// Current epoch randomness. - #[pallet::storage] - #[pallet::getter(fn randomness)] - pub type CurrentRandomness = StorageValue<_, Randomness, ValueQuery>; - - /// Next epoch randomness. - #[pallet::storage] - #[pallet::getter(fn next_randomness)] - pub type NextRandomness = StorageValue<_, Randomness, ValueQuery>; - - /// Randomness accumulator. - /// - /// Excluded the first imported block, its value is updated on block finalization. - #[pallet::storage] - #[pallet::getter(fn randomness_accumulator)] - pub(crate) type RandomnessAccumulator = StorageValue<_, Randomness, ValueQuery>; - - /// The configuration for the current epoch. - #[pallet::storage] - #[pallet::getter(fn config)] - pub type EpochConfig = StorageValue<_, EpochConfiguration, ValueQuery>; - - /// The configuration for the next epoch. - #[pallet::storage] - #[pallet::getter(fn next_config)] - pub type NextEpochConfig = StorageValue<_, EpochConfiguration>; - - /// Pending epoch configuration change that will be set as `NextEpochConfig` when the next - /// epoch is enacted. - /// - /// In other words, a configuration change submitted during epoch N will be enacted on epoch - /// N+2. This is to maintain coherence for already submitted tickets for epoch N+1 that where - /// computed using configuration parameters stored for epoch N+1. - #[pallet::storage] - pub type PendingEpochConfigChange = StorageValue<_, EpochConfiguration>; - - /// Stored tickets metadata. - #[pallet::storage] - pub type TicketsMeta = StorageValue<_, TicketsMetadata, ValueQuery>; - - /// Tickets identifiers map. - /// - /// The map holds tickets ids for the current and next epoch. - /// - /// The key is a tuple composed by: - /// - `u8` equal to epoch's index modulo 2; - /// - `u32` equal to the ticket's index in a sorted list of epoch's tickets. - /// - /// Epoch X first N-th ticket has key (X mod 2, N) - /// - /// Note that the ticket's index doesn't directly correspond to the slot index within the epoch. - /// The assigment is computed dynamically using an *outside-in* strategy. - /// - /// Be aware that entries within this map are never removed, only overwritten. - /// Last element index should be fetched from the [`TicketsMeta`] value. - #[pallet::storage] - pub type TicketsIds = StorageMap<_, Identity, (u8, u32), TicketId>; - - /// Tickets to be used for current and next epoch. - #[pallet::storage] - pub type TicketsData = StorageMap<_, Identity, TicketId, TicketBody>; - - /// Next epoch tickets unsorted segments. - /// - /// Contains lists of tickets where each list represents a batch of tickets - /// received via the `submit_tickets` extrinsic. - /// - /// Each segment has max length [`SEGMENT_MAX_SIZE`]. - #[pallet::storage] - pub type UnsortedSegments = - StorageMap<_, Identity, u32, BoundedVec>, ValueQuery>; - - /// The most recently set of tickets which are candidates to become the next - /// epoch tickets. - #[pallet::storage] - pub type SortedCandidates = - StorageValue<_, BoundedVec>, ValueQuery>; - - /// Parameters used to construct the epoch's ring verifier. - /// - /// In practice: Updatable Universal Reference String and the seed. - #[pallet::storage] - #[pallet::getter(fn ring_context)] - pub type RingContext = StorageValue<_, vrf::RingContext>; - - /// Ring verifier data for the current epoch. - #[pallet::storage] - pub type RingVerifierData = StorageValue<_, vrf::RingVerifierData>; - - /// Slot claim VRF pre-output used to generate per-slot randomness. - /// - /// The value is ephemeral and is cleared on block finalization. - #[pallet::storage] - pub(crate) type ClaimTemporaryData = StorageValue<_, vrf::VrfPreOutput>; - - /// Genesis configuration for Sassafras protocol. - #[pallet::genesis_config] - #[derive(frame_support::DefaultNoBound)] - pub struct GenesisConfig { - /// Genesis authorities. - pub authorities: Vec, - /// Genesis epoch configuration. - pub epoch_config: EpochConfiguration, - /// Phantom config - #[serde(skip)] - pub _phantom: sp_std::marker::PhantomData, - } - - #[pallet::genesis_build] - impl BuildGenesisConfig for GenesisConfig { - fn build(&self) { - EpochConfig::::put(self.epoch_config); - Pallet::::genesis_authorities_initialize(&self.authorities); - - #[cfg(feature = "construct-dummy-ring-context")] - { - debug!(target: LOG_TARGET, "Constructing dummy ring context"); - let ring_ctx = vrf::RingContext::new_testing(); - RingContext::::put(ring_ctx); - Pallet::::update_ring_verifier(&self.authorities); - } - } - } - - #[pallet::hooks] - impl Hooks> for Pallet { - fn on_initialize(block_num: BlockNumberFor) -> Weight { - debug_assert_eq!(block_num, frame_system::Pallet::::block_number()); - - let claim = >::digest() - .logs - .iter() - .find_map(|item| item.pre_runtime_try_to::(&SASSAFRAS_ENGINE_ID)) - .expect("Valid block must have a slot claim. qed"); - - CurrentSlot::::put(claim.slot); - - if block_num == One::one() { - Self::post_genesis_initialize(claim.slot); - } - - let randomness_pre_output = claim - .vrf_signature - .pre_outputs - .get(0) - .expect("Valid claim must have VRF signature; qed"); - ClaimTemporaryData::::put(randomness_pre_output); - - let trigger_weight = T::EpochChangeTrigger::trigger::(block_num); - - T::WeightInfo::on_initialize() + trigger_weight - } - - fn on_finalize(_: BlockNumberFor) { - // At the end of the block, we can safely include the current slot randomness - // to the accumulator. If we've determined that this block was the first in - // a new epoch, the changeover logic has already occurred at this point - // (i.e. `enact_epoch_change` has already been called). - let randomness_input = vrf::slot_claim_input( - &Self::randomness(), - CurrentSlot::::get(), - EpochIndex::::get(), - ); - let randomness_pre_output = ClaimTemporaryData::::take() - .expect("Unconditionally populated in `on_initialize`; `on_finalize` is always called after; qed"); - let randomness = randomness_pre_output - .make_bytes::(RANDOMNESS_VRF_CONTEXT, &randomness_input); - Self::deposit_slot_randomness(&randomness); - - // Check if we are in the epoch's second half. - // If so, start sorting the next epoch tickets. - let epoch_length = T::EpochLength::get(); - let current_slot_idx = Self::current_slot_index(); - if current_slot_idx >= epoch_length / 2 { - let mut metadata = TicketsMeta::::get(); - if metadata.unsorted_tickets_count != 0 { - let next_epoch_idx = EpochIndex::::get() + 1; - let next_epoch_tag = (next_epoch_idx & 1) as u8; - let slots_left = epoch_length.checked_sub(current_slot_idx).unwrap_or(1); - Self::sort_segments( - metadata - .unsorted_tickets_count - .div_ceil(SEGMENT_MAX_SIZE * slots_left as u32), - next_epoch_tag, - &mut metadata, - ); - TicketsMeta::::set(metadata); - } - } - } - } - - #[pallet::call] - impl Pallet { - /// Submit next epoch tickets candidates. - /// - /// The number of tickets allowed to be submitted in one call is equal to the epoch length. - #[pallet::call_index(0)] - #[pallet::weight(T::WeightInfo::submit_tickets(tickets.len() as u32))] - pub fn submit_tickets( - origin: OriginFor, - tickets: BoundedVec>, - ) -> DispatchResultWithPostInfo { - ensure_none(origin)?; - - debug!(target: LOG_TARGET, "Received {} tickets", tickets.len()); - - let epoch_length = T::EpochLength::get(); - let current_slot_idx = Self::current_slot_index(); - if current_slot_idx > epoch_length / 2 { - warn!(target: LOG_TARGET, "Tickets shall be submitted in the first epoch half",); - return Err("Tickets shall be submitted in the first epoch half".into()) - } - - let Some(verifier) = RingVerifierData::::get().map(|v| v.into()) else { - warn!(target: LOG_TARGET, "Ring verifier key not initialized"); - return Err("Ring verifier key not initialized".into()) - }; - - let next_authorities = Self::next_authorities(); - - // Compute tickets threshold - let next_config = Self::next_config().unwrap_or_else(|| Self::config()); - let ticket_threshold = sp_consensus_sassafras::ticket_id_threshold( - next_config.redundancy_factor, - epoch_length as u32, - next_config.attempts_number, - next_authorities.len() as u32, - ); - - // Get next epoch params - let randomness = NextRandomness::::get(); - let epoch_idx = EpochIndex::::get() + 1; - - let mut valid_tickets = BoundedVec::with_bounded_capacity(tickets.len()); - - for ticket in tickets { - debug!(target: LOG_TARGET, "Checking ring proof"); - - let Some(ticket_id_pre_output) = ticket.signature.pre_outputs.get(0) else { - debug!(target: LOG_TARGET, "Missing ticket VRF pre-output from ring signature"); - continue - }; - let ticket_id_input = - vrf::ticket_id_input(&randomness, ticket.body.attempt_idx, epoch_idx); - - // Check threshold constraint - let ticket_id = vrf::make_ticket_id(&ticket_id_input, &ticket_id_pre_output); - if ticket_id >= ticket_threshold { - debug!(target: LOG_TARGET, "Ignoring ticket over threshold ({:032x} >= {:032x})", ticket_id, ticket_threshold); - continue - } - - // Check for duplicates - if TicketsData::::contains_key(ticket_id) { - debug!(target: LOG_TARGET, "Ignoring duplicate ticket ({:032x})", ticket_id); - continue - } - - // Check ring signature - let sign_data = vrf::ticket_body_sign_data(&ticket.body, ticket_id_input); - if !ticket.signature.ring_vrf_verify(&sign_data, &verifier) { - debug!(target: LOG_TARGET, "Proof verification failure for ticket ({:032x})", ticket_id); - continue - } - - if let Ok(_) = valid_tickets.try_push(ticket_id).defensive_proof( - "Input segment has same length as bounded destination vector; qed", - ) { - TicketsData::::set(ticket_id, Some(ticket.body)); - } - } - - if !valid_tickets.is_empty() { - Self::append_tickets(valid_tickets); - } - - Ok(Pays::No.into()) - } - - /// Plan an epoch configuration change. - /// - /// The epoch configuration change is recorded and will be announced at the begining - /// of the next epoch together with next epoch authorities information. - /// In other words, the configuration will be enacted one epoch later. - /// - /// Multiple calls to this method will replace any existing planned config change - /// that has not been enacted yet. - #[pallet::call_index(1)] - #[pallet::weight(T::WeightInfo::plan_config_change())] - pub fn plan_config_change( - origin: OriginFor, - config: EpochConfiguration, - ) -> DispatchResult { - ensure_root(origin)?; - - ensure!( - config.redundancy_factor != 0 && config.attempts_number != 0, - Error::::InvalidConfiguration - ); - PendingEpochConfigChange::::put(config); - Ok(()) - } - } - - #[pallet::validate_unsigned] - impl ValidateUnsigned for Pallet { - type Call = Call; - - fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity { - let Call::submit_tickets { tickets } = call else { - return InvalidTransaction::Call.into() - }; - - // Discard tickets not coming from the local node or that are not included in a block - if source == TransactionSource::External { - warn!( - target: LOG_TARGET, - "Rejecting unsigned `submit_tickets` transaction from external source", - ); - return InvalidTransaction::BadSigner.into() - } - - // Current slot should be less than half of epoch length. - let epoch_length = T::EpochLength::get(); - let current_slot_idx = Self::current_slot_index(); - if current_slot_idx > epoch_length / 2 { - warn!(target: LOG_TARGET, "Tickets shall be proposed in the first epoch half",); - return InvalidTransaction::Stale.into() - } - - // This should be set such that it is discarded after the first epoch half - let tickets_longevity = epoch_length / 2 - current_slot_idx; - let tickets_tag = tickets.using_encoded(|bytes| hashing::blake2_256(bytes)); - - ValidTransaction::with_tag_prefix("Sassafras") - .priority(TransactionPriority::max_value()) - .longevity(tickets_longevity as u64) - .and_provides(tickets_tag) - .propagate(true) - .build() - } - } -} - -// Inherent methods -impl Pallet { - /// Determine whether an epoch change should take place at this block. - /// - /// Assumes that initialization has already taken place. - pub(crate) fn should_end_epoch(block_num: BlockNumberFor) -> bool { - // The epoch has technically ended during the passage of time between this block and the - // last, but we have to "end" the epoch now, since there is no earlier possible block we - // could have done it. - // - // The exception is for block 1: the genesis has slot 0, so we treat epoch 0 as having - // started at the slot of block 1. We want to use the same randomness and validator set as - // signalled in the genesis, so we don't rotate the epoch. - block_num > One::one() && Self::current_slot_index() >= T::EpochLength::get() - } - - /// Current slot index relative to the current epoch. - fn current_slot_index() -> u32 { - Self::slot_index(CurrentSlot::::get()) - } - - /// Slot index relative to the current epoch. - fn slot_index(slot: Slot) -> u32 { - slot.checked_sub(*Self::current_epoch_start()) - .and_then(|v| v.try_into().ok()) - .unwrap_or(u32::MAX) - } - - /// Finds the start slot of the current epoch. - /// - /// Only guaranteed to give correct results after `initialize` of the first - /// block in the chain (as its result is based off of `GenesisSlot`). - fn current_epoch_start() -> Slot { - Self::epoch_start(EpochIndex::::get()) - } - - /// Get the epoch's first slot. - fn epoch_start(epoch_index: u64) -> Slot { - const PROOF: &str = "slot number is u64; it should relate in some way to wall clock time; \ - if u64 is not enough we should crash for safety; qed."; - - let epoch_start = epoch_index.checked_mul(T::EpochLength::get() as u64).expect(PROOF); - GenesisSlot::::get().checked_add(epoch_start).expect(PROOF).into() - } - - pub(crate) fn update_ring_verifier(authorities: &[AuthorityId]) { - debug!(target: LOG_TARGET, "Loading ring context"); - let Some(ring_ctx) = RingContext::::get() else { - debug!(target: LOG_TARGET, "Ring context not initialized"); - return - }; - - let pks: Vec<_> = authorities.iter().map(|auth| *auth.as_ref()).collect(); - - debug!(target: LOG_TARGET, "Building ring verifier (ring size: {})", pks.len()); - let verifier_data = ring_ctx - .verifier_data(&pks) - .expect("Failed to build ring verifier. This is a bug"); - - RingVerifierData::::put(verifier_data); - } - - /// Enact an epoch change. - /// - /// WARNING: Should be called on every block once and if and only if [`should_end_epoch`] - /// has returned `true`. - /// - /// If we detect one or more skipped epochs the policy is to use the authorities and values - /// from the first skipped epoch. The tickets data is invalidated. - pub(crate) fn enact_epoch_change( - authorities: WeakBoundedVec, - next_authorities: WeakBoundedVec, - ) { - if next_authorities != authorities { - Self::update_ring_verifier(&next_authorities); - } - - // Update authorities - Authorities::::put(&authorities); - NextAuthorities::::put(&next_authorities); - - // Update epoch index - let mut epoch_idx = EpochIndex::::get() + 1; - - let slot_idx = CurrentSlot::::get().saturating_sub(Self::epoch_start(epoch_idx)); - if slot_idx >= T::EpochLength::get() { - // Detected one or more skipped epochs, clear tickets data and recompute epoch index. - Self::reset_tickets_data(); - let skipped_epochs = *slot_idx / T::EpochLength::get() as u64; - epoch_idx += skipped_epochs; - warn!( - target: LOG_TARGET, - "Detected {} skipped epochs, resuming from epoch {}", - skipped_epochs, - epoch_idx - ); - } - - let mut metadata = TicketsMeta::::get(); - let mut metadata_dirty = false; - - EpochIndex::::put(epoch_idx); - - let next_epoch_idx = epoch_idx + 1; - - // Updates current epoch randomness and computes the *next* epoch randomness. - let next_randomness = Self::update_epoch_randomness(next_epoch_idx); - - if let Some(config) = NextEpochConfig::::take() { - EpochConfig::::put(config); - } - - let next_config = PendingEpochConfigChange::::take(); - if let Some(next_config) = next_config { - NextEpochConfig::::put(next_config); - } - - // After we update the current epoch, we signal the *next* epoch change - // so that nodes can track changes. - let next_epoch = NextEpochDescriptor { - randomness: next_randomness, - authorities: next_authorities.into_inner(), - config: next_config, - }; - Self::deposit_next_epoch_descriptor_digest(next_epoch); - - let epoch_tag = (epoch_idx & 1) as u8; - - // Optionally finish sorting - if metadata.unsorted_tickets_count != 0 { - Self::sort_segments(u32::MAX, epoch_tag, &mut metadata); - metadata_dirty = true; - } - - // Clear the "prev ≡ next (mod 2)" epoch tickets counter and bodies. - // Ids are left since are just cyclically overwritten on-the-go. - let prev_epoch_tag = epoch_tag ^ 1; - let prev_epoch_tickets_count = &mut metadata.tickets_count[prev_epoch_tag as usize]; - if *prev_epoch_tickets_count != 0 { - for idx in 0..*prev_epoch_tickets_count { - if let Some(ticket_id) = TicketsIds::::get((prev_epoch_tag, idx)) { - TicketsData::::remove(ticket_id); - } - } - *prev_epoch_tickets_count = 0; - metadata_dirty = true; - } - - if metadata_dirty { - TicketsMeta::::set(metadata); - } - } - - // Call this function on epoch change to enact current epoch randomness. - // - // Returns the next epoch randomness. - fn update_epoch_randomness(next_epoch_index: u64) -> Randomness { - let curr_epoch_randomness = NextRandomness::::get(); - CurrentRandomness::::put(curr_epoch_randomness); - - let accumulator = RandomnessAccumulator::::get(); - - let mut buf = [0; RANDOMNESS_LENGTH + 8]; - buf[..RANDOMNESS_LENGTH].copy_from_slice(&accumulator[..]); - buf[RANDOMNESS_LENGTH..].copy_from_slice(&next_epoch_index.to_le_bytes()); - - let next_randomness = hashing::blake2_256(&buf); - NextRandomness::::put(&next_randomness); - - next_randomness - } - - // Deposit per-slot randomness. - fn deposit_slot_randomness(randomness: &Randomness) { - let accumulator = RandomnessAccumulator::::get(); - - let mut buf = [0; 2 * RANDOMNESS_LENGTH]; - buf[..RANDOMNESS_LENGTH].copy_from_slice(&accumulator[..]); - buf[RANDOMNESS_LENGTH..].copy_from_slice(&randomness[..]); - - let accumulator = hashing::blake2_256(&buf); - RandomnessAccumulator::::put(accumulator); - } - - // Deposit next epoch descriptor in the block header digest. - fn deposit_next_epoch_descriptor_digest(desc: NextEpochDescriptor) { - let item = ConsensusLog::NextEpochData(desc); - let log = DigestItem::Consensus(SASSAFRAS_ENGINE_ID, item.encode()); - >::deposit_log(log) - } - - // Initialize authorities on genesis phase. - // - // Genesis authorities may have been initialized via other means (e.g. via session pallet). - // - // If this function has already been called with some authorities, then the new list - // should match the previously set one. - fn genesis_authorities_initialize(authorities: &[AuthorityId]) { - let prev_authorities = Authorities::::get(); - - if !prev_authorities.is_empty() { - // This function has already been called. - if prev_authorities.as_slice() == authorities { - return - } else { - panic!("Authorities were already initialized"); - } - } - - let authorities = WeakBoundedVec::try_from(authorities.to_vec()) - .expect("Initial number of authorities should be lower than T::MaxAuthorities"); - Authorities::::put(&authorities); - NextAuthorities::::put(&authorities); - } - - // Method to be called on first block `on_initialize` to properly populate some key parameters. - fn post_genesis_initialize(slot: Slot) { - // Keep track of the actual first slot used (may not be zero based). - GenesisSlot::::put(slot); - - // Properly initialize randomness using genesis hash and current slot. - // This is important to guarantee that a different set of tickets are produced for: - // - different chains which share the same ring parameters and - // - same chain started with a different slot base. - let genesis_hash = frame_system::Pallet::::parent_hash(); - let mut buf = genesis_hash.as_ref().to_vec(); - buf.extend_from_slice(&slot.to_le_bytes()); - let randomness = hashing::blake2_256(buf.as_slice()); - RandomnessAccumulator::::put(randomness); - - let next_randoness = Self::update_epoch_randomness(1); - - // Deposit a log as this is the first block in first epoch. - let next_epoch = NextEpochDescriptor { - randomness: next_randoness, - authorities: Self::next_authorities().into_inner(), - config: None, - }; - Self::deposit_next_epoch_descriptor_digest(next_epoch); - } - - /// Current epoch information. - pub fn current_epoch() -> Epoch { - let index = EpochIndex::::get(); - Epoch { - index, - start: Self::epoch_start(index), - length: T::EpochLength::get(), - authorities: Self::authorities().into_inner(), - randomness: Self::randomness(), - config: Self::config(), - } - } - - /// Next epoch information. - pub fn next_epoch() -> Epoch { - let index = EpochIndex::::get() + 1; - Epoch { - index, - start: Self::epoch_start(index), - length: T::EpochLength::get(), - authorities: Self::next_authorities().into_inner(), - randomness: Self::next_randomness(), - config: Self::next_config().unwrap_or_else(|| Self::config()), - } - } - - /// Fetch expected ticket-id for the given slot according to an "outside-in" sorting strategy. - /// - /// Given an ordered sequence of tickets [t0, t1, t2, ..., tk] to be assigned to n slots, - /// with n >= k, then the tickets are assigned to the slots according to the following - /// strategy: - /// - /// slot-index : [ 0, 1, 2, ............ , n ] - /// tickets : [ t1, t3, t5, ... , t4, t2, t0 ]. - /// - /// With slot-index computed as `epoch_start() - slot`. - /// - /// If `slot` value falls within the current epoch then we fetch tickets from the current epoch - /// tickets list. - /// - /// If `slot` value falls within the next epoch then we fetch tickets from the next epoch - /// tickets ids list. Note that in this case we may have not finished receiving all the tickets - /// for that epoch yet. The next epoch tickets should be considered "stable" only after the - /// current epoch first half slots were elapsed (see `submit_tickets_unsigned_extrinsic`). - /// - /// Returns `None` if, according to the sorting strategy, there is no ticket associated to the - /// specified slot-index (happens if a ticket falls in the middle of an epoch and n > k), - /// or if the slot falls beyond the next epoch. - /// - /// Before importing the first block this returns `None`. - pub fn slot_ticket_id(slot: Slot) -> Option { - if frame_system::Pallet::::block_number().is_zero() { - return None - } - let epoch_idx = EpochIndex::::get(); - let epoch_len = T::EpochLength::get(); - let mut slot_idx = Self::slot_index(slot); - let mut metadata = TicketsMeta::::get(); - - let get_ticket_idx = |slot_idx| { - let ticket_idx = if slot_idx < epoch_len / 2 { - 2 * slot_idx + 1 - } else { - 2 * (epoch_len - (slot_idx + 1)) - }; - debug!( - target: LOG_TARGET, - "slot-idx {} <-> ticket-idx {}", - slot_idx, - ticket_idx - ); - ticket_idx as u32 - }; - - let mut epoch_tag = (epoch_idx & 1) as u8; - - if epoch_len <= slot_idx && slot_idx < 2 * epoch_len { - // Try to get a ticket for the next epoch. Since its state values were not enacted yet, - // we may have to finish sorting the tickets. - epoch_tag ^= 1; - slot_idx -= epoch_len; - if metadata.unsorted_tickets_count != 0 { - Self::sort_segments(u32::MAX, epoch_tag, &mut metadata); - TicketsMeta::::set(metadata); - } - } else if slot_idx >= 2 * epoch_len { - return None - } - - let ticket_idx = get_ticket_idx(slot_idx); - if ticket_idx < metadata.tickets_count[epoch_tag as usize] { - TicketsIds::::get((epoch_tag, ticket_idx)) - } else { - None - } - } - - /// Returns ticket id and data associated with the given `slot`. - /// - /// Refer to the `slot_ticket_id` documentation for the slot-ticket association - /// criteria. - pub fn slot_ticket(slot: Slot) -> Option<(TicketId, TicketBody)> { - Self::slot_ticket_id(slot).and_then(|id| TicketsData::::get(id).map(|body| (id, body))) - } - - // Sort and truncate candidate tickets, cleanup storage. - fn sort_and_truncate(candidates: &mut Vec, max_tickets: usize) -> u128 { - candidates.sort_unstable(); - candidates.drain(max_tickets..).for_each(TicketsData::::remove); - candidates[max_tickets - 1] - } - - /// Sort the tickets which belong to the epoch with the specified `epoch_tag`. - /// - /// At most `max_segments` are taken from the `UnsortedSegments` structure. - /// - /// The tickets of the removed segments are merged with the tickets on the `SortedCandidates` - /// which is then sorted an truncated to contain at most `MaxTickets` entries. - /// - /// If all the entries in `UnsortedSegments` are consumed, then `SortedCandidates` is elected - /// as the next epoch tickets, else it is saved to be used by next calls of this function. - pub(crate) fn sort_segments(max_segments: u32, epoch_tag: u8, metadata: &mut TicketsMetadata) { - let unsorted_segments_count = metadata.unsorted_tickets_count.div_ceil(SEGMENT_MAX_SIZE); - let max_segments = max_segments.min(unsorted_segments_count); - let max_tickets = Self::epoch_length() as usize; - - // Fetch the sorted candidates (if any). - let mut candidates = SortedCandidates::::take().into_inner(); - - // There is an upper bound to check only if we already sorted the max number - // of allowed tickets. - let mut upper_bound = *candidates.get(max_tickets - 1).unwrap_or(&TicketId::MAX); - - let mut require_sort = false; - - // Consume at most `max_segments` segments. - // During the process remove every stale ticket from `TicketsData` storage. - for segment_idx in (0..unsorted_segments_count).rev().take(max_segments as usize) { - let segment = UnsortedSegments::::take(segment_idx); - metadata.unsorted_tickets_count -= segment.len() as u32; - - // Push only ids with a value less than the current `upper_bound`. - let prev_len = candidates.len(); - for ticket_id in segment { - if ticket_id < upper_bound { - candidates.push(ticket_id); - } else { - TicketsData::::remove(ticket_id); - } - } - require_sort = candidates.len() != prev_len; - - // As we approach the tail of the segments buffer the `upper_bound` value is expected - // to decrease (fast). We thus expect the number of tickets pushed into the - // `candidates` vector to follow an exponential drop. - // - // Given this, sorting and truncating after processing each segment may be an overkill - // as we may find pushing few tickets more and more often. Is preferable to perform - // the sort and truncation operations only when we reach some bigger threshold - // (currently set as twice the capacity of `SortCandidate`). - // - // The more is the protocol's redundancy factor (i.e. the ratio between tickets allowed - // to be submitted and the epoch length) the more this check becomes relevant. - if candidates.len() > 2 * max_tickets { - upper_bound = Self::sort_and_truncate(&mut candidates, max_tickets); - require_sort = false; - } - } - - if candidates.len() > max_tickets { - Self::sort_and_truncate(&mut candidates, max_tickets); - } else if require_sort { - candidates.sort_unstable(); - } - - if metadata.unsorted_tickets_count == 0 { - // Sorting is over, write to next epoch map. - candidates.iter().enumerate().for_each(|(i, id)| { - TicketsIds::::insert((epoch_tag, i as u32), id); - }); - metadata.tickets_count[epoch_tag as usize] = candidates.len() as u32; - } else { - // Keep the partial result for the next calls. - SortedCandidates::::set(BoundedVec::truncate_from(candidates)); - } - } - - /// Append a set of tickets to the segments map. - pub(crate) fn append_tickets(mut tickets: BoundedVec>) { - debug!(target: LOG_TARGET, "Appending batch with {} tickets", tickets.len()); - tickets.iter().for_each(|t| trace!(target: LOG_TARGET, " + {t:032x}")); - - let mut metadata = TicketsMeta::::get(); - let mut segment_idx = metadata.unsorted_tickets_count / SEGMENT_MAX_SIZE; - - while !tickets.is_empty() { - let rem = metadata.unsorted_tickets_count % SEGMENT_MAX_SIZE; - let to_be_added = tickets.len().min((SEGMENT_MAX_SIZE - rem) as usize); - - let mut segment = UnsortedSegments::::get(segment_idx); - let _ = segment - .try_extend(tickets.drain(..to_be_added)) - .defensive_proof("We don't add more than `SEGMENT_MAX_SIZE` and this is the maximum bound for the vector."); - UnsortedSegments::::insert(segment_idx, segment); - - metadata.unsorted_tickets_count += to_be_added as u32; - segment_idx += 1; - } - - TicketsMeta::::set(metadata); - } - - /// Remove all tickets related data. - /// - /// May not be efficient as the calling places may repeat some of this operations - /// but is a very extraordinary operation (hopefully never happens in production) - /// and better safe than sorry. - fn reset_tickets_data() { - let metadata = TicketsMeta::::get(); - - // Remove even/odd-epoch data. - for epoch_tag in 0..=1 { - for idx in 0..metadata.tickets_count[epoch_tag] { - if let Some(id) = TicketsIds::::get((epoch_tag as u8, idx)) { - TicketsData::::remove(id); - } - } - } - - // Remove all unsorted tickets segments. - let segments_count = metadata.unsorted_tickets_count.div_ceil(SEGMENT_MAX_SIZE); - (0..segments_count).for_each(UnsortedSegments::::remove); - - // Reset sorted candidates - SortedCandidates::::kill(); - - // Reset tickets metadata - TicketsMeta::::kill(); - } - - /// Submit next epoch validator tickets via an unsigned extrinsic constructed with a call to - /// `submit_unsigned_transaction`. - /// - /// The submitted tickets are added to the next epoch outstanding tickets as long as the - /// extrinsic is called within the first half of the epoch. Tickets received during the - /// second half are dropped. - pub fn submit_tickets_unsigned_extrinsic(tickets: Vec) -> bool { - let tickets = BoundedVec::truncate_from(tickets); - let call = Call::submit_tickets { tickets }; - match SubmitTransaction::>::submit_unsigned_transaction(call.into()) { - Ok(_) => true, - Err(e) => { - error!(target: LOG_TARGET, "Error submitting tickets {:?}", e); - false - }, - } - } - - /// Epoch length - pub fn epoch_length() -> u32 { - T::EpochLength::get() - } -} - -/// Trigger an epoch change, if any should take place. -pub trait EpochChangeTrigger { - /// May trigger an epoch change, if any should take place. - /// - /// Returns an optional `Weight` if epoch change has been triggered. - /// - /// This should be called during every block, after initialization is done. - fn trigger(_: BlockNumberFor) -> Weight; -} - -/// An `EpochChangeTrigger` which does nothing. -/// -/// In practice this means that the epoch change logic is left to some external component -/// (e.g. pallet-session). -pub struct EpochChangeExternalTrigger; - -impl EpochChangeTrigger for EpochChangeExternalTrigger { - fn trigger(_: BlockNumberFor) -> Weight { - // nothing - trigger is external. - Weight::zero() - } -} - -/// An `EpochChangeTrigger` which recycle the same authorities set forever. -/// -/// The internal trigger should only be used when no other module is responsible for -/// changing authority set. -pub struct EpochChangeInternalTrigger; - -impl EpochChangeTrigger for EpochChangeInternalTrigger { - fn trigger(block_num: BlockNumberFor) -> Weight { - if Pallet::::should_end_epoch(block_num) { - let authorities = Pallet::::next_authorities(); - let next_authorities = authorities.clone(); - let len = next_authorities.len() as u32; - Pallet::::enact_epoch_change(authorities, next_authorities); - T::WeightInfo::enact_epoch_change(len, T::EpochLength::get()) - } else { - Weight::zero() - } - } -} - -impl BoundToRuntimeAppPublic for Pallet { - type Public = AuthorityId; -} diff --git a/substrate/frame/sassafras/src/mock.rs b/substrate/frame/sassafras/src/mock.rs deleted file mode 100644 index 5aca815cc21..00000000000 --- a/substrate/frame/sassafras/src/mock.rs +++ /dev/null @@ -1,343 +0,0 @@ -// 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. - -//! Test utilities for Sassafras pallet. - -use crate::{self as pallet_sassafras, EpochChangeInternalTrigger, *}; - -use frame_support::{ - derive_impl, - traits::{ConstU32, OnFinalize, OnInitialize}, -}; -use sp_consensus_sassafras::{ - digests::SlotClaim, - vrf::{RingProver, VrfSignature}, - AuthorityIndex, AuthorityPair, EpochConfiguration, Slot, TicketBody, TicketEnvelope, TicketId, -}; -use sp_core::{ - crypto::{ByteArray, Pair, UncheckedFrom, VrfSecret, Wraps}, - ed25519::Public as EphemeralPublic, - H256, U256, -}; -use sp_runtime::{ - testing::{Digest, DigestItem, Header, TestXt}, - BuildStorage, -}; - -const LOG_TARGET: &str = "sassafras::tests"; - -const EPOCH_LENGTH: u32 = 10; -const MAX_AUTHORITIES: u32 = 100; - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] -impl frame_system::Config for Test { - type Block = frame_system::mocking::MockBlock; -} - -impl frame_system::offchain::SendTransactionTypes for Test -where - RuntimeCall: From, -{ - type OverarchingCall = RuntimeCall; - type Extrinsic = TestXt; -} - -impl pallet_sassafras::Config for Test { - type EpochLength = ConstU32; - type MaxAuthorities = ConstU32; - type EpochChangeTrigger = EpochChangeInternalTrigger; - type WeightInfo = (); -} - -frame_support::construct_runtime!( - pub enum Test { - System: frame_system, - Sassafras: pallet_sassafras, - } -); - -// Default used for most of the tests. -// -// The redundancy factor has been set to max value to accept all submitted -// tickets without worrying about the threshold. -pub const TEST_EPOCH_CONFIGURATION: EpochConfiguration = - EpochConfiguration { redundancy_factor: u32::MAX, attempts_number: 5 }; - -/// Build and returns test storage externalities -pub fn new_test_ext(authorities_len: usize) -> sp_io::TestExternalities { - new_test_ext_with_pairs(authorities_len, false).1 -} - -/// Build and returns test storage externalities and authority set pairs used -/// by Sassafras genesis configuration. -pub fn new_test_ext_with_pairs( - authorities_len: usize, - with_ring_context: bool, -) -> (Vec, sp_io::TestExternalities) { - let pairs = (0..authorities_len) - .map(|i| AuthorityPair::from_seed(&U256::from(i).into())) - .collect::>(); - - let authorities: Vec<_> = pairs.iter().map(|p| p.public()).collect(); - - let mut storage = frame_system::GenesisConfig::::default().build_storage().unwrap(); - - pallet_sassafras::GenesisConfig:: { - authorities: authorities.clone(), - epoch_config: TEST_EPOCH_CONFIGURATION, - _phantom: sp_std::marker::PhantomData, - } - .assimilate_storage(&mut storage) - .unwrap(); - - let mut ext: sp_io::TestExternalities = storage.into(); - - if with_ring_context { - ext.execute_with(|| { - log::debug!(target: LOG_TARGET, "Building testing ring context"); - let ring_ctx = vrf::RingContext::new_testing(); - RingContext::::set(Some(ring_ctx.clone())); - Sassafras::update_ring_verifier(&authorities); - }); - } - - (pairs, ext) -} - -fn make_ticket_with_prover( - attempt: u32, - pair: &AuthorityPair, - prover: &RingProver, -) -> TicketEnvelope { - log::debug!("attempt: {}", attempt); - - // Values are referring to the next epoch - let epoch = Sassafras::epoch_index() + 1; - let randomness = Sassafras::next_randomness(); - - // Make a dummy ephemeral public that hopefully is unique within one test instance. - // In the tests, the values within the erased public are just used to compare - // ticket bodies, so it is not important to be a valid key. - let mut raw: [u8; 32] = [0; 32]; - raw.copy_from_slice(&pair.public().as_slice()[0..32]); - let erased_public = EphemeralPublic::unchecked_from(raw); - let revealed_public = erased_public; - - let ticket_id_input = vrf::ticket_id_input(&randomness, attempt, epoch); - - let body = TicketBody { attempt_idx: attempt, erased_public, revealed_public }; - let sign_data = vrf::ticket_body_sign_data(&body, ticket_id_input); - - let signature = pair.as_ref().ring_vrf_sign(&sign_data, &prover); - - // Ticket-id can be generated via vrf-preout. - // We don't care that much about its value here. - TicketEnvelope { body, signature } -} - -pub fn make_prover(pair: &AuthorityPair) -> RingProver { - let public = pair.public(); - let mut prover_idx = None; - - let ring_ctx = Sassafras::ring_context().unwrap(); - - let pks: Vec = Sassafras::authorities() - .iter() - .enumerate() - .map(|(idx, auth)| { - if public == *auth { - prover_idx = Some(idx); - } - *auth.as_ref() - }) - .collect(); - - log::debug!("Building prover. Ring size: {}", pks.len()); - let prover = ring_ctx.prover(&pks, prover_idx.unwrap()).unwrap(); - log::debug!("Done"); - - prover -} - -/// Construct `attempts` tickets envelopes for the next epoch. -/// -/// E.g. by passing an optional threshold -pub fn make_tickets(attempts: u32, pair: &AuthorityPair) -> Vec { - let prover = make_prover(pair); - (0..attempts) - .into_iter() - .map(|attempt| make_ticket_with_prover(attempt, pair, &prover)) - .collect() -} - -pub fn make_ticket_body(attempt_idx: u32, pair: &AuthorityPair) -> (TicketId, TicketBody) { - // Values are referring to the next epoch - let epoch = Sassafras::epoch_index() + 1; - let randomness = Sassafras::next_randomness(); - - let ticket_id_input = vrf::ticket_id_input(&randomness, attempt_idx, epoch); - let ticket_id_pre_output = pair.as_inner_ref().vrf_pre_output(&ticket_id_input); - - let id = vrf::make_ticket_id(&ticket_id_input, &ticket_id_pre_output); - - // Make a dummy ephemeral public that hopefully is unique within one test instance. - // In the tests, the values within the erased public are just used to compare - // ticket bodies, so it is not important to be a valid key. - let mut raw: [u8; 32] = [0; 32]; - raw[..16].copy_from_slice(&pair.public().as_slice()[0..16]); - raw[16..].copy_from_slice(&id.to_le_bytes()); - let erased_public = EphemeralPublic::unchecked_from(raw); - let revealed_public = erased_public; - - let body = TicketBody { attempt_idx, erased_public, revealed_public }; - - (id, body) -} - -pub fn make_dummy_ticket_body(attempt_idx: u32) -> (TicketId, TicketBody) { - let hash = sp_core::hashing::blake2_256(&attempt_idx.to_le_bytes()); - - let erased_public = EphemeralPublic::unchecked_from(hash); - let revealed_public = erased_public; - - let body = TicketBody { attempt_idx, erased_public, revealed_public }; - - let mut bytes = [0u8; 16]; - bytes.copy_from_slice(&hash[..16]); - let id = TicketId::from_le_bytes(bytes); - - (id, body) -} - -pub fn make_ticket_bodies( - number: u32, - pair: Option<&AuthorityPair>, -) -> Vec<(TicketId, TicketBody)> { - (0..number) - .into_iter() - .map(|i| match pair { - Some(pair) => make_ticket_body(i, pair), - None => make_dummy_ticket_body(i), - }) - .collect() -} - -/// Persist the given tickets in the unsorted segments buffer. -/// -/// This function skips all the checks performed by the `submit_tickets` extrinsic and -/// directly appends the tickets to the `UnsortedSegments` structure. -pub fn persist_next_epoch_tickets_as_segments(tickets: &[(TicketId, TicketBody)]) { - let mut ids = Vec::with_capacity(tickets.len()); - tickets.iter().for_each(|(id, body)| { - TicketsData::::set(id, Some(body.clone())); - ids.push(*id); - }); - let max_chunk_size = Sassafras::epoch_length() as usize; - ids.chunks(max_chunk_size).for_each(|chunk| { - Sassafras::append_tickets(BoundedVec::truncate_from(chunk.to_vec())); - }) -} - -/// Calls the [`persist_next_epoch_tickets_as_segments`] and then proceeds to the -/// sorting of the candidates. -/// -/// Only "winning" tickets are left. -pub fn persist_next_epoch_tickets(tickets: &[(TicketId, TicketBody)]) { - persist_next_epoch_tickets_as_segments(tickets); - // Force sorting of next epoch tickets (enactment) by explicitly querying the first of them. - let next_epoch = Sassafras::next_epoch(); - assert_eq!(TicketsMeta::::get().unsorted_tickets_count, tickets.len() as u32); - Sassafras::slot_ticket(next_epoch.start).unwrap(); - assert_eq!(TicketsMeta::::get().unsorted_tickets_count, 0); -} - -fn slot_claim_vrf_signature(slot: Slot, pair: &AuthorityPair) -> VrfSignature { - let mut epoch = Sassafras::epoch_index(); - let mut randomness = Sassafras::randomness(); - - // Check if epoch is going to change on initialization. - let epoch_start = Sassafras::current_epoch_start(); - let epoch_length = EPOCH_LENGTH.into(); - if epoch_start != 0_u64 && slot >= epoch_start + epoch_length { - epoch += slot.saturating_sub(epoch_start).saturating_div(epoch_length); - randomness = crate::NextRandomness::::get(); - } - - let data = vrf::slot_claim_sign_data(&randomness, slot, epoch); - pair.as_ref().vrf_sign(&data) -} - -/// Construct a `PreDigest` instance for the given parameters. -pub fn make_slot_claim( - authority_idx: AuthorityIndex, - slot: Slot, - pair: &AuthorityPair, -) -> SlotClaim { - let vrf_signature = slot_claim_vrf_signature(slot, pair); - SlotClaim { authority_idx, slot, vrf_signature, ticket_claim: None } -} - -/// Construct a `Digest` with a `SlotClaim` item. -pub fn make_digest(authority_idx: AuthorityIndex, slot: Slot, pair: &AuthorityPair) -> Digest { - let claim = make_slot_claim(authority_idx, slot, pair); - Digest { logs: vec![DigestItem::from(&claim)] } -} - -pub fn initialize_block( - number: u64, - slot: Slot, - parent_hash: H256, - pair: &AuthorityPair, -) -> Digest { - let digest = make_digest(0, slot, pair); - System::reset_events(); - System::initialize(&number, &parent_hash, &digest); - Sassafras::on_initialize(number); - digest -} - -pub fn finalize_block(number: u64) -> Header { - Sassafras::on_finalize(number); - System::finalize() -} - -/// Progress the pallet state up to the given block `number` and `slot`. -pub fn go_to_block(number: u64, slot: Slot, pair: &AuthorityPair) -> Digest { - Sassafras::on_finalize(System::block_number()); - let parent_hash = System::finalize().hash(); - - let digest = make_digest(0, slot, pair); - - System::reset_events(); - System::initialize(&number, &parent_hash, &digest); - Sassafras::on_initialize(number); - - digest -} - -/// Progress the pallet state up to the given block `number`. -/// Slots will grow linearly accordingly to blocks. -pub fn progress_to_block(number: u64, pair: &AuthorityPair) -> Option { - let mut slot = Sassafras::current_slot() + 1; - let mut digest = None; - for i in System::block_number() + 1..=number { - let dig = go_to_block(i, slot, pair); - digest = Some(dig); - slot = slot + 1; - } - digest -} diff --git a/substrate/frame/sassafras/src/tests.rs b/substrate/frame/sassafras/src/tests.rs deleted file mode 100644 index ec3425cce7b..00000000000 --- a/substrate/frame/sassafras/src/tests.rs +++ /dev/null @@ -1,874 +0,0 @@ -// 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 Sassafras pallet. - -use crate::*; -use mock::*; - -use sp_consensus_sassafras::Slot; - -fn h2b(hex: &str) -> [u8; N] { - array_bytes::hex2array_unchecked(hex) -} - -fn b2h(bytes: [u8; N]) -> String { - array_bytes::bytes2hex("", &bytes) -} - -#[test] -fn genesis_values_assumptions_check() { - new_test_ext(3).execute_with(|| { - assert_eq!(Sassafras::authorities().len(), 3); - assert_eq!(Sassafras::config(), TEST_EPOCH_CONFIGURATION); - }); -} - -#[test] -fn post_genesis_randomness_initialization() { - let (pairs, mut ext) = new_test_ext_with_pairs(1, false); - let pair = &pairs[0]; - - ext.execute_with(|| { - assert_eq!(Sassafras::randomness(), [0; 32]); - assert_eq!(Sassafras::next_randomness(), [0; 32]); - assert_eq!(Sassafras::randomness_accumulator(), [0; 32]); - - // Test the values with a zero genesis block hash - let _ = initialize_block(1, 123.into(), [0x00; 32].into(), pair); - - assert_eq!(Sassafras::randomness(), [0; 32]); - println!("[DEBUG] {}", b2h(Sassafras::next_randomness())); - assert_eq!( - Sassafras::next_randomness(), - h2b("b9497550deeeb4adc134555930de61968a0558f8947041eb515b2f5fa68ffaf7") - ); - println!("[DEBUG] {}", b2h(Sassafras::randomness_accumulator())); - assert_eq!( - Sassafras::randomness_accumulator(), - h2b("febcc7fe9539fe17ed29f525831394edfb30b301755dc9bd91584a1f065faf87") - ); - let (id1, _) = make_ticket_bodies(1, Some(pair))[0]; - - // Reset what is relevant - NextRandomness::::set([0; 32]); - RandomnessAccumulator::::set([0; 32]); - - // Test the values with a non-zero genesis block hash - let _ = initialize_block(1, 123.into(), [0xff; 32].into(), pair); - - assert_eq!(Sassafras::randomness(), [0; 32]); - println!("[DEBUG] {}", b2h(Sassafras::next_randomness())); - assert_eq!( - Sassafras::next_randomness(), - h2b("51c1e3b3a73d2043b3cabae98ff27bdd4aad8967c21ecda7b9465afaa0e70f37") - ); - println!("[DEBUG] {}", b2h(Sassafras::randomness_accumulator())); - assert_eq!( - Sassafras::randomness_accumulator(), - h2b("466bf3007f2e17bffee0b3c42c90f33d654f5ff61eff28b0cc650825960abd52") - ); - let (id2, _) = make_ticket_bodies(1, Some(pair))[0]; - - // Ticket ids should be different when next epoch randomness is different - assert_ne!(id1, id2); - - // Reset what is relevant - NextRandomness::::set([0; 32]); - RandomnessAccumulator::::set([0; 32]); - - // Test the values with a non-zero genesis block hash - let _ = initialize_block(1, 321.into(), [0x00; 32].into(), pair); - - println!("[DEBUG] {}", b2h(Sassafras::next_randomness())); - assert_eq!( - Sassafras::next_randomness(), - h2b("d85d84a54f79453000eb62e8a17b30149bd728d3232bc2787a89d51dc9a36008") - ); - println!("[DEBUG] {}", b2h(Sassafras::randomness_accumulator())); - assert_eq!( - Sassafras::randomness_accumulator(), - h2b("8a035eed02b5b8642b1515ed19752df8df156627aea45c4ef6e3efa88be9a74d") - ); - let (id2, _) = make_ticket_bodies(1, Some(pair))[0]; - - // Ticket ids should be different when next epoch randomness is different - assert_ne!(id1, id2); - }); -} - -// Tests if the sorted tickets are assigned to each slot outside-in. -#[test] -fn slot_ticket_id_outside_in_fetch() { - let genesis_slot = Slot::from(100); - let tickets_count = 6; - - // Current epoch tickets - let curr_tickets: Vec = (0..tickets_count).map(|i| i as TicketId).collect(); - - // Next epoch tickets - let next_tickets: Vec = - (0..tickets_count - 1).map(|i| (i + tickets_count) as TicketId).collect(); - - new_test_ext(0).execute_with(|| { - // Some corner cases - TicketsIds::::insert((0, 0_u32), 1_u128); - - // Cleanup - (0..3).for_each(|i| TicketsIds::::remove((0, i as u32))); - - curr_tickets - .iter() - .enumerate() - .for_each(|(i, id)| TicketsIds::::insert((0, i as u32), id)); - - next_tickets - .iter() - .enumerate() - .for_each(|(i, id)| TicketsIds::::insert((1, i as u32), id)); - - TicketsMeta::::set(TicketsMetadata { - tickets_count: [curr_tickets.len() as u32, next_tickets.len() as u32], - unsorted_tickets_count: 0, - }); - - // Before importing the first block the pallet always return `None` - // This is a kind of special hardcoded case that should never happen in practice - // as the first thing the pallet does is to initialize the genesis slot. - - assert_eq!(Sassafras::slot_ticket_id(0.into()), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 0), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 1), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 100), None); - - // Initialize genesis slot.. - GenesisSlot::::set(genesis_slot); - frame_system::Pallet::::set_block_number(One::one()); - - // Try to fetch a ticket for a slot before current epoch. - assert_eq!(Sassafras::slot_ticket_id(0.into()), None); - - // Current epoch tickets. - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 0), Some(curr_tickets[1])); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 1), Some(curr_tickets[3])); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 2), Some(curr_tickets[5])); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 3), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 4), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 5), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 6), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 7), Some(curr_tickets[4])); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 8), Some(curr_tickets[2])); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 9), Some(curr_tickets[0])); - - // Next epoch tickets (note that only 5 tickets are available) - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 10), Some(next_tickets[1])); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 11), Some(next_tickets[3])); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 12), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 13), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 14), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 15), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 16), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 17), Some(next_tickets[4])); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 18), Some(next_tickets[2])); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 19), Some(next_tickets[0])); - - // Try to fetch the tickets for slots beyond the next epoch. - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 20), None); - assert_eq!(Sassafras::slot_ticket_id(genesis_slot + 42), None); - }); -} - -// Different test for outside-in test with more focus on corner case correctness. -#[test] -fn slot_ticket_id_outside_in_fetch_corner_cases() { - new_test_ext(0).execute_with(|| { - frame_system::Pallet::::set_block_number(One::one()); - - let mut meta = TicketsMetadata { tickets_count: [0, 0], unsorted_tickets_count: 0 }; - let curr_epoch_idx = EpochIndex::::get(); - - let mut epoch_test = |epoch_idx| { - let tag = (epoch_idx & 1) as u8; - let epoch_start = Sassafras::epoch_start(epoch_idx); - - // cleanup - meta.tickets_count = [0, 0]; - TicketsMeta::::set(meta); - assert!((0..10).all(|i| Sassafras::slot_ticket_id((epoch_start + i).into()).is_none())); - - meta.tickets_count[tag as usize] += 1; - TicketsMeta::::set(meta); - TicketsIds::::insert((tag, 0_u32), 1_u128); - assert_eq!(Sassafras::slot_ticket_id((epoch_start + 9).into()), Some(1_u128)); - assert!((0..9).all(|i| Sassafras::slot_ticket_id((epoch_start + i).into()).is_none())); - - meta.tickets_count[tag as usize] += 1; - TicketsMeta::::set(meta); - TicketsIds::::insert((tag, 1_u32), 2_u128); - assert_eq!(Sassafras::slot_ticket_id((epoch_start + 0).into()), Some(2_u128)); - assert!((1..9).all(|i| Sassafras::slot_ticket_id((epoch_start + i).into()).is_none())); - - meta.tickets_count[tag as usize] += 2; - TicketsMeta::::set(meta); - TicketsIds::::insert((tag, 2_u32), 3_u128); - assert_eq!(Sassafras::slot_ticket_id((epoch_start + 8).into()), Some(3_u128)); - assert!((1..8).all(|i| Sassafras::slot_ticket_id((epoch_start + i).into()).is_none())); - }; - - // Even epoch - epoch_test(curr_epoch_idx); - epoch_test(curr_epoch_idx + 1); - }); -} - -#[test] -fn on_first_block_after_genesis() { - let (pairs, mut ext) = new_test_ext_with_pairs(4, false); - - ext.execute_with(|| { - let start_slot = Slot::from(100); - let start_block = 1; - - let digest = initialize_block(start_block, start_slot, Default::default(), &pairs[0]); - - let common_assertions = || { - assert_eq!(Sassafras::genesis_slot(), start_slot); - assert_eq!(Sassafras::current_slot(), start_slot); - assert_eq!(Sassafras::epoch_index(), 0); - assert_eq!(Sassafras::current_epoch_start(), start_slot); - assert_eq!(Sassafras::current_slot_index(), 0); - assert_eq!(Sassafras::randomness(), [0; 32]); - println!("[DEBUG] {}", b2h(Sassafras::next_randomness())); - assert_eq!( - Sassafras::next_randomness(), - h2b("a49592ef190b96f3eb87bde4c8355e33df28c75006156e8c81998158de2ed49e") - ); - }; - - // Post-initialization status - - assert!(ClaimTemporaryData::::exists()); - common_assertions(); - println!("[DEBUG] {}", b2h(Sassafras::randomness_accumulator())); - assert_eq!( - Sassafras::randomness_accumulator(), - h2b("f0d42f6b7c0d157ecbd788be44847b80a96c290c04b5dfa5d1d40c98aa0c04ed") - ); - - let header = finalize_block(start_block); - - // Post-finalization status - - assert!(!ClaimTemporaryData::::exists()); - common_assertions(); - println!("[DEBUG] {}", b2h(Sassafras::randomness_accumulator())); - assert_eq!( - Sassafras::randomness_accumulator(), - h2b("9f2b9fd19a772c34d437dcd8b84a927e73a5cb43d3d1cd00093223d60d2b4843"), - ); - - // Header data check - - assert_eq!(header.digest.logs.len(), 2); - assert_eq!(header.digest.logs[0], digest.logs[0]); - - // Genesis epoch start deposits consensus - let consensus_log = sp_consensus_sassafras::digests::ConsensusLog::NextEpochData( - sp_consensus_sassafras::digests::NextEpochDescriptor { - authorities: Sassafras::next_authorities().into_inner(), - randomness: Sassafras::next_randomness(), - config: None, - }, - ); - let consensus_digest = DigestItem::Consensus(SASSAFRAS_ENGINE_ID, consensus_log.encode()); - assert_eq!(header.digest.logs[1], consensus_digest) - }) -} - -#[test] -fn on_normal_block() { - let (pairs, mut ext) = new_test_ext_with_pairs(4, false); - let start_slot = Slot::from(100); - let start_block = 1; - let end_block = start_block + 1; - - ext.execute_with(|| { - initialize_block(start_block, start_slot, Default::default(), &pairs[0]); - - // We don't want to trigger an epoch change in this test. - let epoch_length = Sassafras::epoch_length() as u64; - assert!(epoch_length > end_block); - - // Progress to block 2 - let digest = progress_to_block(end_block, &pairs[0]).unwrap(); - - let common_assertions = || { - assert_eq!(Sassafras::genesis_slot(), start_slot); - assert_eq!(Sassafras::current_slot(), start_slot + 1); - assert_eq!(Sassafras::epoch_index(), 0); - assert_eq!(Sassafras::current_epoch_start(), start_slot); - assert_eq!(Sassafras::current_slot_index(), 1); - assert_eq!(Sassafras::randomness(), [0; 32]); - println!("[DEBUG] {}", b2h(Sassafras::next_randomness())); - assert_eq!( - Sassafras::next_randomness(), - h2b("a49592ef190b96f3eb87bde4c8355e33df28c75006156e8c81998158de2ed49e") - ); - }; - - // Post-initialization status - - assert!(ClaimTemporaryData::::exists()); - common_assertions(); - println!("[DEBUG] {}", b2h(Sassafras::randomness_accumulator())); - assert_eq!( - Sassafras::randomness_accumulator(), - h2b("9f2b9fd19a772c34d437dcd8b84a927e73a5cb43d3d1cd00093223d60d2b4843"), - ); - - let header = finalize_block(end_block); - - // Post-finalization status - - assert!(!ClaimTemporaryData::::exists()); - common_assertions(); - assert_eq!( - Sassafras::randomness_accumulator(), - h2b("be9261adb9686dfd3f23f8a276b7acc7f4beb3137070beb64c282ac22d84cbf0"), - ); - - // Header data check - - assert_eq!(header.digest.logs.len(), 1); - assert_eq!(header.digest.logs[0], digest.logs[0]); - }); -} - -#[test] -fn produce_epoch_change_digest_no_config() { - let (pairs, mut ext) = new_test_ext_with_pairs(4, false); - - ext.execute_with(|| { - let start_slot = Slot::from(100); - let start_block = 1; - - initialize_block(start_block, start_slot, Default::default(), &pairs[0]); - - // We want to trigger an epoch change in this test. - let epoch_length = Sassafras::epoch_length() as u64; - let end_block = start_block + epoch_length; - - let digest = progress_to_block(end_block, &pairs[0]).unwrap(); - - let common_assertions = || { - assert_eq!(Sassafras::genesis_slot(), start_slot); - assert_eq!(Sassafras::current_slot(), start_slot + epoch_length); - assert_eq!(Sassafras::epoch_index(), 1); - assert_eq!(Sassafras::current_epoch_start(), start_slot + epoch_length); - assert_eq!(Sassafras::current_slot_index(), 0); - println!("[DEBUG] {}", b2h(Sassafras::randomness())); - assert_eq!( - Sassafras::randomness(), - h2b("a49592ef190b96f3eb87bde4c8355e33df28c75006156e8c81998158de2ed49e") - ); - }; - - // Post-initialization status - - assert!(ClaimTemporaryData::::exists()); - common_assertions(); - println!("[DEBUG] {}", b2h(Sassafras::next_randomness())); - assert_eq!( - Sassafras::next_randomness(), - h2b("d3a18b857af6ecc7b52f047107e684fff0058b5722d540a296d727e37eaa55b3"), - ); - println!("[DEBUG] {}", b2h(Sassafras::randomness_accumulator())); - assert_eq!( - Sassafras::randomness_accumulator(), - h2b("bf0f1228f4ff953c8c1bda2cceb668bf86ea05d7ae93e26d021c9690995d5279"), - ); - - let header = finalize_block(end_block); - - // Post-finalization status - - assert!(!ClaimTemporaryData::::exists()); - common_assertions(); - println!("[DEBUG] {}", b2h(Sassafras::next_randomness())); - assert_eq!( - Sassafras::next_randomness(), - h2b("d3a18b857af6ecc7b52f047107e684fff0058b5722d540a296d727e37eaa55b3"), - ); - println!("[DEBUG] {}", b2h(Sassafras::randomness_accumulator())); - assert_eq!( - Sassafras::randomness_accumulator(), - h2b("8a1ceb346036c386d021264b10912c8b656799668004c4a487222462b394cd89"), - ); - - // Header data check - - assert_eq!(header.digest.logs.len(), 2); - assert_eq!(header.digest.logs[0], digest.logs[0]); - // Deposits consensus log on epoch change - let consensus_log = sp_consensus_sassafras::digests::ConsensusLog::NextEpochData( - sp_consensus_sassafras::digests::NextEpochDescriptor { - authorities: Sassafras::next_authorities().into_inner(), - randomness: Sassafras::next_randomness(), - config: None, - }, - ); - let consensus_digest = DigestItem::Consensus(SASSAFRAS_ENGINE_ID, consensus_log.encode()); - assert_eq!(header.digest.logs[1], consensus_digest) - }) -} - -#[test] -fn produce_epoch_change_digest_with_config() { - let (pairs, mut ext) = new_test_ext_with_pairs(4, false); - - ext.execute_with(|| { - let start_slot = Slot::from(100); - let start_block = 1; - - initialize_block(start_block, start_slot, Default::default(), &pairs[0]); - - let config = EpochConfiguration { redundancy_factor: 1, attempts_number: 123 }; - Sassafras::plan_config_change(RuntimeOrigin::root(), config).unwrap(); - - // We want to trigger an epoch change in this test. - let epoch_length = Sassafras::epoch_length() as u64; - let end_block = start_block + epoch_length; - - let digest = progress_to_block(end_block, &pairs[0]).unwrap(); - - let header = finalize_block(end_block); - - // Header data check. - // Skip pallet status checks that were already performed by other tests. - - assert_eq!(header.digest.logs.len(), 2); - assert_eq!(header.digest.logs[0], digest.logs[0]); - // Deposits consensus log on epoch change - let consensus_log = sp_consensus_sassafras::digests::ConsensusLog::NextEpochData( - sp_consensus_sassafras::digests::NextEpochDescriptor { - authorities: Sassafras::next_authorities().into_inner(), - randomness: Sassafras::next_randomness(), - config: Some(config), - }, - ); - let consensus_digest = DigestItem::Consensus(SASSAFRAS_ENGINE_ID, consensus_log.encode()); - assert_eq!(header.digest.logs[1], consensus_digest) - }) -} - -#[test] -fn segments_incremental_sort_works() { - let (pairs, mut ext) = new_test_ext_with_pairs(1, false); - let pair = &pairs[0]; - let segments_count = 14; - let start_slot = Slot::from(100); - let start_block = 1; - - ext.execute_with(|| { - let epoch_length = Sassafras::epoch_length() as u64; - // -3 just to have the last segment not full... - let submitted_tickets_count = segments_count * SEGMENT_MAX_SIZE - 3; - - initialize_block(start_block, start_slot, Default::default(), pair); - - // Manually populate the segments to skip the threshold check - let mut tickets = make_ticket_bodies(submitted_tickets_count, None); - persist_next_epoch_tickets_as_segments(&tickets); - - // Proceed to half of the epoch (sortition should not have been started yet) - let half_epoch_block = start_block + epoch_length / 2; - progress_to_block(half_epoch_block, pair); - - let mut unsorted_tickets_count = submitted_tickets_count; - - // Check that next epoch tickets sortition is not started yet - let meta = TicketsMeta::::get(); - assert_eq!(meta.unsorted_tickets_count, unsorted_tickets_count); - assert_eq!(meta.tickets_count, [0, 0]); - - // Follow the incremental sortition block by block - - progress_to_block(half_epoch_block + 1, pair); - unsorted_tickets_count -= 3 * SEGMENT_MAX_SIZE - 3; - let meta = TicketsMeta::::get(); - assert_eq!(meta.unsorted_tickets_count, unsorted_tickets_count,); - assert_eq!(meta.tickets_count, [0, 0]); - - progress_to_block(half_epoch_block + 2, pair); - unsorted_tickets_count -= 3 * SEGMENT_MAX_SIZE; - let meta = TicketsMeta::::get(); - assert_eq!(meta.unsorted_tickets_count, unsorted_tickets_count); - assert_eq!(meta.tickets_count, [0, 0]); - - progress_to_block(half_epoch_block + 3, pair); - unsorted_tickets_count -= 3 * SEGMENT_MAX_SIZE; - let meta = TicketsMeta::::get(); - assert_eq!(meta.unsorted_tickets_count, unsorted_tickets_count); - assert_eq!(meta.tickets_count, [0, 0]); - - progress_to_block(half_epoch_block + 4, pair); - unsorted_tickets_count -= 3 * SEGMENT_MAX_SIZE; - let meta = TicketsMeta::::get(); - assert_eq!(meta.unsorted_tickets_count, unsorted_tickets_count); - assert_eq!(meta.tickets_count, [0, 0]); - - let header = finalize_block(half_epoch_block + 4); - - // Sort should be finished now. - // Check that next epoch tickets count have the correct value. - // Bigger ticket ids were discarded during sortition. - unsorted_tickets_count -= 2 * SEGMENT_MAX_SIZE; - assert_eq!(unsorted_tickets_count, 0); - let meta = TicketsMeta::::get(); - assert_eq!(meta.unsorted_tickets_count, unsorted_tickets_count); - assert_eq!(meta.tickets_count, [0, epoch_length as u32]); - // Epoch change log should have been pushed as well - assert_eq!(header.digest.logs.len(), 1); - // No tickets for the current epoch - assert_eq!(TicketsIds::::get((0, 0)), None); - - // Check persistence of "winning" tickets - tickets.sort_by_key(|t| t.0); - (0..epoch_length as usize).into_iter().for_each(|i| { - let id = TicketsIds::::get((1, i as u32)).unwrap(); - let body = TicketsData::::get(id).unwrap(); - assert_eq!((id, body), tickets[i]); - }); - // Check removal of "loosing" tickets - (epoch_length as usize..tickets.len()).into_iter().for_each(|i| { - assert!(TicketsIds::::get((1, i as u32)).is_none()); - assert!(TicketsData::::get(tickets[i].0).is_none()); - }); - - // The next block will be the first produced on the new epoch. - // At this point the tickets are found already sorted and ready to be used. - let slot = Sassafras::current_slot() + 1; - let number = System::block_number() + 1; - initialize_block(number, slot, header.hash(), pair); - let header = finalize_block(number); - // Epoch changes digest is also produced - assert_eq!(header.digest.logs.len(), 2); - }); -} - -#[test] -fn tickets_fetch_works_after_epoch_change() { - let (pairs, mut ext) = new_test_ext_with_pairs(4, false); - let pair = &pairs[0]; - let start_slot = Slot::from(100); - let start_block = 1; - let submitted_tickets = 300; - - ext.execute_with(|| { - initialize_block(start_block, start_slot, Default::default(), pair); - - // We don't want to trigger an epoch change in this test. - let epoch_length = Sassafras::epoch_length() as u64; - assert!(epoch_length > 2); - progress_to_block(2, &pairs[0]).unwrap(); - - // Persist tickets as three different segments. - let tickets = make_ticket_bodies(submitted_tickets, None); - persist_next_epoch_tickets_as_segments(&tickets); - - let meta = TicketsMeta::::get(); - assert_eq!(meta.unsorted_tickets_count, submitted_tickets); - assert_eq!(meta.tickets_count, [0, 0]); - - // Progress up to the last epoch slot (do not enact epoch change) - progress_to_block(epoch_length, &pairs[0]).unwrap(); - - // At this point next epoch tickets should have been sorted and ready to be used - let meta = TicketsMeta::::get(); - assert_eq!(meta.unsorted_tickets_count, 0); - assert_eq!(meta.tickets_count, [0, epoch_length as u32]); - - // Compute and sort the tickets ids (aka tickets scores) - let mut expected_ids: Vec<_> = tickets.into_iter().map(|(id, _)| id).collect(); - expected_ids.sort(); - expected_ids.truncate(epoch_length as usize); - - // Check if we can fetch next epoch tickets ids (outside-in). - let slot = Sassafras::current_slot(); - assert_eq!(Sassafras::slot_ticket_id(slot + 1).unwrap(), expected_ids[1]); - assert_eq!(Sassafras::slot_ticket_id(slot + 2).unwrap(), expected_ids[3]); - assert_eq!(Sassafras::slot_ticket_id(slot + 3).unwrap(), expected_ids[5]); - assert_eq!(Sassafras::slot_ticket_id(slot + 4).unwrap(), expected_ids[7]); - assert_eq!(Sassafras::slot_ticket_id(slot + 7).unwrap(), expected_ids[6]); - assert_eq!(Sassafras::slot_ticket_id(slot + 8).unwrap(), expected_ids[4]); - assert_eq!(Sassafras::slot_ticket_id(slot + 9).unwrap(), expected_ids[2]); - assert_eq!(Sassafras::slot_ticket_id(slot + 10).unwrap(), expected_ids[0]); - assert!(Sassafras::slot_ticket_id(slot + 11).is_none()); - - // Enact epoch change by progressing one more block - - progress_to_block(epoch_length + 1, &pairs[0]).unwrap(); - - let meta = TicketsMeta::::get(); - assert_eq!(meta.unsorted_tickets_count, 0); - assert_eq!(meta.tickets_count, [0, 10]); - - // Check if we can fetch current epoch tickets ids (outside-in). - let slot = Sassafras::current_slot(); - assert_eq!(Sassafras::slot_ticket_id(slot).unwrap(), expected_ids[1]); - assert_eq!(Sassafras::slot_ticket_id(slot + 1).unwrap(), expected_ids[3]); - assert_eq!(Sassafras::slot_ticket_id(slot + 2).unwrap(), expected_ids[5]); - assert_eq!(Sassafras::slot_ticket_id(slot + 3).unwrap(), expected_ids[7]); - assert_eq!(Sassafras::slot_ticket_id(slot + 6).unwrap(), expected_ids[6]); - assert_eq!(Sassafras::slot_ticket_id(slot + 7).unwrap(), expected_ids[4]); - assert_eq!(Sassafras::slot_ticket_id(slot + 8).unwrap(), expected_ids[2]); - assert_eq!(Sassafras::slot_ticket_id(slot + 9).unwrap(), expected_ids[0]); - assert!(Sassafras::slot_ticket_id(slot + 10).is_none()); - - // Enact another epoch change, for which we don't have any ticket - progress_to_block(2 * epoch_length + 1, &pairs[0]).unwrap(); - let meta = TicketsMeta::::get(); - assert_eq!(meta.unsorted_tickets_count, 0); - assert_eq!(meta.tickets_count, [0, 0]); - }); -} - -#[test] -fn block_allowed_to_skip_epochs() { - let (pairs, mut ext) = new_test_ext_with_pairs(4, false); - let pair = &pairs[0]; - let start_slot = Slot::from(100); - let start_block = 1; - - ext.execute_with(|| { - let epoch_length = Sassafras::epoch_length() as u64; - - initialize_block(start_block, start_slot, Default::default(), pair); - - let tickets = make_ticket_bodies(3, Some(pair)); - persist_next_epoch_tickets(&tickets); - - let next_random = Sassafras::next_randomness(); - - // We want to skip 3 epochs in this test. - let offset = 4 * epoch_length; - go_to_block(start_block + offset, start_slot + offset, &pairs[0]); - - // Post-initialization status - - assert!(ClaimTemporaryData::::exists()); - assert_eq!(Sassafras::genesis_slot(), start_slot); - assert_eq!(Sassafras::current_slot(), start_slot + offset); - assert_eq!(Sassafras::epoch_index(), 4); - assert_eq!(Sassafras::current_epoch_start(), start_slot + offset); - assert_eq!(Sassafras::current_slot_index(), 0); - - // Tickets data has been discarded - assert_eq!(TicketsMeta::::get(), TicketsMetadata::default()); - assert!(tickets.iter().all(|(id, _)| TicketsData::::get(id).is_none())); - assert_eq!(SortedCandidates::::get().len(), 0); - - // We used the last known next epoch randomness as a fallback - assert_eq!(next_random, Sassafras::randomness()); - }); -} - -#[test] -fn obsolete_tickets_are_removed_on_epoch_change() { - let (pairs, mut ext) = new_test_ext_with_pairs(4, false); - let pair = &pairs[0]; - let start_slot = Slot::from(100); - let start_block = 1; - - ext.execute_with(|| { - let epoch_length = Sassafras::epoch_length() as u64; - - initialize_block(start_block, start_slot, Default::default(), pair); - - let tickets = make_ticket_bodies(10, Some(pair)); - let mut epoch1_tickets = tickets[..4].to_vec(); - let mut epoch2_tickets = tickets[4..].to_vec(); - - // Persist some tickets for next epoch (N) - persist_next_epoch_tickets(&epoch1_tickets); - assert_eq!(TicketsMeta::::get().tickets_count, [0, 4]); - // Check next epoch tickets presence - epoch1_tickets.sort_by_key(|t| t.0); - (0..epoch1_tickets.len()).into_iter().for_each(|i| { - let id = TicketsIds::::get((1, i as u32)).unwrap(); - let body = TicketsData::::get(id).unwrap(); - assert_eq!((id, body), epoch1_tickets[i]); - }); - - // Advance one epoch to enact the tickets - go_to_block(start_block + epoch_length, start_slot + epoch_length, pair); - assert_eq!(TicketsMeta::::get().tickets_count, [0, 4]); - - // Persist some tickets for next epoch (N+1) - persist_next_epoch_tickets(&epoch2_tickets); - assert_eq!(TicketsMeta::::get().tickets_count, [6, 4]); - epoch2_tickets.sort_by_key(|t| t.0); - // Check for this epoch and next epoch tickets presence - (0..epoch1_tickets.len()).into_iter().for_each(|i| { - let id = TicketsIds::::get((1, i as u32)).unwrap(); - let body = TicketsData::::get(id).unwrap(); - assert_eq!((id, body), epoch1_tickets[i]); - }); - (0..epoch2_tickets.len()).into_iter().for_each(|i| { - let id = TicketsIds::::get((0, i as u32)).unwrap(); - let body = TicketsData::::get(id).unwrap(); - assert_eq!((id, body), epoch2_tickets[i]); - }); - - // Advance to epoch 2 and check for cleanup - - go_to_block(start_block + 2 * epoch_length, start_slot + 2 * epoch_length, pair); - assert_eq!(TicketsMeta::::get().tickets_count, [6, 0]); - - (0..epoch1_tickets.len()).into_iter().for_each(|i| { - let id = TicketsIds::::get((1, i as u32)).unwrap(); - assert!(TicketsData::::get(id).is_none()); - }); - (0..epoch2_tickets.len()).into_iter().for_each(|i| { - let id = TicketsIds::::get((0, i as u32)).unwrap(); - let body = TicketsData::::get(id).unwrap(); - assert_eq!((id, body), epoch2_tickets[i]); - }); - }) -} - -const TICKETS_FILE: &str = "src/data/25_tickets_100_auths.bin"; - -fn data_read(filename: &str) -> T { - use std::{fs::File, io::Read}; - let mut file = File::open(filename).unwrap(); - let mut buf = Vec::new(); - file.read_to_end(&mut buf).unwrap(); - T::decode(&mut &buf[..]).unwrap() -} - -fn data_write(filename: &str, data: T) { - use std::{fs::File, io::Write}; - let mut file = File::create(filename).unwrap(); - let buf = data.encode(); - file.write_all(&buf).unwrap(); -} - -// We don't want to implement anything secure here. -// Just a trivial shuffle for the tests. -fn trivial_fisher_yates_shuffle(vector: &mut Vec, random_seed: u64) { - let mut rng = random_seed as usize; - for i in (1..vector.len()).rev() { - let j = rng % (i + 1); - vector.swap(i, j); - rng = (rng.wrapping_mul(6364793005) + 1) as usize; // Some random number generation - } -} - -// For this test we use a set of pre-constructed tickets from a file. -// Creating a large set of tickets on the fly takes time, and may be annoying -// for test execution. -// -// A valid ring-context is required for this test since we are passing through the -// `submit_ticket` call which tests for ticket validity. -#[test] -fn submit_tickets_with_ring_proof_check_works() { - use sp_core::Pair as _; - // env_logger::init(); - - let (authorities, mut tickets): (Vec, Vec) = - data_read(TICKETS_FILE); - - // Also checks that duplicates are discarded - tickets.extend(tickets.clone()); - trivial_fisher_yates_shuffle(&mut tickets, 321); - - let (pairs, mut ext) = new_test_ext_with_pairs(authorities.len(), true); - let pair = &pairs[0]; - // Check if deserialized data has been generated for the correct set of authorities... - assert!(authorities.iter().zip(pairs.iter()).all(|(auth, pair)| auth == &pair.public())); - - ext.execute_with(|| { - let start_slot = Slot::from(0); - let start_block = 1; - - // Tweak the config to discard ~half of the tickets. - let mut config = EpochConfig::::get(); - config.redundancy_factor = 25; - EpochConfig::::set(config); - - initialize_block(start_block, start_slot, Default::default(), pair); - NextRandomness::::set([0; 32]); - - // Check state before tickets submission - assert_eq!( - TicketsMeta::::get(), - TicketsMetadata { unsorted_tickets_count: 0, tickets_count: [0, 0] }, - ); - - // Submit the tickets - let max_tickets_per_call = Sassafras::epoch_length() as usize; - tickets.chunks(max_tickets_per_call).for_each(|chunk| { - let chunk = BoundedVec::truncate_from(chunk.to_vec()); - Sassafras::submit_tickets(RuntimeOrigin::none(), chunk).unwrap(); - }); - - // Check state after submission - assert_eq!( - TicketsMeta::::get(), - TicketsMetadata { unsorted_tickets_count: 16, tickets_count: [0, 0] }, - ); - assert_eq!(UnsortedSegments::::get(0).len(), 16); - assert_eq!(UnsortedSegments::::get(1).len(), 0); - - finalize_block(start_block); - }) -} - -#[test] -#[ignore = "test tickets data generator"] -fn make_tickets_data() { - use super::*; - use sp_core::crypto::Pair; - - // Number of authorities who produces tickets (for the sake of this test) - let tickets_authors_count = 5; - // Total number of authorities (the ring) - let authorities_count = 100; - let (pairs, mut ext) = new_test_ext_with_pairs(authorities_count, true); - - let authorities: Vec<_> = pairs.iter().map(|sk| sk.public()).collect(); - - ext.execute_with(|| { - let config = EpochConfig::::get(); - - let tickets_count = tickets_authors_count * config.attempts_number as usize; - let mut tickets = Vec::with_capacity(tickets_count); - - // Construct pre-built tickets with a well known `NextRandomness` value. - NextRandomness::::set([0; 32]); - - println!("Constructing {} tickets", tickets_count); - pairs.iter().take(tickets_authors_count).enumerate().for_each(|(i, pair)| { - let t = make_tickets(config.attempts_number, pair); - tickets.extend(t); - println!("{:.2}%", 100f32 * ((i + 1) as f32 / tickets_authors_count as f32)); - }); - - data_write(TICKETS_FILE, (authorities, tickets)); - }); -} diff --git a/substrate/frame/sassafras/src/weights.rs b/substrate/frame/sassafras/src/weights.rs deleted file mode 100644 index 32ea2d29a18..00000000000 --- a/substrate/frame/sassafras/src/weights.rs +++ /dev/null @@ -1,425 +0,0 @@ -// 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. - -//! Autogenerated weights for `pallet_sassafras` -//! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-11-16, STEPS: `20`, REPEAT: `3`, LOW RANGE: `[]`, HIGH RANGE: `[]` -//! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `behemoth`, CPU: `AMD Ryzen Threadripper 3970X 32-Core Processor` -//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` - -// Executed Command: -// ./target/release/node-template -// benchmark -// pallet -// --chain -// dev -// --pallet -// pallet_sassafras -// --extrinsic -// * -// --steps -// 20 -// --repeat -// 3 -// --output -// weights.rs -// --template -// substrate/.maintain/frame-weight-template.hbs - -#![cfg_attr(rustfmt, rustfmt_skip)] -#![allow(unused_parens)] -#![allow(unused_imports)] -#![allow(missing_docs)] - -use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; -use core::marker::PhantomData; - -/// Weight functions needed for `pallet_sassafras`. -pub trait WeightInfo { - fn on_initialize() -> Weight; - fn enact_epoch_change(x: u32, y: u32, ) -> Weight; - fn submit_tickets(x: u32, ) -> Weight; - fn plan_config_change() -> Weight; - fn update_ring_verifier(x: u32, ) -> Weight; - fn load_ring_context() -> Weight; - fn sort_segments(x: u32, ) -> Weight; -} - -/// Weights for `pallet_sassafras` using the Substrate node and recommended hardware. -pub struct SubstrateWeight(PhantomData); -impl WeightInfo for SubstrateWeight { - /// Storage: `System::Digest` (r:1 w:1) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `Sassafras::NextRandomness` (r:1 w:0) - /// Proof: `Sassafras::NextRandomness` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextAuthorities` (r:1 w:0) - /// Proof: `Sassafras::NextAuthorities` (`max_values`: Some(1), `max_size`: Some(3302), added: 3797, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::CurrentRandomness` (r:1 w:0) - /// Proof: `Sassafras::CurrentRandomness` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::EpochIndex` (r:1 w:0) - /// Proof: `Sassafras::EpochIndex` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::RandomnessAccumulator` (r:1 w:1) - /// Proof: `Sassafras::RandomnessAccumulator` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::CurrentSlot` (r:0 w:1) - /// Proof: `Sassafras::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::ClaimTemporaryData` (r:0 w:1) - /// Proof: `Sassafras::ClaimTemporaryData` (`max_values`: Some(1), `max_size`: Some(33), added: 528, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::GenesisSlot` (r:0 w:1) - /// Proof: `Sassafras::GenesisSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - fn on_initialize() -> Weight { - // Proof Size summary in bytes: - // Measured: `302` - // Estimated: `4787` - // Minimum execution time: 438_039_000 picoseconds. - Weight::from_parts(439_302_000, 4787) - .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().writes(5_u64)) - } - /// Storage: `Sassafras::CurrentSlot` (r:1 w:0) - /// Proof: `Sassafras::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::EpochIndex` (r:1 w:1) - /// Proof: `Sassafras::EpochIndex` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::GenesisSlot` (r:1 w:0) - /// Proof: `Sassafras::GenesisSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextAuthorities` (r:1 w:1) - /// Proof: `Sassafras::NextAuthorities` (`max_values`: Some(1), `max_size`: Some(3302), added: 3797, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::RingContext` (r:1 w:0) - /// Proof: `Sassafras::RingContext` (`max_values`: Some(1), `max_size`: Some(590324), added: 590819, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsMeta` (r:1 w:1) - /// Proof: `Sassafras::TicketsMeta` (`max_values`: Some(1), `max_size`: Some(12), added: 507, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextRandomness` (r:1 w:1) - /// Proof: `Sassafras::NextRandomness` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::RandomnessAccumulator` (r:1 w:0) - /// Proof: `Sassafras::RandomnessAccumulator` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextEpochConfig` (r:1 w:1) - /// Proof: `Sassafras::NextEpochConfig` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::PendingEpochConfigChange` (r:1 w:1) - /// Proof: `Sassafras::PendingEpochConfigChange` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `System::Digest` (r:1 w:1) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `Sassafras::SortedCandidates` (r:1 w:0) - /// Proof: `Sassafras::SortedCandidates` (`max_values`: Some(1), `max_size`: Some(3202), added: 3697, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::UnsortedSegments` (r:79 w:79) - /// Proof: `Sassafras::UnsortedSegments` (`max_values`: None, `max_size`: Some(2054), added: 4529, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsIds` (r:5000 w:200) - /// Proof: `Sassafras::TicketsIds` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::Authorities` (r:0 w:1) - /// Proof: `Sassafras::Authorities` (`max_values`: Some(1), `max_size`: Some(3302), added: 3797, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsData` (r:0 w:9896) - /// Proof: `Sassafras::TicketsData` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::RingVerifierData` (r:0 w:1) - /// Proof: `Sassafras::RingVerifierData` (`max_values`: Some(1), `max_size`: Some(388), added: 883, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::EpochConfig` (r:0 w:1) - /// Proof: `Sassafras::EpochConfig` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::CurrentRandomness` (r:0 w:1) - /// Proof: `Sassafras::CurrentRandomness` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// The range of component `x` is `[1, 100]`. - /// The range of component `y` is `[1000, 5000]`. - fn enact_epoch_change(x: u32, y: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `594909 + x * (33 ±0) + y * (53 ±0)` - // Estimated: `593350 + x * (24 ±1) + y * (2496 ±0)` - // Minimum execution time: 121_279_846_000 picoseconds. - Weight::from_parts(94_454_851_972, 593350) - // Standard Error: 24_177_301 - .saturating_add(Weight::from_parts(8_086_191, 0).saturating_mul(x.into())) - // Standard Error: 601_053 - .saturating_add(Weight::from_parts(15_578_413, 0).saturating_mul(y.into())) - .saturating_add(T::DbWeight::get().reads(13_u64)) - .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(y.into()))) - .saturating_add(T::DbWeight::get().writes(112_u64)) - .saturating_add(T::DbWeight::get().writes((2_u64).saturating_mul(y.into()))) - .saturating_add(Weight::from_parts(0, 24).saturating_mul(x.into())) - .saturating_add(Weight::from_parts(0, 2496).saturating_mul(y.into())) - } - /// Storage: `Sassafras::CurrentSlot` (r:1 w:0) - /// Proof: `Sassafras::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::EpochIndex` (r:1 w:0) - /// Proof: `Sassafras::EpochIndex` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::GenesisSlot` (r:1 w:0) - /// Proof: `Sassafras::GenesisSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::RingVerifierData` (r:1 w:0) - /// Proof: `Sassafras::RingVerifierData` (`max_values`: Some(1), `max_size`: Some(388), added: 883, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextAuthorities` (r:1 w:0) - /// Proof: `Sassafras::NextAuthorities` (`max_values`: Some(1), `max_size`: Some(3302), added: 3797, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextEpochConfig` (r:1 w:0) - /// Proof: `Sassafras::NextEpochConfig` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextRandomness` (r:1 w:0) - /// Proof: `Sassafras::NextRandomness` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsData` (r:25 w:25) - /// Proof: `Sassafras::TicketsData` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsMeta` (r:1 w:1) - /// Proof: `Sassafras::TicketsMeta` (`max_values`: Some(1), `max_size`: Some(12), added: 507, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::UnsortedSegments` (r:1 w:1) - /// Proof: `Sassafras::UnsortedSegments` (`max_values`: None, `max_size`: Some(2054), added: 4529, mode: `MaxEncodedLen`) - /// The range of component `x` is `[1, 25]`. - fn submit_tickets(x: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `3869` - // Estimated: `5519 + x * (2559 ±0)` - // Minimum execution time: 36_904_934_000 picoseconds. - Weight::from_parts(25_822_957_295, 5519) - // Standard Error: 11_047_832 - .saturating_add(Weight::from_parts(11_338_353_299, 0).saturating_mul(x.into())) - .saturating_add(T::DbWeight::get().reads(9_u64)) - .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(x.into()))) - .saturating_add(T::DbWeight::get().writes(2_u64)) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(x.into()))) - .saturating_add(Weight::from_parts(0, 2559).saturating_mul(x.into())) - } - /// Storage: `Sassafras::PendingEpochConfigChange` (r:0 w:1) - /// Proof: `Sassafras::PendingEpochConfigChange` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - fn plan_config_change() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 4_038_000 picoseconds. - Weight::from_parts(4_499_000, 0) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } - /// Storage: `Sassafras::RingContext` (r:1 w:0) - /// Proof: `Sassafras::RingContext` (`max_values`: Some(1), `max_size`: Some(590324), added: 590819, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::RingVerifierData` (r:0 w:1) - /// Proof: `Sassafras::RingVerifierData` (`max_values`: Some(1), `max_size`: Some(388), added: 883, mode: `MaxEncodedLen`) - /// The range of component `x` is `[1, 100]`. - fn update_ring_verifier(x: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `590485` - // Estimated: `591809` - // Minimum execution time: 105_121_424_000 picoseconds. - Weight::from_parts(105_527_334_385, 591809) - // Standard Error: 2_933_910 - .saturating_add(Weight::from_parts(96_136_261, 0).saturating_mul(x.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } - /// Storage: `Sassafras::RingContext` (r:1 w:0) - /// Proof: `Sassafras::RingContext` (`max_values`: Some(1), `max_size`: Some(590324), added: 590819, mode: `MaxEncodedLen`) - fn load_ring_context() -> Weight { - // Proof Size summary in bytes: - // Measured: `590485` - // Estimated: `591809` - // Minimum execution time: 44_005_681_000 picoseconds. - Weight::from_parts(44_312_079_000, 591809) - .saturating_add(T::DbWeight::get().reads(1_u64)) - } - /// Storage: `Sassafras::SortedCandidates` (r:1 w:0) - /// Proof: `Sassafras::SortedCandidates` (`max_values`: Some(1), `max_size`: Some(3202), added: 3697, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::UnsortedSegments` (r:100 w:100) - /// Proof: `Sassafras::UnsortedSegments` (`max_values`: None, `max_size`: Some(2054), added: 4529, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsIds` (r:0 w:200) - /// Proof: `Sassafras::TicketsIds` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsData` (r:0 w:12600) - /// Proof: `Sassafras::TicketsData` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) - /// The range of component `x` is `[1, 100]`. - fn sort_segments(x: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `222 + x * (2060 ±0)` - // Estimated: `4687 + x * (4529 ±0)` - // Minimum execution time: 183_501_000 picoseconds. - Weight::from_parts(183_501_000, 4687) - // Standard Error: 1_426_363 - .saturating_add(Weight::from_parts(169_156_241, 0).saturating_mul(x.into())) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(x.into()))) - .saturating_add(T::DbWeight::get().writes((129_u64).saturating_mul(x.into()))) - .saturating_add(Weight::from_parts(0, 4529).saturating_mul(x.into())) - } -} - -// For backwards compatibility and tests. -impl WeightInfo for () { - /// Storage: `System::Digest` (r:1 w:1) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `Sassafras::NextRandomness` (r:1 w:0) - /// Proof: `Sassafras::NextRandomness` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextAuthorities` (r:1 w:0) - /// Proof: `Sassafras::NextAuthorities` (`max_values`: Some(1), `max_size`: Some(3302), added: 3797, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::CurrentRandomness` (r:1 w:0) - /// Proof: `Sassafras::CurrentRandomness` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::EpochIndex` (r:1 w:0) - /// Proof: `Sassafras::EpochIndex` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::RandomnessAccumulator` (r:1 w:1) - /// Proof: `Sassafras::RandomnessAccumulator` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::CurrentSlot` (r:0 w:1) - /// Proof: `Sassafras::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::ClaimTemporaryData` (r:0 w:1) - /// Proof: `Sassafras::ClaimTemporaryData` (`max_values`: Some(1), `max_size`: Some(33), added: 528, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::GenesisSlot` (r:0 w:1) - /// Proof: `Sassafras::GenesisSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - fn on_initialize() -> Weight { - // Proof Size summary in bytes: - // Measured: `302` - // Estimated: `4787` - // Minimum execution time: 438_039_000 picoseconds. - Weight::from_parts(439_302_000, 4787) - .saturating_add(RocksDbWeight::get().reads(6_u64)) - .saturating_add(RocksDbWeight::get().writes(5_u64)) - } - /// Storage: `Sassafras::CurrentSlot` (r:1 w:0) - /// Proof: `Sassafras::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::EpochIndex` (r:1 w:1) - /// Proof: `Sassafras::EpochIndex` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::GenesisSlot` (r:1 w:0) - /// Proof: `Sassafras::GenesisSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextAuthorities` (r:1 w:1) - /// Proof: `Sassafras::NextAuthorities` (`max_values`: Some(1), `max_size`: Some(3302), added: 3797, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::RingContext` (r:1 w:0) - /// Proof: `Sassafras::RingContext` (`max_values`: Some(1), `max_size`: Some(590324), added: 590819, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsMeta` (r:1 w:1) - /// Proof: `Sassafras::TicketsMeta` (`max_values`: Some(1), `max_size`: Some(12), added: 507, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextRandomness` (r:1 w:1) - /// Proof: `Sassafras::NextRandomness` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::RandomnessAccumulator` (r:1 w:0) - /// Proof: `Sassafras::RandomnessAccumulator` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextEpochConfig` (r:1 w:1) - /// Proof: `Sassafras::NextEpochConfig` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::PendingEpochConfigChange` (r:1 w:1) - /// Proof: `Sassafras::PendingEpochConfigChange` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `System::Digest` (r:1 w:1) - /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) - /// Storage: `Sassafras::SortedCandidates` (r:1 w:0) - /// Proof: `Sassafras::SortedCandidates` (`max_values`: Some(1), `max_size`: Some(3202), added: 3697, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::UnsortedSegments` (r:79 w:79) - /// Proof: `Sassafras::UnsortedSegments` (`max_values`: None, `max_size`: Some(2054), added: 4529, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsIds` (r:5000 w:200) - /// Proof: `Sassafras::TicketsIds` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::Authorities` (r:0 w:1) - /// Proof: `Sassafras::Authorities` (`max_values`: Some(1), `max_size`: Some(3302), added: 3797, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsData` (r:0 w:9896) - /// Proof: `Sassafras::TicketsData` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::RingVerifierData` (r:0 w:1) - /// Proof: `Sassafras::RingVerifierData` (`max_values`: Some(1), `max_size`: Some(388), added: 883, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::EpochConfig` (r:0 w:1) - /// Proof: `Sassafras::EpochConfig` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::CurrentRandomness` (r:0 w:1) - /// Proof: `Sassafras::CurrentRandomness` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// The range of component `x` is `[1, 100]`. - /// The range of component `y` is `[1000, 5000]`. - fn enact_epoch_change(x: u32, y: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `594909 + x * (33 ±0) + y * (53 ±0)` - // Estimated: `593350 + x * (24 ±1) + y * (2496 ±0)` - // Minimum execution time: 121_279_846_000 picoseconds. - Weight::from_parts(94_454_851_972, 593350) - // Standard Error: 24_177_301 - .saturating_add(Weight::from_parts(8_086_191, 0).saturating_mul(x.into())) - // Standard Error: 601_053 - .saturating_add(Weight::from_parts(15_578_413, 0).saturating_mul(y.into())) - .saturating_add(RocksDbWeight::get().reads(13_u64)) - .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(y.into()))) - .saturating_add(RocksDbWeight::get().writes(112_u64)) - .saturating_add(RocksDbWeight::get().writes((2_u64).saturating_mul(y.into()))) - .saturating_add(Weight::from_parts(0, 24).saturating_mul(x.into())) - .saturating_add(Weight::from_parts(0, 2496).saturating_mul(y.into())) - } - /// Storage: `Sassafras::CurrentSlot` (r:1 w:0) - /// Proof: `Sassafras::CurrentSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::EpochIndex` (r:1 w:0) - /// Proof: `Sassafras::EpochIndex` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::GenesisSlot` (r:1 w:0) - /// Proof: `Sassafras::GenesisSlot` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::RingVerifierData` (r:1 w:0) - /// Proof: `Sassafras::RingVerifierData` (`max_values`: Some(1), `max_size`: Some(388), added: 883, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextAuthorities` (r:1 w:0) - /// Proof: `Sassafras::NextAuthorities` (`max_values`: Some(1), `max_size`: Some(3302), added: 3797, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextEpochConfig` (r:1 w:0) - /// Proof: `Sassafras::NextEpochConfig` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::NextRandomness` (r:1 w:0) - /// Proof: `Sassafras::NextRandomness` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsData` (r:25 w:25) - /// Proof: `Sassafras::TicketsData` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsMeta` (r:1 w:1) - /// Proof: `Sassafras::TicketsMeta` (`max_values`: Some(1), `max_size`: Some(12), added: 507, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::UnsortedSegments` (r:1 w:1) - /// Proof: `Sassafras::UnsortedSegments` (`max_values`: None, `max_size`: Some(2054), added: 4529, mode: `MaxEncodedLen`) - /// The range of component `x` is `[1, 25]`. - fn submit_tickets(x: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `3869` - // Estimated: `5519 + x * (2559 ±0)` - // Minimum execution time: 36_904_934_000 picoseconds. - Weight::from_parts(25_822_957_295, 5519) - // Standard Error: 11_047_832 - .saturating_add(Weight::from_parts(11_338_353_299, 0).saturating_mul(x.into())) - .saturating_add(RocksDbWeight::get().reads(9_u64)) - .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(x.into()))) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(x.into()))) - .saturating_add(Weight::from_parts(0, 2559).saturating_mul(x.into())) - } - /// Storage: `Sassafras::PendingEpochConfigChange` (r:0 w:1) - /// Proof: `Sassafras::PendingEpochConfigChange` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) - fn plan_config_change() -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 4_038_000 picoseconds. - Weight::from_parts(4_499_000, 0) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - /// Storage: `Sassafras::RingContext` (r:1 w:0) - /// Proof: `Sassafras::RingContext` (`max_values`: Some(1), `max_size`: Some(590324), added: 590819, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::RingVerifierData` (r:0 w:1) - /// Proof: `Sassafras::RingVerifierData` (`max_values`: Some(1), `max_size`: Some(388), added: 883, mode: `MaxEncodedLen`) - /// The range of component `x` is `[1, 100]`. - fn update_ring_verifier(x: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `590485` - // Estimated: `591809` - // Minimum execution time: 105_121_424_000 picoseconds. - Weight::from_parts(105_527_334_385, 591809) - // Standard Error: 2_933_910 - .saturating_add(Weight::from_parts(96_136_261, 0).saturating_mul(x.into())) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - /// Storage: `Sassafras::RingContext` (r:1 w:0) - /// Proof: `Sassafras::RingContext` (`max_values`: Some(1), `max_size`: Some(590324), added: 590819, mode: `MaxEncodedLen`) - fn load_ring_context() -> Weight { - // Proof Size summary in bytes: - // Measured: `590485` - // Estimated: `591809` - // Minimum execution time: 44_005_681_000 picoseconds. - Weight::from_parts(44_312_079_000, 591809) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - } - /// Storage: `Sassafras::SortedCandidates` (r:1 w:0) - /// Proof: `Sassafras::SortedCandidates` (`max_values`: Some(1), `max_size`: Some(3202), added: 3697, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::UnsortedSegments` (r:100 w:100) - /// Proof: `Sassafras::UnsortedSegments` (`max_values`: None, `max_size`: Some(2054), added: 4529, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsIds` (r:0 w:200) - /// Proof: `Sassafras::TicketsIds` (`max_values`: None, `max_size`: Some(21), added: 2496, mode: `MaxEncodedLen`) - /// Storage: `Sassafras::TicketsData` (r:0 w:12600) - /// Proof: `Sassafras::TicketsData` (`max_values`: None, `max_size`: Some(84), added: 2559, mode: `MaxEncodedLen`) - /// The range of component `x` is `[1, 100]`. - fn sort_segments(x: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `222 + x * (2060 ±0)` - // Estimated: `4687 + x * (4529 ±0)` - // Minimum execution time: 183_501_000 picoseconds. - Weight::from_parts(183_501_000, 4687) - // Standard Error: 1_426_363 - .saturating_add(Weight::from_parts(169_156_241, 0).saturating_mul(x.into())) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(x.into()))) - .saturating_add(RocksDbWeight::get().writes((129_u64).saturating_mul(x.into()))) - .saturating_add(Weight::from_parts(0, 4529).saturating_mul(x.into())) - } -} diff --git a/substrate/frame/scheduler/Cargo.toml b/substrate/frame/scheduler/Cargo.toml index c27276c607e..6aa81baf7ac 100644 --- a/substrate/frame/scheduler/Cargo.toml +++ b/substrate/frame/scheduler/Cargo.toml @@ -9,29 +9,26 @@ repository.workspace = true description = "FRAME Scheduler pallet" readme = "README.md" -[lints] -workspace = true - [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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.6" [dev-dependencies] pallet-preimage = { path = "../preimage" } -sp-core = { path = "../../primitives/core", default-features = false } +sp-core = { path = "../../primitives/core", default-features = false} substrate-test-utils = { path = "../../test-utils" } [features] -default = ["std"] +default = [ "std" ] runtime-benchmarks = [ "frame-benchmarking", "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/scheduler/src/mock.rs b/substrate/frame/scheduler/src/mock.rs index 4edcfa0a7bf..b6eb1d044fa 100644 --- a/substrate/frame/scheduler/src/mock.rs +++ b/substrate/frame/scheduler/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as scheduler; use frame_support::{ - derive_impl, ord_parameter_types, parameter_types, + ord_parameter_types, parameter_types, traits::{ ConstU32, ConstU64, Contains, EitherOfDiverse, EqualPrivilegeOnly, OnFinalize, OnInitialize, }, @@ -118,8 +118,6 @@ parameter_types! { Weight::from_parts(2_000_000_000_000, u64::MAX), ); } - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl system::Config for Test { type BaseCallFilter = BaseFilter; type BlockWeights = BlockWeights; diff --git a/substrate/frame/scored-pool/Cargo.toml b/substrate/frame/scored-pool/Cargo.toml index 7a534ddd79d..81707382693 100644 --- a/substrate/frame/scored-pool/Cargo.toml +++ b/substrate/frame/scored-pool/Cargo.toml @@ -9,27 +9,24 @@ repository.workspace = true description = "FRAME pallet for scored pools" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } sp-core = { path = "../../primitives/core" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/scored-pool/src/mock.rs b/substrate/frame/scored-pool/src/mock.rs index 6c032ab808c..32a66c0cdc5 100644 --- a/substrate/frame/scored-pool/src/mock.rs +++ b/substrate/frame/scored-pool/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_scored_pool; use frame_support::{ - construct_runtime, derive_impl, ord_parameter_types, parameter_types, + construct_runtime, ord_parameter_types, parameter_types, traits::{ConstU32, ConstU64}, }; use frame_system::EnsureSignedBy; @@ -51,7 +51,6 @@ ord_parameter_types! { pub const ScoreOrigin: u64 = 3; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/session/Cargo.toml b/substrate/frame/session/Cargo.toml index 4589dbb427a..246dec63bba 100644 --- a/substrate/frame/session/Cargo.toml +++ b/substrate/frame/session/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME sessions pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,21 +17,21 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = impl-trait-for-tuples = "0.2.2" log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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-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-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 } +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} [features] -default = ["historical", "std"] -historical = ["sp-trie"] +default = [ "historical", "std" ] +historical = [ "sp-trie" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/session/benchmarking/Cargo.toml b/substrate/frame/session/benchmarking/Cargo.toml index 16f85048d8d..87f08985138 100644 --- a/substrate/frame/session/benchmarking/Cargo.toml +++ b/substrate/frame/session/benchmarking/Cargo.toml @@ -9,23 +9,20 @@ repository.workspace = true description = "FRAME sessions pallet benchmarking" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", 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 } +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} [dev-dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", features = ["derive"] } @@ -38,7 +35,7 @@ sp-core = { path = "../../../primitives/core" } sp-io = { path = "../../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "frame-benchmarking/std", "frame-election-provider-support/std", diff --git a/substrate/frame/session/benchmarking/src/mock.rs b/substrate/frame/session/benchmarking/src/mock.rs index e1744fa43ab..47c337569a0 100644 --- a/substrate/frame/session/benchmarking/src/mock.rs +++ b/substrate/frame/session/benchmarking/src/mock.rs @@ -24,7 +24,7 @@ use frame_election_provider_support::{ onchain, SequentialPhragmen, }; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64}, }; use sp_runtime::{traits::IdentityLookup, BuildStorage}; @@ -45,7 +45,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); @@ -179,7 +178,6 @@ impl pallet_staking::Config for Test { 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; diff --git a/substrate/frame/session/src/historical/offchain.rs b/substrate/frame/session/src/historical/offchain.rs index 95f4d762949..1b4d53b74b4 100644 --- a/substrate/frame/session/src/historical/offchain.rs +++ b/substrate/frame/session/src/historical/offchain.rs @@ -17,11 +17,13 @@ //! Off-chain logic for creating a proof based data provided by on-chain logic. //! -//! Validator-set extracting an iterator from an off-chain worker stored list containing historical -//! validator-sets. Based on the logic of historical slashing, but the validation is done off-chain. +//! Validator-set extracting an iterator from an off-chain worker stored list containing +//! historical validator-sets. +//! Based on the logic of historical slashing, but the validation is done off-chain. //! Use [`fn store_current_session_validator_set_to_offchain()`](super::onchain) to store the -//! required data to the offchain validator set. This is used in conjunction with [`ProvingTrie`] -//! and the off-chain indexing API. +//! required data to the offchain validator set. +//! This is used in conjunction with [`ProvingTrie`](super::ProvingTrie) and +//! the off-chain indexing API. use sp_runtime::{ offchain::storage::{MutateStorageError, StorageRetrievalError, StorageValueRef}, diff --git a/substrate/frame/session/src/mock.rs b/substrate/frame/session/src/mock.rs index f3f18fde168..2db54e1a597 100644 --- a/substrate/frame/session/src/mock.rs +++ b/substrate/frame/session/src/mock.rs @@ -35,7 +35,7 @@ use sp_staking::SessionIndex; use sp_state_machine::BasicExternalities; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64}, }; @@ -232,7 +232,6 @@ pub fn new_test_ext() -> sp_io::TestExternalities { sp_io::TestExternalities::new(t) } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/society/Cargo.toml b/substrate/frame/society/Cargo.toml index 46b4f7a7d66..654447e6893 100644 --- a/substrate/frame/society/Cargo.toml +++ b/substrate/frame/society/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME society pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,13 +18,13 @@ rand_chacha = { version = "0.2", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } -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 = { 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} [dev-dependencies] frame-support-test = { path = "../support/test" } @@ -36,7 +33,7 @@ sp-core = { path = "../../primitives/core" } sp-io = { path = "../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/society/src/mock.rs b/substrate/frame/society/src/mock.rs index 3e29d01ca8e..0bee08236f7 100644 --- a/substrate/frame/society/src/mock.rs +++ b/substrate/frame/society/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_society; use frame_support::{ - assert_noop, assert_ok, derive_impl, ord_parameter_types, parameter_types, + assert_noop, assert_ok, ord_parameter_types, parameter_types, traits::{ConstU32, ConstU64}, }; use frame_support_test::TestRandomness; @@ -58,7 +58,6 @@ ord_parameter_types! { pub const MaxBids: u32 = 10; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/src/lib.rs b/substrate/frame/src/lib.rs index 0e0f9d8900c..c54df98c550 100644 --- a/substrate/frame/src/lib.rs +++ b/substrate/frame/src/lib.rs @@ -15,6 +15,10 @@ // See the License for the specific language governing permissions and // limitations under the License. +//! > Made for [![polkadot]](https://polkadot.network) +//! +//! [polkadot]: https://img.shields.io/badge/polkadot-E6007A?style=for-the-badge&logo=polkadot&logoColor=white +//! //! # FRAME //! //! ```no_compile @@ -30,21 +34,14 @@ //! > **F**ramework for **R**untime **A**ggregation of **M**odularized **E**ntities: Substrate's //! > State Transition Function (Runtime) Framework. //! -//! ## Documentation -//! -//! See [`polkadot_sdk::frame`](../polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html). -//! //! ## Warning: Experimental //! //! This crate and all of its content is experimental, and should not yet be used in production. //! -//! ## Underlying dependencies +//! ## Getting Started //! -//! This crate is an amalgamation of multiple other crates that are often used together to compose a -//! pallet. It is not necessary to use it, and it may fall short for certain purposes. -//! -//! In short, this crate only re-exports types and traits from multiple sources. All of these -//! sources are listed (and re-exported again) in [`deps`]. +//! TODO: link to `developer_hub::polkadot_sdk::frame`. The `developer_hub` hasn't been published +//! yet, this can be updated once it is linkable. #![cfg_attr(not(feature = "std"), no_std)] #![cfg(feature = "experimental")] @@ -57,19 +54,9 @@ /// `#[pallet::bar]` inside the mod. pub use frame_support::pallet; -pub use frame_support::pallet_macros::{import_section, pallet_section}; - /// The logging library of the runtime. Can normally be the classic `log` crate. pub use log; -/// A list of all macros used within the main [`pallet`] macro. -/// -/// Note: All of these macros are "stubs" and not really usable outside `#[pallet] mod pallet { .. -/// }`. They are mainly provided for documentation and IDE support. -pub mod pallet_macros { - pub use frame_support::{derive_impl, pallet, pallet_macros::*}; -} - /// The main prelude of FRAME. /// /// This prelude should almost always be the first line of code in any pallet or runtime. @@ -91,6 +78,9 @@ pub mod prelude { /// Pallet prelude of `frame-support`. /// /// Note: this needs to revised once `frame-support` evolves. + // `frame-support` will be break down https://github.com/paritytech/polkadot-sdk/issues/127 and its reexports will + // most likely change. These wildcard reexportings can be optimized once `frame-support` has + // changed. #[doc(no_inline)] pub use frame_support::pallet_prelude::*; @@ -166,9 +156,6 @@ pub mod runtime { /// Types to define your runtime version. pub use sp_version::{create_runtime_str, runtime_version, RuntimeVersion}; - /// Macro to implement runtime APIs. - pub use sp_api::impl_runtime_apis; - #[cfg(feature = "std")] pub use sp_version::NativeVersion; } @@ -193,6 +180,9 @@ pub mod runtime { pub use sp_inherents::{CheckInherentsResult, InherentData}; pub use sp_runtime::ApplyExtrinsicResult; + /// Macro to implement runtime APIs. + pub use sp_api::impl_runtime_apis; + pub use frame_system_rpc_runtime_api::*; pub use sp_api::{self, *}; pub use sp_block_builder::*; diff --git a/substrate/frame/staking/Cargo.toml b/substrate/frame/staking/Cargo.toml index 31831fd7ed2..c5cac9fefa7 100644 --- a/substrate/frame/staking/Cargo.toml +++ b/substrate/frame/staking/Cargo.toml @@ -9,30 +9,27 @@ repository.workspace = true description = "FRAME pallet staking" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"] } +serde = { version = "1.0.188", default-features = false, features = ["alloc", "derive"]} codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = [ "derive", ] } scale-info = { version = "2.10.0", default-features = false, features = ["derive", "serde"] } -sp-io = { path = "../../primitives/io", default-features = false } +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 } +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 = [ "historical", -] } -pallet-authorship = { path = "../authorship", default-features = false } +]} +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 } +frame-election-provider-support = { path = "../election-provider-support", default-features = false} log = { version = "0.4.17", default-features = false } # Optional imports for benchmarking @@ -53,7 +50,7 @@ frame-election-provider-support = { path = "../election-provider-support" } rand_chacha = { version = "0.2" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/staking/reward-curve/Cargo.toml b/substrate/frame/staking/reward-curve/Cargo.toml index e33fd255fa8..0a725996115 100644 --- a/substrate/frame/staking/reward-curve/Cargo.toml +++ b/substrate/frame/staking/reward-curve/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "Reward Curve for FRAME staking pallet" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -18,10 +15,10 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -proc-macro-crate = "2.0.1" +proc-macro-crate = "1.1.3" proc-macro2 = "1.0.56" quote = "1.0.28" -syn = { version = "2.0.40", features = ["full", "visit"] } +syn = { version = "2.0.38", features = ["full", "visit"] } [dev-dependencies] sp-runtime = { path = "../../../primitives/runtime" } diff --git a/substrate/frame/staking/reward-fn/Cargo.toml b/substrate/frame/staking/reward-fn/Cargo.toml index 80a27cc0f53..25f4c33dd62 100644 --- a/substrate/frame/staking/reward-fn/Cargo.toml +++ b/substrate/frame/staking/reward-fn/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "Reward function for FRAME staking pallet" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -18,8 +15,8 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] log = { version = "0.4.17", default-features = false } -sp-arithmetic = { path = "../../../primitives/arithmetic", default-features = false } +sp-arithmetic = { path = "../../../primitives/arithmetic", default-features = false} [features] -default = ["std"] -std = ["log/std", "sp-arithmetic/std"] +default = [ "std" ] +std = [ "log/std", "sp-arithmetic/std" ] diff --git a/substrate/frame/staking/runtime-api/Cargo.toml b/substrate/frame/staking/runtime-api/Cargo.toml index b3fd4cfda01..746b463b8ce 100644 --- a/substrate/frame/staking/runtime-api/Cargo.toml +++ b/substrate/frame/staking/runtime-api/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "RPC runtime API for transaction payment FRAME pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,5 +18,5 @@ sp-api = { version = "4.0.0-dev", default-features = false, path = "../../../pri sp-staking = { version = "4.0.0-dev", default-features = false, path = "../../../primitives/staking" } [features] -default = ["std"] -std = ["codec/std", "sp-api/std", "sp-staking/std"] +default = [ "std" ] +std = [ "codec/std", "sp-api/std", "sp-staking/std" ] diff --git a/substrate/frame/staking/src/benchmarking.rs b/substrate/frame/staking/src/benchmarking.rs index abb78b7e304..6f60c4909f4 100644 --- a/substrate/frame/staking/src/benchmarking.rs +++ b/substrate/frame/staking/src/benchmarking.rs @@ -25,7 +25,6 @@ use codec::Decode; use frame_election_provider_support::{bounds::DataProviderBounds, SortedListProvider}; use frame_support::{ pallet_prelude::*, - storage::bounded_vec::BoundedVec, traits::{Currency, Get, Imbalance, UnfilteredDispatchable}, }; use sp_runtime::{ @@ -526,39 +525,6 @@ benchmarks! { assert_eq!(Invulnerables::::get().len(), v as usize); } - deprecate_controller_batch { - // We pass a dynamic number of controllers to the benchmark, up to - // `MaxControllersInDeprecationBatch`. - let i in 0 .. T::MaxControllersInDeprecationBatch::get(); - - let mut controllers: Vec<_> = vec![]; - let mut stashes: Vec<_> = vec![]; - for n in 0..i as u32 { - let (stash, controller) = create_unique_stash_controller::( - n, - 100, - RewardDestination::Staked, - false - )?; - controllers.push(controller); - stashes.push(stash); - } - let bounded_controllers: BoundedVec<_, T::MaxControllersInDeprecationBatch> = - BoundedVec::try_from(controllers.clone()).unwrap(); - }: _(RawOrigin::Root, bounded_controllers) - verify { - for n in 0..i as u32 { - let stash = &stashes[n as usize]; - let controller = &controllers[n as usize]; - // Ledger no longer keyed by controller. - assert_eq!(Ledger::::get(controller), None); - // Bonded now maps to the stash. - assert_eq!(Bonded::::get(stash), Some(stash.clone())); - // Ledger is now keyed by stash. - assert_eq!(Ledger::::get(stash).unwrap().stash, *stash); - } - } - force_unstake { // Slashing Spans let s in 0 .. MAX_SPANS; @@ -907,7 +873,7 @@ benchmarks! { )?; let caller = whitelisted_caller(); - }: _(RawOrigin::Signed(caller), stash.clone()) + }: _(RawOrigin::Signed(caller), controller) verify { assert!(!T::VoterList::contains(&stash)); } diff --git a/substrate/frame/staking/src/mock.rs b/substrate/frame/staking/src/mock.rs index 5332dbfdd5b..364d125792b 100644 --- a/substrate/frame/staking/src/mock.rs +++ b/substrate/frame/staking/src/mock.rs @@ -23,7 +23,7 @@ use frame_election_provider_support::{ onchain, SequentialPhragmen, VoteWeight, }; use frame_support::{ - assert_ok, derive_impl, ord_parameter_types, parameter_types, + assert_ok, ord_parameter_types, parameter_types, traits::{ ConstU64, Currency, EitherOfDiverse, FindAuthor, Get, Hooks, Imbalance, OnUnbalanced, OneSessionHandler, @@ -122,10 +122,8 @@ parameter_types! { pub static SlashDeferDuration: EraIndex = 0; pub static Period: BlockNumber = 5; pub static Offset: BlockNumber = 0; - pub static MaxControllersInDeprecationBatch: u32 = 5900; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); @@ -317,7 +315,6 @@ impl crate::pallet::pallet::Config for Test { type NominationsQuota = WeightedNominationsQuota<16>; type MaxUnlockingChunks = MaxUnlockingChunks; type HistoryDepth = HistoryDepth; - type MaxControllersInDeprecationBatch = MaxControllersInDeprecationBatch; type EventListeners = EventListenerMock; type BenchmarkingConfig = TestBenchmarkingConfig; type WeightInfo = (); diff --git a/substrate/frame/staking/src/pallet/mod.rs b/substrate/frame/staking/src/pallet/mod.rs index b914545a76b..1f79ef63a47 100644 --- a/substrate/frame/staking/src/pallet/mod.rs +++ b/substrate/frame/staking/src/pallet/mod.rs @@ -269,9 +269,6 @@ pub mod pallet { #[pallet::constant] type MaxUnlockingChunks: Get; - /// The maximum amount of controller accounts that can be deprecated in one call. - type MaxControllersInDeprecationBatch: Get; - /// Something that listens to staking updates and performs actions based on the data it /// receives. /// @@ -1326,17 +1323,18 @@ pub mod pallet { pub fn set_controller(origin: OriginFor) -> DispatchResult { let stash = ensure_signed(origin)?; - // The bonded map and ledger are mutated directly as this extrinsic is related to a + // the bonded map and ledger are mutated directly as this extrinsic is related to a // (temporary) passive migration. Self::ledger(StakingAccount::Stash(stash.clone())).map(|ledger| { let controller = ledger.controller() - .defensive_proof("Ledger's controller field didn't exist. The controller should have been fetched using StakingLedger.") + .defensive_proof("ledger was fetched used the StakingInterface, so controller field must exist; qed.") .ok_or(Error::::NotController)?; if controller == stash { - // Stash is already its own controller. + // stash is already its own controller. return Err(Error::::AlreadyPaired.into()) } + // update bond and ledger. >::remove(controller); >::insert(&stash, &stash); >::insert(&stash, ledger); @@ -1766,16 +1764,11 @@ pub mod pallet { /// who do not satisfy these requirements. #[pallet::call_index(23)] #[pallet::weight(T::WeightInfo::chill_other())] - pub fn chill_other(origin: OriginFor, stash: T::AccountId) -> DispatchResult { + pub fn chill_other(origin: OriginFor, controller: T::AccountId) -> DispatchResult { // Anyone can call this function. let caller = ensure_signed(origin)?; - let ledger = Self::ledger(Stash(stash.clone()))?; - let controller = ledger - .controller() - .defensive_proof( - "Ledger's controller field didn't exist. The controller should have been fetched using StakingLedger.", - ) - .ok_or(Error::::NotController)?; + let ledger = Self::ledger(Controller(controller.clone()))?; + let stash = ledger.stash; // In order for one user to chill another user, the following conditions must be met: // @@ -1922,54 +1915,6 @@ pub mod pallet { Ok(Pays::No.into()) } - - /// Updates a batch of controller accounts to their corresponding stash account if they are - /// not the same. Ignores any controller accounts that do not exist, and does not operate if - /// the stash and controller are already the same. - /// - /// Effects will be felt instantly (as soon as this function is completed successfully). - /// - /// The dispatch origin must be `T::AdminOrigin`. - #[pallet::call_index(28)] - #[pallet::weight(T::WeightInfo::deprecate_controller_batch(controllers.len() as u32))] - pub fn deprecate_controller_batch( - origin: OriginFor, - controllers: BoundedVec, - ) -> DispatchResultWithPostInfo { - T::AdminOrigin::ensure_origin(origin)?; - - // Ignore controllers that do not exist or are already the same as stash. - let filtered_batch_with_ledger: Vec<_> = controllers - .iter() - .filter_map(|controller| { - let ledger = Self::ledger(StakingAccount::Controller(controller.clone())); - ledger.ok().map_or(None, |ledger| { - // If the controller `RewardDestination` is still the deprecated - // `Controller` variant, skip deprecating this account. - let payee_deprecated = Payee::::get(&ledger.stash) == { - #[allow(deprecated)] - RewardDestination::Controller - }; - - if ledger.stash != *controller && !payee_deprecated { - Some((controller.clone(), ledger)) - } else { - None - } - }) - }) - .collect(); - - // Update unique pairs. - for (controller, ledger) in filtered_batch_with_ledger { - let stash = ledger.stash.clone(); - - >::insert(&stash, &stash); - >::remove(controller); - >::insert(stash, ledger); - } - Ok(Some(T::WeightInfo::deprecate_controller_batch(controllers.len() as u32)).into()) - } } } diff --git a/substrate/frame/staking/src/tests.rs b/substrate/frame/staking/src/tests.rs index 0e9be70ee7d..7d967609f52 100644 --- a/substrate/frame/staking/src/tests.rs +++ b/substrate/frame/staking/src/tests.rs @@ -6206,7 +6206,7 @@ fn proportional_ledger_slash_works() { #[test] fn reducing_max_unlocking_chunks_abrupt() { // Concern is on validators only - // By Default 11, 10 are stash and ctlr and 21,20 + // By Default 11, 10 are stash and ctrl and 21,20 ExtBuilder::default().build_and_execute(|| { // given a staker at era=10 and MaxUnlockChunks set to 2 MaxUnlockingChunks::set(2); @@ -6867,181 +6867,4 @@ mod ledger { assert_eq!(Payee::::get(&21), RewardDestination::Stash); }) } - - #[test] - fn deprecate_controller_batch_works_full_weight() { - ExtBuilder::default().build_and_execute(|| { - // Given: - - let start = 1001; - let mut controllers: Vec<_> = vec![]; - for n in start..(start + MaxControllersInDeprecationBatch::get()).into() { - let ctlr: u64 = n.into(); - let stash: u64 = (n + 10000).into(); - - Ledger::::insert( - ctlr, - StakingLedger { - controller: None, - total: (10 + ctlr).into(), - active: (10 + ctlr).into(), - ..StakingLedger::default_from(stash) - }, - ); - Bonded::::insert(stash, ctlr); - Payee::::insert(stash, RewardDestination::Staked); - - controllers.push(ctlr); - } - - // When: - - let bounded_controllers: BoundedVec< - _, - ::MaxControllersInDeprecationBatch, - > = BoundedVec::try_from(controllers).unwrap(); - - // Only `AdminOrigin` can sign. - assert_noop!( - Staking::deprecate_controller_batch( - RuntimeOrigin::signed(2), - bounded_controllers.clone() - ), - BadOrigin - ); - - let result = - Staking::deprecate_controller_batch(RuntimeOrigin::root(), bounded_controllers); - assert_ok!(result); - assert_eq!( - result.unwrap().actual_weight.unwrap(), - ::WeightInfo::deprecate_controller_batch( - ::MaxControllersInDeprecationBatch::get() - ) - ); - - // Then: - - for n in start..(start + MaxControllersInDeprecationBatch::get()).into() { - let ctlr: u64 = n.into(); - let stash: u64 = (n + 10000).into(); - - // Ledger no longer keyed by controller. - assert_eq!(Ledger::::get(ctlr), None); - // Bonded now maps to the stash. - assert_eq!(Bonded::::get(stash), Some(stash)); - - // Ledger is now keyed by stash. - let ledger_updated = Ledger::::get(stash).unwrap(); - assert_eq!(ledger_updated.stash, stash); - - // Check `active` and `total` values match the original ledger set by controller. - assert_eq!(ledger_updated.active, (10 + ctlr).into()); - assert_eq!(ledger_updated.total, (10 + ctlr).into()); - } - }) - } - - #[test] - fn deprecate_controller_batch_works_half_weight() { - ExtBuilder::default().build_and_execute(|| { - // Given: - - let start = 1001; - let mut controllers: Vec<_> = vec![]; - for n in start..(start + MaxControllersInDeprecationBatch::get()).into() { - let ctlr: u64 = n.into(); - - // Only half of entries are unique pairs. - let stash: u64 = if n % 2 == 0 { (n + 10000).into() } else { ctlr }; - - Ledger::::insert( - ctlr, - StakingLedger { controller: None, ..StakingLedger::default_from(stash) }, - ); - Bonded::::insert(stash, ctlr); - Payee::::insert(stash, RewardDestination::Staked); - - controllers.push(ctlr); - } - - // When: - let bounded_controllers: BoundedVec< - _, - ::MaxControllersInDeprecationBatch, - > = BoundedVec::try_from(controllers.clone()).unwrap(); - - let result = - Staking::deprecate_controller_batch(RuntimeOrigin::root(), bounded_controllers); - assert_ok!(result); - assert_eq!( - result.unwrap().actual_weight.unwrap(), - ::WeightInfo::deprecate_controller_batch(controllers.len() as u32) - ); - - // Then: - - for n in start..(start + MaxControllersInDeprecationBatch::get()).into() { - let unique_pair = n % 2 == 0; - let ctlr: u64 = n.into(); - let stash: u64 = if unique_pair { (n + 10000).into() } else { ctlr }; - - // Side effect of migration for unique pair. - if unique_pair { - assert_eq!(Ledger::::get(ctlr), None); - } - // Bonded maps to the stash. - assert_eq!(Bonded::::get(stash), Some(stash)); - - // Ledger is keyed by stash. - let ledger_updated = Ledger::::get(stash).unwrap(); - assert_eq!(ledger_updated.stash, stash); - } - }) - } - - #[test] - fn deprecate_controller_batch_skips_unmigrated_controller_payees() { - ExtBuilder::default().build_and_execute(|| { - // Given: - - let stash: u64 = 1000; - let ctlr: u64 = 1001; - - Ledger::::insert( - ctlr, - StakingLedger { controller: None, ..StakingLedger::default_from(stash) }, - ); - Bonded::::insert(stash, ctlr); - #[allow(deprecated)] - Payee::::insert(stash, RewardDestination::Controller); - - // When: - - let bounded_controllers: BoundedVec< - _, - ::MaxControllersInDeprecationBatch, - > = BoundedVec::try_from(vec![ctlr]).unwrap(); - - let result = - Staking::deprecate_controller_batch(RuntimeOrigin::root(), bounded_controllers); - assert_ok!(result); - assert_eq!( - result.unwrap().actual_weight.unwrap(), - ::WeightInfo::deprecate_controller_batch(1 as u32) - ); - - // Then: - - // Esure deprecation did not happen. - assert_eq!(Ledger::::get(ctlr).is_some(), true); - - // Bonded still keyed by controller. - assert_eq!(Bonded::::get(stash), Some(ctlr)); - - // Ledger is still keyed by controller. - let ledger_updated = Ledger::::get(ctlr).unwrap(); - assert_eq!(ledger_updated.stash, stash); - }) - } } diff --git a/substrate/frame/staking/src/weights.rs b/substrate/frame/staking/src/weights.rs index 7c9a0500164..ad9ca75a032 100644 --- a/substrate/frame/staking/src/weights.rs +++ b/substrate/frame/staking/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_staking` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-10, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-11-17, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yprdrvc7-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -66,7 +66,6 @@ pub trait WeightInfo { fn force_new_era() -> Weight; fn force_new_era_always() -> Weight; fn set_invulnerables(v: u32, ) -> Weight; - fn deprecate_controller_batch(i: u32, ) -> Weight; fn force_unstake(s: u32, ) -> Weight; fn cancel_deferred_slash(s: u32, ) -> Weight; fn payout_stakers_alive_staked(n: u32, ) -> Weight; @@ -99,8 +98,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `927` // Estimated: `4764` - // Minimum execution time: 42_491_000 picoseconds. - Weight::from_parts(44_026_000, 4764) + // Minimum execution time: 43_427_000 picoseconds. + Weight::from_parts(45_221_000, 4764) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(4_u64)) } @@ -120,8 +119,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1990` // Estimated: `8877` - // Minimum execution time: 88_756_000 picoseconds. - Weight::from_parts(91_000_000, 8877) + // Minimum execution time: 87_100_000 picoseconds. + Weight::from_parts(90_599_000, 8877) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -147,8 +146,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `2195` // Estimated: `8877` - // Minimum execution time: 91_331_000 picoseconds. - Weight::from_parts(94_781_000, 8877) + // Minimum execution time: 91_488_000 picoseconds. + Weight::from_parts(94_126_000, 8877) .saturating_add(T::DbWeight::get().reads(12_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -167,10 +166,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1115` // Estimated: `4764` - // Minimum execution time: 42_495_000 picoseconds. - Weight::from_parts(44_189_470, 4764) - // Standard Error: 1_389 - .saturating_add(Weight::from_parts(47_484, 0).saturating_mul(s.into())) + // Minimum execution time: 42_713_000 picoseconds. + Weight::from_parts(44_530_499, 4764) + // Standard Error: 1_067 + .saturating_add(Weight::from_parts(51_411, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -207,10 +206,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `2196 + s * (4 ±0)` // Estimated: `6248 + s * (4 ±0)` - // Minimum execution time: 89_004_000 picoseconds. - Weight::from_parts(96_677_570, 6248) - // Standard Error: 4_635 - .saturating_add(Weight::from_parts(1_387_718, 0).saturating_mul(s.into())) + // Minimum execution time: 88_700_000 picoseconds. + Weight::from_parts(98_329_624, 6248) + // Standard Error: 4_477 + .saturating_add(Weight::from_parts(1_347_380, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(13_u64)) .saturating_add(T::DbWeight::get().writes(11_u64)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(s.into()))) @@ -242,8 +241,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1372` // Estimated: `4556` - // Minimum execution time: 51_532_000 picoseconds. - Weight::from_parts(53_308_000, 4556) + // Minimum execution time: 51_877_000 picoseconds. + Weight::from_parts(53_503_000, 4556) .saturating_add(T::DbWeight::get().reads(11_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -256,10 +255,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1280 + k * (569 ±0)` // Estimated: `4556 + k * (3033 ±0)` - // Minimum execution time: 28_955_000 picoseconds. - Weight::from_parts(29_609_869, 4556) - // Standard Error: 6_793 - .saturating_add(Weight::from_parts(6_412_124, 0).saturating_mul(k.into())) + // Minimum execution time: 29_604_000 picoseconds. + Weight::from_parts(31_726_296, 4556) + // Standard Error: 6_350 + .saturating_add(Weight::from_parts(6_416_846, 0).saturating_mul(k.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(k.into()))) @@ -292,10 +291,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1866 + n * (102 ±0)` // Estimated: `6248 + n * (2520 ±0)` - // Minimum execution time: 64_080_000 picoseconds. - Weight::from_parts(61_985_382, 6248) - // Standard Error: 13_320 - .saturating_add(Weight::from_parts(4_030_513, 0).saturating_mul(n.into())) + // Minimum execution time: 64_276_000 picoseconds. + Weight::from_parts(62_615_844, 6248) + // Standard Error: 14_914 + .saturating_add(Weight::from_parts(4_097_019, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(12_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(6_u64)) @@ -319,8 +318,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1650` // Estimated: `6248` - // Minimum execution time: 54_194_000 picoseconds. - Weight::from_parts(55_578_000, 6248) + // Minimum execution time: 55_064_000 picoseconds. + Weight::from_parts(56_566_000, 6248) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -334,8 +333,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `902` // Estimated: `4556` - // Minimum execution time: 16_597_000 picoseconds. - Weight::from_parts(16_980_000, 4556) + // Minimum execution time: 16_626_000 picoseconds. + Weight::from_parts(17_519_000, 4556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -349,8 +348,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `969` // Estimated: `4556` - // Minimum execution time: 20_626_000 picoseconds. - Weight::from_parts(21_242_000, 4556) + // Minimum execution time: 20_545_000 picoseconds. + Weight::from_parts(21_395_000, 4556) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -362,8 +361,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `902` // Estimated: `4556` - // Minimum execution time: 19_972_000 picoseconds. - Weight::from_parts(20_470_000, 4556) + // Minimum execution time: 20_179_000 picoseconds. + Weight::from_parts(20_728_000, 4556) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -373,8 +372,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_571_000 picoseconds. - Weight::from_parts(2_720_000, 0) + // Minimum execution time: 2_594_000 picoseconds. + Weight::from_parts(2_777_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Staking::ForceEra` (r:0 w:1) @@ -383,8 +382,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_056_000 picoseconds. - Weight::from_parts(8_413_000, 0) + // Minimum execution time: 8_302_000 picoseconds. + Weight::from_parts(8_741_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Staking::ForceEra` (r:0 w:1) @@ -393,8 +392,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_162_000 picoseconds. - Weight::from_parts(8_497_000, 0) + // Minimum execution time: 8_504_000 picoseconds. + Weight::from_parts(8_774_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Staking::ForceEra` (r:0 w:1) @@ -403,8 +402,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_320_000 picoseconds. - Weight::from_parts(8_564_000, 0) + // Minimum execution time: 8_474_000 picoseconds. + Weight::from_parts(8_740_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `Staking::Invulnerables` (r:0 w:1) @@ -414,31 +413,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_470_000 picoseconds. - Weight::from_parts(3_110_242, 0) - // Standard Error: 63 - .saturating_add(Weight::from_parts(11_786, 0).saturating_mul(v.into())) + // Minimum execution time: 2_732_000 picoseconds. + Weight::from_parts(3_360_048, 0) + // Standard Error: 34 + .saturating_add(Weight::from_parts(9_964, 0).saturating_mul(v.into())) .saturating_add(T::DbWeight::get().writes(1_u64)) } - /// Storage: `Staking::Ledger` (r:5900 w:11800) - /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) - /// Storage: `Staking::Payee` (r:5900 w:0) - /// Proof: `Staking::Payee` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) - /// Storage: `Staking::Bonded` (r:0 w:5900) - /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) - /// The range of component `i` is `[0, 5900]`. - fn deprecate_controller_batch(i: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `1356 + i * (151 ±0)` - // Estimated: `990 + i * (3566 ±0)` - // Minimum execution time: 2_101_000 picoseconds. - Weight::from_parts(2_238_000, 990) - // Standard Error: 56_753 - .saturating_add(Weight::from_parts(18_404_902, 0).saturating_mul(i.into())) - .saturating_add(T::DbWeight::get().reads((2_u64).saturating_mul(i.into()))) - .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(i.into()))) - .saturating_add(Weight::from_parts(0, 3566).saturating_mul(i.into())) - } /// Storage: `Staking::SlashingSpans` (r:1 w:1) /// Proof: `Staking::SlashingSpans` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `Staking::Bonded` (r:1 w:1) @@ -472,10 +452,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `2196 + s * (4 ±0)` // Estimated: `6248 + s * (4 ±0)` - // Minimum execution time: 86_765_000 picoseconds. - Weight::from_parts(95_173_565, 6248) - // Standard Error: 4_596 - .saturating_add(Weight::from_parts(1_354_849, 0).saturating_mul(s.into())) + // Minimum execution time: 87_495_000 picoseconds. + Weight::from_parts(95_710_388, 6248) + // Standard Error: 5_849 + .saturating_add(Weight::from_parts(1_339_335, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(13_u64)) .saturating_add(T::DbWeight::get().writes(12_u64)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(s.into()))) @@ -488,10 +468,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `66672` // Estimated: `70137` - // Minimum execution time: 104_490_000 picoseconds. - Weight::from_parts(1_162_956_951, 70137) - // Standard Error: 76_760 - .saturating_add(Weight::from_parts(6_485_569, 0).saturating_mul(s.into())) + // Minimum execution time: 98_255_000 picoseconds. + Weight::from_parts(892_807_378, 70137) + // Standard Error: 57_735 + .saturating_add(Weight::from_parts(4_876_449, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -527,11 +507,11 @@ impl WeightInfo for SubstrateWeight { fn payout_stakers_alive_staked(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `33297 + n * (377 ±0)` - // Estimated: `30944 + n * (3774 ±0)` - // Minimum execution time: 144_790_000 picoseconds. - Weight::from_parts(36_764_791, 30944) - // Standard Error: 89_592 - .saturating_add(Weight::from_parts(49_620_105, 0).saturating_mul(n.into())) + // Estimated: `30944 + n * (3774 ±3)` + // Minimum execution time: 144_258_000 picoseconds. + Weight::from_parts(175_256_796, 30944) + // Standard Error: 24_339 + .saturating_add(Weight::from_parts(46_011_700, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(14_u64)) .saturating_add(T::DbWeight::get().reads((6_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(4_u64)) @@ -555,10 +535,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `1991 + l * (7 ±0)` // Estimated: `8877` - // Minimum execution time: 81_768_000 picoseconds. - Weight::from_parts(85_332_982, 8877) - // Standard Error: 5_380 - .saturating_add(Weight::from_parts(70_298, 0).saturating_mul(l.into())) + // Minimum execution time: 83_532_000 picoseconds. + Weight::from_parts(86_757_943, 8877) + // Standard Error: 6_379 + .saturating_add(Weight::from_parts(57_566, 0).saturating_mul(l.into())) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -593,10 +573,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `2196 + s * (4 ±0)` // Estimated: `6248 + s * (4 ±0)` - // Minimum execution time: 96_123_000 picoseconds. - Weight::from_parts(100_278_672, 6248) - // Standard Error: 3_487 - .saturating_add(Weight::from_parts(1_326_503, 0).saturating_mul(s.into())) + // Minimum execution time: 96_776_000 picoseconds. + Weight::from_parts(100_950_027, 6248) + // Standard Error: 4_719 + .saturating_add(Weight::from_parts(1_432_091, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(12_u64)) .saturating_add(T::DbWeight::get().writes(11_u64)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(s.into()))) @@ -642,12 +622,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0 + n * (720 ±0) + v * (3598 ±0)` // Estimated: `512390 + n * (3566 ±0) + v * (3566 ±0)` - // Minimum execution time: 572_893_000 picoseconds. - Weight::from_parts(578_010_000, 512390) - // Standard Error: 2_094_268 - .saturating_add(Weight::from_parts(68_419_710, 0).saturating_mul(v.into())) - // Standard Error: 208_682 - .saturating_add(Weight::from_parts(18_826_175, 0).saturating_mul(n.into())) + // Minimum execution time: 577_699_000 picoseconds. + Weight::from_parts(582_827_000, 512390) + // Standard Error: 2_000_851 + .saturating_add(Weight::from_parts(67_316_744, 0).saturating_mul(v.into())) + // Standard Error: 199_373 + .saturating_add(Weight::from_parts(18_503_387, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(206_u64)) .saturating_add(T::DbWeight::get().reads((5_u64).saturating_mul(v.into()))) .saturating_add(T::DbWeight::get().reads((4_u64).saturating_mul(n.into()))) @@ -678,12 +658,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `3175 + n * (911 ±0) + v * (395 ±0)` // Estimated: `512390 + n * (3566 ±0) + v * (3566 ±0)` - // Minimum execution time: 33_836_205_000 picoseconds. - Weight::from_parts(34_210_443_000, 512390) - // Standard Error: 441_692 - .saturating_add(Weight::from_parts(6_122_533, 0).saturating_mul(v.into())) - // Standard Error: 441_692 - .saturating_add(Weight::from_parts(4_418_264, 0).saturating_mul(n.into())) + // Minimum execution time: 34_048_778_000 picoseconds. + Weight::from_parts(34_397_777_000, 512390) + // Standard Error: 346_115 + .saturating_add(Weight::from_parts(3_704_941, 0).saturating_mul(v.into())) + // Standard Error: 346_115 + .saturating_add(Weight::from_parts(4_064_819, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(201_u64)) .saturating_add(T::DbWeight::get().reads((5_u64).saturating_mul(v.into()))) .saturating_add(T::DbWeight::get().reads((4_u64).saturating_mul(n.into()))) @@ -700,10 +680,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `979 + v * (50 ±0)` // Estimated: `3510 + v * (2520 ±0)` - // Minimum execution time: 2_454_689_000 picoseconds. - Weight::from_parts(161_771_064, 3510) - // Standard Error: 31_022 - .saturating_add(Weight::from_parts(4_820_158, 0).saturating_mul(v.into())) + // Minimum execution time: 2_473_149_000 picoseconds. + Weight::from_parts(84_721_859, 3510) + // Standard Error: 8_690 + .saturating_add(Weight::from_parts(4_870_439, 0).saturating_mul(v.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(v.into()))) .saturating_add(Weight::from_parts(0, 2520).saturating_mul(v.into())) @@ -724,8 +704,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_073_000 picoseconds. - Weight::from_parts(5_452_000, 0) + // Minimum execution time: 5_312_000 picoseconds. + Weight::from_parts(5_897_000, 0) .saturating_add(T::DbWeight::get().writes(6_u64)) } /// Storage: `Staking::MinCommission` (r:0 w:1) @@ -744,12 +724,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_465_000 picoseconds. - Weight::from_parts(4_832_000, 0) + // Minimum execution time: 4_676_000 picoseconds. + Weight::from_parts(4_913_000, 0) .saturating_add(T::DbWeight::get().writes(6_u64)) } - /// Storage: `Staking::Bonded` (r:1 w:0) - /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:0) /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) /// Storage: `Staking::Nominators` (r:1 w:1) @@ -772,11 +750,11 @@ impl WeightInfo for SubstrateWeight { /// Proof: `VoterList::CounterForListNodes` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn chill_other() -> Weight { // Proof Size summary in bytes: - // Measured: `1939` + // Measured: `1773` // Estimated: `6248` - // Minimum execution time: 71_239_000 picoseconds. - Weight::from_parts(74_649_000, 6248) - .saturating_add(T::DbWeight::get().reads(12_u64)) + // Minimum execution time: 67_286_000 picoseconds. + Weight::from_parts(69_081_000, 6248) + .saturating_add(T::DbWeight::get().reads(11_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } /// Storage: `Staking::MinCommission` (r:1 w:0) @@ -787,8 +765,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `691` // Estimated: `3510` - // Minimum execution time: 12_525_000 picoseconds. - Weight::from_parts(13_126_000, 3510) + // Minimum execution time: 12_749_000 picoseconds. + Weight::from_parts(13_275_000, 3510) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -798,8 +776,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_918_000 picoseconds. - Weight::from_parts(3_176_000, 0) + // Minimum execution time: 3_155_000 picoseconds. + Weight::from_parts(3_319_000, 0) .saturating_add(T::DbWeight::get().writes(1_u64)) } } @@ -820,8 +798,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `927` // Estimated: `4764` - // Minimum execution time: 42_491_000 picoseconds. - Weight::from_parts(44_026_000, 4764) + // Minimum execution time: 43_427_000 picoseconds. + Weight::from_parts(45_221_000, 4764) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(4_u64)) } @@ -841,8 +819,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1990` // Estimated: `8877` - // Minimum execution time: 88_756_000 picoseconds. - Weight::from_parts(91_000_000, 8877) + // Minimum execution time: 87_100_000 picoseconds. + Weight::from_parts(90_599_000, 8877) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -868,8 +846,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `2195` // Estimated: `8877` - // Minimum execution time: 91_331_000 picoseconds. - Weight::from_parts(94_781_000, 8877) + // Minimum execution time: 91_488_000 picoseconds. + Weight::from_parts(94_126_000, 8877) .saturating_add(RocksDbWeight::get().reads(12_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -888,10 +866,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1115` // Estimated: `4764` - // Minimum execution time: 42_495_000 picoseconds. - Weight::from_parts(44_189_470, 4764) - // Standard Error: 1_389 - .saturating_add(Weight::from_parts(47_484, 0).saturating_mul(s.into())) + // Minimum execution time: 42_713_000 picoseconds. + Weight::from_parts(44_530_499, 4764) + // Standard Error: 1_067 + .saturating_add(Weight::from_parts(51_411, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -928,10 +906,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `2196 + s * (4 ±0)` // Estimated: `6248 + s * (4 ±0)` - // Minimum execution time: 89_004_000 picoseconds. - Weight::from_parts(96_677_570, 6248) - // Standard Error: 4_635 - .saturating_add(Weight::from_parts(1_387_718, 0).saturating_mul(s.into())) + // Minimum execution time: 88_700_000 picoseconds. + Weight::from_parts(98_329_624, 6248) + // Standard Error: 4_477 + .saturating_add(Weight::from_parts(1_347_380, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(13_u64)) .saturating_add(RocksDbWeight::get().writes(11_u64)) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(s.into()))) @@ -963,8 +941,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1372` // Estimated: `4556` - // Minimum execution time: 51_532_000 picoseconds. - Weight::from_parts(53_308_000, 4556) + // Minimum execution time: 51_877_000 picoseconds. + Weight::from_parts(53_503_000, 4556) .saturating_add(RocksDbWeight::get().reads(11_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -977,10 +955,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1280 + k * (569 ±0)` // Estimated: `4556 + k * (3033 ±0)` - // Minimum execution time: 28_955_000 picoseconds. - Weight::from_parts(29_609_869, 4556) - // Standard Error: 6_793 - .saturating_add(Weight::from_parts(6_412_124, 0).saturating_mul(k.into())) + // Minimum execution time: 29_604_000 picoseconds. + Weight::from_parts(31_726_296, 4556) + // Standard Error: 6_350 + .saturating_add(Weight::from_parts(6_416_846, 0).saturating_mul(k.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(k.into()))) @@ -1013,10 +991,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1866 + n * (102 ±0)` // Estimated: `6248 + n * (2520 ±0)` - // Minimum execution time: 64_080_000 picoseconds. - Weight::from_parts(61_985_382, 6248) - // Standard Error: 13_320 - .saturating_add(Weight::from_parts(4_030_513, 0).saturating_mul(n.into())) + // Minimum execution time: 64_276_000 picoseconds. + Weight::from_parts(62_615_844, 6248) + // Standard Error: 14_914 + .saturating_add(Weight::from_parts(4_097_019, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(12_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes(6_u64)) @@ -1040,8 +1018,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1650` // Estimated: `6248` - // Minimum execution time: 54_194_000 picoseconds. - Weight::from_parts(55_578_000, 6248) + // Minimum execution time: 55_064_000 picoseconds. + Weight::from_parts(56_566_000, 6248) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -1055,8 +1033,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `902` // Estimated: `4556` - // Minimum execution time: 16_597_000 picoseconds. - Weight::from_parts(16_980_000, 4556) + // Minimum execution time: 16_626_000 picoseconds. + Weight::from_parts(17_519_000, 4556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1070,8 +1048,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `969` // Estimated: `4556` - // Minimum execution time: 20_626_000 picoseconds. - Weight::from_parts(21_242_000, 4556) + // Minimum execution time: 20_545_000 picoseconds. + Weight::from_parts(21_395_000, 4556) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1083,8 +1061,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `902` // Estimated: `4556` - // Minimum execution time: 19_972_000 picoseconds. - Weight::from_parts(20_470_000, 4556) + // Minimum execution time: 20_179_000 picoseconds. + Weight::from_parts(20_728_000, 4556) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1094,8 +1072,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_571_000 picoseconds. - Weight::from_parts(2_720_000, 0) + // Minimum execution time: 2_594_000 picoseconds. + Weight::from_parts(2_777_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Staking::ForceEra` (r:0 w:1) @@ -1104,8 +1082,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_056_000 picoseconds. - Weight::from_parts(8_413_000, 0) + // Minimum execution time: 8_302_000 picoseconds. + Weight::from_parts(8_741_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Staking::ForceEra` (r:0 w:1) @@ -1114,8 +1092,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_162_000 picoseconds. - Weight::from_parts(8_497_000, 0) + // Minimum execution time: 8_504_000 picoseconds. + Weight::from_parts(8_774_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Staking::ForceEra` (r:0 w:1) @@ -1124,8 +1102,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_320_000 picoseconds. - Weight::from_parts(8_564_000, 0) + // Minimum execution time: 8_474_000 picoseconds. + Weight::from_parts(8_740_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `Staking::Invulnerables` (r:0 w:1) @@ -1135,31 +1113,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_470_000 picoseconds. - Weight::from_parts(3_110_242, 0) - // Standard Error: 63 - .saturating_add(Weight::from_parts(11_786, 0).saturating_mul(v.into())) + // Minimum execution time: 2_732_000 picoseconds. + Weight::from_parts(3_360_048, 0) + // Standard Error: 34 + .saturating_add(Weight::from_parts(9_964, 0).saturating_mul(v.into())) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: `Staking::Ledger` (r:5900 w:11800) - /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) - /// Storage: `Staking::Payee` (r:5900 w:0) - /// Proof: `Staking::Payee` (`max_values`: None, `max_size`: Some(73), added: 2548, mode: `MaxEncodedLen`) - /// Storage: `Staking::Bonded` (r:0 w:5900) - /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) - /// The range of component `i` is `[0, 5900]`. - fn deprecate_controller_batch(i: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `1356 + i * (151 ±0)` - // Estimated: `990 + i * (3566 ±0)` - // Minimum execution time: 2_101_000 picoseconds. - Weight::from_parts(2_238_000, 990) - // Standard Error: 56_753 - .saturating_add(Weight::from_parts(18_404_902, 0).saturating_mul(i.into())) - .saturating_add(RocksDbWeight::get().reads((2_u64).saturating_mul(i.into()))) - .saturating_add(RocksDbWeight::get().writes((3_u64).saturating_mul(i.into()))) - .saturating_add(Weight::from_parts(0, 3566).saturating_mul(i.into())) - } /// Storage: `Staking::SlashingSpans` (r:1 w:1) /// Proof: `Staking::SlashingSpans` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `Staking::Bonded` (r:1 w:1) @@ -1193,10 +1152,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `2196 + s * (4 ±0)` // Estimated: `6248 + s * (4 ±0)` - // Minimum execution time: 86_765_000 picoseconds. - Weight::from_parts(95_173_565, 6248) - // Standard Error: 4_596 - .saturating_add(Weight::from_parts(1_354_849, 0).saturating_mul(s.into())) + // Minimum execution time: 87_495_000 picoseconds. + Weight::from_parts(95_710_388, 6248) + // Standard Error: 5_849 + .saturating_add(Weight::from_parts(1_339_335, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(13_u64)) .saturating_add(RocksDbWeight::get().writes(12_u64)) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(s.into()))) @@ -1209,10 +1168,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `66672` // Estimated: `70137` - // Minimum execution time: 104_490_000 picoseconds. - Weight::from_parts(1_162_956_951, 70137) - // Standard Error: 76_760 - .saturating_add(Weight::from_parts(6_485_569, 0).saturating_mul(s.into())) + // Minimum execution time: 98_255_000 picoseconds. + Weight::from_parts(892_807_378, 70137) + // Standard Error: 57_735 + .saturating_add(Weight::from_parts(4_876_449, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1248,11 +1207,11 @@ impl WeightInfo for () { fn payout_stakers_alive_staked(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `33297 + n * (377 ±0)` - // Estimated: `30944 + n * (3774 ±0)` - // Minimum execution time: 144_790_000 picoseconds. - Weight::from_parts(36_764_791, 30944) - // Standard Error: 89_592 - .saturating_add(Weight::from_parts(49_620_105, 0).saturating_mul(n.into())) + // Estimated: `30944 + n * (3774 ±3)` + // Minimum execution time: 144_258_000 picoseconds. + Weight::from_parts(175_256_796, 30944) + // Standard Error: 24_339 + .saturating_add(Weight::from_parts(46_011_700, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(14_u64)) .saturating_add(RocksDbWeight::get().reads((6_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes(4_u64)) @@ -1276,10 +1235,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `1991 + l * (7 ±0)` // Estimated: `8877` - // Minimum execution time: 81_768_000 picoseconds. - Weight::from_parts(85_332_982, 8877) - // Standard Error: 5_380 - .saturating_add(Weight::from_parts(70_298, 0).saturating_mul(l.into())) + // Minimum execution time: 83_532_000 picoseconds. + Weight::from_parts(86_757_943, 8877) + // Standard Error: 6_379 + .saturating_add(Weight::from_parts(57_566, 0).saturating_mul(l.into())) .saturating_add(RocksDbWeight::get().reads(9_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -1314,10 +1273,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `2196 + s * (4 ±0)` // Estimated: `6248 + s * (4 ±0)` - // Minimum execution time: 96_123_000 picoseconds. - Weight::from_parts(100_278_672, 6248) - // Standard Error: 3_487 - .saturating_add(Weight::from_parts(1_326_503, 0).saturating_mul(s.into())) + // Minimum execution time: 96_776_000 picoseconds. + Weight::from_parts(100_950_027, 6248) + // Standard Error: 4_719 + .saturating_add(Weight::from_parts(1_432_091, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(12_u64)) .saturating_add(RocksDbWeight::get().writes(11_u64)) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(s.into()))) @@ -1363,12 +1322,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0 + n * (720 ±0) + v * (3598 ±0)` // Estimated: `512390 + n * (3566 ±0) + v * (3566 ±0)` - // Minimum execution time: 572_893_000 picoseconds. - Weight::from_parts(578_010_000, 512390) - // Standard Error: 2_094_268 - .saturating_add(Weight::from_parts(68_419_710, 0).saturating_mul(v.into())) - // Standard Error: 208_682 - .saturating_add(Weight::from_parts(18_826_175, 0).saturating_mul(n.into())) + // Minimum execution time: 577_699_000 picoseconds. + Weight::from_parts(582_827_000, 512390) + // Standard Error: 2_000_851 + .saturating_add(Weight::from_parts(67_316_744, 0).saturating_mul(v.into())) + // Standard Error: 199_373 + .saturating_add(Weight::from_parts(18_503_387, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(206_u64)) .saturating_add(RocksDbWeight::get().reads((5_u64).saturating_mul(v.into()))) .saturating_add(RocksDbWeight::get().reads((4_u64).saturating_mul(n.into()))) @@ -1399,12 +1358,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `3175 + n * (911 ±0) + v * (395 ±0)` // Estimated: `512390 + n * (3566 ±0) + v * (3566 ±0)` - // Minimum execution time: 33_836_205_000 picoseconds. - Weight::from_parts(34_210_443_000, 512390) - // Standard Error: 441_692 - .saturating_add(Weight::from_parts(6_122_533, 0).saturating_mul(v.into())) - // Standard Error: 441_692 - .saturating_add(Weight::from_parts(4_418_264, 0).saturating_mul(n.into())) + // Minimum execution time: 34_048_778_000 picoseconds. + Weight::from_parts(34_397_777_000, 512390) + // Standard Error: 346_115 + .saturating_add(Weight::from_parts(3_704_941, 0).saturating_mul(v.into())) + // Standard Error: 346_115 + .saturating_add(Weight::from_parts(4_064_819, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(201_u64)) .saturating_add(RocksDbWeight::get().reads((5_u64).saturating_mul(v.into()))) .saturating_add(RocksDbWeight::get().reads((4_u64).saturating_mul(n.into()))) @@ -1421,10 +1380,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `979 + v * (50 ±0)` // Estimated: `3510 + v * (2520 ±0)` - // Minimum execution time: 2_454_689_000 picoseconds. - Weight::from_parts(161_771_064, 3510) - // Standard Error: 31_022 - .saturating_add(Weight::from_parts(4_820_158, 0).saturating_mul(v.into())) + // Minimum execution time: 2_473_149_000 picoseconds. + Weight::from_parts(84_721_859, 3510) + // Standard Error: 8_690 + .saturating_add(Weight::from_parts(4_870_439, 0).saturating_mul(v.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(v.into()))) .saturating_add(Weight::from_parts(0, 2520).saturating_mul(v.into())) @@ -1445,8 +1404,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 5_073_000 picoseconds. - Weight::from_parts(5_452_000, 0) + // Minimum execution time: 5_312_000 picoseconds. + Weight::from_parts(5_897_000, 0) .saturating_add(RocksDbWeight::get().writes(6_u64)) } /// Storage: `Staking::MinCommission` (r:0 w:1) @@ -1465,12 +1424,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_465_000 picoseconds. - Weight::from_parts(4_832_000, 0) + // Minimum execution time: 4_676_000 picoseconds. + Weight::from_parts(4_913_000, 0) .saturating_add(RocksDbWeight::get().writes(6_u64)) } - /// Storage: `Staking::Bonded` (r:1 w:0) - /// Proof: `Staking::Bonded` (`max_values`: None, `max_size`: Some(72), added: 2547, mode: `MaxEncodedLen`) /// Storage: `Staking::Ledger` (r:1 w:0) /// Proof: `Staking::Ledger` (`max_values`: None, `max_size`: Some(1091), added: 3566, mode: `MaxEncodedLen`) /// Storage: `Staking::Nominators` (r:1 w:1) @@ -1493,11 +1450,11 @@ impl WeightInfo for () { /// Proof: `VoterList::CounterForListNodes` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) fn chill_other() -> Weight { // Proof Size summary in bytes: - // Measured: `1939` + // Measured: `1773` // Estimated: `6248` - // Minimum execution time: 71_239_000 picoseconds. - Weight::from_parts(74_649_000, 6248) - .saturating_add(RocksDbWeight::get().reads(12_u64)) + // Minimum execution time: 67_286_000 picoseconds. + Weight::from_parts(69_081_000, 6248) + .saturating_add(RocksDbWeight::get().reads(11_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } /// Storage: `Staking::MinCommission` (r:1 w:0) @@ -1508,8 +1465,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `691` // Estimated: `3510` - // Minimum execution time: 12_525_000 picoseconds. - Weight::from_parts(13_126_000, 3510) + // Minimum execution time: 12_749_000 picoseconds. + Weight::from_parts(13_275_000, 3510) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1519,8 +1476,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_918_000 picoseconds. - Weight::from_parts(3_176_000, 0) + // Minimum execution time: 3_155_000 picoseconds. + Weight::from_parts(3_319_000, 0) .saturating_add(RocksDbWeight::get().writes(1_u64)) } } diff --git a/substrate/frame/state-trie-migration/Cargo.toml b/substrate/frame/state-trie-migration/Cargo.toml index 46f86d203c3..9e81397fadd 100644 --- a/substrate/frame/state-trie-migration/Cargo.toml +++ b/substrate/frame/state-trie-migration/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME pallet migration of trie" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -18,18 +15,18 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", optional = true } +serde = { version = "1.0.188", optional = 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 } +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} [dev-dependencies] parking_lot = "0.12.1" @@ -38,7 +35,7 @@ pallet-balances = { path = "../balances" } sp-tracing = { path = "../../primitives/tracing" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/state-trie-migration/src/lib.rs b/substrate/frame/state-trie-migration/src/lib.rs index 5330634ca07..ac3996459cd 100644 --- a/substrate/frame/state-trie-migration/src/lib.rs +++ b/substrate/frame/state-trie-migration/src/lib.rs @@ -1051,7 +1051,7 @@ mod mock { use super::*; use crate as pallet_state_trie_migration; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64, Hooks}, weights::Weight, }; @@ -1081,7 +1081,6 @@ mod mock { pub const SS58Prefix: u8 = 42; } - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/statement/Cargo.toml b/substrate/frame/statement/Cargo.toml index d41afc3244b..a5c8cf5b8de 100644 --- a/substrate/frame/statement/Cargo.toml +++ b/substrate/frame/statement/Cargo.toml @@ -8,30 +8,27 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME pallet for statement store" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"]} scale-info = { version = "2.10.0", 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 } +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} log = { version = "0.4.17", default-features = false } [dev-dependencies] pallet-balances = { path = "../balances" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/statement/src/mock.rs b/substrate/frame/statement/src/mock.rs index 192baa1f218..10a74e100df 100644 --- a/substrate/frame/statement/src/mock.rs +++ b/substrate/frame/statement/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_statement; use frame_support::{ - derive_impl, ord_parameter_types, + ord_parameter_types, traits::{ConstU32, ConstU64, Everything}, weights::constants::RocksDbWeight, }; @@ -47,7 +47,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = Everything; type BlockWeights = (); diff --git a/substrate/frame/sudo/Cargo.toml b/substrate/frame/sudo/Cargo.toml index 027716ce317..ef507a95316 100644 --- a/substrate/frame/sudo/Cargo.toml +++ b/substrate/frame/sudo/Cargo.toml @@ -9,21 +9,18 @@ repository.workspace = true description = "FRAME pallet for sudo" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } +frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true} scale-info = { version = "2.10.0", 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 } +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} docify = "0.2.6" @@ -31,7 +28,7 @@ docify = "0.2.6" sp-core = { path = "../../primitives/core" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/sudo/src/mock.rs b/substrate/frame/sudo/src/mock.rs index 878e9239080..6f123b7c82b 100644 --- a/substrate/frame/sudo/src/mock.rs +++ b/substrate/frame/sudo/src/mock.rs @@ -19,10 +19,7 @@ use super::*; use crate as sudo; -use frame_support::{ - derive_impl, - traits::{ConstU32, Contains}, -}; +use frame_support::traits::{ConstU32, Contains}; use sp_core::{ConstU64, H256}; use sp_io; use sp_runtime::{ @@ -111,7 +108,6 @@ impl Contains for BlockEverything { } } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = BlockEverything; type BlockWeights = (); diff --git a/substrate/frame/support/Cargo.toml b/substrate/frame/support/Cargo.toml index 07f9075c82b..b8e21e60761 100644 --- a/substrate/frame/support/Cargo.toml +++ b/substrate/frame/support/Cargo.toml @@ -9,35 +9,32 @@ repository.workspace = true description = "Support code for the runtime." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] array-bytes = { version = "6.1", default-features = false } -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"] } +serde = { version = "1.0.188", default-features = false, features = ["alloc", "derive"] } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } frame-metadata = { version = "16.0.0", default-features = false, features = ["current"] } -sp-api = { path = "../../primitives/api", default-features = false, 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 } -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 } +sp-api = { path = "../../primitives/api", default-features = false, 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} +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 } +frame-support-procedural = { path = "procedural", default-features = false} paste = "1.0" -sp-state-machine = { path = "../../primitives/state-machine", default-features = false, optional = true } +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" @@ -45,7 +42,7 @@ log = { version = "0.4.17", default-features = false } sp-core-hashing-proc-macro = { path = "../../primitives/core/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-genesis-builder = { path = "../../primitives/genesis-builder", default-features=false} serde_json = { version = "1.0.108", default-features = false, features = ["alloc"] } docify = "0.2.6" static_assertions = "1.1.0" @@ -58,7 +55,7 @@ pretty_assertions = "1.2.1" frame-system = { path = "../system" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "environmental/std", @@ -104,8 +101,8 @@ no-metadata-docs = [ ] # By default some types have documentation, `full-metadata-docs` allows to add documentation to # more types in the metadata. -full-metadata-docs = ["scale-info/docs"] +full-metadata-docs = [ "scale-info/docs" ] # Generate impl-trait for tuples with the given number of tuples. Will be needed as the number of # pallets in a runtime grows. Does increase the compile time! -tuples-96 = ["frame-support-procedural/tuples-96"] -tuples-128 = ["frame-support-procedural/tuples-128"] +tuples-96 = [ "frame-support-procedural/tuples-96" ] +tuples-128 = [ "frame-support-procedural/tuples-128" ] diff --git a/substrate/frame/support/procedural/Cargo.toml b/substrate/frame/support/procedural/Cargo.toml index 08995c578c5..45ed1750a52 100644 --- a/substrate/frame/support/procedural/Cargo.toml +++ b/substrate/frame/support/procedural/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "Proc macro of Support code for the runtime." -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -24,18 +21,15 @@ cfg-expr = "0.15.5" itertools = "0.10.3" proc-macro2 = "1.0.56" quote = "1.0.28" -syn = { version = "2.0.40", features = ["full"] } +syn = { version = "2.0.38", features = ["full"] } 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-core-hashing = { path = "../../../primitives/core/hashing" } -[dev-dependencies] -regex = "1" - [features] -default = ["std"] +default = [ "std" ] std = [] no-metadata-docs = [] # Generate impl-trait for tuples with the given number of tuples. Will be needed as the number of diff --git a/substrate/frame/support/procedural/src/construct_runtime/expand/mod.rs b/substrate/frame/support/procedural/src/construct_runtime/expand/mod.rs index 88f9a3c6e33..a0fc6b8130b 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/expand/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/expand/mod.rs @@ -26,7 +26,6 @@ mod metadata; mod origin; mod outer_enums; mod slash_reason; -mod task; mod unsigned; pub use call::expand_outer_dispatch; @@ -39,5 +38,4 @@ pub use metadata::expand_runtime_metadata; pub use origin::expand_outer_origin; pub use outer_enums::{expand_outer_enum, OuterEnumType}; pub use slash_reason::expand_outer_slash_reason; -pub use task::expand_outer_task; pub use unsigned::expand_outer_validate_unsigned; diff --git a/substrate/frame/support/procedural/src/construct_runtime/expand/task.rs b/substrate/frame/support/procedural/src/construct_runtime/expand/task.rs deleted file mode 100644 index bd952202bbb..00000000000 --- a/substrate/frame/support/procedural/src/construct_runtime/expand/task.rs +++ /dev/null @@ -1,131 +0,0 @@ -// 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 crate::construct_runtime::Pallet; -use proc_macro2::{Ident, TokenStream as TokenStream2}; -use quote::quote; - -/// Expands aggregate `RuntimeTask` enum. -pub fn expand_outer_task( - runtime_name: &Ident, - pallet_decls: &[Pallet], - scrate: &TokenStream2, -) -> TokenStream2 { - let mut from_impls = Vec::new(); - let mut task_variants = Vec::new(); - let mut variant_names = Vec::new(); - let mut task_paths = Vec::new(); - for decl in pallet_decls { - if decl.find_part("Task").is_none() { - continue; - } - - let variant_name = &decl.name; - let path = &decl.path; - let index = decl.index; - - from_impls.push(quote! { - impl From<#path::Task<#runtime_name>> for RuntimeTask { - fn from(hr: #path::Task<#runtime_name>) -> Self { - RuntimeTask::#variant_name(hr) - } - } - - impl TryInto<#path::Task<#runtime_name>> for RuntimeTask { - type Error = (); - - fn try_into(self) -> Result<#path::Task<#runtime_name>, Self::Error> { - match self { - RuntimeTask::#variant_name(hr) => Ok(hr), - _ => Err(()), - } - } - } - }); - - task_variants.push(quote! { - #[codec(index = #index)] - #variant_name(#path::Task<#runtime_name>), - }); - - variant_names.push(quote!(#variant_name)); - - task_paths.push(quote!(#path::Task)); - } - - let prelude = quote!(#scrate::traits::tasks::__private); - - const INCOMPLETE_MATCH_QED: &'static str = - "cannot have an instantiated RuntimeTask without some Task variant in the runtime. QED"; - - let output = quote! { - /// An aggregation of all `Task` enums across all pallets included in the current runtime. - #[derive( - Clone, Eq, PartialEq, - #scrate::__private::codec::Encode, - #scrate::__private::codec::Decode, - #scrate::__private::scale_info::TypeInfo, - #scrate::__private::RuntimeDebug, - )] - pub enum RuntimeTask { - #( #task_variants )* - } - - #[automatically_derived] - impl #scrate::traits::Task for RuntimeTask { - type Enumeration = #prelude::IntoIter; - - fn is_valid(&self) -> bool { - match self { - #(RuntimeTask::#variant_names(val) => val.is_valid(),)* - _ => unreachable!(#INCOMPLETE_MATCH_QED), - } - } - - fn run(&self) -> Result<(), #scrate::traits::tasks::__private::DispatchError> { - match self { - #(RuntimeTask::#variant_names(val) => val.run(),)* - _ => unreachable!(#INCOMPLETE_MATCH_QED), - } - } - - fn weight(&self) -> #scrate::pallet_prelude::Weight { - match self { - #(RuntimeTask::#variant_names(val) => val.weight(),)* - _ => unreachable!(#INCOMPLETE_MATCH_QED), - } - } - - fn task_index(&self) -> u32 { - match self { - #(RuntimeTask::#variant_names(val) => val.task_index(),)* - _ => unreachable!(#INCOMPLETE_MATCH_QED), - } - } - - fn iter() -> Self::Enumeration { - let mut all_tasks = Vec::new(); - #(all_tasks.extend(#task_paths::iter().map(RuntimeTask::from).collect::>());)* - all_tasks.into_iter() - } - } - - #( #from_impls )* - }; - - output -} diff --git a/substrate/frame/support/procedural/src/construct_runtime/mod.rs b/substrate/frame/support/procedural/src/construct_runtime/mod.rs index 7a9c4d89a74..ce34694275b 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/mod.rs @@ -253,7 +253,7 @@ pub fn construct_runtime(input: TokenStream) -> TokenStream { let res = res.unwrap_or_else(|e| e.to_compile_error()); let res = expander::Expander::new("construct_runtime") - .dry(std::env::var("EXPAND_MACROS").is_err()) + .dry(std::env::var("FRAME_EXPAND").is_err()) .verbose(true) .write_to_out_dir(res) .expect("Does not fail because of IO in OUT_DIR; qed"); @@ -386,7 +386,6 @@ fn construct_runtime_final_expansion( let pallet_to_index = decl_pallet_runtime_setup(&name, &pallets, &scrate); let dispatch = expand::expand_outer_dispatch(&name, system_pallet, &pallets, &scrate); - let tasks = expand::expand_outer_task(&name, &pallets, &scrate); let metadata = expand::expand_runtime_metadata( &name, &pallets, @@ -476,8 +475,6 @@ fn construct_runtime_final_expansion( #dispatch - #tasks - #metadata #outer_config @@ -603,12 +600,66 @@ fn decl_all_pallets<'a>( } }); + let all_pallets_without_system_reversed = attribute_to_names.iter().map(|(attr, names)| { + let names = names.iter().filter(|n| **n != SYSTEM_PALLET_NAME).rev(); + quote! { + #attr + /// All pallets included in the runtime as a nested tuple of types in reversed order. + /// Excludes the System pallet. + #[deprecated(note = "Using reverse pallet orders is deprecated. use only \ + `AllPalletsWithSystem or AllPalletsWithoutSystem`")] + pub type AllPalletsWithoutSystemReversed = ( #(#names,)* ); + } + }); + + let all_pallets_with_system_reversed = attribute_to_names.iter().map(|(attr, names)| { + let names = names.iter().rev(); + quote! { + #attr + /// All pallets included in the runtime as a nested tuple of types in reversed order. + #[deprecated(note = "Using reverse pallet orders is deprecated. use only \ + `AllPalletsWithSystem or AllPalletsWithoutSystem`")] + pub type AllPalletsWithSystemReversed = ( #(#names,)* ); + } + }); + + let all_pallets_reversed_with_system_first = attribute_to_names.iter().map(|(attr, names)| { + let system = quote::format_ident!("{}", SYSTEM_PALLET_NAME); + let names = std::iter::once(&system) + .chain(names.iter().rev().filter(|n| **n != SYSTEM_PALLET_NAME).cloned()); + quote! { + #attr + /// All pallets included in the runtime as a nested tuple of types in reversed order. + /// With the system pallet first. + #[deprecated(note = "Using reverse pallet orders is deprecated. use only \ + `AllPalletsWithSystem or AllPalletsWithoutSystem`")] + pub type AllPalletsReversedWithSystemFirst = ( #(#names,)* ); + } + }); + quote!( #types + /// All pallets included in the runtime as a nested tuple of types. + #[deprecated(note = "The type definition has changed from representing all pallets \ + excluding system, in reversed order to become the representation of all pallets \ + including system pallet in regular order. For this reason it is encouraged to use \ + explicitly one of `AllPalletsWithSystem`, `AllPalletsWithoutSystem`, \ + `AllPalletsWithSystemReversed`, `AllPalletsWithoutSystemReversed`. \ + Note that the type `frame_executive::Executive` expects one of `AllPalletsWithSystem` \ + , `AllPalletsWithSystemReversed`, `AllPalletsReversedWithSystemFirst`. More details in \ + https://github.com/paritytech/substrate/pull/10043")] + pub type AllPallets = AllPalletsWithSystem; + #( #all_pallets_with_system )* #( #all_pallets_without_system )* + + #( #all_pallets_with_system_reversed )* + + #( #all_pallets_without_system_reversed )* + + #( #all_pallets_reversed_with_system_first )* ) } fn decl_pallet_runtime_setup( diff --git a/substrate/frame/support/procedural/src/construct_runtime/parse.rs b/substrate/frame/support/procedural/src/construct_runtime/parse.rs index 88f3f14dc86..9b08e164697 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/parse.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/parse.rs @@ -42,7 +42,6 @@ mod keyword { syn::custom_keyword!(ValidateUnsigned); syn::custom_keyword!(FreezeReason); syn::custom_keyword!(HoldReason); - syn::custom_keyword!(Task); syn::custom_keyword!(LockId); syn::custom_keyword!(SlashReason); syn::custom_keyword!(exclude_parts); @@ -405,7 +404,6 @@ pub enum PalletPartKeyword { ValidateUnsigned(keyword::ValidateUnsigned), FreezeReason(keyword::FreezeReason), HoldReason(keyword::HoldReason), - Task(keyword::Task), LockId(keyword::LockId), SlashReason(keyword::SlashReason), } @@ -436,8 +434,6 @@ impl Parse for PalletPartKeyword { Ok(Self::FreezeReason(input.parse()?)) } else if lookahead.peek(keyword::HoldReason) { Ok(Self::HoldReason(input.parse()?)) - } else if lookahead.peek(keyword::Task) { - Ok(Self::Task(input.parse()?)) } else if lookahead.peek(keyword::LockId) { Ok(Self::LockId(input.parse()?)) } else if lookahead.peek(keyword::SlashReason) { @@ -463,7 +459,6 @@ impl PalletPartKeyword { Self::ValidateUnsigned(_) => "ValidateUnsigned", Self::FreezeReason(_) => "FreezeReason", Self::HoldReason(_) => "HoldReason", - Self::Task(_) => "Task", Self::LockId(_) => "LockId", Self::SlashReason(_) => "SlashReason", } @@ -476,7 +471,7 @@ impl PalletPartKeyword { /// Returns the names of all pallet parts that allow to have a generic argument. fn all_generic_arg() -> &'static [&'static str] { - &["Event", "Error", "Origin", "Config", "Task"] + &["Event", "Error", "Origin", "Config"] } } @@ -494,7 +489,6 @@ impl ToTokens for PalletPartKeyword { Self::ValidateUnsigned(inner) => inner.to_tokens(tokens), Self::FreezeReason(inner) => inner.to_tokens(tokens), Self::HoldReason(inner) => inner.to_tokens(tokens), - Self::Task(inner) => inner.to_tokens(tokens), Self::LockId(inner) => inner.to_tokens(tokens), Self::SlashReason(inner) => inner.to_tokens(tokens), } diff --git a/substrate/frame/support/procedural/src/derive_impl.rs b/substrate/frame/support/procedural/src/derive_impl.rs index d6d5bf68efd..8b5e334f1f5 100644 --- a/substrate/frame/support/procedural/src/derive_impl.rs +++ b/substrate/frame/support/procedural/src/derive_impl.rs @@ -46,15 +46,11 @@ pub struct PalletAttr { typ: PalletAttrType, } -fn is_runtime_type(item: &syn::ImplItemType) -> bool { - item.attrs.iter().any(|attr| { - if let Ok(PalletAttr { typ: PalletAttrType::RuntimeType(_), .. }) = - parse2::(attr.into_token_stream()) - { - return true - } - false - }) +fn get_first_item_pallet_attr(item: &syn::ImplItemType) -> syn::Result> +where + Attr: syn::parse::Parse, +{ + item.attrs.get(0).map(|a| syn::parse2(a.into_token_stream())).transpose() } #[derive(Parse, Debug)] @@ -136,15 +132,12 @@ fn combine_impls( return None } if let ImplItem::Type(typ) = item.clone() { - let cfg_attrs = typ - .attrs - .iter() - .filter(|attr| attr.path().get_ident().map_or(false, |ident| ident == "cfg")) - .map(|attr| attr.to_token_stream()); - if is_runtime_type(&typ) { + let mut typ = typ.clone(); + if let Ok(Some(PalletAttr { typ: PalletAttrType::RuntimeType(_), .. })) = + get_first_item_pallet_attr::(&mut typ) + { let item: ImplItem = if inject_runtime_types { parse_quote! { - #( #cfg_attrs )* type #ident = #ident; } } else { @@ -154,7 +147,6 @@ fn combine_impls( } // modify and insert uncolliding type items let modified_item: ImplItem = parse_quote! { - #( #cfg_attrs )* type #ident = <#default_impl_path as #disambiguation_path>::#ident; }; return Some(modified_item) @@ -235,25 +227,3 @@ fn test_derive_impl_attr_args_parsing() { assert!(parse2::(quote!()).is_err()); assert!(parse2::(quote!(Config Config)).is_err()); } - -#[test] -fn test_runtime_type_with_doc() { - trait TestTrait { - type Test; - } - #[allow(unused)] - struct TestStruct; - let p = parse2::(quote!( - impl TestTrait for TestStruct { - /// Some doc - #[inject_runtime_type] - type Test = u32; - } - )) - .unwrap(); - for item in p.items { - if let ImplItem::Type(typ) = item { - assert_eq!(is_runtime_type(&typ), true); - } - } -} diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs index a420a18835f..636e7ad0eff 100644 --- a/substrate/frame/support/procedural/src/lib.rs +++ b/substrate/frame/support/procedural/src/lib.rs @@ -646,6 +646,7 @@ pub fn storage_alias(attributes: TokenStream, input: TokenStream) -> TokenStream /// ``` /// /// where `TestDefaultConfig` was defined and registered as follows: +/// /// ```ignore /// pub struct TestDefaultConfig; /// @@ -672,6 +673,7 @@ pub fn storage_alias(attributes: TokenStream, input: TokenStream) -> TokenStream /// ``` /// /// The above call to `derive_impl` would expand to roughly the following: +/// /// ```ignore /// impl frame_system::Config for Test { /// use frame_system::config_preludes::TestDefaultConfig; @@ -879,7 +881,6 @@ pub fn inject_runtime_type(_: TokenStream, tokens: TokenStream) -> TokenStream { let item = syn::parse_macro_input!(item as TraitItemType); if item.ident != "RuntimeCall" && item.ident != "RuntimeEvent" && - item.ident != "RuntimeTask" && item.ident != "RuntimeOrigin" && item.ident != "RuntimeHoldReason" && item.ident != "RuntimeFreezeReason" && @@ -887,11 +888,10 @@ pub fn inject_runtime_type(_: TokenStream, tokens: TokenStream) -> TokenStream { { return syn::Error::new_spanned( item, - "`#[inject_runtime_type]` can only be attached to `RuntimeCall`, `RuntimeEvent`, \ - `RuntimeTask`, `RuntimeOrigin` or `PalletInfo`", + "`#[inject_runtime_type]` can only be attached to `RuntimeCall`, `RuntimeEvent`, `RuntimeOrigin` or `PalletInfo`", ) .to_compile_error() - .into() + .into(); } tokens } @@ -1097,11 +1097,8 @@ pub fn weight(_: TokenStream, _: TokenStream) -> TokenStream { pallet_macro_stub() } -/// -/// --- -/// -/// **Rust-Analyzer users**: See the documentation of the Rust item in -/// [`frame_support::pallet_macros::call`](../../frame_support/pallet_macros/attr.call.html). +/// Compact encoding for arguments can be achieved via `#[pallet::compact]`. The function must +/// return a `DispatchResultWithPostInfo` or `DispatchResult`. #[proc_macro_attribute] pub fn compact(_: TokenStream, _: TokenStream) -> TokenStream { pallet_macro_stub() @@ -1111,7 +1108,7 @@ pub fn compact(_: TokenStream, _: TokenStream) -> TokenStream { /// --- /// /// **Rust-Analyzer users**: See the documentation of the Rust item in -/// [`frame_support::pallet_macros::call`](../../frame_support/pallet_macros/attr.call.html). +/// `frame_support::pallet_macros::call`. #[proc_macro_attribute] pub fn call(_: TokenStream, _: TokenStream) -> TokenStream { pallet_macro_stub() @@ -1120,10 +1117,41 @@ pub fn call(_: TokenStream, _: TokenStream) -> TokenStream { /// Each dispatchable may also be annotated with the `#[pallet::call_index($idx)]` attribute, /// which explicitly defines the codec index for the dispatchable function in the `Call` enum. /// -/// --- +/// All call indexes start from 0, until it encounters a dispatchable function with a defined +/// call index. The dispatchable function that lexically follows the function with a defined +/// call index will have that call index, but incremented by 1, e.g. if there are 3 +/// dispatchable functions `fn foo`, `fn bar` and `fn qux` in that order, and only `fn bar` +/// has a call index of 10, then `fn qux` will have an index of 11, instead of 1. /// -/// **Rust-Analyzer users**: See the documentation of the Rust item in -/// [`frame_support::pallet_macros::call`](../../frame_support/pallet_macros/attr.call.html). +/// All arguments must implement [`Debug`], [`PartialEq`], [`Eq`], `Decode`, `Encode`, and +/// [`Clone`]. For ease of use, bound by the trait `frame_support::pallet_prelude::Member`. +/// +/// If no `#[pallet::call]` exists, then a default implementation corresponding to the +/// following code is automatically generated: +/// +/// ```ignore +/// #[pallet::call] +/// impl Pallet {} +/// ``` +/// +/// **WARNING**: modifying dispatchables, changing their order, removing some, etc., must be +/// done with care. Indeed this will change the outer runtime call type (which is an enum with +/// one variant per pallet), this outer runtime call can be stored on-chain (e.g. in +/// `pallet-scheduler`). Thus migration might be needed. To mitigate against some of this, the +/// `#[pallet::call_index($idx)]` attribute can be used to fix the order of the dispatchable so +/// that the `Call` enum encoding does not change after modification. As a general rule of +/// thumb, it is therefore adventageous to always add new calls to the end so you can maintain +/// the existing order of calls. +/// +/// ### Macro expansion +/// +/// The macro creates an enum `Call` with one variant per dispatchable. This enum implements: +/// [`Clone`], [`Eq`], [`PartialEq`], [`Debug`] (with stripped implementation in `not("std")`), +/// `Encode`, `Decode`, `GetDispatchInfo`, `GetCallName`, `GetCallIndex` and +/// `UnfilteredDispatchable`. +/// +/// The macro implements the `Callable` trait on `Pallet` and a function `call_functions` +/// which returns the dispatchable metadata. #[proc_macro_attribute] pub fn call_index(_: TokenStream, _: TokenStream) -> TokenStream { pallet_macro_stub() @@ -1518,56 +1546,6 @@ pub fn composite_enum(_: TokenStream, _: TokenStream) -> TokenStream { pallet_macro_stub() } -/// -/// --- -/// -/// **Rust-Analyzer users**: See the documentation of the Rust item in -/// `frame_support::pallet_macros::tasks_experimental`. -#[proc_macro_attribute] -pub fn tasks_experimental(_: TokenStream, _: TokenStream) -> TokenStream { - pallet_macro_stub() -} - -/// -/// --- -/// -/// **Rust-Analyzer users**: See the documentation of the Rust item in -/// `frame_support::pallet_macros::task_list`. -#[proc_macro_attribute] -pub fn task_list(_: TokenStream, _: TokenStream) -> TokenStream { - pallet_macro_stub() -} - -/// -/// --- -/// -/// **Rust-Analyzer users**: See the documentation of the Rust item in -/// `frame_support::pallet_macros::task_condition`. -#[proc_macro_attribute] -pub fn task_condition(_: TokenStream, _: TokenStream) -> TokenStream { - pallet_macro_stub() -} - -/// -/// --- -/// -/// **Rust-Analyzer users**: See the documentation of the Rust item in -/// `frame_support::pallet_macros::task_weight`. -#[proc_macro_attribute] -pub fn task_weight(_: TokenStream, _: TokenStream) -> TokenStream { - pallet_macro_stub() -} - -/// -/// --- -/// -/// **Rust-Analyzer users**: See the documentation of the Rust item in -/// `frame_support::pallet_macros::task_index`. -#[proc_macro_attribute] -pub fn task_index(_: TokenStream, _: TokenStream) -> TokenStream { - pallet_macro_stub() -} - /// Can be attached to a module. Doing so will declare that module as importable into a pallet /// via [`#[import_section]`](`macro@import_section`). /// diff --git a/substrate/frame/support/procedural/src/pallet/expand/call.rs b/substrate/frame/support/procedural/src/pallet/expand/call.rs index 624cde018dc..cf302faafc7 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/call.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/call.rs @@ -241,15 +241,6 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { }) .collect::>(); - let cfg_attrs = methods - .iter() - .map(|method| { - let attrs = - method.cfg_attrs.iter().map(|attr| attr.to_token_stream()).collect::>(); - quote::quote!( #( #attrs )* ) - }) - .collect::>(); - let feeless_check = methods.iter().map(|method| &method.feeless_check).collect::>(); let feeless_check_result = feeless_check.iter().zip(args_name.iter()).map(|(feeless_check, arg_name)| { @@ -306,7 +297,6 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { #frame_support::Never, ), #( - #cfg_attrs #[doc = #fn_doc] #[codec(index = #call_index)] #fn_name { @@ -320,7 +310,6 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { impl<#type_impl_gen> #call_ident<#type_use_gen> #where_clause { #( - #cfg_attrs #[doc = #new_call_variant_doc] pub fn #new_call_variant_fn_name( #( #args_name_stripped: #args_type ),* @@ -339,7 +328,6 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { fn get_dispatch_info(&self) -> #frame_support::dispatch::DispatchInfo { match *self { #( - #cfg_attrs Self::#fn_name { #( #args_name_pattern_ref, )* } => { let __pallet_base_weight = #fn_weight; @@ -377,7 +365,6 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { fn is_feeless(&self, origin: &Self::Origin) -> bool { match *self { #( - #cfg_attrs Self::#fn_name { #( #args_name_pattern_ref, )* } => { #feeless_check_result }, @@ -392,13 +379,13 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { { fn get_call_name(&self) -> &'static str { match *self { - #( #cfg_attrs Self::#fn_name { .. } => stringify!(#fn_name), )* + #( Self::#fn_name { .. } => stringify!(#fn_name), )* Self::__Ignore(_, _) => unreachable!("__PhantomItem cannot be used."), } } fn get_call_names() -> &'static [&'static str] { - &[ #( #cfg_attrs stringify!(#fn_name), )* ] + &[ #( stringify!(#fn_name), )* ] } } @@ -407,13 +394,13 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { { fn get_call_index(&self) -> u8 { match *self { - #( #cfg_attrs Self::#fn_name { .. } => #call_index, )* + #( Self::#fn_name { .. } => #call_index, )* Self::__Ignore(_, _) => unreachable!("__PhantomItem cannot be used."), } } fn get_call_indices() -> &'static [u8] { - &[ #( #cfg_attrs #call_index, )* ] + &[ #( #call_index, )* ] } } @@ -429,7 +416,6 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { #frame_support::dispatch_context::run_in_context(|| { match self { #( - #cfg_attrs Self::#fn_name { #( #args_name_pattern, )* } => { #frame_support::__private::sp_tracing::enter_span!( #frame_support::__private::sp_tracing::trace_span!(stringify!(#fn_name)) diff --git a/substrate/frame/support/procedural/src/pallet/expand/error.rs b/substrate/frame/support/procedural/src/pallet/expand/error.rs index 72fb6e92357..877489fd605 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/error.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/error.rs @@ -16,14 +16,10 @@ // limitations under the License. use crate::{ - pallet::{ - parse::error::{VariantDef, VariantField}, - Def, - }, + pallet::{parse::error::VariantField, Def}, COUNTER, }; use frame_support_procedural_tools::get_doc_literals; -use quote::ToTokens; use syn::spanned::Spanned; /// @@ -71,23 +67,20 @@ pub fn expand_error(def: &mut Def) -> proc_macro2::TokenStream { ) ); - let as_str_matches = error.variants.iter().map( - |VariantDef { ident: variant, field: field_ty, docs: _, cfg_attrs }| { - let variant_str = variant.to_string(); - let cfg_attrs = cfg_attrs.iter().map(|attr| attr.to_token_stream()); - match field_ty { - Some(VariantField { is_named: true }) => { - quote::quote_spanned!(error.attr_span => #( #cfg_attrs )* Self::#variant { .. } => #variant_str,) - }, - Some(VariantField { is_named: false }) => { - quote::quote_spanned!(error.attr_span => #( #cfg_attrs )* Self::#variant(..) => #variant_str,) - }, - None => { - quote::quote_spanned!(error.attr_span => #( #cfg_attrs )* Self::#variant => #variant_str,) - }, - } - }, - ); + let as_str_matches = error.variants.iter().map(|(variant, field_ty, _)| { + let variant_str = variant.to_string(); + match field_ty { + Some(VariantField { is_named: true }) => { + quote::quote_spanned!(error.attr_span => Self::#variant { .. } => #variant_str,) + }, + Some(VariantField { is_named: false }) => { + quote::quote_spanned!(error.attr_span => Self::#variant(..) => #variant_str,) + }, + None => { + quote::quote_spanned!(error.attr_span => Self::#variant => #variant_str,) + }, + } + }); let error_item = { let item = &mut def.item.content.as_mut().expect("Checked by def parser").1[error.index]; diff --git a/substrate/frame/support/procedural/src/pallet/expand/mod.rs b/substrate/frame/support/procedural/src/pallet/expand/mod.rs index db242df781b..6f32e569751 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/mod.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/mod.rs @@ -31,7 +31,6 @@ mod origin; mod pallet_struct; mod storage; mod store_trait; -mod tasks; mod tt_default_parts; mod type_value; mod validate_unsigned; @@ -61,7 +60,6 @@ pub fn expand(mut def: Def) -> proc_macro2::TokenStream { let pallet_struct = pallet_struct::expand_pallet_struct(&mut def); let config = config::expand_config(&mut def); let call = call::expand_call(&mut def); - let tasks = tasks::expand_tasks(&mut def); let error = error::expand_error(&mut def); let event = event::expand_event(&mut def); let storages = storage::expand_storages(&mut def); @@ -102,7 +100,6 @@ storage item. Otherwise, all storage items are listed among [*Type Definitions*] #pallet_struct #config #call - #tasks #error #event #storages diff --git a/substrate/frame/support/procedural/src/pallet/expand/tasks.rs b/substrate/frame/support/procedural/src/pallet/expand/tasks.rs deleted file mode 100644 index 6697e5c822a..00000000000 --- a/substrate/frame/support/procedural/src/pallet/expand/tasks.rs +++ /dev/null @@ -1,267 +0,0 @@ -//! Contains logic for expanding task-related items. - -// 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. - -//! Home of the expansion code for the Tasks API - -use crate::pallet::{parse::tasks::*, Def}; -use derive_syn_parse::Parse; -use inflector::Inflector; -use proc_macro2::TokenStream as TokenStream2; -use quote::{format_ident, quote, ToTokens}; -use syn::{parse_quote, spanned::Spanned, ItemEnum, ItemImpl}; - -impl TaskEnumDef { - /// Since we optionally allow users to manually specify a `#[pallet::task_enum]`, in the - /// event they _don't_ specify one (which is actually the most common behavior) we have to - /// generate one based on the existing [`TasksDef`]. This method performs that generation. - pub fn generate( - tasks: &TasksDef, - type_decl_bounded_generics: TokenStream2, - type_use_generics: TokenStream2, - ) -> Self { - let variants = if tasks.tasks_attr.is_some() { - tasks - .tasks - .iter() - .map(|task| { - let ident = &task.item.sig.ident; - let ident = - format_ident!("{}", ident.to_string().to_class_case(), span = ident.span()); - - let args = task.item.sig.inputs.iter().collect::>(); - - if args.is_empty() { - quote!(#ident) - } else { - quote!(#ident { - #(#args),* - }) - } - }) - .collect::>() - } else { - Vec::new() - }; - let mut task_enum_def: TaskEnumDef = parse_quote! { - /// Auto-generated enum that encapsulates all tasks defined by this pallet. - /// - /// Conceptually similar to the [`Call`] enum, but for tasks. This is only - /// generated if there are tasks present in this pallet. - #[pallet::task_enum] - pub enum Task<#type_decl_bounded_generics> { - #( - #variants, - )* - } - }; - task_enum_def.type_use_generics = type_use_generics; - task_enum_def - } -} - -impl ToTokens for TaskEnumDef { - fn to_tokens(&self, tokens: &mut TokenStream2) { - let item_enum = &self.item_enum; - let ident = &item_enum.ident; - let vis = &item_enum.vis; - let attrs = &item_enum.attrs; - let generics = &item_enum.generics; - let variants = &item_enum.variants; - let scrate = &self.scrate; - let type_use_generics = &self.type_use_generics; - if self.attr.is_some() { - // `item_enum` is short-hand / generated enum - tokens.extend(quote! { - #(#attrs)* - #[derive( - #scrate::CloneNoBound, - #scrate::EqNoBound, - #scrate::PartialEqNoBound, - #scrate::pallet_prelude::Encode, - #scrate::pallet_prelude::Decode, - #scrate::pallet_prelude::TypeInfo, - )] - #[codec(encode_bound())] - #[codec(decode_bound())] - #[scale_info(skip_type_params(#type_use_generics))] - #vis enum #ident #generics { - #variants - #[doc(hidden)] - #[codec(skip)] - __Ignore(core::marker::PhantomData, #scrate::Never), - } - - impl core::fmt::Debug for #ident<#type_use_generics> { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct(stringify!(#ident)).field("value", self).finish() - } - } - }); - } else { - // `item_enum` is a manually specified enum (no attribute) - tokens.extend(item_enum.to_token_stream()); - } - } -} - -/// Represents an already-expanded [`TasksDef`]. -#[derive(Parse)] -pub struct ExpandedTasksDef { - pub task_item_impl: ItemImpl, - pub task_trait_impl: ItemImpl, -} - -impl ToTokens for TasksDef { - fn to_tokens(&self, tokens: &mut TokenStream2) { - let scrate = &self.scrate; - let enum_ident = syn::Ident::new("Task", self.enum_ident.span()); - let enum_arguments = &self.enum_arguments; - let enum_use = quote!(#enum_ident #enum_arguments); - - let task_fn_idents = self - .tasks - .iter() - .map(|task| { - format_ident!( - "{}", - &task.item.sig.ident.to_string().to_class_case(), - span = task.item.sig.ident.span() - ) - }) - .collect::>(); - let task_indices = self.tasks.iter().map(|task| &task.index_attr.meta.index); - let task_conditions = self.tasks.iter().map(|task| &task.condition_attr.meta.expr); - let task_weights = self.tasks.iter().map(|task| &task.weight_attr.meta.expr); - let task_iters = self.tasks.iter().map(|task| &task.list_attr.meta.expr); - - let task_fn_impls = self.tasks.iter().map(|task| { - let mut task_fn_impl = task.item.clone(); - task_fn_impl.attrs = vec![]; - task_fn_impl - }); - - let task_fn_names = self.tasks.iter().map(|task| &task.item.sig.ident); - let task_arg_names = self.tasks.iter().map(|task| &task.arg_names).collect::>(); - - let sp_std = quote!(#scrate::__private::sp_std); - let impl_generics = &self.item_impl.generics; - tokens.extend(quote! { - impl #impl_generics #enum_use - { - #(#task_fn_impls)* - } - - impl #impl_generics #scrate::traits::Task for #enum_use - { - type Enumeration = #sp_std::vec::IntoIter<#enum_use>; - - fn iter() -> Self::Enumeration { - let mut all_tasks = #sp_std::vec![]; - #(all_tasks - .extend(#task_iters.map(|(#(#task_arg_names),*)| #enum_ident::#task_fn_idents { #(#task_arg_names: #task_arg_names.clone()),* }) - .collect::<#sp_std::vec::Vec<_>>()); - )* - all_tasks.into_iter() - } - - fn task_index(&self) -> u32 { - match self.clone() { - #(#enum_ident::#task_fn_idents { .. } => #task_indices,)* - Task::__Ignore(_, _) => unreachable!(), - } - } - - fn is_valid(&self) -> bool { - match self.clone() { - #(#enum_ident::#task_fn_idents { #(#task_arg_names),* } => (#task_conditions)(#(#task_arg_names),* ),)* - Task::__Ignore(_, _) => unreachable!(), - } - } - - fn run(&self) -> Result<(), #scrate::pallet_prelude::DispatchError> { - match self.clone() { - #(#enum_ident::#task_fn_idents { #(#task_arg_names),* } => { - <#enum_use>::#task_fn_names(#( #task_arg_names, )* ) - },)* - Task::__Ignore(_, _) => unreachable!(), - } - } - - #[allow(unused_variables)] - fn weight(&self) -> #scrate::pallet_prelude::Weight { - match self.clone() { - #(#enum_ident::#task_fn_idents { #(#task_arg_names),* } => #task_weights,)* - Task::__Ignore(_, _) => unreachable!(), - } - } - } - }); - } -} - -/// Expands the [`TasksDef`] in the enclosing [`Def`], if present, and returns its tokens. -/// -/// This modifies the underlying [`Def`] in addition to returning any tokens that were added. -pub fn expand_tasks_impl(def: &mut Def) -> TokenStream2 { - let Some(tasks) = &mut def.tasks else { return quote!() }; - let ExpandedTasksDef { task_item_impl, task_trait_impl } = parse_quote!(#tasks); - quote! { - #task_item_impl - #task_trait_impl - } -} - -/// Represents a fully-expanded [`TaskEnumDef`]. -#[derive(Parse)] -pub struct ExpandedTaskEnum { - pub item_enum: ItemEnum, - pub debug_impl: ItemImpl, -} - -/// Modifies a [`Def`] to expand the underlying [`TaskEnumDef`] if present, and also returns -/// its tokens. A blank [`TokenStream2`] is returned if no [`TaskEnumDef`] has been generated -/// or defined. -pub fn expand_task_enum(def: &mut Def) -> TokenStream2 { - let Some(task_enum) = &mut def.task_enum else { return quote!() }; - let ExpandedTaskEnum { item_enum, debug_impl } = parse_quote!(#task_enum); - quote! { - #item_enum - #debug_impl - } -} - -/// Modifies a [`Def`] to expand the underlying [`TasksDef`] and also generate a -/// [`TaskEnumDef`] if applicable. The tokens for these items are returned if they are created. -pub fn expand_tasks(def: &mut Def) -> TokenStream2 { - if let Some(tasks_def) = &def.tasks { - if def.task_enum.is_none() { - def.task_enum = Some(TaskEnumDef::generate( - &tasks_def, - def.type_decl_bounded_generics(tasks_def.item_impl.span()), - def.type_use_generics(tasks_def.item_impl.span()), - )); - } - } - let tasks_extra_output = expand_tasks_impl(def); - let task_enum_extra_output = expand_task_enum(def); - quote! { - #tasks_extra_output - #task_enum_extra_output - } -} diff --git a/substrate/frame/support/procedural/src/pallet/expand/tt_default_parts.rs b/substrate/frame/support/procedural/src/pallet/expand/tt_default_parts.rs index 7cc1415dfdd..c9a776ee247 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/tt_default_parts.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/tt_default_parts.rs @@ -31,8 +31,6 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { let call_part = def.call.as_ref().map(|_| quote::quote!(Call,)); - let task_part = def.task_enum.as_ref().map(|_| quote::quote!(Task,)); - let storage_part = (!def.storages.is_empty()).then(|| quote::quote!(Storage,)); let event_part = def.event.as_ref().map(|event| { @@ -101,7 +99,7 @@ pub fn expand_tt_default_parts(def: &mut Def) -> proc_macro2::TokenStream { tokens = [{ expanded::{ Pallet, #call_part #storage_part #event_part #error_part #origin_part #config_part - #inherent_part #validate_unsigned_part #freeze_reason_part #task_part + #inherent_part #validate_unsigned_part #freeze_reason_part #hold_reason_part #lock_id_part #slash_reason_part } }] diff --git a/substrate/frame/support/procedural/src/pallet/parse/call.rs b/substrate/frame/support/procedural/src/pallet/parse/call.rs index 4e09b86fdde..519e1e61895 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/call.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/call.rs @@ -26,7 +26,6 @@ use syn::{spanned::Spanned, ExprClosure}; mod keyword { syn::custom_keyword!(Call); syn::custom_keyword!(OriginFor); - syn::custom_keyword!(RuntimeOrigin); syn::custom_keyword!(weight); syn::custom_keyword!(call_index); syn::custom_keyword!(compact); @@ -85,8 +84,6 @@ pub struct CallVariantDef { pub docs: Vec, /// Attributes annotated at the top of the dispatchable function. pub attrs: Vec, - /// The `cfg` attributes. - pub cfg_attrs: Vec, /// The optional `feeless_if` attribute on the `pallet::call`. pub feeless_check: Option, } @@ -161,10 +158,10 @@ impl syn::parse::Parse for ArgAttrIsCompact { } } -/// Check the syntax is `OriginFor`, `&OriginFor` or `T::RuntimeOrigin`. +/// Check the syntax is `OriginFor` or `&OriginFor`. pub fn check_dispatchable_first_arg_type(ty: &syn::Type, is_ref: bool) -> syn::Result<()> { - pub struct CheckOriginFor(bool); - impl syn::parse::Parse for CheckOriginFor { + pub struct CheckDispatchableFirstArg(bool); + impl syn::parse::Parse for CheckDispatchableFirstArg { fn parse(input: syn::parse::ParseStream) -> syn::Result { let is_ref = input.parse::().is_ok(); input.parse::()?; @@ -176,27 +173,14 @@ pub fn check_dispatchable_first_arg_type(ty: &syn::Type, is_ref: bool) -> syn::R } } - pub struct CheckRuntimeOrigin; - impl syn::parse::Parse for CheckRuntimeOrigin { - fn parse(input: syn::parse::ParseStream) -> syn::Result { - input.parse::()?; - input.parse::()?; - input.parse::()?; - - Ok(Self) - } - } - - let result_origin_for = syn::parse2::(ty.to_token_stream()); - let result_runtime_origin = syn::parse2::(ty.to_token_stream()); - return match (result_origin_for, result_runtime_origin) { - (Ok(CheckOriginFor(has_ref)), _) if is_ref == has_ref => Ok(()), - (_, Ok(_)) => Ok(()), - (_, _) => { + let result = syn::parse2::(ty.to_token_stream()); + return match result { + Ok(CheckDispatchableFirstArg(has_ref)) if is_ref == has_ref => Ok(()), + _ => { let msg = if is_ref { "Invalid type: expected `&OriginFor`" } else { - "Invalid type: expected `OriginFor` or `T::RuntimeOrigin`" + "Invalid type: expected `OriginFor`" }; return Err(syn::Error::new(ty.span(), msg)) }, @@ -268,7 +252,6 @@ impl CallDef { return Err(syn::Error::new(method.sig.span(), msg)) } - let cfg_attrs: Vec = helper::get_item_cfg_attrs(&method.attrs); let mut call_idx_attrs = vec![]; let mut weight_attrs = vec![]; let mut feeless_attrs = vec![]; @@ -289,7 +272,8 @@ impl CallDef { if weight_attrs.is_empty() && dev_mode { // inject a default O(1) weight when dev mode is enabled and no weight has // been specified on the call - let empty_weight: syn::Expr = syn::parse_quote!(0); + let empty_weight: syn::Expr = syn::parse(quote::quote!(0).into()) + .expect("we are parsing a quoted string; qed"); weight_attrs.push(FunctionAttr::Weight(empty_weight)); } @@ -298,8 +282,8 @@ impl CallDef { 0 if dev_mode => CallWeightDef::DevModeDefault, 0 => return Err(syn::Error::new( method.sig.span(), - "A pallet::call requires either a concrete `#[pallet::weight($expr)]` or an - inherited weight from the `#[pallet:call(weight($type))]` attribute, but + "A pallet::call requires either a concrete `#[pallet::weight($expr)]` or an + inherited weight from the `#[pallet:call(weight($type))]` attribute, but none were given.", )), 1 => match weight_attrs.pop().unwrap() { @@ -445,7 +429,6 @@ impl CallDef { args, docs, attrs: method.attrs.clone(), - cfg_attrs, feeless_check, }); } else { diff --git a/substrate/frame/support/procedural/src/pallet/parse/composite.rs b/substrate/frame/support/procedural/src/pallet/parse/composite.rs index fa5f47dfdfa..6e6ea6a795c 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/composite.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/composite.rs @@ -26,14 +26,11 @@ pub mod keyword { syn::custom_keyword!(HoldReason); syn::custom_keyword!(LockId); syn::custom_keyword!(SlashReason); - syn::custom_keyword!(Task); - pub enum CompositeKeyword { FreezeReason(FreezeReason), HoldReason(HoldReason), LockId(LockId), SlashReason(SlashReason), - Task(Task), } impl ToTokens for CompositeKeyword { @@ -44,7 +41,6 @@ pub mod keyword { HoldReason(inner) => inner.to_tokens(tokens), LockId(inner) => inner.to_tokens(tokens), SlashReason(inner) => inner.to_tokens(tokens), - Task(inner) => inner.to_tokens(tokens), } } } @@ -60,8 +56,6 @@ pub mod keyword { Ok(Self::LockId(input.parse()?)) } else if lookahead.peek(SlashReason) { Ok(Self::SlashReason(input.parse()?)) - } else if lookahead.peek(Task) { - Ok(Self::Task(input.parse()?)) } else { Err(lookahead.error()) } @@ -77,7 +71,6 @@ pub mod keyword { match self { FreezeReason(_) => "FreezeReason", HoldReason(_) => "HoldReason", - Task(_) => "Task", LockId(_) => "LockId", SlashReason(_) => "SlashReason", } @@ -87,7 +80,7 @@ pub mod keyword { } pub struct CompositeDef { - /// The index of the CompositeDef item in the pallet module. + /// The index of the HoldReason item in the pallet module. pub index: usize, /// The composite keyword used (contains span). pub composite_keyword: keyword::CompositeKeyword, diff --git a/substrate/frame/support/procedural/src/pallet/parse/error.rs b/substrate/frame/support/procedural/src/pallet/parse/error.rs index 362df8d7340..6f82ce61fc9 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/error.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/error.rs @@ -25,31 +25,19 @@ mod keyword { syn::custom_keyword!(Error); } -/// Records information about the error enum variant field. +/// Records information about the error enum variants. pub struct VariantField { /// Whether or not the field is named, i.e. whether it is a tuple variant or struct variant. pub is_named: bool, } -/// Records information about the error enum variants. -pub struct VariantDef { - /// The variant ident. - pub ident: syn::Ident, - /// The variant field, if any. - pub field: Option, - /// The variant doc literals. - pub docs: Vec, - /// The `cfg` attributes. - pub cfg_attrs: Vec, -} - /// This checks error declaration as a enum declaration with only variants without fields nor /// discriminant. pub struct ErrorDef { /// The index of error item in pallet module. pub index: usize, - /// Variant definitions. - pub variants: Vec, + /// Variants ident, optional field and doc literals (ordered as declaration order) + pub variants: Vec<(syn::Ident, Option, Vec)>, /// A set of usage of instance, must be check for consistency with trait. pub instances: Vec, /// The keyword error used (contains span). @@ -99,14 +87,8 @@ impl ErrorDef { let span = variant.discriminant.as_ref().unwrap().0.span(); return Err(syn::Error::new(span, msg)) } - let cfg_attrs: Vec = helper::get_item_cfg_attrs(&variant.attrs); - Ok(VariantDef { - ident: variant.ident.clone(), - field: field_ty, - docs: get_doc_literals(&variant.attrs), - cfg_attrs, - }) + Ok((variant.ident.clone(), field_ty, get_doc_literals(&variant.attrs))) }) .collect::>()?; diff --git a/substrate/frame/support/procedural/src/pallet/parse/mod.rs b/substrate/frame/support/procedural/src/pallet/parse/mod.rs index e1efdbcc202..83a881751ef 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/mod.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/mod.rs @@ -33,16 +33,11 @@ pub mod inherent; pub mod origin; pub mod pallet_struct; pub mod storage; -pub mod tasks; pub mod type_value; pub mod validate_unsigned; -#[cfg(test)] -pub mod tests; - use composite::{keyword::CompositeKeyword, CompositeDef}; use frame_support_procedural_tools::generate_access_from_frame_or_crate; -use quote::ToTokens; use syn::spanned::Spanned; /// Parsed definition of a pallet. @@ -54,8 +49,6 @@ pub struct Def { pub pallet_struct: pallet_struct::PalletStructDef, pub hooks: Option, pub call: Option, - pub tasks: Option, - pub task_enum: Option, pub storages: Vec, pub error: Option, pub event: Option, @@ -91,8 +84,6 @@ impl Def { let mut pallet_struct = None; let mut hooks = None; let mut call = None; - let mut tasks = None; - let mut task_enum = None; let mut error = None; let mut event = None; let mut origin = None; @@ -127,32 +118,6 @@ impl Def { }, Some(PalletAttr::RuntimeCall(cw, span)) if call.is_none() => call = Some(call::CallDef::try_from(span, index, item, dev_mode, cw)?), - Some(PalletAttr::Tasks(_)) if tasks.is_none() => { - let item_tokens = item.to_token_stream(); - // `TasksDef::parse` needs to know if attr was provided so we artificially - // re-insert it here - tasks = Some(syn::parse2::(quote::quote! { - #[pallet::tasks_experimental] - #item_tokens - })?); - - // replace item with a no-op because it will be handled by the expansion of tasks - *item = syn::Item::Verbatim(quote::quote!()); - } - Some(PalletAttr::TaskCondition(span)) => return Err(syn::Error::new( - span, - "`#[pallet::task_condition]` can only be used on items within an `impl` statement." - )), - Some(PalletAttr::TaskIndex(span)) => return Err(syn::Error::new( - span, - "`#[pallet::task_index]` can only be used on items within an `impl` statement." - )), - Some(PalletAttr::TaskList(span)) => return Err(syn::Error::new( - span, - "`#[pallet::task_list]` can only be used on items within an `impl` statement." - )), - Some(PalletAttr::RuntimeTask(_)) if task_enum.is_none() => - task_enum = Some(syn::parse2::(item.to_token_stream())?), Some(PalletAttr::Error(span)) if error.is_none() => error = Some(error::ErrorDef::try_from(span, index, item)?), Some(PalletAttr::RuntimeEvent(span)) if event.is_none() => @@ -225,8 +190,6 @@ impl Def { return Err(syn::Error::new(item_span, msg)) } - Self::resolve_tasks(&item_span, &mut tasks, &mut task_enum, items)?; - let def = Def { item, config: config @@ -235,8 +198,6 @@ impl Def { .ok_or_else(|| syn::Error::new(item_span, "Missing `#[pallet::pallet]`"))?, hooks, call, - tasks, - task_enum, extra_constants, genesis_config, genesis_build, @@ -259,99 +220,6 @@ impl Def { Ok(def) } - /// Performs extra logic checks necessary for the `#[pallet::tasks_experimental]` feature. - fn resolve_tasks( - item_span: &proc_macro2::Span, - tasks: &mut Option, - task_enum: &mut Option, - items: &mut Vec, - ) -> syn::Result<()> { - // fallback for manual (without macros) definition of tasks impl - Self::resolve_manual_tasks_impl(tasks, task_enum, items)?; - - // fallback for manual (without macros) definition of task enum - Self::resolve_manual_task_enum(tasks, task_enum, items)?; - - // ensure that if `task_enum` is specified, `tasks` is also specified - match (&task_enum, &tasks) { - (Some(_), None) => - return Err(syn::Error::new( - *item_span, - "Missing `#[pallet::tasks_experimental]` impl", - )), - (None, Some(tasks)) => - if tasks.tasks_attr.is_none() { - return Err(syn::Error::new( - tasks.item_impl.impl_token.span(), - "A `#[pallet::tasks_experimental]` attribute must be attached to your `Task` impl if the \ - task enum has been omitted", - )) - } else { - }, - _ => (), - } - - Ok(()) - } - - /// Tries to locate task enum based on the tasks impl target if attribute is not specified - /// but impl is present. If one is found, `task_enum` is set appropriately. - fn resolve_manual_task_enum( - tasks: &Option, - task_enum: &mut Option, - items: &mut Vec, - ) -> syn::Result<()> { - let (None, Some(tasks)) = (&task_enum, &tasks) else { return Ok(()) }; - let syn::Type::Path(type_path) = &*tasks.item_impl.self_ty else { return Ok(()) }; - let type_path = type_path.path.segments.iter().collect::>(); - let (Some(seg), None) = (type_path.get(0), type_path.get(1)) else { return Ok(()) }; - let mut result = None; - for item in items { - let syn::Item::Enum(item_enum) = item else { continue }; - if item_enum.ident == seg.ident { - result = Some(syn::parse2::(item_enum.to_token_stream())?); - // replace item with a no-op because it will be handled by the expansion of - // `task_enum`. We use a no-op instead of simply removing it from the vec - // so that any indices collected by `Def::try_from` remain accurate - *item = syn::Item::Verbatim(quote::quote!()); - break - } - } - *task_enum = result; - Ok(()) - } - - /// Tries to locate a manual tasks impl (an impl impling a trait whose last path segment is - /// `Task`) in the event that one has not been found already via the attribute macro - pub fn resolve_manual_tasks_impl( - tasks: &mut Option, - task_enum: &Option, - items: &Vec, - ) -> syn::Result<()> { - let None = tasks else { return Ok(()) }; - let mut result = None; - for item in items { - let syn::Item::Impl(item_impl) = item else { continue }; - let Some((_, path, _)) = &item_impl.trait_ else { continue }; - let Some(trait_last_seg) = path.segments.last() else { continue }; - let syn::Type::Path(target_path) = &*item_impl.self_ty else { continue }; - let target_path = target_path.path.segments.iter().collect::>(); - let (Some(target_ident), None) = (target_path.get(0), target_path.get(1)) else { - continue - }; - let matches_task_enum = match task_enum { - Some(task_enum) => task_enum.item_enum.ident == target_ident.ident, - None => true, - }; - if trait_last_seg.ident == "Task" && matches_task_enum { - result = Some(syn::parse2::(item_impl.to_token_stream())?); - break - } - } - *tasks = result; - Ok(()) - } - /// Check that usage of trait `Event` is consistent with the definition, i.e. it is declared /// and trait defines type RuntimeEvent, or not declared and no trait associated type. fn check_event_usage(&self) -> syn::Result<()> { @@ -540,11 +408,6 @@ impl GenericKind { mod keyword { syn::custom_keyword!(origin); syn::custom_keyword!(call); - syn::custom_keyword!(tasks_experimental); - syn::custom_keyword!(task_enum); - syn::custom_keyword!(task_list); - syn::custom_keyword!(task_condition); - syn::custom_keyword!(task_index); syn::custom_keyword!(weight); syn::custom_keyword!(event); syn::custom_keyword!(config); @@ -609,11 +472,6 @@ enum PalletAttr { /// instead of the zero weight. So to say: it works together with `dev_mode`. RuntimeCall(Option, proc_macro2::Span), Error(proc_macro2::Span), - Tasks(proc_macro2::Span), - TaskList(proc_macro2::Span), - TaskCondition(proc_macro2::Span), - TaskIndex(proc_macro2::Span), - RuntimeTask(proc_macro2::Span), RuntimeEvent(proc_macro2::Span), RuntimeOrigin(proc_macro2::Span), Inherent(proc_macro2::Span), @@ -632,13 +490,8 @@ impl PalletAttr { Self::Config(span, _) => *span, Self::Pallet(span) => *span, Self::Hooks(span) => *span, - Self::Tasks(span) => *span, - Self::TaskCondition(span) => *span, - Self::TaskIndex(span) => *span, - Self::TaskList(span) => *span, - Self::Error(span) => *span, - Self::RuntimeTask(span) => *span, Self::RuntimeCall(_, span) => *span, + Self::Error(span) => *span, Self::RuntimeEvent(span) => *span, Self::RuntimeOrigin(span) => *span, Self::Inherent(span) => *span, @@ -682,16 +535,6 @@ impl syn::parse::Parse for PalletAttr { false => Some(InheritedCallWeightAttr::parse(&content)?), }; Ok(PalletAttr::RuntimeCall(attr, span)) - } else if lookahead.peek(keyword::tasks_experimental) { - Ok(PalletAttr::Tasks(content.parse::()?.span())) - } else if lookahead.peek(keyword::task_enum) { - Ok(PalletAttr::RuntimeTask(content.parse::()?.span())) - } else if lookahead.peek(keyword::task_condition) { - Ok(PalletAttr::TaskCondition(content.parse::()?.span())) - } else if lookahead.peek(keyword::task_index) { - Ok(PalletAttr::TaskIndex(content.parse::()?.span())) - } else if lookahead.peek(keyword::task_list) { - Ok(PalletAttr::TaskList(content.parse::()?.span())) } else if lookahead.peek(keyword::error) { Ok(PalletAttr::Error(content.parse::()?.span())) } else if lookahead.peek(keyword::event) { diff --git a/substrate/frame/support/procedural/src/pallet/parse/tasks.rs b/substrate/frame/support/procedural/src/pallet/parse/tasks.rs deleted file mode 100644 index 6405bb415a6..00000000000 --- a/substrate/frame/support/procedural/src/pallet/parse/tasks.rs +++ /dev/null @@ -1,968 +0,0 @@ -// 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. - -//! Home of the parsing code for the Tasks API - -use std::collections::HashSet; - -#[cfg(test)] -use crate::assert_parse_error_matches; - -#[cfg(test)] -use crate::pallet::parse::tests::simulate_manifest_dir; - -use derive_syn_parse::Parse; -use frame_support_procedural_tools::generate_access_from_frame_or_crate; -use proc_macro2::TokenStream as TokenStream2; -use quote::{quote, ToTokens}; -use syn::{ - parse::ParseStream, - parse2, - spanned::Spanned, - token::{Bracket, Paren, PathSep, Pound}, - Attribute, Error, Expr, Ident, ImplItem, ImplItemFn, ItemEnum, ItemImpl, LitInt, Path, - PathArguments, Result, TypePath, -}; - -pub mod keywords { - use syn::custom_keyword; - - custom_keyword!(tasks_experimental); - custom_keyword!(task_enum); - custom_keyword!(task_list); - custom_keyword!(task_condition); - custom_keyword!(task_index); - custom_keyword!(task_weight); - custom_keyword!(pallet); -} - -/// Represents the `#[pallet::tasks_experimental]` attribute and its attached item. Also includes -/// metadata about the linked [`TaskEnumDef`] if applicable. -#[derive(Clone, Debug)] -pub struct TasksDef { - pub tasks_attr: Option, - pub tasks: Vec, - pub item_impl: ItemImpl, - /// Path to `frame_support` - pub scrate: Path, - pub enum_ident: Ident, - pub enum_arguments: PathArguments, -} - -impl syn::parse::Parse for TasksDef { - fn parse(input: ParseStream) -> Result { - let item_impl: ItemImpl = input.parse()?; - let (tasks_attrs, normal_attrs) = partition_tasks_attrs(&item_impl); - let tasks_attr = match tasks_attrs.first() { - Some(attr) => Some(parse2::(attr.to_token_stream())?), - None => None, - }; - if let Some(extra_tasks_attr) = tasks_attrs.get(1) { - return Err(Error::new( - extra_tasks_attr.span(), - "unexpected extra `#[pallet::tasks_experimental]` attribute", - )) - } - let tasks: Vec = if tasks_attr.is_some() { - item_impl - .items - .clone() - .into_iter() - .filter(|impl_item| matches!(impl_item, ImplItem::Fn(_))) - .map(|item| parse2::(item.to_token_stream())) - .collect::>()? - } else { - Vec::new() - }; - let mut task_indices = HashSet::::new(); - for task in tasks.iter() { - let task_index = &task.index_attr.meta.index; - if !task_indices.insert(task_index.clone()) { - return Err(Error::new( - task_index.span(), - format!("duplicate task index `{}`", task_index), - )) - } - } - let mut item_impl = item_impl; - item_impl.attrs = normal_attrs; - - // we require the path on the impl to be a TypePath - let enum_path = parse2::(item_impl.self_ty.to_token_stream())?; - let segments = enum_path.path.segments.iter().collect::>(); - let (Some(last_seg), None) = (segments.get(0), segments.get(1)) else { - return Err(Error::new( - enum_path.span(), - "if specified manually, the task enum must be defined locally in this \ - pallet and cannot be a re-export", - )) - }; - let enum_ident = last_seg.ident.clone(); - let enum_arguments = last_seg.arguments.clone(); - - // We do this here because it would be improper to do something fallible like this at - // the expansion phase. Fallible stuff should happen during parsing. - let scrate = generate_access_from_frame_or_crate("frame-support")?; - - Ok(TasksDef { tasks_attr, item_impl, tasks, scrate, enum_ident, enum_arguments }) - } -} - -/// Parsing for a `#[pallet::tasks_experimental]` attr. -pub type PalletTasksAttr = PalletTaskAttr; - -/// Parsing for any of the attributes that can be used within a `#[pallet::tasks_experimental]` -/// [`ItemImpl`]. -pub type TaskAttr = PalletTaskAttr; - -/// Parsing for a `#[pallet::task_index]` attr. -pub type TaskIndexAttr = PalletTaskAttr; - -/// Parsing for a `#[pallet::task_condition]` attr. -pub type TaskConditionAttr = PalletTaskAttr; - -/// Parsing for a `#[pallet::task_list]` attr. -pub type TaskListAttr = PalletTaskAttr; - -/// Parsing for a `#[pallet::task_weight]` attr. -pub type TaskWeightAttr = PalletTaskAttr; - -/// Parsing for a `#[pallet:task_enum]` attr. -pub type PalletTaskEnumAttr = PalletTaskAttr; - -/// Parsing for a manually-specified (or auto-generated) task enum, optionally including the -/// attached `#[pallet::task_enum]` attribute. -#[derive(Clone, Debug)] -pub struct TaskEnumDef { - pub attr: Option, - pub item_enum: ItemEnum, - pub scrate: Path, - pub type_use_generics: TokenStream2, -} - -impl syn::parse::Parse for TaskEnumDef { - fn parse(input: ParseStream) -> Result { - let mut item_enum = input.parse::()?; - let attr = extract_pallet_attr(&mut item_enum)?; - let attr = match attr { - Some(attr) => Some(parse2(attr)?), - None => None, - }; - - // We do this here because it would be improper to do something fallible like this at - // the expansion phase. Fallible stuff should happen during parsing. - let scrate = generate_access_from_frame_or_crate("frame-support")?; - - let type_use_generics = quote!(T); - - Ok(TaskEnumDef { attr, item_enum, scrate, type_use_generics }) - } -} - -/// Represents an individual tasks within a [`TasksDef`]. -#[derive(Debug, Clone)] -pub struct TaskDef { - pub index_attr: TaskIndexAttr, - pub condition_attr: TaskConditionAttr, - pub list_attr: TaskListAttr, - pub weight_attr: TaskWeightAttr, - pub normal_attrs: Vec, - pub item: ImplItemFn, - pub arg_names: Vec, -} - -impl syn::parse::Parse for TaskDef { - fn parse(input: ParseStream) -> Result { - let item = input.parse::()?; - // we only want to activate TaskAttrType parsing errors for tasks-related attributes, - // so we filter them here - let (task_attrs, normal_attrs) = partition_task_attrs(&item); - - let task_attrs: Vec = task_attrs - .into_iter() - .map(|attr| parse2(attr.to_token_stream())) - .collect::>()?; - - let Some(index_attr) = task_attrs - .iter() - .find(|attr| matches!(attr.meta, TaskAttrMeta::TaskIndex(_))) - .cloned() - else { - return Err(Error::new( - item.sig.ident.span(), - "missing `#[pallet::task_index(..)]` attribute", - )) - }; - - let Some(condition_attr) = task_attrs - .iter() - .find(|attr| matches!(attr.meta, TaskAttrMeta::TaskCondition(_))) - .cloned() - else { - return Err(Error::new( - item.sig.ident.span(), - "missing `#[pallet::task_condition(..)]` attribute", - )) - }; - - let Some(list_attr) = task_attrs - .iter() - .find(|attr| matches!(attr.meta, TaskAttrMeta::TaskList(_))) - .cloned() - else { - return Err(Error::new( - item.sig.ident.span(), - "missing `#[pallet::task_list(..)]` attribute", - )) - }; - - let Some(weight_attr) = task_attrs - .iter() - .find(|attr| matches!(attr.meta, TaskAttrMeta::TaskWeight(_))) - .cloned() - else { - return Err(Error::new( - item.sig.ident.span(), - "missing `#[pallet::task_weight(..)]` attribute", - )) - }; - - if let Some(duplicate) = task_attrs - .iter() - .filter(|attr| matches!(attr.meta, TaskAttrMeta::TaskCondition(_))) - .collect::>() - .get(1) - { - return Err(Error::new( - duplicate.span(), - "unexpected extra `#[pallet::task_condition(..)]` attribute", - )) - } - - if let Some(duplicate) = task_attrs - .iter() - .filter(|attr| matches!(attr.meta, TaskAttrMeta::TaskList(_))) - .collect::>() - .get(1) - { - return Err(Error::new( - duplicate.span(), - "unexpected extra `#[pallet::task_list(..)]` attribute", - )) - } - - if let Some(duplicate) = task_attrs - .iter() - .filter(|attr| matches!(attr.meta, TaskAttrMeta::TaskIndex(_))) - .collect::>() - .get(1) - { - return Err(Error::new( - duplicate.span(), - "unexpected extra `#[pallet::task_index(..)]` attribute", - )) - } - - let mut arg_names = vec![]; - for input in item.sig.inputs.iter() { - match input { - syn::FnArg::Typed(pat_type) => match &*pat_type.pat { - syn::Pat::Ident(ident) => arg_names.push(ident.ident.clone()), - _ => return Err(Error::new(input.span(), "unexpected pattern type")), - }, - _ => return Err(Error::new(input.span(), "unexpected function argument type")), - } - } - - let index_attr = index_attr.try_into().expect("we check the type above; QED"); - let condition_attr = condition_attr.try_into().expect("we check the type above; QED"); - let list_attr = list_attr.try_into().expect("we check the type above; QED"); - let weight_attr = weight_attr.try_into().expect("we check the type above; QED"); - - Ok(TaskDef { - index_attr, - condition_attr, - list_attr, - weight_attr, - normal_attrs, - item, - arg_names, - }) - } -} - -/// The contents of a [`TasksDef`]-related attribute. -#[derive(Parse, Debug, Clone)] -pub enum TaskAttrMeta { - #[peek(keywords::task_list, name = "#[pallet::task_list(..)]")] - TaskList(TaskListAttrMeta), - #[peek(keywords::task_index, name = "#[pallet::task_index(..)")] - TaskIndex(TaskIndexAttrMeta), - #[peek(keywords::task_condition, name = "#[pallet::task_condition(..)")] - TaskCondition(TaskConditionAttrMeta), - #[peek(keywords::task_weight, name = "#[pallet::task_weight(..)")] - TaskWeight(TaskWeightAttrMeta), -} - -/// The contents of a `#[pallet::task_list]` attribute. -#[derive(Parse, Debug, Clone)] -pub struct TaskListAttrMeta { - pub task_list: keywords::task_list, - #[paren] - _paren: Paren, - #[inside(_paren)] - pub expr: Expr, -} - -/// The contents of a `#[pallet::task_index]` attribute. -#[derive(Parse, Debug, Clone)] -pub struct TaskIndexAttrMeta { - pub task_index: keywords::task_index, - #[paren] - _paren: Paren, - #[inside(_paren)] - pub index: LitInt, -} - -/// The contents of a `#[pallet::task_condition]` attribute. -#[derive(Parse, Debug, Clone)] -pub struct TaskConditionAttrMeta { - pub task_condition: keywords::task_condition, - #[paren] - _paren: Paren, - #[inside(_paren)] - pub expr: Expr, -} - -/// The contents of a `#[pallet::task_weight]` attribute. -#[derive(Parse, Debug, Clone)] -pub struct TaskWeightAttrMeta { - pub task_weight: keywords::task_weight, - #[paren] - _paren: Paren, - #[inside(_paren)] - pub expr: Expr, -} - -/// The contents of a `#[pallet::task]` attribute. -#[derive(Parse, Debug, Clone)] -pub struct PalletTaskAttr { - pub pound: Pound, - #[bracket] - _bracket: Bracket, - #[inside(_bracket)] - pub pallet: keywords::pallet, - #[inside(_bracket)] - pub colons: PathSep, - #[inside(_bracket)] - pub meta: T, -} - -impl ToTokens for TaskListAttrMeta { - fn to_tokens(&self, tokens: &mut TokenStream2) { - let task_list = self.task_list; - let expr = &self.expr; - tokens.extend(quote!(#task_list(#expr))); - } -} - -impl ToTokens for TaskConditionAttrMeta { - fn to_tokens(&self, tokens: &mut TokenStream2) { - let task_condition = self.task_condition; - let expr = &self.expr; - tokens.extend(quote!(#task_condition(#expr))); - } -} - -impl ToTokens for TaskWeightAttrMeta { - fn to_tokens(&self, tokens: &mut TokenStream2) { - let task_weight = self.task_weight; - let expr = &self.expr; - tokens.extend(quote!(#task_weight(#expr))); - } -} - -impl ToTokens for TaskIndexAttrMeta { - fn to_tokens(&self, tokens: &mut TokenStream2) { - let task_index = self.task_index; - let index = &self.index; - tokens.extend(quote!(#task_index(#index))) - } -} - -impl ToTokens for TaskAttrMeta { - fn to_tokens(&self, tokens: &mut TokenStream2) { - match self { - TaskAttrMeta::TaskList(list) => tokens.extend(list.to_token_stream()), - TaskAttrMeta::TaskIndex(index) => tokens.extend(index.to_token_stream()), - TaskAttrMeta::TaskCondition(condition) => tokens.extend(condition.to_token_stream()), - TaskAttrMeta::TaskWeight(weight) => tokens.extend(weight.to_token_stream()), - } - } -} - -impl ToTokens for PalletTaskAttr { - fn to_tokens(&self, tokens: &mut TokenStream2) { - let pound = self.pound; - let pallet = self.pallet; - let colons = self.colons; - let meta = &self.meta; - tokens.extend(quote!(#pound[#pallet #colons #meta])); - } -} - -impl TryFrom> for TaskIndexAttr { - type Error = syn::Error; - - fn try_from(value: PalletTaskAttr) -> Result { - let pound = value.pound; - let pallet = value.pallet; - let colons = value.colons; - match value.meta { - TaskAttrMeta::TaskIndex(meta) => parse2(quote!(#pound[#pallet #colons #meta])), - _ => - return Err(Error::new( - value.span(), - format!("`{:?}` cannot be converted to a `TaskIndexAttr`", value.meta), - )), - } - } -} - -impl TryFrom> for TaskConditionAttr { - type Error = syn::Error; - - fn try_from(value: PalletTaskAttr) -> Result { - let pound = value.pound; - let pallet = value.pallet; - let colons = value.colons; - match value.meta { - TaskAttrMeta::TaskCondition(meta) => parse2(quote!(#pound[#pallet #colons #meta])), - _ => - return Err(Error::new( - value.span(), - format!("`{:?}` cannot be converted to a `TaskConditionAttr`", value.meta), - )), - } - } -} - -impl TryFrom> for TaskWeightAttr { - type Error = syn::Error; - - fn try_from(value: PalletTaskAttr) -> Result { - let pound = value.pound; - let pallet = value.pallet; - let colons = value.colons; - match value.meta { - TaskAttrMeta::TaskWeight(meta) => parse2(quote!(#pound[#pallet #colons #meta])), - _ => - return Err(Error::new( - value.span(), - format!("`{:?}` cannot be converted to a `TaskWeightAttr`", value.meta), - )), - } - } -} - -impl TryFrom> for TaskListAttr { - type Error = syn::Error; - - fn try_from(value: PalletTaskAttr) -> Result { - let pound = value.pound; - let pallet = value.pallet; - let colons = value.colons; - match value.meta { - TaskAttrMeta::TaskList(meta) => parse2(quote!(#pound[#pallet #colons #meta])), - _ => - return Err(Error::new( - value.span(), - format!("`{:?}` cannot be converted to a `TaskListAttr`", value.meta), - )), - } - } -} - -fn extract_pallet_attr(item_enum: &mut ItemEnum) -> Result> { - let mut duplicate = None; - let mut attr = None; - item_enum.attrs = item_enum - .attrs - .iter() - .filter(|found_attr| { - let segs = found_attr - .path() - .segments - .iter() - .map(|seg| seg.ident.clone()) - .collect::>(); - let (Some(seg1), Some(_), None) = (segs.get(0), segs.get(1), segs.get(2)) else { - return true - }; - if seg1 != "pallet" { - return true - } - if attr.is_some() { - duplicate = Some(found_attr.span()); - } - attr = Some(found_attr.to_token_stream()); - false - }) - .cloned() - .collect(); - if let Some(span) = duplicate { - return Err(Error::new(span, "only one `#[pallet::_]` attribute is supported on this item")) - } - Ok(attr) -} - -fn partition_tasks_attrs(item_impl: &ItemImpl) -> (Vec, Vec) { - item_impl.attrs.clone().into_iter().partition(|attr| { - let mut path_segs = attr.path().segments.iter(); - let (Some(prefix), Some(suffix), None) = - (path_segs.next(), path_segs.next(), path_segs.next()) - else { - return false - }; - prefix.ident == "pallet" && suffix.ident == "tasks_experimental" - }) -} - -fn partition_task_attrs(item: &ImplItemFn) -> (Vec, Vec) { - item.attrs.clone().into_iter().partition(|attr| { - let mut path_segs = attr.path().segments.iter(); - let (Some(prefix), Some(suffix)) = (path_segs.next(), path_segs.next()) else { - return false - }; - // N.B: the `PartialEq` impl between `Ident` and `&str` is more efficient than - // parsing and makes no stack or heap allocations - prefix.ident == "pallet" && - (suffix.ident == "tasks_experimental" || - suffix.ident == "task_list" || - suffix.ident == "task_condition" || - suffix.ident == "task_weight" || - suffix.ident == "task_index") - }) -} - -#[test] -fn test_parse_task_list_() { - parse2::(quote!(#[pallet::task_list(Something::iter())])).unwrap(); - parse2::(quote!(#[pallet::task_list(Numbers::::iter_keys())])).unwrap(); - parse2::(quote!(#[pallet::task_list(iter())])).unwrap(); - assert_parse_error_matches!( - parse2::(quote!(#[pallet::task_list()])), - "expected an expression" - ); - assert_parse_error_matches!( - parse2::(quote!(#[pallet::task_list])), - "expected parentheses" - ); -} - -#[test] -fn test_parse_task_index() { - parse2::(quote!(#[pallet::task_index(3)])).unwrap(); - parse2::(quote!(#[pallet::task_index(0)])).unwrap(); - parse2::(quote!(#[pallet::task_index(17)])).unwrap(); - assert_parse_error_matches!( - parse2::(quote!(#[pallet::task_index])), - "expected parentheses" - ); - assert_parse_error_matches!( - parse2::(quote!(#[pallet::task_index("hey")])), - "expected integer literal" - ); - assert_parse_error_matches!( - parse2::(quote!(#[pallet::task_index(0.3)])), - "expected integer literal" - ); -} - -#[test] -fn test_parse_task_condition() { - parse2::(quote!(#[pallet::task_condition(|x| x.is_some())])).unwrap(); - parse2::(quote!(#[pallet::task_condition(|_x| some_expr())])).unwrap(); - parse2::(quote!(#[pallet::task_condition(|| some_expr())])).unwrap(); - parse2::(quote!(#[pallet::task_condition(some_expr())])).unwrap(); -} - -#[test] -fn test_parse_tasks_attr() { - parse2::(quote!(#[pallet::tasks_experimental])).unwrap(); - assert_parse_error_matches!( - parse2::(quote!(#[pallet::taskss])), - "expected `tasks_experimental`" - ); - assert_parse_error_matches!( - parse2::(quote!(#[pallet::tasks_])), - "expected `tasks_experimental`" - ); - assert_parse_error_matches!( - parse2::(quote!(#[pal::tasks])), - "expected `pallet`" - ); - assert_parse_error_matches!( - parse2::(quote!(#[pallet::tasks_experimental()])), - "unexpected token" - ); -} - -#[test] -fn test_parse_tasks_def_basic() { - simulate_manifest_dir("../../examples/basic", || { - let parsed = parse2::(quote! { - #[pallet::tasks_experimental] - impl, I: 'static> Pallet { - /// Add a pair of numbers into the totals and remove them. - #[pallet::task_list(Numbers::::iter_keys())] - #[pallet::task_condition(|i| Numbers::::contains_key(i))] - #[pallet::task_index(0)] - #[pallet::task_weight(0)] - pub fn add_number_into_total(i: u32) -> DispatchResult { - let v = Numbers::::take(i).ok_or(Error::::NotFound)?; - Total::::mutate(|(total_keys, total_values)| { - *total_keys += i; - *total_values += v; - }); - Ok(()) - } - } - }) - .unwrap(); - assert_eq!(parsed.tasks.len(), 1); - }); -} - -#[test] -fn test_parse_tasks_def_basic_increment_decrement() { - simulate_manifest_dir("../../examples/basic", || { - let parsed = parse2::(quote! { - #[pallet::tasks_experimental] - impl, I: 'static> Pallet { - /// Get the value and check if it can be incremented - #[pallet::task_index(0)] - #[pallet::task_condition(|| { - let value = Value::::get().unwrap(); - value < 255 - })] - #[pallet::task_list(Vec::>::new())] - #[pallet::task_weight(0)] - fn increment() -> DispatchResult { - let value = Value::::get().unwrap_or_default(); - if value >= 255 { - Err(Error::::ValueOverflow.into()) - } else { - let new_val = value.checked_add(1).ok_or(Error::::ValueOverflow)?; - Value::::put(new_val); - Pallet::::deposit_event(Event::Incremented { new_val }); - Ok(()) - } - } - - // Get the value and check if it can be decremented - #[pallet::task_index(1)] - #[pallet::task_condition(|| { - let value = Value::::get().unwrap(); - value > 0 - })] - #[pallet::task_list(Vec::>::new())] - #[pallet::task_weight(0)] - fn decrement() -> DispatchResult { - let value = Value::::get().unwrap_or_default(); - if value == 0 { - Err(Error::::ValueUnderflow.into()) - } else { - let new_val = value.checked_sub(1).ok_or(Error::::ValueUnderflow)?; - Value::::put(new_val); - Pallet::::deposit_event(Event::Decremented { new_val }); - Ok(()) - } - } - } - }) - .unwrap(); - assert_eq!(parsed.tasks.len(), 2); - }); -} - -#[test] -fn test_parse_tasks_def_duplicate_index() { - simulate_manifest_dir("../../examples/basic", || { - assert_parse_error_matches!( - parse2::(quote! { - #[pallet::tasks_experimental] - impl, I: 'static> Pallet { - #[pallet::task_list(Something::iter())] - #[pallet::task_condition(|i| i % 2 == 0)] - #[pallet::task_index(0)] - #[pallet::task_weight(0)] - pub fn foo(i: u32) -> DispatchResult { - Ok(()) - } - - #[pallet::task_list(Numbers::::iter_keys())] - #[pallet::task_condition(|i| Numbers::::contains_key(i))] - #[pallet::task_index(0)] - #[pallet::task_weight(0)] - pub fn bar(i: u32) -> DispatchResult { - Ok(()) - } - } - }), - "duplicate task index `0`" - ); - }); -} - -#[test] -fn test_parse_tasks_def_missing_task_list() { - simulate_manifest_dir("../../examples/basic", || { - assert_parse_error_matches!( - parse2::(quote! { - #[pallet::tasks_experimental] - impl, I: 'static> Pallet { - #[pallet::task_condition(|i| i % 2 == 0)] - #[pallet::task_index(0)] - pub fn foo(i: u32) -> DispatchResult { - Ok(()) - } - } - }), - r"missing `#\[pallet::task_list\(\.\.\)\]`" - ); - }); -} - -#[test] -fn test_parse_tasks_def_missing_task_condition() { - simulate_manifest_dir("../../examples/basic", || { - assert_parse_error_matches!( - parse2::(quote! { - #[pallet::tasks_experimental] - impl, I: 'static> Pallet { - #[pallet::task_list(Something::iter())] - #[pallet::task_index(0)] - pub fn foo(i: u32) -> DispatchResult { - Ok(()) - } - } - }), - r"missing `#\[pallet::task_condition\(\.\.\)\]`" - ); - }); -} - -#[test] -fn test_parse_tasks_def_missing_task_index() { - simulate_manifest_dir("../../examples/basic", || { - assert_parse_error_matches!( - parse2::(quote! { - #[pallet::tasks_experimental] - impl, I: 'static> Pallet { - #[pallet::task_condition(|i| i % 2 == 0)] - #[pallet::task_list(Something::iter())] - pub fn foo(i: u32) -> DispatchResult { - Ok(()) - } - } - }), - r"missing `#\[pallet::task_index\(\.\.\)\]`" - ); - }); -} - -#[test] -fn test_parse_tasks_def_missing_task_weight() { - simulate_manifest_dir("../../examples/basic", || { - assert_parse_error_matches!( - parse2::(quote! { - #[pallet::tasks_experimental] - impl, I: 'static> Pallet { - #[pallet::task_condition(|i| i % 2 == 0)] - #[pallet::task_list(Something::iter())] - #[pallet::task_index(0)] - pub fn foo(i: u32) -> DispatchResult { - Ok(()) - } - } - }), - r"missing `#\[pallet::task_weight\(\.\.\)\]`" - ); - }); -} - -#[test] -fn test_parse_tasks_def_unexpected_extra_task_list_attr() { - simulate_manifest_dir("../../examples/basic", || { - assert_parse_error_matches!( - parse2::(quote! { - #[pallet::tasks_experimental] - impl, I: 'static> Pallet { - #[pallet::task_condition(|i| i % 2 == 0)] - #[pallet::task_index(0)] - #[pallet::task_weight(0)] - #[pallet::task_list(Something::iter())] - #[pallet::task_list(SomethingElse::iter())] - pub fn foo(i: u32) -> DispatchResult { - Ok(()) - } - } - }), - r"unexpected extra `#\[pallet::task_list\(\.\.\)\]`" - ); - }); -} - -#[test] -fn test_parse_tasks_def_unexpected_extra_task_condition_attr() { - simulate_manifest_dir("../../examples/basic", || { - assert_parse_error_matches!( - parse2::(quote! { - #[pallet::tasks_experimental] - impl, I: 'static> Pallet { - #[pallet::task_condition(|i| i % 2 == 0)] - #[pallet::task_condition(|i| i % 4 == 0)] - #[pallet::task_index(0)] - #[pallet::task_list(Something::iter())] - #[pallet::task_weight(0)] - pub fn foo(i: u32) -> DispatchResult { - Ok(()) - } - } - }), - r"unexpected extra `#\[pallet::task_condition\(\.\.\)\]`" - ); - }); -} - -#[test] -fn test_parse_tasks_def_unexpected_extra_task_index_attr() { - simulate_manifest_dir("../../examples/basic", || { - assert_parse_error_matches!( - parse2::(quote! { - #[pallet::tasks_experimental] - impl, I: 'static> Pallet { - #[pallet::task_condition(|i| i % 2 == 0)] - #[pallet::task_index(0)] - #[pallet::task_index(0)] - #[pallet::task_list(Something::iter())] - #[pallet::task_weight(0)] - pub fn foo(i: u32) -> DispatchResult { - Ok(()) - } - } - }), - r"unexpected extra `#\[pallet::task_index\(\.\.\)\]`" - ); - }); -} - -#[test] -fn test_parse_tasks_def_extra_tasks_attribute() { - simulate_manifest_dir("../../examples/basic", || { - assert_parse_error_matches!( - parse2::(quote! { - #[pallet::tasks_experimental] - #[pallet::tasks_experimental] - impl, I: 'static> Pallet {} - }), - r"unexpected extra `#\[pallet::tasks_experimental\]` attribute" - ); - }); -} - -#[test] -fn test_parse_task_enum_def_basic() { - simulate_manifest_dir("../../examples/basic", || { - parse2::(quote! { - #[pallet::task_enum] - pub enum Task { - Increment, - Decrement, - } - }) - .unwrap(); - }); -} - -#[test] -fn test_parse_task_enum_def_non_task_name() { - simulate_manifest_dir("../../examples/basic", || { - parse2::(quote! { - #[pallet::task_enum] - pub enum Something { - Foo - } - }) - .unwrap(); - }); -} - -#[test] -fn test_parse_task_enum_def_missing_attr_allowed() { - simulate_manifest_dir("../../examples/basic", || { - parse2::(quote! { - pub enum Task { - Increment, - Decrement, - } - }) - .unwrap(); - }); -} - -#[test] -fn test_parse_task_enum_def_missing_attr_alternate_name_allowed() { - simulate_manifest_dir("../../examples/basic", || { - parse2::(quote! { - pub enum Foo { - Red, - } - }) - .unwrap(); - }); -} - -#[test] -fn test_parse_task_enum_def_wrong_attr() { - simulate_manifest_dir("../../examples/basic", || { - assert_parse_error_matches!( - parse2::(quote! { - #[pallet::something] - pub enum Task { - Increment, - Decrement, - } - }), - "expected `task_enum`" - ); - }); -} - -#[test] -fn test_parse_task_enum_def_wrong_item() { - simulate_manifest_dir("../../examples/basic", || { - assert_parse_error_matches!( - parse2::(quote! { - #[pallet::task_enum] - pub struct Something; - }), - "expected `enum`" - ); - }); -} diff --git a/substrate/frame/support/procedural/src/pallet/parse/tests/mod.rs b/substrate/frame/support/procedural/src/pallet/parse/tests/mod.rs deleted file mode 100644 index a3661f3076d..00000000000 --- a/substrate/frame/support/procedural/src/pallet/parse/tests/mod.rs +++ /dev/null @@ -1,264 +0,0 @@ -// 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 std::{panic, sync::Mutex}; -use syn::parse_quote; - -#[doc(hidden)] -pub mod __private { - pub use regex; -} - -/// Allows you to assert that the input expression resolves to an error whose string -/// representation matches the specified regex literal. -/// -/// ## Example: -/// -/// ``` -/// use super::tasks::*; -/// -/// assert_parse_error_matches!( -/// parse2::(quote! { -/// #[pallet::task_enum] -/// pub struct Something; -/// }), -/// "expected `enum`" -/// ); -/// ``` -/// -/// More complex regular expressions are also possible (anything that could pass as a regex for -/// use with the [`regex`] crate.): -/// -/// ```ignore -/// assert_parse_error_matches!( -/// parse2::(quote! { -/// #[pallet::tasks_experimental] -/// impl, I: 'static> Pallet { -/// #[pallet::task_condition(|i| i % 2 == 0)] -/// #[pallet::task_index(0)] -/// pub fn foo(i: u32) -> DispatchResult { -/// Ok(()) -/// } -/// } -/// }), -/// r"missing `#\[pallet::task_list\(\.\.\)\]`" -/// ); -/// ``` -/// -/// Although this is primarily intended to be used with parsing errors, this macro is general -/// enough that it will work with any error with a reasonable [`core::fmt::Display`] impl. -#[macro_export] -macro_rules! assert_parse_error_matches { - ($expr:expr, $reg:literal) => { - match $expr { - Ok(_) => panic!("Expected an `Error(..)`, but got Ok(..)"), - Err(e) => { - let error_message = e.to_string(); - let re = $crate::pallet::parse::tests::__private::regex::Regex::new($reg) - .expect("Invalid regex pattern"); - assert!( - re.is_match(&error_message), - "Error message \"{}\" does not match the pattern \"{}\"", - error_message, - $reg - ); - }, - } - }; -} - -/// Allows you to assert that an entire pallet parses successfully. A custom syntax is used for -/// specifying arguments so please pay attention to the docs below. -/// -/// The general syntax is: -/// -/// ```ignore -/// assert_pallet_parses! { -/// #[manifest_dir("../../examples/basic")] -/// #[frame_support::pallet] -/// pub mod pallet { -/// #[pallet::config] -/// pub trait Config: frame_system::Config {} -/// -/// #[pallet::pallet] -/// pub struct Pallet(_); -/// } -/// }; -/// ``` -/// -/// The `#[manifest_dir(..)]` attribute _must_ be specified as the _first_ attribute on the -/// pallet module, and should reference the relative (to your current directory) path of a -/// directory containing containing the `Cargo.toml` of a valid pallet. Typically you will only -/// ever need to use the `examples/basic` pallet, but sometimes it might be advantageous to -/// specify a different one that has additional dependencies. -/// -/// The reason this must be specified is that our underlying parsing of pallets depends on -/// reaching out into the file system to look for particular `Cargo.toml` dependencies via the -/// [`generate_access_from_frame_or_crate`] method, so to simulate this properly in a proc -/// macro crate, we need to temporarily convince this function that we are running from the -/// directory of a valid pallet. -#[macro_export] -macro_rules! assert_pallet_parses { - ( - #[manifest_dir($manifest_dir:literal)] - $($tokens:tt)* - ) => { - { - let mut pallet: Option<$crate::pallet::parse::Def> = None; - $crate::pallet::parse::tests::simulate_manifest_dir($manifest_dir, core::panic::AssertUnwindSafe(|| { - pallet = Some($crate::pallet::parse::Def::try_from(syn::parse_quote! { - $($tokens)* - }, false).unwrap()); - })); - pallet.unwrap() - } - } -} - -/// Similar to [`assert_pallet_parses`], except this instead expects the pallet not to parse, -/// and allows you to specify a regex matching the expected parse error. -/// -/// This is identical syntactically to [`assert_pallet_parses`] in every way except there is a -/// second attribute that must be specified immediately after `#[manifest_dir(..)]` which is -/// `#[error_regex(..)]` which should contain a string/regex literal designed to match what you -/// consider to be the correct parsing error we should see when we try to parse this particular -/// pallet. -/// -/// ## Example: -/// -/// ``` -/// assert_pallet_parse_error! { -/// #[manifest_dir("../../examples/basic")] -/// #[error_regex("Missing `\\#\\[pallet::pallet\\]`")] -/// #[frame_support::pallet] -/// pub mod pallet { -/// #[pallet::config] -/// pub trait Config: frame_system::Config {} -/// } -/// } -/// ``` -#[macro_export] -macro_rules! assert_pallet_parse_error { - ( - #[manifest_dir($manifest_dir:literal)] - #[error_regex($reg:literal)] - $($tokens:tt)* - ) => { - $crate::pallet::parse::tests::simulate_manifest_dir($manifest_dir, || { - $crate::assert_parse_error_matches!( - $crate::pallet::parse::Def::try_from( - parse_quote! { - $($tokens)* - }, - false - ), - $reg - ); - }); - } -} - -/// Safely runs the specified `closure` while simulating an alternative `CARGO_MANIFEST_DIR`, -/// restoring `CARGO_MANIFEST_DIR` to its original value upon completion regardless of whether -/// the closure panics. -/// -/// This is useful in tests of `Def::try_from` and other pallet-related methods that internally -/// make use of [`generate_access_from_frame_or_crate`], which is sensitive to entries in the -/// "current" `Cargo.toml` files. -/// -/// This function uses a [`Mutex`] to avoid a race condition created when multiple tests try to -/// modify and then restore the `CARGO_MANIFEST_DIR` ENV var in an overlapping way. -pub fn simulate_manifest_dir, F: FnOnce() + std::panic::UnwindSafe>( - path: P, - closure: F, -) { - use std::{env::*, path::*}; - - /// Ensures that only one thread can modify/restore the `CARGO_MANIFEST_DIR` ENV var at a time, - /// avoiding a race condition because `cargo test` runs tests in parallel. - /// - /// Although this forces all tests that use [`simulate_manifest_dir`] to run sequentially with - /// respect to each other, this is still several orders of magnitude faster than using UI - /// tests, even if they are run in parallel. - static MANIFEST_DIR_LOCK: Mutex<()> = Mutex::new(()); - - // avoid race condition when swapping out `CARGO_MANIFEST_DIR` - let guard = MANIFEST_DIR_LOCK.lock().unwrap(); - - // obtain the current/original `CARGO_MANIFEST_DIR` - let orig = PathBuf::from( - var("CARGO_MANIFEST_DIR").expect("failed to read ENV var `CARGO_MANIFEST_DIR`"), - ); - - // set `CARGO_MANIFEST_DIR` to the provided path, relative to current working dir - set_var("CARGO_MANIFEST_DIR", orig.join(path.as_ref())); - - // safely run closure catching any panics - let result = panic::catch_unwind(closure); - - // restore original `CARGO_MANIFEST_DIR` before unwinding - set_var("CARGO_MANIFEST_DIR", &orig); - - // unlock the mutex so we don't poison it if there is a panic - drop(guard); - - // unwind any panics originally encountered when running closure - result.unwrap(); -} - -mod tasks; - -#[test] -fn test_parse_minimal_pallet() { - assert_pallet_parses! { - #[manifest_dir("../../examples/basic")] - #[frame_support::pallet] - pub mod pallet { - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); - } - }; -} - -#[test] -fn test_parse_pallet_missing_pallet() { - assert_pallet_parse_error! { - #[manifest_dir("../../examples/basic")] - #[error_regex("Missing `\\#\\[pallet::pallet\\]`")] - #[frame_support::pallet] - pub mod pallet { - #[pallet::config] - pub trait Config: frame_system::Config {} - } - } -} - -#[test] -fn test_parse_pallet_missing_config() { - assert_pallet_parse_error! { - #[manifest_dir("../../examples/basic")] - #[error_regex("Missing `\\#\\[pallet::config\\]`")] - #[frame_support::pallet] - pub mod pallet { - #[pallet::pallet] - pub struct Pallet(_); - } - } -} diff --git a/substrate/frame/support/procedural/src/pallet/parse/tests/tasks.rs b/substrate/frame/support/procedural/src/pallet/parse/tests/tasks.rs deleted file mode 100644 index 9f143628404..00000000000 --- a/substrate/frame/support/procedural/src/pallet/parse/tests/tasks.rs +++ /dev/null @@ -1,240 +0,0 @@ -// 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 syn::parse_quote; - -#[test] -fn test_parse_pallet_with_task_enum_missing_impl() { - assert_pallet_parse_error! { - #[manifest_dir("../../examples/basic")] - #[error_regex("Missing `\\#\\[pallet::tasks_experimental\\]` impl")] - #[frame_support::pallet] - pub mod pallet { - #[pallet::task_enum] - pub enum Task { - Something, - } - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); - } - } -} - -#[test] -fn test_parse_pallet_with_task_enum_wrong_attribute() { - assert_pallet_parse_error! { - #[manifest_dir("../../examples/basic")] - #[error_regex("expected one of")] - #[frame_support::pallet] - pub mod pallet { - #[pallet::wrong_attribute] - pub enum Task { - Something, - } - - #[pallet::task_list] - impl frame_support::traits::Task for Task - where - T: TypeInfo, - {} - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); - } - } -} - -#[test] -fn test_parse_pallet_missing_task_enum() { - assert_pallet_parses! { - #[manifest_dir("../../examples/basic")] - #[frame_support::pallet] - pub mod pallet { - #[pallet::tasks_experimental] - #[cfg(test)] // aha, this means it's being eaten - impl frame_support::traits::Task for Task - where - T: TypeInfo, - {} - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); - } - }; -} - -#[test] -fn test_parse_pallet_task_list_in_wrong_place() { - assert_pallet_parse_error! { - #[manifest_dir("../../examples/basic")] - #[error_regex("can only be used on items within an `impl` statement.")] - #[frame_support::pallet] - pub mod pallet { - pub enum MyCustomTaskEnum { - Something, - } - - #[pallet::task_list] - pub fn something() { - println!("hey"); - } - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); - } - } -} - -#[test] -fn test_parse_pallet_manual_tasks_impl_without_manual_tasks_enum() { - assert_pallet_parse_error! { - #[manifest_dir("../../examples/basic")] - #[error_regex(".*attribute must be attached to your.*")] - #[frame_support::pallet] - pub mod pallet { - - impl frame_support::traits::Task for Task - where - T: TypeInfo, - { - type Enumeration = sp_std::vec::IntoIter>; - - fn iter() -> Self::Enumeration { - sp_std::vec![Task::increment, Task::decrement].into_iter() - } - } - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); - } - } -} - -#[test] -fn test_parse_pallet_manual_task_enum_non_manual_impl() { - assert_pallet_parses! { - #[manifest_dir("../../examples/basic")] - #[frame_support::pallet] - pub mod pallet { - pub enum MyCustomTaskEnum { - Something, - } - - #[pallet::tasks_experimental] - impl frame_support::traits::Task for MyCustomTaskEnum - where - T: TypeInfo, - {} - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); - } - }; -} - -#[test] -fn test_parse_pallet_non_manual_task_enum_manual_impl() { - assert_pallet_parses! { - #[manifest_dir("../../examples/basic")] - #[frame_support::pallet] - pub mod pallet { - #[pallet::task_enum] - pub enum MyCustomTaskEnum { - Something, - } - - impl frame_support::traits::Task for MyCustomTaskEnum - where - T: TypeInfo, - {} - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); - } - }; -} - -#[test] -fn test_parse_pallet_manual_task_enum_manual_impl() { - assert_pallet_parses! { - #[manifest_dir("../../examples/basic")] - #[frame_support::pallet] - pub mod pallet { - pub enum MyCustomTaskEnum { - Something, - } - - impl frame_support::traits::Task for MyCustomTaskEnum - where - T: TypeInfo, - {} - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); - } - }; -} - -#[test] -fn test_parse_pallet_manual_task_enum_mismatch_ident() { - assert_pallet_parses! { - #[manifest_dir("../../examples/basic")] - #[frame_support::pallet] - pub mod pallet { - pub enum WrongIdent { - Something, - } - - #[pallet::tasks_experimental] - impl frame_support::traits::Task for MyCustomTaskEnum - where - T: TypeInfo, - {} - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(_); - } - }; -} diff --git a/substrate/frame/support/procedural/tools/Cargo.toml b/substrate/frame/support/procedural/tools/Cargo.toml index 5fffe3eeced..fd42e18180d 100644 --- a/substrate/frame/support/procedural/tools/Cargo.toml +++ b/substrate/frame/support/procedural/tools/Cargo.toml @@ -8,15 +8,12 @@ homepage = "https://substrate.io" repository.workspace = true description = "Proc macro helpers for procedural macros" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -proc-macro-crate = "2.0.1" +proc-macro-crate = "1.1.3" proc-macro2 = "1.0.56" quote = "1.0.28" -syn = { version = "2.0.40", features = ["extra-traits", "full", "visit"] } +syn = { version = "2.0.38", features = ["full", "visit", "extra-traits"] } frame-support-procedural-tools-derive = { path = "derive" } diff --git a/substrate/frame/support/procedural/tools/derive/Cargo.toml b/substrate/frame/support/procedural/tools/derive/Cargo.toml index 9b6122b26fd..06f8e0f3d53 100644 --- a/substrate/frame/support/procedural/tools/derive/Cargo.toml +++ b/substrate/frame/support/procedural/tools/derive/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "Use to derive parsing for parsing struct." -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,4 +17,4 @@ proc-macro = true [dependencies] proc-macro2 = "1.0.56" quote = { version = "1.0.28", features = ["proc-macro"] } -syn = { version = "2.0.40", features = ["extra-traits", "full", "parsing", "proc-macro"] } +syn = { version = "2.0.38", features = ["proc-macro", "full", "extra-traits", "parsing"] } diff --git a/substrate/frame/support/src/dispatch.rs b/substrate/frame/support/src/dispatch.rs index e0cd58884d9..4cbeb6fc0f5 100644 --- a/substrate/frame/support/src/dispatch.rs +++ b/substrate/frame/support/src/dispatch.rs @@ -36,8 +36,7 @@ use sp_weights::Weight; /// returned from a dispatch. pub type DispatchResultWithPostInfo = sp_runtime::DispatchResultWithInfo; -#[docify::export] -/// Un-augmented version of `DispatchResultWithPostInfo` that can be returned from +/// Unaugmented version of `DispatchResultWithPostInfo` that can be returned from /// dispatchable functions and is automatically converted to the augmented type. Should be /// used whenever the `PostDispatchInfo` does not need to be overwritten. As this should /// be the common case it is the implicit return type when none is specified. @@ -695,7 +694,6 @@ mod weight_tests { type BaseCallFilter: crate::traits::Contains; type RuntimeOrigin; type RuntimeCall; - type RuntimeTask; type PalletInfo: crate::traits::PalletInfo; type DbWeight: Get; } @@ -792,7 +790,6 @@ mod weight_tests { type BaseCallFilter = crate::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type RuntimeTask = RuntimeTask; type DbWeight = DbWeight; type PalletInfo = PalletInfo; } diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index a33eef9ba54..acc7344f334 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -47,8 +47,6 @@ pub mod __private { pub use sp_core::{OpaqueMetadata, Void}; pub use sp_core_hashing_proc_macro; pub use sp_inherents; - #[cfg(feature = "std")] - pub use sp_io::TestExternalities; pub use sp_io::{self, hashing, storage::root as storage_root}; pub use sp_metadata_ir as metadata_ir; #[cfg(feature = "std")] @@ -851,7 +849,7 @@ pub mod pallet_prelude { }, traits::{ BuildGenesisConfig, ConstU32, EnsureOrigin, Get, GetDefault, GetStorageVersion, Hooks, - IsType, PalletInfoAccess, StorageInfoTrait, StorageVersion, Task, TypedGet, + IsType, PalletInfoAccess, StorageInfoTrait, StorageVersion, TypedGet, }, Blake2_128, Blake2_128Concat, Blake2_256, CloneNoBound, DebugNoBound, EqNoBound, Identity, PartialEqNoBound, RuntimeDebugNoBound, Twox128, Twox256, Twox64Concat, @@ -2230,159 +2228,13 @@ pub use frame_support_procedural::pallet; /// Contains macro stubs for all of the pallet:: macros pub mod pallet_macros { pub use frame_support_procedural::{ - composite_enum, config, disable_frame_system_supertrait_check, error, event, - extra_constants, feeless_if, generate_deposit, generate_store, getter, hooks, + call_index, compact, composite_enum, config, disable_frame_system_supertrait_check, error, + event, extra_constants, feeless_if, generate_deposit, generate_store, getter, hooks, import_section, inherent, no_default, no_default_bounds, origin, pallet_section, storage_prefix, storage_version, type_value, unbounded, validate_unsigned, weight, whitelist_storage, }; - /// Allows a pallet to declare a set of functions as a *dispatchable extrinsic*. In - /// slightly simplified terms, this macro declares the set of "transactions" of a pallet. - /// - /// > The exact definition of **extrinsic** can be found in - /// > [`sp_runtime::generic::UncheckedExtrinsic`]. - /// - /// A **dispatchable** is a common term in FRAME, referring to process of constructing a - /// function, and dispatching it with the correct inputs. This is commonly used with - /// extrinsics, for example "an extrinsic has been dispatched". See - /// [`sp_runtime::traits::Dispatchable`] and [`crate::traits::UnfilteredDispatchable`]. - /// - /// ## Call Enum - /// - /// The macro is called `call` (rather than `#[pallet::extrinsics]`) because of the - /// generation of a `enum Call`. This enum contains only the encoding of the function - /// arguments of the dispatchable, alongside the information needed to route it to the - /// correct function. - /// - /// ``` - /// #[frame_support::pallet(dev_mode)] - /// pub mod custom_pallet { - /// # use frame_support::pallet_prelude::*; - /// # use frame_system::pallet_prelude::*; - /// # #[pallet::config] - /// # pub trait Config: frame_system::Config {} - /// # #[pallet::pallet] - /// # pub struct Pallet(_); - /// # use frame_support::traits::BuildGenesisConfig; - /// #[pallet::call] - /// impl Pallet { - /// pub fn some_dispatchable(_origin: OriginFor, _input: u32) -> DispatchResult { - /// Ok(()) - /// } - /// pub fn other(_origin: OriginFor, _input: u64) -> DispatchResult { - /// Ok(()) - /// } - /// } - /// - /// // generates something like: - /// // enum Call { - /// // some_dispatchable { input: u32 } - /// // other { input: u64 } - /// // } - /// } - /// - /// fn main() { - /// # use frame_support::{derive_impl, construct_runtime}; - /// # use frame_support::__private::codec::Encode; - /// # use frame_support::__private::TestExternalities; - /// # use frame_support::traits::UnfilteredDispatchable; - /// # impl custom_pallet::Config for Runtime {} - /// # #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] - /// # impl frame_system::Config for Runtime { - /// # type Block = frame_system::mocking::MockBlock; - /// # } - /// construct_runtime! { - /// pub struct Runtime { - /// System: frame_system, - /// Custom: custom_pallet - /// } - /// } - /// - /// # TestExternalities::new_empty().execute_with(|| { - /// let origin: RuntimeOrigin = frame_system::RawOrigin::Signed(10).into(); - /// // calling into a dispatchable from within the runtime is simply a function call. - /// let _ = custom_pallet::Pallet::::some_dispatchable(origin.clone(), 10); - /// - /// // calling into a dispatchable from the outer world involves constructing the bytes of - /// let call = custom_pallet::Call::::some_dispatchable { input: 10 }; - /// let _ = call.clone().dispatch_bypass_filter(origin); - /// - /// // the routing of a dispatchable is simply done through encoding of the `Call` enum, - /// // which is the index of the variant, followed by the arguments. - /// assert_eq!(call.encode(), vec![0u8, 10, 0, 0, 0]); - /// - /// // notice how in the encoding of the second function, the first byte is different and - /// // referring to the second variant of `enum Call`. - /// let call = custom_pallet::Call::::other { input: 10 }; - /// assert_eq!(call.encode(), vec![1u8, 10, 0, 0, 0, 0, 0, 0, 0]); - /// # }); - /// } - /// ``` - /// - /// Further properties of dispatchable functions are as follows: - /// - /// - Unless if annotated by `dev_mode`, it must contain [`weight`] to denote the - /// pre-dispatch weight consumed. - /// - The dispatchable must declare its index via [`call_index`], which can override the - /// position of a function in `enum Call`. - /// - The first argument is always an `OriginFor` (or `T::RuntimeOrigin`). - /// - The return type is always [`crate::dispatch::DispatchResult`] (or - /// [`crate::dispatch::DispatchResultWithPostInfo`]). - /// - /// **WARNING**: modifying dispatchables, changing their order (i.e. using [`call_index`]), - /// removing some, etc., must be done with care. This will change the encoding of the , and - /// the call can be stored on-chain (e.g. in `pallet-scheduler`). Thus, migration might be - /// needed. This is why the use of `call_index` is mandatory by default in FRAME. - /// - /// ## Default Behavior - /// - /// If no `#[pallet::call]` exists, then a default implementation corresponding to the - /// following code is automatically generated: - /// - /// ```ignore - /// #[pallet::call] - /// impl Pallet {} - /// ``` - pub use frame_support_procedural::call; - - /// Enforce the index of a variant in the generated `enum Call`. See [`call`] for more - /// information. - /// - /// All call indexes start from 0, until it encounters a dispatchable function with a - /// defined call index. The dispatchable function that lexically follows the function with - /// a defined call index will have that call index, but incremented by 1, e.g. if there are - /// 3 dispatchable functions `fn foo`, `fn bar` and `fn qux` in that order, and only `fn - /// bar` has a call index of 10, then `fn qux` will have an index of 11, instead of 1. - pub use frame_support_procedural::call_index; - - /// Declares the arguments of a [`call`] function to be encoded using - /// [`codec::Compact`]. This will results in smaller extrinsic encoding. - /// - /// A common example of `compact` is for numeric values that are often times far far away - /// from their theoretical maximum. For example, in the context of a crypto-currency, the - /// balance of an individual account is oftentimes way less than what the numeric type - /// allows. In all such cases, using `compact` is sensible. - /// - /// ``` - /// #[frame_support::pallet(dev_mode)] - /// pub mod custom_pallet { - /// # use frame_support::pallet_prelude::*; - /// # use frame_system::pallet_prelude::*; - /// # #[pallet::config] - /// # pub trait Config: frame_system::Config {} - /// # #[pallet::pallet] - /// # pub struct Pallet(_); - /// # use frame_support::traits::BuildGenesisConfig; - /// #[pallet::call] - /// impl Pallet { - /// pub fn some_dispatchable(_origin: OriginFor, #[pallet::compact] _input: u32) -> DispatchResult { - /// Ok(()) - /// } - /// } - /// } - pub use frame_support_procedural::compact; - /// Allows you to define the genesis configuration for the pallet. /// /// Item is defined as either an enum or a struct. It needs to be public and implement the @@ -2676,61 +2528,6 @@ pub mod pallet_macros { /// } /// ``` pub use frame_support_procedural::storage; - /// This attribute is attached to a function inside an `impl` block annoated with - /// [`pallet::tasks_experimental`](`tasks_experimental`) to define the conditions for a - /// given work item to be valid. - /// - /// It takes a closure as input, which is then used to define the condition. The closure - /// should have the same signature as the function it is attached to, except that it should - /// return a `bool` instead. - pub use frame_support_procedural::task_condition; - /// This attribute is attached to a function inside an `impl` block annoated with - /// [`pallet::tasks_experimental`](`tasks_experimental`) to define the index of a given - /// work item. - /// - /// It takes an integer literal as input, which is then used to define the index. This - /// index should be unique for each function in the `impl` block. - pub use frame_support_procedural::task_index; - /// This attribute is attached to a function inside an `impl` block annoated with - /// [`pallet::tasks_experimental`](`tasks_experimental`) to define an iterator over the - /// available work items for a task. - /// - /// It takes an iterator as input that yields a tuple with same types as the function - /// arguments. - pub use frame_support_procedural::task_list; - /// This attribute is attached to a function inside an `impl` block annoated with - /// [`pallet::tasks_experimental`](`tasks_experimental`) define the weight of a given work - /// item. - /// - /// It takes a closure as input, which should return a `Weight` value. - pub use frame_support_procedural::task_weight; - /// Allows you to define some service work that can be recognized by a script or an - /// off-chain worker. Such a script can then create and submit all such work items at any - /// given time. - /// - /// These work items are defined as instances of the [`Task`](frame_support::traits::Task) - /// trait. [`pallet:tasks_experimental`](`tasks_experimental`) when attached to an `impl` - /// block inside a pallet, will generate an enum `Task` whose variants are mapped to - /// functions inside this `impl` block. - /// - /// Each such function must have the following set of attributes: - /// - /// * [`pallet::task_list`](`task_list`) - /// * [`pallet::task_condition`](`task_condition`) - /// * [`pallet::task_weight`](`task_weight`) - /// * [`pallet::task_index`](`task_index`) - /// - /// All of such Tasks are then aggregated into a `RuntimeTask` by - /// [`construct_runtime`](frame_support::construct_runtime). - /// - /// Finally, the `RuntimeTask` can then used by a script or off-chain worker to create and - /// submit such tasks via an extrinsic defined in `frame_system` called `do_task`. - /// - /// ## Example - #[doc = docify::embed!("src/tests/tasks.rs", tasks_example)] - /// Now, this can be executed as follows: - #[doc = docify::embed!("src/tests/tasks.rs", tasks_work)] - pub use frame_support_procedural::tasks_experimental; } #[deprecated(note = "Will be removed after July 2023; Use `sp_runtime::traits` directly instead.")] diff --git a/substrate/frame/support/src/migrations.rs b/substrate/frame/support/src/migrations.rs index bfd62c8611c..a9eb460421f 100644 --- a/substrate/frame/support/src/migrations.rs +++ b/substrate/frame/support/src/migrations.rs @@ -224,7 +224,8 @@ impl PalletVersionToStorageVersionHelper for T { } } -/// Migrate from the `PalletVersion` struct to the new [`StorageVersion`] struct. +/// Migrate from the `PalletVersion` struct to the new +/// [`StorageVersion`](crate::traits::StorageVersion) struct. /// /// This will remove all `PalletVersion's` from the state and insert the current storage version. pub fn migrate_from_pallet_version_to_storage_version< diff --git a/substrate/frame/support/src/storage/child.rs b/substrate/frame/support/src/storage/child.rs index 76e6f4ee402..e54002d18db 100644 --- a/substrate/frame/support/src/storage/child.rs +++ b/substrate/frame/support/src/storage/child.rs @@ -165,9 +165,9 @@ pub fn kill_storage(child_info: &ChildInfo, limit: Option) -> KillStorageRe /// guarantee that the subsequent call is in a new block; in this case the previous call's result /// cursor need not be passed in an a `None` may be passed instead. This exception may be useful /// then making this call solely from a block-hook such as `on_initialize`. - -/// Returns [`MultiRemovalResults`] to inform about the result. Once the resultant `maybe_cursor` -/// field is `None`, then no further items remain to be deleted. +/// +/// Returns [`MultiRemovalResults`](sp_io::MultiRemovalResults) to inform about the result. Once the +/// resultant `maybe_cursor` field is `None`, then no further items remain to be deleted. /// /// NOTE: After the initial call for any given child storage, it is important that no keys further /// keys are inserted. If so, then they may or may not be deleted by subsequent calls. diff --git a/substrate/frame/support/src/storage/generator/mod.rs b/substrate/frame/support/src/storage/generator/mod.rs index dd6d622852d..2b2abdc2e83 100644 --- a/substrate/frame/support/src/storage/generator/mod.rs +++ b/substrate/frame/support/src/storage/generator/mod.rs @@ -63,7 +63,6 @@ mod tests { type BaseCallFilter: crate::traits::Contains; type RuntimeOrigin; type RuntimeCall; - type RuntimeTask; type PalletInfo: crate::traits::PalletInfo; type DbWeight: Get; } @@ -130,7 +129,6 @@ mod tests { type BaseCallFilter = crate::traits::Everything; type RuntimeOrigin = RuntimeOrigin; type RuntimeCall = RuntimeCall; - type RuntimeTask = RuntimeTask; type PalletInfo = PalletInfo; type DbWeight = (); } diff --git a/substrate/frame/support/src/storage/mod.rs b/substrate/frame/support/src/storage/mod.rs index c77de1f976f..7f39a3fdad8 100644 --- a/substrate/frame/support/src/storage/mod.rs +++ b/substrate/frame/support/src/storage/mod.rs @@ -1583,7 +1583,7 @@ pub trait StorageTryAppend: StorageDecodeLength + private::Sealed { fn bound() -> usize; } -/// Storage value that is capable of [`StorageTryAppend`]. +/// Storage value that is capable of [`StorageTryAppend`](crate::storage::StorageTryAppend). pub trait TryAppendValue, I: Encode> { /// Try and append the `item` into the storage item. /// @@ -1612,7 +1612,7 @@ where } } -/// Storage map that is capable of [`StorageTryAppend`]. +/// Storage map that is capable of [`StorageTryAppend`](crate::storage::StorageTryAppend). pub trait TryAppendMap, I: Encode> { /// Try and append the `item` into the storage map at the given `key`. /// @@ -1646,7 +1646,7 @@ where } } -/// Storage double map that is capable of [`StorageTryAppend`]. +/// Storage double map that is capable of [`StorageTryAppend`](crate::storage::StorageTryAppend). pub trait TryAppendDoubleMap, I: Encode> { /// Try and append the `item` into the storage double map at the given `key`. /// diff --git a/substrate/frame/support/src/tests/mod.rs b/substrate/frame/support/src/tests/mod.rs index c6a0b6cde77..3690159c599 100644 --- a/substrate/frame/support/src/tests/mod.rs +++ b/substrate/frame/support/src/tests/mod.rs @@ -16,7 +16,6 @@ // limitations under the License. use super::*; -use frame_support_procedural::import_section; use sp_io::{MultiRemovalResults, TestExternalities}; use sp_metadata_ir::{ PalletStorageMetadataIR, StorageEntryMetadataIR, StorageEntryModifierIR, StorageEntryTypeIR, @@ -28,15 +27,13 @@ pub use self::frame_system::{pallet_prelude::*, Config, Pallet}; mod inject_runtime_type; mod storage_alias; -mod tasks; -#[import_section(tasks::tasks_example)] #[pallet] pub mod frame_system { #[allow(unused)] use super::{frame_system, frame_system::pallet_prelude::*}; pub use crate::dispatch::RawOrigin; - use crate::{pallet_prelude::*, traits::tasks::Task as TaskTrait}; + use crate::pallet_prelude::*; pub mod config_preludes { use super::{inject_runtime_type, DefaultConfig}; @@ -52,8 +49,6 @@ pub mod frame_system { type RuntimeCall = (); #[inject_runtime_type] type PalletInfo = (); - #[inject_runtime_type] - type RuntimeTask = (); type DbWeight = (); } } @@ -74,8 +69,6 @@ pub mod frame_system { #[pallet::no_default_bounds] type RuntimeCall; #[pallet::no_default_bounds] - type RuntimeTask: crate::traits::tasks::Task; - #[pallet::no_default_bounds] type PalletInfo: crate::traits::PalletInfo; type DbWeight: Get; } @@ -84,33 +77,13 @@ pub mod frame_system { pub enum Error { /// Required by construct_runtime CallFiltered, - /// Used in tasks example. - NotFound, - /// The specified [`Task`] is not valid. - InvalidTask, - /// The specified [`Task`] failed during execution. - FailedTask, } #[pallet::origin] pub type Origin = RawOrigin<::AccountId>; #[pallet::call] - impl Pallet { - #[pallet::call_index(0)] - #[pallet::weight(task.weight())] - pub fn do_task(_origin: OriginFor, task: T::RuntimeTask) -> DispatchResultWithPostInfo { - if !task.is_valid() { - return Err(Error::::InvalidTask.into()) - } - - if let Err(_err) = task.run() { - return Err(Error::::FailedTask.into()) - } - - Ok(().into()) - } - } + impl Pallet {} #[pallet::storage] pub type Data = StorageMap<_, Twox64Concat, u32, u64, ValueQuery>; @@ -196,14 +169,6 @@ pub mod frame_system { } } - /// Some running total. - #[pallet::storage] - pub type Total = StorageValue<_, (u32, u32), ValueQuery>; - - /// Numbers to be added into the total. - #[pallet::storage] - pub type Numbers = StorageMap<_, Twox64Concat, u32, u32, OptionQuery>; - pub mod pallet_prelude { pub type OriginFor = ::RuntimeOrigin; @@ -657,24 +622,6 @@ fn expected_metadata() -> PalletStorageMetadataIR { default: vec![0], docs: vec![], }, - StorageEntryMetadataIR { - name: "Total", - modifier: StorageEntryModifierIR::Default, - ty: StorageEntryTypeIR::Plain(scale_info::meta_type::<(u32, u32)>()), - default: vec![0, 0, 0, 0, 0, 0, 0, 0], - docs: vec![" Some running total."], - }, - StorageEntryMetadataIR { - name: "Numbers", - modifier: StorageEntryModifierIR::Optional, - ty: StorageEntryTypeIR::Map { - hashers: vec![StorageHasherIR::Twox64Concat], - key: scale_info::meta_type::(), - value: scale_info::meta_type::(), - }, - default: vec![0], - docs: vec![" Numbers to be added into the total."], - }, ], } } diff --git a/substrate/frame/support/src/tests/tasks.rs b/substrate/frame/support/src/tests/tasks.rs deleted file mode 100644 index 2774c130075..00000000000 --- a/substrate/frame/support/src/tests/tasks.rs +++ /dev/null @@ -1,62 +0,0 @@ -// 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 crate::{ - assert_ok, - tests::{ - frame_system::{Numbers, Total}, - new_test_ext, Runtime, RuntimeOrigin, RuntimeTask, System, - }, -}; -use frame_support_procedural::pallet_section; - -#[pallet_section] -mod tasks_example { - #[docify::export(tasks_example)] - #[pallet::tasks_experimental] - impl Pallet { - /// Add a pair of numbers into the totals and remove them. - #[pallet::task_list(Numbers::::iter_keys())] - #[pallet::task_condition(|i| Numbers::::contains_key(i))] - #[pallet::task_weight(0.into())] - #[pallet::task_index(0)] - pub fn add_number_into_total(i: u32) -> DispatchResult { - let v = Numbers::::take(i).ok_or(Error::::NotFound)?; - Total::::mutate(|(total_keys, total_values)| { - *total_keys += i; - *total_values += v; - }); - Ok(()) - } - } -} - -#[docify::export] -#[test] -fn tasks_work() { - new_test_ext().execute_with(|| { - Numbers::::insert(0, 1); - - let task = RuntimeTask::System(super::frame_system::Task::::AddNumberIntoTotal { - i: 0u32, - }); - - assert_ok!(System::do_task(RuntimeOrigin::signed(1), task.clone(),)); - assert_eq!(Numbers::::get(0), None); - assert_eq!(Total::::get(), (0, 1)); - }); -} diff --git a/substrate/frame/support/src/traits.rs b/substrate/frame/support/src/traits.rs index 9afd9c16130..6362e750d2a 100644 --- a/substrate/frame/support/src/traits.rs +++ b/substrate/frame/support/src/traits.rs @@ -123,9 +123,6 @@ pub use safe_mode::{SafeMode, SafeModeError, SafeModeNotify}; mod tx_pause; pub use tx_pause::{TransactionPause, TransactionPauseError}; -pub mod tasks; -pub use tasks::Task; - #[cfg(feature = "try-runtime")] mod try_runtime; #[cfg(feature = "try-runtime")] diff --git a/substrate/frame/support/src/traits/messages.rs b/substrate/frame/support/src/traits/messages.rs index 995ac4f7179..58815b107c8 100644 --- a/substrate/frame/support/src/traits/messages.rs +++ b/substrate/frame/support/src/traits/messages.rs @@ -82,8 +82,6 @@ pub enum ExecuteOverweightError { QueuePaused, /// An unspecified error. Other, - /// Another call is currently ongoing and prevents this call from executing. - RecursiveDisallowed, } /// Can service queues and execute overweight messages. diff --git a/substrate/frame/support/src/traits/tasks.rs b/substrate/frame/support/src/traits/tasks.rs deleted file mode 100644 index 24f3430cf50..00000000000 --- a/substrate/frame/support/src/traits/tasks.rs +++ /dev/null @@ -1,87 +0,0 @@ -// 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. - -//! Contains the [`Task`] trait, which defines a general-purpose way for defining and executing -//! service work, and supporting types. - -use codec::FullCodec; -use scale_info::TypeInfo; -use sp_runtime::DispatchError; -use sp_std::{fmt::Debug, iter::Iterator, vec, vec::IntoIter}; -use sp_weights::Weight; - -/// Contain's re-exports of all the supporting types for the [`Task`] trait. Used in the macro -/// expansion of `RuntimeTask`. -#[doc(hidden)] -pub mod __private { - pub use codec::FullCodec; - pub use scale_info::TypeInfo; - pub use sp_runtime::DispatchError; - pub use sp_std::{fmt::Debug, iter::Iterator, vec, vec::IntoIter}; - pub use sp_weights::Weight; -} - -/// A general-purpose trait which defines a type of service work (i.e., work to performed by an -/// off-chain worker) including methods for enumerating, validating, indexing, and running -/// tasks of this type. -pub trait Task: Sized + FullCodec + TypeInfo + Clone + Debug + PartialEq + Eq { - /// An [`Iterator`] over tasks of this type used as the return type for `enumerate`. - type Enumeration: Iterator; - - /// Inspects the pallet's state and enumerates tasks of this type. - fn iter() -> Self::Enumeration; - - /// Checks if a particular instance of this `Task` variant is a valid piece of work. - fn is_valid(&self) -> bool; - - /// Performs the work for this particular `Task` variant. - fn run(&self) -> Result<(), DispatchError>; - - /// Returns the weight of executing this `Task`. - fn weight(&self) -> Weight; - - /// A unique value representing this `Task` within the current pallet. Analogous to - /// `call_index`, but for tasks.' - /// - /// This value should be unique within the current pallet and can overlap with task indices - /// in other pallets. - fn task_index(&self) -> u32; -} - -impl Task for () { - type Enumeration = IntoIter; - - fn iter() -> Self::Enumeration { - vec![].into_iter() - } - - fn is_valid(&self) -> bool { - true - } - - fn run(&self) -> Result<(), DispatchError> { - Ok(()) - } - - fn weight(&self) -> Weight { - Weight::default() - } - - fn task_index(&self) -> u32 { - 0 - } -} diff --git a/substrate/frame/support/src/traits/tokens/fungible/regular.rs b/substrate/frame/support/src/traits/tokens/fungible/regular.rs index aece73777d2..f2fb5c5f7c2 100644 --- a/substrate/frame/support/src/traits/tokens/fungible/regular.rs +++ b/substrate/frame/support/src/traits/tokens/fungible/regular.rs @@ -514,47 +514,3 @@ pub trait Balanced: Inspect + Unbalanced { fn done_deposit(_who: &AccountId, _amount: Self::Balance) {} fn done_withdraw(_who: &AccountId, _amount: Self::Balance) {} } - -/// Dummy implementation of [`Inspect`] -#[cfg(feature = "std")] -impl Inspect for () { - type Balance = u32; - fn total_issuance() -> Self::Balance { - 0 - } - fn minimum_balance() -> Self::Balance { - 0 - } - fn total_balance(_: &AccountId) -> Self::Balance { - 0 - } - fn balance(_: &AccountId) -> Self::Balance { - 0 - } - fn reducible_balance(_: &AccountId, _: Preservation, _: Fortitude) -> Self::Balance { - 0 - } - fn can_deposit(_: &AccountId, _: Self::Balance, _: Provenance) -> DepositConsequence { - DepositConsequence::Success - } - fn can_withdraw(_: &AccountId, _: Self::Balance) -> WithdrawConsequence { - WithdrawConsequence::Success - } -} - -/// Dummy implementation of [`Unbalanced`] -#[cfg(feature = "std")] -impl Unbalanced for () { - fn handle_dust(_: Dust) {} - fn write_balance( - _: &AccountId, - _: Self::Balance, - ) -> Result, DispatchError> { - Ok(None) - } - fn set_total_issuance(_: Self::Balance) {} -} - -/// Dummy implementation of [`Mutate`] -#[cfg(feature = "std")] -impl Mutate for () {} diff --git a/substrate/frame/support/src/traits/tokens/fungibles/regular.rs b/substrate/frame/support/src/traits/tokens/fungibles/regular.rs index 41ef4b40c75..a2fc4e55095 100644 --- a/substrate/frame/support/src/traits/tokens/fungibles/regular.rs +++ b/substrate/frame/support/src/traits/tokens/fungibles/regular.rs @@ -593,66 +593,3 @@ pub trait Balanced: Inspect + Unbalanced { fn done_deposit(_asset: Self::AssetId, _who: &AccountId, _amount: Self::Balance) {} fn done_withdraw(_asset: Self::AssetId, _who: &AccountId, _amount: Self::Balance) {} } - -/// Dummy implementation of [`Inspect`] -#[cfg(feature = "std")] -impl Inspect for () { - type AssetId = u32; - type Balance = u32; - fn total_issuance(_: Self::AssetId) -> Self::Balance { - 0 - } - fn minimum_balance(_: Self::AssetId) -> Self::Balance { - 0 - } - fn total_balance(_: Self::AssetId, _: &AccountId) -> Self::Balance { - 0 - } - fn balance(_: Self::AssetId, _: &AccountId) -> Self::Balance { - 0 - } - fn reducible_balance( - _: Self::AssetId, - _: &AccountId, - _: Preservation, - _: Fortitude, - ) -> Self::Balance { - 0 - } - fn can_deposit( - _: Self::AssetId, - _: &AccountId, - _: Self::Balance, - _: Provenance, - ) -> DepositConsequence { - DepositConsequence::Success - } - fn can_withdraw( - _: Self::AssetId, - _: &AccountId, - _: Self::Balance, - ) -> WithdrawConsequence { - WithdrawConsequence::Success - } - fn asset_exists(_: Self::AssetId) -> bool { - false - } -} - -/// Dummy implementation of [`Unbalanced`] -#[cfg(feature = "std")] -impl Unbalanced for () { - fn handle_dust(_: Dust) {} - fn write_balance( - _: Self::AssetId, - _: &AccountId, - _: Self::Balance, - ) -> Result, DispatchError> { - Ok(None) - } - fn set_total_issuance(_: Self::AssetId, _: Self::Balance) {} -} - -/// Dummy implementation of [`Mutate`] -#[cfg(feature = "std")] -impl Mutate for () {} diff --git a/substrate/frame/support/test/Cargo.toml b/substrate/frame/support/test/Cargo.toml index 8ee1b4b2918..fc10725e814 100644 --- a/substrate/frame/support/test/Cargo.toml +++ b/substrate/frame/support/test/Cargo.toml @@ -8,39 +8,36 @@ publish = false homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] static_assertions = "1.1.0" -serde = { version = "1.0.193", default-features = false, features = ["derive"] } +serde = { version = "1.0.188", default-features = false, features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", 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-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 } -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.74", features = ["diff"] } +sp-state-machine = { path = "../../../primitives/state-machine", optional = true} +frame-support = { path = "..", default-features = false} +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.74", 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 } +frame-system = { path = "../../system", default-features = false} +frame-executive = { path = "../../executive", default-features = false} # 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 = { package = "frame-support-test-pallet", path = "pallet", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking/std", @@ -61,7 +58,7 @@ std = [ "sp-version/std", "test-pallet/std", ] -experimental = ["frame-support/experimental"] +experimental = [ "frame-support/experimental" ] try-runtime = [ "frame-executive/try-runtime", "frame-support/try-runtime", @@ -75,4 +72,4 @@ frame-feature-testing = [] frame-feature-testing-2 = [] # Disable ui tests disable-ui-tests = [] -no-metadata-docs = ["frame-support/no-metadata-docs"] +no-metadata-docs = [ "frame-support/no-metadata-docs" ] diff --git a/substrate/frame/support/test/compile_pass/Cargo.toml b/substrate/frame/support/test/compile_pass/Cargo.toml index 0617aa105a2..19465d924ec 100644 --- a/substrate/frame/support/test/compile_pass/Cargo.toml +++ b/substrate/frame/support/test/compile_pass/Cargo.toml @@ -8,23 +8,20 @@ publish = false homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -renamed-frame-support = { package = "frame-support", path = "../..", default-features = false } -renamed-frame-system = { package = "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 } +renamed-frame-support = { package = "frame-support", path = "../..", default-features = false} +renamed-frame-system = { package = "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} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "renamed-frame-support/std", diff --git a/substrate/frame/support/test/compile_pass/src/lib.rs b/substrate/frame/support/test/compile_pass/src/lib.rs index b304dfcb282..6ea37fb27e7 100644 --- a/substrate/frame/support/test/compile_pass/src/lib.rs +++ b/substrate/frame/support/test/compile_pass/src/lib.rs @@ -22,7 +22,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use renamed_frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, parameter_types, traits::{ConstU16, ConstU32, ConstU64, Everything}, }; use sp_core::{sr25519, H256}; @@ -51,7 +51,6 @@ parameter_types! { pub const Version: RuntimeVersion = VERSION; } -#[derive_impl(renamed_frame_system::config_preludes::TestDefaultConfig as renamed_frame_system::DefaultConfig)] impl renamed_frame_system::Config for Runtime { type BaseCallFilter = Everything; type BlockWeights = (); diff --git a/substrate/frame/support/test/pallet/Cargo.toml b/substrate/frame/support/test/pallet/Cargo.toml index 493c305cb20..c96e22ff1ab 100644 --- a/substrate/frame/support/test/pallet/Cargo.toml +++ b/substrate/frame/support/test/pallet/Cargo.toml @@ -8,22 +8,19 @@ publish = false homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, features = ["derive"] } -frame-support = { path = "../..", default-features = false } -frame-system = { path = "../../../system", default-features = false } -sp-runtime = { path = "../../../../primitives/runtime", default-features = false } +serde = { version = "1.0.188", default-features = false, features = ["derive"] } +frame-support = { path = "../..", default-features = false} +frame-system = { path = "../../../system", default-features = false} +sp-runtime = { path = "../../../../primitives/runtime", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", diff --git a/substrate/frame/support/test/src/lib.rs b/substrate/frame/support/test/src/lib.rs index a8a72337503..6b38d42d33d 100644 --- a/substrate/frame/support/test/src/lib.rs +++ b/substrate/frame/support/test/src/lib.rs @@ -50,8 +50,6 @@ pub mod pallet { + From>; /// The runtime call type. type RuntimeCall; - /// Contains an aggregation of all tasks in this runtime. - type RuntimeTask; /// The runtime event type. type RuntimeEvent: Parameter + Member diff --git a/substrate/frame/support/test/stg_frame_crate/Cargo.toml b/substrate/frame/support/test/stg_frame_crate/Cargo.toml index 632ea4e794f..0f9617c0368 100644 --- a/substrate/frame/support/test/stg_frame_crate/Cargo.toml +++ b/substrate/frame/support/test/stg_frame_crate/Cargo.toml @@ -8,17 +8,14 @@ publish = false homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } -frame = { path = "../../..", default-features = false, features = ["experimental", "runtime"] } +frame = { path = "../../..", default-features = false, features = ["runtime", "experimental"]} scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } [features] -default = ["std"] -std = ["codec/std", "frame/std", "scale-info/std"] +default = [ "std" ] +std = [ "codec/std", "frame/std", "scale-info/std" ] diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr b/substrate/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr index b08efb3a842..08954bb6ab5 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_ui/deprecated_where_block.stderr @@ -17,7 +17,6 @@ error: use of deprecated constant `WhereSection::_w`: | |_^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` = note: this error originates in the macro `frame_support::match_and_insert` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `Runtime: Config` is not satisfied @@ -98,7 +97,7 @@ note: required because it appears within the type `RuntimeEvent` | ||_- in this macro invocation ... | note: required by a bound in `EncodeLike` - --> $CARGO/parity-scale-codec-3.6.5/src/encode_like.rs + --> $CARGO/parity-scale-codec-3.6.4/src/encode_like.rs | | pub trait EncodeLike: Sized + Encode {} | ^^^^^ required by this bound in `EncodeLike` @@ -130,7 +129,7 @@ note: required because it appears within the type `RuntimeEvent` | ||_- in this macro invocation ... | note: required by a bound in `Decode` - --> $CARGO/parity-scale-codec-3.6.5/src/codec.rs + --> $CARGO/parity-scale-codec-3.6.4/src/codec.rs | | pub trait Decode: Sized { | ^^^^^ required by this bound in `Decode` @@ -302,7 +301,7 @@ note: required because it appears within the type `RuntimeCall` | ||_- in this macro invocation ... | note: required by a bound in `EncodeLike` - --> $CARGO/parity-scale-codec-3.6.5/src/encode_like.rs + --> $CARGO/parity-scale-codec-3.6.4/src/encode_like.rs | | pub trait EncodeLike: Sized + Encode {} | ^^^^^ required by this bound in `EncodeLike` @@ -335,7 +334,7 @@ note: required because it appears within the type `RuntimeCall` | ||_- in this macro invocation ... | note: required by a bound in `Decode` - --> $CARGO/parity-scale-codec-3.6.5/src/codec.rs + --> $CARGO/parity-scale-codec-3.6.4/src/codec.rs | | pub trait Decode: Sized { | ^^^^^ required by this bound in `Decode` diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.stderr b/substrate/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.stderr index 8458de97f6d..bf53f43b9ba 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_ui/generics_in_invalid_module.stderr @@ -1,4 +1,4 @@ -error: `Call` is not allowed to have generics. Only the following pallets are allowed to have generics: `Event`, `Error`, `Origin`, `Config`, `Task`. +error: `Call` is not allowed to have generics. Only the following pallets are allowed to have generics: `Event`, `Error`, `Origin`, `Config`. --> tests/construct_runtime_ui/generics_in_invalid_module.rs:24:36 | 24 | Balance: balances::::{Call, Origin}, diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.stderr b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.stderr index feb61793151..ad631de204e 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_details_keyword.stderr @@ -1,4 +1,4 @@ -error: expected one of: `Pallet`, `Call`, `Storage`, `Event`, `Error`, `Config`, `Origin`, `Inherent`, `ValidateUnsigned`, `FreezeReason`, `HoldReason`, `Task`, `LockId`, `SlashReason` +error: expected one of: `Pallet`, `Call`, `Storage`, `Event`, `Error`, `Config`, `Origin`, `Inherent`, `ValidateUnsigned`, `FreezeReason`, `HoldReason`, `LockId`, `SlashReason` --> tests/construct_runtime_ui/invalid_module_details_keyword.rs:23:20 | 23 | system: System::{enum}, diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.stderr b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.stderr index 97943dfc176..b5b89a5a270 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.stderr +++ b/substrate/frame/support/test/tests/construct_runtime_ui/invalid_module_entry.stderr @@ -1,4 +1,4 @@ -error: expected one of: `Pallet`, `Call`, `Storage`, `Event`, `Error`, `Config`, `Origin`, `Inherent`, `ValidateUnsigned`, `FreezeReason`, `HoldReason`, `Task`, `LockId`, `SlashReason` +error: expected one of: `Pallet`, `Call`, `Storage`, `Event`, `Error`, `Config`, `Origin`, `Inherent`, `ValidateUnsigned`, `FreezeReason`, `HoldReason`, `LockId`, `SlashReason` --> tests/construct_runtime_ui/invalid_module_entry.rs:24:23 | 24 | Balance: balances::{Unexpected}, diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs b/substrate/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs index 78ae6f57f08..ea52293a673 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::{construct_runtime, derive_impl}; +use frame_support::construct_runtime; use sp_core::sr25519; use sp_runtime::{generic, traits::BlakeTwo256}; @@ -36,7 +36,6 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:67:2 + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:66:2 | -67 | pub struct Runtime +66 | pub struct Runtime | ^^^ error[E0412]: cannot find type `RuntimeCall` in this scope @@ -22,70 +22,42 @@ error[E0412]: cannot find type `Runtime` in this scope | ^^^^^^^ not found in this scope error[E0412]: cannot find type `Runtime` in this scope - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:40:31 + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:39:31 | -40 | impl frame_system::Config for Runtime { +39 | impl frame_system::Config for Runtime { | ^^^^^^^ not found in this scope error[E0412]: cannot find type `RuntimeOrigin` in this scope - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:42:23 + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:41:23 | -42 | type RuntimeOrigin = RuntimeOrigin; - | ^^^^^^^^^^^^^ - | -help: you might have meant to use the associated type - | -42 | type RuntimeOrigin = Self::RuntimeOrigin; - | ++++++ +41 | type RuntimeOrigin = RuntimeOrigin; + | ^^^^^^^^^^^^^ help: you might have meant to use the associated type: `Self::RuntimeOrigin` error[E0412]: cannot find type `RuntimeCall` in this scope - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:44:21 - | -44 | type RuntimeCall = RuntimeCall; - | ^^^^^^^^^^^ + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:43:21 | -help: you might have meant to use the associated type - | -44 | type RuntimeCall = Self::RuntimeCall; - | ++++++ +43 | type RuntimeCall = RuntimeCall; + | ^^^^^^^^^^^ help: you might have meant to use the associated type: `Self::RuntimeCall` error[E0412]: cannot find type `RuntimeEvent` in this scope - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:50:22 - | -50 | type RuntimeEvent = RuntimeEvent; - | ^^^^^^^^^^^^ + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:49:22 | -help: you might have meant to use the associated type - | -50 | type RuntimeEvent = Self::RuntimeEvent; - | ++++++ +49 | type RuntimeEvent = RuntimeEvent; + | ^^^^^^^^^^^^ help: you might have meant to use the associated type: `Self::RuntimeEvent` error[E0412]: cannot find type `PalletInfo` in this scope - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:56:20 + --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:55:20 | -56 | type PalletInfo = PalletInfo; +55 | type PalletInfo = PalletInfo; | ^^^^^^^^^^ | help: you might have meant to use the associated type | -56 | type PalletInfo = Self::PalletInfo; - | ++++++ +55 | type PalletInfo = Self::PalletInfo; + | ~~~~~~~~~~~~~~~~ help: consider importing one of these items | 18 + use frame_benchmarking::__private::traits::PalletInfo; | 18 + use frame_support::traits::PalletInfo; | - -error[E0412]: cannot find type `RuntimeTask` in this scope - --> tests/construct_runtime_ui/number_of_pallets_exceeds_tuple_size.rs:39:1 - | -39 | #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the macro `frame_system::config_preludes::TestDefaultConfig` which comes from the expansion of the macro `frame_support::macro_magic::forward_tokens_verbatim` (in Nightly builds, run with -Z macro-backtrace for more info) -help: you might have meant to use the associated type - --> $WORKSPACE/substrate/frame/system/src/lib.rs - | - | type Self::RuntimeTask = (); - | ++++++ diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs b/substrate/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs index d3e519af551..2834b5b8f2a 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/pallet_error_too_large.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::{construct_runtime, derive_impl}; +use frame_support::construct_runtime; use sp_core::sr25519; use sp_runtime::{generic, traits::BlakeTwo256}; @@ -61,7 +61,6 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic tests/construct_runtime_ui/pallet_error_too_large.rs:91:1 + --> tests/construct_runtime_ui/pallet_error_too_large.rs:90:1 | -91 | / construct_runtime! { -92 | | pub struct Runtime -93 | | { -94 | | System: frame_system::{Pallet, Call, Storage, Config, Event}, -95 | | Pallet: pallet::{Pallet}, -96 | | } -97 | | } - | |_^ the evaluated program panicked at 'The maximum encoded size of the error type in the `Pallet` pallet exceeds `MAX_MODULE_ERROR_ENCODED_SIZE`', $DIR/tests/construct_runtime_ui/pallet_error_too_large.rs:91:1 +90 | / construct_runtime! { +91 | | pub struct Runtime +92 | | { +93 | | System: frame_system::{Pallet, Call, Storage, Config, Event}, +94 | | Pallet: pallet::{Pallet}, +95 | | } +96 | | } + | |_^ the evaluated program panicked at 'The maximum encoded size of the error type in the `Pallet` pallet exceeds `MAX_MODULE_ERROR_ENCODED_SIZE`', $DIR/tests/construct_runtime_ui/pallet_error_too_large.rs:90:1 | = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs b/substrate/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs index 8193d12120c..62c4b1327e0 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/undefined_call_part.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::{construct_runtime, derive_impl}; +use frame_support::construct_runtime; use sp_core::sr25519; use sp_runtime::{generic, traits::BlakeTwo256}; @@ -36,7 +36,6 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic, Event}, -70 | | Pallet: pallet::{Pallet, Call}, -71 | | } -72 | | } +65 | / construct_runtime! { +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet::{Pallet, Call}, +70 | | } +71 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_call_check::is_call_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs b/substrate/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs index ef3a790b61a..893690501a8 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/undefined_event_part.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::{construct_runtime, derive_impl}; +use frame_support::construct_runtime; use sp_core::sr25519; use sp_runtime::{generic, traits::BlakeTwo256}; @@ -36,7 +36,6 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic, Event}, -70 | | Pallet: pallet expanded::{}::{Pallet, Event}, -71 | | } -72 | | } +65 | / construct_runtime! { +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet expanded::{}::{Pallet, Event}, +70 | | } +71 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_event_check::is_event_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0412]: cannot find type `Event` in module `pallet` - --> tests/construct_runtime_ui/undefined_event_part.rs:66:1 + --> tests/construct_runtime_ui/undefined_event_part.rs:65:1 | -66 | / construct_runtime! { -67 | | pub struct Runtime -68 | | { -69 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, -70 | | Pallet: pallet expanded::{}::{Pallet, Event}, -71 | | } -72 | | } +65 | / construct_runtime! { +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet expanded::{}::{Pallet, Event}, +70 | | } +71 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs b/substrate/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs index b4dd41750c8..a3501ca31a3 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/undefined_genesis_config_part.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::{construct_runtime, derive_impl}; +use frame_support::construct_runtime; use sp_core::sr25519; use sp_runtime::{generic, traits::BlakeTwo256}; @@ -36,7 +36,6 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic, Event}, -70 | | Pallet: pallet expanded::{}::{Pallet, Config}, -71 | | } -72 | | } +65 | / construct_runtime! { +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet expanded::{}::{Pallet, Config}, +70 | | } +71 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_genesis_config_check::is_genesis_config_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0412]: cannot find type `GenesisConfig` in module `pallet` - --> tests/construct_runtime_ui/undefined_genesis_config_part.rs:66:1 + --> tests/construct_runtime_ui/undefined_genesis_config_part.rs:65:1 | -66 | / construct_runtime! { -67 | | pub struct Runtime -68 | | { -69 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, -70 | | Pallet: pallet expanded::{}::{Pallet, Config}, -71 | | } -72 | | } +65 | / construct_runtime! { +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet expanded::{}::{Pallet, Config}, +70 | | } +71 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs b/substrate/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs index 5e0b8f3c44f..e22745930d6 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/undefined_inherent_part.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::{construct_runtime, derive_impl}; +use frame_support::construct_runtime; use sp_core::sr25519; use sp_runtime::{generic, traits::BlakeTwo256}; @@ -36,7 +36,6 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic, Event}, -70 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, -71 | | } -72 | | } +65 | / construct_runtime! { +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +70 | | } +71 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_inherent_check::is_inherent_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `create_inherent` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:66:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:65:1 | 28 | pub struct Pallet(_); | -------------------- function or associated item `create_inherent` not found for this struct ... -66 | construct_runtime! { +65 | construct_runtime! { | _^ -67 | | pub struct Runtime -68 | | { -69 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, -70 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, -71 | | } -72 | | } +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +70 | | } +71 | | } | |_^ function or associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope @@ -37,19 +37,19 @@ error[E0599]: no function or associated item named `create_inherent` found for s = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `is_inherent` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:66:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:65:1 | 28 | pub struct Pallet(_); | -------------------- function or associated item `is_inherent` not found for this struct ... -66 | construct_runtime! { +65 | construct_runtime! { | _^ -67 | | pub struct Runtime -68 | | { -69 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, -70 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, -71 | | } -72 | | } +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +70 | | } +71 | | } | |_^ function or associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope @@ -58,19 +58,19 @@ error[E0599]: no function or associated item named `is_inherent` found for struc = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `check_inherent` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:66:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:65:1 | 28 | pub struct Pallet(_); | -------------------- function or associated item `check_inherent` not found for this struct ... -66 | construct_runtime! { +65 | construct_runtime! { | _^ -67 | | pub struct Runtime -68 | | { -69 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, -70 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, -71 | | } -72 | | } +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +70 | | } +71 | | } | |_^ function or associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope @@ -79,19 +79,19 @@ error[E0599]: no function or associated item named `check_inherent` found for st = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no associated item named `INHERENT_IDENTIFIER` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:66:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:65:1 | 28 | pub struct Pallet(_); | -------------------- associated item `INHERENT_IDENTIFIER` not found for this struct ... -66 | construct_runtime! { +65 | construct_runtime! { | _^ -67 | | pub struct Runtime -68 | | { -69 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, -70 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, -71 | | } -72 | | } +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +70 | | } +71 | | } | |_^ associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope @@ -100,19 +100,19 @@ error[E0599]: no associated item named `INHERENT_IDENTIFIER` found for struct `p = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `is_inherent_required` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_inherent_part.rs:66:1 + --> tests/construct_runtime_ui/undefined_inherent_part.rs:65:1 | 28 | pub struct Pallet(_); | -------------------- function or associated item `is_inherent_required` not found for this struct ... -66 | construct_runtime! { +65 | construct_runtime! { | _^ -67 | | pub struct Runtime -68 | | { -69 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, -70 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, -71 | | } -72 | | } +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet expanded::{}::{Pallet, Inherent}, +70 | | } +71 | | } | |_^ function or associated item not found in `Pallet` | = help: items from traits can only be used if the trait is implemented and in scope diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs b/substrate/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs index 40a4a1ebcb5..656365279b8 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/undefined_origin_part.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::{construct_runtime, derive_impl}; +use frame_support::construct_runtime; use sp_core::sr25519; use sp_runtime::{generic, traits::BlakeTwo256}; @@ -36,7 +36,6 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic, Event}, -70 | | Pallet: pallet expanded::{}::{Pallet, Origin}, -71 | | } -72 | | } +65 | / construct_runtime! { +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet expanded::{}::{Pallet, Origin}, +70 | | } +71 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_origin_check::is_origin_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0412]: cannot find type `Origin` in module `pallet` - --> tests/construct_runtime_ui/undefined_origin_part.rs:66:1 + --> tests/construct_runtime_ui/undefined_origin_part.rs:65:1 | -66 | / construct_runtime! { -67 | | pub struct Runtime -68 | | { -69 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, -70 | | Pallet: pallet expanded::{}::{Pallet, Origin}, -71 | | } -72 | | } +65 | / construct_runtime! { +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system expanded::{}::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet expanded::{}::{Pallet, Origin}, +70 | | } +71 | | } | |_^ not found in `pallet` | = note: this error originates in the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/substrate/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs b/substrate/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs index be9e4ac2c30..05545821ab0 100644 --- a/substrate/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs +++ b/substrate/frame/support/test/tests/construct_runtime_ui/undefined_validate_unsigned_part.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::{construct_runtime, derive_impl}; +use frame_support::construct_runtime; use sp_core::sr25519; use sp_runtime::{generic, traits::BlakeTwo256}; @@ -36,7 +36,6 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic, Event}, -70 | | Pallet: pallet::{Pallet, ValidateUnsigned}, -71 | | } -72 | | } +65 | / construct_runtime! { +66 | | pub struct Runtime +67 | | { +68 | | System: frame_system::{Pallet, Call, Storage, Config, Event}, +69 | | Pallet: pallet::{Pallet, ValidateUnsigned}, +70 | | } +71 | | } | |_- in this macro invocation | = note: this error originates in the macro `pallet::__substrate_validate_unsigned_check::is_validate_unsigned_part_defined` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no variant or associated item named `Pallet` found for enum `RuntimeCall` in the current scope - --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:70:3 + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:69:3 | -66 | // construct_runtime! { -67 | || pub struct Runtime -68 | || { -69 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, -70 | || Pallet: pallet::{Pallet, ValidateUnsigned}, +65 | // construct_runtime! { +66 | || pub struct Runtime +67 | || { +68 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, +69 | || Pallet: pallet::{Pallet, ValidateUnsigned}, | || -^^^^^^ variant or associated item not found in `RuntimeCall` | ||________| | | ... | error[E0599]: no function or associated item named `pre_dispatch` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:66:1 + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:65:1 | 28 | pub struct Pallet(_); | -------------------- function or associated item `pre_dispatch` not found for this struct ... -66 | construct_runtime! { +65 | construct_runtime! { | __^ | | _| | || -67 | || pub struct Runtime -68 | || { -69 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, -70 | || Pallet: pallet::{Pallet, ValidateUnsigned}, -71 | || } -72 | || } +66 | || pub struct Runtime +67 | || { +68 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, +69 | || Pallet: pallet::{Pallet, ValidateUnsigned}, +70 | || } +71 | || } | ||_- in this macro invocation ... | | @@ -54,21 +54,21 @@ error[E0599]: no function or associated item named `pre_dispatch` found for stru = note: this error originates in the macro `frame_support::construct_runtime` which comes from the expansion of the macro `construct_runtime` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no function or associated item named `validate_unsigned` found for struct `pallet::Pallet` in the current scope - --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:66:1 + --> tests/construct_runtime_ui/undefined_validate_unsigned_part.rs:65:1 | 28 | pub struct Pallet(_); | -------------------- function or associated item `validate_unsigned` not found for this struct ... -66 | construct_runtime! { +65 | construct_runtime! { | __^ | | _| | || -67 | || pub struct Runtime -68 | || { -69 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, -70 | || Pallet: pallet::{Pallet, ValidateUnsigned}, -71 | || } -72 | || } +66 | || pub struct Runtime +67 | || { +68 | || System: frame_system::{Pallet, Call, Storage, Config, Event}, +69 | || Pallet: pallet::{Pallet, ValidateUnsigned}, +70 | || } +71 | || } | ||_- in this macro invocation ... | | diff --git a/substrate/frame/support/test/tests/derive_impl.rs b/substrate/frame/support/test/tests/derive_impl.rs deleted file mode 100644 index 675e85f4bfc..00000000000 --- a/substrate/frame/support/test/tests/derive_impl.rs +++ /dev/null @@ -1,52 +0,0 @@ -// 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 frame_support::derive_impl; - -trait Shape { - fn area(&self) -> u32; -} - -struct SomeRectangle {} - -#[frame_support::register_default_impl(SomeRectangle)] -impl Shape for SomeRectangle { - #[cfg(not(feature = "feature-frame-testing"))] - fn area(&self) -> u32 { - 10 - } - - #[cfg(feature = "feature-frame-testing")] - fn area(&self) -> u32 { - 0 - } -} - -struct SomeSquare {} - -#[derive_impl(SomeRectangle)] -impl Shape for SomeSquare {} - -#[test] -fn test_feature_parsing() { - let square = SomeSquare {}; - #[cfg(not(feature = "feature-frame-testing"))] - assert_eq!(square.area(), 10); - - #[cfg(feature = "feature-frame-testing")] - assert_eq!(square.area(), 0); -} diff --git a/substrate/frame/support/test/tests/derive_impl_ui/inject_runtime_type_fails_when_type_not_in_scope.stderr b/substrate/frame/support/test/tests/derive_impl_ui/inject_runtime_type_fails_when_type_not_in_scope.stderr index 58aae713f75..f3ac6b23281 100644 --- a/substrate/frame/support/test/tests/derive_impl_ui/inject_runtime_type_fails_when_type_not_in_scope.stderr +++ b/substrate/frame/support/test/tests/derive_impl_ui/inject_runtime_type_fails_when_type_not_in_scope.stderr @@ -2,13 +2,9 @@ error[E0412]: cannot find type `RuntimeCall` in this scope --> tests/derive_impl_ui/inject_runtime_type_fails_when_type_not_in_scope.rs:30:10 | 30 | type RuntimeCall = (); - | ^^^^^^^^^^^ + | ^^^^^^^^^^^ help: you might have meant to use the associated type: `Self::RuntimeCall` ... 35 | #[derive_impl(Pallet)] // Injects type RuntimeCall = RuntimeCall; | ---------------------- in this macro invocation | = note: this error originates in the macro `Pallet` which comes from the expansion of the macro `frame_support::macro_magic::forward_tokens_verbatim` (in Nightly builds, run with -Z macro-backtrace for more info) -help: you might have meant to use the associated type - | -30 | type Self::RuntimeCall = (); - | ++++++ diff --git a/substrate/frame/support/test/tests/derive_impl_ui/inject_runtime_type_invalid.stderr b/substrate/frame/support/test/tests/derive_impl_ui/inject_runtime_type_invalid.stderr index cda20288984..501aad0419f 100644 --- a/substrate/frame/support/test/tests/derive_impl_ui/inject_runtime_type_invalid.stderr +++ b/substrate/frame/support/test/tests/derive_impl_ui/inject_runtime_type_invalid.stderr @@ -1,4 +1,4 @@ -error: `#[inject_runtime_type]` can only be attached to `RuntimeCall`, `RuntimeEvent`, `RuntimeTask`, `RuntimeOrigin` or `PalletInfo` +error: `#[inject_runtime_type]` can only be attached to `RuntimeCall`, `RuntimeEvent`, `RuntimeOrigin` or `PalletInfo` --> tests/derive_impl_ui/inject_runtime_type_invalid.rs:32:5 | 32 | type RuntimeInfo = (); diff --git a/substrate/frame/support/test/tests/pallet.rs b/substrate/frame/support/test/tests/pallet.rs index 4acca9eafe5..c8875d3dbe8 100644 --- a/substrate/frame/support/test/tests/pallet.rs +++ b/substrate/frame/support/test/tests/pallet.rs @@ -16,7 +16,7 @@ // limitations under the License. use frame_support::{ - assert_ok, derive_impl, + assert_ok, dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, Parameter, Pays}, dispatch_context::with_context, pallet_prelude::{StorageInfoTrait, ValueQuery}, @@ -257,13 +257,6 @@ pub mod pallet { pub fn check_for_dispatch_context(_origin: OriginFor) -> DispatchResult { with_context::<(), _>(|_| ()).ok_or_else(|| DispatchError::Unavailable) } - - #[cfg(feature = "frame-feature-testing")] - #[pallet::call_index(5)] - #[pallet::weight({1})] - pub fn foo_feature_test(_origin: OriginFor) -> DispatchResult { - Ok(()) - } } #[pallet::error] @@ -276,8 +269,6 @@ pub mod pallet { #[codec(skip)] Skipped(u128), CompactU8(#[codec(compact)] u8), - #[cfg(feature = "frame-feature-testing")] - FeatureTest, } #[pallet::event] @@ -691,7 +682,6 @@ frame_support::parameter_types!( pub const MyGetParam3: u32 = 12; ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; @@ -805,7 +795,6 @@ fn call_expand() { } ); assert_eq!(call_foo.get_call_name(), "foo"); - #[cfg(not(feature = "frame-feature-testing"))] assert_eq!( pallet::Call::::get_call_names(), &[ @@ -816,24 +805,9 @@ fn call_expand() { "check_for_dispatch_context" ], ); - #[cfg(feature = "frame-feature-testing")] - assert_eq!( - pallet::Call::::get_call_names(), - &[ - "foo", - "foo_storage_layer", - "foo_index_out_of_order", - "foo_no_post_info", - "check_for_dispatch_context", - "foo_feature_test" - ], - ); assert_eq!(call_foo.get_call_index(), 0u8); - #[cfg(not(feature = "frame-feature-testing"))] - assert_eq!(pallet::Call::::get_call_indices(), &[0u8, 1u8, 4u8, 2u8, 3u8]); - #[cfg(feature = "frame-feature-testing")] - assert_eq!(pallet::Call::::get_call_indices(), &[0u8, 1u8, 4u8, 2u8, 3u8, 5u8]); + assert_eq!(pallet::Call::::get_call_indices(), &[0u8, 1u8, 4u8, 2u8, 3u8]) } #[test] @@ -841,10 +815,7 @@ fn call_expand_index() { let call_foo = pallet::Call::::foo_index_out_of_order {}; assert_eq!(call_foo.get_call_index(), 4u8); - #[cfg(not(feature = "frame-feature-testing"))] - assert_eq!(pallet::Call::::get_call_indices(), &[0u8, 1u8, 4u8, 2u8, 3u8]); - #[cfg(feature = "frame-feature-testing")] - assert_eq!(pallet::Call::::get_call_indices(), &[0u8, 1u8, 4u8, 2u8, 3u8, 5u8]); + assert_eq!(pallet::Call::::get_call_indices(), &[0u8, 1u8, 4u8, 2u8, 3u8]) } #[test] @@ -866,8 +837,6 @@ fn error_expand() { }), ); assert_eq!( as PalletError>::MAX_ENCODED_SIZE, 3); - #[cfg(feature = "frame-feature-testing")] - assert_eq!(format!("{:?}", pallet::Error::::FeatureTest), String::from("FeatureTest"),); } #[test] @@ -1301,6 +1270,52 @@ fn pallet_hooks_expand() { }) } +#[test] +fn all_pallets_type_reversed_order_is_correct() { + TestExternalities::default().execute_with(|| { + frame_system::Pallet::::set_block_number(1); + + #[allow(deprecated)] + { + assert_eq!( + AllPalletsWithoutSystemReversed::on_initialize(1), + Weight::from_parts(10, 0) + ); + AllPalletsWithoutSystemReversed::on_finalize(1); + + assert_eq!( + AllPalletsWithoutSystemReversed::on_runtime_upgrade(), + Weight::from_parts(30, 0) + ); + } + + assert_eq!( + frame_system::Pallet::::events()[0].event, + RuntimeEvent::Example2(pallet2::Event::Something(11)), + ); + assert_eq!( + frame_system::Pallet::::events()[1].event, + RuntimeEvent::Example(pallet::Event::Something(10)), + ); + assert_eq!( + frame_system::Pallet::::events()[2].event, + RuntimeEvent::Example2(pallet2::Event::Something(21)), + ); + assert_eq!( + frame_system::Pallet::::events()[3].event, + RuntimeEvent::Example(pallet::Event::Something(20)), + ); + assert_eq!( + frame_system::Pallet::::events()[4].event, + RuntimeEvent::Example2(pallet2::Event::Something(31)), + ); + assert_eq!( + frame_system::Pallet::::events()[5].event, + RuntimeEvent::Example(pallet::Event::Something(30)), + ); + }) +} + #[test] fn pallet_on_genesis() { TestExternalities::default().execute_with(|| { @@ -2170,6 +2185,31 @@ fn test_storage_info() { ); } +#[test] +fn assert_type_all_pallets_reversed_with_system_first_is_correct() { + // Just ensure the 2 types are same. + #[allow(deprecated)] + fn _a(_t: AllPalletsReversedWithSystemFirst) {} + #[cfg(all(not(feature = "frame-feature-testing"), not(feature = "frame-feature-testing-2")))] + fn _b(t: (System, Example4, Example2, Example)) { + _a(t) + } + #[cfg(all(feature = "frame-feature-testing", not(feature = "frame-feature-testing-2")))] + fn _b(t: (System, Example4, Example3, Example2, Example)) { + _a(t) + } + + #[cfg(all(not(feature = "frame-feature-testing"), feature = "frame-feature-testing-2"))] + fn _b(t: (System, Example5, Example4, Example2, Example)) { + _a(t) + } + + #[cfg(all(feature = "frame-feature-testing", feature = "frame-feature-testing-2"))] + fn _b(t: (System, Example5, Example4, Example3, Example2, Example)) { + _a(t) + } +} + #[test] fn assert_type_all_pallets_with_system_is_correct() { // Just ensure the 2 types are same. @@ -2214,6 +2254,52 @@ fn assert_type_all_pallets_without_system_is_correct() { } } +#[test] +fn assert_type_all_pallets_with_system_reversed_is_correct() { + // Just ensure the 2 types are same. + #[allow(deprecated)] + fn _a(_t: AllPalletsWithSystemReversed) {} + #[cfg(all(not(feature = "frame-feature-testing"), not(feature = "frame-feature-testing-2")))] + fn _b(t: (Example4, Example2, Example, System)) { + _a(t) + } + #[cfg(all(feature = "frame-feature-testing", not(feature = "frame-feature-testing-2")))] + fn _b(t: (Example4, Example3, Example2, Example, System)) { + _a(t) + } + #[cfg(all(not(feature = "frame-feature-testing"), feature = "frame-feature-testing-2"))] + fn _b(t: (Example5, Example4, Example2, Example, System)) { + _a(t) + } + #[cfg(all(feature = "frame-feature-testing", feature = "frame-feature-testing-2"))] + fn _b(t: (Example5, Example4, Example3, Example2, Example, System)) { + _a(t) + } +} + +#[test] +fn assert_type_all_pallets_without_system_reversed_is_correct() { + // Just ensure the 2 types are same. + #[allow(deprecated)] + fn _a(_t: AllPalletsWithoutSystemReversed) {} + #[cfg(all(not(feature = "frame-feature-testing"), not(feature = "frame-feature-testing-2")))] + fn _b(t: (Example4, Example2, Example)) { + _a(t) + } + #[cfg(all(feature = "frame-feature-testing", not(feature = "frame-feature-testing-2")))] + fn _b(t: (Example4, Example3, Example2, Example)) { + _a(t) + } + #[cfg(all(not(feature = "frame-feature-testing"), feature = "frame-feature-testing-2"))] + fn _b(t: (Example5, Example4, Example2, Example)) { + _a(t) + } + #[cfg(all(feature = "frame-feature-testing", feature = "frame-feature-testing-2"))] + fn _b(t: (Example5, Example4, Example3, Example2, Example)) { + _a(t) + } +} + #[test] fn test_storage_alias() { use frame_support::Twox64Concat; @@ -2409,33 +2495,3 @@ fn test_dispatch_context() { .dispatch(RuntimeOrigin::root())); }); } - -#[test] -fn test_call_feature_parsing() { - let call = pallet::Call::::check_for_dispatch_context {}; - match call { - pallet::Call::::check_for_dispatch_context {} | - pallet::Call::::foo { .. } | - pallet::Call::foo_storage_layer { .. } | - pallet::Call::foo_index_out_of_order {} | - pallet::Call::foo_no_post_info {} => (), - #[cfg(feature = "frame-feature-testing")] - pallet::Call::foo_feature_test {} => (), - pallet::Call::__Ignore(_, _) => (), - } -} - -#[test] -fn test_error_feature_parsing() { - let err = pallet::Error::::InsufficientProposersBalance; - match err { - pallet::Error::InsufficientProposersBalance | - pallet::Error::NonExistentStorageValue | - pallet::Error::Code(_) | - pallet::Error::Skipped(_) | - pallet::Error::CompactU8(_) => (), - #[cfg(feature = "frame-feature-testing")] - pallet::Error::FeatureTest => (), - pallet::Error::__Ignore(_, _) => (), - } -} diff --git a/substrate/frame/support/test/tests/pallet_instance.rs b/substrate/frame/support/test/tests/pallet_instance.rs index 68284fdb491..859d8565078 100644 --- a/substrate/frame/support/test/tests/pallet_instance.rs +++ b/substrate/frame/support/test/tests/pallet_instance.rs @@ -16,7 +16,6 @@ // limitations under the License. use frame_support::{ - derive_impl, dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays}, pallet_prelude::ValueQuery, parameter_types, @@ -293,7 +292,6 @@ pub mod pallet2 { } } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; diff --git a/substrate/frame/support/test/tests/pallet_outer_enums_explicit.rs b/substrate/frame/support/test/tests/pallet_outer_enums_explicit.rs index 6246ad93d67..a8250f8b153 100644 --- a/substrate/frame/support/test/tests/pallet_outer_enums_explicit.rs +++ b/substrate/frame/support/test/tests/pallet_outer_enums_explicit.rs @@ -90,8 +90,6 @@ fn module_error_outer_enum_expand_explicit() { frame_system::Error::NonDefaultComposite => (), frame_system::Error::NonZeroRefCount => (), frame_system::Error::CallFiltered => (), - frame_system::Error::InvalidTask => (), - frame_system::Error::FailedTask => (), frame_system::Error::__Ignore(_, _) => (), }, diff --git a/substrate/frame/support/test/tests/pallet_outer_enums_implicit.rs b/substrate/frame/support/test/tests/pallet_outer_enums_implicit.rs index 26023dfa7b7..191f095f5d7 100644 --- a/substrate/frame/support/test/tests/pallet_outer_enums_implicit.rs +++ b/substrate/frame/support/test/tests/pallet_outer_enums_implicit.rs @@ -90,8 +90,6 @@ fn module_error_outer_enum_expand_implicit() { frame_system::Error::NonDefaultComposite => (), frame_system::Error::NonZeroRefCount => (), frame_system::Error::CallFiltered => (), - frame_system::Error::InvalidTask => (), - frame_system::Error::FailedTask => (), frame_system::Error::__Ignore(_, _) => (), }, diff --git a/substrate/frame/support/test/tests/pallet_ui/call_argument_invalid_bound.stderr b/substrate/frame/support/test/tests/pallet_ui/call_argument_invalid_bound.stderr index 40f8f129830..08ea7c0bec3 100644 --- a/substrate/frame/support/test/tests/pallet_ui/call_argument_invalid_bound.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/call_argument_invalid_bound.stderr @@ -10,7 +10,6 @@ error: use of deprecated constant `pallet::warnings::ConstantWeight_0::_w`: | ^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` error[E0277]: `::Bar` doesn't implement `std::fmt::Debug` --> tests/pallet_ui/call_argument_invalid_bound.rs:38:36 diff --git a/substrate/frame/support/test/tests/pallet_ui/call_argument_invalid_bound_2.stderr b/substrate/frame/support/test/tests/pallet_ui/call_argument_invalid_bound_2.stderr index 5744c636235..80316fcd248 100644 --- a/substrate/frame/support/test/tests/pallet_ui/call_argument_invalid_bound_2.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/call_argument_invalid_bound_2.stderr @@ -10,7 +10,6 @@ error: use of deprecated constant `pallet::warnings::ConstantWeight_0::_w`: | ^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` error[E0277]: `::Bar` doesn't implement `std::fmt::Debug` --> tests/pallet_ui/call_argument_invalid_bound_2.rs:38:36 @@ -46,9 +45,9 @@ error[E0277]: the trait bound `::Bar: WrapperTypeEncode` is = note: required for `::Bar` to implement `Encode` error[E0277]: the trait bound `::Bar: WrapperTypeDecode` is not satisfied - --> tests/pallet_ui/call_argument_invalid_bound_2.rs:38:42 + --> tests/pallet_ui/call_argument_invalid_bound_2.rs:34:12 | -38 | pub fn foo(origin: OriginFor, _bar: T::Bar) -> DispatchResultWithPostInfo { - | ^^^^^^ the trait `WrapperTypeDecode` is not implemented for `::Bar` +34 | #[pallet::call] + | ^^^^ the trait `WrapperTypeDecode` is not implemented for `::Bar` | = note: required for `::Bar` to implement `Decode` diff --git a/substrate/frame/support/test/tests/pallet_ui/call_argument_invalid_bound_3.stderr b/substrate/frame/support/test/tests/pallet_ui/call_argument_invalid_bound_3.stderr index b58e4516bce..d45b74bad84 100644 --- a/substrate/frame/support/test/tests/pallet_ui/call_argument_invalid_bound_3.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/call_argument_invalid_bound_3.stderr @@ -10,7 +10,6 @@ error: use of deprecated constant `pallet::warnings::ConstantWeight_0::_w`: | ^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` error[E0277]: `Bar` doesn't implement `std::fmt::Debug` --> tests/pallet_ui/call_argument_invalid_bound_3.rs:40:36 diff --git a/substrate/frame/support/test/tests/pallet_ui/call_invalid_origin_type.stderr b/substrate/frame/support/test/tests/pallet_ui/call_invalid_origin_type.stderr index 1f814eaa407..c04729a2438 100644 --- a/substrate/frame/support/test/tests/pallet_ui/call_invalid_origin_type.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/call_invalid_origin_type.stderr @@ -1,4 +1,4 @@ -error: Invalid type: expected `OriginFor` or `T::RuntimeOrigin` +error: Invalid type: expected `OriginFor` --> tests/pallet_ui/call_invalid_origin_type.rs:34:22 | 34 | pub fn foo(origin: u8) {} diff --git a/substrate/frame/support/test/tests/pallet_ui/call_missing_index.stderr b/substrate/frame/support/test/tests/pallet_ui/call_missing_index.stderr index ba06285bdee..4d55ef79856 100644 --- a/substrate/frame/support/test/tests/pallet_ui/call_missing_index.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/call_missing_index.stderr @@ -11,7 +11,6 @@ error: use of deprecated constant `pallet::warnings::ImplicitCallIndex_0::_w`: | ^^^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` error: use of deprecated constant `pallet::warnings::ImplicitCallIndex_1::_w`: It is deprecated to use implicit call indices. diff --git a/substrate/frame/support/test/tests/pallet_ui/call_weight_argument_has_suffix.stderr b/substrate/frame/support/test/tests/pallet_ui/call_weight_argument_has_suffix.stderr index 4b5abdcd0e6..cf23a76f8ea 100644 --- a/substrate/frame/support/test/tests/pallet_ui/call_weight_argument_has_suffix.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/call_weight_argument_has_suffix.stderr @@ -18,4 +18,3 @@ error: use of deprecated constant `pallet::warnings::ConstantWeight_0::_w`: | ^^^^^^^^^^^^^^^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` diff --git a/substrate/frame/support/test/tests/pallet_ui/call_weight_const_warning.stderr b/substrate/frame/support/test/tests/pallet_ui/call_weight_const_warning.stderr index d399df4d85b..ccd5a935773 100644 --- a/substrate/frame/support/test/tests/pallet_ui/call_weight_const_warning.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/call_weight_const_warning.stderr @@ -10,4 +10,3 @@ error: use of deprecated constant `pallet::warnings::ConstantWeight_0::_w`: | ^^^^^^^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` diff --git a/substrate/frame/support/test/tests/pallet_ui/call_weight_const_warning_twice.stderr b/substrate/frame/support/test/tests/pallet_ui/call_weight_const_warning_twice.stderr index d7e4951e49f..aadb939b645 100644 --- a/substrate/frame/support/test/tests/pallet_ui/call_weight_const_warning_twice.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/call_weight_const_warning_twice.stderr @@ -18,7 +18,6 @@ error: use of deprecated constant `pallet::warnings::ConstantWeight_0::_w`: | ^^^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` error: use of deprecated constant `pallet::warnings::ConstantWeight_1::_w`: It is deprecated to use hard-coded constant as call weight. diff --git a/substrate/frame/support/test/tests/pallet_ui/call_weight_inherited_invalid3.stderr b/substrate/frame/support/test/tests/pallet_ui/call_weight_inherited_invalid3.stderr index 339551d9811..e8e6f2fe6df 100644 --- a/substrate/frame/support/test/tests/pallet_ui/call_weight_inherited_invalid3.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/call_weight_inherited_invalid3.stderr @@ -17,4 +17,3 @@ error: unused import: `frame_system::pallet_prelude::*` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `-D unused-imports` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(unused_imports)]` diff --git a/substrate/frame/support/test/tests/pallet_ui/call_weight_unchecked_warning.stderr b/substrate/frame/support/test/tests/pallet_ui/call_weight_unchecked_warning.stderr index 33302a2a027..89fc1e0820f 100644 --- a/substrate/frame/support/test/tests/pallet_ui/call_weight_unchecked_warning.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/call_weight_unchecked_warning.stderr @@ -10,4 +10,3 @@ error: use of deprecated constant `pallet::warnings::UncheckedWeightWitness_0::_ | ^^^^^^^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` diff --git a/substrate/frame/support/test/tests/pallet_ui/composite_enum_unsupported_identifier.stderr b/substrate/frame/support/test/tests/pallet_ui/composite_enum_unsupported_identifier.stderr index 8de9c8990b0..cdc8f623142 100644 --- a/substrate/frame/support/test/tests/pallet_ui/composite_enum_unsupported_identifier.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/composite_enum_unsupported_identifier.stderr @@ -1,4 +1,4 @@ -error: expected one of: `FreezeReason`, `HoldReason`, `LockId`, `SlashReason`, `Task` +error: expected one of: `FreezeReason`, `HoldReason`, `LockId`, `SlashReason` --> tests/pallet_ui/composite_enum_unsupported_identifier.rs:27:11 | 27 | pub enum HoldReasons {} diff --git a/substrate/frame/support/test/tests/pallet_ui/deprecated_store_attr.stderr b/substrate/frame/support/test/tests/pallet_ui/deprecated_store_attr.stderr index e227033d364..942db0ab469 100644 --- a/substrate/frame/support/test/tests/pallet_ui/deprecated_store_attr.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/deprecated_store_attr.stderr @@ -7,4 +7,3 @@ error: use of deprecated struct `pallet::_::Store`: | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` diff --git a/substrate/frame/support/test/tests/pallet_ui/dev_mode_without_arg_call_index.stderr b/substrate/frame/support/test/tests/pallet_ui/dev_mode_without_arg_call_index.stderr index 01254584c62..bcfe43d008f 100644 --- a/substrate/frame/support/test/tests/pallet_ui/dev_mode_without_arg_call_index.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/dev_mode_without_arg_call_index.stderr @@ -11,7 +11,6 @@ error: use of deprecated constant `pallet::warnings::ImplicitCallIndex_0::_w`: | ^^^^^^^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` error: use of deprecated constant `pallet::warnings::ConstantWeight_0::_w`: It is deprecated to use hard-coded constant as call weight. diff --git a/substrate/frame/support/test/tests/pallet_ui/dev_mode_without_arg_max_encoded_len.stderr b/substrate/frame/support/test/tests/pallet_ui/dev_mode_without_arg_max_encoded_len.stderr index 02ead305dd8..531e8bdffeb 100644 --- a/substrate/frame/support/test/tests/pallet_ui/dev_mode_without_arg_max_encoded_len.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/dev_mode_without_arg_max_encoded_len.stderr @@ -11,7 +11,6 @@ error: use of deprecated constant `pallet::warnings::ImplicitCallIndex_0::_w`: | ^^^^^^^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` error: use of deprecated constant `pallet::warnings::ConstantWeight_0::_w`: It is deprecated to use hard-coded constant as call weight. @@ -27,15 +26,8 @@ error: use of deprecated constant `pallet::warnings::ConstantWeight_0::_w`: error[E0277]: the trait bound `Vec: MaxEncodedLen` is not satisfied --> tests/pallet_ui/dev_mode_without_arg_max_encoded_len.rs:28:12 | -28 | #[pallet::pallet] - | _______________^ -29 | | pub struct Pallet(_); -30 | | -31 | | // Your Pallet's configuration trait, representing custom external types and interfaces. -... | -35 | | #[pallet::storage] -36 | | type MyStorage = StorageValue<_, Vec>; - | |__________________^ the trait `MaxEncodedLen` is not implemented for `Vec` +28 | #[pallet::pallet] + | ^^^^^^ the trait `MaxEncodedLen` is not implemented for `Vec` | = help: the following other types implement trait `MaxEncodedLen`: bool diff --git a/substrate/frame/support/test/tests/pallet_ui/error_does_not_derive_pallet_error.stderr b/substrate/frame/support/test/tests/pallet_ui/error_does_not_derive_pallet_error.stderr index 9cefd2f4899..ea1d0ed99cd 100644 --- a/substrate/frame/support/test/tests/pallet_ui/error_does_not_derive_pallet_error.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/error_does_not_derive_pallet_error.stderr @@ -1,8 +1,8 @@ error[E0277]: the trait bound `MyError: PalletError` is not satisfied - --> tests/pallet_ui/error_does_not_derive_pallet_error.rs:28:15 + --> tests/pallet_ui/error_does_not_derive_pallet_error.rs:18:1 | -28 | CustomError(crate::MyError), - | ^^^^^^^^^^^^^^ the trait `PalletError` is not implemented for `MyError` +18 | #[frame_support::pallet] + | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `PalletError` is not implemented for `MyError` | = help: the following other types implement trait `PalletError`: bool @@ -14,3 +14,4 @@ error[E0277]: the trait bound `MyError: PalletError` is not satisfied u8 u16 and $N others + = note: this error originates in the derive macro `frame_support::PalletError` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/substrate/frame/support/test/tests/pallet_ui/pass/dev_mode_valid.rs b/substrate/frame/support/test/tests/pallet_ui/pass/dev_mode_valid.rs index 4dc33991b12..bf26cfd95b1 100644 --- a/substrate/frame/support/test/tests/pallet_ui/pass/dev_mode_valid.rs +++ b/substrate/frame/support/test/tests/pallet_ui/pass/dev_mode_valid.rs @@ -17,7 +17,7 @@ #![cfg_attr(not(feature = "std"), no_std)] -use frame_support::{derive_impl, traits::ConstU32}; +use frame_support::traits::ConstU32; pub use pallet::*; @@ -70,7 +70,6 @@ pub mod pallet { impl Pallet {} } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type RuntimeOrigin = RuntimeOrigin; diff --git a/substrate/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs b/substrate/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs index de856ddcd3e..9ab486c718c 100644 --- a/substrate/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs +++ b/substrate/frame/support/test/tests/pallet_ui/pass/no_std_genesis_config.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::{construct_runtime, derive_impl}; +use frame_support::construct_runtime; use sp_core::sr25519; use sp_runtime::{generic, traits::BlakeTwo256}; @@ -27,7 +27,6 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic(core::marker::PhantomData); - - #[pallet::tasks_experimental] - impl Pallet { - #[pallet::task_index(0)] - #[pallet::task_condition(|i, j| i == 0u32 && j == 2u64)] - #[pallet::task_list(vec![(0u32, 2u64), (2u32, 4u64)].iter())] - #[pallet::task_weight(0.into())] - fn foo(i: u32, j: u64) -> DispatchResult { - ensure!(i == 0, "i must be 0"); - ensure!(j == 2, "j must be 2"); - Ok(()) - } - } -} - -fn main() { -} diff --git a/substrate/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.stderr b/substrate/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.stderr index 4229d1e8a54..b5d10827524 100644 --- a/substrate/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.stderr @@ -1,15 +1,8 @@ error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:27:12 | -27 | #[pallet::without_storage_info] - | _______________^ -28 | | pub struct Pallet(core::marker::PhantomData); -29 | | -30 | | #[pallet::hooks] -... | -38 | | #[pallet::storage] -39 | | type Foo = StorageValue; - | |____________^ the trait `WrapperTypeDecode` is not implemented for `Bar` +27 | #[pallet::without_storage_info] + | ^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `Bar` | = help: the following other types implement trait `WrapperTypeDecode`: Box @@ -23,15 +16,8 @@ error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:27:12 | -27 | #[pallet::without_storage_info] - | _______________^ -28 | | pub struct Pallet(core::marker::PhantomData); -29 | | -30 | | #[pallet::hooks] -... | -38 | | #[pallet::storage] -39 | | type Foo = StorageValue; - | |____________^ the trait `EncodeLike` is not implemented for `Bar` +27 | #[pallet::without_storage_info] + | ^^^^^^^^^^^^^^^^^^^^ the trait `EncodeLike` is not implemented for `Bar` | = help: the following other types implement trait `EncodeLike`: @@ -50,15 +36,8 @@ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:27:12 | -27 | #[pallet::without_storage_info] - | _______________^ -28 | | pub struct Pallet(core::marker::PhantomData); -29 | | -30 | | #[pallet::hooks] -... | -38 | | #[pallet::storage] -39 | | type Foo = StorageValue; - | |____________^ the trait `WrapperTypeEncode` is not implemented for `Bar` +27 | #[pallet::without_storage_info] + | ^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `Bar` | = help: the following other types implement trait `WrapperTypeEncode`: Box @@ -78,10 +57,8 @@ error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied error[E0277]: the trait bound `Bar: TypeInfo` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:38:12 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue; - | |____________^ the trait `TypeInfo` is not implemented for `Bar` +38 | #[pallet::storage] + | ^^^^^^^ the trait `TypeInfo` is not implemented for `Bar` | = help: the following other types implement trait `TypeInfo`: bool @@ -99,10 +76,8 @@ error[E0277]: the trait bound `Bar: TypeInfo` is not satisfied error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:38:12 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue; - | |____________^ the trait `WrapperTypeDecode` is not implemented for `Bar` +38 | #[pallet::storage] + | ^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `Bar` | = help: the following other types implement trait `WrapperTypeDecode`: Box @@ -116,10 +91,8 @@ error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:38:12 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue; - | |____________^ the trait `EncodeLike` is not implemented for `Bar` +38 | #[pallet::storage] + | ^^^^^^^ the trait `EncodeLike` is not implemented for `Bar` | = help: the following other types implement trait `EncodeLike`: @@ -138,10 +111,8 @@ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:38:12 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue; - | |____________^ the trait `WrapperTypeEncode` is not implemented for `Bar` +38 | #[pallet::storage] + | ^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `Bar` | = help: the following other types implement trait `WrapperTypeEncode`: Box @@ -159,12 +130,10 @@ error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied = note: required for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` to implement `StorageEntryMetadataBuilder` error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:38:12 + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:18:1 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue; - | |____________^ the trait `WrapperTypeDecode` is not implemented for `Bar` +18 | #[frame_support::pallet] + | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `Bar` | = help: the following other types implement trait `WrapperTypeDecode`: Box @@ -174,14 +143,13 @@ error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied = note: required for `Bar` to implement `Decode` = note: required for `Bar` to implement `FullCodec` = note: required for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` to implement `TryDecodeEntireStorage` + = note: this error originates in the attribute macro `frame_support::pallet` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:38:12 + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:18:1 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue; - | |____________^ the trait `EncodeLike` is not implemented for `Bar` +18 | #[frame_support::pallet] + | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `EncodeLike` is not implemented for `Bar` | = help: the following other types implement trait `EncodeLike`: @@ -196,14 +164,13 @@ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied = note: required for `Bar` to implement `FullEncode` = note: required for `Bar` to implement `FullCodec` = note: required for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` to implement `TryDecodeEntireStorage` + = note: this error originates in the attribute macro `frame_support::pallet` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:38:12 + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen.rs:18:1 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue; - | |____________^ the trait `WrapperTypeEncode` is not implemented for `Bar` +18 | #[frame_support::pallet] + | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `Bar` | = help: the following other types implement trait `WrapperTypeEncode`: Box @@ -219,3 +186,4 @@ error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied = note: required for `Bar` to implement `FullEncode` = note: required for `Bar` to implement `FullCodec` = note: required for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` to implement `TryDecodeEntireStorage` + = note: this error originates in the attribute macro `frame_support::pallet` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/substrate/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr b/substrate/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr index 855d289d0a1..b58902590b8 100644 --- a/substrate/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.stderr @@ -1,15 +1,8 @@ error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:27:12 | -27 | #[pallet::without_storage_info] - | _______________^ -28 | | pub struct Pallet(core::marker::PhantomData); -29 | | -30 | | #[pallet::hooks] -... | -38 | | #[pallet::storage] -39 | | type Foo = StorageValue<_, Bar>; - | |____________^ the trait `WrapperTypeDecode` is not implemented for `Bar` +27 | #[pallet::without_storage_info] + | ^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `Bar` | = help: the following other types implement trait `WrapperTypeDecode`: Box @@ -23,15 +16,8 @@ error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:27:12 | -27 | #[pallet::without_storage_info] - | _______________^ -28 | | pub struct Pallet(core::marker::PhantomData); -29 | | -30 | | #[pallet::hooks] -... | -38 | | #[pallet::storage] -39 | | type Foo = StorageValue<_, Bar>; - | |____________^ the trait `EncodeLike` is not implemented for `Bar` +27 | #[pallet::without_storage_info] + | ^^^^^^^^^^^^^^^^^^^^ the trait `EncodeLike` is not implemented for `Bar` | = help: the following other types implement trait `EncodeLike`: @@ -50,15 +36,8 @@ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:27:12 | -27 | #[pallet::without_storage_info] - | _______________^ -28 | | pub struct Pallet(core::marker::PhantomData); -29 | | -30 | | #[pallet::hooks] -... | -38 | | #[pallet::storage] -39 | | type Foo = StorageValue<_, Bar>; - | |____________^ the trait `WrapperTypeEncode` is not implemented for `Bar` +27 | #[pallet::without_storage_info] + | ^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `Bar` | = help: the following other types implement trait `WrapperTypeEncode`: Box @@ -78,10 +57,8 @@ error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied error[E0277]: the trait bound `Bar: TypeInfo` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:38:12 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue<_, Bar>; - | |____________^ the trait `TypeInfo` is not implemented for `Bar` +38 | #[pallet::storage] + | ^^^^^^^ the trait `TypeInfo` is not implemented for `Bar` | = help: the following other types implement trait `TypeInfo`: bool @@ -99,10 +76,8 @@ error[E0277]: the trait bound `Bar: TypeInfo` is not satisfied error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:38:12 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue<_, Bar>; - | |____________^ the trait `WrapperTypeDecode` is not implemented for `Bar` +38 | #[pallet::storage] + | ^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `Bar` | = help: the following other types implement trait `WrapperTypeDecode`: Box @@ -116,10 +91,8 @@ error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:38:12 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue<_, Bar>; - | |____________^ the trait `EncodeLike` is not implemented for `Bar` +38 | #[pallet::storage] + | ^^^^^^^ the trait `EncodeLike` is not implemented for `Bar` | = help: the following other types implement trait `EncodeLike`: @@ -138,10 +111,8 @@ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:38:12 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue<_, Bar>; - | |____________^ the trait `WrapperTypeEncode` is not implemented for `Bar` +38 | #[pallet::storage] + | ^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `Bar` | = help: the following other types implement trait `WrapperTypeEncode`: Box @@ -159,12 +130,10 @@ error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied = note: required for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` to implement `StorageEntryMetadataBuilder` error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:38:12 + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:18:1 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue<_, Bar>; - | |____________^ the trait `WrapperTypeDecode` is not implemented for `Bar` +18 | #[frame_support::pallet] + | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeDecode` is not implemented for `Bar` | = help: the following other types implement trait `WrapperTypeDecode`: Box @@ -174,14 +143,13 @@ error[E0277]: the trait bound `Bar: WrapperTypeDecode` is not satisfied = note: required for `Bar` to implement `Decode` = note: required for `Bar` to implement `FullCodec` = note: required for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` to implement `TryDecodeEntireStorage` + = note: this error originates in the attribute macro `frame_support::pallet` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:38:12 + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:18:1 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue<_, Bar>; - | |____________^ the trait `EncodeLike` is not implemented for `Bar` +18 | #[frame_support::pallet] + | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `EncodeLike` is not implemented for `Bar` | = help: the following other types implement trait `EncodeLike`: @@ -196,14 +164,13 @@ error[E0277]: the trait bound `Bar: EncodeLike` is not satisfied = note: required for `Bar` to implement `FullEncode` = note: required for `Bar` to implement `FullCodec` = note: required for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` to implement `TryDecodeEntireStorage` + = note: this error originates in the attribute macro `frame_support::pallet` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied - --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:38:12 + --> tests/pallet_ui/storage_ensure_span_are_ok_on_wrong_gen_unnamed.rs:18:1 | -38 | #[pallet::storage] - | _______________^ -39 | | type Foo = StorageValue<_, Bar>; - | |____________^ the trait `WrapperTypeEncode` is not implemented for `Bar` +18 | #[frame_support::pallet] + | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `WrapperTypeEncode` is not implemented for `Bar` | = help: the following other types implement trait `WrapperTypeEncode`: Box @@ -219,3 +186,4 @@ error[E0277]: the trait bound `Bar: WrapperTypeEncode` is not satisfied = note: required for `Bar` to implement `FullEncode` = note: required for `Bar` to implement `FullCodec` = note: required for `frame_support::pallet_prelude::StorageValue<_GeneratedPrefixForStorageFoo, Bar>` to implement `TryDecodeEntireStorage` + = note: this error originates in the attribute macro `frame_support::pallet` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/substrate/frame/support/test/tests/pallet_ui/storage_info_unsatisfied.stderr b/substrate/frame/support/test/tests/pallet_ui/storage_info_unsatisfied.stderr index 504db21feeb..e04de98800e 100644 --- a/substrate/frame/support/test/tests/pallet_ui/storage_info_unsatisfied.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/storage_info_unsatisfied.stderr @@ -1,15 +1,8 @@ error[E0277]: the trait bound `Bar: MaxEncodedLen` is not satisfied --> tests/pallet_ui/storage_info_unsatisfied.rs:26:12 | -26 | #[pallet::pallet] - | _______________^ -27 | | pub struct Pallet(core::marker::PhantomData); -28 | | -29 | | #[pallet::hooks] -... | -38 | | #[pallet::storage] -39 | | type Foo = StorageValue<_, Bar>; - | |____________^ the trait `MaxEncodedLen` is not implemented for `Bar` +26 | #[pallet::pallet] + | ^^^^^^ the trait `MaxEncodedLen` is not implemented for `Bar` | = help: the following other types implement trait `MaxEncodedLen`: bool diff --git a/substrate/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr b/substrate/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr index 6fd0b1959c8..31fe3b57338 100644 --- a/substrate/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/storage_info_unsatisfied_nmap.stderr @@ -1,15 +1,8 @@ error[E0277]: the trait bound `Bar: MaxEncodedLen` is not satisfied --> tests/pallet_ui/storage_info_unsatisfied_nmap.rs:29:12 | -29 | #[pallet::pallet] - | _______________^ -30 | | pub struct Pallet(core::marker::PhantomData); -31 | | -32 | | #[pallet::hooks] -... | -41 | | #[pallet::storage] -42 | | type Foo = StorageNMap<_, Key, u32>; - | |____________^ the trait `MaxEncodedLen` is not implemented for `Bar` +29 | #[pallet::pallet] + | ^^^^^^ the trait `MaxEncodedLen` is not implemented for `Bar` | = help: the following other types implement trait `MaxEncodedLen`: bool diff --git a/substrate/frame/support/test/tests/pallet_ui/store_trait_leak_private.stderr b/substrate/frame/support/test/tests/pallet_ui/store_trait_leak_private.stderr index ccb55122e81..20144d825e8 100644 --- a/substrate/frame/support/test/tests/pallet_ui/store_trait_leak_private.stderr +++ b/substrate/frame/support/test/tests/pallet_ui/store_trait_leak_private.stderr @@ -7,7 +7,6 @@ error: use of deprecated struct `pallet::_::Store`: | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `-D deprecated` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(deprecated)]` error[E0446]: private type `_GeneratedPrefixForStorageFoo` in public interface --> tests/pallet_ui/store_trait_leak_private.rs:28:37 diff --git a/substrate/frame/support/test/tests/pallet_ui/task_can_only_be_attached_to_impl.stderr b/substrate/frame/support/test/tests/pallet_ui/task_can_only_be_attached_to_impl.stderr deleted file mode 100644 index eaa8e718840..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_can_only_be_attached_to_impl.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: expected `impl` - --> tests/pallet_ui/task_can_only_be_attached_to_impl.rs:30:5 - | -30 | pub struct Task; - | ^^^ diff --git a/substrate/frame/support/test/tests/pallet_ui/task_condition_invalid_arg.rs b/substrate/frame/support/test/tests/pallet_ui/task_condition_invalid_arg.rs deleted file mode 100644 index 1db96869155..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_condition_invalid_arg.rs +++ /dev/null @@ -1,42 +0,0 @@ -// 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. - -#[frame_support::pallet(dev_mode)] -mod pallet { - use frame_support::pallet_prelude::DispatchResult; - use frame_system::pallet_prelude::OriginFor; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(core::marker::PhantomData); - - #[pallet::tasks_experimental] - impl Pallet { - #[pallet::task_index(0)] - #[pallet::task_condition(|flag: bool| flag)] - #[pallet::task_list(vec![1, 2].iter())] - #[pallet::task_weight(0.into())] - fn foo(_i: u32) -> DispatchResult { - Ok(()) - } - } -} - -fn main() { -} diff --git a/substrate/frame/support/test/tests/pallet_ui/task_condition_invalid_arg.stderr b/substrate/frame/support/test/tests/pallet_ui/task_condition_invalid_arg.stderr deleted file mode 100644 index 9c7bad8119f..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_condition_invalid_arg.stderr +++ /dev/null @@ -1,23 +0,0 @@ -error: unused import: `frame_system::pallet_prelude::OriginFor` - --> tests/pallet_ui/task_condition_invalid_arg.rs:21:6 - | -21 | use frame_system::pallet_prelude::OriginFor; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: `-D unused-imports` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(unused_imports)]` - -error[E0308]: mismatched types - --> tests/pallet_ui/task_condition_invalid_arg.rs:35:10 - | -32 | #[pallet::task_condition(|flag: bool| flag)] - | ----------------- arguments to this function are incorrect -... -35 | fn foo(_i: u32) -> DispatchResult { - | ^^ expected `bool`, found `u32` - | -note: closure parameter defined here - --> tests/pallet_ui/task_condition_invalid_arg.rs:32:29 - | -32 | #[pallet::task_condition(|flag: bool| flag)] - | ^^^^^^^^^^ diff --git a/substrate/frame/support/test/tests/pallet_ui/task_invalid_condition.rs b/substrate/frame/support/test/tests/pallet_ui/task_invalid_condition.rs deleted file mode 100644 index 6875bc13b8f..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_invalid_condition.rs +++ /dev/null @@ -1,42 +0,0 @@ -// 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. - -#[frame_support::pallet(dev_mode)] -mod pallet { - use frame_support::pallet_prelude::DispatchResult; - use frame_system::pallet_prelude::OriginFor; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(core::marker::PhantomData); - - #[pallet::tasks_experimental] - impl Pallet { - #[pallet::task_index(0)] - #[pallet::task_condition(0)] - #[pallet::task_list(vec![1, 2].iter())] - #[pallet::task_weight(0.into())] - fn foo() -> DispatchResult { - Ok(()) - } - } -} - -fn main() { -} diff --git a/substrate/frame/support/test/tests/pallet_ui/task_invalid_condition.stderr b/substrate/frame/support/test/tests/pallet_ui/task_invalid_condition.stderr deleted file mode 100644 index 05c0ba5eecf..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_invalid_condition.stderr +++ /dev/null @@ -1,28 +0,0 @@ -error: unused import: `frame_system::pallet_prelude::OriginFor` - --> tests/pallet_ui/task_invalid_condition.rs:21:6 - | -21 | use frame_system::pallet_prelude::OriginFor; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: `-D unused-imports` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(unused_imports)]` - -error[E0308]: mismatched types - --> tests/pallet_ui/task_invalid_condition.rs:18:1 - | -18 | #[frame_support::pallet(dev_mode)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | expected integer, found `()` - | expected due to this - | - = note: this error originates in the attribute macro `frame_support::pallet` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0618]: expected function, found `{integer}` - --> tests/pallet_ui/task_invalid_condition.rs:32:28 - | -18 | #[frame_support::pallet(dev_mode)] - | ---------------------------------- call expression requires function -... -32 | #[pallet::task_condition(0)] - | ^ diff --git a/substrate/frame/support/test/tests/pallet_ui/task_invalid_index.rs b/substrate/frame/support/test/tests/pallet_ui/task_invalid_index.rs deleted file mode 100644 index 2a4b40523a6..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_invalid_index.rs +++ /dev/null @@ -1,39 +0,0 @@ -// 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. - -#[frame_support::pallet(dev_mode)] -mod pallet { - use frame_support::pallet_prelude::DispatchResult; - use frame_system::pallet_prelude::OriginFor; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(core::marker::PhantomData); - - #[pallet::tasks_experimental] - impl Pallet { - #[pallet::task_index("0")] - fn foo() -> DispatchResult { - Ok(()) - } - } -} - -fn main() { -} diff --git a/substrate/frame/support/test/tests/pallet_ui/task_invalid_index.stderr b/substrate/frame/support/test/tests/pallet_ui/task_invalid_index.stderr deleted file mode 100644 index d33600455bf..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_invalid_index.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: expected integer literal - --> tests/pallet_ui/task_invalid_index.rs:31:24 - | -31 | #[pallet::task_index("0")] - | ^^^ diff --git a/substrate/frame/support/test/tests/pallet_ui/task_invalid_list.rs b/substrate/frame/support/test/tests/pallet_ui/task_invalid_list.rs deleted file mode 100644 index bb6438aaf10..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_invalid_list.rs +++ /dev/null @@ -1,42 +0,0 @@ -// 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. - -#[frame_support::pallet(dev_mode)] -mod pallet { - use frame_support::pallet_prelude::DispatchResult; - use frame_system::pallet_prelude::OriginFor; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(core::marker::PhantomData); - - #[pallet::tasks_experimental] - impl Pallet { - #[pallet::task_index(0)] - #[pallet::task_condition(|| true)] - #[pallet::task_list(0)] - #[pallet::task_weight(0.into())] - fn foo() -> DispatchResult { - Ok(()) - } - } -} - -fn main() { -} diff --git a/substrate/frame/support/test/tests/pallet_ui/task_invalid_list.stderr b/substrate/frame/support/test/tests/pallet_ui/task_invalid_list.stderr deleted file mode 100644 index 536d02610cb..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_invalid_list.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error: unused import: `frame_system::pallet_prelude::OriginFor` - --> tests/pallet_ui/task_invalid_list.rs:21:6 - | -21 | use frame_system::pallet_prelude::OriginFor; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: `-D unused-imports` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(unused_imports)]` - -error[E0689]: can't call method `map` on ambiguous numeric type `{integer}` - --> tests/pallet_ui/task_invalid_list.rs:18:1 - | -18 | #[frame_support::pallet(dev_mode)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the attribute macro `frame_support::pallet` (in Nightly builds, run with -Z macro-backtrace for more info) -help: you must specify a concrete type for this numeric value, like `i32` - | -33 | #[pallet::task_list(0_i32)] - | ~~~~~ diff --git a/substrate/frame/support/test/tests/pallet_ui/task_invalid_weight.rs b/substrate/frame/support/test/tests/pallet_ui/task_invalid_weight.rs deleted file mode 100644 index a0c4040347a..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_invalid_weight.rs +++ /dev/null @@ -1,42 +0,0 @@ -// 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. - -#[frame_support::pallet(dev_mode)] -mod pallet { - use frame_support::pallet_prelude::DispatchResult; - use frame_system::pallet_prelude::OriginFor; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(core::marker::PhantomData); - - #[pallet::tasks_experimental] - impl Pallet { - #[pallet::task_index(0)] - #[pallet::task_condition(|| true)] - #[pallet::task_list(vec![1, 2].iter())] - #[pallet::task_weight("0")] - fn foo() -> DispatchResult { - Ok(()) - } - } -} - -fn main() { -} diff --git a/substrate/frame/support/test/tests/pallet_ui/task_invalid_weight.stderr b/substrate/frame/support/test/tests/pallet_ui/task_invalid_weight.stderr deleted file mode 100644 index 24e925a0699..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_invalid_weight.stderr +++ /dev/null @@ -1,28 +0,0 @@ -error: unused import: `frame_system::pallet_prelude::OriginFor` - --> tests/pallet_ui/task_invalid_weight.rs:21:6 - | -21 | use frame_system::pallet_prelude::OriginFor; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: `-D unused-imports` implied by `-D warnings` - = help: to override `-D warnings` add `#[allow(unused_imports)]` - -error[E0308]: mismatched types - --> tests/pallet_ui/task_invalid_weight.rs:18:1 - | -18 | #[frame_support::pallet(dev_mode)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | expected integer, found `()` - | expected due to this - | - = note: this error originates in the attribute macro `frame_support::pallet` (in Nightly builds, run with -Z macro-backtrace for more info) - -error[E0308]: mismatched types - --> tests/pallet_ui/task_invalid_weight.rs:34:25 - | -18 | #[frame_support::pallet(dev_mode)] - | ---------------------------------- expected `Weight` because of return type -... -34 | #[pallet::task_weight("0")] - | ^^^ expected `Weight`, found `&str` diff --git a/substrate/frame/support/test/tests/pallet_ui/task_missing_condition.rs b/substrate/frame/support/test/tests/pallet_ui/task_missing_condition.rs deleted file mode 100644 index 6ca6e37a5bd..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_missing_condition.rs +++ /dev/null @@ -1,39 +0,0 @@ -// 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. - -#[frame_support::pallet(dev_mode)] -mod pallet { - use frame_support::pallet_prelude::DispatchResult; - use frame_system::pallet_prelude::OriginFor; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(core::marker::PhantomData); - - #[pallet::tasks_experimental] - impl Pallet { - #[pallet::task_index(0)] - fn foo() -> DispatchResult { - Ok(()) - } - } -} - -fn main() { -} diff --git a/substrate/frame/support/test/tests/pallet_ui/task_missing_condition.stderr b/substrate/frame/support/test/tests/pallet_ui/task_missing_condition.stderr deleted file mode 100644 index c709ec7eac9..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_missing_condition.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: missing `#[pallet::task_condition(..)]` attribute - --> tests/pallet_ui/task_missing_condition.rs:32:6 - | -32 | fn foo() -> DispatchResult { - | ^^^ diff --git a/substrate/frame/support/test/tests/pallet_ui/task_missing_index.rs b/substrate/frame/support/test/tests/pallet_ui/task_missing_index.rs deleted file mode 100644 index ed98d229f18..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_missing_index.rs +++ /dev/null @@ -1,38 +0,0 @@ -// 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. - -#[frame_support::pallet(dev_mode)] -mod pallet { - use frame_support::pallet_prelude::DispatchResult; - use frame_system::pallet_prelude::OriginFor; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(core::marker::PhantomData); - - #[pallet::tasks_experimental] - impl Pallet { - fn foo() -> DispatchResult { - Ok(()) - } - } -} - -fn main() { -} diff --git a/substrate/frame/support/test/tests/pallet_ui/task_missing_index.stderr b/substrate/frame/support/test/tests/pallet_ui/task_missing_index.stderr deleted file mode 100644 index ba3c9d132b8..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_missing_index.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: missing `#[pallet::task_index(..)]` attribute - --> tests/pallet_ui/task_missing_index.rs:31:6 - | -31 | fn foo() -> DispatchResult { - | ^^^ diff --git a/substrate/frame/support/test/tests/pallet_ui/task_missing_list.rs b/substrate/frame/support/test/tests/pallet_ui/task_missing_list.rs deleted file mode 100644 index 427efe12763..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_missing_list.rs +++ /dev/null @@ -1,40 +0,0 @@ -// 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. - -#[frame_support::pallet(dev_mode)] -mod pallet { - use frame_support::pallet_prelude::DispatchResult; - use frame_system::pallet_prelude::OriginFor; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(core::marker::PhantomData); - - #[pallet::tasks_experimental] - impl Pallet { - #[pallet::task_index(0)] - #[pallet::task_condition(|| true)] - fn foo() -> DispatchResult { - Ok(()) - } - } -} - -fn main() { -} diff --git a/substrate/frame/support/test/tests/pallet_ui/task_missing_list.stderr b/substrate/frame/support/test/tests/pallet_ui/task_missing_list.stderr deleted file mode 100644 index f4ae26a75ad..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_missing_list.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: missing `#[pallet::task_list(..)]` attribute - --> tests/pallet_ui/task_missing_list.rs:33:6 - | -33 | fn foo() -> DispatchResult { - | ^^^ diff --git a/substrate/frame/support/test/tests/pallet_ui/task_missing_weight.rs b/substrate/frame/support/test/tests/pallet_ui/task_missing_weight.rs deleted file mode 100644 index 704be1f1e0b..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_missing_weight.rs +++ /dev/null @@ -1,41 +0,0 @@ -// 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. - -#[frame_support::pallet(dev_mode)] -mod pallet { - use frame_support::pallet_prelude::DispatchResult; - use frame_system::pallet_prelude::OriginFor; - - #[pallet::config] - pub trait Config: frame_system::Config {} - - #[pallet::pallet] - pub struct Pallet(core::marker::PhantomData); - - #[pallet::tasks_experimental] - impl Pallet { - #[pallet::task_index(0)] - #[pallet::task_condition(|| true)] - #[pallet::task_list(vec![1, 2].iter())] - fn foo() -> DispatchResult { - Ok(()) - } - } -} - -fn main() { -} diff --git a/substrate/frame/support/test/tests/pallet_ui/task_missing_weight.stderr b/substrate/frame/support/test/tests/pallet_ui/task_missing_weight.stderr deleted file mode 100644 index de7b2eb1720..00000000000 --- a/substrate/frame/support/test/tests/pallet_ui/task_missing_weight.stderr +++ /dev/null @@ -1,5 +0,0 @@ -error: missing `#[pallet::task_weight(..)]` attribute - --> tests/pallet_ui/task_missing_weight.rs:34:6 - | -34 | fn foo() -> DispatchResult { - | ^^^ diff --git a/substrate/frame/support/test/tests/runtime_metadata.rs b/substrate/frame/support/test/tests/runtime_metadata.rs index bb7f7d2822e..a545735f2b1 100644 --- a/substrate/frame/support/test/tests/runtime_metadata.rs +++ b/substrate/frame/support/test/tests/runtime_metadata.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::{derive_impl, traits::ConstU32}; +use frame_support::traits::ConstU32; use scale_info::{form::MetaForm, meta_type}; use sp_metadata_ir::{ RuntimeApiMetadataIR, RuntimeApiMethodMetadataIR, RuntimeApiMethodParamMetadataIR, @@ -27,7 +27,6 @@ pub type Header = sp_runtime::generic::Header; pub type UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BlockWeights = (); type BlockLength = (); diff --git a/substrate/frame/support/test/tests/storage_layers.rs b/substrate/frame/support/test/tests/storage_layers.rs index a6d16e0d66d..b825c85f956 100644 --- a/substrate/frame/support/test/tests/storage_layers.rs +++ b/substrate/frame/support/test/tests/storage_layers.rs @@ -16,8 +16,8 @@ // limitations under the License. use frame_support::{ - assert_noop, assert_ok, derive_impl, dispatch::DispatchResult, ensure, - pallet_prelude::ConstU32, storage::with_storage_layer, + assert_noop, assert_ok, dispatch::DispatchResult, ensure, pallet_prelude::ConstU32, + storage::with_storage_layer, }; use pallet::*; use sp_io::TestExternalities; @@ -64,7 +64,6 @@ pub type Header = sp_runtime::generic::Header; pub type Block = sp_runtime::generic::Block; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/system/Cargo.toml b/substrate/frame/system/Cargo.toml index 2491ccd220c..b61b4d531e2 100644 --- a/substrate/frame/system/Cargo.toml +++ b/substrate/frame/system/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME system module" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,15 +17,15 @@ cfg-if = "1.0" codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive", "serde"] } -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"] } -frame-support = { path = "../support", default-features = false } +serde = { version = "1.0.188", default-features = false, features = ["derive", "alloc"] } +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-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-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.6" +docify = "0.2.0" [dev-dependencies] criterion = "0.4.0" @@ -36,7 +33,7 @@ sp-externalities = { path = "../../primitives/externalities" } substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", @@ -55,7 +52,8 @@ runtime-benchmarks = [ "frame-support/runtime-benchmarks", "sp-runtime/runtime-benchmarks", ] -try-runtime = ["frame-support/try-runtime", "sp-runtime/try-runtime"] +try-runtime = [ "frame-support/try-runtime", "sp-runtime/try-runtime" ] +experimental = [] [[bench]] name = "bench" diff --git a/substrate/frame/system/benches/bench.rs b/substrate/frame/system/benches/bench.rs index 79d5a2d8689..da8bb10fd4e 100644 --- a/substrate/frame/system/benches/bench.rs +++ b/substrate/frame/system/benches/bench.rs @@ -16,10 +16,7 @@ // limitations under the License. use criterion::{black_box, criterion_group, criterion_main, Criterion}; -use frame_support::{ - derive_impl, - traits::{ConstU32, ConstU64}, -}; +use frame_support::traits::{ConstU32, ConstU64}; use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -60,8 +57,6 @@ frame_support::parameter_types! { 4 * 1024 * 1024, Perbill::from_percent(75), ); } - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/system/benchmarking/Cargo.toml b/substrate/frame/system/benchmarking/Cargo.toml index 8b9873f44b8..c1d241f4bec 100644 --- a/substrate/frame/system/benchmarking/Cargo.toml +++ b/substrate/frame/system/benchmarking/Cargo.toml @@ -9,21 +9,18 @@ repository.workspace = true description = "FRAME System benchmarking" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] sp-io = { path = "../../../primitives/io" } @@ -31,7 +28,7 @@ sp-externalities = { path = "../../../primitives/externalities" } sp-version = { path = "../../../primitives/version" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking/std", diff --git a/substrate/frame/system/benchmarking/src/mock.rs b/substrate/frame/system/benchmarking/src/mock.rs index 9a81cddca14..4e6b1221da3 100644 --- a/substrate/frame/system/benchmarking/src/mock.rs +++ b/substrate/frame/system/benchmarking/src/mock.rs @@ -20,7 +20,6 @@ #![cfg(test)] use codec::Encode; -use frame_support::derive_impl; use sp_runtime::{traits::IdentityLookup, BuildStorage}; type AccountId = u64; @@ -35,7 +34,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/system/rpc/runtime-api/Cargo.toml b/substrate/frame/system/rpc/runtime-api/Cargo.toml index 8cec5de8d1e..81b6d946d46 100644 --- a/substrate/frame/system/rpc/runtime-api/Cargo.toml +++ b/substrate/frame/system/rpc/runtime-api/Cargo.toml @@ -9,16 +9,13 @@ repository.workspace = true description = "Runtime API definition required by System RPC extensions." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } -sp-api = { path = "../../../../primitives/api", default-features = false } +sp-api = { path = "../../../../primitives/api", default-features = false} [features] -default = ["std"] -std = ["codec/std", "sp-api/std"] +default = [ "std" ] +std = [ "codec/std", "sp-api/std" ] diff --git a/substrate/frame/system/src/lib.rs b/substrate/frame/system/src/lib.rs index 3697e36f3fc..1b8dd6a9367 100644 --- a/substrate/frame/system/src/lib.rs +++ b/substrate/frame/system/src/lib.rs @@ -206,7 +206,6 @@ pub mod pallet { /// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`]. pub mod config_preludes { use super::{inject_runtime_type, DefaultConfig}; - use frame_support::derive_impl; /// Provides a viable default config that can be used with /// [`derive_impl`](`frame_support::derive_impl`) to derive a testing pallet config @@ -241,8 +240,6 @@ pub mod pallet { type RuntimeCall = (); #[inject_runtime_type] type PalletInfo = (); - #[inject_runtime_type] - type RuntimeTask = (); type BaseCallFilter = frame_support::traits::Everything; type BlockHashCount = frame_support::traits::ConstU64<10>; type OnSetCode = (); @@ -261,100 +258,39 @@ pub mod pallet { /// if you use `pallet-balances` or similar. /// * Make sure to overwrite [`DefaultConfig::Version`]. /// * 2s block time, and a default 5mb block size is used. + #[cfg(feature = "experimental")] pub struct SolochainDefaultConfig; + #[cfg(feature = "experimental")] #[frame_support::register_default_impl(SolochainDefaultConfig)] impl DefaultConfig for SolochainDefaultConfig { - /// The default type for storing how many extrinsics an account has signed. type Nonce = u32; - - /// The default type for hashing blocks and tries. type Hash = sp_core::hash::H256; - - /// The default hashing algorithm used. type Hashing = sp_runtime::traits::BlakeTwo256; - - /// The default identifier used to distinguish between accounts. type AccountId = sp_runtime::AccountId32; - - /// The lookup mechanism to get account ID from whatever is passed in dispatchers. type Lookup = sp_runtime::traits::AccountIdLookup; - - /// The maximum number of consumers allowed on a single account. Using 128 as default. type MaxConsumers = frame_support::traits::ConstU32<128>; - - /// The default data to be stored in an account. type AccountData = crate::AccountInfo; - - /// What to do if a new account is created. type OnNewAccount = (); - - /// What to do if an account is fully reaped from the system. type OnKilledAccount = (); - - /// Weight information for the extrinsics of this pallet. type SystemWeightInfo = (); - - /// This is used as an identifier of the chain. type SS58Prefix = (); - - /// Version of the runtime. type Version = (); - - /// Block & extrinsics weights: base values and limits. type BlockWeights = (); - - /// The maximum length of a block (in bytes). type BlockLength = (); - - /// The weight of database operations that the runtime can invoke. type DbWeight = (); - - /// The ubiquitous event type injected by `construct_runtime!`. #[inject_runtime_type] type RuntimeEvent = (); - - /// The ubiquitous origin type injected by `construct_runtime!`. #[inject_runtime_type] type RuntimeOrigin = (); - - /// The aggregated dispatch type available for extrinsics, injected by - /// `construct_runtime!`. #[inject_runtime_type] type RuntimeCall = (); - - /// Converts a module to the index of the module, injected by `construct_runtime!`. - #[inject_runtime_type] - type RuntimeTask = (); #[inject_runtime_type] type PalletInfo = (); - - /// The basic call filter to use in dispatchable. Supports everything as the default. type BaseCallFilter = frame_support::traits::Everything; - - /// Maximum number of block number to block hash mappings to keep (oldest pruned first). - /// Using 256 as default. type BlockHashCount = frame_support::traits::ConstU32<256>; - - /// The set code logic, just the default since we're not a parachain. type OnSetCode = (); } - - /// Default configurations of this pallet in a relay-chain environment. - pub struct RelayChainDefaultConfig; - - /// It currently uses the same configuration as `SolochainDefaultConfig`. - #[derive_impl(SolochainDefaultConfig as DefaultConfig, no_aggregated_types)] - #[frame_support::register_default_impl(RelayChainDefaultConfig)] - impl DefaultConfig for RelayChainDefaultConfig {} - - /// Default configurations of this pallet in a parachain environment. - pub struct ParaChainDefaultConfig; - - /// It currently uses the same configuration as `SolochainDefaultConfig`. - #[derive_impl(SolochainDefaultConfig as DefaultConfig, no_aggregated_types)] - #[frame_support::register_default_impl(ParaChainDefaultConfig)] - impl DefaultConfig for ParaChainDefaultConfig {} } /// System configuration trait. Implemented by runtime. @@ -404,10 +340,6 @@ pub mod pallet { + Debug + From>; - /// The aggregated `RuntimeTask` type. - #[pallet::no_default_bounds] - type RuntimeTask: Task; - /// This stores the number of previous transactions associated with a sender account. type Nonce: Parameter + Member @@ -636,28 +568,6 @@ pub mod pallet { Self::deposit_event(Event::Remarked { sender: who, hash }); Ok(().into()) } - - #[pallet::call_index(8)] - #[pallet::weight(task.weight())] - pub fn do_task(origin: OriginFor, task: T::RuntimeTask) -> DispatchResultWithPostInfo { - ensure_signed(origin)?; - - if !task.is_valid() { - return Err(Error::::InvalidTask.into()) - } - - Self::deposit_event(Event::TaskStarted { task: task.clone() }); - if let Err(err) = task.run() { - Self::deposit_event(Event::TaskFailed { task, err }); - return Err(Error::::FailedTask.into()) - } - - // Emit a success event, if your design includes events for this pallet. - Self::deposit_event(Event::TaskCompleted { task }); - - // Return success. - Ok(().into()) - } } /// Event for the System pallet. @@ -675,12 +585,6 @@ pub mod pallet { KilledAccount { account: T::AccountId }, /// On on-chain remark happened. Remarked { sender: T::AccountId, hash: T::Hash }, - /// A [`Task`] has started executing - TaskStarted { task: T::RuntimeTask }, - /// A [`Task`] has finished executing. - TaskCompleted { task: T::RuntimeTask }, - /// A [`Task`] failed during execution. - TaskFailed { task: T::RuntimeTask, err: DispatchError }, } /// Error for the System pallet @@ -702,10 +606,6 @@ pub mod pallet { NonZeroRefCount, /// The origin filter prevent the call to be dispatched. CallFiltered, - /// The specified [`Task`] is not valid. - InvalidTask, - /// The specified [`Task`] failed during execution. - FailedTask, } /// Exposed trait-generic origin type. @@ -1118,7 +1018,6 @@ impl_ensure_origin_with_arg_ignoring_arg! { {} } -#[docify::export] /// Ensure that the origin `o` represents a signed extrinsic (i.e. transaction). /// Returns `Ok` with the account that signed the extrinsic or an `Err` otherwise. pub fn ensure_signed(o: OuterOrigin) -> Result @@ -1473,7 +1372,6 @@ impl Pallet { /// NOTE: Events not registered at the genesis block and quietly omitted. pub fn deposit_event_indexed(topics: &[T::Hash], event: T::RuntimeEvent) { let block_number = Self::block_number(); - // Don't populate events on genesis. if block_number.is_zero() { return @@ -1657,7 +1555,12 @@ impl Pallet { /// NOTE: Events not registered at the genesis block and quietly omitted. #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))] pub fn events() -> Vec> { - // Dereferencing the events here is fine since we are not in the memory-restricted runtime. + debug_assert!( + !Self::block_number().is_zero(), + "events not registered at the genesis block" + ); + // Dereferencing the events here is fine since we are not in the + // memory-restricted runtime. Self::read_events_no_consensus().map(|e| *e).collect() } @@ -1678,21 +1581,6 @@ impl Pallet { Events::::stream_iter() } - /// Read and return the events of a specific pallet, as denoted by `E`. - /// - /// This is useful for a pallet that wishes to read only the events it has deposited into - /// `frame_system` using the standard `fn deposit_event`. - pub fn read_events_for_pallet() -> Vec - where - T::RuntimeEvent: TryInto, - { - Events::::get() - .into_iter() - .map(|er| er.event) - .filter_map(|e| e.try_into().ok()) - .collect::<_>() - } - /// Set the block number to something in particular. Can be used as an alternative to /// `initialize` for tests that don't need to bother with the other environment entries. #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))] @@ -1919,11 +1807,6 @@ impl BlockNumberProvider for Pallet { fn current_block_number() -> Self::BlockNumber { Pallet::::block_number() } - - #[cfg(feature = "runtime-benchmarks")] - fn set_block_number(n: BlockNumberFor) { - Self::set_block_number(n) - } } /// Implement StoredMap for a simple single-item, provide-when-not-default system. This works fine diff --git a/substrate/frame/system/src/mock.rs b/substrate/frame/system/src/mock.rs index e33ac2f56c8..c016ea9e1cd 100644 --- a/substrate/frame/system/src/mock.rs +++ b/substrate/frame/system/src/mock.rs @@ -17,7 +17,7 @@ use crate::{self as frame_system, *}; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64}, }; use sp_core::H256; @@ -85,7 +85,6 @@ impl OnKilledAccount for RecordKilled { } } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = RuntimeBlockWeights; diff --git a/substrate/frame/timestamp/Cargo.toml b/substrate/frame/timestamp/Cargo.toml index bcf26d622b0..e23ded725d8 100644 --- a/substrate/frame/timestamp/Cargo.toml +++ b/substrate/frame/timestamp/Cargo.toml @@ -10,9 +10,6 @@ description = "FRAME Timestamp Module" documentation = "https://docs.rs/pallet-timestamp" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,15 +17,15 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} docify = "0.2.6" @@ -37,7 +34,7 @@ sp-core = { path = "../../primitives/core" } sp-io = { path = "../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/timestamp/src/mock.rs b/substrate/frame/timestamp/src/mock.rs index b75bcaeb0e0..418d257b3f0 100644 --- a/substrate/frame/timestamp/src/mock.rs +++ b/substrate/frame/timestamp/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_timestamp; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64}, }; use sp_core::H256; @@ -42,7 +42,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/tips/Cargo.toml b/substrate/frame/tips/Cargo.toml index fbd6404d785..6df886b93d7 100644 --- a/substrate/frame/tips/Cargo.toml +++ b/substrate/frame/tips/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet to manage tips" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,22 +16,22 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", features = ["derive"], 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 } -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 } +serde = { version = "1.0.188", features = ["derive"], 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} +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} [dev-dependencies] pallet-balances = { path = "../balances" } sp-storage = { path = "../../primitives/storage" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/tips/src/migrations/v4.rs b/substrate/frame/tips/src/migrations/v4.rs index 2404c6de1a1..35569633d1b 100644 --- a/substrate/frame/tips/src/migrations/v4.rs +++ b/substrate/frame/tips/src/migrations/v4.rs @@ -90,7 +90,7 @@ pub fn migrate, I: 'static>(n: u32) -> Result<(), &'s #[allow(deprecated)] Treasury::::propose_spend(RawOrigin::Signed(caller).into(), value, lookup)?; let proposal_id = >::get() - 1; - Approvals::::try_append(proposal_id).unwrap(); + #[allow(deprecated)] + Treasury::::approve_proposal(RawOrigin::Root.into(), proposal_id)?; } ensure!(>::get().len() == n as usize, "Not all approved"); Ok(()) @@ -162,8 +163,6 @@ mod benchmarks { 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)] @@ -173,6 +172,8 @@ mod benchmarks { beneficiary_lookup, )?; let proposal_id = Treasury::::proposal_count() - 1; + let approve_origin = + T::ApproveOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; #[extrinsic_call] _(approve_origin as T::RuntimeOrigin, proposal_id); @@ -190,7 +191,8 @@ mod benchmarks { beneficiary_lookup, )?; let proposal_id = Treasury::::proposal_count() - 1; - Approvals::::try_append(proposal_id).unwrap(); + #[allow(deprecated)] + Treasury::::approve_proposal(RawOrigin::Root.into(), proposal_id)?; let reject_origin = T::RejectOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; diff --git a/substrate/frame/treasury/src/tests.rs b/substrate/frame/treasury/src/tests.rs index 093757b2770..522ecf6b18f 100644 --- a/substrate/frame/treasury/src/tests.rs +++ b/substrate/frame/treasury/src/tests.rs @@ -27,7 +27,7 @@ use sp_runtime::{ }; use frame_support::{ - assert_err_ignore_postinfo, assert_noop, assert_ok, derive_impl, + assert_err_ignore_postinfo, assert_noop, assert_ok, pallet_prelude::Pays, parameter_types, traits::{ @@ -54,7 +54,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/try-runtime/Cargo.toml b/substrate/frame/try-runtime/Cargo.toml index 1d036e00447..1bb3283b1de 100644 --- a/substrate/frame/try-runtime/Cargo.toml +++ b/substrate/frame/try-runtime/Cargo.toml @@ -8,21 +8,18 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME pallet for democracy" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.1", 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 = { package = "parity-scale-codec", version = "3.6.1", 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} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-support/std", @@ -30,4 +27,4 @@ std = [ "sp-runtime/std", "sp-std/std", ] -try-runtime = ["frame-support/try-runtime", "sp-runtime/try-runtime"] +try-runtime = [ "frame-support/try-runtime", "sp-runtime/try-runtime" ] diff --git a/substrate/frame/tx-pause/Cargo.toml b/substrate/frame/tx-pause/Cargo.toml index 5958dcc2c30..bf0641f5b6d 100644 --- a/substrate/frame/tx-pause/Cargo.toml +++ b/substrate/frame/tx-pause/Cargo.toml @@ -8,24 +8,21 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME transaction pause pallet" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false, features = ["derive"] } docify = "0.2.6" -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 = { 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.10.0", default-features = false, features = ["derive"] } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", 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 } +pallet-utility = { path = "../utility", default-features = false, optional = true } +pallet-proxy = { path = "../proxy", default-features = false, optional = true } [dev-dependencies] sp-core = { path = "../../primitives/core" } @@ -35,7 +32,7 @@ pallet-utility = { path = "../utility" } pallet-proxy = { path = "../proxy" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking/std", diff --git a/substrate/frame/tx-pause/src/mock.rs b/substrate/frame/tx-pause/src/mock.rs index 4f1c981abc6..66218c8c015 100644 --- a/substrate/frame/tx-pause/src/mock.rs +++ b/substrate/frame/tx-pause/src/mock.rs @@ -23,7 +23,7 @@ use super::*; use crate as pallet_tx_pause; use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU64, Everything, InsideBoth, InstanceFilter}, }; use frame_system::EnsureSignedBy; @@ -36,7 +36,6 @@ use sp_runtime::{ parameter_types! { pub const BlockHashCount: u64 = 250; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = InsideBoth; type BlockWeights = (); diff --git a/substrate/frame/uniques/Cargo.toml b/substrate/frame/uniques/Cargo.toml index 218b4ffe4c0..4c1bcca573d 100644 --- a/substrate/frame/uniques/Cargo.toml +++ b/substrate/frame/uniques/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME NFT asset management pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,11 +16,11 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } @@ -32,7 +29,7 @@ sp-io = { path = "../../primitives/io" } sp-std = { path = "../../primitives/std" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/uniques/src/migration.rs b/substrate/frame/uniques/src/migration.rs index 6b2bbf375e7..6c92b753b4a 100644 --- a/substrate/frame/uniques/src/migration.rs +++ b/substrate/frame/uniques/src/migration.rs @@ -17,39 +17,38 @@ //! Various pieces of common functionality. use super::*; -use frame_support::traits::{Get, OnRuntimeUpgrade}; -use sp_std::marker::PhantomData; - -mod v1 { - use super::*; - - /// Actual implementation of the storage migration. - pub struct MigrateToV1Impl(PhantomData<(T, I)>); - - impl, I: 'static> OnRuntimeUpgrade for MigrateToV1Impl { - fn on_runtime_upgrade() -> frame_support::weights::Weight { - let mut count = 0; - for (collection, detail) in Collection::::iter() { - CollectionAccount::::insert(&detail.owner, &collection, ()); - count += 1; - } - - log::info!( - target: LOG_TARGET, - "Storage migration v1 for uniques finished.", - ); - - // calculate and return migration weights - T::DbWeight::get().reads_writes(count as u64 + 1, count as u64 + 1) +use frame_support::traits::{Get, GetStorageVersion, PalletInfoAccess, StorageVersion}; + +/// Migrate the pallet storage to v1. +pub fn migrate_to_v1, I: 'static, P: GetStorageVersion + PalletInfoAccess>( +) -> frame_support::weights::Weight { + let on_chain_storage_version =

::on_chain_storage_version(); + log::info!( + target: LOG_TARGET, + "Running migration storage v1 for uniques with storage version {:?}", + on_chain_storage_version, + ); + + if on_chain_storage_version < 1 { + let mut count = 0; + for (collection, detail) in Collection::::iter() { + CollectionAccount::::insert(&detail.owner, &collection, ()); + count += 1; } + StorageVersion::new(1).put::

(); + log::info!( + target: LOG_TARGET, + "Running migration storage v1 for uniques with storage version {:?} was complete", + on_chain_storage_version, + ); + // calculate and return migration weights + T::DbWeight::get().reads_writes(count as u64 + 1, count as u64 + 1) + } else { + log::warn!( + target: LOG_TARGET, + "Attempted to apply migration to v1 but failed because storage version is {:?}", + on_chain_storage_version, + ); + T::DbWeight::get().reads(1) } } - -/// Migrate the pallet storage from `0` to `1`. -pub type MigrateV0ToV1 = frame_support::migrations::VersionedMigration< - 0, - 1, - v1::MigrateToV1Impl, - Pallet, - ::DbWeight, ->; diff --git a/substrate/frame/uniques/src/mock.rs b/substrate/frame/uniques/src/mock.rs index 056c19ec559..1f62c3c4e93 100644 --- a/substrate/frame/uniques/src/mock.rs +++ b/substrate/frame/uniques/src/mock.rs @@ -21,7 +21,7 @@ use super::*; use crate as pallet_uniques; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, traits::{AsEnsureOriginWithArg, ConstU32, ConstU64}, }; use sp_core::H256; @@ -41,7 +41,6 @@ construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); diff --git a/substrate/frame/utility/Cargo.toml b/substrate/frame/utility/Cargo.toml index 4aa75f9f616..8f7a368709b 100644 --- a/substrate/frame/utility/Cargo.toml +++ b/substrate/frame/utility/Cargo.toml @@ -9,22 +9,19 @@ repository.workspace = true description = "FRAME utilities pallet" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } @@ -34,7 +31,7 @@ pallet-timestamp = { path = "../timestamp" } sp-core = { path = "../../primitives/core" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/utility/src/tests.rs b/substrate/frame/utility/src/tests.rs index 7b42fa511d1..01e3f5264bf 100644 --- a/substrate/frame/utility/src/tests.rs +++ b/substrate/frame/utility/src/tests.rs @@ -23,7 +23,7 @@ use super::*; use crate as utility; use frame_support::{ - assert_err_ignore_postinfo, assert_noop, assert_ok, derive_impl, + assert_err_ignore_postinfo, assert_noop, assert_ok, dispatch::{DispatchErrorWithPostInfo, Pays}, error::BadOrigin, parameter_types, storage, @@ -144,7 +144,6 @@ parameter_types! { pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::simple_max(Weight::MAX); } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = TestBaseCallFilter; type BlockWeights = BlockWeights; diff --git a/substrate/frame/vesting/Cargo.toml b/substrate/frame/vesting/Cargo.toml index 3b5252d6181..ed13a15bc97 100644 --- a/substrate/frame/vesting/Cargo.toml +++ b/substrate/frame/vesting/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "FRAME pallet for manage vesting" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,19 +18,19 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = ] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io", default-features = false } +sp-io = { path = "../../primitives/io", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/vesting/src/benchmarking.rs b/substrate/frame/vesting/src/benchmarking.rs index 311590873d9..34aa04607ad 100644 --- a/substrate/frame/vesting/src/benchmarking.rs +++ b/substrate/frame/vesting/src/benchmarking.rs @@ -55,7 +55,7 @@ fn add_vesting_schedules( let source_lookup = T::Lookup::unlookup(source.clone()); T::Currency::make_free_balance_be(&source, BalanceOf::::max_value()); - T::BlockNumberProvider::set_block_number(BlockNumberFor::::zero()); + System::::set_block_number(BlockNumberFor::::zero()); let mut total_locked: BalanceOf = Zero::zero(); for _ in 0..n { @@ -116,7 +116,7 @@ benchmarks! { add_vesting_schedules::(caller_lookup, s)?; // At block 21, everything is unlocked. - T::BlockNumberProvider::set_block_number(21u32.into()); + System::::set_block_number(21u32.into()); assert_eq!( Vesting::::vesting_balance(&caller), Some(BalanceOf::::zero()), @@ -173,7 +173,7 @@ benchmarks! { add_locks::(&other, l as u8); add_vesting_schedules::(other_lookup.clone(), s)?; // At block 21 everything is unlocked. - T::BlockNumberProvider::set_block_number(21u32.into()); + System::::set_block_number(21u32.into()); assert_eq!( Vesting::::vesting_balance(&other), @@ -335,7 +335,7 @@ benchmarks! { let total_transferred = add_vesting_schedules::(caller_lookup, s)?; // Go to about half way through all the schedules duration. (They all start at 1, and have a duration of 20 or 21). - T::BlockNumberProvider::set_block_number(11u32.into()); + System::::set_block_number(11u32.into()); // We expect half the original locked balance (+ any remainder that vests on the last block). let expected_balance = total_transferred / 2u32.into(); assert_eq!( diff --git a/substrate/frame/vesting/src/lib.rs b/substrate/frame/vesting/src/lib.rs index 4101caded41..dbad7926a30 100644 --- a/substrate/frame/vesting/src/lib.rs +++ b/substrate/frame/vesting/src/lib.rs @@ -71,8 +71,8 @@ use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_runtime::{ traits::{ - AtLeast32BitUnsigned, BlockNumberProvider, Bounded, Convert, MaybeSerializeDeserialize, - One, Saturating, StaticLookup, Zero, + AtLeast32BitUnsigned, Bounded, Convert, MaybeSerializeDeserialize, One, Saturating, + StaticLookup, Zero, }, DispatchError, RuntimeDebug, }; @@ -176,9 +176,6 @@ pub mod pallet { /// the unvested amount. type UnvestedFundsAllowedWithdrawReasons: Get; - /// Provider for the block number. - type BlockNumberProvider: BlockNumberProvider>; - /// Maximum number of vesting schedules an account may have at a given moment. const MAX_VESTING_SCHEDULES: u32; } @@ -568,7 +565,7 @@ impl Pallet { schedules: Vec, BlockNumberFor>>, action: VestingAction, ) -> (Vec, BlockNumberFor>>, BalanceOf) { - let now = T::BlockNumberProvider::current_block_number(); + let now = >::block_number(); let mut total_locked_now: BalanceOf = Zero::zero(); let filtered_schedules = action @@ -652,7 +649,7 @@ impl Pallet { let (mut schedules, mut locked_now) = Self::report_schedule_updates(schedules.to_vec(), action); - let now = T::BlockNumberProvider::current_block_number(); + let now = >::block_number(); if let Some(new_schedule) = Self::merge_vesting_info(now, schedule1, schedule2) { // Merging created a new schedule so we: // 1) need to add it to the accounts vesting schedule collection, @@ -688,7 +685,7 @@ where /// Get the amount that is currently being vested and cannot be transferred out of this account. fn vesting_balance(who: &T::AccountId) -> Option> { if let Some(v) = Self::vesting(who) { - let now = T::BlockNumberProvider::current_block_number(); + let now = >::block_number(); let total_locked_now = v.iter().fold(Zero::zero(), |total, schedule| { schedule.locked_at::(now).saturating_add(total) }); diff --git a/substrate/frame/vesting/src/mock.rs b/substrate/frame/vesting/src/mock.rs index 3af4a9c962d..13d6d5ba57a 100644 --- a/substrate/frame/vesting/src/mock.rs +++ b/substrate/frame/vesting/src/mock.rs @@ -16,7 +16,7 @@ // limitations under the License. use frame_support::{ - derive_impl, parameter_types, + parameter_types, traits::{ConstU32, ConstU64, WithdrawReasons}, }; use sp_core::H256; @@ -39,7 +39,6 @@ frame_support::construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; type AccountId = u64; @@ -96,7 +95,6 @@ impl Config for Test { type MinVestedTransfer = MinVestedTransfer; type WeightInfo = (); type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; - type BlockNumberProvider = System; } pub struct ExtBuilder { diff --git a/substrate/frame/whitelist/Cargo.toml b/substrate/frame/whitelist/Cargo.toml index 5d9a362f9aa..c5246615320 100644 --- a/substrate/frame/whitelist/Cargo.toml +++ b/substrate/frame/whitelist/Cargo.toml @@ -8,21 +8,18 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME pallet for whitelisting call, and dispatch from specific origin" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "2.10.0", 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 } +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} [dev-dependencies] pallet-balances = { path = "../balances" } @@ -31,7 +28,7 @@ sp-core = { path = "../../primitives/core" } sp-io = { path = "../../primitives/io" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "frame-benchmarking?/std", diff --git a/substrate/frame/whitelist/src/mock.rs b/substrate/frame/whitelist/src/mock.rs index 200e589c6aa..4e70a503c28 100644 --- a/substrate/frame/whitelist/src/mock.rs +++ b/substrate/frame/whitelist/src/mock.rs @@ -22,7 +22,7 @@ use crate as pallet_whitelist; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, traits::{ConstU32, ConstU64, Nothing}, }; use frame_system::EnsureRoot; @@ -44,7 +44,6 @@ construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::Config for Test { type BaseCallFilter = Nothing; type BlockWeights = (); diff --git a/substrate/primitives/api/Cargo.toml b/substrate/primitives/api/Cargo.toml index 345647cec25..e95333c9eeb 100644 --- a/substrate/primitives/api/Cargo.toml +++ b/substrate/primitives/api/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Substrate runtime api primitives" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -35,7 +32,7 @@ log = { version = "0.4.17", default-features = false } sp-test-primitives = { path = "../test-primitives" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "hash-db", @@ -61,7 +58,7 @@ std = [ # building a runtime for registering it on chain. # # This sets the max logging level to `off` for `log`. -disable-logging = ["log/max_level_off"] +disable-logging = [ "log/max_level_off" ] # Do not report the documentation in the metadata. -no-metadata-docs = ["sp-api-proc-macro/no-metadata-docs"] -frame-metadata = ["sp-api-proc-macro/frame-metadata", "sp-metadata-ir"] +no-metadata-docs = [ "sp-api-proc-macro/no-metadata-docs" ] +frame-metadata = [ "sp-api-proc-macro/frame-metadata", "sp-metadata-ir" ] diff --git a/substrate/primitives/api/proc-macro/Cargo.toml b/substrate/primitives/api/proc-macro/Cargo.toml index 544a48062d7..d60b9f1bb4e 100644 --- a/substrate/primitives/api/proc-macro/Cargo.toml +++ b/substrate/primitives/api/proc-macro/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Macros for declaring and implementing runtime apis." documentation = "https://docs.rs/sp-api-proc-macro" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,10 +17,10 @@ proc-macro = true [dependencies] quote = "1.0.28" -syn = { version = "2.0.40", features = ["extra-traits", "fold", "full", "visit"] } +syn = { version = "2.0.38", features = ["full", "fold", "extra-traits", "visit"] } proc-macro2 = "1.0.56" blake2 = { version = "0.10.4", default-features = false } -proc-macro-crate = "2.0.1" +proc-macro-crate = "1.1.3" expander = "2.0.0" Inflector = "0.11.4" @@ -32,7 +29,7 @@ assert_matches = "1.3.0" [features] # Required for the doc tests -default = ["std"] -std = ["blake2/std"] +default = [ "std" ] +std = [ "blake2/std" ] no-metadata-docs = [] frame-metadata = [] diff --git a/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs b/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs index 2b1e65ec885..370735819f9 100644 --- a/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -729,7 +729,7 @@ fn decl_runtime_apis_impl_inner(api_decls: &[ItemTrait]) -> Result }; let decl = expander::Expander::new("decl_runtime_apis") - .dry(std::env::var("EXPAND_MACROS").is_err()) + .dry(std::env::var("SP_API_EXPAND").is_err()) .verbose(true) .write_to_out_dir(decl) .expect("Does not fail because of IO in OUT_DIR; qed"); diff --git a/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs b/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs index fd81fdb624c..e439a796e28 100644 --- a/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs +++ b/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs @@ -275,7 +275,6 @@ fn generate_runtime_api_base_structures() -> Result { extensions_generated_for: std::cell::RefCell>, } - #[automatically_derived] impl> #crate_::ApiExt for RuntimeApiImpl { @@ -368,7 +367,6 @@ fn generate_runtime_api_base_structures() -> Result { } } - #[automatically_derived] impl #crate_::ConstructRuntimeApi for RuntimeApi where @@ -391,7 +389,6 @@ fn generate_runtime_api_base_structures() -> Result { } } - #[automatically_derived] impl> RuntimeApiImpl { fn commit_or_rollback_transaction(&self, commit: bool) { let proof = "\ @@ -688,11 +685,9 @@ fn generate_api_impl_for_runtime_api(impls: &[ItemImpl]) -> Result // remove the trait to get just the module path runtime_mod_path.segments.pop(); - let mut processed_impl = + let processed_impl = ApiRuntimeImplToApiRuntimeApiImpl { runtime_block }.process(impl_.clone()); - processed_impl.attrs.push(parse_quote!(#[automatically_derived])); - result.push(processed_impl); } @@ -846,7 +841,7 @@ fn impl_runtime_apis_impl_inner(api_impls: &[ItemImpl]) -> Result { ); let impl_ = expander::Expander::new("impl_runtime_apis") - .dry(std::env::var("EXPAND_MACROS").is_err()) + .dry(std::env::var("SP_API_EXPAND").is_err()) .verbose(true) .write_to_out_dir(impl_) .expect("Does not fail because of IO in OUT_DIR; qed"); diff --git a/substrate/primitives/api/src/lib.rs b/substrate/primitives/api/src/lib.rs index 1b8b7c40ae0..3b00e6b418b 100644 --- a/substrate/primitives/api/src/lib.rs +++ b/substrate/primitives/api/src/lib.rs @@ -406,14 +406,14 @@ pub use sp_api_proc_macro::impl_runtime_apis; /// Mocks given trait implementations as runtime apis. /// -/// Accepts similar syntax as [`impl_runtime_apis!`] and generates simplified mock -/// implementations of the given runtime apis. The difference in syntax is that the trait does -/// not need to be referenced by a qualified path, methods accept the `&self` parameter and the -/// error type can be specified as associated type. If no error type is specified [`String`] is -/// used as error type. -/// -/// Besides implementing the given traits, the [`Core`] and [`ApiExt`] are implemented -/// automatically. +/// Accepts similar syntax as [`impl_runtime_apis!`] and generates +/// simplified mock implementations of the given runtime apis. The difference in syntax is that +/// the trait does not need to be referenced by a qualified path, methods accept the `&self` +/// parameter and the error type can be specified as associated type. If no error type is +/// specified [`String`] is used as error type. +/// +/// Besides implementing the given traits, the [`Core`](sp_api::Core) and +/// [`ApiExt`](sp_api::ApiExt) are implemented automatically. /// /// # Example /// diff --git a/substrate/primitives/api/test/Cargo.toml b/substrate/primitives/api/test/Cargo.toml index 0346ad270ab..f207f5ff02d 100644 --- a/substrate/primitives/api/test/Cargo.toml +++ b/substrate/primitives/api/test/Cargo.toml @@ -8,9 +8,6 @@ publish = false homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/primitives/api/test/tests/ui/impl_incorrect_method_signature.stderr b/substrate/primitives/api/test/tests/ui/impl_incorrect_method_signature.stderr index 788d1807f3b..4bd64c974f2 100644 --- a/substrate/primitives/api/test/tests/ui/impl_incorrect_method_signature.stderr +++ b/substrate/primitives/api/test/tests/ui/impl_incorrect_method_signature.stderr @@ -1,21 +1,3 @@ -error[E0603]: struct `RuntimeVersion` is private - --> tests/ui/impl_incorrect_method_signature.rs:37:27 - | -37 | fn version() -> sp_api::RuntimeVersion { - | ^^^^^^^^^^^^^^ private struct - | -note: the struct `RuntimeVersion` is defined here - --> $WORKSPACE/substrate/primitives/api/src/lib.rs - | - | use sp_version::RuntimeVersion; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -help: consider importing one of these items instead - | -37 | fn version() -> sp_api::__private::RuntimeVersion { - | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -37 | fn version() -> sp_version::RuntimeVersion { - | ~~~~~~~~~~~~~~~~~~~~~~~~~~ - error[E0053]: method `test` has an incompatible type for trait --> tests/ui/impl_incorrect_method_signature.rs:33:17 | diff --git a/substrate/primitives/api/test/tests/ui/type_reference_in_impl_runtime_apis_call.stderr b/substrate/primitives/api/test/tests/ui/type_reference_in_impl_runtime_apis_call.stderr index b4df7c06876..4c21a3afb9b 100644 --- a/substrate/primitives/api/test/tests/ui/type_reference_in_impl_runtime_apis_call.stderr +++ b/substrate/primitives/api/test/tests/ui/type_reference_in_impl_runtime_apis_call.stderr @@ -1,21 +1,3 @@ -error[E0603]: struct `RuntimeVersion` is private - --> tests/ui/type_reference_in_impl_runtime_apis_call.rs:39:27 - | -39 | fn version() -> sp_api::RuntimeVersion { - | ^^^^^^^^^^^^^^ private struct - | -note: the struct `RuntimeVersion` is defined here - --> $WORKSPACE/substrate/primitives/api/src/lib.rs - | - | use sp_version::RuntimeVersion; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ -help: consider importing one of these items instead - | -39 | fn version() -> sp_api::__private::RuntimeVersion { - | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -39 | fn version() -> sp_version::RuntimeVersion { - | ~~~~~~~~~~~~~~~~~~~~~~~~~~ - error[E0053]: method `test` has an incompatible type for trait --> tests/ui/type_reference_in_impl_runtime_apis_call.rs:33:17 | diff --git a/substrate/primitives/application-crypto/Cargo.toml b/substrate/primitives/application-crypto/Cargo.toml index 33bc22ed84f..a4a1bc44a69 100644 --- a/substrate/primitives/application-crypto/Cargo.toml +++ b/substrate/primitives/application-crypto/Cargo.toml @@ -10,23 +10,20 @@ repository.workspace = true documentation = "https://docs.rs/sp-application-crypto" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-core = { path = "../core", default-features = false } +sp-core = { path = "../core", default-features = false} codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, optional = true, features = ["alloc", "derive"] } -sp-std = { path = "../std", default-features = false } -sp-io = { path = "../io", default-features = false } +serde = { version = "1.0.188", default-features = false, optional = true, features = ["derive", "alloc"] } +sp-std = { path = "../std", default-features = false} +sp-io = { path = "../io", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "full_crypto", @@ -38,7 +35,7 @@ std = [ ] # Serde support without relying on std features. -serde = ["dep:serde", "scale-info/serde", "sp-core/serde"] +serde = [ "dep:serde", "scale-info/serde", "sp-core/serde" ] # This feature enables all crypto primitives for `no_std` builds like microcontrollers # or Intel SGX. @@ -54,7 +51,7 @@ full_crypto = [ # This feature adds BLS crypto primitives. # It should not be used in production since the implementation and interface may still # be subject to significant changes. -bls-experimental = ["sp-core/bls-experimental", "sp-io/bls-experimental"] +bls-experimental = [ "sp-core/bls-experimental", "sp-io/bls-experimental" ] # This feature adds Bandersnatch crypto primitives. # It should not be used in production since the implementation and interface may still diff --git a/substrate/primitives/application-crypto/test/Cargo.toml b/substrate/primitives/application-crypto/test/Cargo.toml index 0057606b38e..a6f4f108c8f 100644 --- a/substrate/primitives/application-crypto/test/Cargo.toml +++ b/substrate/primitives/application-crypto/test/Cargo.toml @@ -9,15 +9,12 @@ publish = false homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] 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 } +sp-core = { path = "../../core", default-features = false} +sp-keystore = { path = "../../keystore", default-features = false} substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } diff --git a/substrate/primitives/arithmetic/Cargo.toml b/substrate/primitives/arithmetic/Cargo.toml index f7f1da6a913..249aebec68f 100644 --- a/substrate/primitives/arithmetic/Cargo.toml +++ b/substrate/primitives/arithmetic/Cargo.toml @@ -10,9 +10,6 @@ description = "Minimal fixed point arithmetic primitives and types for runtime." documentation = "https://docs.rs/sp-arithmetic" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -22,20 +19,20 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = "max-encoded-len", ] } integer-sqrt = "0.1.2" -num-traits = { version = "0.2.17", default-features = false } +num-traits = { version = "0.2.8", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"], optional = true } +serde = { version = "1.0.188", default-features = false, features = ["derive", "alloc"], optional = true } static_assertions = "1.1.0" -sp-std = { path = "../std", default-features = false } +sp-std = { path = "../std", default-features = false} [dev-dependencies] criterion = "0.4.0" primitive-types = "0.12.0" -sp-core = { path = "../core", features = ["full_crypto"] } +sp-core = { path = "../core", features = ["full_crypto"]} rand = "0.8.5" [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "num-traits/std", @@ -45,7 +42,7 @@ std = [ "sp-std/std", ] # Serde support without relying on std features. -serde = ["dep:serde", "scale-info/serde"] +serde = [ "dep:serde", "scale-info/serde" ] [[bench]] name = "bench" diff --git a/substrate/primitives/arithmetic/fuzzer/Cargo.toml b/substrate/primitives/arithmetic/fuzzer/Cargo.toml index b881e8d46db..eded5a954c5 100644 --- a/substrate/primitives/arithmetic/fuzzer/Cargo.toml +++ b/substrate/primitives/arithmetic/fuzzer/Cargo.toml @@ -10,9 +10,6 @@ description = "Fuzzer for fixed point arithmetic primitives." documentation = "https://docs.rs/sp-arithmetic-fuzzer" publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/primitives/authority-discovery/Cargo.toml b/substrate/primitives/authority-discovery/Cargo.toml index 82ec5a3eb9a..e4f44e9da38 100644 --- a/substrate/primitives/authority-discovery/Cargo.toml +++ b/substrate/primitives/authority-discovery/Cargo.toml @@ -9,22 +9,19 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.10.0", 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 } -sp-std = { path = "../std", default-features = false } +sp-api = { path = "../api", default-features = false} +sp-application-crypto = { path = "../application-crypto", default-features = false} +sp-runtime = { path = "../runtime", default-features = false} +sp-std = { path = "../std", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "scale-info/std", diff --git a/substrate/primitives/block-builder/Cargo.toml b/substrate/primitives/block-builder/Cargo.toml index de1ffd9d9e6..269eb539532 100644 --- a/substrate/primitives/block-builder/Cargo.toml +++ b/substrate/primitives/block-builder/Cargo.toml @@ -9,18 +9,15 @@ repository.workspace = true description = "The block builder runtime api." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] 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-std = { path = "../std", default-features = false } +sp-api = { path = "../api", default-features = false} +sp-inherents = { path = "../inherents", default-features = false} +sp-runtime = { path = "../runtime", default-features = false} +sp-std = { path = "../std", default-features = false} [features] -default = ["std"] -std = ["sp-api/std", "sp-inherents/std", "sp-runtime/std", "sp-std/std"] +default = [ "std" ] +std = [ "sp-api/std", "sp-inherents/std", "sp-runtime/std", "sp-std/std" ] diff --git a/substrate/primitives/blockchain/Cargo.toml b/substrate/primitives/blockchain/Cargo.toml index 38b3b2030dc..33db09ce0ac 100644 --- a/substrate/primitives/blockchain/Cargo.toml +++ b/substrate/primitives/blockchain/Cargo.toml @@ -10,9 +10,6 @@ description = "Substrate blockchain traits and primitives." documentation = "https://docs.rs/sp-blockchain" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/primitives/consensus/aura/Cargo.toml b/substrate/primitives/consensus/aura/Cargo.toml index 15159f62611..26f02bc3119 100644 --- a/substrate/primitives/consensus/aura/Cargo.toml +++ b/substrate/primitives/consensus/aura/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,16 +16,16 @@ targets = ["x86_64-unknown-linux-gnu"] async-trait = { version = "0.1.57", optional = true } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.10.0", 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-std = { path = "../../std", default-features = false } -sp-timestamp = { path = "../../timestamp", default-features = false } +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-std = { path = "../../std", default-features = false} +sp-timestamp = { path = "../../timestamp", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "async-trait", "codec/std", diff --git a/substrate/primitives/consensus/babe/Cargo.toml b/substrate/primitives/consensus/babe/Cargo.toml index 72cee3604d5..db8bb8cb154 100644 --- a/substrate/primitives/consensus/babe/Cargo.toml +++ b/substrate/primitives/consensus/babe/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,18 +16,18 @@ targets = ["x86_64-unknown-linux-gnu"] async-trait = { version = "0.1.57", optional = true } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"], optional = 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-std = { path = "../../std", default-features = false } -sp-timestamp = { path = "../../timestamp", optional = true } +serde = { version = "1.0.188", default-features = false, features = ["derive", "alloc"], optional = 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-std = { path = "../../std", default-features = false} +sp-timestamp = { path = "../../timestamp", optional = true} [features] -default = ["std"] +default = [ "std" ] std = [ "async-trait", "codec/std", diff --git a/substrate/primitives/consensus/babe/src/lib.rs b/substrate/primitives/consensus/babe/src/lib.rs index d6b2cdd55e0..c083bfd9a31 100644 --- a/substrate/primitives/consensus/babe/src/lib.rs +++ b/substrate/primitives/consensus/babe/src/lib.rs @@ -33,7 +33,7 @@ use sp_std::vec::Vec; use crate::digests::{NextConfigDescriptor, NextEpochDescriptor}; pub use sp_core::sr25519::vrf::{ - VrfInput, VrfPreOutput, VrfProof, VrfSignData, VrfSignature, VrfTranscript, + VrfInput, VrfOutput, VrfProof, VrfSignData, VrfSignature, VrfTranscript, }; /// Key type for BABE module. diff --git a/substrate/primitives/consensus/beefy/Cargo.toml b/substrate/primitives/consensus/beefy/Cargo.toml index 42383cf14a8..e78323c8980 100644 --- a/substrate/primitives/consensus/beefy/Cargo.toml +++ b/substrate/primitives/consensus/beefy/Cargo.toml @@ -8,16 +8,13 @@ homepage = "https://substrate.io" repository.workspace = true description = "Primitives for BEEFY protocol." -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, optional = true, features = ["alloc", "derive"] } +serde = { version = "1.0.188", default-features = false, optional = true, features = ["derive", "alloc"] } sp-api = { path = "../../api", default-features = false } sp-application-crypto = { path = "../../application-crypto", default-features = false } sp-core = { path = "../../core", default-features = false } @@ -33,7 +30,7 @@ array-bytes = "6.1" w3f-bls = { version = "0.1.3", features = ["std"] } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "scale-info/std", diff --git a/substrate/primitives/consensus/common/Cargo.toml b/substrate/primitives/consensus/common/Cargo.toml index 066578406b6..e8f6b806f8c 100644 --- a/substrate/primitives/consensus/common/Cargo.toml +++ b/substrate/primitives/consensus/common/Cargo.toml @@ -10,9 +10,6 @@ description = "Common utilities for building and using consensus engines in subs documentation = "https://docs.rs/sp-consensus/" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/primitives/consensus/grandpa/Cargo.toml b/substrate/primitives/consensus/grandpa/Cargo.toml index 238c9868664..8757869995d 100644 --- a/substrate/primitives/consensus/grandpa/Cargo.toml +++ b/substrate/primitives/consensus/grandpa/Cargo.toml @@ -10,9 +10,6 @@ description = "Primitives for GRANDPA integration, suitable for WASM compilation documentation = "https://docs.rs/sp-consensus-grandpa" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,16 +18,16 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = grandpa = { package = "finality-grandpa", version = "0.16.2", default-features = false, features = ["derive-codec"] } log = { version = "0.4.17", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", features = ["alloc", "derive"], default-features = false, optional = 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-std = { path = "../../std", default-features = false } +serde = { version = "1.0.188", features = ["derive", "alloc"], default-features = false, optional = 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-std = { path = "../../std", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "grandpa/std", diff --git a/substrate/primitives/consensus/pow/Cargo.toml b/substrate/primitives/consensus/pow/Cargo.toml index e528d8365ce..cc4e961dbb6 100644 --- a/substrate/primitives/consensus/pow/Cargo.toml +++ b/substrate/primitives/consensus/pow/Cargo.toml @@ -9,21 +9,18 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", 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 } -sp-std = { path = "../../std", default-features = false } +sp-api = { path = "../../api", default-features = false} +sp-core = { path = "../../core", default-features = false} +sp-runtime = { path = "../../runtime", default-features = false} +sp-std = { path = "../../std", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "sp-api/std", diff --git a/substrate/primitives/consensus/sassafras/Cargo.toml b/substrate/primitives/consensus/sassafras/Cargo.toml index 41385e9d1e9..696e0a64596 100644 --- a/substrate/primitives/consensus/sassafras/Cargo.toml +++ b/substrate/primitives/consensus/sassafras/Cargo.toml @@ -11,25 +11,22 @@ documentation = "https://docs.rs/sp-consensus-sassafras" readme = "README.md" publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] scale-codec = { package = "parity-scale-codec", version = "3.2.2", default-features = false } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, features = ["derive"], optional = 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-std = { path = "../../std", default-features = false } +serde = { version = "1.0.188", default-features = false, features = ["derive"], optional = true } +sp-api = { default-features = false, path = "../../api" } +sp-application-crypto = { default-features = false, path = "../../application-crypto", features = ["bandersnatch-experimental"] } +sp-consensus-slots = { default-features = false, path = "../slots" } +sp-core = { default-features = false, path = "../../core", features = ["bandersnatch-experimental"] } +sp-runtime = { default-features = false, path = "../../runtime" } +sp-std = { default-features = false, path = "../../std" } [features] -default = ["std"] +default = [ "std" ] std = [ "scale-codec/std", "scale-info/std", diff --git a/substrate/primitives/consensus/sassafras/README.md b/substrate/primitives/consensus/sassafras/README.md index d6251940a49..b0f3685494e 100644 --- a/substrate/primitives/consensus/sassafras/README.md +++ b/substrate/primitives/consensus/sassafras/README.md @@ -1,6 +1,12 @@ Primitives for SASSAFRAS. -- Tracking issue: https://github.com/paritytech/polkadot-sdk/issues/41 -- RFC proposal: https://github.com/polkadot-fellows/RFCs/pull/26 +# ⚠️ WARNING ⚠️ -Depends on `sp-core` feature: `bandersnatch-experimental`. +The crate interfaces and structures are highly experimental and may be subject +to significant changes. + +Depends on upstream experimental feature: `bandersnatch-experimental`. + +These structs were mostly extracted from the main SASSAFRAS protocol PR: https://github.com/paritytech/polkadot-sdk/pull/1336. + +Tracking issue: https://github.com/paritytech/polkadot-sdk/issues/41 diff --git a/substrate/primitives/consensus/sassafras/src/digests.rs b/substrate/primitives/consensus/sassafras/src/digests.rs index 5274f1309d8..95a305099de 100644 --- a/substrate/primitives/consensus/sassafras/src/digests.rs +++ b/substrate/primitives/consensus/sassafras/src/digests.rs @@ -48,11 +48,11 @@ pub struct SlotClaim { /// This is mandatory in the first block of each epoch. #[derive(Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)] pub struct NextEpochDescriptor { - /// Randomness value. - pub randomness: Randomness, /// Authorities list. pub authorities: Vec, - /// Epoch configuration. + /// Epoch randomness. + pub randomness: Randomness, + /// Epoch configurable parameters. /// /// If not present previous epoch parameters are used. pub config: Option, diff --git a/substrate/primitives/consensus/sassafras/src/lib.rs b/substrate/primitives/consensus/sassafras/src/lib.rs index 1752f765886..e421e771d40 100644 --- a/substrate/primitives/consensus/sassafras/src/lib.rs +++ b/substrate/primitives/consensus/sassafras/src/lib.rs @@ -80,43 +80,33 @@ pub type EquivocationProof = sp_consensus_slots::EquivocationProof, + /// Randomness for the epoch. + pub randomness: Randomness, /// Epoch configuration. pub config: EpochConfiguration, } diff --git a/substrate/primitives/consensus/sassafras/src/ticket.rs b/substrate/primitives/consensus/sassafras/src/ticket.rs index dc0a61990d3..d81770c96d9 100644 --- a/substrate/primitives/consensus/sassafras/src/ticket.rs +++ b/substrate/primitives/consensus/sassafras/src/ticket.rs @@ -62,10 +62,10 @@ pub struct TicketClaim { pub erased_signature: EphemeralSignature, } -/// Computes a boundary for [`TicketId`] maximum allowed value for a given epoch. +/// Computes ticket-id maximum allowed value for a given epoch. /// -/// Only ticket identifiers below this threshold should be considered as candidates -/// for slot assignment. +/// Only ticket identifiers below this threshold should be considered for slot +/// assignment. /// /// The value is computed as `TicketId::MAX*(redundancy*slots)/(attempts*validators)` /// @@ -76,51 +76,16 @@ pub struct TicketClaim { /// - `validators`: number of validators in epoch. /// /// If `attempts * validators = 0` then we return 0. -/// -/// For details about the formula and implications refer to -/// [*probabilities an parameters*](https://research.web3.foundation/Polkadot/protocols/block-production/SASSAFRAS#probabilities-and-parameters) -/// paragraph of the w3f introduction to the protocol. -// TODO: replace with [RFC-26](https://github.com/polkadot-fellows/RFCs/pull/26) -// "Tickets Threshold" paragraph once is merged pub fn ticket_id_threshold( redundancy: u32, slots: u32, attempts: u32, validators: u32, ) -> TicketId { - let num = redundancy as u64 * slots as u64; let den = attempts as u64 * validators as u64; + let num = redundancy as u64 * slots as u64; TicketId::max_value() .checked_div(den.into()) .unwrap_or_default() .saturating_mul(num.into()) } - -#[cfg(test)] -mod tests { - use super::*; - - // This is a trivial example/check which just better explain explains the rationale - // behind the threshold. - // - // After this reading the formula should become obvious. - #[test] - fn ticket_id_threshold_trivial_check() { - // For an epoch with `s` slots we want to accept a number of tickets equal to ~s·r - let redundancy = 2; - let slots = 1000; - let attempts = 100; - let validators = 500; - - let threshold = ticket_id_threshold(redundancy, slots, attempts, validators); - let threshold = threshold as f64 / TicketId::MAX as f64; - - // We expect that the total number of tickets allowed to be submited - // is slots*redundancy - let avt = ((attempts * validators) as f64 * threshold) as u32; - assert_eq!(avt, slots * redundancy); - - println!("threshold: {}", threshold); - println!("avt = {}", avt); - } -} diff --git a/substrate/primitives/consensus/sassafras/src/vrf.rs b/substrate/primitives/consensus/sassafras/src/vrf.rs index 5deacd8e994..d25a656f950 100644 --- a/substrate/primitives/consensus/sassafras/src/vrf.rs +++ b/substrate/primitives/consensus/sassafras/src/vrf.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Utilities related to VRF input, pre-output and signatures. +//! Utilities related to VRF input, output and signatures. use crate::{Randomness, TicketBody, TicketId}; use scale_codec::Encode; @@ -23,16 +23,10 @@ use sp_consensus_slots::Slot; use sp_std::vec::Vec; pub use sp_core::bandersnatch::{ - ring_vrf::{RingProver, RingVerifier, RingVerifierData, RingVrfSignature}, - vrf::{VrfInput, VrfPreOutput, VrfSignData, VrfSignature}, + ring_vrf::{RingContext, RingProver, RingVerifier, RingVrfSignature}, + vrf::{VrfInput, VrfOutput, VrfSignData, VrfSignature}, }; -/// Ring VRF domain size for Sassafras consensus. -pub const RING_VRF_DOMAIN_SIZE: u32 = 2048; - -/// Bandersnatch VRF [`RingContext`] specialization for Sassafras using [`RING_VRF_DOMAIN_SIZE`]. -pub type RingContext = sp_core::bandersnatch::ring_vrf::RingContext; - fn vrf_input_from_data( domain: &[u8], data: impl IntoIterator>, @@ -90,21 +84,21 @@ pub fn ticket_body_sign_data(ticket_body: &TicketBody, ticket_id_input: VrfInput ) } -/// Make ticket-id from the given VRF input and pre-output. +/// Make ticket-id from the given VRF input and output. /// /// Input should have been obtained via [`ticket_id_input`]. -/// Pre-output should have been obtained from the input directly using the vrf -/// secret key or from the vrf signature pre-outputs. -pub fn make_ticket_id(input: &VrfInput, pre_output: &VrfPreOutput) -> TicketId { - let bytes = pre_output.make_bytes::<16>(b"ticket-id", input); +/// Output should have been obtained from the input directly using the vrf secret key +/// or from the vrf signature outputs. +pub fn make_ticket_id(input: &VrfInput, output: &VrfOutput) -> TicketId { + let bytes = output.make_bytes::<16>(b"ticket-id", input); u128::from_le_bytes(bytes) } -/// Make revealed key seed from a given VRF input and pre-ouput. +/// Make revealed key seed from a given VRF input and ouput. /// /// Input should have been obtained via [`revealed_key_input`]. -/// Pre-output should have been obtained from the input directly using the vrf -/// secret key or from the vrf signature pre-outputs. -pub fn make_revealed_key_seed(input: &VrfInput, pre_output: &VrfPreOutput) -> [u8; 32] { - pre_output.make_bytes::<32>(b"revealed-seed", input) +/// Output should have been obtained from the input directly using the vrf secret key +/// or from the vrf signature outputs. +pub fn make_revealed_key_seed(input: &VrfInput, output: &VrfOutput) -> [u8; 32] { + output.make_bytes::<32>(b"revealed-seed", input) } diff --git a/substrate/primitives/consensus/slots/Cargo.toml b/substrate/primitives/consensus/slots/Cargo.toml index 91bbd1663a9..aa899d86e72 100644 --- a/substrate/primitives/consensus/slots/Cargo.toml +++ b/substrate/primitives/consensus/slots/Cargo.toml @@ -9,21 +9,18 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0", default-features = false, features = ["alloc", "derive"], optional = true } -sp-std = { path = "../../std", default-features = false } -sp-timestamp = { path = "../../timestamp", default-features = false } +serde = { version = "1.0", default-features = false, features = ["derive", "alloc"], optional = true } +sp-std = { path = "../../std", default-features = false} +sp-timestamp = { path = "../../timestamp", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "scale-info/std", @@ -33,4 +30,4 @@ std = [ ] # Serde support without relying on std features. -serde = ["dep:serde", "scale-info/serde"] +serde = [ "dep:serde", "scale-info/serde" ] diff --git a/substrate/primitives/core/Cargo.toml b/substrate/primitives/core/Cargo.toml index cb36d7bb6b4..34485c72ab0 100644 --- a/substrate/primitives/core/Cargo.toml +++ b/substrate/primitives/core/Cargo.toml @@ -9,34 +9,31 @@ repository.workspace = true description = "Shareable Substrate types." documentation = "https://docs.rs/sp-core" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive", "max-encoded-len"] } +codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive","max-encoded-len"] } scale-info = { version = "2.5.0", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } -serde = { version = "1.0.193", optional = true, default-features = false, features = ["alloc", "derive"] } +serde = { version = "1.0.188", optional = true, default-features = false, features = ["derive", "alloc"] } bounded-collections = { version = "0.1.8", 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 } +rand = { version = "0.8.5", features = ["small_rng"], optional = true } substrate-bip39 = { version = "0.4.4", optional = true } bip39 = { version = "2.0.0", default-features = false } zeroize = { version = "1.4.3", default-features = false } secrecy = { version = "0.8.0", default-features = false } 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 } +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} futures = { version = "0.3.21", optional = true } dyn-clonable = { version = "0.9.0", optional = true } thiserror = { version = "1.0.48", optional = true } @@ -52,14 +49,14 @@ blake2 = { version = "0.10.4", default-features = false, optional = true } libsecp256k1 = { version = "0.7", default-features = false, features = ["static-context"], optional = true } schnorrkel = { version = "0.9.1", features = ["preaudit_deprecated", "u64_backend"], default-features = false } merlin = { version = "2.0", default-features = false } -secp256k1 = { version = "0.28.0", default-features = false, features = ["alloc", "recovery"], optional = true } +secp256k1 = { version = "0.28.0", default-features = false, features = ["recovery", "alloc"], optional = true } sp-core-hashing = { path = "hashing", default-features = false, optional = true } -sp-runtime-interface = { path = "../runtime-interface", default-features = false } +sp-runtime-interface = { path = "../runtime-interface", default-features = false} # bls crypto -w3f-bls = { version = "0.1.3", default-features = false, optional = true } +w3f-bls = { version = "0.1.3", default-features = false, optional = true} # bandersnatch crypto -bandersnatch_vrfs = { git = "https://github.com/w3f/ring-vrf", rev = "e9782f9", default-features = false, features = ["substrate-curves"], optional = true } +bandersnatch_vrfs = { git = "https://github.com/w3f/ring-vrf", rev = "3ddc205", default-features = false, optional = true } [dev-dependencies] criterion = "0.4.0" @@ -76,7 +73,7 @@ harness = false bench = false [features] -default = ["std"] +default = [ "std" ] std = [ "array-bytes", "bandersnatch_vrfs?/std", @@ -156,9 +153,9 @@ full_crypto = [ # This feature adds BLS crypto primitives. # It should not be used in production since the implementation and interface may still # be subject to significant changes. -bls-experimental = ["w3f-bls"] +bls-experimental = [ "w3f-bls" ] # This feature adds Bandersnatch crypto primitives. # It should not be used in production since the implementation and interface may still # be subject to significant changes. -bandersnatch-experimental = ["bandersnatch_vrfs"] +bandersnatch-experimental = [ "bandersnatch_vrfs" ] diff --git a/substrate/primitives/core/fuzz/Cargo.toml b/substrate/primitives/core/fuzz/Cargo.toml index c6b5a065b6d..9a094b07d4a 100644 --- a/substrate/primitives/core/fuzz/Cargo.toml +++ b/substrate/primitives/core/fuzz/Cargo.toml @@ -3,9 +3,6 @@ name = "sp-core-fuzz" version = "0.0.0" publish = false -[lints] -workspace = true - [package.metadata] cargo-fuzz = true diff --git a/substrate/primitives/core/hashing/Cargo.toml b/substrate/primitives/core/hashing/Cargo.toml index 011d312ba90..bd22bd79e7d 100644 --- a/substrate/primitives/core/hashing/Cargo.toml +++ b/substrate/primitives/core/hashing/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Primitive core crate hashing implementation." documentation = "https://docs.rs/sp-core-hashing" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -24,7 +21,7 @@ sha3 = { version = "0.10.0", default-features = false } twox-hash = { version = "1.6.3", default-features = false, features = ["digest_0_10"] } [features] -default = ["std"] +default = [ "std" ] std = [ "blake2b_simd/std", "byteorder/std", diff --git a/substrate/primitives/core/hashing/proc-macro/Cargo.toml b/substrate/primitives/core/hashing/proc-macro/Cargo.toml index 312edd85044..187b5559b93 100644 --- a/substrate/primitives/core/hashing/proc-macro/Cargo.toml +++ b/substrate/primitives/core/hashing/proc-macro/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "This crate provides procedural macros for calculating static hash." documentation = "https://docs.rs/sp-core-hashing-proc-macro" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,5 +17,5 @@ proc-macro = true [dependencies] quote = "1.0.28" -syn = { version = "2.0.40", features = ["full", "parsing"] } -sp-core-hashing = { path = "..", default-features = false } +syn = { version = "2.0.38", features = ["full", "parsing"] } +sp-core-hashing = { path = "..", default-features = false} diff --git a/substrate/primitives/core/src/bandersnatch.rs b/substrate/primitives/core/src/bandersnatch.rs index 463d49fd889..78b7f12f9ff 100644 --- a/substrate/primitives/core/src/bandersnatch.rs +++ b/substrate/primitives/core/src/bandersnatch.rs @@ -20,17 +20,13 @@ //! //! The primitive can operate both as a regular VRF or as an anonymized Ring VRF. -#[cfg(feature = "serde")] +#[cfg(feature = "std")] use crate::crypto::Ss58Codec; use crate::crypto::{ ByteArray, CryptoType, CryptoTypeId, Derive, Public as TraitPublic, UncheckedFrom, VrfPublic, }; #[cfg(feature = "full_crypto")] use crate::crypto::{DeriveError, DeriveJunction, Pair as TraitPair, SecretStringError, VrfSecret}; -#[cfg(feature = "serde")] -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; -#[cfg(all(not(feature = "std"), feature = "serde"))] -use sp_std::alloc::{format, string::String}; use bandersnatch_vrfs::CanonicalSerialize; #[cfg(feature = "full_crypto")] @@ -39,7 +35,7 @@ use codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; use scale_info::TypeInfo; use sp_runtime_interface::pass_by::PassByInner; -use sp_std::{vec, vec::Vec}; +use sp_std::{boxed::Box, vec::Vec}; /// Identifier used to match public keys against bandersnatch-vrf keys. pub const CRYPTO_ID: CryptoTypeId = CryptoTypeId(*b"band"); @@ -48,12 +44,23 @@ pub const CRYPTO_ID: CryptoTypeId = CryptoTypeId(*b"band"); #[cfg(feature = "full_crypto")] pub const SIGNING_CTX: &[u8] = b"BandersnatchSigningContext"; +// Max ring domain size. +const RING_DOMAIN_SIZE: usize = 1024; + #[cfg(feature = "full_crypto")] -const SEED_SERIALIZED_SIZE: usize = 32; +const SEED_SERIALIZED_LEN: usize = 32; + +// Short-Weierstrass form serialized sizes. +const PUBLIC_SERIALIZED_LEN: usize = 33; +const SIGNATURE_SERIALIZED_LEN: usize = 65; +const RING_SIGNATURE_SERIALIZED_LEN: usize = 755; +const PREOUT_SERIALIZED_LEN: usize = 33; -const PUBLIC_SERIALIZED_SIZE: usize = 33; -const SIGNATURE_SERIALIZED_SIZE: usize = 65; -const PREOUT_SERIALIZED_SIZE: usize = 33; +// Max size of serialized ring-vrf context params. +// +// This size is dependent on the ring domain size and the actual value +// is equal to the SCALE encoded size of the `KZG` backend. +const RING_CONTEXT_SERIALIZED_LEN: usize = 147716; /// Bandersnatch public key. #[cfg_attr(feature = "full_crypto", derive(Hash))] @@ -70,16 +77,16 @@ const PREOUT_SERIALIZED_SIZE: usize = 33; MaxEncodedLen, TypeInfo, )] -pub struct Public(pub [u8; PUBLIC_SERIALIZED_SIZE]); +pub struct Public(pub [u8; PUBLIC_SERIALIZED_LEN]); -impl UncheckedFrom<[u8; PUBLIC_SERIALIZED_SIZE]> for Public { - fn unchecked_from(raw: [u8; PUBLIC_SERIALIZED_SIZE]) -> Self { +impl UncheckedFrom<[u8; PUBLIC_SERIALIZED_LEN]> for Public { + fn unchecked_from(raw: [u8; PUBLIC_SERIALIZED_LEN]) -> Self { Public(raw) } } -impl AsRef<[u8; PUBLIC_SERIALIZED_SIZE]> for Public { - fn as_ref(&self) -> &[u8; PUBLIC_SERIALIZED_SIZE] { +impl AsRef<[u8; PUBLIC_SERIALIZED_LEN]> for Public { + fn as_ref(&self) -> &[u8; PUBLIC_SERIALIZED_LEN] { &self.0 } } @@ -100,17 +107,17 @@ impl TryFrom<&[u8]> for Public { type Error = (); fn try_from(data: &[u8]) -> Result { - if data.len() != PUBLIC_SERIALIZED_SIZE { + if data.len() != PUBLIC_SERIALIZED_LEN { return Err(()) } - let mut r = [0u8; PUBLIC_SERIALIZED_SIZE]; + let mut r = [0u8; PUBLIC_SERIALIZED_LEN]; r.copy_from_slice(data); Ok(Self::unchecked_from(r)) } } impl ByteArray for Public { - const LEN: usize = PUBLIC_SERIALIZED_SIZE; + const LEN: usize = PUBLIC_SERIALIZED_LEN; } impl TraitPublic for Public {} @@ -135,31 +142,16 @@ impl sp_std::fmt::Debug for Public { } } -#[cfg(feature = "serde")] -impl Serialize for Public { - fn serialize(&self, serializer: S) -> Result { - serializer.serialize_str(&self.to_ss58check()) - } -} - -#[cfg(feature = "serde")] -impl<'de> Deserialize<'de> for Public { - fn deserialize>(deserializer: D) -> Result { - Public::from_ss58check(&String::deserialize(deserializer)?) - .map_err(|e| de::Error::custom(format!("{:?}", e))) - } -} - /// Bandersnatch signature. /// /// The signature is created via the [`VrfSecret::vrf_sign`] using [`SIGNING_CTX`] as transcript /// `label`. #[cfg_attr(feature = "full_crypto", derive(Hash))] #[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, PassByInner, MaxEncodedLen, TypeInfo)] -pub struct Signature([u8; SIGNATURE_SERIALIZED_SIZE]); +pub struct Signature([u8; SIGNATURE_SERIALIZED_LEN]); -impl UncheckedFrom<[u8; SIGNATURE_SERIALIZED_SIZE]> for Signature { - fn unchecked_from(raw: [u8; SIGNATURE_SERIALIZED_SIZE]) -> Self { +impl UncheckedFrom<[u8; SIGNATURE_SERIALIZED_LEN]> for Signature { + fn unchecked_from(raw: [u8; SIGNATURE_SERIALIZED_LEN]) -> Self { Signature(raw) } } @@ -180,17 +172,17 @@ impl TryFrom<&[u8]> for Signature { type Error = (); fn try_from(data: &[u8]) -> Result { - if data.len() != SIGNATURE_SERIALIZED_SIZE { + if data.len() != SIGNATURE_SERIALIZED_LEN { return Err(()) } - let mut r = [0u8; SIGNATURE_SERIALIZED_SIZE]; + let mut r = [0u8; SIGNATURE_SERIALIZED_LEN]; r.copy_from_slice(data); Ok(Self::unchecked_from(r)) } } impl ByteArray for Signature { - const LEN: usize = SIGNATURE_SERIALIZED_SIZE; + const LEN: usize = SIGNATURE_SERIALIZED_LEN; } impl CryptoType for Signature { @@ -212,7 +204,7 @@ impl sp_std::fmt::Debug for Signature { /// The raw secret seed, which can be used to reconstruct the secret [`Pair`]. #[cfg(feature = "full_crypto")] -type Seed = [u8; SEED_SERIALIZED_SIZE]; +type Seed = [u8; SEED_SERIALIZED_LEN]; /// Bandersnatch secret key. #[cfg(feature = "full_crypto")] @@ -240,10 +232,10 @@ impl TraitPair for Pair { /// /// The slice must be 32 bytes long or it will return an error. fn from_seed_slice(seed_slice: &[u8]) -> Result { - if seed_slice.len() != SEED_SERIALIZED_SIZE { + if seed_slice.len() != SEED_SERIALIZED_LEN { return Err(SecretStringError::InvalidSeedLength) } - let mut seed = [0; SEED_SERIALIZED_SIZE]; + let mut seed = [0; SEED_SERIALIZED_LEN]; seed.copy_from_slice(seed_slice); let secret = SecretKey::from_seed(&seed); Ok(Pair { secret, seed }) @@ -274,7 +266,7 @@ impl TraitPair for Pair { fn public(&self) -> Public { let public = self.secret.to_public(); - let mut raw = [0; PUBLIC_SERIALIZED_SIZE]; + let mut raw = [0; PUBLIC_SERIALIZED_LEN]; public .serialize_compressed(raw.as_mut_slice()) .expect("serialization length is constant and checked by test; qed"); @@ -295,7 +287,7 @@ impl TraitPair for Pair { fn verify>(signature: &Signature, data: M, public: &Public) -> bool { let data = vrf::VrfSignData::new_unchecked(SIGNING_CTX, &[data.as_ref()], None); let signature = - vrf::VrfSignature { signature: *signature, pre_outputs: vrf::VrfIosVec::default() }; + vrf::VrfSignature { signature: *signature, outputs: vrf::VrfIosVec::default() }; public.vrf_verify(&data, &signature) } @@ -319,18 +311,18 @@ pub mod vrf { ThinVrfSignature, Transcript, }; - /// Max number of inputs/pre-outputs which can be handled by the VRF signing procedures. + /// Max number of inputs/outputs which can be handled by the VRF signing procedures. /// /// The number is quite arbitrary and chosen to fulfill the use cases found so far. /// If required it can be extended in the future. pub const MAX_VRF_IOS: u32 = 3; - /// Bounded vector used for VRF inputs and pre-outputs. + /// Bounded vector used for VRF inputs and outputs. /// /// Can contain at most [`MAX_VRF_IOS`] elements. pub type VrfIosVec = BoundedVec>; - /// VRF input to construct a [`VrfPreOutput`] instance and embeddable in [`VrfSignData`]. + /// VRF input to construct a [`VrfOutput`] instance and embeddable in [`VrfSignData`]. #[derive(Clone, Debug)] pub struct VrfInput(pub(super) bandersnatch_vrfs::VrfInput); @@ -342,17 +334,17 @@ pub mod vrf { } } - /// VRF pre-output derived from [`VrfInput`] using a [`VrfSecret`]. + /// VRF (pre)output derived from [`VrfInput`] using a [`VrfSecret`]. /// /// This object is used to produce an arbitrary number of verifiable pseudo random /// bytes and is often called pre-output to emphasize that this is not the actual /// output of the VRF but an object capable of generating the output. #[derive(Clone, Debug, PartialEq, Eq)] - pub struct VrfPreOutput(pub(super) bandersnatch_vrfs::VrfPreOut); + pub struct VrfOutput(pub(super) bandersnatch_vrfs::VrfPreOut); - impl Encode for VrfPreOutput { + impl Encode for VrfOutput { fn encode(&self) -> Vec { - let mut bytes = [0; PREOUT_SERIALIZED_SIZE]; + let mut bytes = [0; PREOUT_SERIALIZED_LEN]; self.0 .serialize_compressed(bytes.as_mut_slice()) .expect("serialization length is constant and checked by test; qed"); @@ -360,26 +352,23 @@ pub mod vrf { } } - impl Decode for VrfPreOutput { + impl Decode for VrfOutput { fn decode(i: &mut R) -> Result { - let buf = <[u8; PREOUT_SERIALIZED_SIZE]>::decode(i)?; - let preout = - bandersnatch_vrfs::VrfPreOut::deserialize_compressed_unchecked(buf.as_slice()) - .map_err(|_| "vrf-preout decode error: bad preout")?; - Ok(VrfPreOutput(preout)) + let buf = <[u8; PREOUT_SERIALIZED_LEN]>::decode(i)?; + let preout = bandersnatch_vrfs::VrfPreOut::deserialize_compressed(buf.as_slice()) + .map_err(|_| "vrf-preout decode error: bad preout")?; + Ok(VrfOutput(preout)) } } - impl EncodeLike for VrfPreOutput {} - - impl MaxEncodedLen for VrfPreOutput { + impl MaxEncodedLen for VrfOutput { fn max_encoded_len() -> usize { - <[u8; PREOUT_SERIALIZED_SIZE]>::max_encoded_len() + <[u8; PREOUT_SERIALIZED_LEN]>::max_encoded_len() } } - impl TypeInfo for VrfPreOutput { - type Identity = [u8; PREOUT_SERIALIZED_SIZE]; + impl TypeInfo for VrfOutput { + type Identity = [u8; PREOUT_SERIALIZED_LEN]; fn type_info() -> scale_info::Type { Self::Identity::type_info() @@ -395,21 +384,21 @@ pub mod vrf { /// A good explaination of the topic can be found in Merlin [docs](https://merlin.cool/) /// /// The `inputs` is a sequence of [`VrfInput`]s which, during the signing procedure, are - /// first transformed to [`VrfPreOutput`]s. Both inputs and pre-outputs are then appended to + /// first transformed to [`VrfOutput`]s. Both inputs and outputs are then appended to /// the transcript before signing the Fiat-Shamir transform result (the challenge). /// /// In practice, as a user, all these technical details can be easily ignored. /// What is important to remember is: /// - *Transcript* is an object defining the protocol and used to produce the signature. This - /// object doesn't influence the `VrfPreOutput`s values. - /// - *Vrf inputs* is some additional data which is used to produce *vrf pre-outputs*. This data + /// object doesn't influence the `VrfOutput`s values. + /// - *Vrf inputs* is some additional data which is used to produce *vrf outputs*. This data /// will contribute to the signature as well. #[derive(Clone)] pub struct VrfSignData { - /// Associated protocol transcript. - pub transcript: Transcript, /// VRF inputs to be signed. pub inputs: VrfIosVec, + /// Associated protocol transcript. + pub transcript: Transcript, } impl VrfSignData { @@ -473,22 +462,22 @@ pub mod vrf { /// VRF signature. /// - /// Includes both the transcript `signature` and the `pre-outputs` generated from the + /// Includes both the transcript `signature` and the `outputs` generated from the /// [`VrfSignData::inputs`]. /// /// Refer to [`VrfSignData`] for more details. #[derive(Clone, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen, TypeInfo)] pub struct VrfSignature { + /// VRF (pre)outputs. + pub outputs: VrfIosVec, /// Transcript signature. pub signature: Signature, - /// VRF pre-outputs. - pub pre_outputs: VrfIosVec, } #[cfg(feature = "full_crypto")] impl VrfCrypto for Pair { type VrfInput = VrfInput; - type VrfPreOutput = VrfPreOutput; + type VrfOutput = VrfOutput; type VrfSignData = VrfSignData; type VrfSignature = VrfSignature; } @@ -507,15 +496,15 @@ pub mod vrf { } } - fn vrf_pre_output(&self, input: &Self::VrfInput) -> Self::VrfPreOutput { - let pre_output = self.secret.vrf_preout(&input.0); - VrfPreOutput(pre_output) + fn vrf_output(&self, input: &Self::VrfInput) -> Self::VrfOutput { + let output = self.secret.vrf_preout(&input.0); + VrfOutput(output) } } impl VrfCrypto for Public { type VrfInput = VrfInput; - type VrfPreOutput = VrfPreOutput; + type VrfOutput = VrfOutput; type VrfSignData = VrfSignData; type VrfSignature = VrfSignature; } @@ -523,12 +512,12 @@ pub mod vrf { impl VrfPublic for Public { fn vrf_verify(&self, data: &Self::VrfSignData, signature: &Self::VrfSignature) -> bool { const _: () = assert!(MAX_VRF_IOS == 3, "`MAX_VRF_IOS` expected to be 3"); - let pre_outputs_len = signature.pre_outputs.len(); - if pre_outputs_len != data.inputs.len() { + let outputs_len = signature.outputs.len(); + if outputs_len != data.inputs.len() { return false } // Workaround to overcome backend signature generic over the number of IOs. - match pre_outputs_len { + match outputs_len { 0 => self.vrf_verify_gen::<0>(data, signature), 1 => self.vrf_verify_gen::<1>(data, signature), 2 => self.vrf_verify_gen::<2>(data, signature), @@ -546,12 +535,11 @@ pub mod vrf { let thin_signature: ThinVrfSignature = self.secret.sign_thin_vrf(data.transcript.clone(), &ios); - let pre_outputs: Vec<_> = - thin_signature.preouts.into_iter().map(VrfPreOutput).collect(); - let pre_outputs = VrfIosVec::truncate_from(pre_outputs); + let outputs: Vec<_> = thin_signature.preouts.into_iter().map(VrfOutput).collect(); + let outputs = VrfIosVec::truncate_from(outputs); let mut signature = - VrfSignature { signature: Signature([0; SIGNATURE_SERIALIZED_SIZE]), pre_outputs }; + VrfSignature { signature: Signature([0; SIGNATURE_SERIALIZED_LEN]), outputs }; thin_signature .proof @@ -579,20 +567,20 @@ pub mod vrf { data: &VrfSignData, signature: &VrfSignature, ) -> bool { - let Ok(public) = PublicKey::deserialize_compressed_unchecked(self.as_slice()) else { + let Ok(public) = PublicKey::deserialize_compressed(self.as_slice()) else { return false }; let preouts: [bandersnatch_vrfs::VrfPreOut; N] = - core::array::from_fn(|i| signature.pre_outputs[i].0); + core::array::from_fn(|i| signature.outputs[i].0); // Deserialize only the proof, the rest has already been deserialized // This is another hack used because backend signature type is generic over // the number of ios. - let Ok(proof) = ThinVrfSignature::<0>::deserialize_compressed_unchecked( - signature.signature.as_ref(), - ) - .map(|s| s.proof) else { + let Ok(proof) = + ThinVrfSignature::<0>::deserialize_compressed(signature.signature.as_ref()) + .map(|s| s.proof) + else { return false }; let signature = ThinVrfSignature { proof, preouts }; @@ -603,7 +591,7 @@ pub mod vrf { } } - impl VrfPreOutput { + impl VrfOutput { /// Generate an arbitrary number of bytes from the given `context` and VRF `input`. pub fn make_bytes( &self, @@ -621,96 +609,16 @@ pub mod vrf { pub mod ring_vrf { use super::{vrf::*, *}; pub use bandersnatch_vrfs::ring::{RingProof, RingProver, RingVerifier, KZG}; - use bandersnatch_vrfs::{ring::VerifierKey, CanonicalDeserialize, PublicKey}; - - /// Overhead in the domain size with respect to the supported ring size. - /// - /// Some bits of the domain are reserved for the zk-proof to work. - pub const RING_DOMAIN_OVERHEAD: u32 = 257; - - // Max size of serialized ring-vrf context given `domain_len`. - pub(crate) const fn ring_context_serialized_size(domain_len: u32) -> usize { - // const G1_POINT_COMPRESSED_SIZE: usize = 48; - // const G2_POINT_COMPRESSED_SIZE: usize = 96; - const G1_POINT_UNCOMPRESSED_SIZE: usize = 96; - const G2_POINT_UNCOMPRESSED_SIZE: usize = 192; - const OVERHEAD_SIZE: usize = 20; - const G2_POINTS_NUM: usize = 2; - let g1_points_num = 3 * domain_len as usize + 1; - - OVERHEAD_SIZE + - g1_points_num * G1_POINT_UNCOMPRESSED_SIZE + - G2_POINTS_NUM * G2_POINT_UNCOMPRESSED_SIZE - } - - pub(crate) const RING_VERIFIER_DATA_SERIALIZED_SIZE: usize = 388; - pub(crate) const RING_SIGNATURE_SERIALIZED_SIZE: usize = 755; - - /// remove as soon as soon as serialization is implemented by the backend - pub struct RingVerifierData { - /// Domain size. - pub domain_size: u32, - /// Verifier key. - pub verifier_key: VerifierKey, - } - - impl From for RingVerifier { - fn from(vd: RingVerifierData) -> RingVerifier { - bandersnatch_vrfs::ring::make_ring_verifier(vd.verifier_key, vd.domain_size as usize) - } - } - - impl Encode for RingVerifierData { - fn encode(&self) -> Vec { - const ERR_STR: &str = "serialization length is constant and checked by test; qed"; - let mut buf = [0; RING_VERIFIER_DATA_SERIALIZED_SIZE]; - self.domain_size.serialize_compressed(&mut buf[..4]).expect(ERR_STR); - self.verifier_key.serialize_compressed(&mut buf[4..]).expect(ERR_STR); - buf.encode() - } - } - - impl Decode for RingVerifierData { - fn decode(i: &mut R) -> Result { - const ERR_STR: &str = "serialization length is constant and checked by test; qed"; - let buf = <[u8; RING_VERIFIER_DATA_SERIALIZED_SIZE]>::decode(i)?; - let domain_size = - ::deserialize_compressed_unchecked(&mut &buf[..4]) - .expect(ERR_STR); - let verifier_key = ::deserialize_compressed_unchecked(&mut &buf[4..]).expect(ERR_STR); - - Ok(RingVerifierData { domain_size, verifier_key }) - } - } - - impl EncodeLike for RingVerifierData {} - - impl MaxEncodedLen for RingVerifierData { - fn max_encoded_len() -> usize { - <[u8; RING_VERIFIER_DATA_SERIALIZED_SIZE]>::max_encoded_len() - } - } - - impl TypeInfo for RingVerifierData { - type Identity = [u8; RING_VERIFIER_DATA_SERIALIZED_SIZE]; + use bandersnatch_vrfs::{CanonicalDeserialize, PublicKey}; - fn type_info() -> scale_info::Type { - Self::Identity::type_info() - } - } - - /// Context used to construct ring prover and verifier. - /// - /// Generic parameter `D` represents the ring domain size and drives - /// the max number of supported ring members [`RingContext::max_keyset_size`] - /// which is equal to `D - RING_DOMAIN_OVERHEAD`. + /// Context used to produce ring signatures. #[derive(Clone)] - pub struct RingContext(KZG); + pub struct RingContext(KZG); - impl RingContext { - /// Build an dummy instance for testing purposes. + impl RingContext { + /// Build an dummy instance used for testing purposes. pub fn new_testing() -> Self { - Self(KZG::testing_kzg_setup([0; 32], D)) + Self(KZG::testing_kzg_setup([0; 32], RING_DOMAIN_SIZE as u32)) } /// Get the keyset max size. @@ -722,7 +630,7 @@ pub mod ring_vrf { pub fn prover(&self, public_keys: &[Public], public_idx: usize) -> Option { let mut pks = Vec::with_capacity(public_keys.len()); for public_key in public_keys { - let pk = PublicKey::deserialize_compressed_unchecked(public_key.as_slice()).ok()?; + let pk = PublicKey::deserialize_compressed(public_key.as_slice()).ok()?; pks.push(pk.0.into()); } @@ -735,7 +643,7 @@ pub mod ring_vrf { pub fn verifier(&self, public_keys: &[Public]) -> Option { let mut pks = Vec::with_capacity(public_keys.len()); for public_key in public_keys { - let pk = PublicKey::deserialize_compressed_unchecked(public_key.as_slice()).ok()?; + let pk = PublicKey::deserialize_compressed(public_key.as_slice()).ok()?; pks.push(pk.0.into()); } @@ -743,70 +651,50 @@ pub mod ring_vrf { let ring_verifier = self.0.init_ring_verifier(verifier_key); Some(ring_verifier) } - - /// Information required for a lazy construction of a ring verifier. - pub fn verifier_data(&self, public_keys: &[Public]) -> Option { - let mut pks = Vec::with_capacity(public_keys.len()); - for public_key in public_keys { - let pk = PublicKey::deserialize_compressed_unchecked(public_key.as_slice()).ok()?; - pks.push(pk.0.into()); - } - Some(RingVerifierData { - verifier_key: self.0.verifier_key(pks), - domain_size: self.0.domain_size, - }) - } } - impl Encode for RingContext { + impl Encode for RingContext { fn encode(&self) -> Vec { - let mut buf = vec![0; ring_context_serialized_size(D)]; + let mut buf = Box::new([0; RING_CONTEXT_SERIALIZED_LEN]); self.0 - .serialize_uncompressed(buf.as_mut_slice()) + .serialize_compressed(buf.as_mut_slice()) .expect("serialization length is constant and checked by test; qed"); - buf + buf.encode() } } - impl Decode for RingContext { - fn decode(input: &mut R) -> Result { - let mut buf = vec![0; ring_context_serialized_size(D)]; - input.read(&mut buf[..])?; - let kzg = KZG::deserialize_uncompressed_unchecked(buf.as_slice()) - .map_err(|_| "KZG decode error")?; + impl Decode for RingContext { + fn decode(i: &mut R) -> Result { + let buf = >::decode(i)?; + let kzg = + KZG::deserialize_compressed(buf.as_slice()).map_err(|_| "KZG decode error")?; Ok(RingContext(kzg)) } } - impl EncodeLike for RingContext {} + impl EncodeLike for RingContext {} - impl MaxEncodedLen for RingContext { + impl MaxEncodedLen for RingContext { fn max_encoded_len() -> usize { - ring_context_serialized_size(D) + <[u8; RING_CONTEXT_SERIALIZED_LEN]>::max_encoded_len() } } - impl TypeInfo for RingContext { - type Identity = Self; + impl TypeInfo for RingContext { + type Identity = [u8; RING_CONTEXT_SERIALIZED_LEN]; fn type_info() -> scale_info::Type { - let path = scale_info::Path::new("RingContext", module_path!()); - let array_type_def = scale_info::TypeDefArray { - len: ring_context_serialized_size(D) as u32, - type_param: scale_info::MetaType::new::(), - }; - let type_def = scale_info::TypeDef::Array(array_type_def); - scale_info::Type { path, type_params: Vec::new(), type_def, docs: Vec::new() } + Self::Identity::type_info() } } /// Ring VRF signature. #[derive(Clone, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen, TypeInfo)] pub struct RingVrfSignature { + /// VRF (pre)outputs. + pub outputs: VrfIosVec, /// Ring signature. - pub signature: [u8; RING_SIGNATURE_SERIALIZED_SIZE], - /// VRF pre-outputs. - pub pre_outputs: VrfIosVec, + pub signature: [u8; RING_SIGNATURE_SERIALIZED_LEN], } #[cfg(feature = "full_crypto")] @@ -839,12 +727,11 @@ pub mod ring_vrf { bandersnatch_vrfs::RingProver { ring_prover: prover, secret: &self.secret } .sign_ring_vrf(data.transcript.clone(), &ios); - let pre_outputs: Vec<_> = - ring_signature.preouts.into_iter().map(VrfPreOutput).collect(); - let pre_outputs = VrfIosVec::truncate_from(pre_outputs); + let outputs: Vec<_> = ring_signature.preouts.into_iter().map(VrfOutput).collect(); + let outputs = VrfIosVec::truncate_from(outputs); let mut signature = - RingVrfSignature { pre_outputs, signature: [0; RING_SIGNATURE_SERIALIZED_SIZE] }; + RingVrfSignature { outputs, signature: [0; RING_SIGNATURE_SERIALIZED_LEN] }; ring_signature .proof @@ -862,7 +749,7 @@ pub mod ring_vrf { /// from which the [`RingVerifier`] has been constructed. pub fn ring_vrf_verify(&self, data: &VrfSignData, verifier: &RingVerifier) -> bool { const _: () = assert!(MAX_VRF_IOS == 3, "`MAX_VRF_IOS` expected to be 3"); - let preouts_len = self.pre_outputs.len(); + let preouts_len = self.outputs.len(); if preouts_len != data.inputs.len() { return false } @@ -882,7 +769,7 @@ pub mod ring_vrf { verifier: &RingVerifier, ) -> bool { let Ok(vrf_signature) = - bandersnatch_vrfs::RingVrfSignature::<0>::deserialize_compressed_unchecked( + bandersnatch_vrfs::RingVrfSignature::<0>::deserialize_compressed( self.signature.as_slice(), ) else { @@ -890,7 +777,7 @@ pub mod ring_vrf { }; let preouts: [bandersnatch_vrfs::VrfPreOut; N] = - core::array::from_fn(|i| self.pre_outputs[i].0); + core::array::from_fn(|i| self.outputs[i].0); let signature = bandersnatch_vrfs::RingVrfSignature { proof: vrf_signature.proof, preouts }; @@ -908,11 +795,7 @@ pub mod ring_vrf { mod tests { use super::{ring_vrf::*, vrf::*, *}; use crate::crypto::{VrfPublic, VrfSecret, DEV_PHRASE}; - - const DEV_SEED: &[u8; SEED_SERIALIZED_SIZE] = &[0xcb; SEED_SERIALIZED_SIZE]; - const TEST_DOMAIN_SIZE: u32 = 1024; - - type TestRingContext = RingContext; + const DEV_SEED: &[u8; SEED_SERIALIZED_LEN] = &[0xcb; SEED_SERIALIZED_LEN]; #[allow(unused)] fn b2h(bytes: &[u8]) -> String { @@ -925,10 +808,9 @@ mod tests { #[test] fn backend_assumptions_sanity_check() { - let kzg = KZG::testing_kzg_setup([0; 32], TEST_DOMAIN_SIZE); - assert_eq!(kzg.max_keyset_size() as u32, TEST_DOMAIN_SIZE - RING_DOMAIN_OVERHEAD); - - assert_eq!(kzg.uncompressed_size(), ring_context_serialized_size(TEST_DOMAIN_SIZE)); + let kzg = KZG::testing_kzg_setup([0; 32], RING_DOMAIN_SIZE as u32); + assert_eq!(kzg.max_keyset_size(), RING_DOMAIN_SIZE - 257); + assert_eq!(kzg.compressed_size(), RING_CONTEXT_SERIALIZED_LEN); let pks: Vec<_> = (0..16) .map(|i| SecretKey::from_seed(&[i as u8; 32]).to_public().0.into()) @@ -937,14 +819,11 @@ mod tests { let secret = SecretKey::from_seed(&[0u8; 32]); let public = secret.to_public(); - assert_eq!(public.compressed_size(), PUBLIC_SERIALIZED_SIZE); + assert_eq!(public.compressed_size(), PUBLIC_SERIALIZED_LEN); let input = VrfInput::new(b"foo", &[]); let preout = secret.vrf_preout(&input.0); - assert_eq!(preout.compressed_size(), PREOUT_SERIALIZED_SIZE); - - let verifier_key = kzg.verifier_key(pks.clone()); - assert_eq!(verifier_key.compressed_size() + 4, RING_VERIFIER_DATA_SERIALIZED_SIZE); + assert_eq!(preout.compressed_size(), PREOUT_SERIALIZED_LEN); let prover_key = kzg.prover_key(pks); let ring_prover = kzg.init_ring_prover(prover_key, 0); @@ -953,12 +832,12 @@ mod tests { let thin_signature: bandersnatch_vrfs::ThinVrfSignature<0> = secret.sign_thin_vrf(data.transcript.clone(), &[]); - assert_eq!(thin_signature.compressed_size(), SIGNATURE_SERIALIZED_SIZE); + assert_eq!(thin_signature.compressed_size(), SIGNATURE_SERIALIZED_LEN); let ring_signature: bandersnatch_vrfs::RingVrfSignature<0> = bandersnatch_vrfs::RingProver { ring_prover: &ring_prover, secret: &secret } .sign_ring_vrf(data.transcript.clone(), &[]); - assert_eq!(ring_signature.compressed_size(), RING_SIGNATURE_SERIALIZED_SIZE); + assert_eq!(ring_signature.compressed_size(), RING_SIGNATURE_SERIALIZED_LEN); } #[test] @@ -1040,11 +919,11 @@ mod tests { let signature = pair.vrf_sign(&data); let o10 = pair.make_bytes::<32>(b"ctx1", &i1); - let o11 = signature.pre_outputs[0].make_bytes::<32>(b"ctx1", &i1); + let o11 = signature.outputs[0].make_bytes::<32>(b"ctx1", &i1); assert_eq!(o10, o11); let o20 = pair.make_bytes::<48>(b"ctx2", &i2); - let o21 = signature.pre_outputs[1].make_bytes::<48>(b"ctx2", &i2); + let o21 = signature.outputs[1].make_bytes::<48>(b"ctx2", &i2); assert_eq!(o20, o21); } @@ -1062,8 +941,7 @@ mod tests { let bytes = expected.encode(); - let expected_len = - data.inputs.len() * PREOUT_SERIALIZED_SIZE + SIGNATURE_SERIALIZED_SIZE + 1; + let expected_len = data.inputs.len() * PREOUT_SERIALIZED_LEN + SIGNATURE_SERIALIZED_LEN + 1; assert_eq!(bytes.len(), expected_len); let decoded = VrfSignature::decode(&mut bytes.as_slice()).unwrap(); @@ -1080,7 +958,7 @@ mod tests { #[test] fn ring_vrf_sign_verify() { - let ring_ctx = TestRingContext::new_testing(); + let ring_ctx = RingContext::new_testing(); let mut pks: Vec<_> = (0..16).map(|i| Pair::from_seed(&[i as u8; 32]).public()).collect(); assert!(pks.len() <= ring_ctx.max_keyset_size()); @@ -1106,7 +984,7 @@ mod tests { #[test] fn ring_vrf_sign_verify_with_out_of_ring_key() { - let ring_ctx = TestRingContext::new_testing(); + let ring_ctx = RingContext::new_testing(); let pks: Vec<_> = (0..16).map(|i| Pair::from_seed(&[i as u8; 32]).public()).collect(); let pair = Pair::from_seed(DEV_SEED); @@ -1125,7 +1003,7 @@ mod tests { #[test] fn ring_vrf_make_bytes_matches() { - let ring_ctx = TestRingContext::new_testing(); + let ring_ctx = RingContext::new_testing(); let mut pks: Vec<_> = (0..16).map(|i| Pair::from_seed(&[i as u8; 32]).public()).collect(); assert!(pks.len() <= ring_ctx.max_keyset_size()); @@ -1144,17 +1022,17 @@ mod tests { let signature = pair.ring_vrf_sign(&data, &prover); let o10 = pair.make_bytes::<32>(b"ctx1", &i1); - let o11 = signature.pre_outputs[0].make_bytes::<32>(b"ctx1", &i1); + let o11 = signature.outputs[0].make_bytes::<32>(b"ctx1", &i1); assert_eq!(o10, o11); let o20 = pair.make_bytes::<48>(b"ctx2", &i2); - let o21 = signature.pre_outputs[1].make_bytes::<48>(b"ctx2", &i2); + let o21 = signature.outputs[1].make_bytes::<48>(b"ctx2", &i2); assert_eq!(o20, o21); } #[test] fn encode_decode_ring_vrf_signature() { - let ring_ctx = TestRingContext::new_testing(); + let ring_ctx = RingContext::new_testing(); let mut pks: Vec<_> = (0..16).map(|i| Pair::from_seed(&[i as u8; 32]).public()).collect(); assert!(pks.len() <= ring_ctx.max_keyset_size()); @@ -1177,7 +1055,7 @@ mod tests { let bytes = expected.encode(); let expected_len = - data.inputs.len() * PREOUT_SERIALIZED_SIZE + RING_SIGNATURE_SERIALIZED_SIZE + 1; + data.inputs.len() * PREOUT_SERIALIZED_LEN + RING_SIGNATURE_SERIALIZED_LEN + 1; assert_eq!(bytes.len(), expected_len); let decoded = RingVrfSignature::decode(&mut bytes.as_slice()).unwrap(); @@ -1186,36 +1064,14 @@ mod tests { #[test] fn encode_decode_ring_vrf_context() { - let ctx1 = TestRingContext::new_testing(); + let ctx1 = RingContext::new_testing(); let enc1 = ctx1.encode(); - let _ti = ::type_info(); - - assert_eq!(enc1.len(), ring_context_serialized_size(TEST_DOMAIN_SIZE)); - assert_eq!(enc1.len(), TestRingContext::max_encoded_len()); + assert_eq!(enc1.len(), RingContext::max_encoded_len()); - let ctx2 = TestRingContext::decode(&mut enc1.as_slice()).unwrap(); + let ctx2 = RingContext::decode(&mut enc1.as_slice()).unwrap(); let enc2 = ctx2.encode(); assert_eq!(enc1, enc2); } - - #[test] - fn encode_decode_verifier_data() { - let ring_ctx = TestRingContext::new_testing(); - - let pks: Vec<_> = (0..16).map(|i| Pair::from_seed(&[i as u8; 32]).public()).collect(); - assert!(pks.len() <= ring_ctx.max_keyset_size()); - - let verifier_data = ring_ctx.verifier_data(&pks).unwrap(); - let enc1 = verifier_data.encode(); - - assert_eq!(enc1.len(), RING_VERIFIER_DATA_SERIALIZED_SIZE); - assert_eq!(RingVerifierData::max_encoded_len(), RING_VERIFIER_DATA_SERIALIZED_SIZE); - - let vd2 = RingVerifierData::decode(&mut enc1.as_slice()).unwrap(); - let enc2 = vd2.encode(); - - assert_eq!(enc1, enc2); - } } diff --git a/substrate/primitives/core/src/const_hex2array.rs b/substrate/primitives/core/src/const_hex2array.rs deleted file mode 100644 index cd6071028e6..00000000000 --- a/substrate/primitives/core/src/const_hex2array.rs +++ /dev/null @@ -1,162 +0,0 @@ -// 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. - -//! Provides a const function for converting a hex string to a `u8` array at compile time, when used -//! in the proper context. - -/// Provides a const array from given string literal. -/// -/// Valid characters are `[0-9a-fA-F]`, and the hex string should not start -/// with the `0x` prefix. -#[macro_export] -macro_rules! hex2array { - ($input:expr) => {{ - const BYTES: [u8; $input.len() / 2] = $crate::const_hex2array::private_hex2array($input); - BYTES - }}; -} - -/// Generates array from (static) string literal. -/// -/// Valid characters are `[0-9a-fA-F]`, and the hex string should not start -/// with the `0x` prefix. -/// -/// # Panics -/// -/// The function will panic at compile time when used in a const context if: -/// - The given hex string has an invalid length. -/// - It contains invalid characters. -/// -/// The function will panic at runtime when used in a non-const context if the above conditions are -/// met. -#[doc(hidden)] -pub const fn private_hex2array(hex: &str) -> [u8; N] { - const fn c2b(c: u8) -> u8 { - match c as char { - '0'..='9' => c - b'0', - 'a'..='f' => c - (b'a' - 10), - 'A'..='F' => c - (b'A' - 10), - _ => panic!("hex string contains invalid character"), - } - } - let mut output = [0; N]; - let mut i = 0; - if hex.len() != 2 * N { - panic!("hex string length is not valid"); - } - while i < N { - output[i] = 16 * c2b(hex.as_bytes()[2 * i]) + c2b(hex.as_bytes()[2 * i + 1]); - i += 1; - } - output -} - -#[cfg(test)] -mod testh2b { - use super::private_hex2array; - - #[test] - fn t00() { - const T0: [u8; 0] = private_hex2array(""); - const EMPTY: [u8; 0] = []; - assert_eq!(T0, EMPTY); - } - - macro_rules! test_byte { - ($a:expr, $b:expr) => {{ - const X: [u8; 1] = private_hex2array($a); - assert_eq!(X, [$b]); - }}; - } - - #[test] - fn t01() { - test_byte!("00", 0); - test_byte!("01", 1); - test_byte!("02", 2); - test_byte!("03", 3); - test_byte!("04", 4); - test_byte!("05", 5); - test_byte!("06", 6); - test_byte!("07", 7); - test_byte!("08", 8); - test_byte!("09", 9); - test_byte!("0a", 10); - test_byte!("0A", 10); - test_byte!("0b", 11); - test_byte!("0B", 11); - test_byte!("0c", 12); - test_byte!("0C", 12); - test_byte!("0d", 13); - test_byte!("0D", 13); - test_byte!("0e", 14); - test_byte!("0E", 14); - test_byte!("0f", 15); - test_byte!("0F", 15); - } - - #[test] - fn t02() { - const T0: [u8; 2] = private_hex2array("0a10"); - assert_eq!(T0, [10, 16]); - const T1: [u8; 2] = private_hex2array("4545"); - assert_eq!(T1, [69, 69]); - } - - #[test] - fn t02m() { - assert_eq!(hex2array!("0a10"), [10, 16]); - assert_eq!(hex2array!("4545"), [69, 69]); - assert_eq!( - hex2array!("000102030405060708090a0b0c0d0e0f"), - [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] - ); - } - - #[test] - fn t16() { - const T16: [u8; 16] = private_hex2array("000102030405060708090a0b0c0d0e0f"); - - assert_eq!(T16, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); - } - - #[test] - fn t33() { - const T33: [u8; 33] = - private_hex2array("9c8af77d3a4e3f6f076853922985b9e6724fc9675329087f47aff1ceaaae772180"); - - assert_eq!( - T33, - [ - 156, 138, 247, 125, 58, 78, 63, 111, 7, 104, 83, 146, 41, 133, 185, 230, 114, 79, - 201, 103, 83, 41, 8, 127, 71, 175, 241, 206, 170, 174, 119, 33, 128 - ] - ); - } - - #[test] - #[should_panic = "hex string length is not valid"] - fn t_panic_incorrect_length2() { - let _ = private_hex2array::<2>("454"); - } - - #[test] - #[should_panic = "hex string contains invalid character"] - fn t_panic_invalid_character() { - let _ = private_hex2array::<2>("45ag"); - } -} diff --git a/substrate/primitives/core/src/crypto.rs b/substrate/primitives/core/src/crypto.rs index 2da38d44be4..211ddc2aba0 100644 --- a/substrate/primitives/core/src/crypto.rs +++ b/substrate/primitives/core/src/crypto.rs @@ -1109,8 +1109,8 @@ impl<'a> TryFrom<&'a str> for KeyTypeId { pub trait VrfCrypto { /// VRF input. type VrfInput; - /// VRF pre-output. - type VrfPreOutput; + /// VRF output. + type VrfOutput; /// VRF signing data. type VrfSignData; /// VRF signature. @@ -1119,8 +1119,8 @@ pub trait VrfCrypto { /// VRF Secret Key. pub trait VrfSecret: VrfCrypto { - /// Get VRF-specific pre-output. - fn vrf_pre_output(&self, data: &Self::VrfInput) -> Self::VrfPreOutput; + /// Get VRF-specific output . + fn vrf_output(&self, data: &Self::VrfInput) -> Self::VrfOutput; /// Sign VRF-specific data. fn vrf_sign(&self, input: &Self::VrfSignData) -> Self::VrfSignature; diff --git a/substrate/primitives/core/src/lib.rs b/substrate/primitives/core/src/lib.rs index c7232563cb7..4873d1a2112 100644 --- a/substrate/primitives/core/src/lib.rs +++ b/substrate/primitives/core/src/lib.rs @@ -51,7 +51,6 @@ pub mod hashing; #[cfg(feature = "full_crypto")] pub use hashing::{blake2_128, blake2_256, keccak_256, twox_128, twox_256, twox_64}; -pub mod const_hex2array; pub mod crypto; pub mod hexdisplay; pub use paste; diff --git a/substrate/primitives/core/src/sr25519.rs b/substrate/primitives/core/src/sr25519.rs index 71d9c3b3247..ffa52ef97d1 100644 --- a/substrate/primitives/core/src/sr25519.rs +++ b/substrate/primitives/core/src/sr25519.rs @@ -628,36 +628,36 @@ pub mod vrf { /// VRF signature data #[derive(Clone, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen, TypeInfo)] pub struct VrfSignature { - /// VRF pre-output. - pub pre_output: VrfPreOutput, + /// VRF output. + pub output: VrfOutput, /// VRF proof. pub proof: VrfProof, } - /// VRF pre-output type suitable for schnorrkel operations. + /// VRF output type suitable for schnorrkel operations. #[derive(Clone, Debug, PartialEq, Eq)] - pub struct VrfPreOutput(pub schnorrkel::vrf::VRFOutput); + pub struct VrfOutput(pub schnorrkel::vrf::VRFOutput); - impl Encode for VrfPreOutput { + impl Encode for VrfOutput { fn encode(&self) -> Vec { self.0.as_bytes().encode() } } - impl Decode for VrfPreOutput { + impl Decode for VrfOutput { fn decode(i: &mut R) -> Result { let decoded = <[u8; VRF_OUTPUT_LENGTH]>::decode(i)?; Ok(Self(schnorrkel::vrf::VRFOutput::from_bytes(&decoded).map_err(convert_error)?)) } } - impl MaxEncodedLen for VrfPreOutput { + impl MaxEncodedLen for VrfOutput { fn max_encoded_len() -> usize { <[u8; VRF_OUTPUT_LENGTH]>::max_encoded_len() } } - impl TypeInfo for VrfPreOutput { + impl TypeInfo for VrfOutput { type Identity = [u8; VRF_OUTPUT_LENGTH]; fn type_info() -> scale_info::Type { @@ -699,7 +699,7 @@ pub mod vrf { #[cfg(feature = "full_crypto")] impl VrfCrypto for Pair { type VrfInput = VrfTranscript; - type VrfPreOutput = VrfPreOutput; + type VrfOutput = VrfOutput; type VrfSignData = VrfSignData; type VrfSignature = VrfSignature; } @@ -717,18 +717,18 @@ pub mod vrf { let proof = self.0.dleq_proove(extra, &inout, true).0; - VrfSignature { pre_output: VrfPreOutput(inout.to_output()), proof: VrfProof(proof) } + VrfSignature { output: VrfOutput(inout.to_output()), proof: VrfProof(proof) } } - fn vrf_pre_output(&self, input: &Self::VrfInput) -> Self::VrfPreOutput { - let pre_output = self.0.vrf_create_hash(input.0.clone()).to_output(); - VrfPreOutput(pre_output) + fn vrf_output(&self, input: &Self::VrfInput) -> Self::VrfOutput { + let output = self.0.vrf_create_hash(input.0.clone()).to_output(); + VrfOutput(output) } } impl VrfCrypto for Public { type VrfInput = VrfTranscript; - type VrfPreOutput = VrfPreOutput; + type VrfOutput = VrfOutput; type VrfSignData = VrfSignData; type VrfSignature = VrfSignature; } @@ -739,7 +739,7 @@ pub mod vrf { let public = schnorrkel::PublicKey::from_bytes(self)?; let inout = - signature.pre_output.0.attach_input_hash(&public, data.transcript.0.clone())?; + signature.output.0.attach_input_hash(&public, data.transcript.0.clone())?; let extra = data .extra @@ -802,21 +802,19 @@ pub mod vrf { &self, context: &[u8], input: &VrfInput, - pre_output: &VrfPreOutput, + output: &VrfOutput, ) -> Result<[u8; N], codec::Error> where [u8; N]: Default, { let pubkey = schnorrkel::PublicKey::from_bytes(&self.0).map_err(convert_error)?; - let inout = pre_output - .0 - .attach_input_hash(&pubkey, input.0.clone()) - .map_err(convert_error)?; + let inout = + output.0.attach_input_hash(&pubkey, input.0.clone()).map_err(convert_error)?; Ok(inout.make_bytes::<[u8; N]>(context)) } } - impl VrfPreOutput { + impl VrfOutput { /// Generate output bytes from the given VRF configuration. pub fn make_bytes( &self, @@ -1099,10 +1097,10 @@ mod tests { let input = VrfTranscript::new(b"label", &[(b"domain1", b"data1")]); - let pre_output = pair.vrf_pre_output(&input); + let output = pair.vrf_output(&input); let out1 = pair.make_bytes::<32>(ctx, &input); - let out2 = pre_output.make_bytes::<32>(ctx, &input, &public).unwrap(); + let out2 = output.make_bytes::<32>(ctx, &input, &public).unwrap(); assert_eq!(out1, out2); let extra = VrfTranscript::new(b"extra", &[(b"domain2", b"data2")]); @@ -1110,7 +1108,7 @@ mod tests { let signature = pair.vrf_sign(&data); assert!(public.vrf_verify(&data, &signature)); - let out3 = public.make_bytes::<32>(ctx, &input, &signature.pre_output).unwrap(); + let out3 = public.make_bytes::<32>(ctx, &input, &signature.output).unwrap(); assert_eq!(out2, out3); } @@ -1128,7 +1126,7 @@ mod tests { assert!(public.vrf_verify(&data, &signature)); let out1 = pair.make_bytes::<32>(ctx, &input); - let out2 = public.make_bytes::<32>(ctx, &input, &signature.pre_output).unwrap(); + let out2 = public.make_bytes::<32>(ctx, &input, &signature.output).unwrap(); assert_eq!(out1, out2); // Direct call to backend version of sign after check with extra params @@ -1141,9 +1139,9 @@ mod tests { }) .unwrap(); let signature2 = - VrfSignature { pre_output: VrfPreOutput(inout.to_output()), proof: VrfProof(proof) }; + VrfSignature { output: VrfOutput(inout.to_output()), proof: VrfProof(proof) }; assert!(public.vrf_verify(&data, &signature2)); - assert_eq!(signature.pre_output, signature2.pre_output); + assert_eq!(signature.output, signature2.output); } } diff --git a/substrate/primitives/core/src/traits.rs b/substrate/primitives/core/src/traits.rs index 851d8910391..9815c84f339 100644 --- a/substrate/primitives/core/src/traits.rs +++ b/substrate/primitives/core/src/traits.rs @@ -51,6 +51,7 @@ pub trait CodeExecutor: Sized + Send + Sync + ReadRuntimeVersion + Clone + 'stat runtime_code: &RuntimeCode, method: &str, data: &[u8], + use_native: bool, context: CallContext, ) -> (Result, Self::Error>, bool); } diff --git a/substrate/primitives/crypto/ec-utils/Cargo.toml b/substrate/primitives/crypto/ec-utils/Cargo.toml index 3baa8ea5b78..1484406e7b2 100644 --- a/substrate/primitives/crypto/ec-utils/Cargo.toml +++ b/substrate/primitives/crypto/ec-utils/Cargo.toml @@ -8,9 +8,6 @@ license = "Apache-2.0" homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -26,12 +23,12 @@ ark-ed-on-bls12-381-bandersnatch-ext = { version = "0.4.1", default-features = f 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 } +ark-scale = { version = "0.0.11", default-features = false, features = ["hazmat"], optional = true } sp-runtime-interface = { path = "../../runtime-interface", default-features = false, optional = true } sp-std = { path = "../../std", default-features = false, optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "ark-bls12-377-ext?/std", "ark-bls12-377?/std", @@ -49,11 +46,11 @@ std = [ "sp-runtime-interface?/std", "sp-std?/std", ] -common = ["ark-ec", "ark-scale", "sp-runtime-interface", "sp-std"] -bls12-377 = ["ark-bls12-377", "ark-bls12-377-ext", "common"] -bls12-381 = ["ark-bls12-381", "ark-bls12-381-ext", "common"] -bw6-761 = ["ark-bw6-761", "ark-bw6-761-ext", "common"] -ed-on-bls12-377 = ["ark-ed-on-bls12-377", "ark-ed-on-bls12-377-ext", "common"] +common = [ "ark-ec", "ark-scale", "sp-runtime-interface", "sp-std" ] +bls12-377 = [ "ark-bls12-377", "ark-bls12-377-ext", "common" ] +bls12-381 = [ "ark-bls12-381", "ark-bls12-381-ext", "common" ] +bw6-761 = [ "ark-bw6-761", "ark-bw6-761-ext", "common" ] +ed-on-bls12-377 = [ "ark-ed-on-bls12-377", "ark-ed-on-bls12-377-ext", "common" ] ed-on-bls12-381-bandersnatch = [ "ark-ed-on-bls12-381-bandersnatch", "ark-ed-on-bls12-381-bandersnatch-ext", diff --git a/substrate/primitives/database/Cargo.toml b/substrate/primitives/database/Cargo.toml index 00ccf97c83e..430895236d4 100644 --- a/substrate/primitives/database/Cargo.toml +++ b/substrate/primitives/database/Cargo.toml @@ -10,9 +10,6 @@ description = "Substrate database trait." documentation = "https://docs.rs/sp-database" readme = "README.md" -[lints] -workspace = true - [dependencies] kvdb = "0.13.0" parking_lot = "0.12.1" diff --git a/substrate/primitives/debug-derive/Cargo.toml b/substrate/primitives/debug-derive/Cargo.toml index acf281f306a..c97c8a0a399 100644 --- a/substrate/primitives/debug-derive/Cargo.toml +++ b/substrate/primitives/debug-derive/Cargo.toml @@ -9,8 +9,6 @@ repository.workspace = true description = "Macros to derive runtime debug implementation." documentation = "https://docs.rs/sp-debug-derive" -[lints] -workspace = true [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,11 +18,11 @@ proc-macro = true [dependencies] quote = "1.0.28" -syn = "2.0.40" +syn = "2.0.38" proc-macro2 = "1.0.56" [features] -default = ["std"] +default = [ "std" ] std = [] # By default `RuntimeDebug` implements `Debug` that outputs `` when `std` is # disabled. However, sometimes downstream users need to have the real `Debug` implementation for diff --git a/substrate/primitives/externalities/Cargo.toml b/substrate/primitives/externalities/Cargo.toml index 4c7afc38b81..417eb363867 100644 --- a/substrate/primitives/externalities/Cargo.toml +++ b/substrate/primitives/externalities/Cargo.toml @@ -10,18 +10,15 @@ description = "Substrate externalities abstraction" documentation = "https://docs.rs/sp-externalities" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } environmental = { version = "1.1.3", default-features = false } -sp-std = { path = "../std", default-features = false } -sp-storage = { path = "../storage", default-features = false } +sp-std = { path = "../std", default-features = false} +sp-storage = { path = "../storage", default-features = false} [features] -default = ["std"] -std = ["codec/std", "environmental/std", "sp-std/std", "sp-storage/std"] +default = [ "std" ] +std = [ "codec/std", "environmental/std", "sp-std/std", "sp-storage/std" ] diff --git a/substrate/primitives/genesis-builder/Cargo.toml b/substrate/primitives/genesis-builder/Cargo.toml index b376055d605..cf7ce995711 100644 --- a/substrate/primitives/genesis-builder/Cargo.toml +++ b/substrate/primitives/genesis-builder/Cargo.toml @@ -9,18 +9,15 @@ repository.workspace = true description = "Substrate GenesisConfig builder API" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-api = { path = "../api", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } -sp-std = { path = "../std", default-features = false } +sp-api = { path = "../api", default-features = false} +sp-runtime = { path = "../runtime", default-features = false} +sp-std = { path = "../std", default-features = false} serde_json = { version = "1.0.108", default-features = false, features = ["alloc"] } [features] -default = ["std"] -std = ["serde_json/std", "sp-api/std", "sp-runtime/std", "sp-std/std"] +default = [ "std" ] +std = [ "serde_json/std", "sp-api/std", "sp-runtime/std", "sp-std/std" ] diff --git a/substrate/primitives/inherents/Cargo.toml b/substrate/primitives/inherents/Cargo.toml index e011e9ce9b8..4a511c653fd 100644 --- a/substrate/primitives/inherents/Cargo.toml +++ b/substrate/primitives/inherents/Cargo.toml @@ -10,9 +10,6 @@ description = "Provides types and traits for creating and checking inherents." documentation = "https://docs.rs/sp-inherents" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -22,14 +19,14 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } impl-trait-for-tuples = "0.2.2" thiserror = { version = "1.0.48", optional = true } -sp-runtime = { path = "../runtime", default-features = false, optional = true } -sp-std = { path = "../std", default-features = false } +sp-runtime = { path = "../runtime", default-features = false, optional = true} +sp-std = { path = "../std", default-features = false} [dev-dependencies] futures = "0.3.21" [features] -default = ["std"] +default = [ "std" ] std = [ "async-trait", "codec/std", diff --git a/substrate/primitives/io/Cargo.toml b/substrate/primitives/io/Cargo.toml index 9671880069a..59df8895bb7 100644 --- a/substrate/primitives/io/Cargo.toml +++ b/substrate/primitives/io/Cargo.toml @@ -11,9 +11,6 @@ documentation = "https://docs.rs/sp-io" readme = "README.md" build = "build.rs" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,19 +18,19 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] bytes = { version = "1.1.0", default-features = false } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["bytes"] } -sp-core = { path = "../core", default-features = false } -sp-keystore = { path = "../keystore", default-features = false, optional = true } -sp-std = { path = "../std", default-features = false } +sp-core = { path = "../core", 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 } +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} log = { version = "0.4.17", optional = true } -secp256k1 = { version = "0.28.0", features = ["global-context", "recovery"], optional = true } +secp256k1 = { version = "0.28.0", features = ["recovery", "global-context"], optional = true } tracing = { version = "0.1.29", default-features = false } -tracing-core = { version = "0.1.32", default-features = false } +tracing-core = { version = "0.1.28", default-features = false} # Required for backwards compatibility reason, but only used for verifying when `UseDalekExt` is set. ed25519-dalek = { version = "2.0", default-features = false, optional = true } @@ -42,7 +39,7 @@ ed25519-dalek = { version = "2.0", default-features = false, optional = true } rustversion = "1.0.6" [features] -default = ["std"] +default = [ "std" ] std = [ "bytes/std", "codec/std", @@ -63,7 +60,7 @@ std = [ "tracing/std", ] -with-tracing = ["sp-tracing/with-tracing"] +with-tracing = [ "sp-tracing/with-tracing" ] # These two features are used for `no_std` builds for the environments which already provides # `#[panic_handler]`, `#[alloc_error_handler]` and `#[global_allocator]`. @@ -95,9 +92,9 @@ improved_panic_error_reporting = [] # This feature adds BLS crypto primitives. # It should not be used in production since the implementation and interface may still # be subject to significant changes. -bls-experimental = ["sp-keystore/bls-experimental"] +bls-experimental = [ "sp-keystore/bls-experimental" ] # This feature adds Bandersnatch crypto primitives. # It should not be used in production since the implementation and interface may still # be subject to significant changes. -bandersnatch-experimental = ["sp-keystore/bandersnatch-experimental"] +bandersnatch-experimental = [ "sp-keystore/bandersnatch-experimental" ] diff --git a/substrate/primitives/keyring/Cargo.toml b/substrate/primitives/keyring/Cargo.toml index 80d773b452a..1ab78eeed45 100644 --- a/substrate/primitives/keyring/Cargo.toml +++ b/substrate/primitives/keyring/Cargo.toml @@ -10,13 +10,11 @@ description = "Keyring support code for the runtime. A set of test accounts." documentation = "https://docs.rs/sp-keyring" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] +lazy_static = "1.4.0" strum = { version = "0.24.1", features = ["derive"], default-features = false } sp-core = { path = "../core" } sp-runtime = { path = "../runtime" } @@ -25,4 +23,4 @@ sp-runtime = { path = "../runtime" } # This feature adds Bandersnatch crypto primitives. # It should not be used in production since the implementation and interface may still # be subject to significant changes. -bandersnatch-experimental = ["sp-core/bandersnatch-experimental"] +bandersnatch-experimental = [ "sp-core/bandersnatch-experimental" ] diff --git a/substrate/primitives/keyring/src/bandersnatch.rs b/substrate/primitives/keyring/src/bandersnatch.rs index eb60f856327..8de6786a6fb 100644 --- a/substrate/primitives/keyring/src/bandersnatch.rs +++ b/substrate/primitives/keyring/src/bandersnatch.rs @@ -21,9 +21,12 @@ pub use sp_core::bandersnatch; use sp_core::{ bandersnatch::{Pair, Public, Signature}, crypto::UncheckedFrom, - hex2array, ByteArray, Pair as PairT, + ByteArray, Pair as PairT, }; +use lazy_static::lazy_static; +use std::{collections::HashMap, ops::Deref, sync::Mutex}; + /// Set of test accounts. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, strum::EnumIter)] pub enum Keyring { @@ -71,7 +74,7 @@ impl Keyring { } pub fn public(self) -> Public { - Public::from(self) + self.pair().public() } pub fn to_seed(self) -> String { @@ -126,9 +129,20 @@ impl std::str::FromStr for Keyring { } } +lazy_static! { + static ref PRIVATE_KEYS: Mutex> = + Mutex::new(Keyring::iter().map(|who| (who, who.pair())).collect()); + static ref PUBLIC_KEYS: HashMap = PRIVATE_KEYS + .lock() + .unwrap() + .iter() + .map(|(&who, pair)| (who, pair.public())) + .collect(); +} + impl From for Public { fn from(k: Keyring) -> Self { - Public::unchecked_from(<[u8; PUBLIC_RAW_LEN]>::from(k)) + *(*PUBLIC_KEYS).get(&k).unwrap() } } @@ -140,24 +154,32 @@ impl From for Pair { impl From for [u8; PUBLIC_RAW_LEN] { fn from(k: Keyring) -> Self { - match k { - Keyring::Alice => - hex2array!("9c8af77d3a4e3f6f076853922985b9e6724fc9675329087f47aff1ceaaae772180"), - Keyring::Bob => - hex2array!("1abfbb76dc8374a1a6d93d59a5c81f07c18835f4681a6258aa0f514d363bff4780"), - Keyring::Charlie => - hex2array!("0f4a9990aca3d39a7cd8bf187e2e81a9ea6f9cedb2db405f2fffff384c5dd02680"), - Keyring::Dave => - hex2array!("bd7a87d4dfa89926a408b5acbed554ae3b053fa3532531053295cbabf07d337000"), - Keyring::Eve => - hex2array!("f992d5b8eac8fc004d521bee6edc1174cfa7fae3a1baec8262511ee351f9f85e00"), - Keyring::Ferdie => - hex2array!("1ce2613e89bc5c8e358aad884099cfb576a61176f2f9968cd0d486a04457245180"), - Keyring::One => - hex2array!("a29e03ac273e521274d8e501a6242abd2ab393d7e197221a9113bdf8e2e5b34d00"), - Keyring::Two => - hex2array!("f968d47e819ddb18a9d0f2ebd16501680b1a3f07ee375c6f81310e5f99a04f4d00"), - } + *(*PUBLIC_KEYS).get(&k).unwrap().as_ref() + } +} + +impl From for &'static [u8; PUBLIC_RAW_LEN] { + fn from(k: Keyring) -> Self { + PUBLIC_KEYS.get(&k).unwrap().as_ref() + } +} + +impl AsRef<[u8; PUBLIC_RAW_LEN]> for Keyring { + fn as_ref(&self) -> &[u8; PUBLIC_RAW_LEN] { + PUBLIC_KEYS.get(self).unwrap().as_ref() + } +} + +impl AsRef for Keyring { + fn as_ref(&self) -> &Public { + PUBLIC_KEYS.get(self).unwrap() + } +} + +impl Deref for Keyring { + type Target = [u8; PUBLIC_RAW_LEN]; + fn deref(&self) -> &[u8; PUBLIC_RAW_LEN] { + PUBLIC_KEYS.get(self).unwrap().as_ref() } } @@ -184,9 +206,4 @@ mod tests { &Keyring::Bob.public(), )); } - #[test] - fn verify_static_public_keys() { - assert!(Keyring::iter() - .all(|k| { k.pair().public().as_ref() == <[u8; PUBLIC_RAW_LEN]>::from(k) })); - } } diff --git a/substrate/primitives/keyring/src/ed25519.rs b/substrate/primitives/keyring/src/ed25519.rs index ade42b29494..3060bfb1ad9 100644 --- a/substrate/primitives/keyring/src/ed25519.rs +++ b/substrate/primitives/keyring/src/ed25519.rs @@ -17,12 +17,14 @@ //! Support code for the runtime. A set of test accounts. +use lazy_static::lazy_static; pub use sp_core::ed25519; use sp_core::{ ed25519::{Pair, Public, Signature}, - hex2array, ByteArray, Pair as PairT, H256, + ByteArray, Pair as PairT, H256, }; use sp_runtime::AccountId32; +use std::{collections::HashMap, ops::Deref}; /// Set of test accounts. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, strum::EnumIter)] @@ -91,7 +93,7 @@ impl Keyring { } pub fn public(self) -> Public { - Public::from(self) + self.pair().public() } pub fn to_seed(self) -> String { @@ -126,9 +128,16 @@ impl From for sp_runtime::MultiSigner { } } +lazy_static! { + static ref PRIVATE_KEYS: HashMap = + Keyring::iter().map(|i| (i, i.pair())).collect(); + static ref PUBLIC_KEYS: HashMap = + PRIVATE_KEYS.iter().map(|(&name, pair)| (name, pair.public())).collect(); +} + impl From for Public { fn from(k: Keyring) -> Self { - Public::from_raw(k.into()) + *(*PUBLIC_KEYS).get(&k).unwrap() } } @@ -146,42 +155,38 @@ impl From for Pair { impl From for [u8; 32] { fn from(k: Keyring) -> Self { - match k { - Keyring::Alice => - hex2array!("88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee"), - Keyring::Bob => - hex2array!("d17c2d7823ebf260fd138f2d7e27d114c0145d968b5ff5006125f2414fadae69"), - Keyring::Charlie => - hex2array!("439660b36c6c03afafca027b910b4fecf99801834c62a5e6006f27d978de234f"), - Keyring::Dave => - hex2array!("5e639b43e0052c47447dac87d6fd2b6ec50bdd4d0f614e4299c665249bbd09d9"), - Keyring::Eve => - hex2array!("1dfe3e22cc0d45c70779c1095f7489a8ef3cf52d62fbd8c2fa38c9f1723502b5"), - Keyring::Ferdie => - hex2array!("568cb4a574c6d178feb39c27dfc8b3f789e5f5423e19c71633c748b9acf086b5"), - Keyring::AliceStash => - hex2array!("451781cd0c5504504f69ceec484cc66e4c22a2b6a9d20fb1a426d91ad074a2a8"), - Keyring::BobStash => - hex2array!("292684abbb28def63807c5f6e84e9e8689769eb37b1ab130d79dbfbf1b9a0d44"), - Keyring::CharlieStash => - hex2array!("dd6a6118b6c11c9c9e5a4f34ed3d545e2c74190f90365c60c230fa82e9423bb9"), - Keyring::DaveStash => - hex2array!("1d0432d75331ab299065bee79cdb1bdc2497c597a3087b4d955c67e3c000c1e2"), - Keyring::EveStash => - hex2array!("c833bdd2e1a7a18acc1c11f8596e2e697bb9b42d6b6051e474091a1d43a294d7"), - Keyring::FerdieStash => - hex2array!("199d749dbf4b8135cb1f3c8fd697a390fc0679881a8a110c1d06375b3b62cd09"), - Keyring::One => - hex2array!("16f97016bbea8f7b45ae6757b49efc1080accc175d8f018f9ba719b60b0815e4"), - Keyring::Two => - hex2array!("5079bcd20fd97d7d2f752c4607012600b401950260a91821f73e692071c82bf5"), - } + *(*PUBLIC_KEYS).get(&k).unwrap().as_array_ref() } } impl From for H256 { fn from(k: Keyring) -> Self { - k.into() + (*PUBLIC_KEYS).get(&k).unwrap().as_array_ref().into() + } +} + +impl From for &'static [u8; 32] { + fn from(k: Keyring) -> Self { + (*PUBLIC_KEYS).get(&k).unwrap().as_array_ref() + } +} + +impl AsRef<[u8; 32]> for Keyring { + fn as_ref(&self) -> &[u8; 32] { + (*PUBLIC_KEYS).get(self).unwrap().as_array_ref() + } +} + +impl AsRef for Keyring { + fn as_ref(&self) -> &Public { + (*PUBLIC_KEYS).get(self).unwrap() + } +} + +impl Deref for Keyring { + type Target = [u8; 32]; + fn deref(&self) -> &[u8; 32] { + (*PUBLIC_KEYS).get(self).unwrap().as_array_ref() } } @@ -208,9 +213,4 @@ mod tests { &Keyring::Bob.public(), )); } - - #[test] - fn verify_static_public_keys() { - assert!(Keyring::iter().all(|k| { k.pair().public().as_ref() == <[u8; 32]>::from(k) })); - } } diff --git a/substrate/primitives/keyring/src/sr25519.rs b/substrate/primitives/keyring/src/sr25519.rs index 1c2a2526efb..914a66b4d83 100644 --- a/substrate/primitives/keyring/src/sr25519.rs +++ b/substrate/primitives/keyring/src/sr25519.rs @@ -17,13 +17,14 @@ //! Support code for the runtime. A set of test accounts. +use lazy_static::lazy_static; pub use sp_core::sr25519; use sp_core::{ - hex2array, sr25519::{Pair, Public, Signature}, ByteArray, Pair as PairT, H256, }; use sp_runtime::AccountId32; +use std::{collections::HashMap, ops::Deref}; /// Set of test accounts. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, strum::Display, strum::EnumIter)] @@ -92,7 +93,7 @@ impl Keyring { } pub fn public(self) -> Public { - Public::from(self) + self.pair().public() } pub fn to_seed(self) -> String { @@ -164,6 +165,13 @@ impl std::str::FromStr for Keyring { } } +lazy_static! { + static ref PRIVATE_KEYS: HashMap = + Keyring::iter().map(|i| (i, i.pair())).collect(); + static ref PUBLIC_KEYS: HashMap = + PRIVATE_KEYS.iter().map(|(&name, pair)| (name, pair.public())).collect(); +} + impl From for AccountId32 { fn from(k: Keyring) -> Self { k.to_account_id() @@ -172,7 +180,7 @@ impl From for AccountId32 { impl From for Public { fn from(k: Keyring) -> Self { - Public::from_raw(k.into()) + *(*PUBLIC_KEYS).get(&k).unwrap() } } @@ -184,42 +192,38 @@ impl From for Pair { impl From for [u8; 32] { fn from(k: Keyring) -> Self { - match k { - Keyring::Alice => - hex2array!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"), - Keyring::Bob => - hex2array!("8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48"), - Keyring::Charlie => - hex2array!("90b5ab205c6974c9ea841be688864633dc9ca8a357843eeacf2314649965fe22"), - Keyring::Dave => - hex2array!("306721211d5404bd9da88e0204360a1a9ab8b87c66c1bc2fcdd37f3c2222cc20"), - Keyring::Eve => - hex2array!("e659a7a1628cdd93febc04a4e0646ea20e9f5f0ce097d9a05290d4a9e054df4e"), - Keyring::Ferdie => - hex2array!("1cbd2d43530a44705ad088af313e18f80b53ef16b36177cd4b77b846f2a5f07c"), - Keyring::AliceStash => - hex2array!("be5ddb1579b72e84524fc29e78609e3caf42e85aa118ebfe0b0ad404b5bdd25f"), - Keyring::BobStash => - hex2array!("fe65717dad0447d715f660a0a58411de509b42e6efb8375f562f58a554d5860e"), - Keyring::CharlieStash => - hex2array!("1e07379407fecc4b89eb7dbd287c2c781cfb1907a96947a3eb18e4f8e7198625"), - Keyring::DaveStash => - hex2array!("e860f1b1c7227f7c22602f53f15af80747814dffd839719731ee3bba6edc126c"), - Keyring::EveStash => - hex2array!("8ac59e11963af19174d0b94d5d78041c233f55d2e19324665bafdfb62925af2d"), - Keyring::FerdieStash => - hex2array!("101191192fc877c24d725b337120fa3edc63d227bbc92705db1e2cb65f56981a"), - Keyring::One => - hex2array!("ac859f8a216eeb1b320b4c76d118da3d7407fa523484d0a980126d3b4d0d220a"), - Keyring::Two => - hex2array!("1254f7017f0b8347ce7ab14f96d818802e7e9e0c0d1b7c9acb3c726b080e7a03"), - } + *(*PUBLIC_KEYS).get(&k).unwrap().as_array_ref() } } impl From for H256 { fn from(k: Keyring) -> Self { - k.into() + (*PUBLIC_KEYS).get(&k).unwrap().as_array_ref().into() + } +} + +impl From for &'static [u8; 32] { + fn from(k: Keyring) -> Self { + (*PUBLIC_KEYS).get(&k).unwrap().as_array_ref() + } +} + +impl AsRef<[u8; 32]> for Keyring { + fn as_ref(&self) -> &[u8; 32] { + (*PUBLIC_KEYS).get(self).unwrap().as_array_ref() + } +} + +impl AsRef for Keyring { + fn as_ref(&self) -> &Public { + (*PUBLIC_KEYS).get(self).unwrap() + } +} + +impl Deref for Keyring { + type Target = [u8; 32]; + fn deref(&self) -> &[u8; 32] { + (*PUBLIC_KEYS).get(self).unwrap().as_array_ref() } } @@ -246,8 +250,4 @@ mod tests { &Keyring::Bob.public(), )); } - #[test] - fn verify_static_public_keys() { - assert!(Keyring::iter().all(|k| { k.pair().public().as_ref() == <[u8; 32]>::from(k) })); - } } diff --git a/substrate/primitives/keystore/Cargo.toml b/substrate/primitives/keystore/Cargo.toml index d60f5d6c568..ff7c27bf565 100644 --- a/substrate/primitives/keystore/Cargo.toml +++ b/substrate/primitives/keystore/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Keystore primitives." documentation = "https://docs.rs/sp-core" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,23 +16,23 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } parking_lot = { version = "0.12.1", default-features = false } thiserror = "1.0" -sp-core = { path = "../core", default-features = false } -sp-externalities = { path = "../externalities", default-features = false } +sp-core = { path = "../core", default-features = false} +sp-externalities = { path = "../externalities", default-features = false} [dev-dependencies] -rand = "0.8.5" +rand = "0.7.2" rand_chacha = "0.2.2" [features] -default = ["std"] -std = ["codec/std", "sp-core/std", "sp-externalities/std"] +default = [ "std" ] +std = [ "codec/std", "sp-core/std", "sp-externalities/std" ] # This feature adds BLS crypto primitives. # It should not be used in production since the implementation and interface may still # be subject to significant changes. -bls-experimental = ["sp-core/bls-experimental"] +bls-experimental = [ "sp-core/bls-experimental" ] # This feature adds Bandersnatch crypto primitives. # It should not be used in production since the implementation and interface may still # be subject to significant changes. -bandersnatch-experimental = ["sp-core/bandersnatch-experimental"] +bandersnatch-experimental = [ "sp-core/bandersnatch-experimental" ] diff --git a/substrate/primitives/keystore/src/lib.rs b/substrate/primitives/keystore/src/lib.rs index 07c4e2d5fd1..e415080779c 100644 --- a/substrate/primitives/keystore/src/lib.rs +++ b/substrate/primitives/keystore/src/lib.rs @@ -92,19 +92,19 @@ pub trait Keystore: Send + Sync { data: &sr25519::vrf::VrfSignData, ) -> Result, Error>; - /// Generate an sr25519 VRF pre-output for a given input data. + /// Generate an sr25519 VRF output for a given input data. /// /// Receives [`KeyTypeId`] and an [`sr25519::Public`] key to be able to map /// them to a private key that exists in the keystore. /// /// Returns `None` if the given `key_type` and `public` combination doesn't /// exist in the keystore or an `Err` when something failed. - fn sr25519_vrf_pre_output( + fn sr25519_vrf_output( &self, key_type: KeyTypeId, public: &sr25519::Public, input: &sr25519::vrf::VrfInput, - ) -> Result, Error>; + ) -> Result, Error>; /// Returns all ed25519 public keys for the given key type. fn ed25519_public_keys(&self, key_type: KeyTypeId) -> Vec; @@ -223,7 +223,7 @@ pub trait Keystore: Send + Sync { input: &bandersnatch::vrf::VrfSignData, ) -> Result, Error>; - /// Generate a bandersnatch VRF pre-output for a given input data. + /// Generate a bandersnatch VRF (pre)output for a given input data. /// /// Receives [`KeyTypeId`] and an [`bandersnatch::Public`] key to be able to map /// them to a private key that exists in the keystore. @@ -231,12 +231,12 @@ pub trait Keystore: Send + Sync { /// Returns `None` if the given `key_type` and `public` combination doesn't /// exist in the keystore or an `Err` when something failed. #[cfg(feature = "bandersnatch-experimental")] - fn bandersnatch_vrf_pre_output( + fn bandersnatch_vrf_output( &self, key_type: KeyTypeId, public: &bandersnatch::Public, input: &bandersnatch::vrf::VrfInput, - ) -> Result, Error>; + ) -> Result, Error>; /// Generate a bandersnatch ring-VRF signature for the given data. /// @@ -474,13 +474,13 @@ impl Keystore for Arc { (**self).sr25519_vrf_sign(key_type, public, data) } - fn sr25519_vrf_pre_output( + fn sr25519_vrf_output( &self, key_type: KeyTypeId, public: &sr25519::Public, input: &sr25519::vrf::VrfInput, - ) -> Result, Error> { - (**self).sr25519_vrf_pre_output(key_type, public, input) + ) -> Result, Error> { + (**self).sr25519_vrf_output(key_type, public, input) } fn ed25519_public_keys(&self, key_type: KeyTypeId) -> Vec { @@ -569,13 +569,13 @@ impl Keystore for Arc { } #[cfg(feature = "bandersnatch-experimental")] - fn bandersnatch_vrf_pre_output( + fn bandersnatch_vrf_output( &self, key_type: KeyTypeId, public: &bandersnatch::Public, input: &bandersnatch::vrf::VrfInput, - ) -> Result, Error> { - (**self).bandersnatch_vrf_pre_output(key_type, public, input) + ) -> Result, Error> { + (**self).bandersnatch_vrf_output(key_type, public, input) } #[cfg(feature = "bandersnatch-experimental")] diff --git a/substrate/primitives/keystore/src/testing.rs b/substrate/primitives/keystore/src/testing.rs index 585efba0283..08110e8e497 100644 --- a/substrate/primitives/keystore/src/testing.rs +++ b/substrate/primitives/keystore/src/testing.rs @@ -113,14 +113,14 @@ impl MemoryKeystore { Ok(sig) } - fn vrf_pre_output( + fn vrf_output( &self, key_type: KeyTypeId, public: &T::Public, input: &T::VrfInput, - ) -> Result, Error> { - let pre_output = self.pair::(key_type, public).map(|pair| pair.vrf_pre_output(input)); - Ok(pre_output) + ) -> Result, Error> { + let preout = self.pair::(key_type, public).map(|pair| pair.vrf_output(input)); + Ok(preout) } } @@ -155,13 +155,13 @@ impl Keystore for MemoryKeystore { self.vrf_sign::(key_type, public, data) } - fn sr25519_vrf_pre_output( + fn sr25519_vrf_output( &self, key_type: KeyTypeId, public: &sr25519::Public, input: &sr25519::vrf::VrfInput, - ) -> Result, Error> { - self.vrf_pre_output::(key_type, public, input) + ) -> Result, Error> { + self.vrf_output::(key_type, public, input) } fn ed25519_public_keys(&self, key_type: KeyTypeId) -> Vec { @@ -265,13 +265,13 @@ impl Keystore for MemoryKeystore { } #[cfg(feature = "bandersnatch-experimental")] - fn bandersnatch_vrf_pre_output( + fn bandersnatch_vrf_output( &self, key_type: KeyTypeId, public: &bandersnatch::Public, input: &bandersnatch::vrf::VrfInput, - ) -> Result, Error> { - self.vrf_pre_output::(key_type, public, input) + ) -> Result, Error> { + self.vrf_output::(key_type, public, input) } #[cfg(feature = "bls-experimental")] @@ -443,7 +443,7 @@ mod tests { } #[test] - fn sr25519_vrf_pre_output() { + fn sr25519_vrf_output() { let store = MemoryKeystore::new(); let secret_uri = "//Alice"; @@ -458,17 +458,16 @@ mod tests { ], ); - let result = store.sr25519_vrf_pre_output(SR25519, &pair.public(), &input); + let result = store.sr25519_vrf_output(SR25519, &pair.public(), &input); assert!(result.unwrap().is_none()); store .insert(SR25519, secret_uri, pair.public().as_ref()) .expect("Inserts unknown key"); - let pre_output = - store.sr25519_vrf_pre_output(SR25519, &pair.public(), &input).unwrap().unwrap(); + let preout = store.sr25519_vrf_output(SR25519, &pair.public(), &input).unwrap().unwrap(); - let result = pre_output.make_bytes::<32>(b"rand", &input, &pair.public()); + let result = preout.make_bytes::<32>(b"rand", &input, &pair.public()); assert!(result.is_ok()); } @@ -526,7 +525,7 @@ mod tests { let store = MemoryKeystore::new(); - let ring_ctx = bandersnatch::ring_vrf::RingContext::<1024>::new_testing(); + let ring_ctx = bandersnatch::ring_vrf::RingContext::new_testing(); let mut pks: Vec<_> = (0..16) .map(|i| bandersnatch::Pair::from_seed(&[i as u8; 32]).public()) diff --git a/substrate/primitives/maybe-compressed-blob/Cargo.toml b/substrate/primitives/maybe-compressed-blob/Cargo.toml index 86f73626c0a..c6fa7103672 100644 --- a/substrate/primitives/maybe-compressed-blob/Cargo.toml +++ b/substrate/primitives/maybe-compressed-blob/Cargo.toml @@ -10,9 +10,6 @@ description = "Handling of blobs, usually Wasm code, which may be compresed" documentation = "https://docs.rs/sp-maybe-compressed-blob" readme = "README.md" -[lints] -workspace = true - [dependencies] thiserror = "1.0" zstd = { version = "0.12.4", default-features = false } diff --git a/substrate/primitives/merkle-mountain-range/Cargo.toml b/substrate/primitives/merkle-mountain-range/Cargo.toml index dec55a5c8f3..5216765825f 100644 --- a/substrate/primitives/merkle-mountain-range/Cargo.toml +++ b/substrate/primitives/merkle-mountain-range/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "Merkle Mountain Range primitives." -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,19 +16,19 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } log = { version = "0.4.17", default-features = false } mmr-lib = { package = "ckb-merkle-mountain-range", version = "0.5.2", default-features = false } -serde = { version = "1.0.193", features = ["alloc", "derive"], default-features = false, optional = true } -sp-api = { path = "../api", default-features = false } -sp-core = { path = "../core", default-features = false } -sp-debug-derive = { path = "../debug-derive", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } -sp-std = { path = "../std", default-features = false } +serde = { version = "1.0.188", features = ["derive", "alloc"], default-features = false, optional = true } +sp-api = { path = "../api", default-features = false} +sp-core = { path = "../core", default-features = false} +sp-debug-derive = { path = "../debug-derive", default-features = false} +sp-runtime = { path = "../runtime", default-features = false} +sp-std = { path = "../std", default-features = false} thiserror = "1.0" [dev-dependencies] array-bytes = "6.1" [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "log/std", @@ -46,4 +43,4 @@ std = [ ] # Serde support without relying on std features. -serde = ["dep:serde", "scale-info/serde", "sp-core/serde", "sp-runtime/serde"] +serde = [ "dep:serde", "scale-info/serde", "sp-core/serde", "sp-runtime/serde" ] diff --git a/substrate/primitives/metadata-ir/Cargo.toml b/substrate/primitives/metadata-ir/Cargo.toml index 0dc496bab53..77c21b920f2 100644 --- a/substrate/primitives/metadata-ir/Cargo.toml +++ b/substrate/primitives/metadata-ir/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Intermediate representation of the runtime metadata." documentation = "https://docs.rs/sp-metadata-ir" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,8 +16,8 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } frame-metadata = { version = "16.0.0", default-features = false, features = ["current"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -sp-std = { path = "../std", default-features = false } +sp-std = { path = "../std", default-features = false} [features] -default = ["std"] -std = ["codec/std", "frame-metadata/std", "scale-info/std", "sp-std/std"] +default = [ "std" ] +std = [ "codec/std", "frame-metadata/std", "scale-info/std", "sp-std/std" ] diff --git a/substrate/primitives/mixnet/Cargo.toml b/substrate/primitives/mixnet/Cargo.toml index 6ea7a6cbe8c..bc6878086cf 100644 --- a/substrate/primitives/mixnet/Cargo.toml +++ b/substrate/primitives/mixnet/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository = "https://github.com/paritytech/substrate/" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -23,7 +20,7 @@ sp-application-crypto = { default-features = false, path = "../application-crypt sp-std = { default-features = false, path = "../std" } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "scale-info/std", diff --git a/substrate/primitives/npos-elections/Cargo.toml b/substrate/primitives/npos-elections/Cargo.toml index dcd03e7e5e0..90418e561f2 100644 --- a/substrate/primitives/npos-elections/Cargo.toml +++ b/substrate/primitives/npos-elections/Cargo.toml @@ -9,27 +9,24 @@ repository.workspace = true description = "NPoS election algorithm primitives" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"], optional = true } -sp-arithmetic = { path = "../arithmetic", default-features = false } -sp-core = { path = "../core", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } -sp-std = { path = "../std", default-features = false } +serde = { version = "1.0.188", default-features = false, features = ["derive", "alloc"], optional = true } +sp-arithmetic = { path = "../arithmetic", default-features = false} +sp-core = { path = "../core", default-features = false} +sp-runtime = { path = "../runtime", default-features = false} +sp-std = { path = "../std", default-features = false} [dev-dependencies] rand = "0.8.5" substrate-test-utils = { path = "../../test-utils" } [features] -default = ["std"] +default = [ "std" ] bench = [] std = [ "codec/std", diff --git a/substrate/primitives/npos-elections/fuzzer/Cargo.toml b/substrate/primitives/npos-elections/fuzzer/Cargo.toml index 37eaeea2b82..5e75f926f87 100644 --- a/substrate/primitives/npos-elections/fuzzer/Cargo.toml +++ b/substrate/primitives/npos-elections/fuzzer/Cargo.toml @@ -10,16 +10,13 @@ description = "Fuzzer for phragmén implementation." documentation = "https://docs.rs/sp-npos-elections-fuzzer" publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } honggfuzz = "0.5" -rand = { version = "0.8", features = ["small_rng", "std"] } +rand = { version = "0.8", features = ["std", "small_rng"] } sp-npos-elections = { path = ".." } sp-runtime = { path = "../../runtime" } diff --git a/substrate/primitives/npos-elections/src/lib.rs b/substrate/primitives/npos-elections/src/lib.rs index 8d741f4130d..62ae0502114 100644 --- a/substrate/primitives/npos-elections/src/lib.rs +++ b/substrate/primitives/npos-elections/src/lib.rs @@ -22,8 +22,9 @@ //! - [`ghragmms`](phragmms::phragmms()): Implements a hybrid approach inspired by Phragmén which is //! executed faster but it can achieve a constant factor approximation of the maximin problem, //! similar to that of the MMS algorithm. -//! - [`balance`]: Implements the star balancing algorithm. This iterative process can push a -//! solution toward being more "balanced", which in turn can increase its score. +//! - [`balance`](balancing::balance): Implements the star balancing algorithm. This iterative +//! process can push a solution toward being more "balanced", which in turn can increase its +//! score. //! //! ### Terminology //! diff --git a/substrate/primitives/offchain/Cargo.toml b/substrate/primitives/offchain/Cargo.toml index 19d66ae31e9..5f8821b43c7 100644 --- a/substrate/primitives/offchain/Cargo.toml +++ b/substrate/primitives/offchain/Cargo.toml @@ -9,17 +9,14 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-api = { path = "../api", default-features = false } -sp-core = { path = "../core", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } +sp-api = { path = "../api", default-features = false} +sp-core = { path = "../core", default-features = false} +sp-runtime = { path = "../runtime", default-features = false} [features] -default = ["std"] -std = ["sp-api/std", "sp-core/std", "sp-runtime/std"] +default = [ "std" ] +std = [ "sp-api/std", "sp-core/std", "sp-runtime/std" ] diff --git a/substrate/primitives/panic-handler/Cargo.toml b/substrate/primitives/panic-handler/Cargo.toml index a0df527f56e..428062757c1 100644 --- a/substrate/primitives/panic-handler/Cargo.toml +++ b/substrate/primitives/panic-handler/Cargo.toml @@ -10,9 +10,6 @@ description = "Custom panic hook with bug report link" documentation = "https://docs.rs/sp-panic-handler" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/primitives/rpc/Cargo.toml b/substrate/primitives/rpc/Cargo.toml index a542b65cdc9..77bdcc4f89a 100644 --- a/substrate/primitives/rpc/Cargo.toml +++ b/substrate/primitives/rpc/Cargo.toml @@ -9,15 +9,12 @@ repository.workspace = true description = "Substrate RPC primitives and utilities." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] rustc-hash = "1.1.0" -serde = { version = "1.0.193", features = ["derive"] } +serde = { version = "1.0.188", features = ["derive"] } sp-core = { path = "../core" } [dev-dependencies] diff --git a/substrate/primitives/runtime-interface/Cargo.toml b/substrate/primitives/runtime-interface/Cargo.toml index a4c8457b598..69a0d112a16 100644 --- a/substrate/primitives/runtime-interface/Cargo.toml +++ b/substrate/primitives/runtime-interface/Cargo.toml @@ -10,23 +10,20 @@ description = "Substrate runtime interface" documentation = "https://docs.rs/sp-runtime-interface/" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] bytes = { version = "1.1.0", default-features = false } sp-wasm-interface = { path = "../wasm-interface", default-features = false } -sp-std = { path = "../std", default-features = false } -sp-tracing = { path = "../tracing", default-features = false } +sp-std = { path = "../std", default-features = false} +sp-tracing = { path = "../tracing", default-features = false} sp-runtime-interface-proc-macro = { path = "proc-macro" } -sp-externalities = { path = "../externalities", default-features = false } +sp-externalities = { path = "../externalities", default-features = false} codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["bytes"] } static_assertions = "1.0.0" primitive-types = { version = "0.12.0", default-features = false } -sp-storage = { path = "../storage", default-features = false } +sp-storage = { path = "../storage", default-features = false} impl-trait-for-tuples = "0.2.2" [dev-dependencies] @@ -38,7 +35,7 @@ rustversion = "1.0.6" trybuild = "1.0.74" [features] -default = ["std"] +default = [ "std" ] std = [ "bytes/std", "codec/std", diff --git a/substrate/primitives/runtime-interface/proc-macro/Cargo.toml b/substrate/primitives/runtime-interface/proc-macro/Cargo.toml index 7cf1abf8048..fbc49785ae9 100644 --- a/substrate/primitives/runtime-interface/proc-macro/Cargo.toml +++ b/substrate/primitives/runtime-interface/proc-macro/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "This crate provides procedural macros for usage within the context of the Substrate runtime interface." documentation = "https://docs.rs/sp-runtime-interface-proc-macro" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,8 +17,7 @@ proc-macro = true [dependencies] Inflector = "0.11.4" -proc-macro-crate = "2.0.1" +proc-macro-crate = "1.1.3" proc-macro2 = "1.0.56" quote = "1.0.28" -expander = "2.0.0" -syn = { version = "2.0.40", features = ["extra-traits", "fold", "full", "visit"] } +syn = { version = "2.0.38", features = ["full", "visit", "fold", "extra-traits"] } diff --git a/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/mod.rs b/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/mod.rs index d0cc9e7b96b..008d69b3210 100644 --- a/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/mod.rs +++ b/substrate/primitives/runtime-interface/proc-macro/src/runtime_interface/mod.rs @@ -68,11 +68,5 @@ pub fn runtime_interface_impl( } }; - let res = expander::Expander::new("runtime_interface") - .dry(std::env::var("EXPAND_MACROS").is_err()) - .verbose(true) - .write_to_out_dir(res) - .expect("Does not fail because of IO in OUT_DIR; qed"); - Ok(res) } diff --git a/substrate/primitives/runtime-interface/src/pass_by.rs b/substrate/primitives/runtime-interface/src/pass_by.rs index 103e9c16220..8d145669adc 100644 --- a/substrate/primitives/runtime-interface/src/pass_by.rs +++ b/substrate/primitives/runtime-interface/src/pass_by.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Provides the [`PassBy`] trait to simplify the implementation of the +//! Provides the [`PassBy`](PassBy) trait to simplify the implementation of the //! runtime interface traits for custom types. //! //! [`Codec`], [`Inner`] and [`Enum`] are the provided strategy implementations. diff --git a/substrate/primitives/runtime-interface/test-wasm-deprecated/Cargo.toml b/substrate/primitives/runtime-interface/test-wasm-deprecated/Cargo.toml index f663c6d4726..8e06aac851f 100644 --- a/substrate/primitives/runtime-interface/test-wasm-deprecated/Cargo.toml +++ b/substrate/primitives/runtime-interface/test-wasm-deprecated/Cargo.toml @@ -9,22 +9,19 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-core = { path = "../../core", default-features = false } -sp-io = { path = "../../io", default-features = false } -sp-runtime-interface = { path = "..", default-features = false } +sp-core = { path = "../../core", default-features = false} +sp-io = { path = "../../io", default-features = false} +sp-runtime-interface = { path = "..", default-features = false} [build-dependencies] substrate-wasm-builder = { path = "../../../utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "sp-core/std", "sp-io/std", diff --git a/substrate/primitives/runtime-interface/test-wasm/Cargo.toml b/substrate/primitives/runtime-interface/test-wasm/Cargo.toml index ecb3c7f8732..7729f89fa39 100644 --- a/substrate/primitives/runtime-interface/test-wasm/Cargo.toml +++ b/substrate/primitives/runtime-interface/test-wasm/Cargo.toml @@ -9,24 +9,21 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] bytes = { version = "1.1.0", default-features = false } -sp-core = { path = "../../core", default-features = false } -sp-io = { path = "../../io", default-features = false } -sp-runtime-interface = { path = "..", default-features = false } -sp-std = { path = "../../std", default-features = false } +sp-core = { path = "../../core", default-features = false} +sp-io = { path = "../../io", default-features = false} +sp-runtime-interface = { path = "..", default-features = false} +sp-std = { path = "../../std", default-features = false} [build-dependencies] substrate-wasm-builder = { path = "../../../utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "bytes/std", "sp-core/std", diff --git a/substrate/primitives/runtime-interface/test/Cargo.toml b/substrate/primitives/runtime-interface/test/Cargo.toml index 55d70960989..feb6a454af1 100644 --- a/substrate/primitives/runtime-interface/test/Cargo.toml +++ b/substrate/primitives/runtime-interface/test/Cargo.toml @@ -8,15 +8,12 @@ publish = false homepage = "https://substrate.io" repository.workspace = true -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] tracing = "0.1.29" -tracing-core = "0.1.32" +tracing-core = "0.1.28" sc-executor = { path = "../../../client/executor" } sc-executor-common = { path = "../../../client/executor/common" } sp-io = { path = "../../io" } diff --git a/substrate/primitives/runtime/Cargo.toml b/substrate/primitives/runtime/Cargo.toml index 81ea7616f5e..ffb5356fefb 100644 --- a/substrate/primitives/runtime/Cargo.toml +++ b/substrate/primitives/runtime/Cargo.toml @@ -10,9 +10,6 @@ description = "Runtime Modules shared primitive types." documentation = "https://docs.rs/sp-runtime" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -26,16 +23,13 @@ log = { version = "0.4.17", default-features = false } paste = "1.0" rand = { version = "0.8.5", optional = true } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"], optional = true } -sp-application-crypto = { path = "../application-crypto", default-features = false } -sp-arithmetic = { path = "../arithmetic", default-features = false } -sp-core = { path = "../core", default-features = false } -sp-io = { path = "../io", default-features = false } -sp-std = { path = "../std", default-features = false } -sp-weights = { path = "../weights", default-features = false } -docify = { version = "0.2.6" } - -simple-mermaid = { git = "https://github.com/kianenigma/simple-mermaid.git", branch = "main" } +serde = { version = "1.0.188", default-features = false, features = ["derive", "alloc"], optional = true } +sp-application-crypto = { path = "../application-crypto", default-features = false} +sp-arithmetic = { path = "../arithmetic", default-features = false} +sp-core = { path = "../core", default-features = false} +sp-io = { path = "../io", default-features = false} +sp-std = { path = "../std", default-features = false} +sp-weights = { path = "../weights", default-features = false} [dev-dependencies] rand = "0.8.5" @@ -49,7 +43,7 @@ substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } [features] runtime-benchmarks = [] try-runtime = [] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "either/use_std", diff --git a/substrate/primitives/runtime/src/generic/checked_extrinsic.rs b/substrate/primitives/runtime/src/generic/checked_extrinsic.rs index a4b542f79a7..77d7f9fb3cd 100644 --- a/substrate/primitives/runtime/src/generic/checked_extrinsic.rs +++ b/substrate/primitives/runtime/src/generic/checked_extrinsic.rs @@ -53,11 +53,9 @@ pub enum ExtrinsicFormat { // - Signed(id, extension) instead of Some((id, extra)). // - Introduce General(extension) for one without a signature. -/// Definition of something that the external world might want to say; its existence implies that it -/// has been checked and is good, particularly with regards to the signature. -/// -/// This is typically passed into [`traits::Applyable::apply`], which should execute -/// [`CheckedExtrinsic::function`], alongside all other bits and bobs. +/// Definition of something that the external world might want to say; its +/// existence implies that it has been checked and is good, particularly with +/// regards to the signature. #[derive(PartialEq, Eq, Clone, sp_core::RuntimeDebug)] pub struct CheckedExtrinsic { /// Who this purports to be from and the number of extrinsics have come before diff --git a/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs b/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs index 9c8136ec6e6..f893f8d4bb7 100644 --- a/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs +++ b/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs @@ -95,28 +95,8 @@ where } } -/// An extrinsic right from the external world. This is unchecked and so can contain a signature. -/// -/// An extrinsic is formally described as any external data that is originating from the outside of -/// the runtime and fed into the runtime as a part of the block-body. -/// -/// Inherents are special types of extrinsics that are placed into the block by the block-builder. -/// They are unsigned because the assertion is that they are "inherently true" by virtue of getting -/// past all validators. -/// -/// Transactions are all other statements provided by external entities that the chain deems values -/// and decided to include in the block. This value is typically in the form of fee payment, but it -/// could in principle be any other interaction. Transactions are either signed or unsigned. A -/// sensible transaction pool should ensure that only transactions that are worthwhile are -/// considered for block-building. -#[doc = simple_mermaid::mermaid!("../../../../../docs/mermaid/extrinsics.mmd")] -/// This type is by no means enforced within Substrate, but given its genericness, it is highly -/// likely that for most use-cases it will suffice. Thus, the encoding of this type will dictate -/// exactly what bytes should be sent to a runtime to transact with it. -/// -/// This can be checked using [`Checkable`], yielding a [`CheckedExtrinsic`], which is the -/// counterpart of this type after its signature (and other non-negotiable validity checks) have -/// passed. +/// A extrinsic right from the external world. This is unchecked and so +/// can contain a signature. #[derive(PartialEq, Eq, Clone, Debug)] pub struct UncheckedExtrinsic { /// Information regarding the type of extrinsic this is (inherent or transaction) as well as @@ -326,7 +306,6 @@ where } } -#[docify::export(unchecked_extrinsic_encode_impl)] impl Encode for UncheckedExtrinsic where diff --git a/substrate/primitives/runtime/src/offchain/storage_lock.rs b/substrate/primitives/runtime/src/offchain/storage_lock.rs index 116e1578815..1b795978447 100644 --- a/substrate/primitives/runtime/src/offchain/storage_lock.rs +++ b/substrate/primitives/runtime/src/offchain/storage_lock.rs @@ -250,7 +250,7 @@ impl Lockable for BlockAndTime { /// /// A lock that is persisted in the DB and provides the ability to guard against /// concurrent access in an off-chain worker, with a defined expiry deadline -/// based on the concrete [`Lockable`] implementation. +/// based on the concrete [`Lockable`](Lockable) implementation. pub struct StorageLock<'a, L = Time> { // A storage value ref which defines the DB entry representing the lock. value_ref: StorageValueRef<'a>, diff --git a/substrate/primitives/session/Cargo.toml b/substrate/primitives/session/Cargo.toml index 25700210fee..4c11762ffb7 100644 --- a/substrate/primitives/session/Cargo.toml +++ b/substrate/primitives/session/Cargo.toml @@ -9,24 +9,21 @@ repository.workspace = true description = "Primitives for sessions" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -sp-api = { path = "../api", default-features = false } -sp-core = { path = "../core", default-features = false } -sp-runtime = { path = "../runtime", optional = true } -sp-staking = { path = "../staking", default-features = false } -sp-std = { path = "../std", default-features = false } +sp-api = { path = "../api", default-features = false} +sp-core = { path = "../core", default-features = false} +sp-runtime = { path = "../runtime", optional = true} +sp-staking = { path = "../staking", default-features = false} +sp-std = { path = "../std", default-features = false} sp-keystore = { path = "../keystore", optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "scale-info/std", diff --git a/substrate/primitives/staking/Cargo.toml b/substrate/primitives/staking/Cargo.toml index 2c721265142..ef96276a003 100644 --- a/substrate/primitives/staking/Cargo.toml +++ b/substrate/primitives/staking/Cargo.toml @@ -9,24 +9,21 @@ repository.workspace = true description = "A crate which contains primitives that are useful for implementation that uses staking approaches in general. Definitions related to sessions, slashing, etc go here." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"], optional = true } +serde = { version = "1.0.188", default-features = false, features = ["derive", "alloc"], optional = true } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } impl-trait-for-tuples = "0.2.2" -sp-core = { path = "../core", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } -sp-std = { path = "../std", default-features = false } +sp-core = { path = "../core", default-features = false} +sp-runtime = { path = "../runtime", default-features = false} +sp-std = { path = "../std", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "scale-info/std", @@ -35,4 +32,4 @@ std = [ "sp-runtime/std", "sp-std/std", ] -runtime-benchmarks = ["sp-runtime/runtime-benchmarks"] +runtime-benchmarks = [ "sp-runtime/runtime-benchmarks" ] diff --git a/substrate/primitives/state-machine/Cargo.toml b/substrate/primitives/state-machine/Cargo.toml index f891a74dbf4..ec5d9b5ea14 100644 --- a/substrate/primitives/state-machine/Cargo.toml +++ b/substrate/primitives/state-machine/Cargo.toml @@ -10,9 +10,6 @@ repository.workspace = true documentation = "https://docs.rs/sp-state-machine" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -25,11 +22,11 @@ rand = { version = "0.8.5", optional = true } smallvec = "1.11.0" thiserror = { version = "1.0.48", optional = true } tracing = { version = "0.1.29", optional = true } -sp-core = { path = "../core", default-features = false } -sp-externalities = { path = "../externalities", default-features = false } -sp-panic-handler = { path = "../panic-handler", optional = true } -sp-std = { path = "../std", default-features = false } -sp-trie = { path = "../trie", default-features = false } +sp-core = { path = "../core", default-features = false} +sp-externalities = { path = "../externalities", default-features = false} +sp-panic-handler = { path = "../panic-handler", optional = true} +sp-std = { path = "../std", default-features = false} +sp-trie = { path = "../trie", default-features = false} trie-db = { version = "0.28.0", default-features = false } [dev-dependencies] @@ -40,7 +37,7 @@ sp-runtime = { path = "../runtime" } assert_matches = "1.5" [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "hash-db/std", diff --git a/substrate/primitives/state-machine/src/lib.rs b/substrate/primitives/state-machine/src/lib.rs index 5909a30a814..0e2b9bfdfff 100644 --- a/substrate/primitives/state-machine/src/lib.rs +++ b/substrate/primitives/state-machine/src/lib.rs @@ -142,6 +142,7 @@ pub use crate::{ mod std_reexport { pub use crate::{ basic::BasicExternalities, + error::{Error, ExecutionError}, in_memory_backend::new_in_mem, read_only::{InspectState, ReadOnlyExternalities}, testing::TestExternalities, @@ -288,7 +289,7 @@ mod execution { let result = self .exec - .call(&mut ext, self.runtime_code, self.method, self.call_data, self.context) + .call(&mut ext, self.runtime_code, self.method, self.call_data, false, self.context) .0; self.overlay @@ -1119,9 +1120,10 @@ mod tests { _: &RuntimeCode, _method: &str, _data: &[u8], + use_native: bool, _: CallContext, ) -> (CallResult, bool) { - let using_native = self.native_available; + let using_native = use_native && self.native_available; match (using_native, self.native_succeeds, self.fallback_succeeds) { (true, true, _) | (false, _, true) => ( Ok(vec![ diff --git a/substrate/primitives/state-machine/src/overlayed_changes/changeset.rs b/substrate/primitives/state-machine/src/overlayed_changes/changeset.rs index 59589dbbb37..8f2d02fd684 100644 --- a/substrate/primitives/state-machine/src/overlayed_changes/changeset.rs +++ b/substrate/primitives/state-machine/src/overlayed_changes/changeset.rs @@ -298,7 +298,7 @@ impl OverlayedMap { /// Call this when control returns from the runtime. /// - /// This rollbacks all dangling transaction left open by 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 let ExecutionMode::Client = self.execution_mode { diff --git a/substrate/primitives/state-machine/src/overlayed_changes/mod.rs b/substrate/primitives/state-machine/src/overlayed_changes/mod.rs index 626cf6c3caf..28cfecf1dbd 100644 --- a/substrate/primitives/state-machine/src/overlayed_changes/mod.rs +++ b/substrate/primitives/state-machine/src/overlayed_changes/mod.rs @@ -348,7 +348,7 @@ impl OverlayedChanges { /// `None` can be used to delete a value specified by the given key. /// /// Can be rolled back or committed when called inside a transaction. - pub fn set_child_storage( + pub(crate) fn set_child_storage( &mut self, child_info: &ChildInfo, key: StorageKey, @@ -373,7 +373,7 @@ impl OverlayedChanges { /// Clear child storage of given storage key. /// /// Can be rolled back or committed when called inside a transaction. - pub fn clear_child_storage(&mut self, child_info: &ChildInfo) -> u32 { + pub(crate) fn clear_child_storage(&mut self, child_info: &ChildInfo) -> u32 { self.mark_dirty(); let extrinsic_index = self.extrinsic_index(); @@ -391,7 +391,7 @@ impl OverlayedChanges { /// Removes all key-value pairs which keys share the given prefix. /// /// Can be rolled back or committed when called inside a transaction. - pub fn clear_prefix(&mut self, prefix: &[u8]) -> u32 { + pub(crate) fn clear_prefix(&mut self, prefix: &[u8]) -> u32 { self.mark_dirty(); self.top.clear_where(|key, _| key.starts_with(prefix), self.extrinsic_index()) @@ -400,7 +400,7 @@ impl OverlayedChanges { /// Removes all key-value pairs which keys share the given prefix. /// /// Can be rolled back or committed when called inside a transaction - pub fn clear_child_prefix(&mut self, child_info: &ChildInfo, prefix: &[u8]) -> u32 { + pub(crate) fn clear_child_prefix(&mut self, child_info: &ChildInfo, prefix: &[u8]) -> u32 { self.mark_dirty(); let extrinsic_index = self.extrinsic_index(); @@ -498,7 +498,7 @@ impl OverlayedChanges { /// Call this when control returns from the runtime. /// - /// This rollbacks all dangling transaction left open by the runtime. + /// This commits all dangling transaction left open by the runtime. /// Calling this while outside the runtime will return an error. pub fn exit_runtime(&mut self) -> Result<(), NotInRuntime> { self.top.exit_runtime()?; diff --git a/substrate/primitives/state-machine/src/trie_backend.rs b/substrate/primitives/state-machine/src/trie_backend.rs index 7496463e642..7b337b5fd54 100644 --- a/substrate/primitives/state-machine/src/trie_backend.rs +++ b/substrate/primitives/state-machine/src/trie_backend.rs @@ -33,12 +33,12 @@ use sp_core::storage::{ChildInfo, StateVersion}; #[cfg(feature = "std")] use sp_trie::{ cache::{LocalTrieCache, TrieCache}, - MemoryDB, + recorder::Recorder, + MemoryDB, StorageProof, }; #[cfg(not(feature = "std"))] use sp_trie::{Error, NodeCodec}; -use sp_trie::{MerkleValue, PrefixedMemoryDB, StorageProof, TrieRecorderProvider}; - +use sp_trie::{MerkleValue, PrefixedMemoryDB}; use trie_db::TrieCache as TrieCacheT; #[cfg(not(feature = "std"))] use trie_db::{node::NodeOwned, CachedValue}; @@ -112,6 +112,8 @@ pub struct UnimplementedCacheProvider { // Not strictly necessary, but the H bound allows to use this as a drop-in // replacement for the `LocalTrieCache` in no-std contexts. _phantom: core::marker::PhantomData, + // Statically prevents construction. + _infallible: core::convert::Infallible, } #[cfg(not(feature = "std"))] @@ -154,83 +156,52 @@ impl TrieCacheProvider for UnimplementedCacheProvider { } } -/// Recorder provider that allows construction of a [`TrieBackend`] and satisfies the requirements, -/// but can never be instantiated. -#[cfg(not(feature = "std"))] -pub struct UnimplementedRecorderProvider { - // Not strictly necessary, but the H bound allows to use this as a drop-in - // replacement for the [`sp_trie::recorder::Recorder`] in no-std contexts. - _phantom: core::marker::PhantomData, -} - -#[cfg(not(feature = "std"))] -impl trie_db::TrieRecorder for UnimplementedRecorderProvider { - fn record<'a>(&mut self, _access: trie_db::TrieAccess<'a, H::Out>) { - unimplemented!() - } - - fn trie_nodes_recorded_for_key(&self, _key: &[u8]) -> trie_db::RecordedForKey { - unimplemented!() - } -} - -#[cfg(not(feature = "std"))] -impl TrieRecorderProvider for UnimplementedRecorderProvider { - type Recorder<'a> = UnimplementedRecorderProvider where H: 'a; - - fn drain_storage_proof(self) -> Option { - unimplemented!() - } - - fn as_trie_recorder(&self, _storage_root: H::Out) -> Self::Recorder<'_> { - unimplemented!() - } -} - #[cfg(feature = "std")] type DefaultCache = LocalTrieCache; #[cfg(not(feature = "std"))] type DefaultCache = UnimplementedCacheProvider; -#[cfg(feature = "std")] -type DefaultRecorder = sp_trie::recorder::Recorder; - -#[cfg(not(feature = "std"))] -type DefaultRecorder = UnimplementedRecorderProvider; - /// Builder for creating a [`TrieBackend`]. -pub struct TrieBackendBuilder< - S: TrieBackendStorage, - H: Hasher, - C = DefaultCache, - R = DefaultRecorder, -> { +pub struct TrieBackendBuilder, H: Hasher, C = DefaultCache> { storage: S, root: H::Out, - recorder: Option, + #[cfg(feature = "std")] + recorder: Option>, cache: Option, } -impl TrieBackendBuilder +impl TrieBackendBuilder> where S: TrieBackendStorage, H: Hasher, { /// Create a new builder instance. pub fn new(storage: S, root: H::Out) -> Self { - Self { storage, root, recorder: None, cache: None } + Self { + storage, + root, + #[cfg(feature = "std")] + recorder: None, + cache: None, + } } } -impl TrieBackendBuilder +impl TrieBackendBuilder where S: TrieBackendStorage, H: Hasher, { /// Create a new builder instance. pub fn new_with_cache(storage: S, root: H::Out, cache: C) -> Self { - Self { storage, root, recorder: None, cache: Some(cache) } + Self { + storage, + root, + #[cfg(feature = "std")] + recorder: None, + cache: Some(cache), + } } /// Wrap the given [`TrieBackend`]. /// @@ -239,47 +210,53 @@ where /// backend. /// /// The backend storage and the cache will be taken from `other`. - pub fn wrap(other: &TrieBackend) -> TrieBackendBuilder<&S, H, &C, R> { + pub fn wrap(other: &TrieBackend) -> TrieBackendBuilder<&S, H, &C> { TrieBackendBuilder { storage: other.essence.backend_storage(), root: *other.essence.root(), + #[cfg(feature = "std")] recorder: None, cache: other.essence.trie_node_cache.as_ref(), } } /// Use the given optional `recorder` for the to be configured [`TrieBackend`]. - pub fn with_optional_recorder(self, recorder: Option) -> Self { + #[cfg(feature = "std")] + pub fn with_optional_recorder(self, recorder: Option>) -> Self { Self { recorder, ..self } } /// Use the given `recorder` for the to be configured [`TrieBackend`]. - pub fn with_recorder(self, recorder: R) -> Self { + #[cfg(feature = "std")] + pub fn with_recorder(self, recorder: Recorder) -> Self { Self { recorder: Some(recorder), ..self } } /// Use the given optional `cache` for the to be configured [`TrieBackend`]. - pub fn with_optional_cache(self, cache: Option) -> TrieBackendBuilder { + pub fn with_optional_cache(self, cache: Option) -> TrieBackendBuilder { TrieBackendBuilder { cache, root: self.root, storage: self.storage, + #[cfg(feature = "std")] recorder: self.recorder, } } /// Use the given `cache` for the to be configured [`TrieBackend`]. - pub fn with_cache(self, cache: LC) -> TrieBackendBuilder { + pub fn with_cache(self, cache: LC) -> TrieBackendBuilder { TrieBackendBuilder { cache: Some(cache), root: self.root, storage: self.storage, + #[cfg(feature = "std")] recorder: self.recorder, } } /// Build the configured [`TrieBackend`]. - pub fn build(self) -> TrieBackend { + #[cfg(feature = "std")] + pub fn build(self) -> TrieBackend { TrieBackend { essence: TrieBackendEssence::new_with_cache_and_recorder( self.storage, @@ -290,18 +267,27 @@ where next_storage_key_cache: Default::default(), } } + + /// Build the configured [`TrieBackend`]. + #[cfg(not(feature = "std"))] + pub fn build(self) -> TrieBackend { + TrieBackend { + essence: TrieBackendEssence::new_with_cache(self.storage, self.root, self.cache), + next_storage_key_cache: Default::default(), + } + } } /// A cached iterator. -struct CachedIter +struct CachedIter where H: Hasher, { last_key: sp_std::vec::Vec, - iter: RawIter, + iter: RawIter, } -impl Default for CachedIter +impl Default for CachedIter where H: Hasher, { @@ -327,32 +313,23 @@ fn access_cache(cell: &CacheCell, callback: impl FnOnce(&mut T) -> R) - } /// Patricia trie-based backend. Transaction type is an overlay of changes to commit. -pub struct TrieBackend< - S: TrieBackendStorage, - H: Hasher, - C = DefaultCache, - R = DefaultRecorder, -> { - pub(crate) essence: TrieBackendEssence, - next_storage_key_cache: CacheCell>>, +pub struct TrieBackend, H: Hasher, C = DefaultCache> { + pub(crate) essence: TrieBackendEssence, + next_storage_key_cache: CacheCell>>, } -impl< - S: TrieBackendStorage, - H: Hasher, - C: TrieCacheProvider + Send + Sync, - R: TrieRecorderProvider + Send + Sync, - > TrieBackend +impl, H: Hasher, C: TrieCacheProvider + Send + Sync> + TrieBackend where H::Out: Codec, { #[cfg(test)] - pub(crate) fn from_essence(essence: TrieBackendEssence) -> Self { + pub(crate) fn from_essence(essence: TrieBackendEssence) -> Self { Self { essence, next_storage_key_cache: Default::default() } } /// Get backend essence reference. - pub fn essence(&self) -> &TrieBackendEssence { + pub fn essence(&self) -> &TrieBackendEssence { &self.essence } @@ -384,31 +361,28 @@ where /// Extract the [`StorageProof`]. /// /// This only returns `Some` when there was a recorder set. + #[cfg(feature = "std")] pub fn extract_proof(mut self) -> Option { - self.essence.recorder.take().and_then(|r| r.drain_storage_proof()) + self.essence.recorder.take().map(|r| r.drain_storage_proof()) } } -impl, H: Hasher, C: TrieCacheProvider, R: TrieRecorderProvider> - sp_std::fmt::Debug for TrieBackend +impl, H: Hasher, C: TrieCacheProvider> sp_std::fmt::Debug + for TrieBackend { fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { write!(f, "TrieBackend") } } -impl< - S: TrieBackendStorage, - H: Hasher, - C: TrieCacheProvider + Send + Sync, - R: TrieRecorderProvider + Send + Sync, - > Backend for TrieBackend +impl, H: Hasher, C: TrieCacheProvider + Send + Sync> Backend + for TrieBackend where H::Out: Ord + Codec, { type Error = crate::DefaultError; type TrieBackendStorage = S; - type RawIter = crate::trie_backend_essence::RawIter; + type RawIter = crate::trie_backend_essence::RawIter; fn storage_hash(&self, key: &[u8]) -> Result, Self::Error> { self.essence.storage_hash(key) diff --git a/substrate/primitives/state-machine/src/trie_backend_essence.rs b/substrate/primitives/state-machine/src/trie_backend_essence.rs index 3f789111dee..ad7aeab899c 100644 --- a/substrate/primitives/state-machine/src/trie_backend_essence.rs +++ b/substrate/primitives/state-machine/src/trie_backend_essence.rs @@ -28,19 +28,19 @@ use hash_db::{self, AsHashDB, HashDB, HashDBRef, Hasher, Prefix}; #[cfg(feature = "std")] use parking_lot::RwLock; use sp_core::storage::{ChildInfo, ChildType, StateVersion}; -#[cfg(feature = "std")] -use sp_std::sync::Arc; use sp_std::{boxed::Box, marker::PhantomData, vec::Vec}; +#[cfg(feature = "std")] +use sp_trie::recorder::Recorder; use sp_trie::{ child_delta_trie_root, delta_trie_root, empty_child_trie_root, read_child_trie_first_descedant_value, read_child_trie_hash, read_child_trie_value, read_trie_first_descedant_value, read_trie_value, trie_types::{TrieDBBuilder, TrieError}, DBValue, KeySpacedDB, MerkleValue, NodeCodec, PrefixedMemoryDB, Trie, TrieCache, - TrieDBRawIterator, TrieRecorder, TrieRecorderProvider, + TrieDBRawIterator, TrieRecorder, }; #[cfg(feature = "std")] -use std::collections::HashMap; +use std::{collections::HashMap, sync::Arc}; // In this module, we only use layout for read operation and empty root, // where V1 and V0 are equivalent. use sp_trie::LayoutV1 as Layout; @@ -83,7 +83,7 @@ enum IterState { } /// A raw iterator over the storage. -pub struct RawIter +pub struct RawIter where H: Hasher, { @@ -93,26 +93,25 @@ where child_info: Option, trie_iter: TrieDBRawIterator>, state: IterState, - _phantom: PhantomData<(S, C, R)>, + _phantom: PhantomData<(S, C)>, } -impl RawIter +impl RawIter where H: Hasher, S: TrieBackendStorage, H::Out: Codec + Ord, C: TrieCacheProvider + Send + Sync, - R: TrieRecorderProvider + Send + Sync, { #[inline] - fn prepare( + fn prepare( &mut self, - backend: &TrieBackendEssence, + backend: &TrieBackendEssence, callback: impl FnOnce( &sp_trie::TrieDB>, &mut TrieDBRawIterator>, - ) -> Option::Out>>>>, - ) -> Option> { + ) -> Option::Out>>>>, + ) -> Option> { if !matches!(self.state, IterState::Pending) { return None } @@ -140,7 +139,7 @@ where } } -impl Default for RawIter +impl Default for RawIter where H: Hasher, { @@ -157,15 +156,14 @@ where } } -impl StorageIterator for RawIter +impl StorageIterator for RawIter where H: Hasher, S: TrieBackendStorage, H::Out: Codec + Ord, C: TrieCacheProvider + Send + Sync, - R: TrieRecorderProvider + Send + Sync, { - type Backend = crate::TrieBackend; + type Backend = crate::TrieBackend; type Error = crate::DefaultError; #[inline] @@ -206,17 +204,18 @@ where } /// Patricia trie-based pairs storage essence. -pub struct TrieBackendEssence, H: Hasher, C, R> { +pub struct TrieBackendEssence, H: Hasher, C> { storage: S, root: H::Out, empty: H::Out, #[cfg(feature = "std")] pub(crate) cache: Arc>>, pub(crate) trie_node_cache: Option, - pub(crate) recorder: Option, + #[cfg(feature = "std")] + pub(crate) recorder: Option>, } -impl, H: Hasher, C, R> TrieBackendEssence { +impl, H: Hasher, C> TrieBackendEssence { /// Create new trie-based backend. pub fn new(storage: S, root: H::Out) -> Self { Self::new_with_cache(storage, root, None) @@ -231,22 +230,23 @@ impl, H: Hasher, C, R> TrieBackendEssence { #[cfg(feature = "std")] cache: Arc::new(RwLock::new(Cache::new())), trie_node_cache: cache, + #[cfg(feature = "std")] recorder: None, } } /// Create new trie-based backend. + #[cfg(feature = "std")] pub fn new_with_cache_and_recorder( storage: S, root: H::Out, cache: Option, - recorder: Option, + recorder: Option>, ) -> Self { TrieBackendEssence { storage, root, empty: H::hash(&[0u8]), - #[cfg(feature = "std")] cache: Arc::new(RwLock::new(Cache::new())), trie_node_cache: cache, recorder, @@ -289,31 +289,37 @@ impl, H: Hasher, C, R> TrieBackendEssence { } } -impl, H: Hasher, C: TrieCacheProvider, R: TrieRecorderProvider> - TrieBackendEssence -{ +impl, H: Hasher, C: TrieCacheProvider> TrieBackendEssence { /// Call the given closure passing it the recorder and the cache. /// /// If the given `storage_root` is `None`, `self.root` will be used. #[inline] - fn with_recorder_and_cache( + fn with_recorder_and_cache( &self, storage_root: Option, callback: impl FnOnce( Option<&mut dyn TrieRecorder>, Option<&mut dyn TrieCache>>, - ) -> RE, - ) -> RE { + ) -> R, + ) -> R { let storage_root = storage_root.unwrap_or_else(|| self.root); let mut cache = self.trie_node_cache.as_ref().map(|c| c.as_trie_db_cache(storage_root)); let cache = cache.as_mut().map(|c| c as _); - let mut recorder = self.recorder.as_ref().map(|r| r.as_trie_recorder(storage_root)); - let recorder = match recorder.as_mut() { - Some(recorder) => Some(recorder as &mut dyn TrieRecorder), - None => None, - }; - callback(recorder, cache) + #[cfg(feature = "std")] + { + let mut recorder = self.recorder.as_ref().map(|r| r.as_trie_recorder(storage_root)); + let recorder = match recorder.as_mut() { + Some(recorder) => Some(recorder as &mut dyn TrieRecorder), + None => None, + }; + callback(recorder, cache) + } + + #[cfg(not(feature = "std"))] + { + callback(None, cache) + } } /// Call the given closure passing it the recorder and the cache. @@ -323,14 +329,15 @@ impl, H: Hasher, C: TrieCacheProvider, R: TrieRecord /// the new storage root. This is required to register the changes in the cache /// for the correct storage root. The given `storage_root` corresponds to the root of the "old" /// trie. If the value is not given, `self.root` is used. - fn with_recorder_and_cache_for_storage_root( + #[cfg(feature = "std")] + fn with_recorder_and_cache_for_storage_root( &self, storage_root: Option, callback: impl FnOnce( Option<&mut dyn TrieRecorder>, Option<&mut dyn TrieCache>>, - ) -> (Option, RE), - ) -> RE { + ) -> (Option, R), + ) -> R { let storage_root = storage_root.unwrap_or_else(|| self.root); let mut recorder = self.recorder.as_ref().map(|r| r.as_trie_recorder(storage_root)); let recorder = match recorder.as_mut() { @@ -354,26 +361,46 @@ impl, H: Hasher, C: TrieCacheProvider, R: TrieRecord result } + + #[cfg(not(feature = "std"))] + fn with_recorder_and_cache_for_storage_root( + &self, + _storage_root: Option, + callback: impl FnOnce( + Option<&mut dyn TrieRecorder>, + Option<&mut dyn TrieCache>>, + ) -> (Option, R), + ) -> R { + if let Some(local_cache) = self.trie_node_cache.as_ref() { + let mut cache = local_cache.as_trie_db_mut_cache(); + + let (new_root, r) = callback(None, Some(&mut cache)); + + if let Some(new_root) = new_root { + local_cache.merge(cache, new_root); + } + + r + } else { + callback(None, None).1 + } + } } -impl< - S: TrieBackendStorage, - H: Hasher, - C: TrieCacheProvider + Send + Sync, - R: TrieRecorderProvider + Send + Sync, - > TrieBackendEssence +impl, H: Hasher, C: TrieCacheProvider + Send + Sync> + TrieBackendEssence where H::Out: Codec + Ord, { /// Calls the given closure with a [`TrieDb`] constructed for the given /// storage root and (optionally) child trie. #[inline] - fn with_trie_db( + fn with_trie_db( &self, root: H::Out, child_info: Option<&ChildInfo>, - callback: impl FnOnce(&sp_trie::TrieDB>) -> RE, - ) -> RE { + callback: impl FnOnce(&sp_trie::TrieDB>) -> R, + ) -> R { let backend = self as &dyn HashDBRef>; let db = child_info .as_ref() @@ -582,7 +609,7 @@ where } /// Create a raw iterator over the storage. - pub fn raw_iter(&self, args: IterArgs) -> Result> { + pub fn raw_iter(&self, args: IterArgs) -> Result> { let root = if let Some(child_info) = args.child_info.as_ref() { let root = match self.child_root(&child_info)? { Some(root) => root, @@ -804,28 +831,19 @@ where } } -impl< - S: TrieBackendStorage, - H: Hasher, - C: TrieCacheProvider + Send + Sync, - R: TrieRecorderProvider + Send + Sync, - > AsHashDB for TrieBackendEssence +impl, H: Hasher, C: TrieCacheProvider + Send + Sync> + AsHashDB for TrieBackendEssence { fn as_hash_db<'b>(&'b self) -> &'b (dyn HashDB + 'b) { self } - fn as_hash_db_mut<'b>(&'b mut self) -> &'b mut (dyn HashDB + 'b) { self } } -impl< - S: TrieBackendStorage, - H: Hasher, - C: TrieCacheProvider + Send + Sync, - R: TrieRecorderProvider + Send + Sync, - > HashDB for TrieBackendEssence +impl, H: Hasher, C: TrieCacheProvider + Send + Sync> HashDB + for TrieBackendEssence { fn get(&self, key: &H::Out, prefix: Prefix) -> Option { if *key == self.empty { @@ -857,12 +875,8 @@ impl< } } -impl< - S: TrieBackendStorage, - H: Hasher, - C: TrieCacheProvider + Send + Sync, - R: TrieRecorderProvider + Send + Sync, - > HashDBRef for TrieBackendEssence +impl, H: Hasher, C: TrieCacheProvider + Send + Sync> + HashDBRef for TrieBackendEssence { fn get(&self, key: &H::Out, prefix: Prefix) -> Option { HashDB::get(self, key, prefix) @@ -914,10 +928,7 @@ mod test { .expect("insert failed"); }; - let essence_1 = - TrieBackendEssence::<_, _, LocalTrieCache<_>, sp_trie::recorder::Recorder<_>>::new( - mdb, root_1, - ); + let essence_1 = TrieBackendEssence::<_, _, LocalTrieCache<_>>::new(mdb, root_1); let mdb = essence_1.backend_storage().clone(); let essence_1 = TrieBackend::from_essence(essence_1); @@ -927,10 +938,7 @@ mod test { assert_eq!(essence_1.next_storage_key(b"5"), Ok(Some(b"6".to_vec()))); assert_eq!(essence_1.next_storage_key(b"6"), Ok(None)); - let essence_2 = - TrieBackendEssence::<_, _, LocalTrieCache<_>, sp_trie::recorder::Recorder<_>>::new( - mdb, root_2, - ); + let essence_2 = TrieBackendEssence::<_, _, LocalTrieCache<_>>::new(mdb, root_2); assert_eq!(essence_2.next_child_storage_key(child_info, b"2"), Ok(Some(b"3".to_vec()))); assert_eq!(essence_2.next_child_storage_key(child_info, b"3"), Ok(Some(b"4".to_vec()))); diff --git a/substrate/primitives/statement-store/Cargo.toml b/substrate/primitives/statement-store/Cargo.toml index f4a80eb0c38..658229cef22 100644 --- a/substrate/primitives/statement-store/Cargo.toml +++ b/substrate/primitives/statement-store/Cargo.toml @@ -9,22 +9,19 @@ repository.workspace = true description = "A crate which contains primitives related to the statement store" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -sp-core = { path = "../core", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } -sp-std = { path = "../std", 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 } +sp-core = { path = "../core", default-features = false} +sp-runtime = { path = "../runtime", default-features = false} +sp-std = { path = "../std", 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} thiserror = { version = "1.0", optional = true } # ECIES dependencies @@ -34,10 +31,10 @@ curve25519-dalek = { version = "4.0.0", 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 } +rand = { version = "0.8.5", features = ["small_rng"], optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "aes-gcm", "aes-gcm?/std", diff --git a/substrate/primitives/std/Cargo.toml b/substrate/primitives/std/Cargo.toml index f349a7b1196..2283a4a97a4 100644 --- a/substrate/primitives/std/Cargo.toml +++ b/substrate/primitives/std/Cargo.toml @@ -10,12 +10,9 @@ description = "Lowest-abstraction level for the Substrate runtime: just exports documentation = "https://docs.rs/sp-std" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [features] -default = ["std"] +default = [ "std" ] std = [] diff --git a/substrate/primitives/storage/Cargo.toml b/substrate/primitives/storage/Cargo.toml index 429c17fde50..11e574f1c4c 100644 --- a/substrate/primitives/storage/Cargo.toml +++ b/substrate/primitives/storage/Cargo.toml @@ -10,9 +10,6 @@ repository.workspace = true documentation = "https://docs.rs/sp-storage/" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,12 +17,12 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } impl-serde = { version = "0.4.0", optional = true, default-features = false } ref-cast = "1.0.0" -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"], optional = true } -sp-debug-derive = { path = "../debug-derive", default-features = false } -sp-std = { path = "../std", default-features = false } +serde = { version = "1.0.188", default-features = false, features = ["derive", "alloc"], optional = true } +sp-debug-derive = { path = "../debug-derive", default-features = false} +sp-std = { path = "../std", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "impl-serde/std", @@ -35,4 +32,4 @@ std = [ ] # Serde support without relying on std features. -serde = ["dep:serde", "impl-serde"] +serde = [ "dep:serde", "impl-serde" ] diff --git a/substrate/primitives/test-primitives/Cargo.toml b/substrate/primitives/test-primitives/Cargo.toml index 536cca334dd..a3775d7f61f 100644 --- a/substrate/primitives/test-primitives/Cargo.toml +++ b/substrate/primitives/test-primitives/Cargo.toml @@ -8,23 +8,20 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, features = ["derive"], optional = 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-std = { path = "../std", default-features = false } +serde = { version = "1.0.188", default-features = false, features = ["derive"], optional = 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-std = { path = "../std", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "scale-info/std", diff --git a/substrate/primitives/timestamp/Cargo.toml b/substrate/primitives/timestamp/Cargo.toml index ea1e4ebbee3..44b0fdd831c 100644 --- a/substrate/primitives/timestamp/Cargo.toml +++ b/substrate/primitives/timestamp/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Substrate core types and inherents for timestamps." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,12 +16,12 @@ targets = ["x86_64-unknown-linux-gnu"] async-trait = { version = "0.1.57", optional = true } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } thiserror = { version = "1.0.48", optional = true } -sp-inherents = { path = "../inherents", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } -sp-std = { path = "../std", default-features = false } +sp-inherents = { path = "../inherents", default-features = false} +sp-runtime = { path = "../runtime", default-features = false} +sp-std = { path = "../std", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "async-trait", "codec/std", diff --git a/substrate/primitives/tracing/Cargo.toml b/substrate/primitives/tracing/Cargo.toml index 0ad3cd0705b..0f7e217ec38 100644 --- a/substrate/primitives/tracing/Cargo.toml +++ b/substrate/primitives/tracing/Cargo.toml @@ -9,16 +9,13 @@ repository.workspace = true description = "Instrumentation primitives and macros for Substrate." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] # let's default to wasm32 default-target = "wasm32-unknown-unknown" # with the tracing enabled features = ["with-tracing"] # allowing for linux-gnu here, too, allows for `std` to show up as well -targets = ["wasm32-unknown-unknown", "x86_64-unknown-linux-gnu"] +targets = ["x86_64-unknown-linux-gnu", "wasm32-unknown-unknown"] [dependencies] sp-std = { path = "../std", default-features = false } @@ -26,14 +23,14 @@ codec = { version = "3.6.1", package = "parity-scale-codec", default-features = "derive", ] } tracing = { version = "0.1.29", default-features = false } -tracing-core = { version = "0.1.32", default-features = false } +tracing-core = { version = "0.1.28", default-features = false } tracing-subscriber = { version = "0.2.25", optional = true, features = [ "tracing-log", ] } [features] -default = ["std"] -with-tracing = ["codec/derive", "codec/full"] +default = [ "std" ] +with-tracing = [ "codec/derive", "codec/full" ] std = [ "codec/std", "sp-std/std", diff --git a/substrate/primitives/transaction-pool/Cargo.toml b/substrate/primitives/transaction-pool/Cargo.toml index 6e66910ac38..d1d38ffa1af 100644 --- a/substrate/primitives/transaction-pool/Cargo.toml +++ b/substrate/primitives/transaction-pool/Cargo.toml @@ -10,16 +10,13 @@ description = "Transaction pool runtime facing API." documentation = "https://docs.rs/sp-transaction-pool" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-api = { path = "../api", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } +sp-api = { path = "../api", default-features = false} +sp-runtime = { path = "../runtime", default-features = false} [features] -default = ["std"] -std = ["sp-api/std", "sp-runtime/std"] +default = [ "std" ] +std = [ "sp-api/std", "sp-runtime/std" ] diff --git a/substrate/primitives/transaction-storage-proof/Cargo.toml b/substrate/primitives/transaction-storage-proof/Cargo.toml index f8c3ded2ef7..5a35dd8f11f 100644 --- a/substrate/primitives/transaction-storage-proof/Cargo.toml +++ b/substrate/primitives/transaction-storage-proof/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,14 +16,14 @@ targets = ["x86_64-unknown-linux-gnu"] async-trait = { version = "0.1.57", optional = true } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -sp-core = { path = "../core", optional = true } -sp-inherents = { path = "../inherents", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } -sp-std = { path = "../std", default-features = false } -sp-trie = { path = "../trie", optional = true } +sp-core = { path = "../core", optional = true} +sp-inherents = { path = "../inherents", default-features = false} +sp-runtime = { path = "../runtime", default-features = false} +sp-std = { path = "../std", default-features = false} +sp-trie = { path = "../trie", optional = true} [features] -default = ["std"] +default = [ "std" ] std = [ "async-trait", "codec/std", diff --git a/substrate/primitives/trie/Cargo.toml b/substrate/primitives/trie/Cargo.toml index 79ed5c20000..0822d84a76e 100644 --- a/substrate/primitives/trie/Cargo.toml +++ b/substrate/primitives/trie/Cargo.toml @@ -10,9 +10,6 @@ homepage = "https://substrate.io" documentation = "https://docs.rs/sp-trie" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -23,6 +20,7 @@ harness = false [dependencies] ahash = { version = "0.8.2", optional = true } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false } +hashbrown = { version = "0.13.2", optional = true } 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 } @@ -34,9 +32,8 @@ thiserror = { version = "1.0.48", optional = true } tracing = { version = "0.1.29", optional = true } trie-db = { version = "0.28.0", default-features = false } trie-root = { version = "0.18.0", default-features = false } -sp-core = { path = "../core", default-features = false } -sp-std = { path = "../std", default-features = false } -sp-externalities = { path = "../externalities", default-features = false } +sp-core = { path = "../core", default-features = false} +sp-std = { path = "../std", default-features = false} schnellru = { version = "0.2.1", optional = true } [dev-dependencies] @@ -47,11 +44,12 @@ trie-standardmap = "0.16.0" sp-runtime = { path = "../runtime" } [features] -default = ["std"] +default = [ "std" ] std = [ "ahash", "codec/std", "hash-db/std", + "hashbrown", "lazy_static", "memory-db/std", "nohash-hasher", @@ -60,7 +58,6 @@ std = [ "scale-info/std", "schnellru", "sp-core/std", - "sp-externalities/std", "sp-runtime/std", "sp-std/std", "thiserror", diff --git a/substrate/primitives/trie/src/cache/shared_cache.rs b/substrate/primitives/trie/src/cache/shared_cache.rs index e3ba94a2af7..01ac41a1e47 100644 --- a/substrate/primitives/trie/src/cache/shared_cache.rs +++ b/substrate/primitives/trie/src/cache/shared_cache.rs @@ -19,11 +19,11 @@ ///! that combines both caches and is exported to the outside. use super::{CacheSize, NodeCached}; use hash_db::Hasher; +use hashbrown::{hash_set::Entry as SetEntry, HashSet}; use nohash_hasher::BuildNoHashHasher; use parking_lot::{Mutex, RwLock, RwLockWriteGuard}; use schnellru::LruMap; use std::{ - collections::{hash_map::Entry as SetEntry, HashMap}, hash::{BuildHasher, Hasher as _}, sync::Arc, }; @@ -148,7 +148,7 @@ pub struct SharedValueCacheLimiter { heap_size: usize, /// A set with all of the keys deduplicated to save on memory. - known_storage_keys: HashMap, (), ahash::RandomState>, + known_storage_keys: HashSet>, /// A counter with the number of elements that got evicted from the cache. /// @@ -189,10 +189,10 @@ where } self.heap_size += new_item_heap_size; - entry.insert(()); + entry.insert(); }, SetEntry::Occupied(entry) => { - key.storage_key = entry.key().clone(); + key.storage_key = entry.get().clone(); }, } @@ -491,7 +491,7 @@ impl> SharedValueCache { max_inline_size, max_heap_size, heap_size: 0, - known_storage_keys: HashMap::with_hasher(RANDOM_STATE.clone()), + known_storage_keys: Default::default(), items_evicted: 0, max_items_evicted: 0, // Will be set during `update`. }, @@ -778,9 +778,7 @@ mod tests { assert_eq!(1, cache.lru.limiter_mut().known_storage_keys.len()); assert_eq!( 3, // Two instances inside the cache + one extra in `known_storage_keys`. - Arc::strong_count( - cache.lru.limiter_mut().known_storage_keys.get_key_value(&key[..]).unwrap().0 - ) + Arc::strong_count(cache.lru.limiter_mut().known_storage_keys.get(&key[..]).unwrap()) ); assert_eq!(key.len(), cache.lru.limiter().heap_size); assert_eq!(cache.lru.len(), 2); @@ -794,9 +792,7 @@ mod tests { assert_eq!(1, cache.lru.limiter_mut().known_storage_keys.len()); assert_eq!( 3, - Arc::strong_count( - cache.lru.limiter_mut().known_storage_keys.get_key_value(&key[..]).unwrap().0 - ) + Arc::strong_count(cache.lru.limiter_mut().known_storage_keys.get(&key[..]).unwrap()) ); assert_eq!(key.len(), cache.lru.limiter().heap_size); assert_eq!(cache.lru.len(), 2); @@ -816,9 +812,7 @@ mod tests { assert_eq!(1, cache.lru.limiter_mut().known_storage_keys.len()); assert_eq!( 3, - Arc::strong_count( - cache.lru.limiter_mut().known_storage_keys.get_key_value(&key[..]).unwrap().0 - ) + Arc::strong_count(cache.lru.limiter_mut().known_storage_keys.get(&key[..]).unwrap()) ); assert_eq!(key.len(), cache.lru.limiter().heap_size); assert_eq!(cache.lru.len(), 2); @@ -839,7 +833,7 @@ mod tests { assert_eq!(cache.lru.limiter().items_evicted, 2); assert_eq!(10, cache.lru.len()); assert_eq!(10, cache.lru.limiter_mut().known_storage_keys.len()); - assert!(cache.lru.limiter_mut().known_storage_keys.get_key_value(&key[..]).is_none()); + assert!(cache.lru.limiter_mut().known_storage_keys.get(&key[..]).is_none()); assert_eq!(key.len() * 10, cache.lru.limiter().heap_size); assert_eq!(cache.lru.len(), 10); assert!(cache.lru.limiter().heap_size <= cache.lru.limiter().max_heap_size); @@ -860,6 +854,6 @@ mod tests { vec![], ); - assert!(cache.lru.limiter_mut().known_storage_keys.get_key_value(&key[..]).is_none()); + assert!(cache.lru.limiter_mut().known_storage_keys.get(&key[..]).is_none()); } } diff --git a/substrate/primitives/trie/src/lib.rs b/substrate/primitives/trie/src/lib.rs index fd1320b3fbc..1a1ed670454 100644 --- a/substrate/primitives/trie/src/lib.rs +++ b/substrate/primitives/trie/src/lib.rs @@ -30,9 +30,6 @@ mod storage_proof; mod trie_codec; mod trie_stream; -#[cfg(feature = "std")] -pub mod proof_size_extension; - /// Our `NodeCodec`-specific error. pub use error::Error; /// Various re-exports from the `hash-db` crate. @@ -149,29 +146,6 @@ where } } -/// Type that is able to provide a [`trie_db::TrieRecorder`]. -/// -/// Types implementing this trait can be used to maintain recorded state -/// across operations on different [`trie_db::TrieDB`] instances. -pub trait TrieRecorderProvider { - /// Recorder type that is going to be returned by implementors of this trait. - type Recorder<'a>: trie_db::TrieRecorder + 'a - where - Self: 'a; - - /// Create a [`StorageProof`] derived from the internal state. - fn drain_storage_proof(self) -> Option; - - /// Provide a recorder implementing [`trie_db::TrieRecorder`]. - fn as_trie_recorder(&self, storage_root: H::Out) -> Self::Recorder<'_>; -} - -/// Type that is able to provide a proof size estimation. -pub trait ProofSizeProvider { - /// Returns the storage proof size. - fn estimate_encoded_size(&self) -> usize; -} - /// TrieDB error over `TrieConfiguration` trait. pub type TrieError = trie_db::TrieError, CError>; /// Reexport from `hash_db`, with genericity set for `Hasher` trait. diff --git a/substrate/primitives/trie/src/proof_size_extension.rs b/substrate/primitives/trie/src/proof_size_extension.rs deleted file mode 100644 index c97f334494a..00000000000 --- a/substrate/primitives/trie/src/proof_size_extension.rs +++ /dev/null @@ -1,39 +0,0 @@ -// 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. - -//! Externalities extension that provides access to the current proof size -//! of the underlying recorder. - -use crate::ProofSizeProvider; - -sp_externalities::decl_extension! { - /// The proof size extension to fetch the current storage proof size - /// in externalities. - pub struct ProofSizeExt(Box); -} - -impl ProofSizeExt { - /// Creates a new instance of [`ProofSizeExt`]. - pub fn new(recorder: T) -> Self { - ProofSizeExt(Box::new(recorder)) - } - - /// Returns the storage proof size. - pub fn storage_proof_size(&self) -> u64 { - self.0.estimate_encoded_size() as _ - } -} diff --git a/substrate/primitives/trie/src/recorder.rs b/substrate/primitives/trie/src/recorder.rs index 22a22b33b37..154cee3f37d 100644 --- a/substrate/primitives/trie/src/recorder.rs +++ b/substrate/primitives/trie/src/recorder.rs @@ -23,7 +23,7 @@ use crate::{NodeCodec, StorageProof}; use codec::Encode; use hash_db::Hasher; -use parking_lot::{Mutex, MutexGuard}; +use parking_lot::Mutex; use std::{ collections::{HashMap, HashSet}, marker::PhantomData, @@ -80,9 +80,7 @@ impl Default for RecorderInner { /// The trie recorder. /// -/// Owns the recorded data. Is used to transform data into a storage -/// proof and to provide transaction support. The `as_trie_recorder` method provides a -/// [`trie_db::TrieDB`] compatible recorder that implements the actual recording logic. +/// It can be used to record accesses to the trie and then to convert them into a [`StorageProof`]. pub struct Recorder { inner: Arc>>, /// The estimated encoded size of the storage proof this recorder will produce. @@ -107,13 +105,6 @@ impl Clone for Recorder { } impl Recorder { - /// Returns [`RecordedForKey`] per recorded key per trie. - /// - /// There are multiple tries when working with e.g. child tries. - pub fn recorded_keys(&self) -> HashMap<::Out, HashMap, RecordedForKey>> { - self.inner.lock().recorded_keys.clone() - } - /// Returns the recorder as [`TrieRecorder`](trie_db::TrieRecorder) compatible type. /// /// - `storage_root`: The storage root of the trie for which accesses are recorded. This is @@ -121,8 +112,11 @@ impl Recorder { /// /// NOTE: This locks a mutex that stays locked until the return value is dropped. #[inline] - pub fn as_trie_recorder(&self, storage_root: H::Out) -> TrieRecorder<'_, H> { - TrieRecorder:: { + pub fn as_trie_recorder( + &self, + storage_root: H::Out, + ) -> impl trie_db::TrieRecorder + '_ { + TrieRecorder:: { inner: self.inner.lock(), storage_root, encoded_size_estimation: self.encoded_size_estimation.clone(), @@ -237,33 +231,15 @@ impl Recorder { } } -impl crate::ProofSizeProvider for Recorder { - fn estimate_encoded_size(&self) -> usize { - Recorder::estimate_encoded_size(self) - } -} - /// The [`TrieRecorder`](trie_db::TrieRecorder) implementation. -pub struct TrieRecorder<'a, H: Hasher> { - inner: MutexGuard<'a, RecorderInner>, +struct TrieRecorder { + inner: I, storage_root: H::Out, encoded_size_estimation: Arc, _phantom: PhantomData, } -impl crate::TrieRecorderProvider for Recorder { - type Recorder<'a> = TrieRecorder<'a, H> where H: 'a; - - fn drain_storage_proof(self) -> Option { - Some(Recorder::drain_storage_proof(self)) - } - - fn as_trie_recorder(&self, storage_root: H::Out) -> Self::Recorder<'_> { - Recorder::as_trie_recorder(&self, storage_root) - } -} - -impl<'a, H: Hasher> TrieRecorder<'a, H> { +impl>> TrieRecorder { /// Update the recorded keys entry for the given `full_key`. fn update_recorded_keys(&mut self, full_key: &[u8], access: RecordedForKey) { let inner = self.inner.deref_mut(); @@ -307,7 +283,9 @@ impl<'a, H: Hasher> TrieRecorder<'a, H> { } } -impl<'a, H: Hasher> trie_db::TrieRecorder for TrieRecorder<'a, H> { +impl>> trie_db::TrieRecorder + for TrieRecorder +{ fn record(&mut self, access: TrieAccess) { let mut encoded_size_update = 0; diff --git a/substrate/primitives/version/Cargo.toml b/substrate/primitives/version/Cargo.toml index ed056f7ac36..41a83f01f66 100644 --- a/substrate/primitives/version/Cargo.toml +++ b/substrate/primitives/version/Cargo.toml @@ -10,9 +10,6 @@ description = "Version module for the Substrate runtime; Provides a function tha documentation = "https://docs.rs/sp-version" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -21,15 +18,15 @@ codec = { package = "parity-scale-codec", version = "3.6.1", default-features = impl-serde = { version = "0.4.0", default-features = false, optional = true } parity-wasm = { version = "0.45", optional = true } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, features = ["alloc", "derive"], optional = true } +serde = { version = "1.0.188", default-features = false, features = ["derive", "alloc"], optional = true } thiserror = { version = "1.0.48", optional = true } sp-core-hashing-proc-macro = { path = "../core/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-runtime = { path = "../runtime", default-features = false} +sp-std = { path = "../std", default-features = false} +sp-version-proc-macro = { path = "proc-macro", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ "codec/std", "impl-serde/std", @@ -42,4 +39,4 @@ std = [ ] # Serde support without relying on std features. -serde = ["dep:serde", "impl-serde", "sp-runtime/serde"] +serde = [ "dep:serde", "impl-serde", "sp-runtime/serde" ] diff --git a/substrate/primitives/version/proc-macro/Cargo.toml b/substrate/primitives/version/proc-macro/Cargo.toml index f7df8ec113f..7fce559e3ed 100644 --- a/substrate/primitives/version/proc-macro/Cargo.toml +++ b/substrate/primitives/version/proc-macro/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Macro for defining a runtime version." documentation = "https://docs.rs/sp-api-proc-macro" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -19,10 +16,10 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.1", features = ["derive"] } +codec = { package = "parity-scale-codec", version = "3.6.1", features = [ "derive" ] } proc-macro2 = "1.0.56" quote = "1.0.28" -syn = { version = "2.0.40", features = ["extra-traits", "fold", "full", "visit"] } +syn = { version = "2.0.38", features = ["full", "fold", "extra-traits", "visit"] } [dev-dependencies] sp-version = { path = ".." } diff --git a/substrate/primitives/wasm-interface/Cargo.toml b/substrate/primitives/wasm-interface/Cargo.toml index 9fe5cc1f2d0..c7413fec43c 100644 --- a/substrate/primitives/wasm-interface/Cargo.toml +++ b/substrate/primitives/wasm-interface/Cargo.toml @@ -10,9 +10,6 @@ description = "Types and traits for interfacing between the host and the wasm ru documentation = "https://docs.rs/sp-wasm-interface" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -22,9 +19,9 @@ impl-trait-for-tuples = "0.2.2" log = { version = "0.4.17", optional = true } wasmtime = { version = "8.0.1", default-features = false, optional = true } anyhow = { version = "1.0.68", optional = true } -sp-std = { path = "../std", default-features = false } +sp-std = { path = "../std", default-features = false} [features] -default = ["std"] -std = ["codec/std", "log/std", "sp-std/std", "wasmtime"] -wasmtime = ["anyhow", "dep:wasmtime"] +default = [ "std" ] +std = [ "codec/std", "log/std", "sp-std/std", "wasmtime" ] +wasmtime = [ "anyhow", "dep:wasmtime" ] diff --git a/substrate/primitives/weights/Cargo.toml b/substrate/primitives/weights/Cargo.toml index c01e1a5a07f..6642f97029f 100644 --- a/substrate/primitives/weights/Cargo.toml +++ b/substrate/primitives/weights/Cargo.toml @@ -9,46 +9,38 @@ repository.workspace = true description = "Types and traits for interfacing between the host and the wasm runtime." documentation = "https://docs.rs/sp-wasm-interface" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -bounded-collections = { version = "0.1.4", default-features = false } codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -serde = { version = "1.0.193", default-features = false, optional = true, features = ["alloc", "derive"] } +serde = { version = "1.0.188", default-features = false, optional = true, features = ["derive", "alloc"] } smallvec = "1.11.0" -sp-arithmetic = { path = "../arithmetic", default-features = false } -sp-debug-derive = { path = "../debug-derive", default-features = false } -sp-std = { path = "../std", default-features = false } -schemars = { version = "0.8.3", default-features = false, optional = true } +sp-arithmetic = { path = "../arithmetic", default-features = false} +sp-core = { path = "../core", default-features = false} +sp-debug-derive = { path = "../debug-derive", default-features = false} +sp-std = { path = "../std", default-features = false} [features] -default = ["std"] +default = [ "std" ] std = [ - "bounded-collections/std", "codec/std", "scale-info/std", "serde/std", "sp-arithmetic/std", + "sp-core/std", "sp-debug-derive/std", "sp-std/std", ] # By default some types have documentation, `full-metadata-docs` allows to add documentation to # more types in the metadata. -full-metadata-docs = ["scale-info/docs"] +full-metadata-docs = [ "scale-info/docs" ] # Serde support without relying on std features. serde = [ - "bounded-collections/serde", "dep:serde", "scale-info/serde", "sp-arithmetic/serde", -] - -json-schema = [ - "dep:schemars", + "sp-core/serde", ] diff --git a/substrate/primitives/weights/src/lib.rs b/substrate/primitives/weights/src/lib.rs index ef431bddee2..ececb622fa0 100644 --- a/substrate/primitives/weights/src/lib.rs +++ b/substrate/primitives/weights/src/lib.rs @@ -27,7 +27,6 @@ extern crate self as sp_weights; mod weight_meter; mod weight_v2; -use bounded_collections::Get; use codec::{CompactAs, Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; #[cfg(feature = "serde")] @@ -37,6 +36,7 @@ use sp_arithmetic::{ traits::{BaseArithmetic, SaturatedConversion, Unsigned}, Perbill, }; +use sp_core::Get; use sp_debug_derive::RuntimeDebug; pub use weight_meter::*; @@ -270,7 +270,7 @@ pub type NoFee = FixedFee<0, T>; /// # Example /// /// ``` -/// # use bounded_collections::ConstU128; +/// # use sp_core::ConstU128; /// # use sp_weights::ConstantMultiplier; /// // Results in a multiplier of 10 for each unit of weight (or length) /// type LengthToFee = ConstantMultiplier::>; @@ -360,7 +360,7 @@ mod tests { #[test] fn constant_fee_works() { - use bounded_collections::ConstU128; + use sp_core::ConstU128; assert_eq!( ConstantMultiplier::>::weight_to_fee(&Weight::zero()), 0 diff --git a/substrate/primitives/weights/src/weight_v2.rs b/substrate/primitives/weights/src/weight_v2.rs index 3c10929f433..d692aaff8f5 100644 --- a/substrate/primitives/weights/src/weight_v2.rs +++ b/substrate/primitives/weights/src/weight_v2.rs @@ -23,7 +23,6 @@ use super::*; #[derive(Encode, Decode, MaxEncodedLen, TypeInfo, Eq, PartialEq, Copy, Clone, Debug, Default)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))] pub struct Weight { #[codec(compact)] /// The weight of computational time used based on some reference hardware. diff --git a/substrate/scripts/ci/deny.toml b/substrate/scripts/ci/deny.toml index b1dbf773e31..1afb4a4f693 100644 --- a/substrate/scripts/ci/deny.toml +++ b/substrate/scripts/ci/deny.toml @@ -5,7 +5,7 @@ unlicensed = "deny" # See https://spdx.org/licenses/ for list of possible licenses # [possible values: any SPDX 3.11 short identifier (+ optional exception)]. allow = [ - "MPL-2.0", + "MPL-2.0", ] # List of explicitly disallowed licenses # See https://spdx.org/licenses/ for list of possible licenses @@ -34,70 +34,70 @@ confidence-threshold = 0.8 # Allow 1 or more licenses on a per-crate basis, so that particular licenses # aren't accepted for every possible crate as with the normal allow list exceptions = [ - # Each entry is the crate and version constraint, and its specific allow list - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "chain-spec-builder" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "mmr-gadget" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "node-bench" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "node-inspect" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "node-template-release" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "node-testing" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-authority-discovery" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-basic-authorship" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-block-builder" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-chain-spec" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-chain-spec-derive" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-cli" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-client-api" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-client-db" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-aura" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-babe" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-babe-rpc" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-beefy" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-beefy-rpc" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-epochs" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-grandpa" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-grandpa-rpc" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-manual-seal" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-pow" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-slots" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-executor" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-executor-common" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-executor-wasmi" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-executor-wasmtime" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-informant" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-keystore" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-mixnet" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-bitswap" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-common" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-gossip" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-light" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-statement" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-sync" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-test" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-transactions" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-offchain" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-peerset" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-proposer-metrics" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-rpc" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-rpc-api" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-rpc-server" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-rpc-spec-v2" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-runtime-test" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-service" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-service-test" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-state-db" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-statement-store" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-storage-monitor" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-sysinfo" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-telemetry" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-tracing" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-transaction-pool" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-transaction-pool-api" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "staging-node-cli" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "subkey" }, - { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "substrate" }, + # Each entry is the crate and version constraint, and its specific allow list + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "chain-spec-builder" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "mmr-gadget" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "node-bench" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "staging-node-cli" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "node-inspect" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "node-template-release" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "node-testing" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-authority-discovery" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-basic-authorship" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-block-builder" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-chain-spec" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-chain-spec-derive" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-cli" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-client-api" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-client-db" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-aura" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-babe" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-babe-rpc" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-beefy" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-beefy-rpc" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-epochs" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-grandpa" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-grandpa-rpc" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-manual-seal" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-pow" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-consensus-slots" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-executor" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-executor-common" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-executor-wasmi" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-executor-wasmtime" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-informant" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-keystore" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-mixnet" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-bitswap" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-common" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-gossip" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-light" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-sync" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-test" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-transactions" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-network-statement" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-offchain" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-peerset" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-proposer-metrics" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-rpc" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-rpc-api" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-rpc-server" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-rpc-spec-v2" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-runtime-test" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-service" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-service-test" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-state-db" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-statement-store" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-storage-monitor" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-sysinfo" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-telemetry" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-tracing" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-transaction-pool" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "sc-transaction-pool-api" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "subkey" }, + { allow = ["GPL-3.0 WITH Classpath-exception-2.0"], name = "substrate" }, ] # Some crates don't have (easily) machine readable licensing information, @@ -114,6 +114,6 @@ expression = "MIT AND ISC AND OpenSSL" # and the crate will be checked normally, which may produce warnings or errors # depending on the rest of your configuration license-files = [ - # Each entry is a crate relative path, and the (opaque) hash of its contents - { path = "LICENSE", hash = 0xbd0eed23 }, + # Each entry is a crate relative path, and the (opaque) hash of its contents + { path = "LICENSE", hash = 0xbd0eed23 } ] diff --git a/substrate/scripts/ci/node-template-release/Cargo.toml b/substrate/scripts/ci/node-template-release/Cargo.toml index ca9759d5963..73ffce8645b 100644 --- a/substrate/scripts/ci/node-template-release/Cargo.toml +++ b/substrate/scripts/ci/node-template-release/Cargo.toml @@ -7,14 +7,11 @@ license = "GPL-3.0 WITH Classpath-exception-2.0" homepage = "https://substrate.io" publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } flate2 = "1.0" fs_extra = "1.3" glob = "0.3" diff --git a/substrate/src/lib.rs b/substrate/src/lib.rs new file mode 100644 index 00000000000..b5a583fcfcf --- /dev/null +++ b/substrate/src/lib.rs @@ -0,0 +1,242 @@ +// 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 . + +//! # Substrate +//! +//! Substrate is a Rust framework for building blockchains in a modular and extensible way. While in +//! itself un-opinionated, it is the main engine behind the Polkadot ecosystem. +//! +//! [![github]](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/) - [![polkadot]](https://polkadot.network) +//! +//! This crate in itself does not contain any code and is just meant ot be a documentation hub for +//! substrate-based crates. +//! +//! ## Overview +//! +//! Substrate approaches blockchain development with an acknowledgement of a few self-evident +//! truths: +//! +//! 1. Society and technology evolves. +//! 2. Humans are fallible. +//! +//! This, specifically, makes the task of designing a correct, safe and long-lasting blockchain +//! system hard. +//! +//! Nonetheless, in order to achieve this goal, substrate embraces the following: +//! +//! 1. Use of **Rust** as a modern, and safe programming language, which limits human error through +//! various means, most notably memory safety. +//! 2. Substrate is written from the ground-up with a generic, modular and extensible design. This +//! ensures that software components can be easily swapped and upgraded. Examples of this is +//! multiple consensus mechanisms provided by Substrate, as listed below. +//! 3. Lastly, the final blockchain system created with the above properties needs to be +//! upgradeable. In order to achieve this, Substrate is designed as a meta-protocol, whereby the +//! application logic of the blockchain (called "Runtime") is encoded as a Wasm blob, and is +//! stored onchain. The rest of the system (called "Client") acts as the executor of the Wasm +//! blob. +//! +//! In essence, the meta-protocol of all Substrate based chains is the "Runtime as Wasm blob" +//! accord. This enables the Runtime to become inherently upgradeable (without forks). The upgrade +//! is merely a matter of the Wasm blob being changed in the chain state, which is, in principle, +//! same as updating an account's balance. +//! +//! ### Architecture +//! +//! Therefore, Substrate can be visualized as follows: +#![doc = simple_mermaid::mermaid!("../../docs/mermaid/substrate_simple.mmd")] +//! +//! The client and the runtime of course need to communicate. This is done through two concepts: +//! +//! 1. Host functions: a way for the (Wasm) runtime to talk to the client. All host functions are +//! defined in [`sp-io`]. For example, [`sp-io::storage`] are the set of host functions that +//! allow the runtime to read and write data to the on-chain state. +//! 2. Runtime APIs: a way for the client to talk to the Wasm runtime. Runtime APIs are defined +//! using macros and utilities in [`sp-api`]. For example, [`sp-api::Core`] is the most basic +//! runtime API that any blockchain must implement in order to be able to (re) execute blocks. +#![doc = simple_mermaid::mermaid!("../../docs/mermaid/substrate_client_runtime.mmd")] +//! +//! [`FRAME`], Substrate's default runtime development library takes the above even further by +//! embracing a declarative programming model whereby correctness is enhanced and the system is +//! highly configurable through parameterization. +//! +//! All in all, this design enables all substrate-based chains to achieve forkless, self-enacting +//! upgrades out of the box. Combined with governance abilities that are shipped with `FRAME`, this +//! enables a chain to survive the test of time. +//! +//! ## How to Get Stared +//! +//! Most developers want to leave the client side code as-is, and focus on the runtime. To do so, +//! look into the [`frame`] crate, which is the entry point crate into runtime development with +//! FRAME. +//! +//! > Side note, it is entirely possible to craft a substrate-based runtime without FRAME, an +//! > example of which can be found [here](https://github.com/JoshOrndorff/frameless-node-template). +//! +//! In more broad terms, the following avenues exist into developing with substrate: +//! +//! * **Templates**: A number of substrate-based templates exist and they can be used for various +//! purposes, with zero to little additional code needed. All of these templates contain runtimes +//! that are highly configurable and are likely suitable for basic needs. +//! * [`FRAME`]: If need, one can customize that runtime even further, by using `FRAME` and +//! developing custom modules. +//! * **Core**: To the contrary, some developers may want to customize the client side software to +//! achieve novel goals such as a new consensus engine, or a new database backend. While +//! Substrate's main configurability is in the runtime, the client is also highly generic and can +//! be customized to a great extent. +//! +//! ## Structure +//! +//! Substrate is a massive cargo workspace with hundreds of crates, therefore it is useful to know +//! how to navigate its crates. +//! +//! In broad terms, it is divided into three categories: +//! +//! * `sc-*` (short for *substrate-client*) crates, located under `./client` folder. These are all +//! the client crates. Notable examples are crates such as [`sc-network`], various consensus +//! crates, [`sc-rpc-api`] and [`sc-client-db`], all of which are expected to reside in the client +//! side. +//! * `sp-*` (short for *substrate-primitives*) crates, located under `./primitives` folder. These +//! are the traits that glue the client and runtime together, but are not opinionated about what +//! framework is using for building the runtime. Notable examples are [`sp-api`] and [`sp-io`], +//! which form the communication bridge between the client and runtime. +//! * `pallet-*` and `frame-*` crates, located under `./frame` folder. These are the crates related +//! to FRAME. See [`frame`] for more information. +//! +//! ### Wasm Build +//! +//! Many of the Substrate crates, such as entire `sp-*`, need to compile to both Wasm (when a Wasm +//! runtime is being generated) and native (for example, when testing). To achieve this, Substrate +//! follows the convention of the Rust community, and uses a `feature = "std"` to signify that a +//! crate is being built with the standard library, and is built for native. Otherwise, it is built +//! for `no_std`. +//! +//! This can be summarized in `#![cfg_attr(not(feature = "std"), no_std)]`, which you can often find +//! in any Substrate-based runtime. +//! +//! Substrate-based runtimes use [`substrate-wasm-builder`] in their `build.rs` to automatically +//! build their Wasm files as a part of normal build commandsOnce built, the wasm file is placed in +//! `./target/{debug|release}/wbuild/{runtime_name}.wasm`. +//! +//! ### Binaries +//! +//! Multiple binaries are shipped with substrate, the most important of which are located in the +//! `./bin` folder. +//! +//! * [`node`] is an extensive substrate node that contains the superset of all runtime and client +//! side features. The corresponding runtime, called [`kitchensink_runtime`] contains all of the +//! modules that are provided with `FRAME`. This node and runtime is only used for testing and +//! demonstration. +//! * [`chain-spec-builder`]: Utility to build more detailed [chain-spec][`sc-chain-spec`] for the +//! aforementioned node. Other projects typically contain a `build-spec` subcommand that does the +//! same. +//! * [`node-template`]: a template node that contains a minimal set of features and can act as a +//! starting point of a project. +//! * [`subkey`]: Substrate's key management utility. +//! +//! ### Anatomy of a Binary Crate +//! +//! From the above, [`node`] and [`node-template`] are essentially blueprints of a substrate-based +//! project, as the name of the latter is implying. Each substrate-based project typically contains +//! the following: +//! +//! * Under `./runtime`, a `./runtime/src/lib.rs` which is the top level runtime amalgamator file. +//! This file typically contains the [`frame_support::construct_runtime`] macro, which is the +//! final definition of a runtime. +//! +//! * Under `./node`, a `main.rs`, which is the point, and a `./service.rs`, which contains all the +//! client side components. Skimming this file yields an overview of the networking, database, +//! consensus and similar client side components. +//! +//! > The above two are conventions, not rules. +//! +//! ## Parachain? +//! +//! As noted above, Substrate is the main engine behind the Polkadot ecosystem. One of the ways +//! through which Polkadot can be utilized is by building "parachains", blockchains that are +//! connected to Polkadot's shared security. +//! +//! To build a parachain, one could use +//! [`Cumulus`](https://github.com/paritytech/polkadot-sdk/tree/master/cumulus), the library on top +//! of Substrate, empowering any substrate-based chain to be a Polkadot parachain. +//! +//! ## Where To Go Next? +//! +//! Additional noteworthy crates within substrate: +//! +//! - Chain specification of a Substrate node: +//! - [`sc-chain-spec`] +//! - RPC APIs of a Substrate node: [`sc-rpc-api`]/[`sc-rpc`] +//! - CLI Options of a Substrate node: [`sc-cli`] +//! - All of the consensus related crates provided by Substrate: +//! - [`sc-consensus-aura`] +//! - [`sc-consensus-babe`] +//! - [`sc-consensus-grandpa`] +//! - [`sc-consensus-beefy`] +//! - [`sc-consensus-manual-seal`] +//! - [`sc-consensus-pow`] +//! +//! Additional noteworthy external resources: +//! +//! - [Substrate Developer Hub](https://substrate.dev) +//! - [Parity Tech's Documentation Hub](https://paritytech.github.io/) +//! - [Frontier: Substrate's Ethereum Compatibility Library](https://paritytech.github.io/frontier/) +//! - [Polkadot Wiki](https://wiki.polkadot.network/en/) +//! +//! Notable upstream crates: +//! +//! - [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec) +//! - [`parity-db`](https://github.com/paritytech/parity-db) +//! - [`trie`](https://github.com/paritytech/trie) +//! - [`parity-common`](https://github.com/paritytech/parity-common) +//! +//! Templates: +//! +//! - classic [`substrate-node-template`](https://github.com/substrate-developer-hub/substrate-node-template) +//! - classic [cumulus-parachain-template](https://github.com/substrate-developer-hub/substrate-parachain-template) +//! - [`extended-parachain-template`](https://github.com/paritytech/extended-parachain-template) +//! - [`frontier-parachain-template`](https://github.com/paritytech/frontier-parachain-template) +//! +//! [polkadot]: +//! https://img.shields.io/badge/polkadot-E6007A?style=for-the-badge&logo=polkadot&logoColor=white +//! [github]: +//! https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github +//! [`FRAME`]: ../frame/index.html +//! [`sp-io`]: ../sp_io/index.html +//! [`sp-api`]: ../sp_api/index.html +//! [`sp-api`]: ../sp_api/index.html +//! [`sc-client-db`]: ../sc_client_db/index.html +//! [`sc-chain-spec`]: ../sc_chain_spec/index.html +//! [`sc-network`]: ../sc_network/index.html +//! [`sc-rpc-api`]: ../sc_rpc_api/index.html +//! [`sc-rpc`]: ../sc_rpc/index.html +//! [`sc-cli`]: ../sc_cli/index.html +//! [`sc-consensus-aura`]: ../sc_consensus_aura/index.html +//! [`sc-consensus-babe`]: ../sc_consensus_babe/index.html +//! [`sc-consensus-grandpa`]: ../sc_consensus_grandpa/index.html +//! [`sc-consensus-beefy`]: ../sc_consensus_beefy/index.html +//! [`sc-consensus-manual-seal`]: ../sc_consensus_manual_seal/index.html +//! [`sc-consensus-pow`]: ../sc_consensus_pow/index.html +//! [`node`]: ../node_cli/index.html +//! [`node-template`]: ../node_template/index.html +//! [`kitchensink_runtime`]: ../kitchensink_runtime/index.html +//! [`subkey`]: ../subkey/index.html +//! [`chain-spec-builder`]: ../chain_spec_builder/index.html +//! [`substrate-wasm-builder`]: https://crates.io/crates/substrate-wasm-builder + +#![deny(rustdoc::broken_intra_doc_links)] +#![deny(rustdoc::private_intra_doc_links)] diff --git a/substrate/test-utils/Cargo.toml b/substrate/test-utils/Cargo.toml index 526ed7c049c..31bdc0f663a 100644 --- a/substrate/test-utils/Cargo.toml +++ b/substrate/test-utils/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Substrate test utilities" publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,5 +17,5 @@ futures = "0.3.16" tokio = { version = "1.22.0", features = ["macros", "time"] } [dev-dependencies] -trybuild = { version = "1.0.74", features = ["diff"] } +trybuild = { version = "1.0.74", features = [ "diff" ] } sc-service = { path = "../client/service" } diff --git a/substrate/test-utils/cli/Cargo.toml b/substrate/test-utils/cli/Cargo.toml index d654a3aaa72..022db32c34f 100644 --- a/substrate/test-utils/cli/Cargo.toml +++ b/substrate/test-utils/cli/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -29,4 +26,4 @@ sc-service = { path = "../../client/service" } futures = "0.3.28" [features] -try-runtime = ["node-cli/try-runtime"] +try-runtime = [ "node-cli/try-runtime" ] diff --git a/substrate/test-utils/client/Cargo.toml b/substrate/test-utils/client/Cargo.toml index a137e7b17fc..032fbaf4e65 100644 --- a/substrate/test-utils/client/Cargo.toml +++ b/substrate/test-utils/client/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,18 +17,18 @@ array-bytes = "6.1" async-trait = "0.1.57" codec = { package = "parity-scale-codec", version = "3.6.1" } futures = "0.3.21" -serde = "1.0.193" +serde = "1.0.188" serde_json = "1.0.108" sc-client-api = { path = "../../client/api" } sc-client-db = { path = "../../client/db", default-features = false, 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 = [ "test-helpers", -] } +]} sp-blockchain = { path = "../../primitives/blockchain" } sp-consensus = { path = "../../primitives/consensus/common" } sp-core = { path = "../../primitives/core" } diff --git a/substrate/test-utils/client/src/lib.rs b/substrate/test-utils/client/src/lib.rs index f383f7c3dc3..084dd2a1861 100644 --- a/substrate/test-utils/client/src/lib.rs +++ b/substrate/test-utils/client/src/lib.rs @@ -263,10 +263,9 @@ impl D: sc_executor::NativeExecutionDispatch + 'static, Backend: sc_client_api::backend::Backend + 'static, { - let mut executor = executor.into().unwrap_or_else(|| { + let executor = executor.into().unwrap_or_else(|| { NativeElseWasmExecutor::new_with_wasm_executor(WasmExecutor::builder().build()) }); - executor.disable_use_native(); let executor = LocalCallExecutor::new( self.backend.clone(), executor.clone(), diff --git a/substrate/test-utils/runtime/Cargo.toml b/substrate/test-utils/runtime/Cargo.toml index 881a77f1f92..2f1e192eded 100644 --- a/substrate/test-utils/runtime/Cargo.toml +++ b/substrate/test-utils/runtime/Cargo.toml @@ -9,44 +9,41 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false, features = ["serde"] } +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 } +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.1", default-features = false, features = ["derive"] } scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -sp-inherents = { path = "../../primitives/inherents", default-features = false } -sp-keyring = { path = "../../primitives/keyring", optional = true } -sp-offchain = { path = "../../primitives/offchain", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-std = { path = "../../primitives/std", 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-inherents = { path = "../../primitives/inherents", default-features = false} +sp-keyring = { path = "../../primitives/keyring", optional = true} +sp-offchain = { path = "../../primitives/offchain", default-features = false} +sp-core = { path = "../../primitives/core", default-features = false} +sp-std = { path = "../../primitives/std", 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-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 } +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-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 } +sp-trie = { path = "../../primitives/trie", default-features = false} +sp-transaction-pool = { path = "../../primitives/transaction-pool", default-features = false} trie-db = { version = "0.28.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 } +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} # 3rd party array-bytes = { version = "6.1", optional = true } @@ -61,14 +58,14 @@ sp-consensus = { path = "../../primitives/consensus/common" } substrate-test-runtime-client = { path = "client" } sp-tracing = { path = "../../primitives/tracing" } json-patch = { version = "1.0.0", default-features = false } -serde = { version = "1.0.193", features = ["alloc", "derive"], default-features = false } +serde = { version = "1.0.188", features = ["alloc", "derive"], default-features = false } serde_json = { version = "1.0.108", default-features = false, features = ["alloc"] } [build-dependencies] substrate-wasm-builder = { path = "../../utils/wasm-builder", optional = true } [features] -default = ["std"] +default = [ "std" ] std = [ "array-bytes", @@ -111,4 +108,4 @@ std = [ "trie-db/std", ] # Special feature to disable logging -disable-logging = ["sp-api/disable-logging"] +disable-logging = [ "sp-api/disable-logging" ] diff --git a/substrate/test-utils/runtime/client/Cargo.toml b/substrate/test-utils/runtime/client/Cargo.toml index cbb964f6785..40cfa8ab1b7 100644 --- a/substrate/test-utils/runtime/client/Cargo.toml +++ b/substrate/test-utils/runtime/client/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/test-utils/runtime/src/lib.rs b/substrate/test-utils/runtime/src/lib.rs index 634878fca44..c4d9535ad2a 100644 --- a/substrate/test-utils/runtime/src/lib.rs +++ b/substrate/test-utils/runtime/src/lib.rs @@ -27,7 +27,7 @@ pub mod substrate_test_pallet; use codec::{Decode, Encode}; use frame_support::{ - construct_runtime, derive_impl, + construct_runtime, dispatch::DispatchClass, genesis_builder_helper::{build_config, create_default_config}, parameter_types, @@ -340,7 +340,6 @@ parameter_types! { .build_or_panic(); } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] impl frame_system::pallet::Config for Runtime { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = RuntimeBlockWeights; diff --git a/substrate/test-utils/runtime/transaction-pool/Cargo.toml b/substrate/test-utils/runtime/transaction-pool/Cargo.toml index b52a897438b..cb6ee6d79f4 100644 --- a/substrate/test-utils/runtime/transaction-pool/Cargo.toml +++ b/substrate/test-utils/runtime/transaction-pool/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true publish = false -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/utils/binary-merkle-tree/Cargo.toml b/substrate/utils/binary-merkle-tree/Cargo.toml index 441f89b790f..6bb1d5f0f1e 100644 --- a/substrate/utils/binary-merkle-tree/Cargo.toml +++ b/substrate/utils/binary-merkle-tree/Cargo.toml @@ -8,9 +8,6 @@ repository.workspace = true description = "A no-std/Substrate compatible library to construct binary merkle tree." homepage = "https://substrate.io" -[lints] -workspace = true - [dependencies] array-bytes = { version = "6.1", optional = true } log = { version = "0.4", default-features = false, optional = true } @@ -23,6 +20,6 @@ sp-core = { path = "../../primitives/core" } sp-runtime = { path = "../../primitives/runtime" } [features] -debug = ["array-bytes", "log"] -default = ["debug", "std"] -std = ["hash-db/std", "log/std", "sp-core/std", "sp-runtime/std"] +debug = [ "array-bytes", "log" ] +default = [ "debug", "std" ] +std = [ "hash-db/std", "log/std", "sp-core/std", "sp-runtime/std" ] diff --git a/substrate/utils/build-script-utils/Cargo.toml b/substrate/utils/build-script-utils/Cargo.toml index 464647ea723..ab15d5552c2 100644 --- a/substrate/utils/build-script-utils/Cargo.toml +++ b/substrate/utils/build-script-utils/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Crate with utility functions for `build.rs` scripts." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/utils/fork-tree/Cargo.toml b/substrate/utils/fork-tree/Cargo.toml index 27bb908986f..eea500641fe 100644 --- a/substrate/utils/fork-tree/Cargo.toml +++ b/substrate/utils/fork-tree/Cargo.toml @@ -10,9 +10,6 @@ description = "Utility library for managing tree-like ordered data with logic fo documentation = "https://docs.rs/fork-tree" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/utils/frame/benchmarking-cli/Cargo.toml b/substrate/utils/frame/benchmarking-cli/Cargo.toml index b9495fa46c2..b67d08a85c2 100644 --- a/substrate/utils/frame/benchmarking-cli/Cargo.toml +++ b/substrate/utils/frame/benchmarking-cli/Cargo.toml @@ -9,16 +9,13 @@ repository.workspace = true description = "CLI for benchmarking FRAME" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] array-bytes = "6.1" chrono = "0.4" -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } codec = { package = "parity-scale-codec", version = "3.6.1" } comfy-table = { version = "7.0.1", default-features = false } handlebars = "4.2.2" @@ -27,9 +24,9 @@ itertools = "0.10.3" lazy_static = "1.4.0" linked-hash-map = "0.5.4" log = "0.4.17" -rand = { version = "0.8.5", features = ["small_rng"] } +rand = { version = "0.8.4", features = ["small_rng"] } rand_pcg = "0.3.1" -serde = "1.0.193" +serde = "1.0.188" serde_json = "1.0.108" thiserror = "1.0.48" thousands = "0.2.0" @@ -37,11 +34,11 @@ frame-benchmarking = { path = "../../../frame/benchmarking" } frame-support = { path = "../../../frame/support" } frame-system = { path = "../../../frame/system" } sc-block-builder = { path = "../../../client/block-builder" } -sc-cli = { path = "../../../client/cli", 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-client-db = { path = "../../../client/db", default-features = false} sc-executor = { path = "../../../client/executor" } -sc-service = { path = "../../../client/service", default-features = false } +sc-service = { path = "../../../client/service", default-features = false} sc-sysinfo = { path = "../../../client/sysinfo" } sp-api = { path = "../../../primitives/api" } sp-blockchain = { path = "../../../primitives/blockchain" } @@ -59,7 +56,7 @@ sp-wasm-interface = { path = "../../../primitives/wasm-interface" } gethostname = "0.2.3" [features] -default = ["rocksdb"] +default = [ "rocksdb" ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", @@ -68,4 +65,4 @@ runtime-benchmarks = [ "sc-service/runtime-benchmarks", "sp-runtime/runtime-benchmarks", ] -rocksdb = ["sc-cli/rocksdb", "sc-client-db/rocksdb"] +rocksdb = [ "sc-cli/rocksdb", "sc-client-db/rocksdb" ] diff --git a/substrate/utils/frame/frame-utilities-cli/Cargo.toml b/substrate/utils/frame/frame-utilities-cli/Cargo.toml index 7e0c0241947..24c04f47391 100644 --- a/substrate/utils/frame/frame-utilities-cli/Cargo.toml +++ b/substrate/utils/frame/frame-utilities-cli/Cargo.toml @@ -10,11 +10,8 @@ description = "cli interface for FRAME" documentation = "https://docs.rs/substrate-frame-cli" readme = "README.md" -[lints] -workspace = true - [dependencies] -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } frame-support = { path = "../../../frame/support" } frame-system = { path = "../../../frame/system" } sc-cli = { path = "../../../client/cli" } diff --git a/substrate/utils/frame/generate-bags/Cargo.toml b/substrate/utils/frame/generate-bags/Cargo.toml index f075452f4c6..ac22197c5ac 100644 --- a/substrate/utils/frame/generate-bags/Cargo.toml +++ b/substrate/utils/frame/generate-bags/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "Bag threshold generation script for pallet-bag-list" -[lints] -workspace = true - [dependencies] # FRAME frame-support = { path = "../../../frame/support" } diff --git a/substrate/utils/frame/generate-bags/node-runtime/Cargo.toml b/substrate/utils/frame/generate-bags/node-runtime/Cargo.toml index 4614caa7f7b..13e61138356 100644 --- a/substrate/utils/frame/generate-bags/node-runtime/Cargo.toml +++ b/substrate/utils/frame/generate-bags/node-runtime/Cargo.toml @@ -9,12 +9,9 @@ repository.workspace = true description = "Bag threshold generation script for pallet-bag-list and kitchensink-runtime." publish = false -[lints] -workspace = true - [dependencies] kitchensink-runtime = { path = "../../../../bin/node/runtime" } generate-bags = { path = ".." } # third-party -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } diff --git a/substrate/utils/frame/remote-externalities/Cargo.toml b/substrate/utils/frame/remote-externalities/Cargo.toml index bd5a51eeec6..7067aed238a 100644 --- a/substrate/utils/frame/remote-externalities/Cargo.toml +++ b/substrate/utils/frame/remote-externalities/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "An externalities provided environment that can load itself from remote nodes or cached files" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -18,7 +15,7 @@ targets = ["x86_64-unknown-linux-gnu"] jsonrpsee = { version = "0.16.2", features = ["http-client"] } codec = { package = "parity-scale-codec", version = "3.6.1" } log = "0.4.17" -serde = "1.0.193" +serde = "1.0.188" sp-core = { path = "../../../primitives/core" } sp-state-machine = { path = "../../../primitives/state-machine" } sp-io = { path = "../../../primitives/io" } diff --git a/substrate/utils/frame/remote-externalities/src/lib.rs b/substrate/utils/frame/remote-externalities/src/lib.rs index 5c7a36867ff..71e9320ebee 100644 --- a/substrate/utils/frame/remote-externalities/src/lib.rs +++ b/substrate/utils/frame/remote-externalities/src/lib.rs @@ -47,7 +47,6 @@ use std::{ fs, ops::{Deref, DerefMut}, path::{Path, PathBuf}, - sync::Arc, time::{Duration, Instant}, }; use substrate_rpc_client::{rpc_params, BatchRequestBuilder, ChainApi, ClientT, StateApi}; @@ -299,7 +298,6 @@ impl Default for SnapshotConfig { } /// Builder for remote-externalities. -#[derive(Clone)] pub struct Builder { /// Custom key-pairs to be injected into the final externalities. The *hashed* keys and values /// must be given. @@ -402,134 +400,41 @@ where }) } - /// Get keys with `prefix` at `block` in a parallel manner. - async fn rpc_get_keys_parallel( - &self, - prefix: &StorageKey, - block: B::Hash, - parallel: usize, - ) -> Result, &'static str> { - /// Divide the workload and return the start key of each chunks. Guaranteed to return a - /// non-empty list. - fn gen_start_keys(prefix: &StorageKey) -> Vec { - let mut prefix = prefix.as_ref().to_vec(); - let scale = 32usize.saturating_sub(prefix.len()); - - // no need to divide workload - if scale < 9 { - prefix.extend(vec![0; scale]); - return vec![StorageKey(prefix)] - } - - let chunks = 16; - let step = 0x10000 / chunks; - let ext = scale - 2; - - (0..chunks) - .map(|i| { - let mut key = prefix.clone(); - let start = i * step; - key.extend(vec![(start >> 8) as u8, (start & 0xff) as u8]); - key.extend(vec![0; ext]); - StorageKey(key) - }) - .collect() - } - - let start_keys = gen_start_keys(&prefix); - let start_keys: Vec> = start_keys.iter().map(Some).collect(); - let mut end_keys: Vec> = start_keys[1..].to_vec(); - end_keys.push(None); - - // use a semaphore to limit max scraping tasks - let parallel = Arc::new(tokio::sync::Semaphore::new(parallel)); - let builder = Arc::new(self.clone()); - let mut handles = vec![]; - - for (start_key, end_key) in start_keys.into_iter().zip(end_keys) { - let permit = parallel - .clone() - .acquire_owned() - .await - .expect("semaphore is not closed until the end of loop"); - - let builder = builder.clone(); - let prefix = prefix.clone(); - let start_key = start_key.cloned(); - let end_key = end_key.cloned(); - - let handle = tokio::spawn(async move { - let res = builder - .rpc_get_keys_in_range(&prefix, block, start_key.as_ref(), end_key.as_ref()) - .await; - drop(permit); - res - }); - - handles.push(handle); - } - - parallel.close(); - - let keys = futures::future::join_all(handles) - .await - .into_iter() - .filter_map(|res| match res { - Ok(Ok(keys)) => Some(keys), - _ => None, - }) - .flatten() - .collect::>(); - - Ok(keys) - } - - /// Get all keys with `prefix` within the given range at `block`. - /// Both `start_key` and `end_key` are optional if you want an open-ended range. - async fn rpc_get_keys_in_range( + /// Get all the keys at `prefix` at `hash` using the paged, safe RPC methods. + async fn rpc_get_keys_paged( &self, - prefix: &StorageKey, - block: B::Hash, - start_key: Option<&StorageKey>, - end_key: Option<&StorageKey>, + prefix: StorageKey, + at: B::Hash, ) -> Result, &'static str> { - let mut last_key: Option<&StorageKey> = start_key; - let mut keys: Vec = vec![]; - - loop { + let mut last_key: Option = None; + let mut all_keys: Vec = vec![]; + let keys = loop { // This loop can hit the node with very rapid requests, occasionally causing it to // error out in CI (https://github.com/paritytech/substrate/issues/14129), so we retry. let retry_strategy = FixedInterval::new(Self::KEYS_PAGE_RETRY_INTERVAL).take(Self::MAX_RETRIES); let get_page_closure = - || self.get_keys_single_page(Some(prefix.clone()), last_key.cloned(), block); - let mut page = Retry::spawn(retry_strategy, get_page_closure).await?; - - // avoid duplicated keys across workloads - if let (Some(last), Some(end)) = (page.last(), end_key) { - if last >= end { - page.retain(|key| key < end); - } - } - + || self.get_keys_single_page(Some(prefix.clone()), last_key.clone(), at); + let page = Retry::spawn(retry_strategy, get_page_closure).await?; let page_len = page.len(); - keys.extend(page); - last_key = keys.last(); - // scraping out of range or no more matches, - // we are done either way + all_keys.extend(page); + if page_len < Self::DEFAULT_KEY_DOWNLOAD_PAGE as usize { log::debug!(target: LOG_TARGET, "last page received: {}", page_len); - break - } - - log::debug!( - target: LOG_TARGET, - "new total = {}, full page received: {}", - keys.len(), - HexDisplay::from(last_key.expect("full page received, cannot be None")) - ); - } + break all_keys + } else { + let new_last_key = + all_keys.last().expect("all_keys is populated; has .last(); qed"); + log::debug!( + target: LOG_TARGET, + "new total = {}, full page received: {}", + all_keys.len(), + HexDisplay::from(new_last_key) + ); + last_key = Some(new_last_key.clone()); + }; + }; Ok(keys) } @@ -624,7 +529,7 @@ where "Batch request failed ({}/{} retries). Error: {}", retries, Self::MAX_RETRIES, - e + e.to_string() ); // after 2 subsequent failures something very wrong is happening. log a warning // and reset the batch size down to 1. @@ -685,7 +590,7 @@ where /// map them to values one by one. /// /// This can work with public nodes. But, expect it to be darn slow. - pub(crate) async fn rpc_get_pairs( + pub(crate) async fn rpc_get_pairs_paged( &self, prefix: StorageKey, at: B::Hash, @@ -693,10 +598,8 @@ where ) -> Result, &'static str> { let start = Instant::now(); let mut sp = Spinner::with_timer(Spinners::Dots, "Scraping keys...".into()); - // TODO We could start downloading when having collected the first batch of keys - // https://github.com/paritytech/polkadot-sdk/issues/2494 let keys = self - .rpc_get_keys_parallel(&prefix, at, Self::PARALLEL_REQUESTS) + .rpc_get_keys_paged(prefix.clone(), at) .await? .into_iter() .collect::>(); @@ -725,9 +628,9 @@ where .unwrap() .progress_chars("=>-"), ); - let payloads_chunked = payloads.chunks((payloads.len() / Self::PARALLEL_REQUESTS).max(1)); + let payloads_chunked = payloads.chunks((&payloads.len() / Self::PARALLEL_REQUESTS).max(1)); let requests = payloads_chunked.map(|payload_chunk| { - Self::get_storage_data_dynamic_batch_size(client, payload_chunk.to_vec(), &bar) + Self::get_storage_data_dynamic_batch_size(&client, payload_chunk.to_vec(), &bar) }); // Execute the requests and move the Result outside. let storage_data_result: Result, _> = @@ -741,7 +644,7 @@ where }, }; bar.finish_with_message("✅ Downloaded key values"); - println!(); + print!("\n"); // Check if we got responses for all submitted requests. assert_eq!(keys.len(), storage_data.len()); @@ -875,9 +778,8 @@ where pending_ext: &mut TestExternalities>, ) -> Result { let child_roots = top_kv - .iter() - .filter(|(k, _)| is_default_child_storage_key(k.as_ref())) - .map(|(k, _)| k.clone()) + .into_iter() + .filter_map(|(k, _)| is_default_child_storage_key(k.as_ref()).then(|| k.clone())) .collect::>(); if child_roots.is_empty() { @@ -897,10 +799,11 @@ where let mut child_kv = vec![]; for prefixed_top_key in child_roots { let child_keys = - Self::rpc_child_get_keys(client, &prefixed_top_key, StorageKey(vec![]), at).await?; + Self::rpc_child_get_keys(&client, &prefixed_top_key, StorageKey(vec![]), at) + .await?; let child_kv_inner = - Self::rpc_child_get_storage_paged(client, &prefixed_top_key, child_keys, at) + Self::rpc_child_get_storage_paged(&client, &prefixed_top_key, child_keys, at) .await?; let prefixed_top_key = PrefixedStorageKey::new(prefixed_top_key.clone().0); @@ -943,7 +846,7 @@ where for prefix in &config.hashed_prefixes { let now = std::time::Instant::now(); let additional_key_values = - self.rpc_get_pairs(StorageKey(prefix.to_vec()), at, pending_ext).await?; + self.rpc_get_pairs_paged(StorageKey(prefix.to_vec()), at, pending_ext).await?; let elapsed = now.elapsed(); log::info!( target: LOG_TARGET, @@ -1207,7 +1110,7 @@ mod test_prelude { pub(crate) type Block = RawBlock>; pub(crate) fn init_logger() { - sp_tracing::try_init_simple(); + let _ = sp_tracing::try_init_simple(); } } @@ -1537,26 +1440,4 @@ mod remote_tests { .unwrap() .execute_with(|| {}); } - - #[tokio::test] - async fn can_fetch_in_parallel() { - init_logger(); - - let uri = String::from("wss://kusama-bridge-hub-rpc.polkadot.io:443"); - let mut builder = Builder::::new() - .mode(Mode::Online(OnlineConfig { transport: uri.into(), ..Default::default() })); - builder.init_remote_client().await.unwrap(); - - let at = builder.as_online().at.unwrap(); - - let prefix = StorageKey(vec![13]); - let paged = builder.rpc_get_keys_in_range(&prefix, at, None, None).await.unwrap(); - let para = builder.rpc_get_keys_parallel(&prefix, at, 4).await.unwrap(); - assert_eq!(paged, para); - - let prefix = StorageKey(vec![]); - let paged = builder.rpc_get_keys_in_range(&prefix, at, None, None).await.unwrap(); - let para = builder.rpc_get_keys_parallel(&prefix, at, 8).await.unwrap(); - assert_eq!(paged, para); - } } diff --git a/substrate/utils/frame/rpc/client/Cargo.toml b/substrate/utils/frame/rpc/client/Cargo.toml index 986f9f3943c..d0f323c096f 100644 --- a/substrate/utils/frame/rpc/client/Cargo.toml +++ b/substrate/utils/frame/rpc/client/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "Shared JSON-RPC client" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] 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 368273d609f..d25e6ec67c9 100644 --- a/substrate/utils/frame/rpc/state-trie-migration-rpc/Cargo.toml +++ b/substrate/utils/frame/rpc/state-trie-migration-rpc/Cargo.toml @@ -9,9 +9,6 @@ repository.workspace = true description = "Node-specific RPC methods for interaction with state trie migration." readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -24,7 +21,7 @@ sp-state-machine = { path = "../../../../primitives/state-machine" } sp-trie = { path = "../../../../primitives/trie" } trie-db = "0.28.0" -jsonrpsee = { version = "0.16.2", features = ["client-core", "macros", "server"] } +jsonrpsee = { version = "0.16.2", features = ["client-core", "server", "macros"] } # Substrate Dependencies sc-client-api = { path = "../../../../client/api" } diff --git a/substrate/utils/frame/rpc/support/Cargo.toml b/substrate/utils/frame/rpc/support/Cargo.toml index 1cc6d8e98b3..22283fbf450 100644 --- a/substrate/utils/frame/rpc/support/Cargo.toml +++ b/substrate/utils/frame/rpc/support/Cargo.toml @@ -8,9 +8,6 @@ homepage = "https://substrate.io" repository.workspace = true description = "Substrate RPC for FRAME's support" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -24,7 +21,7 @@ sp-storage = { path = "../../../../primitives/storage" } [dev-dependencies] scale-info = "2.10.0" -jsonrpsee = { version = "0.16.2", features = ["jsonrpsee-types", "ws-client"] } +jsonrpsee = { version = "0.16.2", features = ["ws-client", "jsonrpsee-types"] } tokio = "1.22.0" sp-core = { path = "../../../../primitives/core" } sp-runtime = { path = "../../../../primitives/runtime" } diff --git a/substrate/utils/frame/rpc/support/src/lib.rs b/substrate/utils/frame/rpc/support/src/lib.rs index bb5098293c2..2d8e45cbfc6 100644 --- a/substrate/utils/frame/rpc/support/src/lib.rs +++ b/substrate/utils/frame/rpc/support/src/lib.rs @@ -34,7 +34,7 @@ use sp_storage::{StorageData, StorageKey}; /// # use jsonrpsee::core::Error as RpcError; /// # use jsonrpsee::ws_client::WsClientBuilder; /// # use codec::Encode; -/// # use frame_support::{construct_runtime, derive_impl, traits::ConstU32}; +/// # use frame_support::{construct_runtime, traits::ConstU32}; /// # use substrate_frame_rpc_support::StorageQuery; /// # use sc_rpc_api::state::StateApiClient; /// # use sp_runtime::{traits::{BlakeTwo256, IdentityLookup}, testing::Header}; @@ -49,7 +49,6 @@ use sp_storage::{StorageData, StorageKey}; /// # /// # type Hash = sp_core::H256; /// # -/// # #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] /// # impl frame_system::Config for TestRuntime { /// # type BaseCallFilter = (); /// # type BlockWeights = (); @@ -63,7 +62,6 @@ use sp_storage::{StorageData, StorageKey}; /// # type Lookup = IdentityLookup; /// # type Block = frame_system::mocking::MockBlock; /// # type RuntimeEvent = RuntimeEvent; -/// # type RuntimeTask = RuntimeTask; /// # type BlockHashCount = (); /// # type DbWeight = (); /// # type Version = (); diff --git a/substrate/utils/frame/rpc/system/Cargo.toml b/substrate/utils/frame/rpc/system/Cargo.toml index 84c3265c93d..77c3b7eeee3 100644 --- a/substrate/utils/frame/rpc/system/Cargo.toml +++ b/substrate/utils/frame/rpc/system/Cargo.toml @@ -9,15 +9,12 @@ repository.workspace = true description = "FRAME's system exposed over Substrate RPC" readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.6.1" } -jsonrpsee = { version = "0.16.2", features = ["client-core", "macros", "server"] } +jsonrpsee = { version = "0.16.2", features = ["client-core", "server", "macros"] } futures = "0.3.21" log = "0.4.17" frame-system-rpc-runtime-api = { path = "../../../../frame/system/rpc/runtime-api" } diff --git a/substrate/utils/frame/try-runtime/cli/Cargo.toml b/substrate/utils/frame/try-runtime/cli/Cargo.toml index 9f560ab3271..6be4306193c 100644 --- a/substrate/utils/frame/try-runtime/cli/Cargo.toml +++ b/substrate/utils/frame/try-runtime/cli/Cargo.toml @@ -8,14 +8,11 @@ homepage = "https://substrate.io" repository.workspace = true description = "Cli command runtime testing and dry-running" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] -remote-externalities = { package = "frame-remote-externalities", path = "../../remote-externalities" } +remote-externalities = { package = "frame-remote-externalities" , path = "../../remote-externalities" } sc-cli = { path = "../../../../client/cli" } sc-executor = { path = "../../../../client/executor" } sp-consensus-aura = { path = "../../../../primitives/consensus/aura" } @@ -34,15 +31,15 @@ sp-version = { path = "../../../../primitives/version" } sp-debug-derive = { path = "../../../../primitives/debug-derive" } sp-api = { path = "../../../../primitives/api" } sp-weights = { path = "../../../../primitives/weights" } -frame-try-runtime = { path = "../../../../frame/try-runtime", optional = true } +frame-try-runtime = { path = "../../../../frame/try-runtime", optional = true} substrate-rpc-client = { path = "../../rpc/client" } async-trait = "0.1.57" -clap = { version = "4.4.11", features = ["derive"] } +clap = { version = "4.4.6", features = ["derive"] } hex = { version = "0.4.3", default-features = false } log = "0.4.17" parity-scale-codec = "3.6.1" -serde = "1.0.193" +serde = "1.0.188" serde_json = "1.0.108" zstd = { version = "0.12.4", default-features = false } diff --git a/substrate/utils/prometheus/Cargo.toml b/substrate/utils/prometheus/Cargo.toml index 252998d94bd..bf999a66111 100644 --- a/substrate/utils/prometheus/Cargo.toml +++ b/substrate/utils/prometheus/Cargo.toml @@ -9,9 +9,6 @@ homepage = "https://substrate.io" repository.workspace = true readme = "README.md" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/substrate/utils/wasm-builder/Cargo.toml b/substrate/utils/wasm-builder/Cargo.toml index 2154cfca177..2550122ad4b 100644 --- a/substrate/utils/wasm-builder/Cargo.toml +++ b/substrate/utils/wasm-builder/Cargo.toml @@ -4,13 +4,11 @@ version = "5.0.0-dev" authors.workspace = true description = "Utility for building WASM binaries" edition.workspace = true +readme = "README.md" repository.workspace = true license = "Apache-2.0" homepage = "https://substrate.io" -[lints] -workspace = true - [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] @@ -20,7 +18,7 @@ build-helper = "0.1.1" cargo_metadata = "0.15.4" strum = { version = "0.24.1", features = ["derive"] } tempfile = "3.1.0" -toml = "0.8.2" +toml = "0.7.3" walkdir = "2.3.2" sp-maybe-compressed-blob = { path = "../../primitives/maybe-compressed-blob" } filetime = "0.2.16" diff --git a/substrate/utils/wasm-builder/README.md b/substrate/utils/wasm-builder/README.md new file mode 100644 index 00000000000..db32f5cbc95 --- /dev/null +++ b/substrate/utils/wasm-builder/README.md @@ -0,0 +1,86 @@ +# Wasm builder is a utility for building a project as a Wasm binary + +The Wasm builder is a tool that integrates the process of building the WASM binary of your project into the main `cargo` +build process. + +## Project setup + +A project that should be compiled as a Wasm binary needs to: + +1. Add a `build.rs` file. +2. Add `wasm-builder` as dependency into `build-dependencies` (can be made optional and only enabled when `std` feature + is used). + +The `build.rs` file needs to contain the following code: + +```rust +fn main() { + #[cfg(feature = "std")] + { + substrate_wasm_builder::WasmBuilder::new() + // Tell the builder to build the project (crate) this `build.rs` is part of. + .with_current_project() + // Make sure to export the `heap_base` global, this is required by Substrate + .export_heap_base() + // Build the Wasm file so that it imports the memory (need to be provided by at instantiation) + .import_memory() + // Build it. + .build(); + } +} +``` + +As the final step, you need to add the following to your project: + +```rust +include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); +``` + +This will include the generated Wasm binary as two constants `WASM_BINARY` and `WASM_BINARY_BLOATY`. The former is a +compact Wasm binary and the latter is the Wasm binary as being generated by the compiler. Both variables have +`Option<&'static [u8]>` as type. + +### Features + +Wasm builder supports to enable cargo features while building the Wasm binary. By default it will enable all features in +the wasm build that are enabled for the native build except the `default` and `std` features. Besides that, wasm builder +supports the special `runtime-wasm` feature. This `runtime-wasm` feature will be enabled by the wasm builder when it +compiles the Wasm binary. If this feature is not present, it will not be enabled. + +## Environment variables + +By using environment variables, you can configure which Wasm binaries are built and how: + +- `SKIP_WASM_BUILD` - Skips building any Wasm binary. This is useful when only native should be recompiled. If this is + the first run and there doesn't exist a Wasm binary, this will set both variables to `None`. +- `WASM_BUILD_TYPE` - Sets the build type for building Wasm binaries. Supported values are `release` or `debug`. By + default the build type is equal to the build type used by the main build. +- `FORCE_WASM_BUILD` - Can be set to force a Wasm build. On subsequent calls the value of the variable needs to change. + As wasm-builder instructs `cargo` to watch for file changes this environment variable should only + be required in certain circumstances. +- `WASM_BUILD_RUSTFLAGS` - Extend `RUSTFLAGS` given to `cargo build` while building the wasm binary. +- `WASM_BUILD_NO_COLOR` - Disable color output of the wasm build. +- `WASM_TARGET_DIRECTORY` - Will copy any build Wasm binary to the given directory. The path needs to be absolute. +- `WASM_BUILD_TOOLCHAIN` - The toolchain that should be used to build the Wasm binaries. The format needs to be the same + as used by cargo, e.g. `nightly-2020-02-20`. +- `CARGO_NET_OFFLINE` - If `true`, `--offline` will be passed to all processes launched to prevent network access. + Useful in offline environments. + +Each project can be skipped individually by using the environment variable `SKIP_PROJECT_NAME_WASM_BUILD`. Where +`PROJECT_NAME` needs to be replaced by the name of the cargo project, e.g. `node-runtime` will be `NODE_RUNTIME`. + +## Prerequisites + +Wasm builder requires the following prerequisites for building the Wasm binary: + +- rust nightly + `wasm32-unknown-unknown` toolchain + +or + +- rust stable and version at least 1.68.0 + `wasm32-unknown-unknown` toolchain + +If a specific rust is installed with `rustup`, it is important that the wasm target is installed as well. For example if +installing the rust from 20.02.2020 using `rustup install nightly-2020-02-20`, the wasm target needs to be installed as +well `rustup target add wasm32-unknown-unknown --toolchain nightly-2020-02-20`. + +License: Apache-2.0 diff --git a/substrate/utils/wasm-builder/src/lib.rs b/substrate/utils/wasm-builder/src/lib.rs index ec85fd1ffdd..c9011f97be7 100644 --- a/substrate/utils/wasm-builder/src/lib.rs +++ b/substrate/utils/wasm-builder/src/lib.rs @@ -87,9 +87,6 @@ //! required as we walk up from the target directory until we find a `Cargo.toml`. If the target //! directory is changed for the build, this environment variable can be used to point to the //! actual workspace. -//! - `WASM_BUILD_STD` - Sets whether the Rust's standard library crates will also be built. This is -//! necessary to make sure the standard library crates only use the exact WASM feature set that -//! our executor supports. Enabled by default. //! - `CARGO_NET_OFFLINE` - If `true`, `--offline` will be passed to all processes launched to //! prevent network access. Useful in offline environments. //! @@ -161,9 +158,6 @@ const FORCE_WASM_BUILD_ENV: &str = "FORCE_WASM_BUILD"; /// Environment variable that hints the workspace we are building. const WASM_BUILD_WORKSPACE_HINT: &str = "WASM_BUILD_WORKSPACE_HINT"; -/// Environment variable to set whether we'll build `core`/`std`. -const WASM_BUILD_STD: &str = "WASM_BUILD_STD"; - /// Write to the given `file` if the `content` is different. fn write_file_if_changed(file: impl AsRef, content: impl AsRef) { if fs::read_to_string(file.as_ref()).ok().as_deref() != Some(content.as_ref()) { @@ -288,12 +282,6 @@ impl CargoCommand { self.version } - /// Returns whether this version of the toolchain supports nightly features. - fn supports_nightly_features(&self) -> bool { - self.version.map_or(false, |version| version.is_nightly) || - env::var("RUSTC_BOOTSTRAP").is_ok() - } - /// Check if the supplied cargo command supports our Substrate wasm environment. /// /// This means that either the cargo version is at minimum 1.68.0 or this is a nightly cargo. @@ -344,26 +332,3 @@ impl std::ops::Deref for CargoCommandVersioned { fn color_output_enabled() -> bool { env::var(crate::WASM_BUILD_NO_COLOR).is_err() } - -/// Fetches a boolean environment variable. Will exit the process if the value is invalid. -fn get_bool_environment_variable(name: &str) -> Option { - let value = env::var_os(name)?; - - // We're comparing `OsString`s here so we can't use a `match`. - if value == "1" { - Some(true) - } else if value == "0" { - Some(false) - } else { - build_helper::warning!( - "the '{}' environment variable has an invalid value; it must be either '1' or '0'", - name - ); - std::process::exit(1); - } -} - -/// Returns whether we need to also compile the standard library when compiling the runtime. -fn build_std_required() -> bool { - crate::get_bool_environment_variable(crate::WASM_BUILD_STD).unwrap_or(true) -} diff --git a/substrate/utils/wasm-builder/src/prerequisites.rs b/substrate/utils/wasm-builder/src/prerequisites.rs index 2cdbdd2798e..8e81e6774fa 100644 --- a/substrate/utils/wasm-builder/src/prerequisites.rs +++ b/substrate/utils/wasm-builder/src/prerequisites.rs @@ -47,11 +47,14 @@ pub(crate) fn check() -> Result { check_wasm_toolchain_installed(cargo_command) } -/// Creates a minimal dummy crate at the given path and returns the manifest path. -fn create_minimal_crate(project_dir: &Path) -> std::path::PathBuf { - fs::create_dir_all(project_dir.join("src")).expect("Creating src dir does not fail; qed"); - +/// Create the project that will be used to check that the wasm toolchain is installed and to +/// extract the rustc version. +fn create_check_toolchain_project(project_dir: &Path) { + let lib_rs_file = project_dir.join("src/lib.rs"); + let main_rs_file = project_dir.join("src/main.rs"); + let build_rs_file = project_dir.join("build.rs"); let manifest_path = project_dir.join("Cargo.toml"); + write_file_if_changed( &manifest_path, r#" @@ -59,99 +62,120 @@ fn create_minimal_crate(project_dir: &Path) -> std::path::PathBuf { name = "wasm-test" version = "1.0.0" edition = "2021" + build = "build.rs" + + [lib] + name = "wasm_test" + crate-type = ["cdylib"] [workspace] "#, ); - - write_file_if_changed(project_dir.join("src/main.rs"), "fn main() {}"); - manifest_path + write_file_if_changed(lib_rs_file, "pub fn test() {}"); + + // We want to know the rustc version of the rustc that is being used by our cargo command. + // The cargo command is determined by some *very* complex algorithm to find the cargo command + // that supports nightly. + // The best solution would be if there is a `cargo rustc --version` command, which sadly + // doesn't exists. So, the only available way of getting the rustc version is to build a project + // and capture the rustc version in this build process. This `build.rs` is exactly doing this. + // It gets the rustc version by calling `rustc --version` and exposing it in the `RUSTC_VERSION` + // environment variable. + write_file_if_changed( + build_rs_file, + r#" + fn main() { + let rustc_cmd = std::env::var("RUSTC").ok().unwrap_or_else(|| "rustc".into()); + + let rustc_version = std::process::Command::new(rustc_cmd) + .arg("--version") + .output() + .ok() + .and_then(|o| String::from_utf8(o.stdout).ok()); + + println!( + "cargo:rustc-env=RUSTC_VERSION={}", + rustc_version.unwrap_or_else(|| "unknown rustc version".into()), + ); + } + "#, + ); + // Just prints the `RURSTC_VERSION` environment variable that is being created by the + // `build.rs` script. + write_file_if_changed( + main_rs_file, + r#" + fn main() { + println!("{}", env!("RUSTC_VERSION")); + } + "#, + ); } fn check_wasm_toolchain_installed( cargo_command: CargoCommand, ) -> Result { let temp = tempdir().expect("Creating temp dir does not fail; qed"); - let manifest_path = create_minimal_crate(temp.path()).display().to_string(); - - let prepare_command = |subcommand| { - let mut cmd = cargo_command.command(); - // Chdir to temp to avoid including project's .cargo/config.toml - // by accident - it can happen in some CI environments. - cmd.current_dir(&temp); - cmd.args(&[ - subcommand, - "--target=wasm32-unknown-unknown", - "--manifest-path", - &manifest_path, - ]); - - if super::color_output_enabled() { - cmd.arg("--color=always"); - } + fs::create_dir_all(temp.path().join("src")).expect("Creating src dir does not fail; qed"); + create_check_toolchain_project(temp.path()); + + let err_msg = print_error_message("Rust WASM toolchain not installed, please install it!"); + let manifest_path = temp.path().join("Cargo.toml").display().to_string(); + + let mut build_cmd = cargo_command.command(); + // Chdir to temp to avoid including project's .cargo/config.toml + // by accident - it can happen in some CI environments. + build_cmd.current_dir(&temp); + build_cmd.args(&[ + "build", + "--target=wasm32-unknown-unknown", + "--manifest-path", + &manifest_path, + ]); - // manually set the `CARGO_TARGET_DIR` to prevent a cargo deadlock - let target_dir = temp.path().join("target").display().to_string(); - cmd.env("CARGO_TARGET_DIR", &target_dir); - - // Make sure the host's flags aren't used here, e.g. if an alternative linker is specified - // in the RUSTFLAGS then the check we do here will break unless we clear these. - cmd.env_remove("CARGO_ENCODED_RUSTFLAGS"); - cmd.env_remove("RUSTFLAGS"); - cmd - }; - - let err_msg = - print_error_message("Rust WASM toolchain is not properly installed; please install it!"); - let build_result = prepare_command("build").output().map_err(|_| err_msg.clone())?; - if !build_result.status.success() { - return match String::from_utf8(build_result.stderr) { - Ok(ref err) if err.contains("the `wasm32-unknown-unknown` target may not be installed") => - Err(print_error_message("Cannot compile the WASM runtime: the `wasm32-unknown-unknown` target is not installed!\n\ - You can install it with `rustup target add wasm32-unknown-unknown` if you're using `rustup`.")), - - // Apparently this can happen when we're running on a non Tier 1 platform. - Ok(ref err) if err.contains("linker `rust-lld` not found") => - Err(print_error_message("Cannot compile the WASM runtime: `rust-lld` not found!")), - - Ok(ref err) => Err(format!( - "{}\n\n{}\n{}\n{}{}\n", - err_msg, - Color::Yellow.bold().paint("Further error information:"), - Color::Yellow.bold().paint("-".repeat(60)), - err, - Color::Yellow.bold().paint("-".repeat(60)), - )), - - Err(_) => Err(err_msg), - }; + if super::color_output_enabled() { + build_cmd.arg("--color=always"); } - let mut run_cmd = prepare_command("rustc"); - run_cmd.args(&["-q", "--", "--version"]); - - let version = run_cmd - .output() - .ok() - .and_then(|o| String::from_utf8(o.stdout).ok()) - .unwrap_or_else(|| "unknown rustc version".into()); - - if crate::build_std_required() { - let mut sysroot_cmd = prepare_command("rustc"); - sysroot_cmd.args(&["-q", "--", "--print", "sysroot"]); - if let Some(sysroot) = - sysroot_cmd.output().ok().and_then(|o| String::from_utf8(o.stdout).ok()) - { - let src_path = - Path::new(sysroot.trim()).join("lib").join("rustlib").join("src").join("rust"); - if !src_path.exists() { - return Err(print_error_message( - "Cannot compile the WASM runtime: no standard library sources found!\n\ - You can install them with `rustup component add rust-src` if you're using `rustup`.", - )) + let mut run_cmd = cargo_command.command(); + // Chdir to temp to avoid including project's .cargo/config.toml + // by accident - it can happen in some CI environments. + run_cmd.current_dir(&temp); + run_cmd.args(&["run", "--manifest-path", &manifest_path]); + + // manually set the `CARGO_TARGET_DIR` to prevent a cargo deadlock + let target_dir = temp.path().join("target").display().to_string(); + build_cmd.env("CARGO_TARGET_DIR", &target_dir); + run_cmd.env("CARGO_TARGET_DIR", &target_dir); + + // Make sure the host's flags aren't used here, e.g. if an alternative linker is specified + // in the RUSTFLAGS then the check we do here will break unless we clear these. + build_cmd.env_remove("CARGO_ENCODED_RUSTFLAGS"); + run_cmd.env_remove("CARGO_ENCODED_RUSTFLAGS"); + build_cmd.env_remove("RUSTFLAGS"); + run_cmd.env_remove("RUSTFLAGS"); + + build_cmd.output().map_err(|_| err_msg.clone()).and_then(|s| { + if s.status.success() { + let version = run_cmd.output().ok().and_then(|o| String::from_utf8(o.stdout).ok()); + Ok(CargoCommandVersioned::new( + cargo_command, + version.unwrap_or_else(|| "unknown rustc version".into()), + )) + } else { + match String::from_utf8(s.stderr) { + Ok(ref err) if err.contains("linker `rust-lld` not found") => + Err(print_error_message("`rust-lld` not found, please install it!")), + Ok(ref err) => Err(format!( + "{}\n\n{}\n{}\n{}{}\n", + err_msg, + Color::Yellow.bold().paint("Further error information:"), + Color::Yellow.bold().paint("-".repeat(60)), + err, + Color::Yellow.bold().paint("-".repeat(60)), + )), + Err(_) => Err(err_msg), } } - } - - Ok(CargoCommandVersioned::new(cargo_command, version)) + }) } diff --git a/substrate/utils/wasm-builder/src/version.rs b/substrate/utils/wasm-builder/src/version.rs index 3a0a306d737..e4f7d98be61 100644 --- a/substrate/utils/wasm-builder/src/version.rs +++ b/substrate/utils/wasm-builder/src/version.rs @@ -212,21 +212,4 @@ mod tests { version_1_69_0, ); } - - #[test] - fn parse_rustc_version() { - let version = Version::extract("rustc 1.73.0 (cc66ad468 2023-10-03)").unwrap(); - assert_eq!( - version, - Version { - major: 1, - minor: 73, - patch: 0, - is_nightly: false, - year: Some(2023), - month: Some(10), - day: Some(03), - } - ); - } } diff --git a/substrate/utils/wasm-builder/src/wasm_project.rs b/substrate/utils/wasm-builder/src/wasm_project.rs index 2126a49bd7f..9c25d1aba3c 100644 --- a/substrate/utils/wasm-builder/src/wasm_project.rs +++ b/substrate/utils/wasm-builder/src/wasm_project.rs @@ -750,25 +750,6 @@ fn build_bloaty_blob( build_cmd.arg("--offline"); } - // Our executor currently only supports the WASM MVP feature set, however nowadays - // when compiling WASM the Rust compiler has more features enabled by default. - // - // We do set the `-C target-cpu=mvp` flag to make sure that *our* code gets compiled - // in a way that is compatible with our executor, however this doesn't affect Rust's - // standard library crates (`std`, `core` and `alloc`) which are by default precompiled - // and still can make use of these extra features. - // - // So here we force the compiler to also compile the standard library crates for us - // to make sure that they also only use the MVP features. - if crate::build_std_required() { - // Unfortunately this is still a nightly-only flag, but FWIW it is pretty widely used - // so it's unlikely to break without a replacement. - build_cmd.arg("-Z").arg("build-std"); - if !cargo_cmd.supports_nightly_features() { - build_cmd.env("RUSTC_BOOTSTRAP", "1"); - } - } - println!("{}", colorize_info_message("Information that should be included in a bug report.")); println!("{} {:?}", colorize_info_message("Executing build command:"), build_cmd); println!("{} {}", colorize_info_message("Using rustc version:"), cargo_cmd.rustc_version()); @@ -971,7 +952,6 @@ fn generate_rerun_if_changed_instructions( println!("cargo:rerun-if-env-changed={}", crate::WASM_BUILD_RUSTFLAGS_ENV); println!("cargo:rerun-if-env-changed={}", crate::WASM_TARGET_DIRECTORY); println!("cargo:rerun-if-env-changed={}", crate::WASM_BUILD_TOOLCHAIN); - println!("cargo:rerun-if-env-changed={}", crate::WASM_BUILD_STD); } /// Track files and paths related to the given package to rerun `build.rs` on any relevant change. -- GitLab