From 9f1f451245784a0d2f4c943610c838bb1b7c8ac0 Mon Sep 17 00:00:00 2001 From: Guantong <04637@163.com> Date: Mon, 21 Nov 2022 10:11:14 +0800 Subject: [PATCH] Prepare polkadot v0.9.30 for darwinia-2.0 (#226) * update substrate dep master > v0.9.30 * Companion for paritytech/parity-bridges-common#1589 * Companion for paritytech/parity-bridges-common#1593 * Companion for paritytech/parity-bridges-common#1478 * Companion for paritytech/parity-bridges-common#1596 * Companion for paritytech/parity-bridges-common#1600 * Companion for paritytech/parity-bridges-common#1603 * Companion for paritytech/parity-bridges-common#1604 * Companion for paritytech/parity-bridges-common#1597 part.1 * Companion for paritytech/parity-bridges-common#1597 part.2 update weights * Companion for paritytech/parity-bridges-common#1597 part.3 * Companion for paritytech/parity-bridges-common#1597 part.4 fix compile * clear unused imports * Companion for paritytech/parity-bridges-common#1613 part.1 undone * fix tests --- Cargo.lock | 214 ++++++++++------ modules/dispatch/Cargo.toml | 12 +- modules/dispatch/src/lib.rs | 214 +++++++++------- modules/fee-market/Cargo.toml | 18 +- modules/fee-market/src/lib.rs | 3 +- modules/fee-market/src/mock.rs | 52 ++-- modules/fee-market/src/s2s/payment.rs | 7 +- modules/fee-market/src/tests.rs | 179 ++++++++----- modules/fee-market/src/weight.rs | 77 +++--- modules/grandpa/Cargo.toml | 18 +- modules/grandpa/src/extension.rs | 19 +- modules/grandpa/src/lib.rs | 270 ++++++++++++++++---- modules/grandpa/src/mock.rs | 13 +- modules/grandpa/src/storage_types.rs | 66 +++++ modules/grandpa/src/weights.rs | 24 +- modules/messages/Cargo.toml | 16 +- modules/messages/src/inbound_lane.rs | 2 +- modules/messages/src/lib.rs | 184 ++++++------- modules/messages/src/mock.rs | 44 ++-- modules/messages/src/weights.rs | 160 ++++++------ modules/messages/src/weights_ext.rs | 45 ++-- modules/parachains/Cargo.toml | 16 +- modules/parachains/src/extension.rs | 19 +- modules/parachains/src/lib.rs | 168 +++++++++--- modules/parachains/src/mock.rs | 16 +- modules/parachains/src/weights.rs | 48 ++-- modules/parachains/src/weights_ext.rs | 11 +- primitives/darwinia-core/Cargo.toml | 10 +- primitives/darwinia-core/src/lib.rs | 15 +- primitives/header-chain/Cargo.toml | 10 +- primitives/header-chain/src/lib.rs | 40 --- primitives/message-dispatch/Cargo.toml | 6 +- primitives/message-dispatch/src/lib.rs | 2 +- primitives/messages/Cargo.toml | 8 +- primitives/messages/src/lib.rs | 2 +- primitives/messages/src/source_chain.rs | 18 +- primitives/messages/src/target_chain.rs | 2 +- primitives/parachains/Cargo.toml | 4 +- primitives/parachains/src/lib.rs | 6 +- primitives/polkadot-core/Cargo.toml | 14 +- primitives/polkadot-core/src/lib.rs | 7 +- primitives/runtime/Cargo.toml | 16 +- primitives/runtime/src/chain.rs | 20 +- primitives/runtime/src/lib.rs | 8 +- primitives/runtime/src/storage_types.rs | 90 +++++++ primitives/test-utils/Cargo.toml | 8 +- primitives/test-utils/src/lib.rs | 20 +- runtime-common/Cargo.toml | 24 +- runtime-common/src/integrity.rs | 6 +- runtime-common/src/lib.rs | 4 +- runtime-common/src/messages.rs | 61 ++--- runtime-common/src/messages_benchmarking.rs | 4 +- runtime-common/src/messages_extension.rs | 2 +- 53 files changed, 1441 insertions(+), 881 deletions(-) create mode 100644 modules/grandpa/src/storage_types.rs create mode 100644 primitives/runtime/src/storage_types.rs diff --git a/Cargo.lock b/Cargo.lock index a01a8a042..8c81bccf3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -169,6 +169,12 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" +[[package]] +name = "base64ct" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b645a089122eccb6111b4f81cbc1a49f5900ac4666bb93ac027feaecf15607bf" + [[package]] name = "bitflags" version = "1.3.2" @@ -196,16 +202,6 @@ dependencies = [ "digest 0.10.5", ] -[[package]] -name = "blake2-rfc" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6d530bdd2d52966a6d03b7a964add7ae1a288d25214066fd4b600f0f796400" -dependencies = [ - "arrayvec 0.4.12", - "constant_time_eq", -] - [[package]] name = "block-buffer" version = "0.7.3" @@ -443,6 +439,15 @@ version = "1.0.73" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" +[[package]] +name = "cfg-expr" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aacacf4d96c24b2ad6eb8ee6df040e4f27b0d0b39a5710c30091baa830485db" +dependencies = [ + "smallvec", +] + [[package]] name = "cfg-if" version = "1.0.0" @@ -467,12 +472,6 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3" -[[package]] -name = "constant_time_eq" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" - [[package]] name = "core-foundation-sys" version = "0.8.3" @@ -797,7 +796,7 @@ dependencies = [ [[package]] name = "frame-benchmarking" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "frame-support", "frame-system", @@ -832,7 +831,7 @@ dependencies = [ [[package]] name = "frame-support" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "bitflags", "frame-metadata", @@ -857,16 +856,19 @@ dependencies = [ "sp-state-machine", "sp-std", "sp-tracing", + "sp-weights", "tt-call", ] [[package]] name = "frame-support-procedural" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "Inflector", + "cfg-expr", "frame-support-procedural-tools", + "itertools", "proc-macro2", "quote", "syn", @@ -875,7 +877,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "frame-support-procedural-tools-derive", "proc-macro-crate", @@ -887,7 +889,7 @@ dependencies = [ [[package]] name = "frame-support-procedural-tools-derive" version = "3.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "proc-macro2", "quote", @@ -897,7 +899,7 @@ dependencies = [ [[package]] name = "frame-system" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "frame-support", "log", @@ -909,6 +911,7 @@ dependencies = [ "sp-runtime", "sp-std", "sp-version", + "sp-weights", ] [[package]] @@ -1203,6 +1206,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "itertools" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "0.4.8" @@ -1383,9 +1395,9 @@ dependencies = [ [[package]] name = "memory_units" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71d96e3f3c0b6325d8ccd83c33b28acb183edcb6c67938ba104ec546854b0882" +checksum = "8452105ba047068f40ff7093dd1d9da90898e63dd61736462e9cdda6a90ad3c3" [[package]] name = "merlin" @@ -1418,7 +1430,7 @@ dependencies = [ "matrixmultiply", "nalgebra-macros", "num-complex", - "num-rational 0.4.1", + "num-rational", "num-traits", "rand 0.8.5", "rand_distr", @@ -1451,9 +1463,9 @@ checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" [[package]] name = "num-bigint" -version = "0.2.6" +version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "090c7f9998ee0ff65aa5b723e4009f7b217707f1fb5ea551329cc4d6231fb304" +checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" dependencies = [ "autocfg", "num-integer", @@ -1489,18 +1501,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "num-rational" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c000134b5dbf44adc5cb772486d335293351644b801551abe8f75c84cfa4aef" -dependencies = [ - "autocfg", - "num-bigint", - "num-integer", - "num-traits", -] - [[package]] name = "num-rational" version = "0.4.1" @@ -1508,6 +1508,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0638a1c9d0a3c0914158145bc76cff373a75a627e6ecbfb71cbe6f453a5a19b0" dependencies = [ "autocfg", + "num-bigint", "num-integer", "num-traits", ] @@ -1562,7 +1563,7 @@ checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" [[package]] name = "pallet-balances" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "frame-benchmarking", "frame-support", @@ -1683,7 +1684,7 @@ dependencies = [ [[package]] name = "pallet-timestamp" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "frame-benchmarking", "frame-support", @@ -1692,6 +1693,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-inherents", + "sp-io", "sp-runtime", "sp-std", "sp-timestamp", @@ -1700,7 +1702,7 @@ dependencies = [ [[package]] name = "pallet-transaction-payment" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "frame-support", "frame-system", @@ -1771,9 +1773,9 @@ dependencies = [ [[package]] name = "parity-wasm" -version = "0.42.2" +version = "0.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be5e13c266502aadf83426d87d81a0f5d1ef45b8027f5a471c360abfe4bfae92" +checksum = "e1ad0aff30c1da14b1254fcb2af73e1fa9a28670e584a626f53a369d0e157304" [[package]] name = "parking_lot" @@ -1834,6 +1836,17 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "pkcs8" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cabda3fb821068a9a4fab19a683eac3af12edf0f34b94a8be53c4972b8149d0" +dependencies = [ + "der", + "spki", + "zeroize", +] + [[package]] name = "ppv-lite86" version = "0.2.16" @@ -2144,6 +2157,7 @@ checksum = "08da66b8b0965a5555b6bd6639e68ccba85e1e2506f5fbb089e93f8a04e1a2d1" dependencies = [ "der", "generic-array 0.14.6", + "pkcs8", "subtle", "zeroize", ] @@ -2301,7 +2315,7 @@ checksum = "2fd0db749597d91ff862fd1d55ea87f7855a744a8425a64695b6fca237d1dad1" [[package]] name = "sp-api" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "hash-db", "log", @@ -2319,7 +2333,7 @@ dependencies = [ [[package]] name = "sp-api-proc-macro" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "blake2", "proc-macro-crate", @@ -2331,7 +2345,7 @@ dependencies = [ [[package]] name = "sp-application-crypto" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "parity-scale-codec", "scale-info", @@ -2344,7 +2358,7 @@ dependencies = [ [[package]] name = "sp-arithmetic" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "integer-sqrt", "num-traits", @@ -2359,18 +2373,18 @@ dependencies = [ [[package]] name = "sp-core" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ + "array-bytes", "base58", "bitflags", - "blake2-rfc", + "blake2", "byteorder", "dyn-clonable", "ed25519-zebra", "futures", "hash-db", "hash256-std-hasher", - "hex", "impl-serde", "lazy_static", "libsecp256k1", @@ -2405,7 +2419,7 @@ dependencies = [ [[package]] name = "sp-core-hashing" version = "4.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "blake2", "byteorder", @@ -2419,7 +2433,7 @@ dependencies = [ [[package]] name = "sp-core-hashing-proc-macro" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "proc-macro2", "quote", @@ -2430,7 +2444,7 @@ dependencies = [ [[package]] name = "sp-debug-derive" version = "4.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "proc-macro2", "quote", @@ -2440,7 +2454,7 @@ dependencies = [ [[package]] name = "sp-externalities" version = "0.12.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "environmental", "parity-scale-codec", @@ -2451,7 +2465,7 @@ dependencies = [ [[package]] name = "sp-finality-grandpa" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "finality-grandpa", "log", @@ -2469,7 +2483,7 @@ dependencies = [ [[package]] name = "sp-inherents" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "async-trait", "impl-trait-for-tuples", @@ -2483,7 +2497,7 @@ dependencies = [ [[package]] name = "sp-io" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "bytes", "futures", @@ -2509,7 +2523,7 @@ dependencies = [ [[package]] name = "sp-keystore" version = "0.12.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "async-trait", "futures", @@ -2525,7 +2539,7 @@ dependencies = [ [[package]] name = "sp-panic-handler" version = "4.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "backtrace", "lazy_static", @@ -2535,7 +2549,7 @@ dependencies = [ [[package]] name = "sp-runtime" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "either", "hash256-std-hasher", @@ -2552,12 +2566,13 @@ dependencies = [ "sp-core", "sp-io", "sp-std", + "sp-weights", ] [[package]] name = "sp-runtime-interface" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "bytes", "impl-trait-for-tuples", @@ -2575,7 +2590,7 @@ dependencies = [ [[package]] name = "sp-runtime-interface-proc-macro" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "Inflector", "proc-macro-crate", @@ -2587,7 +2602,7 @@ dependencies = [ [[package]] name = "sp-staking" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "parity-scale-codec", "scale-info", @@ -2598,7 +2613,7 @@ dependencies = [ [[package]] name = "sp-state-machine" version = "0.12.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "hash-db", "log", @@ -2620,12 +2635,12 @@ dependencies = [ [[package]] name = "sp-std" version = "4.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" [[package]] name = "sp-storage" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "impl-serde", "parity-scale-codec", @@ -2638,7 +2653,7 @@ dependencies = [ [[package]] name = "sp-timestamp" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "async-trait", "futures-timer", @@ -2654,7 +2669,7 @@ dependencies = [ [[package]] name = "sp-tracing" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "parity-scale-codec", "sp-std", @@ -2666,7 +2681,7 @@ dependencies = [ [[package]] name = "sp-trie" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "ahash", "hash-db", @@ -2689,7 +2704,7 @@ dependencies = [ [[package]] name = "sp-version" version = "5.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "impl-serde", "parity-scale-codec", @@ -2706,7 +2721,7 @@ dependencies = [ [[package]] name = "sp-version-proc-macro" version = "4.0.0-dev" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "parity-scale-codec", "proc-macro2", @@ -2717,7 +2732,7 @@ dependencies = [ [[package]] name = "sp-wasm-interface" version = "6.0.0" -source = "git+https://github.com/paritytech/substrate?branch=master#57e3486d9c7bb4deaef33cf9ba2da083b4e40314" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" dependencies = [ "impl-trait-for-tuples", "log", @@ -2726,6 +2741,32 @@ dependencies = [ "wasmi", ] +[[package]] +name = "sp-weights" +version = "4.0.0" +source = "git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30#a3ed0119c45cdd0d571ad34e5b3ee7518c8cef8d" +dependencies = [ + "impl-trait-for-tuples", + "parity-scale-codec", + "scale-info", + "serde", + "smallvec", + "sp-arithmetic", + "sp-core", + "sp-debug-derive", + "sp-std", +] + +[[package]] +name = "spki" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d01ac02a6ccf3e07db148d2be087da624fea0221a16152ed01f0496a6b0a27" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "ss58-registry" version = "1.29.1" @@ -3124,28 +3165,37 @@ checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f" [[package]] name = "wasmi" -version = "0.9.1" +version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca00c5147c319a8ec91ec1a0edbec31e566ce2c9cc93b3f9bb86a9efd0eb795d" +checksum = "06c326c93fbf86419608361a2c925a31754cf109da1b8b55737070b4d6669422" dependencies = [ - "downcast-rs", - "libc", - "memory_units", - "num-rational 0.2.4", - "num-traits", "parity-wasm", "wasmi-validation", + "wasmi_core", ] [[package]] name = "wasmi-validation" -version = "0.4.1" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "165343ecd6c018fc09ebcae280752702c9a2ef3e6f8d02f1cfcbdb53ef6d7937" +checksum = "91ff416ad1ff0c42e5a926ed5d5fab74c0f098749aa0ad8b2a34b982ce0e867b" dependencies = [ "parity-wasm", ] +[[package]] +name = "wasmi_core" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57d20cb3c59b788653d99541c646c561c9dd26506f25c0cebfe810659c54c6d7" +dependencies = [ + "downcast-rs", + "libm", + "memory_units", + "num-rational", + "num-traits", +] + [[package]] name = "winapi" version = "0.3.9" diff --git a/modules/dispatch/Cargo.toml b/modules/dispatch/Cargo.toml index 37005ec00..3de9296c4 100644 --- a/modules/dispatch/Cargo.toml +++ b/modules/dispatch/Cargo.toml @@ -14,14 +14,14 @@ scale-info = { version = "2.1", default-features = false, features = ["derive"] bp-message-dispatch = { default-features = false, path = "../../primitives/message-dispatch" } bp-runtime = { default-features = false, path = "../../primitives/runtime" } # paritytech -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [dev-dependencies] -sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [features] default = ["std"] diff --git a/modules/dispatch/src/lib.rs b/modules/dispatch/src/lib.rs index 4c9c7bf76..1621f3590 100644 --- a/modules/dispatch/src/lib.rs +++ b/modules/dispatch/src/lib.rs @@ -38,14 +38,13 @@ use bp_runtime::{ }; // paritytech use frame_support::{ - dispatch::{DispatchInfo, DispatchResultWithPostInfo, Dispatchable, Weight}, + dispatch::{DispatchInfo, DispatchResultWithPostInfo, Dispatchable, GetDispatchInfo, Weight}, ensure, log, pallet_prelude::Pays, traits::Get, - weights::GetDispatchInfo, }; use frame_system::RawOrigin; -use sp_runtime::traits::{BadOrigin, Convert, IdentifyAccount, MaybeDisplay, Verify, Zero}; +use sp_runtime::traits::{BadOrigin, Convert, IdentifyAccount, MaybeDisplay, Verify}; use sp_std::{fmt::Debug, prelude::*}; #[frame_support::pallet] @@ -59,7 +58,8 @@ pub mod pallet { #[pallet::config] pub trait Config: frame_system::Config { /// The overarching event type. - type Event: From> + IsType<::Event>; + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; /// Id of the message. Whenever message is passed to the dispatch module, it emits /// event with this id + dispatch result. Could be e.g. (LaneId, MessageNonce) if /// it comes from the messages module. @@ -77,24 +77,31 @@ pub mod pallet { /// owner of `TargetChainAccountPublic`. type TargetChainSignature: Parameter + Verify; /// The overarching dispatch call type. - type Call: Parameter + type RuntimeCall: Parameter + GetDispatchInfo + Dispatchable< - Origin = ::Origin, + RuntimeOrigin = ::RuntimeOrigin, PostInfo = frame_support::dispatch::PostDispatchInfo, >; /// Pre-dispatch validation for incoming calls. /// /// The pallet will validate all incoming calls right before they're dispatched. If this /// validator rejects the call, special event (`Event::MessageCallRejected`) is emitted. - type CallValidator: CallValidate>::Call>; + type CallValidator: CallValidate< + Self::AccountId, + Self::RuntimeOrigin, + >::RuntimeCall, + >; /// The type that is used to wrap the `Self::Call` when it is moved over bridge. /// /// The idea behind this is to avoid `Call` conversion/decoding until we'll be sure /// that all other stuff (like `spec_version`) is ok. If we would try to decode /// `Call` which has been encoded using previous `spec_version`, then we might end /// up with decoding error, instead of `MessageVersionSpecMismatch`. - type EncodedCall: Decode + Encode + Into>::Call, ()>> + Clone; + type EncodedCall: Decode + + Encode + + Into>::RuntimeCall, ()>> + + Clone; /// A type which can be turned into an AccountId from a 256-bit hash. /// /// Used when deriving target chain AccountIds from source chain AccountIds. @@ -102,8 +109,8 @@ pub mod pallet { /// The type is used to customize the dispatch call origin. type IntoDispatchOrigin: IntoDispatchOrigin< Self::AccountId, - >::Call, - Self::Origin, + >::RuntimeCall, + Self::RuntimeOrigin, >; } @@ -207,7 +214,7 @@ impl, I: 'static> MessageDispatch Self::deposit_event(Event::MessageRejected(source_chain, id)); return MessageDispatchResult { dispatch_result: false, - unspent_weight: 0, + unspent_weight: Weight::zero(), dispatch_fee_paid_during_dispatch: false, }; }, @@ -319,7 +326,7 @@ impl, I: 'static> MessageDispatch // because otherwise Calls may be dispatched at lower price) let dispatch_info = call.get_dispatch_info(); let expected_weight = dispatch_info.weight; - if message.weight < expected_weight { + if message.weight.all_lt(expected_weight) { log::trace!( target: "runtime::bridge-dispatch", "Message {:?}/{:?}: passed weight is too low. Expected at least {:?}, got {:?}", @@ -500,7 +507,7 @@ mod tests { const TARGET_CHAIN_ID: ChainId = *b"trgt"; const TEST_SPEC_VERSION: SpecVersion = 0; - const TEST_WEIGHT: Weight = 1_000_000_000; + const TEST_WEIGHT: Weight = Weight::from_ref_time(1_000_000_000); #[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, TypeInfo)] pub struct TestAccountPublic(AccountId); @@ -542,7 +549,7 @@ mod tests { parameter_types! { pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: Weight = 1024; + pub const MaximumBlockWeight: Weight = Weight::from_ref_time(1024); pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } @@ -555,9 +562,7 @@ mod tests { type BlockLength = (); type BlockNumber = u64; type BlockWeights = (); - type Call = Call; type DbWeight = (); - type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; type Header = Header; @@ -567,8 +572,10 @@ mod tests { type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); - type Origin = Origin; type PalletInfo = PalletInfo; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; type SS58Prefix = (); type SystemWeightInfo = (); type Version = (); @@ -577,11 +584,11 @@ mod tests { impl Config for TestRuntime { type AccountIdConverter = AccountIdConverter; type BridgeMessageId = BridgeMessageId; - type Call = Call; type CallValidator = CallValidator; type EncodedCall = EncodedCall; - type Event = Event; type IntoDispatchOrigin = TestIntoDispatchOrigin; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; type SourceChainAccountId = AccountId; type TargetChainAccountPublic = TestAccountPublic; type TargetChainSignature = TestSignature; @@ -590,28 +597,28 @@ mod tests { #[derive(Decode, Encode, Clone)] pub struct EncodedCall(Vec); - impl From for Result { - fn from(call: EncodedCall) -> Result { - Call::decode(&mut &call.0[..]).map_err(drop) + impl From for Result { + fn from(call: EncodedCall) -> Result { + RuntimeCall::decode(&mut &call.0[..]).map_err(drop) } } pub struct CallValidator; - impl CallValidate for CallValidator { + impl CallValidate for CallValidator { fn check_receiving_before_dispatch( _relayer_account: &AccountId, - _call: &Call, + _call: &RuntimeCall, ) -> Result<(), &'static str> { Ok(()) } fn call_validate( _relayer_account: &AccountId, - _origin: &Origin, - call: &Call, + _origin: &RuntimeOrigin, + call: &RuntimeCall, ) -> Result<(), TransactionValidityError> { match call { - Call::System(frame_system::Call::fill_block { .. }) => + RuntimeCall::System(frame_system::Call::fill_block { .. }) => Err(TransactionValidityError::Invalid(InvalidTransaction::Call)), _ => Ok(()), } @@ -619,8 +626,8 @@ mod tests { } pub struct TestIntoDispatchOrigin; - impl IntoDispatchOrigin for TestIntoDispatchOrigin { - fn into_dispatch_origin(id: &AccountId, _call: &Call) -> Origin { + impl IntoDispatchOrigin for TestIntoDispatchOrigin { + fn into_dispatch_origin(id: &AccountId, _call: &RuntimeCall) -> RuntimeOrigin { frame_system::RawOrigin::Signed(*id).into() } } @@ -632,7 +639,7 @@ mod tests { fn prepare_message( origin: CallOrigin, - call: Call, + call: RuntimeCall, ) -> as MessageDispatch< AccountId, ::BridgeMessageId, @@ -647,7 +654,7 @@ mod tests { } fn prepare_root_message( - call: Call, + call: RuntimeCall, ) -> as MessageDispatch< AccountId, ::BridgeMessageId, @@ -656,7 +663,7 @@ mod tests { } fn prepare_target_message( - call: Call, + call: RuntimeCall, ) -> as MessageDispatch< AccountId, ::BridgeMessageId, @@ -666,7 +673,7 @@ mod tests { } fn prepare_source_message( - call: Call, + call: RuntimeCall, ) -> as MessageDispatch< AccountId, ::BridgeMessageId, @@ -682,9 +689,10 @@ mod tests { let relayer_account = 1; const BAD_SPEC_VERSION: SpecVersion = 99; - let mut message = prepare_root_message(Call::System(frame_system::Call::remark { - remark: vec![1, 2, 3], - })); + let mut message = + prepare_root_message(RuntimeCall::System(frame_system::Call::remark { + remark: vec![1, 2, 3], + })); let weight = message.weight; message.spec_version = BAD_SPEC_VERSION; @@ -704,7 +712,7 @@ mod tests { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Dispatch( + event: RuntimeEvent::Dispatch( call_dispatch::Event::::MessageVersionSpecMismatch( SOURCE_CHAIN_ID, id, @@ -723,11 +731,14 @@ mod tests { new_test_ext().execute_with(|| { let id = [0; 4]; let relayer_account = 1; - let call = Call::System(frame_system::Call::set_heap_pages { pages: 42 }); + let call = RuntimeCall::System(frame_system::Call::set_heap_pages { pages: 42 }); let call_weight = call.get_dispatch_info().weight; let mut message = prepare_root_message(call); - message.weight = 7; - assert!(call_weight > 7, "needed for test to actually trigger a weight mismatch"); + message.weight = Weight::from_ref_time(7); + assert!( + call_weight.all_gt(Weight::from_ref_time(7)), + "needed for test to actually trigger a weight mismatch" + ); System::set_block_number(1); let result = Dispatch::dispatch( @@ -738,19 +749,19 @@ mod tests { Ok(message), |_, _| unreachable!(), ); - assert_eq!(result.unspent_weight, 7); + assert_eq!(result.unspent_weight, Weight::from_ref_time(7)); assert!(!result.dispatch_result); assert_eq!( System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Dispatch( + event: RuntimeEvent::Dispatch( call_dispatch::Event::::MessageWeightMismatch( SOURCE_CHAIN_ID, id, call_weight, - 7, + Weight::from_ref_time(7), ) ), topics: vec![], @@ -768,7 +779,7 @@ mod tests { let call_origin = CallOrigin::TargetAccount(1, TestAccountPublic(1), TestSignature(99)); let message = prepare_message( call_origin, - Call::System(frame_system::Call::remark { remark: vec![1, 2, 3] }), + RuntimeCall::System(frame_system::Call::remark { remark: vec![1, 2, 3] }), ); let weight = message.weight; @@ -788,7 +799,7 @@ mod tests { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Dispatch( + event: RuntimeEvent::Dispatch( call_dispatch::Event::::MessageSignatureMismatch( SOURCE_CHAIN_ID, id @@ -820,10 +831,9 @@ mod tests { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Dispatch(call_dispatch::Event::::MessageRejected( - SOURCE_CHAIN_ID, - id - )), + event: RuntimeEvent::Dispatch( + call_dispatch::Event::::MessageRejected(SOURCE_CHAIN_ID, id) + ), topics: vec![], }], ); @@ -836,9 +846,10 @@ mod tests { let id = [0; 4]; let relayer_account = 1; - let mut message = prepare_root_message(Call::System(frame_system::Call::remark { - remark: vec![1, 2, 3], - })); + let mut message = + prepare_root_message(RuntimeCall::System(frame_system::Call::remark { + remark: vec![1, 2, 3], + })); let weight = message.weight; message.call.0 = vec![]; @@ -858,7 +869,7 @@ mod tests { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Dispatch( + event: RuntimeEvent::Dispatch( call_dispatch::Event::::MessageCallDecodeFailed( SOURCE_CHAIN_ID, id @@ -876,8 +887,9 @@ mod tests { let id = [0; 4]; let relayer_account = 1; - let call = - Call::System(frame_system::Call::fill_block { ratio: Perbill::from_percent(75) }); + let call = RuntimeCall::System(frame_system::Call::fill_block { + ratio: Perbill::from_percent(75), + }); let weight = call.get_dispatch_info().weight; let mut message = prepare_root_message(call); message.weight = weight; @@ -898,7 +910,7 @@ mod tests { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Dispatch( + event: RuntimeEvent::Dispatch( call_dispatch::Event::::MessageCallValidateFailed( SOURCE_CHAIN_ID, id, @@ -917,9 +929,10 @@ mod tests { let id = [0; 4]; let relayer_account = 1; - let mut message = prepare_root_message(Call::System(frame_system::Call::remark { - remark: vec![1, 2, 3], - })); + let mut message = + prepare_root_message(RuntimeCall::System(frame_system::Call::remark { + remark: vec![1, 2, 3], + })); let weight = message.weight; message.dispatch_fee_payment = DispatchFeePayment::AtTargetChain; @@ -939,7 +952,7 @@ mod tests { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Dispatch( + event: RuntimeEvent::Dispatch( call_dispatch::Event::::MessageDispatchPaymentFailed( SOURCE_CHAIN_ID, id, @@ -962,9 +975,10 @@ mod tests { let id = [0; 4]; let relayer_account = 1; - let mut message = prepare_root_message(Call::System(frame_system::Call::remark { - remark: vec![1, 2, 3], - })); + let mut message = + prepare_root_message(RuntimeCall::System(frame_system::Call::remark { + remark: vec![1, 2, 3], + })); message.dispatch_fee_payment = DispatchFeePayment::AtTargetChain; System::set_block_number(1); @@ -983,11 +997,13 @@ mod tests { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Dispatch(call_dispatch::Event::::MessageDispatched( - SOURCE_CHAIN_ID, - id, - Ok(()) - )), + event: RuntimeEvent::Dispatch( + call_dispatch::Event::::MessageDispatched( + SOURCE_CHAIN_ID, + id, + Ok(()) + ) + ), topics: vec![], }], ); @@ -1000,7 +1016,7 @@ mod tests { let id = [0; 4]; let relayer_account = 1; - let call = Call::System(frame_system::Call::set_heap_pages { pages: 1 }); + let call = RuntimeCall::System(frame_system::Call::set_heap_pages { pages: 1 }); let message = prepare_target_message(call); System::set_block_number(1); @@ -1019,11 +1035,13 @@ mod tests { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Dispatch(call_dispatch::Event::::MessageDispatched( - SOURCE_CHAIN_ID, - id, - Err(sp_runtime::DispatchError::BadOrigin) - )), + event: RuntimeEvent::Dispatch( + call_dispatch::Event::::MessageDispatched( + SOURCE_CHAIN_ID, + id, + Err(sp_runtime::DispatchError::BadOrigin) + ) + ), topics: vec![], }], ); @@ -1035,7 +1053,7 @@ mod tests { new_test_ext().execute_with(|| { let id = [0; 4]; let relayer_account = 1; - let message = prepare_root_message(Call::System(frame_system::Call::remark { + let message = prepare_root_message(RuntimeCall::System(frame_system::Call::remark { remark: vec![1, 2, 3], })); @@ -1055,11 +1073,13 @@ mod tests { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Dispatch(call_dispatch::Event::::MessageDispatched( - SOURCE_CHAIN_ID, - id, - Ok(()) - )), + event: RuntimeEvent::Dispatch( + call_dispatch::Event::::MessageDispatched( + SOURCE_CHAIN_ID, + id, + Ok(()) + ) + ), topics: vec![], }], ); @@ -1072,7 +1092,7 @@ mod tests { let id = [0; 4]; let relayer_account = 1; - let call = Call::System(frame_system::Call::remark { remark: vec![] }); + let call = RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); let message = prepare_target_message(call); System::set_block_number(1); @@ -1091,11 +1111,13 @@ mod tests { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Dispatch(call_dispatch::Event::::MessageDispatched( - SOURCE_CHAIN_ID, - id, - Ok(()) - )), + event: RuntimeEvent::Dispatch( + call_dispatch::Event::::MessageDispatched( + SOURCE_CHAIN_ID, + id, + Ok(()) + ) + ), topics: vec![], }], ); @@ -1108,7 +1130,7 @@ mod tests { let id = [0; 4]; let relayer_account = 1; - let call = Call::System(frame_system::Call::remark { remark: vec![] }); + let call = RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); let message = prepare_source_message(call); System::set_block_number(1); @@ -1127,11 +1149,13 @@ mod tests { System::events(), vec![EventRecord { phase: Phase::Initialization, - event: Event::Dispatch(call_dispatch::Event::::MessageDispatched( - SOURCE_CHAIN_ID, - id, - Ok(()) - )), + event: RuntimeEvent::Dispatch( + call_dispatch::Event::::MessageDispatched( + SOURCE_CHAIN_ID, + id, + Ok(()) + ) + ), topics: vec![], }], ); @@ -1140,7 +1164,7 @@ mod tests { #[test] fn origin_is_checked_when_verifying_sending_message_using_source_root_account() { - let call = Call::System(frame_system::Call::remark { remark: vec![] }); + let call = RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); let message = prepare_root_message(call); // When message is sent by Root, CallOrigin::SourceRoot is allowed @@ -1152,7 +1176,7 @@ mod tests { #[test] fn origin_is_checked_when_verifying_sending_message_using_target_account() { - let call = Call::System(frame_system::Call::remark { remark: vec![] }); + let call = RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); let message = prepare_target_message(call); // When message is sent by Root, CallOrigin::TargetAccount is not allowed @@ -1168,7 +1192,7 @@ mod tests { #[test] fn origin_is_checked_when_verifying_sending_message_using_source_account() { - let call = Call::System(frame_system::Call::remark { remark: vec![] }); + let call = RuntimeCall::System(frame_system::Call::remark { remark: vec![] }); let message = prepare_source_message(call); // Sending a message from the expected origin account works diff --git a/modules/fee-market/Cargo.toml b/modules/fee-market/Cargo.toml index 5324f1d39..09f11ca6f 100644 --- a/modules/fee-market/Cargo.toml +++ b/modules/fee-market/Cargo.toml @@ -14,21 +14,21 @@ version = "0.1.0" codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false } scale-info = { version = "2.0.1", default-features = false, features = ["derive"] } # paritytech -frame-benchmarking = { optional = true, git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } -frame-support = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } -frame-system = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } -pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } -sp-core = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } -sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } -sp-std = { git = "https://github.com/paritytech/substrate", branch = "master", default-features = false } +frame-benchmarking = { optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30", default-features = false } +frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30", default-features = false } +frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30", default-features = false } +pallet-timestamp = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30", default-features = false } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30", default-features = false } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30", default-features = false } +sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30", default-features = false } +sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30", default-features = false } # darwinia-bridges-substrate bp-messages = { default-features = false, path = "../../primitives/messages" } bp-runtime = { default-features = false, path = "../../primitives/runtime" } [dev-dependencies] bitvec = { version = "1" } -pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } pallet-bridge-messages = { path = "../messages" } [features] diff --git a/modules/fee-market/src/lib.rs b/modules/fee-market/src/lib.rs index ae3f2747a..6749ab3b6 100644 --- a/modules/fee-market/src/lib.rs +++ b/modules/fee-market/src/lib.rs @@ -96,7 +96,8 @@ pub mod pallet { type Slasher: Slasher; type Currency: LockableCurrency; - type Event: From> + IsType<::Event>; + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; type WeightInfo: WeightInfo; } diff --git a/modules/fee-market/src/mock.rs b/modules/fee-market/src/mock.rs index 0fd6f026a..bb7306c5e 100644 --- a/modules/fee-market/src/mock.rs +++ b/modules/fee-market/src/mock.rs @@ -76,9 +76,7 @@ impl frame_system::Config for Test { type BlockLength = (); type BlockNumber = u64; type BlockWeights = (); - type Call = Call; type DbWeight = DbWeight; - type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; type Header = Header; @@ -88,8 +86,10 @@ impl frame_system::Config for Test { type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); - type Origin = Origin; type PalletInfo = PalletInfo; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; type SS58Prefix = (); type SystemWeightInfo = (); type Version = (); @@ -102,11 +102,11 @@ impl pallet_balances::Config for Test { type AccountStore = System; type Balance = Balance; type DustRemoval = (); - type Event = Event; type ExistentialDeposit = ExistentialDeposit; type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = [u8; 8]; + type RuntimeEvent = RuntimeEvent; type WeightInfo = (); } @@ -133,9 +133,10 @@ pub const TEST_RELAYER_A: AccountId = 100; /// Account id of additional test relayer - B. pub const TEST_RELAYER_B: AccountId = 101; /// Payload that is rejected by `TestTargetHeaderChain`. -pub const PAYLOAD_REJECTED_BY_TARGET_CHAIN: TestPayload = message_payload(1, 50); +pub const PAYLOAD_REJECTED_BY_TARGET_CHAIN: TestPayload = + message_payload(1, Weight::from_ref_time(50)); /// Regular message payload. -pub const REGULAR_PAYLOAD: TestPayload = message_payload(0, 50); +pub const REGULAR_PAYLOAD: TestPayload = message_payload(0, Weight::from_ref_time(50)); /// Vec of proved messages, grouped by lane. pub type MessagesByLaneVec = Vec<(LaneId, ProvedLaneMessages>)>; @@ -160,7 +161,12 @@ impl Size for TestPayload { } /// Constructs message payload using given arguments and zero unspent weight. pub const fn message_payload(id: u64, declared_weight: Weight) -> TestPayload { - TestPayload { id, declared_weight, dispatch_result: dispatch_result(0), extra: Vec::new() } + TestPayload { + id, + declared_weight, + dispatch_result: dispatch_result(Weight::zero()), + extra: Vec::new(), + } } /// Test messages proof. @@ -221,13 +227,11 @@ impl TargetHeaderChain for TestTargetHeaderChain { /// Lane message verifier that is used in tests. #[derive(Debug, Default)] pub struct TestLaneMessageVerifier; -impl LaneMessageVerifier - for TestLaneMessageVerifier -{ +impl LaneMessageVerifier for TestLaneMessageVerifier { type Error = &'static str; fn verify_message( - _submitter: &Origin, + _submitter: &RuntimeOrigin, delivery_and_dispatch_fee: &TestMessageFee, _lane: &LaneId, _lane_outbound_data: &OutboundLaneData, @@ -255,7 +259,8 @@ impl TestMessageDeliveryAndDispatchPayment { /// Returns true if given fee has been paid by given submitter. pub fn is_fee_paid(submitter: AccountId, fee: TestMessageFee) -> bool { - let raw_origin: Result, _> = Origin::signed(submitter).into(); + let raw_origin: Result, _> = + RuntimeOrigin::signed(submitter).into(); frame_support::storage::unhashed::get(b":message-fee:") == Some((raw_origin.unwrap(), fee)) } @@ -266,13 +271,13 @@ impl TestMessageDeliveryAndDispatchPayment { frame_support::storage::unhashed::take::(&key).is_some() } } -impl MessageDeliveryAndDispatchPayment +impl MessageDeliveryAndDispatchPayment for TestMessageDeliveryAndDispatchPayment { type Error = &'static str; fn pay_delivery_and_dispatch_fee( - submitter: &Origin, + submitter: &RuntimeOrigin, fee: &TestMessageFee, _relayer_fund_account: &AccountId, ) -> Result<(), Self::Error> { @@ -371,7 +376,7 @@ impl MessageDispatch for TestMessageDispatch { fn dispatch_weight(message: &mut DispatchMessage) -> Weight { match message.data.payload.as_ref() { Ok(payload) => payload.declared_weight, - Err(_) => 0, + Err(_) => Weight::zero(), } } @@ -388,7 +393,7 @@ impl MessageDispatch for TestMessageDispatch { ) -> MessageDispatchResult { match message.data.payload.as_ref() { Ok(payload) => payload.dispatch_result.clone(), - Err(_) => dispatch_result(0), + Err(_) => dispatch_result(Weight::zero()), } } } @@ -413,7 +418,6 @@ frame_support::parameter_types! { impl pallet_bridge_messages::Config for Test { type AccountIdConverter = AccountIdConverter; type BridgedChainId = TestBridgedChainId; - type Event = Event; type InboundMessageFee = TestMessageFee; type InboundPayload = TestPayload; type InboundRelayer = TestRelayer; @@ -429,12 +433,13 @@ impl pallet_bridge_messages::Config for Test { type OutboundMessageFee = TestMessageFee; type OutboundPayload = TestPayload; type Parameter = TestMessagesParameter; + type RuntimeEvent = RuntimeEvent; type SourceHeaderChain = TestSourceHeaderChain; type TargetHeaderChain = TestTargetHeaderChain; type WeightInfo = (); } -impl SenderOrigin for Origin { +impl SenderOrigin for RuntimeOrigin { fn linked_account(&self) -> Option { match self.caller { OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) => @@ -478,10 +483,10 @@ impl Config for Test { type ConfirmRelayersRewardRatio = ConfirmRelayersRewardRatio; type Currency = Balances; type DutyRelayersRewardRatio = DutyRelayersRewardRatio; - type Event = Event; type LockId = FeeMarketLockId; type MessageRelayersRewardRatio = MessageRelayersRewardRatio; type MinimumRelayFee = MinimumRelayFee; + type RuntimeEvent = RuntimeEvent; type Slasher = TestSlasher; type Slot = Slot; type TreasuryPalletId = TreasuryPalletId; @@ -572,7 +577,12 @@ pub(crate) fn unrewarded_relayer( pub(crate) fn send_regular_message(sender: u64, fee: Balance) -> (LaneId, u64) { let message_nonce = outbound_lane::(TEST_LANE_ID).data().latest_generated_nonce + 1; - assert_ok!(Messages::send_message(Origin::signed(sender), TEST_LANE_ID, REGULAR_PAYLOAD, fee)); + assert_ok!(Messages::send_message( + RuntimeOrigin::signed(sender), + TEST_LANE_ID, + REGULAR_PAYLOAD, + fee + )); (TEST_LANE_ID, message_nonce) } @@ -584,7 +594,7 @@ pub(crate) fn receive_messages_delivery_proof( last_delivered_nonce: u64, ) { assert_ok!(Messages::receive_messages_delivery_proof( - Origin::signed(sender), + RuntimeOrigin::signed(sender), TestMessagesDeliveryProof(Ok(( TEST_LANE_ID, InboundLaneData { diff --git a/modules/fee-market/src/s2s/payment.rs b/modules/fee-market/src/s2s/payment.rs index e256cd46a..aedd9ef0e 100644 --- a/modules/fee-market/src/s2s/payment.rs +++ b/modules/fee-market/src/s2s/payment.rs @@ -44,18 +44,19 @@ pub struct FeeMarketPayment { _phantom: sp_std::marker::PhantomData<(T, I, Currency)>, } -impl MessageDeliveryAndDispatchPayment> +impl + MessageDeliveryAndDispatchPayment> for FeeMarketPayment where T: frame_system::Config + Config, I: 'static, - T::Origin: SenderOrigin, + T::RuntimeOrigin: SenderOrigin, Currency: CurrencyT, { type Error = &'static str; fn pay_delivery_and_dispatch_fee( - submitter: &T::Origin, + submitter: &T::RuntimeOrigin, fee: &BalanceOf, relayer_fund_account: &T::AccountId, ) -> Result<(), Self::Error> { diff --git a/modules/fee-market/src/tests.rs b/modules/fee-market/src/tests.rs index bc5b084ed..81b4492f7 100644 --- a/modules/fee-market/src/tests.rs +++ b/modules/fee-market/src/tests.rs @@ -26,7 +26,7 @@ use crate::{ assert_market_storage, assert_relayer_info, mock::{ receive_messages_delivery_proof, send_regular_message, unrewarded_relayer, AccountId, - Balances, Event, ExtBuilder, FeeMarket, Messages, Origin, System, Test, + Balances, ExtBuilder, FeeMarket, Messages, RuntimeEvent, RuntimeOrigin, System, Test, TestMessageDeliveryAndDispatchPayment, REGULAR_PAYLOAD, TEST_LANE_ID, TEST_RELAYER_A, TEST_RELAYER_B, }, @@ -40,7 +40,11 @@ fn test_enroll_failed_with_insuffience_balance() { let collater_per_order = ::CollateralPerOrder::get(); ExtBuilder::default().with_balances(vec![(1, collater_per_order)]).build().execute_with(|| { assert_err!( - FeeMarket::enroll_and_lock_collateral(Origin::signed(1), collater_per_order + 1, None), + FeeMarket::enroll_and_lock_collateral( + RuntimeOrigin::signed(1), + collater_per_order + 1, + None + ), >::InsufficientBalance ); }); @@ -51,7 +55,11 @@ fn test_enroll_failed_if_collateral_too_low() { let collater_per_order = ::CollateralPerOrder::get(); ExtBuilder::default().with_balances(vec![(1, collater_per_order)]).build().execute_with(|| { assert_err!( - FeeMarket::enroll_and_lock_collateral(Origin::signed(1), collater_per_order - 1, None), + FeeMarket::enroll_and_lock_collateral( + RuntimeOrigin::signed(1), + collater_per_order - 1, + None + ), >::CollateralTooLow ); }); @@ -62,7 +70,7 @@ fn test_enroll_with_default_quota() { let collater_per_order = ::CollateralPerOrder::get(); ExtBuilder::default().with_balances(vec![(1, collater_per_order)]).build().execute_with(|| { assert_ok!(FeeMarket::enroll_and_lock_collateral( - Origin::signed(1), + RuntimeOrigin::signed(1), collater_per_order, None )); @@ -76,7 +84,7 @@ fn test_enroll_failed_if_quota_too_low() { ExtBuilder::default().with_balances(vec![(1, collater_per_order)]).build().execute_with(|| { assert_err!( FeeMarket::enroll_and_lock_collateral( - Origin::signed(1), + RuntimeOrigin::signed(1), collater_per_order, Some(::MinimumRelayFee::get() - 1), ), @@ -95,7 +103,11 @@ fn test_enroll_with_correct_balance_changes() { .build() .execute_with(|| { assert_err!( - FeeMarket::enroll_and_lock_collateral(Origin::signed(1), collater_per_order, None), + FeeMarket::enroll_and_lock_collateral( + RuntimeOrigin::signed(1), + collater_per_order, + None + ), >::AlreadyEnrolled ); @@ -125,7 +137,11 @@ fn test_enroll_again_failed() { .build() .execute_with(|| { assert_err!( - FeeMarket::enroll_and_lock_collateral(Origin::signed(1), collater_per_order, None), + FeeMarket::enroll_and_lock_collateral( + RuntimeOrigin::signed(1), + collater_per_order, + None + ), >::AlreadyEnrolled ); }); @@ -142,7 +158,10 @@ fn test_increase_collateral_with_insuffience_balance() { .build() .execute_with(|| { assert_err!( - FeeMarket::increase_locked_collateral(Origin::signed(1), collater_per_order + 1), + FeeMarket::increase_locked_collateral( + RuntimeOrigin::signed(1), + collater_per_order + 1 + ), >::InsufficientBalance ); }); @@ -153,7 +172,7 @@ fn test_increase_collateral_not_enrolled() { let collater_per_order = ::CollateralPerOrder::get(); ExtBuilder::default().with_balances(vec![(1, collater_per_order)]).build().execute_with(|| { assert_err!( - FeeMarket::increase_locked_collateral(Origin::signed(1), collater_per_order), + FeeMarket::increase_locked_collateral(RuntimeOrigin::signed(1), collater_per_order), >::NotEnrolled ); }); @@ -168,7 +187,10 @@ fn test_increase_collateral_new_collateral_less_than_before() { .build() .execute_with(|| { assert_err!( - FeeMarket::increase_locked_collateral(Origin::signed(1), collater_per_order - 1), + FeeMarket::increase_locked_collateral( + RuntimeOrigin::signed(1), + collater_per_order - 1 + ), >::NewCollateralShouldLargerThanBefore ); }); @@ -199,7 +221,7 @@ fn test_increase_collateral_relayer_balance_update_correctly() { } assert_ok!(FeeMarket::increase_locked_collateral( - Origin::signed(1), + RuntimeOrigin::signed(1), collater_per_order + 10 )); assert_relayer_info! { @@ -224,7 +246,10 @@ fn test_decrease_collateral_with_insuffience_balance() { .build() .execute_with(|| { assert_err!( - FeeMarket::decrease_locked_collateral(Origin::signed(1), collater_per_order + 1), + FeeMarket::decrease_locked_collateral( + RuntimeOrigin::signed(1), + collater_per_order + 1 + ), >::InsufficientBalance ); }); @@ -235,7 +260,7 @@ fn test_decrease_collateral_not_enrolled() { let collater_per_order = ::CollateralPerOrder::get(); ExtBuilder::default().with_balances(vec![(1, collater_per_order)]).build().execute_with(|| { assert_err!( - FeeMarket::decrease_locked_collateral(Origin::signed(1), collater_per_order), + FeeMarket::decrease_locked_collateral(RuntimeOrigin::signed(1), collater_per_order), >::NotEnrolled ); }); @@ -250,7 +275,10 @@ fn test_decrease_collateral_new_collateral_more_than_before() { .build() .execute_with(|| { assert_err!( - FeeMarket::decrease_locked_collateral(Origin::signed(1), collater_per_order + 1), + FeeMarket::decrease_locked_collateral( + RuntimeOrigin::signed(1), + collater_per_order + 1 + ), >::NewCollateralShouldLessThanBefore ); }); @@ -308,7 +336,7 @@ fn test_decrease_collateral_are_not_allowed_when_occupied() { assert_err!( FeeMarket::decrease_locked_collateral( - Origin::signed(1), + RuntimeOrigin::signed(1), collater_per_order * 2 - 1 ), >::StillHasOrdersNotConfirmed @@ -359,7 +387,7 @@ fn test_decrease_collateral_without_occuiped() { } assert_ok!(FeeMarket::decrease_locked_collateral( - Origin::signed(1), + RuntimeOrigin::signed(1), collater_per_order - 10 )); @@ -385,7 +413,7 @@ fn test_update_relayer_fee_failed_if_not_enroll() { .build() .execute_with(|| { assert_err!( - FeeMarket::update_relay_fee(Origin::signed(1), 1), + FeeMarket::update_relay_fee(RuntimeOrigin::signed(1), 1), >::NotEnrolled ); }); @@ -401,7 +429,7 @@ fn test_update_relayer_fee_failed_if_new_fee_too_low() { .build() .execute_with(|| { assert_err!( - FeeMarket::update_relay_fee(Origin::signed(1), default_fee - 1), + FeeMarket::update_relay_fee(RuntimeOrigin::signed(1), default_fee - 1), >::RelayFeeTooLow ); }); @@ -416,7 +444,7 @@ fn test_update_relayer_fee_works() { .with_relayers(vec![(1, collater_per_order, None)]) .build() .execute_with(|| { - assert_ok!(FeeMarket::update_relay_fee(Origin::signed(1), default_fee + 10),); + assert_ok!(FeeMarket::update_relay_fee(RuntimeOrigin::signed(1), default_fee + 10),); assert_eq!(FeeMarket::relayer(&1).unwrap().fee, default_fee + 10); }); } @@ -432,7 +460,7 @@ fn test_cancel_enroll_failed_if_not_enroll() { .build() .execute_with(|| { assert_err!( - FeeMarket::cancel_enrollment(Origin::signed(1)), + FeeMarket::cancel_enrollment(RuntimeOrigin::signed(1)), >::NotEnrolled ); }); @@ -458,15 +486,15 @@ fn test_cancel_enroll_failed_if_not_occuipied() { let _ = send_regular_message(1, default_fee); assert_err!( - FeeMarket::cancel_enrollment(Origin::signed(1)), + FeeMarket::cancel_enrollment(RuntimeOrigin::signed(1)), >::OccupiedRelayer ); assert_err!( - FeeMarket::cancel_enrollment(Origin::signed(2)), + FeeMarket::cancel_enrollment(RuntimeOrigin::signed(2)), >::OccupiedRelayer ); assert_err!( - FeeMarket::cancel_enrollment(Origin::signed(3)), + FeeMarket::cancel_enrollment(RuntimeOrigin::signed(3)), >::OccupiedRelayer ); }); @@ -500,9 +528,9 @@ fn test_cancel_enroll_ok_if_order_confirmed() { 1, ); - assert_ok!(FeeMarket::cancel_enrollment(Origin::signed(1))); - assert_ok!(FeeMarket::cancel_enrollment(Origin::signed(2))); - assert_ok!(FeeMarket::cancel_enrollment(Origin::signed(3))); + assert_ok!(FeeMarket::cancel_enrollment(RuntimeOrigin::signed(1))); + assert_ok!(FeeMarket::cancel_enrollment(RuntimeOrigin::signed(2))); + assert_ok!(FeeMarket::cancel_enrollment(RuntimeOrigin::signed(3))); }); } @@ -529,9 +557,9 @@ fn test_cancel_enroll_relayers_market_update_correctly() { "market_fee": Some(default_fee), } - assert_ok!(FeeMarket::cancel_enrollment(Origin::signed(1))); - assert_ok!(FeeMarket::cancel_enrollment(Origin::signed(2))); - assert_ok!(FeeMarket::cancel_enrollment(Origin::signed(3))); + assert_ok!(FeeMarket::cancel_enrollment(RuntimeOrigin::signed(1))); + assert_ok!(FeeMarket::cancel_enrollment(RuntimeOrigin::signed(2))); + assert_ok!(FeeMarket::cancel_enrollment(RuntimeOrigin::signed(3))); assert_market_storage! { "relayers": Vec::::new(), @@ -557,9 +585,9 @@ fn test_cancel_enroll_relayers_balances_update_correctly() { ]) .build() .execute_with(|| { - assert_ok!(FeeMarket::cancel_enrollment(Origin::signed(1))); - assert_ok!(FeeMarket::cancel_enrollment(Origin::signed(2))); - assert_ok!(FeeMarket::cancel_enrollment(Origin::signed(3))); + assert_ok!(FeeMarket::cancel_enrollment(RuntimeOrigin::signed(1))); + assert_ok!(FeeMarket::cancel_enrollment(RuntimeOrigin::signed(2))); + assert_ok!(FeeMarket::cancel_enrollment(RuntimeOrigin::signed(3))); assert_relayer_info! { "account_id": 1, @@ -718,7 +746,7 @@ fn test_market_fee_update_after_new_relayer_enroll() { } let _ = FeeMarket::enroll_and_lock_collateral( - Origin::signed(4), + RuntimeOrigin::signed(4), collater_per_order, Some(default_fee + 25), ); @@ -755,7 +783,7 @@ fn test_market_fee_update_after_increase_collateral() { } assert_ok!(FeeMarket::increase_locked_collateral( - Origin::signed(2), + RuntimeOrigin::signed(2), collater_per_order + 1, )); @@ -791,7 +819,7 @@ fn test_market_fee_update_after_decrease_collateral() { } assert_ok!(FeeMarket::decrease_locked_collateral( - Origin::signed(2), + RuntimeOrigin::signed(2), collater_per_order * 2 - 1, )); @@ -828,7 +856,7 @@ fn test_market_fee_update_after_update_fee() { "market_fee": Some(default_fee + 30), } - assert_ok!(FeeMarket::update_relay_fee(Origin::signed(4), default_fee + 25,)); + assert_ok!(FeeMarket::update_relay_fee(RuntimeOrigin::signed(4), default_fee + 25,)); assert_market_storage! { "relayers": vec![1, 2, 3, 4], @@ -863,7 +891,7 @@ fn test_market_fee_update_after_cancel_enroll() { "market_fee": Some(default_fee), } - assert_ok!(FeeMarket::cancel_enrollment(Origin::signed(1))); + assert_ok!(FeeMarket::cancel_enrollment(RuntimeOrigin::signed(1))); assert_market_storage! { "relayers": vec![2, 3, 4], @@ -896,7 +924,7 @@ fn test_market_fee_update_after_adjust_assigned_relayers_number() { "market_fee": Some(default_fee), } - assert_ok!(FeeMarket::set_assigned_relayers_number(Origin::root(), 2)); + assert_ok!(FeeMarket::set_assigned_relayers_number(RuntimeOrigin::root(), 2)); assert_market_storage! { "relayers": vec![1, 2, 3], @@ -1009,7 +1037,7 @@ fn test_order_create_if_market_ready() { let (lane, message_nonce) = send_regular_message(1, default_fee); let order = FeeMarket::order((&lane, &message_nonce)).unwrap(); let relayers = order.assigned_relayers_slice(); - System::assert_has_event(Event::FeeMarket(crate::Event::OrderCreated( + System::assert_has_event(RuntimeEvent::FeeMarket(crate::Event::OrderCreated( lane, message_nonce, order.fee(), @@ -1029,7 +1057,12 @@ fn test_order_create_if_market_not_ready() { .execute_with(|| { System::set_block_number(2); assert_err!( - Messages::send_message(Origin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, 200), + Messages::send_message( + RuntimeOrigin::signed(1), + TEST_LANE_ID, + REGULAR_PAYLOAD, + 200 + ), DispatchError::Module(ModuleError { index: 4, error: [3, 0, 0, 0], @@ -1361,7 +1394,7 @@ fn test_payment_cal_rewards_normally_single_message() { assert!(TestMessageDeliveryAndDispatchPayment::is_reward_paid(3, 4)); assert!(TestMessageDeliveryAndDispatchPayment::is_reward_paid(5, 6)); assert!(TestMessageDeliveryAndDispatchPayment::is_reward_paid(TEST_RELAYER_A, 24)); - System::assert_has_event(Event::FeeMarket(crate::Event::OrderReward( + System::assert_has_event(RuntimeEvent::FeeMarket(crate::Event::OrderReward( lane, message_nonce, RewardItem { @@ -1743,7 +1776,7 @@ fn test_payment_slash_with_protect() { System::set_block_number(2); let market_fee = FeeMarket::market_fee().unwrap(); let _ = send_regular_message(1, market_fee); - assert_ok!(FeeMarket::set_slash_protect(Origin::root(), 50)); + assert_ok!(FeeMarket::set_slash_protect(RuntimeOrigin::root(), 50)); // Receive delivery message proof System::set_block_number(2000); @@ -1794,7 +1827,7 @@ fn test_payment_slash_event() { System::set_block_number(2); let market_fee = FeeMarket::market_fee().unwrap(); let (_, _) = send_regular_message(1, market_fee); - assert_ok!(FeeMarket::set_slash_protect(Origin::root(), 50)); + assert_ok!(FeeMarket::set_slash_protect(RuntimeOrigin::root(), 50)); // Receive delivery message proof System::set_block_number(2000); @@ -1805,32 +1838,38 @@ fn test_payment_slash_event() { 1, ); - System::assert_has_event(Event::FeeMarket(crate::Event::FeeMarketSlash(SlashReport { - lane: TEST_LANE_ID, - message: 1, - sent_time: 2, - confirm_time: Some(2000), - delay_time: Some(1848), - account_id: 1, - amount: 50, - }))); - System::assert_has_event(Event::FeeMarket(crate::Event::FeeMarketSlash(SlashReport { - lane: TEST_LANE_ID, - message: 1, - sent_time: 2, - confirm_time: Some(2000), - delay_time: Some(1848), - account_id: 2, - amount: 50, - }))); - System::assert_has_event(Event::FeeMarket(crate::Event::FeeMarketSlash(SlashReport { - lane: TEST_LANE_ID, - message: 1, - sent_time: 2, - confirm_time: Some(2000), - delay_time: Some(1848), - account_id: 3, - amount: 50, - }))); + System::assert_has_event(RuntimeEvent::FeeMarket(crate::Event::FeeMarketSlash( + SlashReport { + lane: TEST_LANE_ID, + message: 1, + sent_time: 2, + confirm_time: Some(2000), + delay_time: Some(1848), + account_id: 1, + amount: 50, + }, + ))); + System::assert_has_event(RuntimeEvent::FeeMarket(crate::Event::FeeMarketSlash( + SlashReport { + lane: TEST_LANE_ID, + message: 1, + sent_time: 2, + confirm_time: Some(2000), + delay_time: Some(1848), + account_id: 2, + amount: 50, + }, + ))); + System::assert_has_event(RuntimeEvent::FeeMarket(crate::Event::FeeMarketSlash( + SlashReport { + lane: TEST_LANE_ID, + message: 1, + sent_time: 2, + confirm_time: Some(2000), + delay_time: Some(1848), + account_id: 3, + amount: 50, + }, + ))); }); } diff --git a/modules/fee-market/src/weight.rs b/modules/fee-market/src/weight.rs index d0c4f0ad9..3d338c09f 100644 --- a/modules/fee-market/src/weight.rs +++ b/modules/fee-market/src/weight.rs @@ -67,88 +67,89 @@ pub trait WeightInfo { pub struct SubstrateWeight(PhantomData); impl WeightInfo for SubstrateWeight { fn enroll_and_lock_collateral() -> Weight { - (196_247_000 as Weight) - .saturating_add(T::DbWeight::get().reads(25 as Weight)) - .saturating_add(T::DbWeight::get().writes(5 as Weight)) + Weight::from_ref_time(196_247_000 as u64) + .saturating_add(T::DbWeight::get().reads(25 as u64)) + .saturating_add(T::DbWeight::get().writes(5 as u64)) } fn increase_locked_collateral() -> Weight { - (192_480_000 as Weight) - .saturating_add(T::DbWeight::get().reads(25 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(192_480_000 as u64) + .saturating_add(T::DbWeight::get().reads(25 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } fn decrease_locked_collateral() -> Weight { - (200_415_000 as Weight) - .saturating_add(T::DbWeight::get().reads(25 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) + Weight::from_ref_time(200_415_000 as u64) + .saturating_add(T::DbWeight::get().reads(25 as u64)) + .saturating_add(T::DbWeight::get().writes(4 as u64)) } // Storage: PangoroFeeMarket Relayers (r:1 w:0) Storage: PangoroFeeMarket RelayersMap (r:20 w:1) // Storage: PangoroFeeMarket Orders (r:1 w:0) Storage: PangoroFeeMarket AssignedRelayersNumber // (r:1 w:0) Storage: PangoroFeeMarket AssignedRelayers (r:0 w:1) fn update_relay_fee() -> Weight { - (178_163_000 as Weight) - .saturating_add(T::DbWeight::get().reads(23 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) + Weight::from_ref_time(178_163_000 as u64) + .saturating_add(T::DbWeight::get().reads(23 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } fn cancel_enrollment() -> Weight { - (192_109_000 as Weight) - .saturating_add(T::DbWeight::get().reads(25 as Weight)) - .saturating_add(T::DbWeight::get().writes(5 as Weight)) + Weight::from_ref_time(192_109_000 as u64) + .saturating_add(T::DbWeight::get().reads(25 as u64)) + .saturating_add(T::DbWeight::get().writes(5 as u64)) } fn set_slash_protect() -> Weight { - (17_332_000 as Weight).saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(17_332_000 as u64).saturating_add(T::DbWeight::get().writes(1 as u64)) } fn set_assigned_relayers_number() -> Weight { - (170_128_000 as Weight) - .saturating_add(T::DbWeight::get().reads(22 as Weight)) - .saturating_add(T::DbWeight::get().writes(2 as Weight)) + Weight::from_ref_time(170_128_000 as u64) + .saturating_add(T::DbWeight::get().reads(22 as u64)) + .saturating_add(T::DbWeight::get().writes(2 as u64)) } } // For backwards compatibility and tests impl WeightInfo for () { fn enroll_and_lock_collateral() -> Weight { - (196_247_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(25 as Weight)) - .saturating_add(RocksDbWeight::get().writes(5 as Weight)) + Weight::from_ref_time(196_247_000 as u64) + .saturating_add(RocksDbWeight::get().reads(25 as u64)) + .saturating_add(RocksDbWeight::get().writes(5 as u64)) } fn increase_locked_collateral() -> Weight { - (192_480_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(25 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(192_480_000 as u64) + .saturating_add(RocksDbWeight::get().reads(25 as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) } fn decrease_locked_collateral() -> Weight { - (200_415_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(25 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + Weight::from_ref_time(200_415_000 as u64) + .saturating_add(RocksDbWeight::get().reads(25 as u64)) + .saturating_add(RocksDbWeight::get().writes(4 as u64)) } fn update_relay_fee() -> Weight { - (178_163_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(23 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + Weight::from_ref_time(178_163_000 as u64) + .saturating_add(RocksDbWeight::get().reads(23 as u64)) + .saturating_add(RocksDbWeight::get().writes(2 as u64)) } fn cancel_enrollment() -> Weight { - (192_109_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(25 as Weight)) - .saturating_add(RocksDbWeight::get().writes(5 as Weight)) + Weight::from_ref_time(192_109_000 as u64) + .saturating_add(RocksDbWeight::get().reads(25 as u64)) + .saturating_add(RocksDbWeight::get().writes(5 as u64)) } fn set_slash_protect() -> Weight { - (17_332_000 as Weight).saturating_add(RocksDbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(17_332_000 as u64) + .saturating_add(RocksDbWeight::get().writes(1 as u64)) } fn set_assigned_relayers_number() -> Weight { - (170_128_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(22 as Weight)) - .saturating_add(RocksDbWeight::get().writes(2 as Weight)) + Weight::from_ref_time(170_128_000 as u64) + .saturating_add(RocksDbWeight::get().reads(22 as u64)) + .saturating_add(RocksDbWeight::get().writes(2 as u64)) } } diff --git a/modules/grandpa/Cargo.toml b/modules/grandpa/Cargo.toml index a432163d6..04da8be43 100644 --- a/modules/grandpa/Cargo.toml +++ b/modules/grandpa/Cargo.toml @@ -17,18 +17,18 @@ bp-header-chain = { default-features = false, path = "../../primitives/header-ch bp-runtime = { default-features = false, path = "../../primitives/runtime" } bp-test-utils = { optional = true, default-features = false, path = "../../primitives/test-utils" } # paritytech -frame-benchmarking = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-finality-grandpa = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-trie = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +frame-benchmarking = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-finality-grandpa = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-trie = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [dev-dependencies] # paritytech -sp-core = { git = "https://github.com/paritytech/substrate", branch = "master" } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" } +sp-core = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [features] default = ["std"] diff --git a/modules/grandpa/src/extension.rs b/modules/grandpa/src/extension.rs index f9ed8fdd0..059cab291 100644 --- a/modules/grandpa/src/extension.rs +++ b/modules/grandpa/src/extension.rs @@ -29,11 +29,11 @@ use sp_runtime::{ /// if there are multiple relays running and submitting the same information. impl< Call: IsSubType, T>>, - T: frame_system::Config + Config, + T: frame_system::Config + Config, I: 'static, > FilterCall for Pallet { - fn validate(call: &::Call) -> TransactionValidity { + fn validate(call: &::RuntimeCall) -> TransactionValidity { let bundled_block_number = match call.is_sub_type() { Some(crate::Call::::submit_finality_proof { ref finality_target, .. }) => *finality_target.number(), @@ -66,18 +66,19 @@ mod tests { // darwinia-network use super::FilterCall; use crate::{ - mock::{run_test, test_header, Call, TestNumber, TestRuntime}, + mock::{run_test, test_header, RuntimeCall, TestNumber, TestRuntime}, BestFinalized, }; use bp_test_utils::make_default_justification; fn validate_block_submit(num: TestNumber) -> bool { - crate::Pallet::::validate(&Call::Grandpa( - crate::Call::::submit_finality_proof { - finality_target: Box::new(test_header(num)), - justification: make_default_justification(&test_header(num)), - }, - )) + crate::Pallet::::validate(&RuntimeCall::Grandpa(crate::Call::< + TestRuntime, + (), + >::submit_finality_proof { + finality_target: Box::new(test_header(num)), + justification: make_default_justification(&test_header(num)), + })) .is_ok() } diff --git a/modules/grandpa/src/lib.rs b/modules/grandpa/src/lib.rs index 3b670edd1..41f9e8a67 100644 --- a/modules/grandpa/src/lib.rs +++ b/modules/grandpa/src/lib.rs @@ -47,12 +47,16 @@ pub use weights::WeightInfo; pub mod benchmarking; mod extension; +mod storage_types; // crates.io use finality_grandpa::voter_set::VoterSet; // darwinia-network use bp_header_chain::{justification::GrandpaJustification, InitializationData}; -use bp_runtime::{BlockNumberOf, Chain, HashOf, HasherOf, HeaderOf, OwnedBridgeModule}; +use bp_runtime::{ + BlockNumberOf, BoundedStorageValue, Chain, HashOf, HasherOf, HeaderOf, OwnedBridgeModule, +}; +use storage_types::StoredAuthoritySet; // paritytech use frame_support::{ensure, fail, log}; use frame_system::ensure_signed; @@ -71,6 +75,9 @@ pub type BridgedBlockHash = HashOf<>::BridgedChain>; pub type BridgedBlockHasher = HasherOf<>::BridgedChain>; /// Header of the bridged chain. pub type BridgedHeader = HeaderOf<>::BridgedChain>; +/// Stored header of the bridged chain. +pub type StoredBridgedHeader = + BoundedStorageValue<>::MaxBridgedHeaderSize, BridgedHeader>; #[frame_support::pallet] pub mod pallet { @@ -105,12 +112,24 @@ pub mod pallet { #[pallet::constant] type HeadersToKeep: Get; + /// Max number of authorities at the bridged chain. + #[pallet::constant] + type MaxBridgedAuthorities: Get; + /// Maximal size (in bytes) of the SCALE-encoded bridged chain header. + /// + /// This constant must be selected with care. The pallet requires mandatory headers to be + /// submitted to be able to proceed. Mandatory headers contain public keys of all GRANDPA + /// authorities. E.g. for 1024 authorities, the size of encoded keys will be at least 32 KB. + /// The same header may also contain other digest items as well, so some reserve here + /// is required. + #[pallet::constant] + type MaxBridgedHeaderSize: Get; + /// Weights gathered through benchmarking. type WeightInfo: WeightInfo; } #[pallet::pallet] - #[pallet::without_storage_info] pub struct Pallet(PhantomData<(T, I)>); #[pallet::hooks] @@ -118,9 +137,7 @@ pub mod pallet { fn on_initialize(_n: T::BlockNumber) -> frame_support::weights::Weight { >::mutate(|count| *count = count.saturating_sub(1)); - (0_u64) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(1)) + T::DbWeight::get().reads_writes(1, 1) } } @@ -184,12 +201,24 @@ pub mod pallet { let authority_set = >::get(); let set_id = authority_set.set_id; - verify_justification::(&justification, hash, *number, authority_set)?; + verify_justification::(&justification, hash, *number, authority_set.into())?; let is_authorities_change_enacted = try_enact_authority_change::(&finality_target, set_id)?; + let finality_target = StoredBridgedHeader::::try_from_inner(*finality_target) + .map_err(|e| { + log::error!( + target: LOG_TARGET, + "Size of header {:?} ({}) is larger that the configured value {}", + hash, + e.value_size, + e.maximal_size, + ); + + Error::::TooLargeHeader + })?; >::mutate(|count| *count += 1); - insert_header::(*finality_target, hash); + insert_header::(finality_target, hash); log::info!( target: LOG_TARGET, "Successfully imported finalized header with hash {:?}!", @@ -225,7 +254,7 @@ pub mod pallet { let init_allowed = !>::exists(); ensure!(init_allowed, >::AlreadyInitialized); - initialize_bridge::(init_data.clone()); + initialize_bridge::(init_data.clone())?; log::info!( target: LOG_TARGET, @@ -290,12 +319,12 @@ pub mod pallet { /// Headers which have been imported into the pallet. #[pallet::storage] pub type ImportedHeaders, I: 'static = ()> = - StorageMap<_, Identity, BridgedBlockHash, BridgedHeader>; + StorageMap<_, Identity, BridgedBlockHash, StoredBridgedHeader>; /// The current GRANDPA Authority set. #[pallet::storage] pub(super) type CurrentAuthoritySet, I: 'static = ()> = - StorageValue<_, bp_header_chain::AuthoritySet, ValueQuery>; + StorageValue<_, StoredAuthoritySet, ValueQuery>; /// Optional pallet owner. /// @@ -337,7 +366,7 @@ pub mod pallet { } if let Some(init_data) = self.init_data.clone() { - initialize_bridge::(init_data); + initialize_bridge::(init_data).expect("genesis config is correct; qed"); } else { // Since the bridge hasn't been initialized we shouldn't allow anyone to perform // transactions. @@ -368,6 +397,10 @@ pub mod pallet { AlreadyInitialized, /// The storage proof doesn't contains storage root. So it is invalid for given header. StorageRootMismatch, + /// Too many authorities in the set. + TooManyAuthoritiesInSet, + /// Too large header. + TooLargeHeader, /// Error generated by the `OwnedBridgeModule` trait. BridgeModule(bp_runtime::OwnedBridgeModuleError), } @@ -396,8 +429,11 @@ pub mod pallet { ensure!(change.delay == Zero::zero(), >::UnsupportedScheduledChange); // TODO [#788]: Stop manually increasing the `set_id` here. - let next_authorities = bp_header_chain::AuthoritySet { - authorities: change.next_authorities, + let next_authorities = StoredAuthoritySet:: { + authorities: change + .next_authorities + .try_into() + .map_err(|_| Error::::TooManyAuthoritiesInSet)?, set_id: current_set_id + 1, }; @@ -458,7 +494,7 @@ pub mod pallet { /// Note this function solely takes care of updating the storage and pruning old entries, /// but does not verify the validity of such import. pub(crate) fn insert_header, I: 'static>( - header: BridgedHeader, + header: StoredBridgedHeader, hash: BridgedBlockHash, ) { let index = >::get(); @@ -479,19 +515,42 @@ pub mod pallet { /// were called by a trusted origin. pub(crate) fn initialize_bridge, I: 'static>( init_params: super::InitializationData>, - ) { + ) -> Result<(), Error> { let super::InitializationData { header, authority_list, set_id, operating_mode } = init_params; - + let authority_set_length = authority_list.len(); + let authority_set = StoredAuthoritySet::::try_new(authority_list, set_id) + .map_err(|_| { + log::error!( + target: LOG_TARGET, + "Failed to initialize bridge. Number of authorities in the set {} is larger than the configured value {}", + authority_set_length, + T::MaxBridgedAuthorities::get(), + ); + + Error::TooManyAuthoritiesInSet + })?; let initial_hash = header.hash(); + let header = StoredBridgedHeader::::try_from_inner(*header).map_err(|e| { + log::error!( + target: LOG_TARGET, + "Failed to initialize bridge. Size of header {:?} ({}) is larger that the configured value {}", + initial_hash, + e.value_size, + e.maximal_size, + ); + + Error::::TooLargeHeader + })?; + >::put(initial_hash); >::put(0); - insert_header::(*header, initial_hash); + insert_header::(header, initial_hash); - let authority_set = bp_header_chain::AuthoritySet::new(authority_list, set_id); >::put(authority_set); >::put(operating_mode); + Ok(()) } #[cfg(feature = "runtime-benchmarks")] @@ -500,7 +559,7 @@ pub mod pallet { ) { let start_number = *init_params.header.number(); let end_number = start_number + T::HeadersToKeep::get().into(); - initialize_bridge::(init_params); + initialize_bridge::(init_params).expect("benchmarks are correct"); let mut number = start_number; while number < end_number { @@ -513,7 +572,11 @@ pub mod pallet { Default::default(), ); let hash = header.hash(); - insert_header::(header, hash); + insert_header::( + StoredBridgedHeader::::try_from_inner(header) + .expect("only used from benchmarks; benchmarks are correct; qed"), + hash, + ); } } } @@ -526,7 +589,7 @@ impl, I: 'static> Pallet { /// if the pallet has not been initialized yet. pub fn best_finalized() -> Option> { let (_, hash) = >::get()?; - >::get(hash) + >::get(hash).map(|h| h.into_inner()) } /// Check if a particular header is known to the bridge pallet. @@ -596,13 +659,17 @@ pub fn initialize_for_benchmarks, I: 'static>(header: BridgedHeader * benchmarks */ set_id: 0, operating_mode: bp_runtime::BasicOperatingMode::Normal, - }); + }) + .expect("only used from benchmarks; benchmarks are correct; qed"); } #[cfg(test)] mod tests { use super::*; - use crate::mock::{run_test, test_header, Origin, TestHeader, TestNumber, TestRuntime}; + use crate::mock::{ + run_test, test_header, RuntimeOrigin, TestHeader, TestNumber, TestRuntime, + MAX_BRIDGED_AUTHORITIES, MAX_HEADER_SIZE, + }; use bp_runtime::BasicOperatingMode; use bp_test_utils::{ authority_list, generate_owned_bridge_module_tests, make_default_justification, @@ -610,17 +677,17 @@ mod tests { }; use codec::Encode; use frame_support::{ - assert_err, assert_noop, assert_ok, storage::generator::StorageValue, - weights::PostDispatchInfo, + assert_err, assert_noop, assert_ok, dispatch::PostDispatchInfo, + storage::generator::StorageValue, }; use sp_runtime::{Digest, DigestItem, DispatchError}; fn initialize_substrate_bridge() { - assert_ok!(init_with_origin(Origin::root())); + assert_ok!(init_with_origin(RuntimeOrigin::root())); } fn init_with_origin( - origin: Origin, + origin: RuntimeOrigin, ) -> Result< InitializationData, sp_runtime::DispatchErrorWithPostInfo, @@ -642,7 +709,7 @@ mod tests { let justification = make_default_justification(&header); Pallet::::submit_finality_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(header), justification, ) @@ -678,16 +745,32 @@ mod tests { Digest { logs: vec![DigestItem::Consensus(GRANDPA_ENGINE_ID, consensus_log.encode())] } } + fn many_authorities_log() -> Digest { + let consensus_log = + ConsensusLog::::ScheduledChange(sp_finality_grandpa::ScheduledChange { + next_authorities: std::iter::repeat((ALICE.into(), 1)) + .take(MAX_BRIDGED_AUTHORITIES as usize + 1) + .collect(), + delay: 0, + }); + + Digest { logs: vec![DigestItem::Consensus(GRANDPA_ENGINE_ID, consensus_log.encode())] } + } + + fn large_digest() -> Digest { + Digest { logs: vec![DigestItem::Other(vec![42; MAX_HEADER_SIZE as _])] } + } + #[test] fn init_root_or_owner_origin_can_initialize_pallet() { run_test(|| { - assert_noop!(init_with_origin(Origin::signed(1)), DispatchError::BadOrigin); - assert_ok!(init_with_origin(Origin::root())); + assert_noop!(init_with_origin(RuntimeOrigin::signed(1)), DispatchError::BadOrigin); + assert_ok!(init_with_origin(RuntimeOrigin::root())); // Reset storage so we can initialize the pallet again BestFinalized::::kill(); PalletOwner::::put(2); - assert_ok!(init_with_origin(Origin::signed(2))); + assert_ok!(init_with_origin(RuntimeOrigin::signed(2))); }) } @@ -697,7 +780,7 @@ mod tests { assert_eq!(BestFinalized::::get(), None,); assert_eq!(Pallet::::best_finalized(), None); - let init_data = init_with_origin(Origin::root()).unwrap(); + let init_data = init_with_origin(RuntimeOrigin::root()).unwrap(); assert!(>::contains_key(init_data.header.hash())); assert_eq!(BestFinalized::::get().unwrap().1, init_data.header.hash()); @@ -714,19 +797,58 @@ mod tests { run_test(|| { initialize_substrate_bridge(); assert_noop!( - init_with_origin(Origin::root()), + init_with_origin(RuntimeOrigin::root()), >::AlreadyInitialized ); }) } + #[test] + fn init_fails_if_there_are_too_many_authorities_in_the_set() { + run_test(|| { + let genesis = test_header(0); + let init_data = InitializationData { + header: Box::new(genesis), + authority_list: std::iter::repeat(authority_list().remove(0)) + .take(MAX_BRIDGED_AUTHORITIES as usize + 1) + .collect(), + set_id: 1, + operating_mode: BasicOperatingMode::Normal, + }; + + assert_noop!( + Pallet::::initialize(RuntimeOrigin::root(), init_data), + Error::::TooManyAuthoritiesInSet, + ); + }); + } + + #[test] + fn init_fails_if_header_is_too_large() { + run_test(|| { + let mut genesis = test_header(0); + genesis.digest = large_digest(); + let init_data = InitializationData { + header: Box::new(genesis), + authority_list: authority_list(), + set_id: 1, + operating_mode: BasicOperatingMode::Normal, + }; + + assert_noop!( + Pallet::::initialize(RuntimeOrigin::root(), init_data), + Error::::TooLargeHeader, + ); + }); + } + #[test] fn pallet_rejects_transactions_if_halted() { run_test(|| { initialize_substrate_bridge(); assert_ok!(Pallet::::set_operating_mode( - Origin::root(), + RuntimeOrigin::root(), BasicOperatingMode::Halted )); assert_noop!( @@ -735,7 +857,7 @@ mod tests { ); assert_ok!(Pallet::::set_operating_mode( - Origin::root(), + RuntimeOrigin::root(), BasicOperatingMode::Normal )); assert_ok!(submit_finality_proof(1)); @@ -757,7 +879,7 @@ mod tests { submit_finality_proof(1), PostDispatchInfo { actual_weight: None, - pays_fee: frame_support::weights::Pays::Yes, + pays_fee: frame_support::dispatch::Pays::Yes, }, ); @@ -780,7 +902,7 @@ mod tests { assert_err!( Pallet::::submit_finality_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(header), justification, ), @@ -800,7 +922,7 @@ mod tests { assert_err!( Pallet::::submit_finality_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(header), justification, ), @@ -822,14 +944,14 @@ mod tests { operating_mode: BasicOperatingMode::Normal, }; - assert_ok!(Pallet::::initialize(Origin::root(), init_data)); + assert_ok!(Pallet::::initialize(RuntimeOrigin::root(), init_data)); let header = test_header(1); let justification = make_default_justification(&header); assert_err!( Pallet::::submit_finality_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(header), justification, ), @@ -868,13 +990,13 @@ mod tests { // Let's import our test header assert_ok!( Pallet::::submit_finality_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(header.clone()), justification ), PostDispatchInfo { actual_weight: None, - pays_fee: frame_support::weights::Pays::No, + pays_fee: frame_support::dispatch::Pays::No, }, ); @@ -885,7 +1007,8 @@ mod tests { // Make sure that the authority set actually changed upon importing our header assert_eq!( >::get(), - bp_header_chain::AuthoritySet::new(next_authorities, next_set_id), + StoredAuthoritySet::::try_new(next_authorities, next_set_id) + .unwrap(), ); }) } @@ -906,7 +1029,7 @@ mod tests { // Should not be allowed to import this header assert_err!( Pallet::::submit_finality_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(header), justification ), @@ -931,7 +1054,7 @@ mod tests { // Should not be allowed to import this header assert_err!( Pallet::::submit_finality_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(header), justification ), @@ -940,6 +1063,56 @@ mod tests { }) } + #[test] + fn importing_header_rejects_header_with_too_many_authorities() { + run_test(|| { + initialize_substrate_bridge(); + + // Need to update the header digest to indicate that our header signals an authority set + // change. However, the change doesn't happen until the next block. + let mut header = test_header(2); + header.digest = many_authorities_log(); + + // Create a valid justification for the header + let justification = make_default_justification(&header); + + // Should not be allowed to import this header + assert_err!( + Pallet::::submit_finality_proof( + RuntimeOrigin::signed(1), + Box::new(header), + justification + ), + >::TooManyAuthoritiesInSet + ); + }); + } + + #[test] + fn importing_header_rejects_header_if_it_is_too_large() { + run_test(|| { + initialize_substrate_bridge(); + + // Need to update the header digest to indicate that our header signals an authority set + // change. However, the change doesn't happen until the next block. + let mut header = test_header(2); + header.digest = large_digest(); + + // Create a valid justification for the header + let justification = make_default_justification(&header); + + // Should not be allowed to import this header + assert_err!( + Pallet::::submit_finality_proof( + RuntimeOrigin::signed(1), + Box::new(header), + justification + ), + >::TooLargeHeader + ); + }); + } + #[test] fn parse_finalized_storage_proof_rejects_proof_on_unknown_header() { run_test(|| { @@ -964,7 +1137,10 @@ mod tests { let hash = header.hash(); >::put((2, hash)); - >::insert(hash, header); + >::insert( + hash, + StoredBridgedHeader::::try_from_inner(header).unwrap(), + ); assert_ok!( Pallet::::parse_finalized_storage_proof(hash, storage_proof, |_| (),), @@ -993,7 +1169,7 @@ mod tests { invalid_justification.round = 42; Pallet::::submit_finality_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(header), invalid_justification, ) diff --git a/modules/grandpa/src/mock.rs b/modules/grandpa/src/mock.rs index fb229f26c..ba4df1ceb 100644 --- a/modules/grandpa/src/mock.rs +++ b/modules/grandpa/src/mock.rs @@ -40,6 +40,9 @@ pub type TestNumber = crate::BridgedBlockNumber; type Block = MockBlock; type UncheckedExtrinsic = MockUncheckedExtrinsic; +pub const MAX_BRIDGED_AUTHORITIES: u32 = 2048; +pub const MAX_HEADER_SIZE: u32 = 65536; + frame_support::construct_runtime! { pub enum TestRuntime where Block = Block, @@ -53,7 +56,7 @@ frame_support::construct_runtime! { frame_support::parameter_types! { pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: Weight = 1024; + pub const MaximumBlockWeight: Weight = Weight::from_ref_time(1024); pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } @@ -65,9 +68,7 @@ impl frame_system::Config for TestRuntime { type BlockLength = (); type BlockNumber = u64; type BlockWeights = (); - type Call = Call; type DbWeight = (); - type Event = (); type Hash = H256; type Hashing = BlakeTwo256; type Header = Header; @@ -77,8 +78,10 @@ impl frame_system::Config for TestRuntime { type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); - type Origin = Origin; type PalletInfo = PalletInfo; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = (); + type RuntimeOrigin = RuntimeOrigin; type SS58Prefix = (); type SystemWeightInfo = (); type Version = (); @@ -93,6 +96,8 @@ frame_support::parameter_types! { impl grandpa::Config for TestRuntime { type BridgedChain = TestBridgedChain; type HeadersToKeep = HeadersToKeep; + type MaxBridgedAuthorities = frame_support::traits::ConstU32; + type MaxBridgedHeaderSize = frame_support::traits::ConstU32; type MaxRequests = MaxRequests; type WeightInfo = (); } diff --git a/modules/grandpa/src/storage_types.rs b/modules/grandpa/src/storage_types.rs new file mode 100644 index 000000000..d930dbadb --- /dev/null +++ b/modules/grandpa/src/storage_types.rs @@ -0,0 +1,66 @@ +// Copyright 2022 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 . + +//! Wrappers for public types that are implementing `MaxEncodedLen` + +use crate::Config; + +use bp_header_chain::AuthoritySet; +use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::{BoundedVec, RuntimeDebugNoBound}; +use scale_info::TypeInfo; +use sp_finality_grandpa::{AuthorityId, AuthorityList, AuthorityWeight, SetId}; + +/// A bounded list of Grandpa authorities with associated weights. +pub type StoredAuthorityList = + BoundedVec<(AuthorityId, AuthorityWeight), MaxBridgedAuthorities>; + +/// A bounded GRANDPA Authority List and ID. +#[derive(Clone, Decode, Encode, Eq, TypeInfo, MaxEncodedLen, RuntimeDebugNoBound)] +#[scale_info(skip_type_params(T, I))] +pub struct StoredAuthoritySet, I: 'static> { + /// List of GRANDPA authorities for the current round. + pub authorities: StoredAuthorityList<>::MaxBridgedAuthorities>, + /// Monotonic identifier of the current GRANDPA authority set. + pub set_id: SetId, +} + +impl, I: 'static> StoredAuthoritySet { + /// Try to create a new bounded GRANDPA Authority Set from unbounded list. + /// + /// Returns error if number of authorities in the provided list is too large. + pub fn try_new(authorities: AuthorityList, set_id: SetId) -> Result { + Ok(Self { authorities: TryFrom::try_from(authorities).map_err(drop)?, set_id }) + } +} + +impl, I: 'static> PartialEq for StoredAuthoritySet { + fn eq(&self, other: &Self) -> bool { + self.set_id == other.set_id && self.authorities == other.authorities + } +} + +impl, I: 'static> Default for StoredAuthoritySet { + fn default() -> Self { + StoredAuthoritySet { authorities: BoundedVec::default(), set_id: 0 } + } +} + +impl, I: 'static> From> for AuthoritySet { + fn from(t: StoredAuthoritySet) -> Self { + AuthoritySet { authorities: t.authorities.into(), set_id: t.set_id } + } +} diff --git a/modules/grandpa/src/weights.rs b/modules/grandpa/src/weights.rs index f23a2ac19..aea26dd56 100644 --- a/modules/grandpa/src/weights.rs +++ b/modules/grandpa/src/weights.rs @@ -54,24 +54,24 @@ pub trait WeightInfo { } /// Weights for `pallet_bridge_grandpa` using the Millau node and recommended hardware. -pub struct MillauWeight(PhantomData); -impl WeightInfo for MillauWeight { +pub struct BridgeWeight(PhantomData); +impl WeightInfo for BridgeWeight { fn submit_finality_proof(p: u32, v: u32) -> Weight { - (55_070_000 as Weight) - .saturating_add((39_678_000 as Weight).saturating_mul(p as Weight)) - .saturating_add((1_540_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(T::DbWeight::get().reads(7 as Weight)) - .saturating_add(T::DbWeight::get().writes(6 as Weight)) + Weight::from_ref_time(55_070_000 as u64) + .saturating_add(Weight::from_ref_time(39_678_000 as u64).saturating_mul(p as u64)) + .saturating_add(Weight::from_ref_time(1_540_000 as u64).saturating_mul(v as u64)) + .saturating_add(T::DbWeight::get().reads(7 as u64)) + .saturating_add(T::DbWeight::get().writes(6 as u64)) } } // For backwards compatibility and tests impl WeightInfo for () { fn submit_finality_proof(p: u32, v: u32) -> Weight { - (55_070_000 as Weight) - .saturating_add((39_678_000 as Weight).saturating_mul(p as Weight)) - .saturating_add((1_540_000 as Weight).saturating_mul(v as Weight)) - .saturating_add(RocksDbWeight::get().reads(7 as Weight)) - .saturating_add(RocksDbWeight::get().writes(6 as Weight)) + Weight::from_ref_time(55_070_000 as u64) + .saturating_add(Weight::from_ref_time(39_678_000 as u64).saturating_mul(p as u64)) + .saturating_add(Weight::from_ref_time(1_540_000 as u64).saturating_mul(v as u64)) + .saturating_add(RocksDbWeight::get().reads(7 as u64)) + .saturating_add(RocksDbWeight::get().writes(6 as u64)) } } diff --git a/modules/messages/Cargo.toml b/modules/messages/Cargo.toml index 1f2b9b48b..e4d079839 100644 --- a/modules/messages/Cargo.toml +++ b/modules/messages/Cargo.toml @@ -18,19 +18,19 @@ bp-message-dispatch = { default-features = false, path = "../../primitives/messa bp-messages = { default-features = false, path = "../../primitives/messages" } bp-runtime = { default-features = false, path = "../../primitives/runtime" } # paritytech -frame-benchmarking = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +frame-benchmarking = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [dev-dependencies] # darwinia-network bp-test-utils = { path = "../../primitives/test-utils" } # paritytech -pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "master" } -sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" } +pallet-balances = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [features] default = ["std"] diff --git a/modules/messages/src/inbound_lane.rs b/modules/messages/src/inbound_lane.rs index b7d162af6..306260703 100644 --- a/modules/messages/src/inbound_lane.rs +++ b/modules/messages/src/inbound_lane.rs @@ -553,7 +553,7 @@ mod tests { run_test(|| { let mut lane = inbound_lane::(TEST_LANE_ID); let mut payload = REGULAR_PAYLOAD; - payload.dispatch_result.unspent_weight = 1; + *payload.dispatch_result.unspent_weight.ref_time_mut() = 1; assert_eq!( lane.receive_message::( &TEST_RELAYER_A, diff --git a/modules/messages/src/lib.rs b/modules/messages/src/lib.rs index 3e7f0f473..8061b3eec 100644 --- a/modules/messages/src/lib.rs +++ b/modules/messages/src/lib.rs @@ -80,11 +80,7 @@ use bp_messages::{ }; use bp_runtime::{BasicOperatingMode, ChainId, OwnedBridgeModule, Size}; // paritytech -use frame_support::{ - ensure, fail, log, - traits::Get, - weights::{Pays, PostDispatchInfo}, -}; +use frame_support::{dispatch::PostDispatchInfo, ensure, fail, log, traits::Get}; use sp_core::H256; use sp_runtime::traits::Convert; use sp_std::{cell::RefCell, marker::PhantomData, prelude::*}; @@ -103,7 +99,8 @@ pub mod pallet { // General types /// The overarching event type. - type Event: From> + IsType<::Event>; + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; /// Benchmarks results from runtime we're plugged into. type WeightInfo: WeightInfoExt; @@ -178,14 +175,13 @@ pub mod pallet { type TargetHeaderChain: TargetHeaderChain; /// Message payload verifier. type LaneMessageVerifier: LaneMessageVerifier< - Self::Origin, - Self::AccountId, + Self::RuntimeOrigin, Self::OutboundPayload, Self::OutboundMessageFee, >; /// Message delivery payment. type MessageDeliveryAndDispatchPayment: MessageDeliveryAndDispatchPayment< - Self::Origin, + Self::RuntimeOrigin, Self::AccountId, Self::OutboundMessageFee, >; @@ -361,7 +357,7 @@ pub mod pallet { // on this lane. We can't dispatch lane messages out-of-order, so if declared // weight is not enough, let's move to next lane let dispatch_weight = T::MessageDispatch::dispatch_weight(&mut message); - if dispatch_weight > dispatch_weight_left { + if dispatch_weight.any_gt(dispatch_weight_left) { log::trace!( target: LOG_TARGET, "Cannot dispatch any more messages on lane {:?}. Weight: declared={}, left={}", @@ -400,7 +396,7 @@ pub mod pallet { | ReceivalResult::TooManyUnconfirmedMessages => (dispatch_weight, true), }; - let unspent_weight = sp_std::cmp::min(unspent_weight, dispatch_weight); + let unspent_weight = unspent_weight.min(dispatch_weight); dispatch_weight_left -= dispatch_weight - unspent_weight; actual_weight = actual_weight.saturating_sub(unspent_weight).saturating_sub( // delivery call weight formula assumes that the fee is paid at @@ -409,7 +405,7 @@ pub mod pallet { if refund_pay_dispatch_fee { T::WeightInfo::pay_inbound_dispatch_fee_overhead() } else { - 0 + Weight::zero() }, ); } @@ -525,11 +521,11 @@ pub mod pallet { if let Some(confirmed_messages) = confirmed_messages { // handle messages delivery confirmation let preliminary_callback_overhead = - relayers_state.total_messages.saturating_mul(single_message_callback_overhead); + single_message_callback_overhead.saturating_mul(relayers_state.total_messages); let actual_callback_weight = T::OnDeliveryConfirmed::on_messages_delivered(&lane_id, &confirmed_messages); - match preliminary_callback_overhead.checked_sub(actual_callback_weight) { - Some(difference) if difference == 0 => (), + match preliminary_callback_overhead.checked_sub(&actual_callback_weight) { + Some(difference) if difference.is_zero() => (), Some(difference) => { log::trace!( target: LOG_TARGET, @@ -704,8 +700,7 @@ pub fn relayer_fund_account_id bp_messages::source_chain::MessagesBridge< - T::Origin, - T::AccountId, + T::RuntimeOrigin, T::OutboundMessageFee, T::OutboundPayload, > for Pallet @@ -716,7 +711,7 @@ where type Error = sp_runtime::DispatchErrorWithPostInfo; fn send_message( - sender: T::Origin, + sender: T::RuntimeOrigin, lane: LaneId, message: T::OutboundPayload, delivery_and_dispatch_fee: T::OutboundMessageFee, @@ -766,7 +761,7 @@ impl, I: 'static> OutboundLaneStorage for RuntimeOutboundLaneStorag /// Function that actually sends message. fn send_message, I: 'static>( - submitter: T::Origin, + submitter: T::RuntimeOrigin, lane_id: LaneId, payload: T::OutboundPayload, delivery_and_dispatch_fee: T::OutboundMessageFee, @@ -847,8 +842,8 @@ fn send_message, I: 'static>( let single_message_callback_overhead = T::WeightInfo::single_message_callback_overhead(T::DbWeight::get()); let actual_callback_weight = T::OnMessageAccepted::on_messages_accepted(&lane_id, &nonce); - match single_message_callback_overhead.checked_sub(actual_callback_weight) { - Some(difference) if difference == 0 => (), + match single_message_callback_overhead.checked_sub(&actual_callback_weight) { + Some(difference) if difference.is_zero() => (), Some(difference) => { log::trace!( target: LOG_TARGET, @@ -1005,8 +1000,8 @@ mod tests { // darwinia-network use super::*; use crate::mock::{ - message, message_payload, run_test, unrewarded_relayer, Balance, Event as TestEvent, - Origin, TestMessageDeliveryAndDispatchPayment, TestMessagesDeliveryProof, + message, message_payload, run_test, unrewarded_relayer, Balance, RuntimeEvent as TestEvent, + RuntimeOrigin, TestMessageDeliveryAndDispatchPayment, TestMessagesDeliveryProof, TestMessagesParameter, TestMessagesProof, TestOnDeliveryConfirmed1, TestOnDeliveryConfirmed2, TestOnMessageAccepted, TestRuntime, TokenConversionRate, MAX_OUTBOUND_PAYLOAD_SIZE, PAYLOAD_REJECTED_BY_TARGET_CHAIN, REGULAR_PAYLOAD, TEST_LANE_ID, @@ -1051,10 +1046,10 @@ mod tests { let message_nonce = outbound_lane::(TEST_LANE_ID).data().latest_generated_nonce + 1; let weight = Pallet::::send_message( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, - REGULAR_PAYLOAD.declared_weight, + REGULAR_PAYLOAD.declared_weight.ref_time(), ) .expect("send_message has failed") .actual_weight @@ -1076,7 +1071,7 @@ mod tests { // check that fee has been withdrawn from submitter assert!(TestMessageDeliveryAndDispatchPayment::is_fee_paid( 1, - REGULAR_PAYLOAD.declared_weight + REGULAR_PAYLOAD.declared_weight.ref_time() )); weight @@ -1087,7 +1082,7 @@ mod tests { System::::reset_events(); assert_ok!(Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(Ok(( TEST_LANE_ID, InboundLaneData { @@ -1128,7 +1123,7 @@ mod tests { let parameter = TestMessagesParameter::TokenConversionRate(10.into()); assert_ok!(Pallet::::update_pallet_parameter( - Origin::root(), + RuntimeOrigin::root(), parameter.clone(), )); @@ -1152,7 +1147,7 @@ mod tests { let parameter = TestMessagesParameter::TokenConversionRate(10.into()); assert_ok!(Pallet::::update_pallet_parameter( - Origin::signed(2), + RuntimeOrigin::signed(2), parameter.clone(), )); @@ -1173,7 +1168,7 @@ mod tests { run_test(|| { assert_noop!( Pallet::::update_pallet_parameter( - Origin::signed(2), + RuntimeOrigin::signed(2), TestMessagesParameter::TokenConversionRate(10.into()), ), DispatchError::BadOrigin, @@ -1183,7 +1178,7 @@ mod tests { assert_noop!( Pallet::::update_pallet_parameter( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesParameter::TokenConversionRate(10.into()), ), DispatchError::BadOrigin, @@ -1229,28 +1224,28 @@ mod tests { assert_noop!( Pallet::::send_message( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, - REGULAR_PAYLOAD.declared_weight, + REGULAR_PAYLOAD.declared_weight.ref_time(), ), Error::::NotOperatingNormally, ); assert_noop!( Pallet::::receive_messages_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_RELAYER_A, Ok(vec![message(2, REGULAR_PAYLOAD)]).into(), 1, - REGULAR_PAYLOAD.declared_weight, + REGULAR_PAYLOAD.declared_weight ), Error::::BridgeModule(bp_runtime::OwnedBridgeModuleError::Halted), ); assert_noop!( Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(Ok(( TEST_LANE_ID, InboundLaneData { @@ -1284,24 +1279,24 @@ mod tests { assert_noop!( Pallet::::send_message( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, - REGULAR_PAYLOAD.declared_weight, + REGULAR_PAYLOAD.declared_weight.ref_time(), ), Error::::NotOperatingNormally, ); assert_ok!(Pallet::::receive_messages_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_RELAYER_A, Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), 1, - REGULAR_PAYLOAD.declared_weight, + REGULAR_PAYLOAD.declared_weight ),); assert_ok!(Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(Ok(( TEST_LANE_ID, InboundLaneData { @@ -1337,7 +1332,7 @@ mod tests { message_payload.extra.extend_from_slice(&[0u8; MAX_OUTBOUND_PAYLOAD_SIZE as usize]); assert_noop!( Pallet::::send_message( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_LANE_ID, message_payload.clone(), Balance::MAX, @@ -1351,7 +1346,7 @@ mod tests { } assert_eq!(message_payload.size(), MAX_OUTBOUND_PAYLOAD_SIZE); assert_ok!(Pallet::::send_message( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_LANE_ID, message_payload, Balance::MAX, @@ -1365,10 +1360,10 @@ mod tests { // messages with this payload are rejected by target chain verifier assert_noop!( Pallet::::send_message( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_LANE_ID, PAYLOAD_REJECTED_BY_TARGET_CHAIN, - PAYLOAD_REJECTED_BY_TARGET_CHAIN.declared_weight + PAYLOAD_REJECTED_BY_TARGET_CHAIN.declared_weight.ref_time() ), Error::::MessageRejectedByChainVerifier, ); @@ -1381,7 +1376,7 @@ mod tests { // messages with zero fee are rejected by lane verifier assert_noop!( Pallet::::send_message( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, 0 @@ -1397,10 +1392,10 @@ mod tests { TestMessageDeliveryAndDispatchPayment::reject_payments(); assert_noop!( Pallet::::send_message( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, - REGULAR_PAYLOAD.declared_weight + REGULAR_PAYLOAD.declared_weight.ref_time() ), Error::::FailedToWithdrawMessageFee, ); @@ -1411,7 +1406,7 @@ mod tests { fn receive_messages_proof_works() { run_test(|| { assert_ok!(Pallet::::receive_messages_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_RELAYER_A, Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), 1, @@ -1455,7 +1450,7 @@ mod tests { Some(OutboundLaneData { latest_received_nonce: 9, ..Default::default() }); assert_ok!(Pallet::::receive_messages_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_RELAYER_A, message_proof, 1, @@ -1489,12 +1484,14 @@ mod tests { #[test] fn receive_messages_proof_does_not_accept_message_if_dispatch_weight_is_not_enough() { run_test(|| { + let mut declared_weight = REGULAR_PAYLOAD.declared_weight; + *declared_weight.ref_time_mut() -= 1; assert_ok!(Pallet::::receive_messages_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_RELAYER_A, Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), 1, - REGULAR_PAYLOAD.declared_weight - 1, + declared_weight, )); assert_eq!(InboundLanes::::get(TEST_LANE_ID).last_delivered_nonce(), 0); }); @@ -1505,11 +1502,11 @@ mod tests { run_test(|| { assert_noop!( Pallet::::receive_messages_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_RELAYER_A, Err(()).into(), 1, - 0, + Weight::zero(), ), Error::::InvalidMessagesProof, ); @@ -1521,11 +1518,11 @@ mod tests { run_test(|| { assert_noop!( Pallet::::receive_messages_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_RELAYER_A, Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), u32::MAX, - 0, + Weight::zero(), ), Error::::TooManyMessagesInTheProof, ); @@ -1549,13 +1546,13 @@ mod tests { fn receive_messages_delivery_proof_rewards_relayers() { run_test(|| { assert_ok!(Pallet::::send_message( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, 1000, )); assert_ok!(Pallet::::send_message( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_LANE_ID, REGULAR_PAYLOAD, 2000, @@ -1563,7 +1560,7 @@ mod tests { // this reports delivery of message 1 => reward is paid to TEST_RELAYER_A assert_ok!(Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(Ok(( TEST_LANE_ID, InboundLaneData { @@ -1586,7 +1583,7 @@ mod tests { // this reports delivery of both message 1 and message 2 => reward is paid only to // TEST_RELAYER_B assert_ok!(Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(Ok(( TEST_LANE_ID, InboundLaneData { @@ -1616,7 +1613,7 @@ mod tests { run_test(|| { assert_noop!( Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(Err(())), Default::default(), ), @@ -1631,7 +1628,7 @@ mod tests { // when number of relayers entries is invalid assert_noop!( Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(Ok(( TEST_LANE_ID, InboundLaneData { @@ -1657,7 +1654,7 @@ mod tests { // when number of messages is invalid assert_noop!( Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(Ok(( TEST_LANE_ID, InboundLaneData { @@ -1683,7 +1680,7 @@ mod tests { // when last delivered nonce is invalid assert_noop!( Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(Ok(( TEST_LANE_ID, InboundLaneData { @@ -1715,11 +1712,12 @@ mod tests { invalid_message.data.payload = Vec::new(); assert_ok!(Pallet::::receive_messages_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_RELAYER_A, Ok(vec![invalid_message]).into(), 1, - 0, // weight may be zero in this case (all messages are improperly encoded) + Weight::zero(), /* weight may be zero in this case (all messages are + * improperly encoded) */ ),); assert_eq!(InboundLanes::::get(TEST_LANE_ID).last_delivered_nonce(), 1,); @@ -1733,7 +1731,7 @@ mod tests { invalid_message.data.payload = Vec::new(); assert_ok!(Pallet::::receive_messages_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_RELAYER_A, Ok( vec![message(1, REGULAR_PAYLOAD), invalid_message, message(3, REGULAR_PAYLOAD),] @@ -1750,12 +1748,12 @@ mod tests { #[test] fn actual_dispatch_weight_does_not_overlow() { run_test(|| { - let message1 = message(1, message_payload(0, Weight::MAX / 2)); - let message2 = message(2, message_payload(0, Weight::MAX / 2)); - let message3 = message(3, message_payload(0, Weight::MAX / 2)); + let message1 = message(1, message_payload(0, u64::MAX / 2)); + let message2 = message(2, message_payload(0, u64::MAX / 2)); + let message3 = message(3, message_payload(0, u64::MAX / 2)); assert_ok!(Pallet::::receive_messages_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_RELAYER_A, // this may cause overflow if source chain storage is invalid Ok(vec![message1, message2, message3]).into(), @@ -1771,11 +1769,11 @@ mod tests { run_test(|| { fn submit_with_unspent_weight( nonce: MessageNonce, - unspent_weight: Weight, + unspent_weight: u64, is_prepaid: bool, ) -> (Weight, Weight) { let mut payload = REGULAR_PAYLOAD; - payload.dispatch_result.unspent_weight = unspent_weight; + *payload.dispatch_result.unspent_weight.ref_time_mut() = unspent_weight; payload.dispatch_result.dispatch_fee_paid_during_dispatch = !is_prepaid; let proof = Ok(vec![message(nonce, payload)]).into(); let messages_count = 1; @@ -1786,7 +1784,7 @@ mod tests { REGULAR_PAYLOAD.declared_weight, ); let post_dispatch_weight = Pallet::::receive_messages_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TEST_RELAYER_A, proof, messages_count, @@ -1801,16 +1799,26 @@ mod tests { // when dispatch is returning `unspent_weight < declared_weight` let (pre, post) = submit_with_unspent_weight(1, 1, false); - assert_eq!(post, pre - 1); + assert_eq!(post.ref_time(), pre.ref_time() - 1); // when dispatch is returning `unspent_weight = declared_weight` - let (pre, post) = submit_with_unspent_weight(2, REGULAR_PAYLOAD.declared_weight, false); - assert_eq!(post, pre - REGULAR_PAYLOAD.declared_weight); + let (pre, post) = + submit_with_unspent_weight(2, REGULAR_PAYLOAD.declared_weight.ref_time(), false); + assert_eq!( + post.ref_time(), + pre.ref_time() - REGULAR_PAYLOAD.declared_weight.ref_time() + ); // when dispatch is returning `unspent_weight > declared_weight` - let (pre, post) = - submit_with_unspent_weight(3, REGULAR_PAYLOAD.declared_weight + 1, false); - assert_eq!(post, pre - REGULAR_PAYLOAD.declared_weight); + let (pre, post) = submit_with_unspent_weight( + 3, + REGULAR_PAYLOAD.declared_weight.ref_time() + 1, + false, + ); + assert_eq!( + post.ref_time(), + pre.ref_time() - REGULAR_PAYLOAD.declared_weight.ref_time() + ); // when there's no unspent weight let (pre, post) = submit_with_unspent_weight(4, 0, false); @@ -1819,8 +1827,10 @@ mod tests { // when dispatch is returning `unspent_weight < declared_weight` AND message is prepaid let (pre, post) = submit_with_unspent_weight(5, 1, true); assert_eq!( - post, - pre - 1 - ::WeightInfo::pay_inbound_dispatch_fee_overhead() + post.ref_time(), + pre.ref_time() + - 1 - ::WeightInfo::pay_inbound_dispatch_fee_overhead() + .ref_time() ); }); } @@ -1864,7 +1874,7 @@ mod tests { // first tx with messages 1+2 assert_ok!(Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(messages_1_and_2_proof), UnrewardedRelayersState { unrewarded_relayer_entries: 1, @@ -1875,7 +1885,7 @@ mod tests { )); // second tx with message 3 assert_ok!(Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(messages_3_proof), UnrewardedRelayersState { unrewarded_relayer_entries: 1, @@ -1918,7 +1928,7 @@ mod tests { crate::mock::DbWeight::get(), ); let post_dispatch_weight = Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), proof, relayers_state, ) @@ -1978,7 +1988,7 @@ mod tests { // numer of actually confirmed messages is `1`. assert_noop!( Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(Ok(( TEST_LANE_ID, InboundLaneData { last_confirmed_nonce: 1, relayers: Default::default() }, @@ -2004,7 +2014,7 @@ mod tests { // confirm delivery of all sent messages assert_ok!(Pallet::::receive_messages_delivery_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), TestMessagesDeliveryProof(Ok(( TEST_LANE_ID, InboundLaneData { diff --git a/modules/messages/src/mock.rs b/modules/messages/src/mock.rs index d37832eff..5bdaecece 100644 --- a/modules/messages/src/mock.rs +++ b/modules/messages/src/mock.rs @@ -129,7 +129,7 @@ frame_support::construct_runtime! { parameter_types! { pub const BlockHashCount: u64 = 250; - pub const MaximumBlockWeight: Weight = 1024; + pub const MaximumBlockWeight: Weight = Weight::from_ref_time(1024); pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 1, write: 2 }; @@ -142,9 +142,7 @@ impl frame_system::Config for TestRuntime { type BlockLength = (); type BlockNumber = u64; type BlockWeights = (); - type Call = Call; type DbWeight = DbWeight; - type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; type Header = SubstrateHeader; @@ -154,8 +152,10 @@ impl frame_system::Config for TestRuntime { type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); - type Origin = Origin; type PalletInfo = PalletInfo; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; type SS58Prefix = (); type SystemWeightInfo = (); type Version = (); @@ -168,11 +168,11 @@ impl pallet_balances::Config for TestRuntime { type AccountStore = frame_system::Pallet; type Balance = Balance; type DustRemoval = (); - type Event = Event; type ExistentialDeposit = ExistentialDeposit; type MaxLocks = (); type MaxReserves = (); type ReserveIdentifier = (); + type RuntimeEvent = RuntimeEvent; type WeightInfo = (); } @@ -198,7 +198,6 @@ parameter_types! { impl Config for TestRuntime { type AccountIdConverter = AccountIdConverter; type BridgedChainId = TestBridgedChainId; - type Event = Event; type InboundMessageFee = TestMessageFee; type InboundPayload = TestPayload; type InboundRelayer = TestRelayer; @@ -214,12 +213,13 @@ impl Config for TestRuntime { type OutboundMessageFee = TestMessageFee; type OutboundPayload = TestPayload; type Parameter = TestMessagesParameter; + type RuntimeEvent = RuntimeEvent; type SourceHeaderChain = TestSourceHeaderChain; type TargetHeaderChain = TestTargetHeaderChain; type WeightInfo = (); } -impl SenderOrigin for Origin { +impl SenderOrigin for RuntimeOrigin { fn linked_account(&self) -> Option { match self.caller { OriginCaller::system(frame_system::RawOrigin::Signed(ref submitter)) => @@ -296,13 +296,11 @@ impl TargetHeaderChain for TestTargetHeaderChain { /// Lane message verifier that is used in tests. #[derive(Debug, Default)] pub struct TestLaneMessageVerifier; -impl LaneMessageVerifier - for TestLaneMessageVerifier -{ +impl LaneMessageVerifier for TestLaneMessageVerifier { type Error = &'static str; fn verify_message( - _submitter: &Origin, + _submitter: &RuntimeOrigin, delivery_and_dispatch_fee: &TestMessageFee, _lane: &LaneId, _lane_outbound_data: &OutboundLaneData, @@ -327,7 +325,8 @@ impl TestMessageDeliveryAndDispatchPayment { /// Returns true if given fee has been paid by given submitter. pub fn is_fee_paid(submitter: AccountId, fee: TestMessageFee) -> bool { - let raw_origin: Result, _> = Origin::signed(submitter).into(); + let raw_origin: Result, _> = + RuntimeOrigin::signed(submitter).into(); frame_support::storage::unhashed::get(b":message-fee:") == Some((raw_origin.unwrap(), fee)) } @@ -338,13 +337,13 @@ impl TestMessageDeliveryAndDispatchPayment { frame_support::storage::unhashed::take::(&key).is_some() } } -impl MessageDeliveryAndDispatchPayment +impl MessageDeliveryAndDispatchPayment for TestMessageDeliveryAndDispatchPayment { type Error = &'static str; fn pay_delivery_and_dispatch_fee( - submitter: &Origin, + submitter: &RuntimeOrigin, fee: &TestMessageFee, _relayer_fund_account: &AccountId, ) -> Result<(), Self::Error> { @@ -491,7 +490,7 @@ impl OnDeliveryConfirmed for TestOnDeliveryConfirmed2 { fn on_messages_delivered(lane: &LaneId, messages: &DeliveredMessages) -> Weight { let key = (b"TestOnDeliveryConfirmed2", lane, messages).encode(); frame_support::storage::unhashed::put(&key, &true); - 0 + Weight::zero() } } @@ -519,7 +518,7 @@ impl MessageDispatch for TestMessageDispatch { fn dispatch_weight(message: &mut DispatchMessage) -> Weight { match message.data.payload.as_ref() { Ok(payload) => payload.declared_weight, - Err(_) => 0, + Err(_) => Weight::zero(), } } @@ -547,8 +546,13 @@ pub fn message(nonce: MessageNonce, payload: TestPayload) -> Message TestPayload { - TestPayload { id, declared_weight, dispatch_result: dispatch_result(0), extra: Vec::new() } +pub const fn message_payload(id: u64, declared_weight: u64) -> TestPayload { + TestPayload { + id, + declared_weight: Weight::from_ref_time(declared_weight), + dispatch_result: dispatch_result(0), + extra: Vec::new(), + } } /// Return message data with valid fee for given payload. @@ -557,10 +561,10 @@ pub fn message_data(payload: TestPayload) -> MessageData { } /// Returns message dispatch result with given unspent weight. -pub const fn dispatch_result(unspent_weight: Weight) -> MessageDispatchResult { +pub const fn dispatch_result(unspent_weight: u64) -> MessageDispatchResult { MessageDispatchResult { dispatch_result: true, - unspent_weight, + unspent_weight: Weight::from_ref_time(unspent_weight), dispatch_fee_paid_during_dispatch: true, } } diff --git a/modules/messages/src/weights.rs b/modules/messages/src/weights.rs index c6d4c22bc..a7c416ab0 100644 --- a/modules/messages/src/weights.rs +++ b/modules/messages/src/weights.rs @@ -64,164 +64,164 @@ pub trait WeightInfo { } /// Weights for `pallet_bridge_messages` using the Millau node and recommended hardware. -pub struct MillauWeight(PhantomData); -impl WeightInfo for MillauWeight { +pub struct BridgeWeight(PhantomData); +impl WeightInfo for BridgeWeight { fn send_minimal_message_worst_case() -> Weight { - (117_480_000 as Weight) - .saturating_add(T::DbWeight::get().reads(7 as Weight)) - .saturating_add(T::DbWeight::get().writes(12 as Weight)) + Weight::from_ref_time(117_480_000 as u64) + .saturating_add(T::DbWeight::get().reads(7 as u64)) + .saturating_add(T::DbWeight::get().writes(12 as u64)) } fn send_1_kb_message_worst_case() -> Weight { - (128_391_000 as Weight) - .saturating_add(T::DbWeight::get().reads(7 as Weight)) - .saturating_add(T::DbWeight::get().writes(12 as Weight)) + Weight::from_ref_time(128_391_000 as u64) + .saturating_add(T::DbWeight::get().reads(7 as u64)) + .saturating_add(T::DbWeight::get().writes(12 as u64)) } fn send_16_kb_message_worst_case() -> Weight { - (149_149_000 as Weight) - .saturating_add(T::DbWeight::get().reads(7 as Weight)) - .saturating_add(T::DbWeight::get().writes(12 as Weight)) + Weight::from_ref_time(149_149_000 as u64) + .saturating_add(T::DbWeight::get().reads(7 as u64)) + .saturating_add(T::DbWeight::get().writes(12 as u64)) } fn maximal_increase_message_fee() -> Weight { - (6_015_058_000 as Weight) - .saturating_add(T::DbWeight::get().reads(5 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(6_015_058_000 as u64) + .saturating_add(T::DbWeight::get().reads(5 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } fn receive_single_message_proof() -> Weight { - (179_892_000 as Weight) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(179_892_000 as u64) + .saturating_add(T::DbWeight::get().reads(6 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } fn receive_two_messages_proof() -> Weight { - (291_793_000 as Weight) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(291_793_000 as u64) + .saturating_add(T::DbWeight::get().reads(6 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } fn receive_single_message_proof_with_outbound_lane_state() -> Weight { - (192_191_000 as Weight) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(192_191_000 as u64) + .saturating_add(T::DbWeight::get().reads(6 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } fn receive_single_message_proof_1_kb() -> Weight { - (202_104_000 as Weight) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(202_104_000 as u64) + .saturating_add(T::DbWeight::get().reads(6 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } fn receive_single_message_proof_16_kb() -> Weight { - (357_144_000 as Weight) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(357_144_000 as u64) + .saturating_add(T::DbWeight::get().reads(6 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } fn receive_single_prepaid_message_proof() -> Weight { - (122_648_000 as Weight) - .saturating_add(T::DbWeight::get().reads(3 as Weight)) - .saturating_add(T::DbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(122_648_000 as u64) + .saturating_add(T::DbWeight::get().reads(3 as u64)) + .saturating_add(T::DbWeight::get().writes(1 as u64)) } fn receive_delivery_proof_for_single_message() -> Weight { - (107_631_000 as Weight) - .saturating_add(T::DbWeight::get().reads(6 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(107_631_000 as u64) + .saturating_add(T::DbWeight::get().reads(6 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { - (113_885_000 as Weight) - .saturating_add(T::DbWeight::get().reads(7 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(113_885_000 as u64) + .saturating_add(T::DbWeight::get().reads(7 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { - (155_151_000 as Weight) - .saturating_add(T::DbWeight::get().reads(8 as Weight)) - .saturating_add(T::DbWeight::get().writes(4 as Weight)) + Weight::from_ref_time(155_151_000 as u64) + .saturating_add(T::DbWeight::get().reads(8 as u64)) + .saturating_add(T::DbWeight::get().writes(4 as u64)) } } // For backwards compatibility and tests impl WeightInfo for () { fn send_minimal_message_worst_case() -> Weight { - (117_480_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(7 as Weight)) - .saturating_add(RocksDbWeight::get().writes(12 as Weight)) + Weight::from_ref_time(117_480_000 as u64) + .saturating_add(RocksDbWeight::get().reads(7 as u64)) + .saturating_add(RocksDbWeight::get().writes(12 as u64)) } fn send_1_kb_message_worst_case() -> Weight { - (128_391_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(7 as Weight)) - .saturating_add(RocksDbWeight::get().writes(12 as Weight)) + Weight::from_ref_time(128_391_000 as u64) + .saturating_add(RocksDbWeight::get().reads(7 as u64)) + .saturating_add(RocksDbWeight::get().writes(12 as u64)) } fn send_16_kb_message_worst_case() -> Weight { - (149_149_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(7 as Weight)) - .saturating_add(RocksDbWeight::get().writes(12 as Weight)) + Weight::from_ref_time(149_149_000 as u64) + .saturating_add(RocksDbWeight::get().reads(7 as u64)) + .saturating_add(RocksDbWeight::get().writes(12 as u64)) } fn maximal_increase_message_fee() -> Weight { - (6_015_058_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(5 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(6_015_058_000 as u64) + .saturating_add(RocksDbWeight::get().reads(5 as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) } fn receive_single_message_proof() -> Weight { - (179_892_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(179_892_000 as u64) + .saturating_add(RocksDbWeight::get().reads(6 as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) } fn receive_two_messages_proof() -> Weight { - (291_793_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(291_793_000 as u64) + .saturating_add(RocksDbWeight::get().reads(6 as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) } fn receive_single_message_proof_with_outbound_lane_state() -> Weight { - (192_191_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(192_191_000 as u64) + .saturating_add(RocksDbWeight::get().reads(6 as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) } fn receive_single_message_proof_1_kb() -> Weight { - (202_104_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(202_104_000 as u64) + .saturating_add(RocksDbWeight::get().reads(6 as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) } fn receive_single_message_proof_16_kb() -> Weight { - (357_144_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(357_144_000 as u64) + .saturating_add(RocksDbWeight::get().reads(6 as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) } fn receive_single_prepaid_message_proof() -> Weight { - (122_648_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(3 as Weight)) - .saturating_add(RocksDbWeight::get().writes(1 as Weight)) + Weight::from_ref_time(122_648_000 as u64) + .saturating_add(RocksDbWeight::get().reads(3 as u64)) + .saturating_add(RocksDbWeight::get().writes(1 as u64)) } fn receive_delivery_proof_for_single_message() -> Weight { - (107_631_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(6 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(107_631_000 as u64) + .saturating_add(RocksDbWeight::get().reads(6 as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) } fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { - (113_885_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(7 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(113_885_000 as u64) + .saturating_add(RocksDbWeight::get().reads(7 as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) } fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { - (155_151_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(8 as Weight)) - .saturating_add(RocksDbWeight::get().writes(4 as Weight)) + Weight::from_ref_time(155_151_000 as u64) + .saturating_add(RocksDbWeight::get().reads(8 as u64)) + .saturating_add(RocksDbWeight::get().writes(4 as u64)) } } diff --git a/modules/messages/src/weights_ext.rs b/modules/messages/src/weights_ext.rs index 037b94a08..9e9404460 100644 --- a/modules/messages/src/weights_ext.rs +++ b/modules/messages/src/weights_ext.rs @@ -44,14 +44,14 @@ pub fn ensure_weights_are_correct( db_weight: RuntimeDbWeight, ) { // verify `send_message` weight components - assert_ne!(W::send_message_overhead(), 0); - assert_ne!(W::send_message_size_overhead(0), 0); + assert_ne!(W::send_message_overhead(), Weight::zero()); + assert_ne!(W::send_message_size_overhead(0), Weight::zero()); // verify `receive_messages_proof` weight components - assert_ne!(W::receive_messages_proof_overhead(), 0); - assert_ne!(W::receive_messages_proof_messages_overhead(1), 0); - assert_ne!(W::receive_messages_proof_outbound_lane_state_overhead(), 0); - assert_ne!(W::storage_proof_size_overhead(1), 0); + assert_ne!(W::receive_messages_proof_overhead(), Weight::zero()); + assert_ne!(W::receive_messages_proof_messages_overhead(1), Weight::zero()); + assert_ne!(W::receive_messages_proof_outbound_lane_state_overhead(), Weight::zero()); + assert_ne!(W::storage_proof_size_overhead(1), Weight::zero()); // verify that the hardcoded value covers `receive_messages_proof` weight let actual_single_regular_message_delivery_tx_weight = W::receive_messages_proof_weight( @@ -59,11 +59,11 @@ pub fn ensure_weights_are_correct( (EXPECTED_DEFAULT_MESSAGE_LENGTH + W::expected_extra_storage_proof_size()) as usize, ), 1, - 0, + Weight::zero(), ); assert!( actual_single_regular_message_delivery_tx_weight - <= expected_default_message_delivery_tx_weight, + .all_lte(expected_default_message_delivery_tx_weight), "Default message delivery transaction weight {} is larger than expected weight {}", actual_single_regular_message_delivery_tx_weight, expected_default_message_delivery_tx_weight, @@ -72,15 +72,15 @@ pub fn ensure_weights_are_correct( // verify that hardcoded value covers additional byte length of `receive_messages_proof` weight let actual_additional_byte_delivery_weight = W::storage_proof_size_overhead(1); assert!( - actual_additional_byte_delivery_weight <= expected_additional_byte_delivery_weight, + actual_additional_byte_delivery_weight.all_lte(expected_additional_byte_delivery_weight), "Single additional byte delivery weight {} is larger than expected weight {}", actual_additional_byte_delivery_weight, expected_additional_byte_delivery_weight, ); // verify `receive_messages_delivery_proof` weight components - assert_ne!(W::receive_messages_delivery_proof_overhead(), 0); - assert_ne!(W::storage_proof_size_overhead(1), 0); + assert_ne!(W::receive_messages_delivery_proof_overhead(), Weight::zero()); + assert_ne!(W::storage_proof_size_overhead(1), Weight::zero()); // `receive_messages_delivery_proof_messages_overhead` and // `receive_messages_delivery_proof_relayers_overhead` may return zero if rewards are not paid @@ -98,7 +98,7 @@ pub fn ensure_weights_are_correct( ); assert!( actual_messages_delivery_confirmation_tx_weight - <= expected_messages_delivery_confirmation_tx_weight, + .all_lte(expected_messages_delivery_confirmation_tx_weight), "Messages delivery confirmation transaction weight {} is larger than expected weight {}", actual_messages_delivery_confirmation_tx_weight, expected_messages_delivery_confirmation_tx_weight, @@ -107,7 +107,7 @@ pub fn ensure_weights_are_correct( // verify pay-dispatch-fee overhead for inbound messages let actual_pay_inbound_dispatch_fee_weight = W::pay_inbound_dispatch_fee_overhead(); assert!( - actual_pay_inbound_dispatch_fee_weight <= expected_pay_inbound_dispatch_fee_weight, + actual_pay_inbound_dispatch_fee_weight.all_lte(expected_pay_inbound_dispatch_fee_weight), "Weight {} of pay-dispatch-fee overhead for inbound messages is larger than expected weight {}", actual_pay_inbound_dispatch_fee_weight, expected_pay_inbound_dispatch_fee_weight, @@ -141,7 +141,7 @@ pub fn ensure_able_to_receive_message( max_incoming_message_dispatch_weight, ); assert!( - max_delivery_transaction_dispatch_weight <= max_extrinsic_weight, + max_delivery_transaction_dispatch_weight.all_lte(max_extrinsic_weight), "Weight of maximal message delivery transaction + {} is larger than maximal possible transaction weight {}", max_delivery_transaction_dispatch_weight, max_extrinsic_weight, @@ -180,7 +180,7 @@ pub fn ensure_able_to_receive_confirmation( db_weight, ); assert!( - max_confirmation_transaction_dispatch_weight <= max_extrinsic_weight, + max_confirmation_transaction_dispatch_weight.all_lte(max_extrinsic_weight), "Weight of maximal confirmation transaction {} is larger than maximal possible transaction weight {}", max_confirmation_transaction_dispatch_weight, max_extrinsic_weight, @@ -263,9 +263,8 @@ pub trait WeightInfoExt: WeightInfo { // and cost of calling `OnDeliveryConfirmed::on_messages_delivered()` for every confirmed // message - let callback_overhead = relayers_state - .total_messages - .saturating_mul(Self::single_message_callback_overhead(db_weight)); + let callback_overhead = Self::single_message_callback_overhead(db_weight) + .saturating_mul(relayers_state.total_messages); transaction_overhead .saturating_add(messages_overhead) @@ -306,7 +305,7 @@ pub trait WeightInfoExt: WeightInfo { let weight_of_single_message_and_single_tx_overhead = Self::receive_single_message_proof(); weight_of_two_messages_and_single_tx_overhead .saturating_sub(weight_of_single_message_and_single_tx_overhead) - .saturating_mul(messages as Weight) + .saturating_mul(messages as _) } /// Returns weight that needs to be accounted when message delivery transaction @@ -337,7 +336,7 @@ pub trait WeightInfoExt: WeightInfo { let weight_of_single_message = Self::receive_delivery_proof_for_single_message(); weight_of_two_messages .saturating_sub(weight_of_single_message) - .saturating_mul(messages as Weight) + .saturating_mul(messages as _) } /// Returns weight that needs to be accounted when receiving confirmations for given a number of @@ -349,7 +348,7 @@ pub trait WeightInfoExt: WeightInfo { Self::receive_delivery_proof_for_two_messages_by_single_relayer(); weight_of_two_messages_by_two_relayers .saturating_sub(weight_of_two_messages_by_single_relayer) - .saturating_mul(relayers as Weight) + .saturating_mul(relayers as _) } /// Returns weight that needs to be accounted when storage proof of given size is received @@ -361,7 +360,7 @@ pub trait WeightInfoExt: WeightInfo { /// relayer must pay when it relays proof of given size (even if cost based on other parameters /// is less than that cost). fn storage_proof_size_overhead(proof_size: u32) -> Weight { - let proof_size_in_bytes = proof_size as Weight; + let proof_size_in_bytes = proof_size; let byte_weight = (Self::receive_single_message_proof_16_kb() - Self::receive_single_message_proof_1_kb()) / (15 * 1024); @@ -393,7 +392,7 @@ impl WeightInfoExt for () { } } -impl WeightInfoExt for crate::weights::MillauWeight { +impl WeightInfoExt for crate::weights::BridgeWeight { fn expected_extra_storage_proof_size() -> u32 { EXTRA_STORAGE_PROOF_SIZE } diff --git a/modules/parachains/Cargo.toml b/modules/parachains/Cargo.toml index f6cb519ca..9b231e049 100644 --- a/modules/parachains/Cargo.toml +++ b/modules/parachains/Cargo.toml @@ -16,20 +16,20 @@ bp-polkadot-core = { default-features = false, path = "../../primitives/pol bp-runtime = { default-features = false, path = "../../primitives/runtime" } pallet-bridge-grandpa = { default-features = false, path = "../grandpa" } # paritytech -frame-benchmarking = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-trie = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +frame-benchmarking = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-trie = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [dev-dependencies] # darwinia-network bp-header-chain = { path = "../../primitives/header-chain" } bp-test-utils = { path = "../../primitives/test-utils" } # paritytech -sp-io = { git = "https://github.com/paritytech/substrate", branch = "master" } +sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [features] default = ["std"] diff --git a/modules/parachains/src/extension.rs b/modules/parachains/src/extension.rs index 437459fdf..4f74d2e04 100644 --- a/modules/parachains/src/extension.rs +++ b/modules/parachains/src/extension.rs @@ -33,7 +33,7 @@ use sp_runtime::transaction_validity::{InvalidTransaction, TransactionValidity, /// pallet will be used in our environment. impl< Call: IsSubType, T>>, - T: frame_system::Config + Config, + T: frame_system::Config + Config, I: 'static, > FilterCall for Pallet where @@ -80,7 +80,7 @@ mod tests { // darwinia-network use crate::{ extension::FilterCall, - mock::{run_test, Call, TestRuntime}, + mock::{run_test, RuntimeCall, TestRuntime}, ParaInfo, ParasInfo, RelayBlockNumber, }; use bp_parachains::BestParaHeadHash; @@ -90,13 +90,14 @@ mod tests { num: RelayBlockNumber, parachains: Vec<(ParaId, ParaHash)>, ) -> bool { - crate::Pallet::::validate(&Call::Parachains( - crate::Call::::submit_parachain_heads { - at_relay_block: (num, Default::default()), - parachains, - parachain_heads_proof: ParaHeadsProof(Vec::new()), - }, - )) + crate::Pallet::::validate(&RuntimeCall::Parachains(crate::Call::< + TestRuntime, + (), + >::submit_parachain_heads { + at_relay_block: (num, Default::default()), + parachains, + parachain_heads_proof: ParaHeadsProof(Vec::new()), + })) .is_ok() } diff --git a/modules/parachains/src/lib.rs b/modules/parachains/src/lib.rs index ac5d2b329..03fe6241a 100644 --- a/modules/parachains/src/lib.rs +++ b/modules/parachains/src/lib.rs @@ -42,7 +42,7 @@ use bp_parachains::{parachain_head_storage_key_at_source, ParaInfo}; use bp_polkadot_core::parachains::{ParaHash, ParaHasher, ParaHead, ParaHeadsProof, ParaId}; use bp_runtime::StorageProofError; // paritytech -use frame_support::{traits::Contains, weights::PostDispatchInfo}; +use frame_support::{dispatch::PostDispatchInfo, traits::Contains}; use sp_runtime::traits::Header as HeaderT; use sp_std::prelude::*; @@ -69,11 +69,15 @@ pub mod pallet { use super::*; use bp_parachains::{BestParaHeadHash, ImportedParaHeadsKeyProvider, ParasInfoKeyProvider}; use bp_runtime::{ - BasicOperatingMode, OwnedBridgeModule, StorageDoubleMapKeyProvider, StorageMapKeyProvider, + BasicOperatingMode, BoundedStorageValue, OwnedBridgeModule, StorageDoubleMapKeyProvider, + StorageMapKeyProvider, }; use frame_support::{log, pallet_prelude::*}; use frame_system::pallet_prelude::*; + /// Stored parachain head of given parachains pallet. + pub type StoredParaHeadOf = + BoundedStorageValue<>::MaxParaHeadSize, ParaHead>; /// Weight info of the given parachains pallet. pub type WeightInfoOf = >::WeightInfo; @@ -94,6 +98,12 @@ pub mod pallet { }, /// The caller has provided obsolete parachain head, which is already known to the pallet. RejectedObsoleteParachainHead { parachain: ParaId, parachain_head_hash: ParaHash }, + /// The caller has provided parachain head that exceeds the maximal configured head size. + RejectedLargeParachainHead { + parachain: ParaId, + parachain_head_hash: ParaHash, + parachain_head_size: u32, + }, /// Parachain head has been updated. UpdatedParachainHead { parachain: ParaId, parachain_head_hash: ParaHash }, } @@ -122,7 +132,8 @@ pub mod pallet { pallet_bridge_grandpa::Config { /// The overarching event type. - type Event: From> + IsType<::Event>; + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; /// Benchmarks results from runtime we're plugged into. type WeightInfo: WeightInfoExt; @@ -156,6 +167,17 @@ pub mod pallet { /// Incautious change of this constant may lead to orphan entries in the runtime storage. #[pallet::constant] type HeadsToKeep: Get; + + /// Maximal size (in bytes) of the SCALE-encoded parachain head. + /// + /// Keep in mind that the size of any tracked parachain header must not exceed this value. + /// So if you're going to track multiple parachains, one of which is storing large digests + /// in its headers, you shall choose this maximal value. + /// + /// There's no mandatory headers in this pallet, so it can't stall if there's some header + /// that exceeds this bound. + #[pallet::constant] + type MaxParaHeadSize: Get; } /// Optional pallet owner. @@ -196,7 +218,7 @@ pub mod pallet { ::Key1, ::Hasher2, ::Key2, - ::Value, + StoredParaHeadOf, >; /// A ring buffer of imported parachain head hashes. Ordered by the insertion time. @@ -206,7 +228,6 @@ pub mod pallet { #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] pub struct Pallet(PhantomData<(T, I)>); impl, I: 'static> OwnedBridgeModule for Pallet { @@ -382,12 +403,12 @@ pub mod pallet { /// Get best finalized header of the given parachain. pub fn best_parachain_head(parachain: ParaId) -> Option { let best_para_head_hash = ParasInfo::::get(parachain)?.best_head_hash.head_hash; - ImportedParaHeads::::get(parachain, best_para_head_hash) + ImportedParaHeads::::get(parachain, best_para_head_hash).map(|h| h.into_inner()) } /// Get parachain head with given hash. pub fn parachain_head(parachain: ParaId, hash: ParaHash) -> Option { - ImportedParaHeads::::get(parachain, hash) + ImportedParaHeads::::get(parachain, hash).map(|h| h.into_inner()) } /// Verify that the passed storage proof is valid, given it is crafted using @@ -479,12 +500,13 @@ pub mod pallet { ) -> Result { // check if head has been already updated at better relay chain block. Without this // check, we may import heads in random order + let err_log_prefix = "The parachain head can't be updated"; let is_valid = Self::validate_updated_parachain_head( parachain, &stored_best_head, updated_at_relay_block_number, updated_head_hash, - "The parachain head can't be updated", + err_log_prefix, ); if !is_valid { Self::deposit_event(Event::RejectedObsoleteParachainHead { @@ -493,6 +515,30 @@ pub mod pallet { }); return Err(()); } + + // verify that the parachain head size is <= `MaxParaHeadSize` + let updated_head = match StoredParaHeadOf::::try_from_inner(updated_head) { + Ok(updated_head) => updated_head, + Err(e) => { + log::trace!( + target: LOG_TARGET, + "{}. The parachain head size for {:?} is {}. It exceeds maximal configured size {}.", + err_log_prefix, + parachain, + e.value_size, + e.maximal_size, + ); + + Self::deposit_event(Event::RejectedLargeParachainHead { + parachain, + parachain_head_hash: updated_head_hash, + parachain_head_size: e.value_size as _, + }); + + return Err(()); + }, + }; + let next_imported_hash_position = stored_best_head .map_or(0, |stored_best_head| stored_best_head.next_imported_hash_position); @@ -580,8 +626,8 @@ mod tests { // darwinia-network use super::*; use crate::mock::{ - run_test, test_relay_header, Event as TestEvent, Origin, TestRuntime, PARAS_PALLET_NAME, - UNTRACKED_PARACHAIN_ID, + run_test, test_relay_header, RuntimeEvent as TestEvent, RuntimeOrigin, TestRuntime, + MAXIMAL_PARACHAIN_HEAD_SIZE, PARAS_PALLET_NAME, UNTRACKED_PARACHAIN_ID, }; use bp_parachains::{BestParaHeadHash, ImportedParaHeadsKeyProvider, ParasInfoKeyProvider}; use bp_runtime::{ @@ -609,7 +655,7 @@ mod tests { fn initialize(state_root: RelayBlockHash) { pallet_bridge_grandpa::Pallet::::initialize( - Origin::root(), + RuntimeOrigin::root(), bp_header_chain::InitializationData { header: Box::new(test_relay_header(0, state_root)), authority_list: authority_list(), @@ -629,7 +675,7 @@ mod tests { let justification = make_default_justification(&header); assert_ok!( pallet_bridge_grandpa::Pallet::::submit_finality_proof( - Origin::signed(1), + RuntimeOrigin::signed(1), Box::new(header), justification, ) @@ -678,6 +724,12 @@ mod tests { ParaHead((parachain, head_number).encode()) } + fn large_head_data(parachain: u32, head_number: u32) -> ParaHead { + ParaHead( + (parachain, head_number, vec![42u8; MAXIMAL_PARACHAIN_HEAD_SIZE as usize]).encode(), + ) + } + fn head_hash(parachain: u32, head_number: u32) -> ParaHash { head_data(parachain, head_number).hash() } @@ -689,7 +741,7 @@ mod tests { proof: ParaHeadsProof, ) -> DispatchResultWithPostInfo { Pallet::::submit_parachain_heads( - Origin::signed(1), + RuntimeOrigin::signed(1), (relay_chain_block, test_relay_header(relay_chain_block, relay_state_root).hash()), parachains, proof, @@ -700,7 +752,7 @@ mod tests { let db_weight = ::DbWeight::get(); WeightInfoOf::::submit_parachain_heads_weight(db_weight, proof, 1) .saturating_sub(if prune_expected { - 0 + Weight::zero() } else { WeightInfoOf::::parachain_head_pruning_weight(db_weight) }) @@ -718,7 +770,7 @@ mod tests { PalletOperatingMode::::put(BasicOperatingMode::Halted); assert_noop!( Pallet::::submit_parachain_heads( - Origin::signed(1), + RuntimeOrigin::signed(1), (0, test_relay_header(0, state_root).hash()), parachains.clone(), proof.clone(), @@ -729,7 +781,7 @@ mod tests { // `submit_parachain_heads()` should succeed now that the pallet is resumed. PalletOperatingMode::::put(BasicOperatingMode::Normal); assert_ok!(Pallet::::submit_parachain_heads( - Origin::signed(1), + RuntimeOrigin::signed(1), (0, test_relay_header(0, state_root).hash()), parachains, proof, @@ -748,7 +800,7 @@ mod tests { let expected_weight = WeightInfo::submit_parachain_heads_weight(DbWeight::get(), &proof, 2); let result = Pallet::::submit_parachain_heads( - Origin::signed(1), + RuntimeOrigin::signed(1), (0, test_relay_header(0, state_root).hash()), parachains, proof, @@ -774,18 +826,21 @@ mod tests { ImportedParaHeads::::get( ParaId(1), initial_best_head(1).best_head_hash.head_hash - ), + ) + .map(|h| h.into_inner()), Some(head_data(1, 0)) ); assert_eq!( ImportedParaHeads::::get( ParaId(2), initial_best_head(2).best_head_hash.head_hash - ), + ) + .map(|h| h.into_inner()), None ); assert_eq!( - ImportedParaHeads::::get(ParaId(3), head_hash(3, 10)), + ImportedParaHeads::::get(ParaId(3), head_hash(3, 10)) + .map(|h| h.into_inner()), Some(head_data(3, 10)) ); @@ -834,11 +889,13 @@ mod tests { }) ); assert_eq!( - ImportedParaHeads::::get(ParaId(1), head_data(1, 5).hash()), + ImportedParaHeads::::get(ParaId(1), head_data(1, 5).hash()) + .map(|h| h.into_inner()), Some(head_data(1, 5)) ); assert_eq!( - ImportedParaHeads::::get(ParaId(1), head_data(1, 10).hash()), + ImportedParaHeads::::get(ParaId(1), head_data(1, 10).hash()) + .map(|h| h.into_inner()), None ); assert_eq!( @@ -867,11 +924,13 @@ mod tests { }) ); assert_eq!( - ImportedParaHeads::::get(ParaId(1), head_data(1, 5).hash()), + ImportedParaHeads::::get(ParaId(1), head_data(1, 5).hash()) + .map(|h| h.into_inner()), Some(head_data(1, 5)) ); assert_eq!( - ImportedParaHeads::::get(ParaId(1), head_data(1, 10).hash()), + ImportedParaHeads::::get(ParaId(1), head_data(1, 10).hash()) + .map(|h| h.into_inner()), Some(head_data(1, 10)) ); assert_eq!( @@ -915,7 +974,7 @@ mod tests { )); initialize(state_root); let result = Pallet::::submit_parachain_heads( - Origin::signed(1), + RuntimeOrigin::signed(1), (0, test_relay_header(0, state_root).hash()), parachains, proof, @@ -1096,6 +1155,57 @@ mod tests { }); } + #[test] + fn does_nothing_when_parachain_head_is_too_large() { + let (state_root, proof, parachains) = + prepare_parachain_heads_proof(vec![(1, head_data(1, 5)), (2, large_head_data(1, 5))]); + run_test(|| { + // start with relay block #0 and try to import head#5 of parachain#1 and untracked + // parachain + initialize(state_root); + let result = Pallet::::submit_parachain_heads( + RuntimeOrigin::signed(1), + (0, test_relay_header(0, state_root).hash()), + parachains, + proof, + ); + assert_ok!(result); + assert_eq!( + ParasInfo::::get(ParaId(1)), + Some(ParaInfo { + best_head_hash: BestParaHeadHash { + at_relay_block_number: 0, + head_hash: head_data(1, 5).hash() + }, + next_imported_hash_position: 1, + }) + ); + assert_eq!(ParasInfo::::get(ParaId(2)), None); + assert_eq!( + System::::events(), + vec![ + EventRecord { + phase: Phase::Initialization, + event: TestEvent::Parachains(Event::UpdatedParachainHead { + parachain: ParaId(1), + parachain_head_hash: head_data(1, 5).hash(), + }), + topics: vec![], + }, + EventRecord { + phase: Phase::Initialization, + event: TestEvent::Parachains(Event::RejectedLargeParachainHead { + parachain: ParaId(2), + parachain_head_hash: large_head_data(1, 5).hash(), + parachain_head_size: large_head_data(1, 5).encoded_size() as u32, + }), + topics: vec![], + }, + ], + ); + }); + } + #[test] fn prunes_old_heads() { run_test(|| { @@ -1198,7 +1308,7 @@ mod tests { // => we'll leave previous value proceed(20, state_root_10_at_20); assert_ok!(Pallet::::submit_parachain_heads( - Origin::signed(1), + RuntimeOrigin::signed(1), (20, test_relay_header(20, state_root_10_at_20).hash()), parachains_10_at_20, proof_10_at_20, @@ -1214,7 +1324,7 @@ mod tests { // => we'll update value proceed(30, state_root_10_at_30); assert_ok!(Pallet::::submit_parachain_heads( - Origin::signed(1), + RuntimeOrigin::signed(1), (30, test_relay_header(30, state_root_10_at_30).hash()), parachains_10_at_30, proof_10_at_30, @@ -1255,7 +1365,7 @@ mod tests { run_test(|| { initialize(state_root); assert_ok!(Pallet::::submit_parachain_heads( - Origin::signed(1), + RuntimeOrigin::signed(1), (0, test_relay_header(0, state_root).hash()), parachains, proof, @@ -1280,7 +1390,7 @@ mod tests { run_test(|| { initialize(state_root); assert_ok!(Pallet::::submit_parachain_heads( - Origin::signed(1), + RuntimeOrigin::signed(1), (0, test_relay_header(0, state_root).hash()), parachains, proof, diff --git a/modules/parachains/src/mock.rs b/modules/parachains/src/mock.rs index 847124b9b..18537b7b4 100644 --- a/modules/parachains/src/mock.rs +++ b/modules/parachains/src/mock.rs @@ -39,6 +39,7 @@ type UncheckedExtrinsic = MockUncheckedExtrinsic; pub const PARAS_PALLET_NAME: &str = "Paras"; pub const UNTRACKED_PARACHAIN_ID: u32 = 10; +pub const MAXIMAL_PARACHAIN_HEAD_SIZE: u32 = 512; frame_support::construct_runtime! { pub enum TestRuntime where @@ -55,7 +56,7 @@ frame_support::construct_runtime! { frame_support::parameter_types! { pub const BlockHashCount: TestNumber = 250; - pub const MaximumBlockWeight: Weight = 1024; + pub const MaximumBlockWeight: Weight = Weight::from_ref_time(1024); pub const MaximumBlockLength: u32 = 2 * 1024; pub const AvailableBlockRatio: Perbill = Perbill::one(); } @@ -67,9 +68,7 @@ impl frame_system::Config for TestRuntime { type BlockLength = (); type BlockNumber = TestNumber; type BlockWeights = (); - type Call = Call; type DbWeight = (); - type Event = Event; type Hash = H256; type Hashing = BlakeTwo256; type Header = Header; @@ -79,8 +78,10 @@ impl frame_system::Config for TestRuntime { type OnKilledAccount = (); type OnNewAccount = (); type OnSetCode = (); - type Origin = Origin; type PalletInfo = PalletInfo; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; type SS58Prefix = (); type SystemWeightInfo = (); type Version = (); @@ -95,6 +96,8 @@ frame_support::parameter_types! { impl pallet_bridge_grandpa::Config for TestRuntime { type BridgedChain = TestBridgedChain; type HeadersToKeep = HeadersToKeep; + type MaxBridgedAuthorities = frame_support::traits::ConstU32<5>; + type MaxBridgedHeaderSize = frame_support::traits::ConstU32<512>; type MaxRequests = MaxRequests; type WeightInfo = (); } @@ -102,6 +105,8 @@ impl pallet_bridge_grandpa::Config for TestRun impl pallet_bridge_grandpa::Config for TestRuntime { type BridgedChain = TestBridgedChain; type HeadersToKeep = HeadersToKeep; + type MaxBridgedAuthorities = frame_support::traits::ConstU32<5>; + type MaxBridgedHeaderSize = frame_support::traits::ConstU32<512>; type MaxRequests = MaxRequests; type WeightInfo = (); } @@ -113,9 +118,10 @@ frame_support::parameter_types! { } impl pallet_bridge_parachains::Config for TestRuntime { type BridgesGrandpaPalletInstance = pallet_bridge_grandpa::Instance1; - type Event = Event; type HeadsToKeep = HeadsToKeep; + type MaxParaHeadSize = frame_support::traits::ConstU32; type ParasPalletName = ParasPalletName; + type RuntimeEvent = RuntimeEvent; type TrackedParachains = IsInVec; type WeightInfo = (); } diff --git a/modules/parachains/src/weights.rs b/modules/parachains/src/weights.rs index c16d6aebd..c5bc0a353 100644 --- a/modules/parachains/src/weights.rs +++ b/modules/parachains/src/weights.rs @@ -56,48 +56,48 @@ pub trait WeightInfo { } /// Weights for `pallet_bridge_parachains` using the Millau node and recommended hardware. -pub struct MillauWeight(PhantomData); -impl WeightInfo for MillauWeight { +pub struct BridgeWeight(PhantomData); +impl WeightInfo for BridgeWeight { fn submit_parachain_heads_with_n_parachains(p: u32) -> Weight { - (0 as Weight) - .saturating_add((18_706_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(T::DbWeight::get().reads(2 as Weight)) - .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(p as Weight))) - .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(p as Weight))) + Weight::from_ref_time(0 as u64) + .saturating_add(Weight::from_ref_time(18_706_000 as u64).saturating_mul(p as u64)) + .saturating_add(T::DbWeight::get().reads(2 as u64)) + .saturating_add(T::DbWeight::get().reads(2 as u64).saturating_mul(p as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64).saturating_mul(p as u64)) } fn submit_parachain_heads_with_1kb_proof() -> Weight { - (27_549_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(27_549_000 as u64) + .saturating_add(T::DbWeight::get().reads(4 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } fn submit_parachain_heads_with_16kb_proof() -> Weight { - (80_792_000 as Weight) - .saturating_add(T::DbWeight::get().reads(4 as Weight)) - .saturating_add(T::DbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(80_792_000 as u64) + .saturating_add(T::DbWeight::get().reads(4 as u64)) + .saturating_add(T::DbWeight::get().writes(3 as u64)) } } // For backwards compatibility and tests impl WeightInfo for () { fn submit_parachain_heads_with_n_parachains(p: u32) -> Weight { - (0 as Weight) - .saturating_add((18_706_000 as Weight).saturating_mul(p as Weight)) - .saturating_add(RocksDbWeight::get().reads(2 as Weight)) - .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(p as Weight))) - .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(p as Weight))) + Weight::from_ref_time(0 as u64) + .saturating_add(Weight::from_ref_time(18_706_000 as u64).saturating_mul(p as u64)) + .saturating_add(RocksDbWeight::get().reads(2 as u64)) + .saturating_add(RocksDbWeight::get().reads(2 as u64).saturating_mul(p as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64).saturating_mul(p as u64)) } fn submit_parachain_heads_with_1kb_proof() -> Weight { - (27_549_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(27_549_000 as u64) + .saturating_add(RocksDbWeight::get().reads(4 as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) } fn submit_parachain_heads_with_16kb_proof() -> Weight { - (80_792_000 as Weight) - .saturating_add(RocksDbWeight::get().reads(4 as Weight)) - .saturating_add(RocksDbWeight::get().writes(3 as Weight)) + Weight::from_ref_time(80_792_000 as u64) + .saturating_add(RocksDbWeight::get().reads(4 as u64)) + .saturating_add(RocksDbWeight::get().writes(3 as u64)) } } diff --git a/modules/parachains/src/weights_ext.rs b/modules/parachains/src/weights_ext.rs index 79745d486..41d7b16a0 100644 --- a/modules/parachains/src/weights_ext.rs +++ b/modules/parachains/src/weights_ext.rs @@ -17,7 +17,7 @@ //! Weight-related utilities. // darwinia-network -use crate::weights::{MillauWeight, WeightInfo}; +use crate::weights::{BridgeWeight, WeightInfo}; use bp_runtime::Size; // paritytech use frame_support::weights::{RuntimeDbWeight, Weight}; @@ -63,8 +63,8 @@ pub trait WeightInfoExt: WeightInfo { ); // potential pruning weight (refunded if hasn't happened) - let pruning_weight = (parachains_count as Weight) - .saturating_mul(Self::parachain_head_pruning_weight(db_weight)); + let pruning_weight = + Self::parachain_head_pruning_weight(db_weight).saturating_mul(parachains_count as u64); base_weight.saturating_add(proof_size_overhead).saturating_add(pruning_weight) } @@ -88,11 +88,10 @@ pub trait WeightInfoExt: WeightInfo { /// Returns weight that needs to be accounted when storage proof of given size is received. fn storage_proof_size_overhead(extra_proof_bytes: u32) -> Weight { - let extra_proof_bytes_in_bytes = extra_proof_bytes as Weight; let extra_byte_weight = (Self::submit_parachain_heads_with_16kb_proof() - Self::submit_parachain_heads_with_1kb_proof()) / (15 * 1024); - extra_proof_bytes_in_bytes.saturating_mul(extra_byte_weight) + extra_byte_weight.saturating_mul(extra_proof_bytes as u64) } } @@ -102,7 +101,7 @@ impl WeightInfoExt for () { } } -impl WeightInfoExt for MillauWeight { +impl WeightInfoExt for BridgeWeight { fn expected_extra_storage_proof_size() -> u32 { EXTRA_STORAGE_PROOF_SIZE } diff --git a/primitives/darwinia-core/Cargo.toml b/primitives/darwinia-core/Cargo.toml index ad22ee7bc..3085b94ec 100644 --- a/primitives/darwinia-core/Cargo.toml +++ b/primitives/darwinia-core/Cargo.toml @@ -13,11 +13,11 @@ scale-info = { version = "2.0.1", default-features = false, features = [ # paritytech bp-messages = { default-features = false, path = "../messages" } bp-runtime = { default-features = false, path = "../runtime" } -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [features] default = ["std"] diff --git a/primitives/darwinia-core/src/lib.rs b/primitives/darwinia-core/src/lib.rs index 56555849a..1c2fcd34e 100644 --- a/primitives/darwinia-core/src/lib.rs +++ b/primitives/darwinia-core/src/lib.rs @@ -20,9 +20,12 @@ mod copy_paste_from_darwinia { // paritytech - use frame_support::weights::{ - constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_SECOND}, - DispatchClass, Weight, + use frame_support::{ + dispatch::DispatchClass, + weights::{ + constants::{BlockExecutionWeight, ExtrinsicBaseWeight, WEIGHT_PER_SECOND}, + Weight, + }, }; use frame_system::limits::{BlockLength, BlockWeights}; use sp_core::H256; @@ -46,7 +49,8 @@ mod copy_paste_from_darwinia { pub const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_perthousand(25); pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); - pub const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND; + // TODO: https://github.com/paritytech/parity-bridges-common/issues/1543 - remove `set_proof_size` + pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND.saturating_mul(2); frame_support::parameter_types! { pub RuntimeBlockLength: BlockLength = @@ -97,8 +101,9 @@ use bp_messages::MessageNonce; use bp_runtime::{Chain, EncodedOrDecodedCall, TransactionEraOf}; // paritytech use frame_support::{ + dispatch::DispatchClass, unsigned::{TransactionValidityError, UnknownTransaction}, - weights::{DispatchClass, Weight}, + weights::Weight, }; use sp_core::H256; use sp_runtime::{ diff --git a/primitives/header-chain/Cargo.toml b/primitives/header-chain/Cargo.toml index 67f80b863..4756fe207 100644 --- a/primitives/header-chain/Cargo.toml +++ b/primitives/header-chain/Cargo.toml @@ -15,11 +15,11 @@ serde = { version = "1.0", optional = true } # darwinia-network bp-runtime = { default-features = false, path = "../runtime" } # paritytech -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-finality-grandpa = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-finality-grandpa = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [dev-dependencies] # crates.io diff --git a/primitives/header-chain/src/lib.rs b/primitives/header-chain/src/lib.rs index bcf3d5d61..bad61d38f 100644 --- a/primitives/header-chain/src/lib.rs +++ b/primitives/header-chain/src/lib.rs @@ -42,46 +42,6 @@ use sp_std::boxed::Box; pub trait Parameter: Codec + EncodeLike + Clone + Eq + Debug + TypeInfo {} impl Parameter for T where T: Codec + EncodeLike + Clone + Eq + Debug + TypeInfo {} -/// base trait for verifying transaction inclusion proofs. -pub trait InclusionProofVerifier { - /// Transaction type. - type Transaction: Parameter; - /// Transaction inclusion proof type. - type TransactionInclusionProof: Parameter; - - /// Verify that transaction is a part of given block. - /// - /// Returns Some(transaction) if proof is valid and None otherwise. - fn verify_transaction_inclusion_proof( - proof: &Self::TransactionInclusionProof, - ) -> Option; -} - -/// A trait for pallets which want to keep track of finalized headers from a bridged chain. -pub trait HeaderChain { - /// Get the best finalized header known to the header chain. - fn best_finalized() -> Option; - - /// Get the best authority set known to the header chain. - fn authority_set() -> AuthoritySet; - - /// Write a header finalized by GRANDPA to the underlying pallet storage. - fn append_header(header: H) -> Result<(), E>; -} -impl HeaderChain for () { - fn best_finalized() -> Option { - None - } - - fn authority_set() -> AuthoritySet { - AuthoritySet::default() - } - - fn append_header(_header: H) -> Result<(), E> { - Ok(()) - } -} - /// Abstract finality proof that is justifying block finality. pub trait FinalityProof: Clone + Send + Sync + Debug { /// Return number of header that this proof is generated for. diff --git a/primitives/message-dispatch/Cargo.toml b/primitives/message-dispatch/Cargo.toml index 8b4cba7b1..ff7218b32 100644 --- a/primitives/message-dispatch/Cargo.toml +++ b/primitives/message-dispatch/Cargo.toml @@ -13,9 +13,9 @@ scale-info = { version = "2.1", default-features = false, features = ["derive"] # darwinia-network bp-runtime = { default-features = false, path = "../runtime" } # paritytech -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [features] default = ["std"] diff --git a/primitives/message-dispatch/src/lib.rs b/primitives/message-dispatch/src/lib.rs index ab69f2370..312e8aeb9 100644 --- a/primitives/message-dispatch/src/lib.rs +++ b/primitives/message-dispatch/src/lib.rs @@ -33,7 +33,7 @@ use sp_runtime::transaction_validity::TransactionValidityError; use sp_std::prelude::*; /// Message dispatch weight. -pub type Weight = u64; +pub type Weight = frame_support::weights::Weight; /// Spec version type. pub type SpecVersion = u32; diff --git a/primitives/messages/Cargo.toml b/primitives/messages/Cargo.toml index aca53c2a8..04847fc65 100644 --- a/primitives/messages/Cargo.toml +++ b/primitives/messages/Cargo.toml @@ -16,10 +16,10 @@ serde = { version = "1.0", optional = true, features = ["derive" # darwinia-network bp-runtime = { default-features = false, path = "../runtime" } # paritytech -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [dev-dependencies] array-bytes = { version = "4.1" } diff --git a/primitives/messages/src/lib.rs b/primitives/messages/src/lib.rs index d3c266354..3d9cc724f 100644 --- a/primitives/messages/src/lib.rs +++ b/primitives/messages/src/lib.rs @@ -378,7 +378,7 @@ mod tests { .len(); let difference = (expected_size.unwrap() as f64 - actual_size as f64).abs(); assert!( - difference / (std::cmp::min(actual_size, expected_size.unwrap() as usize) as f64) < 0.1, + difference / (std::cmp::min(actual_size, expected_size.unwrap()) as f64) < 0.1, "Too large difference between actual ({}) and expected ({:?}) inbound lane data size. Test case: {}+{}", actual_size, expected_size, diff --git a/primitives/messages/src/source_chain.rs b/primitives/messages/src/source_chain.rs index d2d3e67f0..88b1ef257 100644 --- a/primitives/messages/src/source_chain.rs +++ b/primitives/messages/src/source_chain.rs @@ -86,7 +86,7 @@ pub trait TargetHeaderChain { /// Lane3 until some block, ...), then it may be built using this verifier. /// /// Any fee requirements should also be enforced here. -pub trait LaneMessageVerifier { +pub trait LaneMessageVerifier { /// Error type. type Error: Debug + Into<&'static str>; @@ -180,7 +180,7 @@ pub trait OnDeliveryConfirmed { #[impl_trait_for_tuples::impl_for_tuples(30)] impl OnDeliveryConfirmed for Tuple { fn on_messages_delivered(lane: &LaneId, messages: &DeliveredMessages) -> Weight { - let mut total_weight: Weight = 0; + let mut total_weight = Weight::zero(); for_tuples!( #( total_weight = total_weight.saturating_add(Tuple::on_messages_delivered(lane, messages)); @@ -197,7 +197,7 @@ pub trait OnMessageAccepted { } impl OnMessageAccepted for () { fn on_messages_accepted(_lane: &LaneId, _message: &MessageNonce) -> Weight { - 0 + Weight::zero() } } @@ -211,7 +211,7 @@ pub struct SendMessageArtifacts { } /// Messages bridge API to be used from other pallets. -pub trait MessagesBridge { +pub trait MessagesBridge { /// Error type. type Error: Debug; @@ -230,8 +230,8 @@ pub trait MessagesBridge { #[derive(Eq, PartialEq, RuntimeDebug)] pub struct NoopMessagesBridge; -impl - MessagesBridge for NoopMessagesBridge +impl MessagesBridge + for NoopMessagesBridge { type Error = &'static str; @@ -241,7 +241,7 @@ impl _message: Payload, _delivery_and_dispatch_fee: Balance, ) -> Result { - Ok(SendMessageArtifacts { nonce: 0, weight: 0 }) + Ok(SendMessageArtifacts { nonce: 0, weight: Weight::zero() }) } } @@ -262,8 +262,8 @@ impl TargetHeaderChain for ForbidOutboun Err(ALL_OUTBOUND_MESSAGES_REJECTED) } } -impl - LaneMessageVerifier for ForbidOutboundMessages +impl LaneMessageVerifier + for ForbidOutboundMessages { type Error = &'static str; diff --git a/primitives/messages/src/target_chain.rs b/primitives/messages/src/target_chain.rs index 5ab386792..f37c282cc 100644 --- a/primitives/messages/src/target_chain.rs +++ b/primitives/messages/src/target_chain.rs @@ -178,7 +178,7 @@ impl MessageDispatch for ForbidInboundMessages { ) -> MessageDispatchResult { MessageDispatchResult { dispatch_result: false, - unspent_weight: 0, + unspent_weight: Weight::zero(), dispatch_fee_paid_during_dispatch: false, } } diff --git a/primitives/parachains/Cargo.toml b/primitives/parachains/Cargo.toml index 290f5ce29..1fdc2990c 100644 --- a/primitives/parachains/Cargo.toml +++ b/primitives/parachains/Cargo.toml @@ -14,8 +14,8 @@ scale-info = { version = "2.1", default-features = false, features = ["derive"] bp-polkadot-core = { default-features = false, path = "../polkadot-core" } bp-runtime = { default-features = false, path = "../runtime" } # paritytech -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [features] default = ["std"] diff --git a/primitives/parachains/src/lib.rs b/primitives/parachains/src/lib.rs index 7e9e62a91..f0fad710f 100644 --- a/primitives/parachains/src/lib.rs +++ b/primitives/parachains/src/lib.rs @@ -19,7 +19,7 @@ #![cfg_attr(not(feature = "std"), no_std)] // crates.io -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; // darwinia-network use bp_polkadot_core::{ @@ -32,7 +32,7 @@ use frame_support::{Blake2_128Concat, RuntimeDebug, Twox64Concat}; use sp_core::storage::StorageKey; /// Best known parachain head hash. -#[derive(Clone, PartialEq, Decode, Encode, RuntimeDebug, TypeInfo)] +#[derive(Clone, PartialEq, Decode, Encode, MaxEncodedLen, RuntimeDebug, TypeInfo)] pub struct BestParaHeadHash { /// Number of relay block where this head has been read. /// @@ -48,7 +48,7 @@ pub struct BestParaHeadHash { } /// Best known parachain head as it is stored in the runtime storage. -#[derive(PartialEq, Decode, Encode, RuntimeDebug, TypeInfo)] +#[derive(PartialEq, Decode, Encode, MaxEncodedLen, RuntimeDebug, TypeInfo)] pub struct ParaInfo { /// Best known parachain head hash. pub best_head_hash: BestParaHeadHash, diff --git a/primitives/polkadot-core/Cargo.toml b/primitives/polkadot-core/Cargo.toml index 5e7a4108d..236312c69 100644 --- a/primitives/polkadot-core/Cargo.toml +++ b/primitives/polkadot-core/Cargo.toml @@ -16,13 +16,13 @@ serde = { version = "1.0", optional = true, features = ["derive"] } bp-messages = { default-features = false, path = "../messages" } bp-runtime = { default-features = false, path = "../runtime" } # paritytech -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-api = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-version = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-api = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-version = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [features] default = ["std"] diff --git a/primitives/polkadot-core/src/lib.rs b/primitives/polkadot-core/src/lib.rs index 04297430e..ed8e4a642 100644 --- a/primitives/polkadot-core/src/lib.rs +++ b/primitives/polkadot-core/src/lib.rs @@ -43,11 +43,11 @@ use bp_messages::MessageNonce; use bp_runtime::{Chain, EncodedOrDecodedCall}; // paritytech use frame_support::{ - dispatch::Dispatchable, + dispatch::{DispatchClass, Dispatchable}, parameter_types, weights::{ constants::{BlockExecutionWeight, WEIGHT_PER_SECOND}, - DispatchClass, Weight, + Weight, }, RuntimeDebug, }; @@ -129,7 +129,8 @@ const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); /// All Polkadot-like chains allow 2 seconds of compute with a 6-second average block time. /// /// This is a copy-paste from the Polkadot repo's `polkadot-runtime-common` crate. -pub const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND; +// TODO: https://github.com/paritytech/parity-bridges-common/issues/1543 - remove `set_proof_size` +pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND.saturating_mul(2); /// All Polkadot-like chains assume that an on-initialize consumes 1 percent of the weight on /// average, hence a single extrinsic will not be allowed to consume more than diff --git a/primitives/runtime/Cargo.toml b/primitives/runtime/Cargo.toml index 9adbe0014..8d94a13aa 100644 --- a/primitives/runtime/Cargo.toml +++ b/primitives/runtime/Cargo.toml @@ -15,14 +15,14 @@ scale-info = { version = "2.1", default-features = false, features = ["derive"] serde = { version = "1.0", optional = true, features = ["derive"] } trie-db = { version = "0.24", default-features = false } # paritytech -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-state-machine = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-trie = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-state-machine = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-trie = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [dev-dependencies] # crates.io diff --git a/primitives/runtime/src/chain.rs b/primitives/runtime/src/chain.rs index 4f3e4f258..0414f2614 100644 --- a/primitives/runtime/src/chain.rs +++ b/primitives/runtime/src/chain.rs @@ -15,7 +15,7 @@ // along with Parity Bridges Common. If not, see . // crates.io -use codec::{Decode, Encode}; +use codec::{Decode, Encode, MaxEncodedLen}; use num_traits::{AsPrimitive, Bounded, CheckedSub, Saturating, SaturatingAdd, Zero}; // paritytech use frame_support::{weights::Weight, Parameter}; @@ -82,6 +82,7 @@ pub trait Chain: Send + Sync + 'static { + AsPrimitive + Default + Saturating + + MaxEncodedLen // original `sp_runtime::traits::Header::BlockNumber` doesn't have this trait, but // `sp_runtime::generic::Era` requires block number -> `u64` conversion. + Into; @@ -101,7 +102,8 @@ pub trait Chain: Send + Sync + 'static { + SimpleBitOps + AsRef<[u8]> + AsMut<[u8]> - + MaybeMallocSizeOf; + + MaybeMallocSizeOf + + MaxEncodedLen; /// A type that fulfills the abstract idea of what a Substrate hasher (a type /// that produces hashes) is. @@ -119,7 +121,13 @@ pub trait Chain: Send + Sync + 'static { + MaybeSerializeDeserialize; /// The user account identifier type for the runtime. - type AccountId: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord; + type AccountId: Parameter + + Member + + MaybeSerializeDeserialize + + Debug + + MaybeDisplay + + Ord + + MaxEncodedLen; /// Balance of an account in native tokens. /// /// The chain may support multiple tokens, but this particular type is for token that is used @@ -136,7 +144,8 @@ pub trait Chain: Send + Sync + 'static { + PartialOrd + SaturatingAdd + Zero - + TryFrom; + + TryFrom + + MaxEncodedLen; /// Index of a transaction used by the chain. type Index: Parameter + Member @@ -146,7 +155,8 @@ pub trait Chain: Send + Sync + 'static { + MaybeDisplay + MaybeSerializeDeserialize + AtLeast32Bit - + Copy; + + Copy + + MaxEncodedLen; /// Signature type, used on this chain. type Signature: Parameter + Verify; diff --git a/primitives/runtime/src/lib.rs b/primitives/runtime/src/lib.rs index 6d93faba5..11ed5d8c8 100644 --- a/primitives/runtime/src/lib.rs +++ b/primitives/runtime/src/lib.rs @@ -22,6 +22,7 @@ pub mod messages; mod chain; mod storage_proof; +mod storage_types; pub use chain::{ AccountIdOf, AccountPublicOf, BalanceOf, BlockNumberOf, Chain, EncodedOrDecodedCall, HashOf, @@ -34,6 +35,7 @@ pub use storage_proof::{ record_all_keys as record_all_trie_keys, Error as StorageProofError, ProofSize as StorageProofSize, StorageProofChecker, }; +pub use storage_types::BoundedStorageValue; // Re-export macro to avoid include paste dependency everywhere pub use sp_runtime::paste; @@ -227,7 +229,7 @@ pub trait OwnedBridgeModule { } /// Ensure that the origin is either root, or `PalletOwner`. - fn ensure_owner_or_root(origin: T::Origin) -> Result<(), BadOrigin> { + fn ensure_owner_or_root(origin: T::RuntimeOrigin) -> Result<(), BadOrigin> { match origin.into() { Ok(RawOrigin::Root) => Ok(()), Ok(RawOrigin::Signed(ref signer)) @@ -246,7 +248,7 @@ pub trait OwnedBridgeModule { } /// Change the owner of the module. - fn set_owner(origin: T::Origin, maybe_owner: Option) -> DispatchResult { + fn set_owner(origin: T::RuntimeOrigin, maybe_owner: Option) -> DispatchResult { Self::ensure_owner_or_root(origin)?; match maybe_owner { Some(owner) => { @@ -264,7 +266,7 @@ pub trait OwnedBridgeModule { /// Halt or resume all/some module operations. fn set_operating_mode( - origin: T::Origin, + origin: T::RuntimeOrigin, operating_mode: Self::OperatingMode, ) -> DispatchResult { Self::ensure_owner_or_root(origin)?; diff --git a/primitives/runtime/src/storage_types.rs b/primitives/runtime/src/storage_types.rs new file mode 100644 index 000000000..b37f779d0 --- /dev/null +++ b/primitives/runtime/src/storage_types.rs @@ -0,0 +1,90 @@ +// Copyright 2022 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 . + +//! Wrapper for a runtime storage value that checks if value exceeds given maximum +//! during conversion. + +use codec::{Decode, Encode, MaxEncodedLen}; +use frame_support::{traits::Get, RuntimeDebug}; +use scale_info::{Type, TypeInfo}; +use sp_std::{marker::PhantomData, ops::Deref}; + +/// Error that is returned when the value size exceeds maximal configured size. +#[derive(RuntimeDebug)] +pub struct MaximalSizeExceededError { + /// Size of the value. + pub value_size: usize, + /// Maximal configured size. + pub maximal_size: usize, +} + +/// A bounded runtime storage value. +#[derive(Clone, Decode, Encode, Eq, PartialEq)] +pub struct BoundedStorageValue { + value: V, + _phantom: PhantomData, +} + +impl sp_std::fmt::Debug for BoundedStorageValue { + fn fmt(&self, fmt: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + self.value.fmt(fmt) + } +} + +impl, V: Encode> BoundedStorageValue { + /// Construct `BoundedStorageValue` from the underlying `value` with all required checks. + /// + /// Returns error if value size exceeds given bounds. + pub fn try_from_inner(value: V) -> Result { + // this conversion is heavy (since we do encoding here), so we may want to optimize it later + // (e.g. by introducing custom Encode implementation, and turning `BoundedStorageValue` into + // `enum BoundedStorageValue { Decoded(V), Encoded(Vec) }`) + let value_size = value.encoded_size(); + let maximal_size = B::get() as usize; + if value_size > maximal_size { + Err(MaximalSizeExceededError { value_size, maximal_size }) + } else { + Ok(BoundedStorageValue { value, _phantom: Default::default() }) + } + } + + /// Convert into the inner type + pub fn into_inner(self) -> V { + self.value + } +} + +impl Deref for BoundedStorageValue { + type Target = V; + + fn deref(&self) -> &Self::Target { + &self.value + } +} + +impl TypeInfo for BoundedStorageValue { + type Identity = Self; + + fn type_info() -> Type { + V::type_info() + } +} + +impl, V: Encode> MaxEncodedLen for BoundedStorageValue { + fn max_encoded_len() -> usize { + B::get() as usize + } +} diff --git a/primitives/test-utils/Cargo.toml b/primitives/test-utils/Cargo.toml index de37ea2b5..e42d07b99 100644 --- a/primitives/test-utils/Cargo.toml +++ b/primitives/test-utils/Cargo.toml @@ -13,10 +13,10 @@ finality-grandpa = { version = "0.16", default-features = false } # darwinia-network bp-header-chain = { default-features = false, path = "../header-chain" } # paritytech -sp-application-crypto = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-finality-grandpa = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +sp-application-crypto = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-finality-grandpa = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } # paritytech diff --git a/primitives/test-utils/src/lib.rs b/primitives/test-utils/src/lib.rs index 93ac76355..492124ce4 100644 --- a/primitives/test-utils/src/lib.rs +++ b/primitives/test-utils/src/lib.rs @@ -112,7 +112,7 @@ pub fn make_justification_for_header( }; // Note: Adding 1 to account for the target header - let chain = generate_chain(i as u32, depth + 1, &header); + let chain = generate_chain(i, depth + 1, &header); // We don't include our finality target header in the vote ancestries for child in &chain[1..] { @@ -228,16 +228,16 @@ macro_rules! generate_owned_bridge_module_tests { PalletOwner::::put(1); // The root should be able to change the owner. - assert_ok!(Pallet::::set_owner(Origin::root(), Some(2))); + assert_ok!(Pallet::::set_owner(RuntimeOrigin::root(), Some(2))); assert_eq!(PalletOwner::::get(), Some(2)); // The owner should be able to change the owner. - assert_ok!(Pallet::::set_owner(Origin::signed(2), Some(3))); + assert_ok!(Pallet::::set_owner(RuntimeOrigin::signed(2), Some(3))); assert_eq!(PalletOwner::::get(), Some(3)); // Other users shouldn't be able to change the owner. assert_noop!( - Pallet::::set_owner(Origin::signed(1), Some(4)), + Pallet::::set_owner(RuntimeOrigin::signed(1), Some(4)), DispatchError::BadOrigin ); assert_eq!(PalletOwner::::get(), Some(3)); @@ -252,26 +252,26 @@ macro_rules! generate_owned_bridge_module_tests { // The root should be able to halt the pallet. assert_ok!(Pallet::::set_operating_mode( - Origin::root(), + RuntimeOrigin::root(), $halted_operating_mode )); assert_eq!(PalletOperatingMode::::get(), $halted_operating_mode); // The root should be able to resume the pallet. assert_ok!(Pallet::::set_operating_mode( - Origin::root(), + RuntimeOrigin::root(), $normal_operating_mode )); assert_eq!(PalletOperatingMode::::get(), $normal_operating_mode); // The owner should be able to halt the pallet. assert_ok!(Pallet::::set_operating_mode( - Origin::signed(1), + RuntimeOrigin::signed(1), $halted_operating_mode )); assert_eq!(PalletOperatingMode::::get(), $halted_operating_mode); // The owner should be able to resume the pallet. assert_ok!(Pallet::::set_operating_mode( - Origin::signed(1), + RuntimeOrigin::signed(1), $normal_operating_mode )); assert_eq!(PalletOperatingMode::::get(), $normal_operating_mode); @@ -279,7 +279,7 @@ macro_rules! generate_owned_bridge_module_tests { // Other users shouldn't be able to halt the pallet. assert_noop!( Pallet::::set_operating_mode( - Origin::signed(2), + RuntimeOrigin::signed(2), $halted_operating_mode ), DispatchError::BadOrigin @@ -289,7 +289,7 @@ macro_rules! generate_owned_bridge_module_tests { PalletOperatingMode::::put($halted_operating_mode); assert_noop!( Pallet::::set_operating_mode( - Origin::signed(2), + RuntimeOrigin::signed(2), $normal_operating_mode ), DispatchError::BadOrigin diff --git a/runtime-common/Cargo.toml b/runtime-common/Cargo.toml index 2473170c7..70a61c309 100644 --- a/runtime-common/Cargo.toml +++ b/runtime-common/Cargo.toml @@ -25,18 +25,18 @@ pallet-bridge-messages = { default-features = false, path = "../modules/messag pallet-bridge-parachains = { default-features = false, path = "../modules/parachains" } pallet-fee-market = { default-features = false, path = "../modules/fee-market" } # paritytech -frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -pallet-balances = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -pallet-transaction-payment = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-api = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-state-machine = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-trie = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } -sp-version = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate", branch = "master" } +frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +pallet-balances = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +pallet-transaction-payment = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-api = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-state-machine = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-trie = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } +sp-version = { optional = true, default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" } [features] default = ["std"] diff --git a/runtime-common/src/integrity.rs b/runtime-common/src/integrity.rs index f2b5ca4c4..8f281f1ad 100644 --- a/runtime-common/src/integrity.rs +++ b/runtime-common/src/integrity.rs @@ -60,7 +60,7 @@ macro_rules! assert_bridge_types( // `frame_support::weights::Weight` is used here directly, because all chains we know are using this // primitive (may be changed in the future) use $crate::messages::{ - AccountIdOf, BalanceOf, BridgedChain, HashOf, SignatureOf, SignerOf, ThisChain, WeightOf, + AccountIdOf, BalanceOf, BridgedChain, HashOf, SignatureOf, SignerOf, ThisChain, }; use static_assertions::assert_type_eq_all; @@ -68,14 +68,12 @@ macro_rules! assert_bridge_types( assert_type_eq_all!(AccountIdOf>, bp_runtime::AccountIdOf<$this>); assert_type_eq_all!(SignerOf>, bp_runtime::AccountPublicOf<$this>); assert_type_eq_all!(SignatureOf>, bp_runtime::SignatureOf<$this>); - assert_type_eq_all!(WeightOf>, frame_support::weights::Weight); assert_type_eq_all!(BalanceOf>, bp_runtime::BalanceOf<$this>); assert_type_eq_all!(HashOf>, bp_runtime::HashOf<$bridged>); assert_type_eq_all!(AccountIdOf>, bp_runtime::AccountIdOf<$bridged>); assert_type_eq_all!(SignerOf>, bp_runtime::AccountPublicOf<$bridged>); assert_type_eq_all!(SignatureOf>, bp_runtime::SignatureOf<$bridged>); - assert_type_eq_all!(WeightOf>, frame_support::weights::Weight); assert_type_eq_all!(BalanceOf>, bp_runtime::BalanceOf<$bridged>); } } @@ -114,7 +112,7 @@ macro_rules! assert_bridge_messages_pallet_types( use $crate::messages::{ source::FromThisChainMessagePayload, target::FromBridgedChainMessagePayload, - AccountIdOf, BalanceOf, BridgedChain, CallOf, ThisChain, WeightOf, + AccountIdOf, BalanceOf, BridgedChain, CallOf, ThisChain, }; use pallet_bridge_messages::Config as MessagesConfig; use static_assertions::assert_type_eq_all; diff --git a/runtime-common/src/lib.rs b/runtime-common/src/lib.rs index 4df097eb1..e2a98476c 100644 --- a/runtime-common/src/lib.rs +++ b/runtime-common/src/lib.rs @@ -198,12 +198,12 @@ mod tests { impl sp_runtime::traits::Dispatchable for MockCall { type Config = (); type Info = (); - type Origin = (); type PostInfo = (); + type RuntimeOrigin = (); fn dispatch( self, - _origin: Self::Origin, + _origin: Self::RuntimeOrigin, ) -> sp_runtime::DispatchResultWithInfo { unimplemented!() } diff --git a/runtime-common/src/messages.rs b/runtime-common/src/messages.rs index a078c5573..8b0664083 100644 --- a/runtime-common/src/messages.rs +++ b/runtime-common/src/messages.rs @@ -78,11 +78,6 @@ pub trait ChainWithMessages { type Signer: Encode + Decode; /// Signature type used on the chain. type Signature: Encode + Decode; - /// Type of weight that is used on the chain. This would almost always be a regular - /// `frame_support::weight::Weight`. But since the meaning of weight on different chains - /// may be different, the `WeightOf<>` construct is used to avoid confusion between - /// different weights. - type Weight: From + PartialOrd; /// Type of balances that is used on the chain. type Balance: Encode + Decode @@ -97,12 +92,12 @@ pub trait ChainWithMessages { /// This chain that has `pallet-bridge-messages` and `dispatch` modules. pub trait ThisChainWithMessages: ChainWithMessages { /// Call origin on the chain. - type Origin; + type RuntimeOrigin; /// Call type on the chain. - type Call: Encode + Decode; + type RuntimeCall: Encode + Decode; /// Do we accept message sent by given origin to given lane? - fn is_message_accepted(origin: &Self::Origin, lane: &LaneId) -> bool; + fn is_message_accepted(origin: &Self::RuntimeOrigin, lane: &LaneId) -> bool; /// Maximal number of pending (not yet delivered) messages at This chain. /// @@ -132,14 +127,12 @@ pub type AccountIdOf = ::AccountId; pub type SignerOf = ::Signer; /// Signature type used on the chain. pub type SignatureOf = ::Signature; -/// Type of weight that used on the chain. -pub type WeightOf = ::Weight; /// Type of balances that is used on the chain. pub type BalanceOf = ::Balance; /// Type of origin that is used on the chain. -pub type OriginOf = ::Origin; +pub type OriginOf = ::RuntimeOrigin; /// Type of call that is used on this chain. -pub type CallOf = ::Call; +pub type CallOf = ::RuntimeCall; /// Raw storage proof type (just raw trie nodes). pub type RawStorageProof = Vec>; @@ -228,7 +221,6 @@ pub mod source { impl LaneMessageVerifier< OriginOf>, - AccountIdOf>, FromThisChainMessagePayload, BalanceOf>, > for FromThisChainMessageVerifier @@ -532,7 +524,7 @@ pub mod target { fn dispatch_weight( message: &mut DispatchMessage>>, ) -> frame_support::weights::Weight { - message.data.payload.as_ref().map(|payload| payload.weight).unwrap_or(0) + message.data.payload.as_ref().map(|payload| payload.weight).unwrap_or(Weight::zero()) } fn pre_dispatch( @@ -835,13 +827,14 @@ mod tests { // paritytech use frame_support::weights::Weight; - // const DELIVERY_TRANSACTION_WEIGHT: Weight = 100; - // const DELIVERY_CONFIRMATION_TRANSACTION_WEIGHT: Weight = 100; - // const THIS_CHAIN_WEIGHT_TO_BALANCE_RATE: Weight = 2; - // const BRIDGED_CHAIN_WEIGHT_TO_BALANCE_RATE: Weight = 4; + // const DELIVERY_TRANSACTION_WEIGHT: Weight = Weight::from_ref_time(100);; + // const DELIVERY_CONFIRMATION_TRANSACTION_WEIGHT: u64 = 100; + // const THIS_CHAIN_WEIGHT_TO_BALANCE_RATE: u32 = 2; + // const BRIDGED_CHAIN_WEIGHT_TO_BALANCE_RATE: u32 = 4; // const BRIDGED_CHAIN_TO_THIS_CHAIN_BALANCE_RATE: u32 = 6; // const BRIDGED_CHAIN_MIN_EXTRINSIC_WEIGHT: usize = 5; - const BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT: Weight = 2048; + // TODO This should be `usize`, but for current tests, let it be `u64` + const BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT: u64 = 2048; const BRIDGED_CHAIN_MAX_EXTRINSIC_SIZE: u32 = 1024; const TEST_LANE_ID: &LaneId = b"test"; @@ -993,13 +986,12 @@ mod tests { type Hash = (); type Signature = ThisChainSignature; type Signer = ThisChainSigner; - type Weight = frame_support::weights::Weight; } impl ThisChainWithMessages for ThisChain { - type Call = ThisChainCall; - type Origin = ThisChainOrigin; + type RuntimeCall = ThisChainCall; + type RuntimeOrigin = ThisChainOrigin; - fn is_message_accepted(_send_origin: &Self::Origin, lane: &LaneId) -> bool { + fn is_message_accepted(_send_origin: &Self::RuntimeOrigin, lane: &LaneId) -> bool { lane == TEST_LANE_ID } @@ -1024,13 +1016,12 @@ mod tests { type Hash = (); type Signature = BridgedChainSignature; type Signer = BridgedChainSigner; - type Weight = frame_support::weights::Weight; } impl ThisChainWithMessages for BridgedChain { - type Call = BridgedChainCall; - type Origin = BridgedChainOrigin; + type RuntimeCall = BridgedChainCall; + type RuntimeOrigin = BridgedChainOrigin; - fn is_message_accepted(_send_origin: &Self::Origin, _lane: &LaneId) -> bool { + fn is_message_accepted(_send_origin: &Self::RuntimeOrigin, _lane: &LaneId) -> bool { unreachable!() } @@ -1045,8 +1036,8 @@ mod tests { fn verify_dispatch_weight(message_payload: &[u8], payload_weight: &Weight) -> bool { let begin = - std::cmp::min(BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT, message_payload.len() as Weight); - (begin..=BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT).contains(payload_weight) + std::cmp::min(BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT, message_payload.len() as u64); + (begin..=BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT).contains(&payload_weight.ref_time()) } } @@ -1071,7 +1062,7 @@ mod tests { let message_on_bridged_chain = source::FromThisChainMessagePayload:: { spec_version: 1, - weight: 100, + weight: Weight::from_ref_time(100), origin: bp_message_dispatch::CallOrigin::SourceRoot, dispatch_fee_payment: DispatchFeePayment::AtTargetChain, call: ThisChainCall::Transfer.encode(), @@ -1088,7 +1079,7 @@ mod tests { message_on_this_chain, target::FromBridgedChainMessagePayload:: { spec_version: 1, - weight: 100, + weight: Weight::from_ref_time(100), origin: bp_message_dispatch::CallOrigin::SourceRoot, dispatch_fee_payment: DispatchFeePayment::AtTargetChain, call: target::FromBridgedChainEncodedMessageCall::::new( @@ -1164,7 +1155,7 @@ mod tests { assert!(source::verify_chain_message::( &source::FromThisChainMessagePayload:: { spec_version: 1, - weight: 5, + weight: Weight::from_ref_time(5), origin: bp_message_dispatch::CallOrigin::SourceRoot, dispatch_fee_payment: DispatchFeePayment::AtSourceChain, call: vec![1, 2, 3, 4, 5, 6], @@ -1178,7 +1169,7 @@ mod tests { assert!(source::verify_chain_message::( &source::FromThisChainMessagePayload:: { spec_version: 1, - weight: BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT + 1, + weight: Weight::from_ref_time((BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT + 1) as u64), origin: bp_message_dispatch::CallOrigin::SourceRoot, dispatch_fee_payment: DispatchFeePayment::AtSourceChain, call: vec![1, 2, 3, 4, 5, 6], @@ -1192,7 +1183,7 @@ mod tests { assert!(source::verify_chain_message::( &source::FromThisChainMessagePayload:: { spec_version: 1, - weight: BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT, + weight: Weight::from_ref_time(BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT as u64), origin: bp_message_dispatch::CallOrigin::SourceRoot, dispatch_fee_payment: DispatchFeePayment::AtSourceChain, call: vec![0; source::maximal_message_size::() as usize + 1], @@ -1207,7 +1198,7 @@ mod tests { source::verify_chain_message::( &source::FromThisChainMessagePayload:: { spec_version: 1, - weight: BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT, + weight: Weight::from_ref_time(BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT as u64), origin: bp_message_dispatch::CallOrigin::SourceRoot, dispatch_fee_payment: DispatchFeePayment::AtSourceChain, call: vec![0; source::maximal_message_size::() as _], diff --git a/runtime-common/src/messages_benchmarking.rs b/runtime-common/src/messages_benchmarking.rs index 3077f798a..f7aa090d1 100644 --- a/runtime-common/src/messages_benchmarking.rs +++ b/runtime-common/src/messages_benchmarking.rs @@ -34,7 +34,7 @@ use pallet_bridge_messages::benchmarking::{ MessageDeliveryProofParams, MessageParams, MessageProofParams, }; // paritytech -use frame_support::weights::{GetDispatchInfo, Weight}; +use frame_support::{dispatch::GetDispatchInfo, weights::Weight}; use sp_core::Hasher; use sp_runtime::traits::{Header, IdentifyAccount, MaybeSerializeDeserialize, Zero}; use sp_std::{fmt::Debug, prelude::*}; @@ -105,7 +105,7 @@ where nonces_start: *params.message_nonces.start(), nonces_end: *params.message_nonces.end(), }, - 0, + Weight::zero(), ) } diff --git a/runtime-common/src/messages_extension.rs b/runtime-common/src/messages_extension.rs index dae2a2212..37a2243df 100644 --- a/runtime-common/src/messages_extension.rs +++ b/runtime-common/src/messages_extension.rs @@ -42,7 +42,7 @@ impl< MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof, >, Call: IsSubType, T>>, - T: frame_system::Config + T: frame_system::Config + Config, I: 'static, > BridgeRuntimeFilterCall for Pallet