From 4ad375b8496a4d4fc263ce90bcbfccb98df9f7c3 Mon Sep 17 00:00:00 2001 From: StackOverflowExcept1on <109800286+StackOverflowExcept1on@users.noreply.github.com> Date: Tue, 9 Jan 2024 15:52:50 +0300 Subject: [PATCH 1/3] refactor(workspace): replace static-assertions with const fn expressions (#3596) --- Cargo.lock | 11 ----------- Cargo.toml | 1 - core/Cargo.toml | 1 - core/src/lib.rs | 5 +---- core/src/memory.rs | 4 +--- core/src/message/mod.rs | 2 +- core/src/pages.rs | 12 ++++++------ examples/stack-allocations/Cargo.toml | 1 - examples/stack-allocations/src/lib.rs | 5 ++--- gclient/Cargo.toml | 1 - gclient/src/api/calls.rs | 2 +- gcore/Cargo.toml | 1 - gcore/src/lib.rs | 5 +---- gstd/Cargo.toml | 2 -- gstd/src/lib.rs | 5 +---- pallets/gear-program/Cargo.toml | 1 - pallets/gear/Cargo.toml | 1 - pallets/gear/src/schedule.rs | 4 ++-- runtime-interface/Cargo.toml | 2 -- runtime-interface/src/lib.rs | 4 +--- runtime/vara/Cargo.toml | 1 - runtime/vara/src/lib.rs | 5 ++--- scripts/src/clippy.sh | 8 ++++---- utils/runtime-fuzzer/Cargo.toml | 1 - utils/runtime-fuzzer/src/gear_calls.rs | 4 ++-- utils/wasm-gen/Cargo.toml | 1 - utils/wasm-gen/src/generator/syscalls/invocator.rs | 2 +- 27 files changed, 26 insertions(+), 66 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3d7dc3551aa..593e90356f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2274,7 +2274,6 @@ dependencies = [ "parity-scale-codec", "rand 0.8.5", "rand_pcg", - "static_assertions", ] [[package]] @@ -3740,7 +3739,6 @@ dependencies = [ "hex-literal", "log", "parity-scale-codec", - "static_assertions", "subxt", "thiserror", "tokio", @@ -3759,7 +3757,6 @@ dependencies = [ "gsys", "hex-literal", "parity-scale-codec", - "static_assertions", ] [[package]] @@ -3919,7 +3916,6 @@ dependencies = [ "rand 0.8.5", "scale-info", "serde", - "static_assertions", "wabt", "wasmparser-nostd 0.100.1", ] @@ -4180,7 +4176,6 @@ dependencies = [ "sp-runtime-interface", "sp-std 8.0.0 (git+https://github.com/gear-tech/substrate.git?branch=gear-polkadot-v1.0.0-canary)", "sp-wasm-interface", - "static_assertions", "winapi", ] @@ -4396,7 +4391,6 @@ dependencies = [ "log", "proptest", "rand 0.8.5", - "static_assertions", "thiserror", "wasm-smith", "wasmparser-nostd 0.100.1", @@ -4676,7 +4670,6 @@ dependencies = [ "parity-scale-codec", "primitive-types", "scale-info", - "static_assertions", ] [[package]] @@ -7566,7 +7559,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-std 8.0.0 (git+https://github.com/gear-tech/substrate.git?branch=gear-polkadot-v1.0.0-canary)", - "static_assertions", "test-syscalls", "wabt", ] @@ -7743,7 +7735,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-std 8.0.0 (git+https://github.com/gear-tech/substrate.git?branch=gear-polkadot-v1.0.0-canary)", - "static_assertions", ] [[package]] @@ -9556,7 +9547,6 @@ dependencies = [ "sp-io", "sp-keyring", "sp-runtime", - "static_assertions", "vara-runtime", ] @@ -13525,7 +13515,6 @@ dependencies = [ "sp-std 8.0.0 (git+https://github.com/gear-tech/substrate.git?branch=gear-polkadot-v1.0.0-canary)", "sp-transaction-pool", "sp-version", - "static_assertions", "substrate-build-script-utils", "substrate-wasm-builder", "wat", diff --git a/Cargo.toml b/Cargo.toml index f51541d9eef..bb888dda646 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -145,7 +145,6 @@ serde = "^1" serde_json = "^1" serde_yaml = "0.8.26" sha-1 = "0.10.1" -static_assertions = "1" subxt = "0.32.1" subxt-metadata = "0.32.1" subxt-codegen = "0.32.1" diff --git a/core/Cargo.toml b/core/Cargo.toml index 70bf12eb509..98c75a5cd09 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -22,7 +22,6 @@ gear-wasm-instrument.workspace = true wasmparser.workspace = true hex = { workspace = true, features = ["alloc"] } hashbrown.workspace = true -static_assertions.workspace = true paste.workspace = true enum-iterator.workspace = true byteorder.workspace = true diff --git a/core/src/lib.rs b/core/src/lib.rs index cd9b6c45654..b9e0c67664f 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -44,8 +44,5 @@ pub mod reservation; pub mod buffer; pub mod str; -use core::mem::size_of; -use static_assertions::const_assert; - // This allows all casts from u32 into usize be safe. -const_assert!(size_of::() <= size_of::()); +const _: () = assert!(core::mem::size_of::() <= core::mem::size_of::()); diff --git a/core/src/memory.rs b/core/src/memory.rs index a86643128f9..c5981f056af 100644 --- a/core/src/memory.rs +++ b/core/src/memory.rs @@ -175,9 +175,7 @@ impl PageBuf { /// Host pointer can be 64bit or less, to support both we use u64. pub type HostPointer = u64; -static_assertions::const_assert!( - core::mem::size_of::() >= core::mem::size_of::() -); +const _: () = assert!(core::mem::size_of::() >= core::mem::size_of::()); /// Core memory error. #[derive(Debug, Clone, Eq, PartialEq, derive_more::Display)] diff --git a/core/src/message/mod.rs b/core/src/message/mod.rs index 53d0dbd3405..88b37c994f6 100644 --- a/core/src/message/mod.rs +++ b/core/src/message/mod.rs @@ -55,7 +55,7 @@ pub const MAX_PAYLOAD_SIZE: usize = 8 * 1024 * 1024; // **WARNING**: do not remove this check until be sure that // all `MAX_PAYLOAD_SIZE` conversions are safe! -static_assertions::const_assert!(MAX_PAYLOAD_SIZE <= u32::MAX as usize); +const _: () = assert!(MAX_PAYLOAD_SIZE <= u32::MAX as usize); /// Payload size exceed error #[derive( diff --git a/core/src/pages.rs b/core/src/pages.rs index 3e6478018d8..e53ed28d05e 100644 --- a/core/src/pages.rs +++ b/core/src/pages.rs @@ -35,8 +35,8 @@ pub const WASM_PAGE_SIZE: usize = 0x10000; /// native page size, so can vary. pub const GEAR_PAGE_SIZE: usize = 0x4000; -static_assertions::const_assert!(WASM_PAGE_SIZE < u32::MAX as usize); -static_assertions::const_assert_eq!(WASM_PAGE_SIZE % GEAR_PAGE_SIZE, 0); +const _: () = assert!(WASM_PAGE_SIZE < u32::MAX as usize); +const _: () = assert!(WASM_PAGE_SIZE % GEAR_PAGE_SIZE == 0); /// Errors when act with PageU32Size. #[derive(Debug, Clone, derive_more::Display)] @@ -64,7 +64,7 @@ pub struct GearPage(pub(crate) u32); impl From for GearPage { fn from(value: u16) -> Self { // u16::MAX * GearPage::size() - 1 <= u32::MAX - static_assertions::const_assert!(GEAR_PAGE_SIZE <= 0x10000); + const _: () = assert!(GEAR_PAGE_SIZE <= 0x10000); GearPage(value as u32) } } @@ -77,7 +77,7 @@ impl From for u32 { impl PageU32Size for GearPage { fn size_non_zero() -> NonZeroU32 { - static_assertions::const_assert_ne!(GEAR_PAGE_SIZE, 0); + const _: () = assert!(GEAR_PAGE_SIZE != 0); unsafe { NonZeroU32::new_unchecked(GEAR_PAGE_SIZE as u32) } } @@ -102,7 +102,7 @@ pub struct WasmPage(pub(crate) u32); impl From for WasmPage { fn from(value: u16) -> Self { // u16::MAX * WasmPage::size() - 1 == u32::MAX - static_assertions::const_assert!(WASM_PAGE_SIZE == 0x10000); + const _: () = assert!(WASM_PAGE_SIZE == 0x10000); WasmPage(value as u32) } } @@ -121,7 +121,7 @@ impl PageNumber for WasmPage { impl PageU32Size for WasmPage { fn size_non_zero() -> NonZeroU32 { - static_assertions::const_assert_ne!(WASM_PAGE_SIZE, 0); + const _: () = assert!(WASM_PAGE_SIZE != 0); unsafe { NonZeroU32::new_unchecked(WASM_PAGE_SIZE as u32) } } diff --git a/examples/stack-allocations/Cargo.toml b/examples/stack-allocations/Cargo.toml index e6b8fe0c32e..53bc2070b90 100644 --- a/examples/stack-allocations/Cargo.toml +++ b/examples/stack-allocations/Cargo.toml @@ -15,7 +15,6 @@ parity-scale-codec.workspace = true gtest.workspace = true rand_pcg.workspace = true rand.workspace = true -static_assertions.workspace = true [build-dependencies] gear-wasm-builder.workspace = true diff --git a/examples/stack-allocations/src/lib.rs b/examples/stack-allocations/src/lib.rs index 5aa80e5d0aa..64333907992 100644 --- a/examples/stack-allocations/src/lib.rs +++ b/examples/stack-allocations/src/lib.rs @@ -67,7 +67,6 @@ mod tests { use gtest::{Program, System}; use parity_scale_codec::Decode; use rand::{Rng, SeedableRng}; - use static_assertions::const_assert; #[test] fn stress() { @@ -77,11 +76,11 @@ mod tests { const MAX_NUMBER: u8 = 255; // Check that check sum is less than u32::MAX - const_assert!( + const _: () = assert!( MAX_ACTIONS_AMOUNT * MAX_NUMBER as usize * HANDLE_DATA_SIZE <= u32::MAX as usize ); // Check that we can fit all the data in the stack (heuristic no more than 10 wasm pages) - const_assert!(MAX_ACTIONS_AMOUNT * HANDLE_DATA_SIZE <= 64 * 1024 * 10); + const _: () = assert!(MAX_ACTIONS_AMOUNT * HANDLE_DATA_SIZE <= 64 * 1024 * 10); let from = 42; let system = System::new(); diff --git a/gclient/Cargo.toml b/gclient/Cargo.toml index e869aeb4e5c..daf873f476c 100644 --- a/gclient/Cargo.toml +++ b/gclient/Cargo.toml @@ -23,7 +23,6 @@ thiserror.workspace = true async-trait.workspace = true url.workspace = true wabt.workspace = true -static_assertions.workspace = true [dev-dependencies] tokio = { workspace = true, features = ["full"] } diff --git a/gclient/src/api/calls.rs b/gclient/src/api/calls.rs index 4c70f5f46d1..fa946c25455 100644 --- a/gclient/src/api/calls.rs +++ b/gclient/src/api/calls.rs @@ -532,7 +532,7 @@ impl GearApi { ) -> Result { let program = self.0.api().gprog_at(program_id, block_hash).await?; - static_assertions::const_assert_eq!(WASM_PAGE_SIZE % GEAR_PAGE_SIZE, 0); + const _: () = assert!(WASM_PAGE_SIZE % GEAR_PAGE_SIZE == 0); assert!(program.static_pages.0 > 0); let static_page_count = (program.static_pages.0 as usize - 1) * WASM_PAGE_SIZE / GEAR_PAGE_SIZE; diff --git a/gcore/Cargo.toml b/gcore/Cargo.toml index f0e4ac0fdea..31af69700f3 100644 --- a/gcore/Cargo.toml +++ b/gcore/Cargo.toml @@ -11,7 +11,6 @@ gsys.workspace = true gear-core-errors.workspace = true gear-stack-buffer.workspace = true codec = { workspace = true, optional = true } -static_assertions.workspace = true [dev-dependencies] hex-literal.workspace = true diff --git a/gcore/src/lib.rs b/gcore/src/lib.rs index bcc7ce64e02..aaf1705b7c0 100644 --- a/gcore/src/lib.rs +++ b/gcore/src/lib.rs @@ -83,8 +83,5 @@ pub use utils::ext; pub use gsys::{BlockCount, BlockNumber, Gas, GasMultiplier, Percent, Value}; -use core::mem::size_of; -use static_assertions::const_assert; - // This allows all casts from u32 into usize be safe. -const_assert!(size_of::() <= size_of::()); +const _: () = assert!(core::mem::size_of::() <= core::mem::size_of::()); diff --git a/gstd/Cargo.toml b/gstd/Cargo.toml index 3b9ae7a9f78..9eef9a5c005 100644 --- a/gstd/Cargo.toml +++ b/gstd/Cargo.toml @@ -24,8 +24,6 @@ primitive-types = { workspace = true, features = ["scale-info"] } scale-info = { workspace = true, features = ["derive"] } futures = { workspace = true, features = ["alloc"] } -static_assertions.workspace = true - [features] #! ## Default features diff --git a/gstd/src/lib.rs b/gstd/src/lib.rs index 6749a219a01..7a60e321812 100644 --- a/gstd/src/lib.rs +++ b/gstd/src/lib.rs @@ -166,8 +166,5 @@ pub use gstd_codegen::{async_init, async_main}; pub use prelude::*; pub use reservations::*; -use core::mem::size_of; -use static_assertions::const_assert; - // This allows all casts from u32 into usize be safe. -const_assert!(size_of::() <= size_of::()); +const _: () = assert!(core::mem::size_of::() <= core::mem::size_of::()); diff --git a/pallets/gear-program/Cargo.toml b/pallets/gear-program/Cargo.toml index 7b1a063b145..b6e51e49e9e 100644 --- a/pallets/gear-program/Cargo.toml +++ b/pallets/gear-program/Cargo.toml @@ -18,7 +18,6 @@ scale-info = { workspace = true, features = ["derive"] } primitive-types = { workspace = true, features = ["scale-info"] } log.workspace = true hashbrown.workspace = true -static_assertions.workspace = true # Internal deps common.workspace = true diff --git a/pallets/gear/Cargo.toml b/pallets/gear/Cargo.toml index 6d3d8806fed..f449814e4a4 100644 --- a/pallets/gear/Cargo.toml +++ b/pallets/gear/Cargo.toml @@ -21,7 +21,6 @@ gear-wasm-instrument.workspace = true derive_more.workspace = true env_logger = { workspace = true, optional = true } scopeguard.workspace = true -static_assertions.workspace = true # Internal deps common.workspace = true diff --git a/pallets/gear/src/schedule.rs b/pallets/gear/src/schedule.rs index 8e66299e561..ab1c1662a97 100644 --- a/pallets/gear/src/schedule.rs +++ b/pallets/gear/src/schedule.rs @@ -1070,8 +1070,8 @@ impl Default for MemoryWeights { } const KB_AMOUNT_IN_ONE_GEAR_PAGE: u64 = GEAR_PAGE_SIZE as u64 / KB_SIZE; - static_assertions::const_assert!(KB_AMOUNT_IN_ONE_GEAR_PAGE > 0); - static_assertions::const_assert!(GEAR_PAGE_SIZE as u64 % KB_SIZE == 0); + const _: () = assert!(KB_AMOUNT_IN_ONE_GEAR_PAGE > 0); + const _: () = assert!(GEAR_PAGE_SIZE as u64 % KB_SIZE == 0); Self { lazy_pages_signal_read: to_weight!(to_cost_per_gear_page!(lazy_pages_signal_read)), diff --git a/runtime-interface/Cargo.toml b/runtime-interface/Cargo.toml index aa29864c041..20ebcae809c 100644 --- a/runtime-interface/Cargo.toml +++ b/runtime-interface/Cargo.toml @@ -22,8 +22,6 @@ sp-wasm-interface.workspace = true byteorder.workspace = true codec = { workspace = true } log = { workspace = true, optional = true } -static_assertions.workspace = true - [target.'cfg(windows)'.dependencies] winapi = { workspace = true, features = ["memoryapi"] } diff --git a/runtime-interface/src/lib.rs b/runtime-interface/src/lib.rs index 9ac73217680..3bf07f82d8e 100644 --- a/runtime-interface/src/lib.rs +++ b/runtime-interface/src/lib.rs @@ -45,9 +45,7 @@ mod gear_sandbox; pub use gear_sandbox::init as sandbox_init; pub use gear_sandbox::sandbox; -static_assertions::const_assert!( - core::mem::size_of::() >= core::mem::size_of::() -); +const _: () = assert!(core::mem::size_of::() >= core::mem::size_of::()); #[derive(Debug, Clone, Encode, Decode)] #[codec(crate = codec)] diff --git a/runtime/vara/Cargo.toml b/runtime/vara/Cargo.toml index 1c5d1b19d73..354640ebaac 100644 --- a/runtime/vara/Cargo.toml +++ b/runtime/vara/Cargo.toml @@ -16,7 +16,6 @@ const-str.workspace = true log.workspace = true parity-scale-codec.workspace = true scale-info = { workspace = true, features = ["derive"] } -static_assertions.workspace = true # Frame deps frame-support.workspace = true diff --git a/runtime/vara/src/lib.rs b/runtime/vara/src/lib.rs index 65001542699..051befb1eab 100644 --- a/runtime/vara/src/lib.rs +++ b/runtime/vara/src/lib.rs @@ -99,7 +99,6 @@ use sp_std::{ #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; -use static_assertions::const_assert; #[cfg(any(feature = "std", test))] pub use frame_system::Call as SystemCall; @@ -174,8 +173,8 @@ pub const BABE_GENESIS_EPOCH_CONFIG: sp_consensus_babe::BabeEpochConfiguration = // We'll verify that WEIGHT_REF_TIME_PER_SECOND does not overflow, allowing us to use // simple multiply and divide operators instead of saturating or checked ones. -const_assert!(WEIGHT_REF_TIME_PER_SECOND.checked_div(3).is_some()); -const_assert!((WEIGHT_REF_TIME_PER_SECOND / 3).checked_mul(2).is_some()); +const _: () = assert!(WEIGHT_REF_TIME_PER_SECOND.checked_div(3).is_some()); +const _: () = assert!((WEIGHT_REF_TIME_PER_SECOND / 3).checked_mul(2).is_some()); /// We allow for 1/3 of block time for computations, with maximum proof size. /// diff --git a/scripts/src/clippy.sh b/scripts/src/clippy.sh index 0133a609d66..5a381a2c3c8 100755 --- a/scripts/src/clippy.sh +++ b/scripts/src/clippy.sh @@ -20,14 +20,14 @@ EOF } gear_clippy() { - # TODO #3452: remove `-A clippy::needless_pass_by_ref_mut` on next rust update + # TODO #3452: remove `-A clippy::needless_pass_by_ref_mut`, `-A clippy::assertions_on_constants` on next rust update EXCLUDE_PACKAGES="--exclude vara-runtime --exclude runtime-fuzzer --exclude runtime-fuzzer-fuzz" INCLUDE_PACKAGES="-p vara-runtime -p runtime-fuzzer -p runtime-fuzzer-fuzz" - __GEAR_WASM_BUILDER_NO_BUILD=1 SKIP_WASM_BUILD=1 SKIP_VARA_RUNTIME_WASM_BUILD=1 cargo clippy --workspace "$@" $EXCLUDE_PACKAGES -- --no-deps -D warnings -A clippy::needless_pass_by_ref_mut - __GEAR_WASM_BUILDER_NO_BUILD=1 SKIP_WASM_BUILD=1 SKIP_VARA_RUNTIME_WASM_BUILD=1 cargo clippy $INCLUDE_PACKAGES --all-features -- --no-deps -D warnings -A clippy::needless_pass_by_ref_mut + __GEAR_WASM_BUILDER_NO_BUILD=1 SKIP_WASM_BUILD=1 SKIP_VARA_RUNTIME_WASM_BUILD=1 cargo clippy --workspace "$@" $EXCLUDE_PACKAGES -- --no-deps -D warnings -A clippy::needless_pass_by_ref_mut -A clippy::assertions_on_constants + __GEAR_WASM_BUILDER_NO_BUILD=1 SKIP_WASM_BUILD=1 SKIP_VARA_RUNTIME_WASM_BUILD=1 cargo clippy $INCLUDE_PACKAGES --all-features -- --no-deps -D warnings -A clippy::needless_pass_by_ref_mut -A clippy::assertions_on_constants } examples_clippy() { - __GEAR_WASM_BUILDER_NO_BUILD=1 SKIP_WASM_BUILD=1 SKIP_VARA_RUNTIME_WASM_BUILD=1 cargo clippy -p "demo-*" -p test-syscalls --no-default-features "$@" -- --no-deps -D warnings -A clippy::needless_pass_by_ref_mut + __GEAR_WASM_BUILDER_NO_BUILD=1 SKIP_WASM_BUILD=1 SKIP_VARA_RUNTIME_WASM_BUILD=1 cargo clippy -p "demo-*" -p test-syscalls --no-default-features "$@" -- --no-deps -D warnings -A clippy::needless_pass_by_ref_mut -A clippy::assertions_on_constants } diff --git a/utils/runtime-fuzzer/Cargo.toml b/utils/runtime-fuzzer/Cargo.toml index ff5195265ae..e950e495106 100644 --- a/utils/runtime-fuzzer/Cargo.toml +++ b/utils/runtime-fuzzer/Cargo.toml @@ -15,7 +15,6 @@ codec = { workspace = true, features = ["derive"] } hex.workspace = true log.workspace = true sha-1.workspace = true -static_assertions.workspace = true # Temporary deps for the reproducing crash script until #2313 is implemented clap = { workspace = true, features = ["derive"] } diff --git a/utils/runtime-fuzzer/src/gear_calls.rs b/utils/runtime-fuzzer/src/gear_calls.rs index 985c1b2e287..cc7777f3bd3 100644 --- a/utils/runtime-fuzzer/src/gear_calls.rs +++ b/utils/runtime-fuzzer/src/gear_calls.rs @@ -44,7 +44,7 @@ use std::mem; /// /// TODO: #3442 const MAX_PAYLOAD_SIZE: usize = 1024; -static_assertions::const_assert!(MAX_PAYLOAD_SIZE <= gear_core::message::MAX_PAYLOAD_SIZE); +const _: () = assert!(MAX_PAYLOAD_SIZE <= gear_core::message::MAX_PAYLOAD_SIZE); /// Maximum salt size for the fuzzer - 512 bytes. /// @@ -52,7 +52,7 @@ static_assertions::const_assert!(MAX_PAYLOAD_SIZE <= gear_core::message::MAX_PAY /// for one run. Also small salt will make overall size of the /// corpus smaller. const MAX_SALT_SIZE: usize = 512; -static_assertions::const_assert!(MAX_SALT_SIZE <= gear_core::message::MAX_PAYLOAD_SIZE); +const _: () = assert!(MAX_SALT_SIZE <= gear_core::message::MAX_PAYLOAD_SIZE); const ID_SIZE: usize = mem::size_of::(); const GAS_AND_VALUE_SIZE: usize = mem::size_of::<(u64, u128)>(); diff --git a/utils/wasm-gen/Cargo.toml b/utils/wasm-gen/Cargo.toml index c732b30a91b..2209d12c8ed 100644 --- a/utils/wasm-gen/Cargo.toml +++ b/utils/wasm-gen/Cargo.toml @@ -15,7 +15,6 @@ gsys.workspace = true gear-utils.workspace = true gear-core.workspace = true wasmparser.workspace = true -static_assertions.workspace = true thiserror.workspace = true [dev-dependencies] diff --git a/utils/wasm-gen/src/generator/syscalls/invocator.rs b/utils/wasm-gen/src/generator/syscalls/invocator.rs index c90a6a94e10..c31b117a08e 100644 --- a/utils/wasm-gen/src/generator/syscalls/invocator.rs +++ b/utils/wasm-gen/src/generator/syscalls/invocator.rs @@ -604,7 +604,7 @@ impl<'a, 'b> SyscallsInvocator<'a, 'b> { fallible_signature: FallibleSyscallSignature, param_instructions: Vec, ) -> Vec { - static_assertions::assert_eq_size!(gsys::ErrorCode, u32); + const _: () = assert!(mem::size_of::() == mem::size_of::()); let no_error_val = gsys::ErrorCode::default() as i32; assert_eq!( From c2733ecc57ddad27ce7c23a72789258276f89c2f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 9 Jan 2024 19:48:37 +0530 Subject: [PATCH 2/3] [depbot] Bump the deps group with 1 update (#3643) --- .github/workflows/validation.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/validation.yml b/.github/workflows/validation.yml index 4732ebb456f..4e2cc517e3a 100644 --- a/.github/workflows/validation.yml +++ b/.github/workflows/validation.yml @@ -55,7 +55,7 @@ jobs: tags: ${{ needs.tag-image.outputs.image_tag }} - name: SSH into VM - uses: appleboy/ssh-action@v1.0.0 + uses: appleboy/ssh-action@v1.0.3 env: NEW_IMAGE: ${{ needs.tag-image.outputs.image_tag }} with: From fb0ea9aa72773709a7ca98c45cb0b93926ca21b9 Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Wed, 10 Jan 2024 15:19:50 +0400 Subject: [PATCH 3/3] chore: Remove the current rent functionality (#3590) --- core-processor/src/common.rs | 14 - core-processor/src/configs.rs | 4 - core-processor/src/executor.rs | 5 - core-processor/src/ext.rs | 42 +- core-processor/src/handler.rs | 5 - core-processor/src/processing.rs | 13 - examples/syscalls/src/wasm.rs | 1 + gcore/src/exec.rs | 4 +- gsdk/src/metadata/generated.rs | 36 - gstd/src/exec/basic.rs | 4 +- gsys/src/lib.rs | 1 + gtest/src/lib.rs | 4 - gtest/src/manager.rs | 6 +- pallets/gear-debug/src/tests/mod.rs | 126 +- pallets/gear-debug/src/tests/utils.rs | 20 - pallets/gear/src/benchmarking/mod.rs | 210 +-- pallets/gear/src/benchmarking/tasks.rs | 91 -- .../benchmarking/tests/syscalls_integrity.rs | 34 +- pallets/gear/src/benchmarking/utils.rs | 3 +- pallets/gear/src/internal.rs | 71 +- pallets/gear/src/lib.rs | 192 +-- pallets/gear/src/manager/journal.rs | 28 +- pallets/gear/src/manager/task.rs | 163 +- pallets/gear/src/tests.rs | 1306 ++--------------- pallets/gear/src/weights.rs | 173 --- runtime/vara/src/weights/pallet_gear.rs | 173 --- utils/wasm-gen/src/tests.rs | 5 +- 27 files changed, 139 insertions(+), 2595 deletions(-) diff --git a/core-processor/src/common.rs b/core-processor/src/common.rs index 1fcad5367d0..293bc1f5b6c 100644 --- a/core-processor/src/common.rs +++ b/core-processor/src/common.rs @@ -79,8 +79,6 @@ pub struct DispatchResult { pub reply_deposits: Vec<(MessageId, u64)>, /// New programs to be created with additional data (corresponding code hash and init message id). pub program_candidates: BTreeMap>, - /// Map of program ids to paid blocks. - pub program_rents: BTreeMap, /// Gas amount after execution. pub gas_amount: GasAmount, /// Gas amount programs reserved. @@ -132,7 +130,6 @@ impl DispatchResult { awakening: Default::default(), reply_deposits: Default::default(), program_candidates: Default::default(), - program_rents: Default::default(), gas_amount, gas_reserver: None, system_reservation_context, @@ -331,15 +328,6 @@ pub enum JournalNote { /// Simple signal error. code: SignalCode, }, - /// Pay rent for the program. - PayProgramRent { - /// Rent payer. - payer: ProgramId, - /// Program whose rent will be paid. - program_id: ProgramId, - /// Amount of blocks to pay for. - block_count: u32, - }, /// Create deposit for future reply. ReplyDeposit { /// Message id of the message that generated this message. @@ -429,8 +417,6 @@ pub trait JournalHandler { fn system_unreserve_gas(&mut self, message_id: MessageId); /// Send system signal. fn send_signal(&mut self, message_id: MessageId, destination: ProgramId, code: SignalCode); - /// Pay rent for the program. - fn pay_program_rent(&mut self, payer: ProgramId, program_id: ProgramId, block_count: u32); /// Create deposit for future reply. fn reply_deposit(&mut self, message_id: MessageId, future_reply_id: MessageId, amount: u64); } diff --git a/core-processor/src/configs.rs b/core-processor/src/configs.rs index 11c7f9724fc..b1ea8bc62c4 100644 --- a/core-processor/src/configs.rs +++ b/core-processor/src/configs.rs @@ -169,8 +169,6 @@ pub struct ExecutionSettings { /// Most recently determined random seed, along with the time in the past since when it was determinable by chain observers. // TODO: find a way to put a random seed inside block config. pub random_data: (Vec, u32), - /// Rent cost per block. - pub rent_cost: u128, /// Gas multiplier. pub gas_multiplier: gsys::GasMultiplier, } @@ -220,8 +218,6 @@ pub struct BlockConfig { pub code_instrumentation_cost: u64, /// WASM code instrumentation per-byte cost. pub code_instrumentation_byte_cost: u64, - /// Rent cost per block. - pub rent_cost: u128, /// Gas multiplier. pub gas_multiplier: gsys::GasMultiplier, } diff --git a/core-processor/src/executor.rs b/core-processor/src/executor.rs index 35069e56a95..a9811d05781 100644 --- a/core-processor/src/executor.rs +++ b/core-processor/src/executor.rs @@ -214,7 +214,6 @@ where existential_deposit: settings.existential_deposit, program_id, program_candidates_data: Default::default(), - program_rents: Default::default(), host_fn_weights: settings.host_fn_weights, forbidden_funcs: settings.forbidden_funcs, mailbox_threshold: settings.mailbox_threshold, @@ -223,7 +222,6 @@ where reserve_for: settings.reserve_for, reservation: settings.reservation, random_data: settings.random_data, - rent_cost: settings.rent_cost, gas_multiplier: settings.gas_multiplier, }; @@ -338,7 +336,6 @@ where awakening: info.awakening, reply_deposits: info.reply_deposits, program_candidates, - program_rents: info.program_rents, gas_amount: info.gas_amount, gas_reserver: Some(info.gas_reserver), system_reservation_context: info.system_reservation_context, @@ -412,7 +409,6 @@ where existential_deposit: Default::default(), program_id: program.id(), program_candidates_data: Default::default(), - program_rents: Default::default(), host_fn_weights: Default::default(), forbidden_funcs: Default::default(), mailbox_threshold: Default::default(), @@ -422,7 +418,6 @@ where reservation: Default::default(), random_data: Default::default(), system_reservation: Default::default(), - rent_cost: Default::default(), gas_multiplier: gsys::GasMultiplier::from_value_per_gas(1), }; diff --git a/core-processor/src/ext.rs b/core-processor/src/ext.rs index 54e6b20f5bf..a498e645619 100644 --- a/core-processor/src/ext.rs +++ b/core-processor/src/ext.rs @@ -90,8 +90,6 @@ pub struct ProcessorContext { /// Map of code hashes to program ids of future programs, which are planned to be /// initialized with the corresponding code (with the same code hash). pub program_candidates_data: BTreeMap>, - /// Map of program ids to paid blocks. - pub program_rents: BTreeMap, /// Weights of host functions. pub host_fn_weights: HostFnWeights, /// Functions forbidden to be called. @@ -108,8 +106,6 @@ pub struct ProcessorContext { pub reservation: u64, /// Output from Randomness. pub random_data: (Vec, u32), - /// Rent cost per block. - pub rent_cost: u128, /// Gas multiplier. pub gas_multiplier: gsys::GasMultiplier, } @@ -147,7 +143,6 @@ impl ProcessorContext { existential_deposit: 0, program_id: Default::default(), program_candidates_data: Default::default(), - program_rents: Default::default(), host_fn_weights: Default::default(), forbidden_funcs: Default::default(), mailbox_threshold: 0, @@ -156,7 +151,6 @@ impl ProcessorContext { reserve_for: 0, reservation: 0, random_data: ([0u8; 32].to_vec(), 0), - rent_cost: 0, gas_multiplier: gsys::GasMultiplier::from_value_per_gas(1), } } @@ -173,7 +167,6 @@ pub struct ExtInfo { pub awakening: Vec<(MessageId, u32)>, pub reply_deposits: Vec<(MessageId, u64)>, pub program_candidates_data: BTreeMap>, - pub program_rents: BTreeMap, pub context_store: ContextStore, } @@ -382,7 +375,6 @@ impl ProcessorExternalities for Ext { gas_reserver, system_reservation, program_candidates_data, - program_rents, .. } = self.context; @@ -433,7 +425,6 @@ impl ProcessorExternalities for Ext { reply_deposits, context_store, program_candidates_data, - program_rents, }; Ok(info) } @@ -1002,39 +993,10 @@ impl Externalities for Ext { fn pay_program_rent( &mut self, - program_id: ProgramId, + _program_id: ProgramId, rent: u128, ) -> Result<(u128, u32), Self::FallibleError> { - if self.context.rent_cost == 0 { - return Ok((rent, 0)); - } - - let block_count = u32::try_from(rent / self.context.rent_cost).unwrap_or(u32::MAX); - let old_paid_blocks = self - .context - .program_rents - .get(&program_id) - .copied() - .unwrap_or(0); - - let (paid_blocks, blocks_to_pay) = match old_paid_blocks.overflowing_add(block_count) { - (count, false) => (count, block_count), - (_, true) => return Err(ProgramRentError::MaximumBlockCountPaid.into()), - }; - - if blocks_to_pay == 0 { - return Ok((rent, 0)); - } - - let cost = self.context.rent_cost.saturating_mul(blocks_to_pay.into()); - match self.context.value_counter.reduce(cost) { - ChargeResult::Enough => { - self.context.program_rents.insert(program_id, paid_blocks); - } - ChargeResult::NotEnough => return Err(FallibleExecutionError::NotEnoughValue.into()), - } - - Ok((rent.saturating_sub(cost), blocks_to_pay)) + Ok((rent, 0)) } fn program_id(&self) -> Result { diff --git a/core-processor/src/handler.rs b/core-processor/src/handler.rs index 5a208f21e37..694ed70617a 100644 --- a/core-processor/src/handler.rs +++ b/core-processor/src/handler.rs @@ -108,11 +108,6 @@ pub fn handle_journal( destination, code, } => handler.send_signal(message_id, destination, code), - JournalNote::PayProgramRent { - payer, - program_id, - block_count, - } => handler.pay_program_rent(payer, program_id, block_count), JournalNote::ReplyDeposit { message_id, future_reply_id, diff --git a/core-processor/src/processing.rs b/core-processor/src/processing.rs index 14a8e47c06c..09e67142957 100644 --- a/core-processor/src/processing.rs +++ b/core-processor/src/processing.rs @@ -70,7 +70,6 @@ where reserve_for, reservation, write_cost, - rent_cost, gas_multiplier, .. } = block_config.clone(); @@ -89,7 +88,6 @@ where reserve_for, reservation, random_data, - rent_cost, gas_multiplier, }; @@ -287,7 +285,6 @@ pub fn process_success( generated_dispatches, awakening, program_candidates, - program_rents, gas_amount, gas_reserver, system_reservation_context, @@ -385,16 +382,6 @@ pub fn process_success( }); } - // Must be handled after processing programs creation. - let payer = program_id; - for (program_id, block_count) in program_rents { - journal.push(JournalNote::PayProgramRent { - payer, - program_id, - block_count, - }); - } - for (message_id_sent, amount) in reply_deposits { journal.push(JournalNote::ReplyDeposit { message_id, diff --git a/examples/syscalls/src/wasm.rs b/examples/syscalls/src/wasm.rs index 9b6a8d39a1f..f25da1a924c 100644 --- a/examples/syscalls/src/wasm.rs +++ b/examples/syscalls/src/wasm.rs @@ -160,6 +160,7 @@ fn process(syscall_kind: Kind) { let actual_mid: [u8; 32] = msg::id().into(); assert_eq!(expected_mid, actual_mid, "Kind::MessageId: mid test failed"); } + #[allow(deprecated)] Kind::PayProgramRent(program_id, rent, expected) => { let (unused_value, paid_block_count) = exec::pay_program_rent(program_id.into(), rent) .expect(super::PAY_PROGRAM_RENT_EXPECT); diff --git a/gcore/src/exec.rs b/gcore/src/exec.rs index 095f3774db6..a5abe82ce29 100644 --- a/gcore/src/exec.rs +++ b/gcore/src/exec.rs @@ -410,7 +410,7 @@ pub fn program_id() -> ActorId { /// /// # Examples /// -/// ``` +/// ```ignore /// use gcore::exec; /// /// #[no_mangle] @@ -419,6 +419,8 @@ pub fn program_id() -> ActorId { /// exec::pay_program_rent(exec::program_id(), 1_000_000).expect("Unable to pay rent"); /// } /// ``` +#[allow(warnings)] +#[deprecated = "Rent program logic is deprecated. The function is now a no-op and will be removed soon."] pub fn pay_program_rent(program_id: ActorId, value: u128) -> Result<(u128, u32)> { let rent_pid = HashWithValue { hash: program_id.0, diff --git a/gsdk/src/metadata/generated.rs b/gsdk/src/metadata/generated.rs index 30379b81047..29a39b748c5 100644 --- a/gsdk/src/metadata/generated.rs +++ b/gsdk/src/metadata/generated.rs @@ -2141,34 +2141,6 @@ pub mod runtime_types { #[codec(index = 7)] #[doc = "See [`Pallet::set_execute_inherent`]."] set_execute_inherent { value: ::core::primitive::bool }, - #[codec(index = 8)] - #[doc = "See [`Pallet::pay_program_rent`]."] - pay_program_rent { - program_id: runtime_types::gear_core::ids::ProgramId, - block_count: ::core::primitive::u32, - }, - #[codec(index = 9)] - #[doc = "See [`Pallet::resume_session_init`]."] - resume_session_init { - program_id: runtime_types::gear_core::ids::ProgramId, - allocations: ::std::vec::Vec, - code_hash: runtime_types::gear_core::ids::CodeId, - }, - #[codec(index = 10)] - #[doc = "See [`Pallet::resume_session_push`]."] - resume_session_push { - session_id: ::core::primitive::u32, - memory_pages: ::std::vec::Vec<( - runtime_types::gear_core::pages::GearPage, - runtime_types::gear_core::memory::PageBuf, - )>, - }, - #[codec(index = 11)] - #[doc = "See [`Pallet::resume_session_commit`]."] - resume_session_commit { - session_id: ::core::primitive::u32, - block_count: ::core::primitive::u32, - }, } #[derive(Debug, crate::gp::Decode, crate::gp::DecodeAsType, crate::gp::Encode)] #[doc = "The `Error` enum of this pallet."] @@ -7804,10 +7776,6 @@ pub mod calls { ClaimValue, Run, SetExecuteInherent, - PayProgramRent, - ResumeSessionInit, - ResumeSessionPush, - ResumeSessionCommit, } impl CallInfo for GearCall { const PALLET: &'static str = "Gear"; @@ -7821,10 +7789,6 @@ pub mod calls { Self::ClaimValue => "claim_value", Self::Run => "run", Self::SetExecuteInherent => "set_execute_inherent", - Self::PayProgramRent => "pay_program_rent", - Self::ResumeSessionInit => "resume_session_init", - Self::ResumeSessionPush => "resume_session_push", - Self::ResumeSessionCommit => "resume_session_commit", } } } diff --git a/gstd/src/exec/basic.rs b/gstd/src/exec/basic.rs index 6ddd38c083d..7c61b4c400b 100644 --- a/gstd/src/exec/basic.rs +++ b/gstd/src/exec/basic.rs @@ -114,7 +114,7 @@ pub fn wake_delayed(message_id: MessageId, delay: u32) -> Result<()> { /// /// # Examples /// -/// ``` +/// ```ignore /// use gstd::exec; /// /// #[no_mangle] @@ -123,6 +123,8 @@ pub fn wake_delayed(message_id: MessageId, delay: u32) -> Result<()> { /// exec::pay_program_rent(exec::program_id(), 1_000_000).expect("Unable to pay rent"); /// } /// ``` +#[allow(warnings)] +#[deprecated = "Rent program logic is deprecated. The function is now a no-op and will be removed soon."] pub fn pay_program_rent(program_id: ActorId, value: u128) -> Result<(u128, u32)> { Ok(gcore::exec::pay_program_rent(program_id.into(), value)?) } diff --git a/gsys/src/lib.rs b/gsys/src/lib.rs index daf6b517c75..43f3ed4a1b5 100644 --- a/gsys/src/lib.rs +++ b/gsys/src/lib.rs @@ -539,6 +539,7 @@ extern "C" { /// Arguments type: /// - `rent_pid`: `const ptr` for program id and rent value. /// - `err_bn_value`: `mut ptr` for concatenated error code, paid block count and unused rent value. + #[deprecated] pub fn gr_pay_program_rent( rent_pid: *const HashWithValue, err_bn_value: *mut ErrorWithBlockNumberAndValue, diff --git a/gtest/src/lib.rs b/gtest/src/lib.rs index 40fab30a57a..40def872acb 100644 --- a/gtest/src/lib.rs +++ b/gtest/src/lib.rs @@ -489,10 +489,6 @@ pub mod constants { pub const RESERVATION_COST: Gas = 100; /// Cost of storing delayed message per block. pub const DISPATCH_HOLD_COST: Gas = 100; - /// Cost of storing program per block. - /// - /// (!) Currently disabled: storing programs are free. - pub const RENT_COST: Value = 330; /* Execution-related constants */ // TODO: use proper weights of instantiation and instrumentation (#3509). diff --git a/gtest/src/manager.rs b/gtest/src/manager.rs index 8a74a78c129..8427f0b5227 100644 --- a/gtest/src/manager.rs +++ b/gtest/src/manager.rs @@ -22,8 +22,7 @@ use crate::{ Result, TestError, DISPATCH_HOLD_COST, EPOCH_DURATION_IN_BLOCKS, EXISTENTIAL_DEPOSIT, INITIAL_RANDOM_SEED, MAILBOX_THRESHOLD, MAX_RESERVATIONS, MODULE_INSTANTIATION_BYTE_COST, MODULE_INSTRUMENTATION_BYTE_COST, MODULE_INSTRUMENTATION_COST, READ_COST, READ_PER_BYTE_COST, - RENT_COST, RESERVATION_COST, RESERVE_FOR, VALUE_PER_GAS, WAITLIST_COST, WRITE_COST, - WRITE_PER_BYTE_COST, + RESERVATION_COST, RESERVE_FOR, VALUE_PER_GAS, WAITLIST_COST, WRITE_COST, WRITE_PER_BYTE_COST, }; use core_processor::{ common::*, @@ -873,7 +872,6 @@ impl ExtManager { max_reservations: MAX_RESERVATIONS, code_instrumentation_cost: MODULE_INSTRUMENTATION_COST, code_instrumentation_byte_cost: MODULE_INSTRUMENTATION_BYTE_COST, - rent_cost: RENT_COST, gas_multiplier: gsys::GasMultiplier::from_value_per_gas(VALUE_PER_GAS), }; @@ -1213,8 +1211,6 @@ impl JournalHandler for ExtManager { fn send_signal(&mut self, _message_id: MessageId, _destination: ProgramId, _code: SignalCode) {} - fn pay_program_rent(&mut self, _payer: ProgramId, _program_id: ProgramId, _block_count: u32) {} - fn reply_deposit(&mut self, _message_id: MessageId, future_reply_id: MessageId, amount: u64) { self.gas_limits.insert(future_reply_id, amount); } diff --git a/pallets/gear-debug/src/tests/mod.rs b/pallets/gear-debug/src/tests/mod.rs index bff7eb55bc9..a923b2dbf21 100644 --- a/pallets/gear-debug/src/tests/mod.rs +++ b/pallets/gear-debug/src/tests/mod.rs @@ -18,13 +18,8 @@ use super::*; use crate::mock::*; -use common::{ - self, - event::MessageEntry, - scheduler::{ScheduledTask, TaskPool}, - ActiveProgram, CodeStorage, Origin as _, PausedProgramStorage, ProgramStorage, -}; -use frame_support::{assert_err, assert_ok}; +use common::{self, event::MessageEntry, CodeStorage, Origin as _}; +use frame_support::assert_ok; use gear_core::{ ids::{CodeId, MessageId, ProgramId}, memory::PageBuf, @@ -32,11 +27,9 @@ use gear_core::{ pages::{GearPage, PageNumber, PageU32Size, WasmPage}, }; use gear_wasm_instrument::STACK_END_EXPORT_NAME; -use pallet_gear::{ - DebugInfo, Event, Pallet as PalletGear, ProgramStorageOf, RentCostPerBlockOf, TaskPoolOf, -}; +use pallet_gear::{DebugInfo, Event, Pallet as PalletGear}; use parity_scale_codec::Encode; -use sp_core::{Get, H256}; +use sp_core::H256; use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet}; mod utils; @@ -921,114 +914,3 @@ fn check_gear_stack_end() { ); }) } - -#[test] -fn disabled_program_rent() { - use test_syscalls::{Kind, WASM_BINARY as TEST_SYSCALLS_BINARY}; - - assert!(!<::ProgramRentEnabled as Get>::get()); - assert!(::ProgramRentDisabledDelta::get() > 0); - - init_logger(); - new_test_ext().execute_with(|| { - let salt = b"salt".to_vec(); - let pay_rent_id = - ProgramId::generate_from_user(CodeId::generate(TEST_SYSCALLS_BINARY), &salt); - - let program_value = 10_000_000; - assert_ok!(Gear::upload_program( - RuntimeOrigin::signed(1), - TEST_SYSCALLS_BINARY.to_vec(), - salt, - pay_rent_id.into_bytes().to_vec(), - 20_000_000_000, - program_value, - false, - )); - - run_to_next_block(None); - - let old_block = utils::get_active_program(pay_rent_id).expiration_block; - - let block_count = 2_000u32; - let rent = RentCostPerBlockOf::::get() * u128::from(block_count); - let pay_rent_account_id = pay_rent_id.cast::(); - let balance_before = Balances::free_balance(pay_rent_account_id); - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(1), - pay_rent_id, - vec![Kind::PayProgramRent( - pay_rent_id.into_origin().into(), - rent, - None - )] - .encode(), - 20_000_000_000, - 0, - false, - )); - - run_to_next_block(None); - - assert_eq!(utils::maybe_last_message(1).unwrap().payload_bytes(), b"ok"); - - // check that syscall does nothing - assert_eq!( - old_block, - utils::get_active_program(pay_rent_id).expiration_block - ); - assert_eq!(balance_before, Balances::free_balance(pay_rent_account_id)); - - assert!(!ProgramStorageOf::::paused_program_exists( - &pay_rent_id - )); - - // extrinsic should fail - let block_count = 10_000; - assert_err!( - Gear::pay_program_rent(RuntimeOrigin::signed(2), pay_rent_id, block_count), - pallet_gear::Error::::ProgramRentDisabled - ); - - // resume extrinsic should also fail - assert_err!( - Gear::resume_session_init( - RuntimeOrigin::signed(2), - pay_rent_id, - Default::default(), - Default::default(), - ), - pallet_gear::Error::::ProgramRentDisabled - ); - assert_err!( - Gear::resume_session_push(RuntimeOrigin::signed(2), 5, Default::default(),), - pallet_gear::Error::::ProgramRentDisabled - ); - assert_err!( - Gear::resume_session_commit(RuntimeOrigin::signed(2), 5, Default::default(),), - pallet_gear::Error::::ProgramRentDisabled - ); - - let expected_block = utils::get_active_program(pay_rent_id).expiration_block; - - System::set_block_number(expected_block - 1); - Gear::set_block_number(expected_block - 1); - - run_to_next_block(None); - - assert!(!ProgramStorageOf::::paused_program_exists( - &pay_rent_id - )); - - let program = utils::get_active_program(pay_rent_id); - - assert_eq!( - expected_block + ::ProgramRentDisabledDelta::get(), - program.expiration_block - ); - assert!(TaskPoolOf::::contains( - &program.expiration_block, - &ScheduledTask::PauseProgram(pay_rent_id) - )); - }) -} diff --git a/pallets/gear-debug/src/tests/utils.rs b/pallets/gear-debug/src/tests/utils.rs index 8cd1750e85a..5a1501120b4 100644 --- a/pallets/gear-debug/src/tests/utils.rs +++ b/pallets/gear-debug/src/tests/utils.rs @@ -37,23 +37,3 @@ pub fn parse_wat(source: &str) -> Vec { pub fn h256_code_hash(code: &[u8]) -> H256 { CodeId::generate(code).into_origin() } - -#[track_caller] -pub fn get_active_program(program_id: ProgramId) -> ActiveProgram { - ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist") -} - -#[track_caller] -pub(super) fn maybe_last_message(account: AccountId) -> Option { - System::events() - .into_iter() - .rev() - .find_map(|e| match e.event { - RuntimeEvent::Gear(Event::UserMessageSent { message, .. }) => { - (message.destination() == account.into()).then_some(message) - } - _ => None, - }) -} diff --git a/pallets/gear/src/benchmarking/mod.rs b/pallets/gear/src/benchmarking/mod.rs index f203a0ba2e2..d6627afe3a8 100644 --- a/pallets/gear/src/benchmarking/mod.rs +++ b/pallets/gear/src/benchmarking/mod.rs @@ -60,19 +60,14 @@ use crate::{ schedule::{API_BENCHMARK_BATCH_SIZE, INSTR_BENCHMARK_BATCH_SIZE}, BalanceOf, BenchmarkStorage, BlockNumberFor, Call, Config, CurrencyOf, Event, Ext as Externalities, GasHandlerOf, GearBank, MailboxOf, Pallet as Gear, Pallet, - ProgramStorageOf, QueueOf, RentFreePeriodOf, ResumeMinimalPeriodOf, Schedule, TaskPoolOf, -}; -use ::alloc::{ - collections::{BTreeMap, BTreeSet}, - vec, + ProgramStorageOf, QueueOf, Schedule, TaskPoolOf, }; +use ::alloc::{collections::BTreeMap, vec}; use common::{ self, benchmarking, - paused_program_storage::SessionId, scheduler::{ScheduledTask, TaskHandler}, storage::{Counter, *}, - ActiveProgram, CodeMetadata, CodeStorage, GasTree, Origin, PausedProgramStorage, - ProgramStorage, ReservableTree, + ActiveProgram, CodeMetadata, CodeStorage, GasTree, Origin, ProgramStorage, ReservableTree, }; use core_processor::{ common::{DispatchOutcome, JournalNote}, @@ -91,7 +86,7 @@ use gear_core::{ ids::{CodeId, MessageId, ProgramId}, memory::{AllocationsContext, Memory, PageBuf}, message::{ContextSettings, DispatchKind, IncomingDispatch, MessageContext}, - pages::{GearPage, PageU32Size, WasmPage, GEAR_PAGE_SIZE, WASM_PAGE_SIZE}, + pages::{GearPage, PageU32Size, WasmPage}, reservation::GasReserver, }; use gear_core_backend::{ @@ -193,7 +188,6 @@ fn default_processor_context() -> ProcessorContext { existential_deposit: 42, program_id: Default::default(), program_candidates_data: Default::default(), - program_rents: Default::default(), host_fn_weights: Default::default(), forbidden_funcs: Default::default(), mailbox_threshold: 500, @@ -202,7 +196,6 @@ fn default_processor_context() -> ProcessorContext { reserve_for: 0, reservation: 0, random_data: ([0u8; 32].to_vec(), 0), - rent_cost: 0, gas_multiplier: gsys::GasMultiplier::from_value_per_gas(30), } } @@ -242,13 +235,6 @@ where .unwrap_or_else(|e| unreachable!("core-processor logic invalidated: {}", e)) } -fn get_last_session_id() -> Option { - find_latest_event::(|event| match event { - Event::ProgramResumeSessionStarted { session_id, .. } => Some(session_id), - _ => None, - }) -} - pub fn find_latest_event(mapping_filter: F) -> Option where T: Config, @@ -266,39 +252,6 @@ where .find_map(mapping_filter) } -#[track_caller] -fn resume_session_prepare( - c: u32, - program_id: ProgramId, - program: ActiveProgram>, - caller: T::AccountId, - memory_page: &PageBuf, -) -> (SessionId, Vec<(GearPage, PageBuf)>) -where - T::AccountId: Origin, -{ - ProgramStorageOf::::pause_program(program_id, 100u32.into()).unwrap(); - - Gear::::resume_session_init( - RawOrigin::Signed(caller).into(), - program_id, - program.allocations, - program.code_hash.cast(), - ) - .expect("failed to start resume session"); - - let memory_pages = { - let mut pages = Vec::with_capacity(c as usize); - for i in 0..c { - pages.push((GearPage::from(i as u16), memory_page.clone())); - } - - pages - }; - - (get_last_session_id::().unwrap(), memory_pages) -} - /// An instantiated and deployed program. #[derive(Clone)] struct Program { @@ -500,130 +453,6 @@ benchmarks! { assert!(MailboxOf::::is_empty(&caller)); } - pay_program_rent { - let caller = benchmarking::account("caller", 0, 0); - CurrencyOf::::deposit_creating(&caller, 200_000_000_000_000u128.unique_saturated_into()); - let minimum_balance = CurrencyOf::::minimum_balance(); - let code = benchmarking::generate_wasm(16.into()).unwrap(); - let salt = vec![]; - let program_id = ProgramId::generate_from_user(CodeId::generate(&code), &salt); - Gear::::upload_program(RawOrigin::Signed(caller.clone()).into(), code, salt, b"init_payload".to_vec(), 10_000_000_000, 0u32.into(), false).expect("submit program failed"); - - let block_count = 1_000u32.into(); - - init_block::(None); - }: _(RawOrigin::Signed(caller.clone()), program_id, block_count) - verify { - let program: ActiveProgram<_> = ProgramStorageOf::::get_program(program_id) - .expect("program should exist") - .try_into() - .expect("program should be active"); - assert_eq!(program.expiration_block, RentFreePeriodOf::::get() + block_count); - } - - resume_session_init { - let caller = benchmarking::account("caller", 0, 0); - CurrencyOf::::deposit_creating(&caller, 200_000_000_000_000u128.unique_saturated_into()); - let code = benchmarking::generate_wasm(16.into()).unwrap(); - let salt = vec![]; - let program_id = ProgramId::generate_from_user(CodeId::generate(&code), &salt); - Gear::::upload_program(RawOrigin::Signed(caller.clone()).into(), code, salt, b"init_payload".to_vec(), 10_000_000_000, 0u32.into(), false).expect("submit program failed"); - - init_block::(None); - - let program: ActiveProgram<_> = ProgramStorageOf::::get_program(program_id) - .expect("program should exist") - .try_into() - .expect("program should be active"); - ProgramStorageOf::::pause_program(program_id, 100u32.into()).unwrap(); - }: _(RawOrigin::Signed(caller.clone()), program_id, program.allocations, program.code_hash.cast()) - verify { - assert!(ProgramStorageOf::::paused_program_exists(&program_id)); - assert!( - !Gear::::is_active(program_id) - ); - assert!(!ProgramStorageOf::::program_exists(program_id)); - } - - resume_session_push { - let c in 0 .. 16 * (WASM_PAGE_SIZE / GEAR_PAGE_SIZE) as u32; - let caller = benchmarking::account("caller", 0, 0); - CurrencyOf::::deposit_creating(&caller, 200_000_000_000_000u128.unique_saturated_into()); - let code = benchmarking::generate_wasm(16.into()).unwrap(); - let salt = vec![]; - let program_id = ProgramId::generate_from_user(CodeId::generate(&code), &salt); - Gear::::upload_program(RawOrigin::Signed(caller.clone()).into(), code, salt, b"init_payload".to_vec(), 10_000_000_000, 0u32.into(), false,).expect("submit program failed"); - - init_block::(None); - - let program: ActiveProgram<_> = ProgramStorageOf::::get_program(program_id) - .expect("program should exist") - .try_into() - .expect("program should be active"); - - let memory_page = { - let mut page = PageBuf::new_zeroed(); - page[0] = 1; - - page - }; - - let (session_id, memory_pages) = resume_session_prepare::(c, program_id, program, caller.clone(), &memory_page); - }: _(RawOrigin::Signed(caller.clone()), session_id, memory_pages) - verify { - assert!( - matches!(ProgramStorageOf::::resume_session_page_count(&session_id), Some(count) if count == c) - ); - assert!(ProgramStorageOf::::paused_program_exists(&program_id)); - assert!( - !Gear::::is_active(program_id) - ); - assert!(!ProgramStorageOf::::program_exists(program_id)); - } - - resume_session_commit { - let c in 0 .. (MAX_PAGES - 1) * (WASM_PAGE_SIZE / GEAR_PAGE_SIZE) as u32; - let caller = benchmarking::account("caller", 0, 0); - CurrencyOf::::deposit_creating(&caller, 400_000_000_000_000u128.unique_saturated_into()); - let code = benchmarking::generate_wasm(0.into()).unwrap(); - let salt = vec![]; - let program_id = ProgramId::generate_from_user(CodeId::generate(&code), &salt); - Gear::::upload_program(RawOrigin::Signed(caller.clone()).into(), code, salt, b"init_payload".to_vec(), 10_000_000_000, 0u32.into(), false,).expect("submit program failed"); - - init_block::(None); - - let memory_page = { - let mut page = PageBuf::new_zeroed(); - page[0] = 1; - - page - }; - - let program: ActiveProgram<_> = ProgramStorageOf::::update_active_program(program_id, |program| { - for i in 0 .. c { - let page = GearPage::from(i as u16); - ProgramStorageOf::::set_program_page_data(program_id, program.memory_infix, page, memory_page.clone()); - program.pages_with_data.insert(page); - } - - let wasm_pages = (c as usize * GEAR_PAGE_SIZE) / WASM_PAGE_SIZE; - program.allocations = BTreeSet::from_iter((0..wasm_pages).map(|i| WasmPage::from(i as u16))); - - program.clone() - }).expect("program should exist"); - - let (session_id, memory_pages) = resume_session_prepare::(c, program_id, program, caller.clone(), &memory_page); - - Gear::::resume_session_push(RawOrigin::Signed(caller.clone()).into(), session_id, memory_pages).expect("failed to append memory pages"); - }: _(RawOrigin::Signed(caller.clone()), session_id, ResumeMinimalPeriodOf::::get()) - verify { - assert!(ProgramStorageOf::::program_exists(program_id)); - assert!( - Gear::::is_active(program_id) - ); - assert!(!ProgramStorageOf::::paused_program_exists(&program_id)); - } - // This constructs a program that is maximal expensive to instrument. // It creates a maximum number of metering blocks per byte. // @@ -1577,9 +1406,6 @@ benchmarks! { }: { res.replace(run_process(exec)); } - verify { - verify_process(res.unwrap()); - } lazy_pages_signal_read { let p in 0 .. code::max_pages::() as u32; @@ -2767,13 +2593,6 @@ benchmarks! { sbox.invoke(); } - tasks_remove_resume_session { - let session_id = tasks::remove_resume_session::(); - let mut ext_manager = ExtManager::::default(); - }: { - ext_manager.remove_resume_session(session_id); - } - tasks_remove_gas_reservation { let (program_id, reservation_id) = tasks::remove_gas_reservation::(); let mut ext_manager = ExtManager::::default(); @@ -2829,27 +2648,6 @@ benchmarks! { ext_manager.remove_from_mailbox(user.cast(), message_id); } - tasks_pause_program { - let c in 0 .. (MAX_PAGES - 1) * (WASM_PAGE_SIZE / GEAR_PAGE_SIZE) as u32; - - let code = benchmarking::generate_wasm(0.into()).unwrap(); - let program_id = tasks::pause_program_prepare::(c, code); - - let mut ext_manager = ExtManager::::default(); - }: { - ext_manager.pause_program(program_id); - } - - tasks_pause_program_uninited { - let c in 0 .. (MAX_PAGES - 1) * (WASM_PAGE_SIZE / GEAR_PAGE_SIZE) as u32; - - let program_id = tasks::pause_program_prepare::(c, demo_init_wait::WASM_BINARY.to_vec()); - - let mut ext_manager = ExtManager::::default(); - }: { - ext_manager.pause_program(program_id); - } - // This is no benchmark. It merely exist to have an easy way to pretty print the currently // configured `Schedule` during benchmark development. // It can be outputted using the following command: diff --git a/pallets/gear/src/benchmarking/tasks.rs b/pallets/gear/src/benchmarking/tasks.rs index 647d376565b..0107a1409d0 100644 --- a/pallets/gear/src/benchmarking/tasks.rs +++ b/pallets/gear/src/benchmarking/tasks.rs @@ -44,97 +44,6 @@ where Gear::::process_queue(Default::default()); } -#[track_caller] -pub(super) fn pause_program_prepare(c: u32, code: Vec) -> ProgramId -where - T: Config, - T::AccountId: Origin, -{ - let caller = benchmarking::account("caller", 0, 0); - CurrencyOf::::deposit_creating(&caller, 400_000_000_000_000u128.unique_saturated_into()); - - init_block::(None); - - let salt = vec![]; - let program_id = ProgramId::generate_from_user(CodeId::generate(&code), &salt); - Gear::::upload_program( - RawOrigin::Signed(caller).into(), - code, - salt, - b"init_payload".to_vec(), - 10_000_000_000, - 0u32.into(), - false, - ) - .expect("submit program failed"); - - Gear::::process_queue(Default::default()); - - let memory_page = { - let mut page = PageBuf::new_zeroed(); - page[0] = 1; - - page - }; - - ProgramStorageOf::::update_active_program(program_id, |program| { - for i in 0..c { - let page = GearPage::from(i as u16); - ProgramStorageOf::::set_program_page_data( - program_id, - program.memory_infix, - page, - memory_page.clone(), - ); - program.pages_with_data.insert(page); - } - - let wasm_pages = (c as usize * GEAR_PAGE_SIZE) / WASM_PAGE_SIZE; - program.allocations = - BTreeSet::from_iter((0..wasm_pages).map(|i| WasmPage::from(i as u16))); - }) - .expect("program should exist"); - - program_id -} - -#[track_caller] -pub(super) fn remove_resume_session() -> SessionId -where - T: Config, - T::AccountId: Origin, -{ - let caller = benchmarking::account("caller", 0, 0); - CurrencyOf::::deposit_creating(&caller, 200_000_000_000_000u128.unique_saturated_into()); - let code = benchmarking::generate_wasm(16.into()).unwrap(); - let salt = vec![]; - let program_id = ProgramId::generate_from_user(CodeId::generate(&code), &salt); - Gear::::upload_program( - RawOrigin::Signed(caller.clone()).into(), - code, - salt, - b"init_payload".to_vec(), - 10_000_000_000, - 0u32.into(), - false, - ) - .expect("submit program failed"); - - init_block::(None); - - ProgramStorageOf::::pause_program(program_id, 100u32.into()).unwrap(); - - Gear::::resume_session_init( - RawOrigin::Signed(caller).into(), - program_id, - Default::default(), - CodeId::default(), - ) - .expect("failed to start resume session"); - - get_last_session_id::().unwrap() -} - #[track_caller] pub(super) fn remove_gas_reservation() -> (ProgramId, ReservationId) where diff --git a/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs b/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs index 939fcd020ba..6a9009cda36 100644 --- a/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs +++ b/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs @@ -29,7 +29,7 @@ use super::*; -use crate::{BlockGasLimitOf, CurrencyOf, Event, RentCostPerBlockOf, String, WaitlistOf}; +use crate::{BlockGasLimitOf, CurrencyOf, Event, String, WaitlistOf}; use common::event::DispatchStatus; use frame_support::traits::Randomness; use gear_core::ids::{CodeId, ReservationId}; @@ -37,7 +37,6 @@ use gear_core_errors::{ReplyCode, SuccessReplyReason}; use gear_wasm_instrument::syscalls::SyscallName; use pallet_timestamp::Pallet as TimestampPallet; use parity_scale_codec::Decode; -use sp_runtime::SaturatedConversion; use test_syscalls::{Kind, WASM_BINARY as SYSCALLS_TEST_WASM_BINARY}; pub fn read_big_state() @@ -269,40 +268,11 @@ where SyscallName::ReservationReply => check_gr_reservation_reply::(), SyscallName::ReservationReplyCommit => check_gr_reservation_reply_commit::(), SyscallName::SystemReserveGas => check_gr_system_reserve_gas::(), - SyscallName::PayProgramRent => check_gr_pay_program_rent::(), + SyscallName::PayProgramRent => { /*no need for tests */ } } }); } -fn check_gr_pay_program_rent() -where - T: Config, - T::AccountId: Origin, -{ - run_tester::(|tester_pid, _| { - let default_account = utils::default_account(); - CurrencyOf::::deposit_creating( - &default_account, - 100_000_000_000_000_u128.unique_saturated_into(), - ); - - let block_count = 10; - let unused_rent: BalanceOf = 1u32.into(); - let rent = RentCostPerBlockOf::::get() * block_count.into() + unused_rent; - let mp = MessageParamsBuilder::new( - vec![Kind::PayProgramRent( - tester_pid.into_origin().into(), - rent.saturated_into(), - Some((unused_rent.saturated_into(), block_count)), - )] - .encode(), - ) - .with_value(50_000_000_000_000); - - (TestCall::send_message(mp), None::) - }); -} - fn check_gr_system_reserve_gas() where T: Config, diff --git a/pallets/gear/src/benchmarking/utils.rs b/pallets/gear/src/benchmarking/utils.rs index e17a4e5c9f1..0a569512727 100644 --- a/pallets/gear/src/benchmarking/utils.rs +++ b/pallets/gear/src/benchmarking/utils.rs @@ -22,7 +22,7 @@ use super::Exec; use crate::{ manager::{CodeInfo, ExtManager, HandleKind}, Config, CostsPerBlockOf, CurrencyOf, DbWeightOf, MailboxOf, Pallet as Gear, ProgramStorageOf, - QueueOf, RentCostPerBlockOf, + QueueOf, }; use common::{scheduler::SchedulingCostsPerBlock, storage::*, CodeStorage, Origin, ProgramStorage}; use core_processor::{ @@ -83,7 +83,6 @@ where max_reservations: T::ReservationsLimit::get(), code_instrumentation_cost: schedule.code_instrumentation_cost.ref_time(), code_instrumentation_byte_cost: schedule.code_instrumentation_byte_cost.ref_time(), - rent_cost: RentCostPerBlockOf::::get().unique_saturated_into(), gas_multiplier: ::GasMultiplier::get().into(), } } diff --git a/pallets/gear/src/internal.rs b/pallets/gear/src/internal.rs index af4cc41d665..12edb521b9d 100644 --- a/pallets/gear/src/internal.rs +++ b/pallets/gear/src/internal.rs @@ -19,21 +19,21 @@ //! Internal details of Gear Pallet implementation. use crate::{ - Authorship, Config, CostsPerBlockOf, CurrencyOf, DispatchStashOf, Event, ExtManager, - GasBalanceOf, GasHandlerOf, GasNodeIdOf, GearBank, MailboxOf, Pallet, QueueOf, - SchedulingCostOf, TaskPoolOf, WaitlistOf, + Config, CostsPerBlockOf, CurrencyOf, DispatchStashOf, Event, ExtManager, GasBalanceOf, + GasHandlerOf, GasNodeIdOf, GearBank, MailboxOf, Pallet, QueueOf, SchedulingCostOf, TaskPoolOf, + WaitlistOf, }; use alloc::collections::BTreeSet; use common::{ event::{ MessageWaitedReason, MessageWaitedRuntimeReason::*, - MessageWaitedSystemReason::ProgramIsNotInitialized, MessageWokenReason, ProgramChangeKind, - Reason::*, UserMessageReadReason, + MessageWaitedSystemReason::ProgramIsNotInitialized, MessageWokenReason, Reason::*, + UserMessageReadReason, }, gas_provider::{GasNodeId, Imbalance}, scheduler::*, storage::*, - ActiveProgram, GasTree, LockId, LockableTree, Origin, + GasTree, LockId, LockableTree, Origin, }; use core::cmp::{Ord, Ordering}; use core_processor::common::ActorExecutionErrorReplyReason; @@ -46,12 +46,7 @@ use gear_core::{ UserStoredMessage, }, }; -use sp_runtime::{ - traits::{ - Bounded, CheckedAdd, Get, One, SaturatedConversion, Saturating, UniqueSaturatedInto, Zero, - }, - DispatchError, -}; +use sp_runtime::traits::{Get, One, SaturatedConversion, Saturating, UniqueSaturatedInto, Zero}; /// [`HoldBound`] builder #[derive(Clone, Debug)] @@ -950,58 +945,6 @@ where inheritor } - pub(crate) fn pay_program_rent_impl( - program_id: ProgramId, - program: &mut ActiveProgram>, - from: &T::AccountId, - block_count: BlockNumberFor, - ) -> Result<(), DispatchError> { - if !::ProgramRentEnabled::get() { - return Ok(()); - } - - let old_expiration_block = program.expiration_block; - let (new_expiration_block, blocks_to_pay) = old_expiration_block - .checked_add(&block_count) - .map(|count| (count, block_count)) - .unwrap_or_else(|| { - let max = BlockNumberFor::::max_value(); - - (max, max - old_expiration_block) - }); - - if blocks_to_pay.is_zero() { - return Ok(()); - } - - let block_author = Authorship::::author() - .unwrap_or_else(|| unreachable!("Failed to find block author!")); - CurrencyOf::::transfer( - from, - &block_author, - Self::rent_fee_for(blocks_to_pay), - ExistenceRequirement::AllowDeath, - )?; - - let task = ScheduledTask::PauseProgram(program_id); - TaskPoolOf::::delete(old_expiration_block, task.clone()) - .unwrap_or_else(|e| unreachable!("Scheduling logic invalidated! {:?}", e)); - - program.expiration_block = new_expiration_block; - - TaskPoolOf::::add(new_expiration_block, task) - .unwrap_or_else(|e| unreachable!("Scheduling logic invalidated! {:?}", e)); - - Self::deposit_event(Event::ProgramChanged { - id: program_id, - change: ProgramChangeKind::ExpirationChanged { - expiration: new_expiration_block, - }, - }); - - Ok(()) - } - /// This fn and [`split_with_value`] works the same: they call api of gas /// handler to split (optionally with value) for all cases except reply /// sent and contains deposit in storage. diff --git a/pallets/gear/src/lib.rs b/pallets/gear/src/lib.rs index 59260c47fcd..ab52a4fa5b4 100644 --- a/pallets/gear/src/lib.rs +++ b/pallets/gear/src/lib.rs @@ -73,16 +73,14 @@ use frame_system::pallet_prelude::{BlockNumberFor, *}; use gear_core::{ code::{Code, CodeAndId, InstrumentedCode, InstrumentedCodeAndId}, ids::{CodeId, MessageId, ProgramId, ReservationId}, - memory::PageBuf, message::*, - pages::{GearPage, WasmPage}, percent::Percent, }; use manager::{CodeInfo, QueuePostProcessingData}; use pallet_gear_voucher::{PrepaidCall, PrepaidCallsDispatcher}; use primitive_types::H256; use sp_runtime::{ - traits::{One, Saturating, UniqueSaturatedInto, Zero}, + traits::{Bounded, One, Saturating, UniqueSaturatedInto, Zero}, SaturatedConversion, }; use sp_std::{ @@ -115,10 +113,6 @@ pub type GasNodeIdOf = as GasTree>::NodeId; pub type BlockGasLimitOf = <::BlockLimiter as BlockLimiter>::BlockGasLimit; pub type GasBalanceOf = <::GasProvider as GasProvider>::Balance; pub type ProgramStorageOf = ::ProgramStorage; -pub type RentFreePeriodOf = ::ProgramRentFreePeriod; -pub type RentCostPerBlockOf = ::ProgramRentCostPerBlock; -pub type ResumeMinimalPeriodOf = ::ProgramResumeMinimalRentPeriod; -pub type ResumeSessionDurationOf = ::ProgramResumeSessionDuration; pub(crate) type GearBank = pallet_gear_bank::Pallet; /// The current storage version. @@ -608,7 +602,7 @@ pub mod pallet { program_id, &code_info, message_id, - block_number.saturating_add(RentFreePeriodOf::::get()), + block_number, ); Self::create( @@ -1036,7 +1030,6 @@ pub mod pallet { max_reservations: T::ReservationsLimit::get(), code_instrumentation_cost: schedule.code_instrumentation_cost.ref_time(), code_instrumentation_byte_cost: schedule.code_instrumentation_byte_cost.ref_time(), - rent_cost: RentCostPerBlockOf::::get().unique_saturated_into(), gas_multiplier: ::GasMultiplier::get().into(), } } @@ -1194,20 +1187,19 @@ pub mod pallet { let message_id = Self::next_message_id(origin); let block_number = Self::block_number(); - let expiration_block = block_number.saturating_add(RentFreePeriodOf::::get()); ExtManager::::default().set_program( packet.destination(), &code_info, message_id, - expiration_block, + block_number, ); let program_id = packet.destination(); let program_event = Event::ProgramChanged { id: program_id, change: ProgramChangeKind::ProgramSet { - expiration: expiration_block, + expiration: BlockNumberFor::::max_value(), }, }; @@ -1231,20 +1223,14 @@ pub mod pallet { QueueOf::::queue(dispatch) .unwrap_or_else(|e| unreachable!("Messages storage corrupted: {e:?}")); - let task = ScheduledTask::PauseProgram(program_id); - TaskPoolOf::::add(expiration_block, task) - .unwrap_or_else(|e| unreachable!("Scheduling logic invalidated! {:?}", e)); - Self::deposit_event(program_event); Self::deposit_event(event); Ok(()) } - pub fn rent_fee_for(block_count: BlockNumberFor) -> BalanceOf { - let block_count: u64 = block_count.unique_saturated_into(); - - RentCostPerBlockOf::::get().saturating_mul(block_count.unique_saturated_into()) + pub fn run_call(max_gas: Option>) -> Call { + Call::run { max_gas } } } @@ -1622,172 +1608,6 @@ pub mod pallet { Ok(()) } - - /// Pay additional rent for the program. - #[pallet::call_index(8)] - #[pallet::weight(::WeightInfo::pay_program_rent())] - pub fn pay_program_rent( - origin: OriginFor, - program_id: ProgramId, - block_count: BlockNumberFor, - ) -> DispatchResultWithPostInfo { - let who = ensure_signed(origin)?; - - ensure!( - ::ProgramRentEnabled::get(), - Error::::ProgramRentDisabled, - ); - - ProgramStorageOf::::update_active_program( - program_id, - |program| -> Result<(), Error> { - Self::pay_program_rent_impl(program_id, program, &who, block_count) - .map_err(|_| Error::::InsufficientBalance) - }, - )??; - - Ok(().into()) - } - - /// Starts a resume session of the previously paused program. - /// - /// The origin must be Signed. - /// - /// Parameters: - /// - `program_id`: id of the program to resume. - /// - `allocations`: memory allocations of program prior to stop. - /// - `code_hash`: id of the program binary code. - #[pallet::call_index(9)] - #[pallet::weight(::WeightInfo::resume_session_init())] - pub fn resume_session_init( - origin: OriginFor, - program_id: ProgramId, - allocations: BTreeSet, - code_hash: CodeId, - ) -> DispatchResultWithPostInfo { - let who = ensure_signed(origin)?; - - ensure!( - ::ProgramRentEnabled::get(), - Error::::ProgramRentDisabled - ); - - let session_end_block = - Self::block_number().saturating_add(ResumeSessionDurationOf::::get()); - let session_id = ProgramStorageOf::::resume_session_init( - who.clone(), - session_end_block, - program_id, - allocations, - code_hash, - )?; - - let task = ScheduledTask::RemoveResumeSession(session_id); - TaskPoolOf::::add(session_end_block, task) - .unwrap_or_else(|e| unreachable!("Scheduling logic invalidated! {:?}", e)); - - Self::deposit_event(Event::ProgramResumeSessionStarted { - session_id, - account_id: who, - program_id, - session_end_block, - }); - - Ok(().into()) - } - - /// Appends memory pages to the resume session. - /// - /// The origin must be Signed and should be the owner of the session. - /// - /// Parameters: - /// - `session_id`: id of the resume session. - /// - `memory_pages`: program memory (or its part) before it was paused. - #[pallet::call_index(10)] - #[pallet::weight(::WeightInfo::resume_session_push(memory_pages.len() as u32))] - pub fn resume_session_push( - origin: OriginFor, - session_id: SessionId, - memory_pages: Vec<(GearPage, PageBuf)>, - ) -> DispatchResultWithPostInfo { - let who = ensure_signed(origin)?; - - ensure!( - ::ProgramRentEnabled::get(), - Error::::ProgramRentDisabled - ); - - ProgramStorageOf::::resume_session_push(session_id, who, memory_pages)?; - - Ok(().into()) - } - - /// Finishes the program resume session. - /// - /// The origin must be Signed and should be the owner of the session. - /// - /// Parameters: - /// - `session_id`: id of the resume session. - /// - `block_count`: the specified period of rent. - #[pallet::call_index(11)] - #[pallet::weight(DbWeightOf::::get().reads(1) + ::WeightInfo::resume_session_commit(ProgramStorageOf::::resume_session_page_count(session_id).unwrap_or(0)))] - pub fn resume_session_commit( - origin: OriginFor, - session_id: SessionId, - block_count: BlockNumberFor, - ) -> DispatchResultWithPostInfo { - let who = ensure_signed(origin)?; - - ensure!( - ::ProgramRentEnabled::get(), - Error::::ProgramRentDisabled - ); - - ensure!( - block_count >= ResumeMinimalPeriodOf::::get(), - Error::::ResumePeriodLessThanMinimal - ); - - let rent_fee = Self::rent_fee_for(block_count); - ensure!( - CurrencyOf::::free_balance(&who) >= rent_fee, - Error::::InsufficientBalance - ); - - let result = ProgramStorageOf::::resume_session_commit( - session_id, - who.clone(), - Self::block_number().saturating_add(block_count), - )?; - - let task = ScheduledTask::RemoveResumeSession(session_id); - TaskPoolOf::::delete(result.end_block, task) - .unwrap_or_else(|e| unreachable!("Scheduling logic invalidated! {:?}", e)); - - let block_author = Authorship::::author() - .unwrap_or_else(|| unreachable!("Failed to find block author!")); - if let Some((program_id, expiration_block)) = result.info { - let task = ScheduledTask::PauseProgram(program_id); - TaskPoolOf::::add(expiration_block, task) - .unwrap_or_else(|e| unreachable!("Scheduling logic invalidated! {:?}", e)); - - CurrencyOf::::transfer( - &who, - &block_author, - rent_fee, - ExistenceRequirement::AllowDeath, - )?; - - Self::deposit_event(Event::ProgramChanged { - id: program_id, - change: ProgramChangeKind::Active { - expiration: expiration_block, - }, - }); - } - - Ok(().into()) - } } impl Pallet diff --git a/pallets/gear/src/manager/journal.rs b/pallets/gear/src/manager/journal.rs index 6bbd2c5f566..b257d8237fe 100644 --- a/pallets/gear/src/manager/journal.rs +++ b/pallets/gear/src/manager/journal.rs @@ -20,7 +20,7 @@ use crate::{ internal::HoldBoundBuilder, manager::{CodeInfo, ExtManager}, Config, Event, GasAllowanceOf, GasHandlerOf, GasTree, GearBank, Pallet, ProgramStorageOf, - QueueOf, RentFreePeriodOf, TaskPoolOf, WaitlistOf, + QueueOf, TaskPoolOf, WaitlistOf, }; use common::{ event::*, @@ -39,7 +39,6 @@ use gear_core::{ reservation::GasReserver, }; use gear_core_errors::SignalCode; -use sp_core::Get as _; use sp_runtime::traits::{UniqueSaturatedInto, Zero}; use sp_std::{ collections::{btree_map::BTreeMap, btree_set::BTreeSet}, @@ -389,18 +388,12 @@ where for (init_message, candidate_id) in candidates { if !Pallet::::program_exists(candidate_id) { let block_number = Pallet::::block_number(); - let expiration_block = - block_number.saturating_add(RentFreePeriodOf::::get()); - self.set_program(candidate_id, &code_info, init_message, expiration_block); - - let task = ScheduledTask::PauseProgram(candidate_id); - TaskPoolOf::::add(expiration_block, task) - .unwrap_or_else(|e| unreachable!("Scheduling logic invalidated! {:?}", e)); + self.set_program(candidate_id, &code_info, init_message, block_number); Pallet::::deposit_event(Event::ProgramChanged { id: candidate_id, change: ProgramChangeKind::ProgramSet { - expiration: expiration_block, + expiration: block_number, }, }); } else { @@ -537,21 +530,6 @@ where Self::send_signal(self, message_id, destination, code) } - fn pay_program_rent(&mut self, payer: ProgramId, program_id: ProgramId, block_count: u32) { - let from = payer.cast(); - let block_count = block_count.unique_saturated_into(); - - ProgramStorageOf::::update_active_program(program_id, |program| { - Pallet::::pay_program_rent_impl(program_id, program, &from, block_count) - .unwrap_or_else(|e| unreachable!("Failed to transfer value: {:?}", e)); - }) - .unwrap_or_else(|e| { - log::debug!( - "Could not update active program {program_id}: {e:?}. Program is not active?" - ); - }); - } - fn reply_deposit(&mut self, message_id: MessageId, future_reply_id: MessageId, amount: u64) { log::debug!("Creating reply deposit {amount} gas for message id {future_reply_id}"); diff --git a/pallets/gear/src/manager/task.rs b/pallets/gear/src/manager/task.rs index 02d12383a28..21b3826b8aa 100644 --- a/pallets/gear/src/manager/task.rs +++ b/pallets/gear/src/manager/task.rs @@ -17,48 +17,31 @@ // along with this program. If not, see . use crate::{ - manager::ExtManager, weights::WeightInfo, Config, DbWeightOf, DispatchStashOf, Event, Pallet, - ProgramStorageOf, QueueOf, TaskPoolOf, WaitlistOf, + manager::ExtManager, weights::WeightInfo, Config, DispatchStashOf, Event, Pallet, QueueOf, }; use alloc::string::ToString; use common::{ event::{ - MessageWokenRuntimeReason, MessageWokenSystemReason, ProgramChangeKind, RuntimeReason, - SystemReason, UserMessageReadSystemReason, + MessageWokenRuntimeReason, MessageWokenSystemReason, RuntimeReason, SystemReason, + UserMessageReadSystemReason, }, paused_program_storage::SessionId, scheduler::*, storage::*, - ActiveProgram, Gas, Origin, PausedProgramStorage, Program, ProgramState, ProgramStorage, + Gas, Origin, }; use core::cmp; use gear_core::{ - code::MAX_WASM_PAGE_COUNT, ids::{CodeId, MessageId, ProgramId, ReservationId}, message::{DispatchKind, ReplyMessage}, - pages::{GEAR_PAGE_SIZE, WASM_PAGE_SIZE}, }; use gear_core_errors::{ErrorReplyReason, SignalCode}; -use sp_core::Get; -use sp_runtime::Saturating; pub fn get_maximum_task_gas(task: &ScheduledTask) -> Gas { use ScheduledTask::*; match task { - PauseProgram(_) => { - // TODO: #3079 - if ::ProgramRentEnabled::get() { - let count = - u32::from(MAX_WASM_PAGE_COUNT * (WASM_PAGE_SIZE / GEAR_PAGE_SIZE) as u16 / 2); - cmp::max( - ::WeightInfo::tasks_pause_program(count).ref_time(), - ::WeightInfo::tasks_pause_program_uninited(count).ref_time(), - ) - } else { - DbWeightOf::::get().writes(2).ref_time() - } - } + PauseProgram(_) => 0, RemoveCode(_) => todo!("#646"), RemoveFromMailbox(_, _) => { ::WeightInfo::tasks_remove_from_mailbox().ref_time() @@ -79,9 +62,7 @@ pub fn get_maximum_task_gas(task: &ScheduledTask) -> Ga RemoveGasReservation(_, _) => { ::WeightInfo::tasks_remove_gas_reservation().ref_time() } - RemoveResumeSession(_) => { - ::WeightInfo::tasks_remove_resume_session().ref_time() - } + RemoveResumeSession(_) => 0, } } @@ -89,126 +70,10 @@ impl TaskHandler for ExtManager where T::AccountId: Origin, { - fn pause_program(&mut self, program_id: ProgramId) -> Gas { - // - // TODO: #3079 - // - - if !::ProgramRentEnabled::get() { - log::debug!("Program rent logic is disabled."); - - let expiration_block = - ProgramStorageOf::::update_active_program(program_id, |program| { - program.expiration_block = program - .expiration_block - .saturating_add(::ProgramRentDisabledDelta::get()); - - program.expiration_block - }) - .unwrap_or_else(|e| { - unreachable!("PauseProgram task executes only for an active program: {e:?}.") - }); - - let task = ScheduledTask::PauseProgram(program_id); - TaskPoolOf::::add(expiration_block, task) - .unwrap_or_else(|e| unreachable!("Scheduling logic invalidated! {:?}", e)); - - return DbWeightOf::::get().writes(1).ref_time(); - } - - let program: ActiveProgram<_> = ProgramStorageOf::::get_program(program_id) - .unwrap_or_else(|| unreachable!("Program to pause not found.")) - .try_into() - .unwrap_or_else(|e| unreachable!("Pause program task logic corrupted: {e:?}")); - - let pages_with_data = program.pages_with_data.len() as u32; - - let ProgramState::Uninitialized { - message_id: init_message_id, - } = program.state - else { - // pause initialized program - let gas_reservation_map = - ProgramStorageOf::::pause_program(program_id, Pallet::::block_number()) - .unwrap_or_else(|e| unreachable!("Failed to pause program: {:?}", e)); - - // clean wait list from the messages - let reason = MessageWokenSystemReason::ProgramGotInitialized.into_reason(); - WaitlistOf::::drain_key(program_id).for_each(|entry| { - let message = Pallet::::wake_dispatch_requirements(entry, reason.clone()); - - QueueOf::::queue(message) - .unwrap_or_else(|e| unreachable!("Message queue corrupted! {:?}", e)); - }); - - Self::remove_gas_reservation_map(program_id, gas_reservation_map); - Pallet::::deposit_event(Event::ProgramChanged { - id: program_id, - change: ProgramChangeKind::Paused, - }); - - let gas = ::WeightInfo::tasks_pause_program(pages_with_data).ref_time(); - log::trace!("Task gas: tasks_pause_program = {gas}"); - - return gas; - }; - - // terminate uninitialized program - - // clean wait list from the messages - let reason = MessageWokenSystemReason::ProgramGotInitialized.into_reason(); - let origin = WaitlistOf::::drain_key(program_id) - .fold(None, |maybe_origin, entry| { - let message = Pallet::::wake_dispatch_requirements(entry, reason.clone()); - let result = match maybe_origin { - Some(_) => maybe_origin, - None if init_message_id == message.message().id() => { - Some(message.message().source()) - } - _ => None, - }; - - QueueOf::::queue(message) - .unwrap_or_else(|e| unreachable!("Message queue corrupted! {:?}", e)); - - result - }) - .unwrap_or_else(|| unreachable!("Failed to find init-message.")); - - ProgramStorageOf::::waiting_init_remove(program_id); - - // set program status to Terminated - ProgramStorageOf::::update_program_if_active(program_id, |p, _bn| { - match p { - Program::Active(program) => { - Self::remove_gas_reservation_map( - program_id, - core::mem::take(&mut program.gas_reservation_map), - ); - - Self::clean_inactive_program(program_id, program.memory_infix, origin); - } - _ => unreachable!("Action executed only for active program"), - } + fn pause_program(&mut self, _program_id: ProgramId) -> Gas { + log::debug!("Program rent logic is disabled."); - *p = Program::Terminated(origin); - }) - .unwrap_or_else(|e| { - unreachable!( - "Program terminated status may only be set to an existing active program: {e:?}" - ); - }); - - Pallet::::deposit_event(Event::ProgramChanged { - id: program_id, - change: ProgramChangeKind::Terminated, - }); - - let gas = - ::WeightInfo::tasks_pause_program_uninited(pages_with_data).ref_time(); - log::trace!("Task gas: tasks_pause_program_uninited = {gas}"); - - gas + 0 } fn remove_code(&mut self, _code_id: CodeId) -> Gas { @@ -408,13 +273,7 @@ where gas } - fn remove_resume_session(&mut self, session_id: SessionId) -> Gas { - ProgramStorageOf::::remove_resume_session(session_id) - .unwrap_or_else(|e| unreachable!("ProgramStorage corrupted! {:?}", e)); - - let gas = ::WeightInfo::tasks_remove_resume_session().ref_time(); - log::trace!("Task gas: tasks_remove_resume_session = {gas}"); - - gas + fn remove_resume_session(&mut self, _session_id: SessionId) -> Gas { + 0 } } diff --git a/pallets/gear/src/tests.rs b/pallets/gear/src/tests.rs index 3123ded0ca0..54d4538c475 100644 --- a/pallets/gear/src/tests.rs +++ b/pallets/gear/src/tests.rs @@ -47,12 +47,11 @@ use crate::{ runtime_api::RUNTIME_API_BLOCK_LIMITS_COUNT, BlockGasLimitOf, Config, CostsPerBlockOf, CurrencyOf, DbWeightOf, DispatchStashOf, Error, Event, GasAllowanceOf, GasBalanceOf, GasHandlerOf, GasInfo, GearBank, MailboxOf, - ProgramStorageOf, QueueOf, RentCostPerBlockOf, RentFreePeriodOf, ResumeMinimalPeriodOf, - ResumeSessionDurationOf, Schedule, TaskPoolOf, WaitlistOf, + ProgramStorageOf, QueueOf, Schedule, TaskPoolOf, WaitlistOf, }; use common::{ - event::*, scheduler::*, storage::*, ActiveProgram, CodeStorage, GasTree, LockId, LockableTree, - Origin as _, PausedProgramStorage, ProgramStorage, ReservableTree, + event::*, scheduler::*, storage::*, CodeStorage, GasTree, LockId, LockableTree, Origin as _, + ProgramStorage, ReservableTree, }; use core_processor::{common::ActorExecutionErrorReplyReason, ActorPrepareMemoryError}; use frame_support::{ @@ -6211,73 +6210,6 @@ fn terminated_locking_funds() { }); } -#[test] -fn pause_terminated_exited_program() { - use demo_constructor::{demo_exit_init, Calls, Scheme, WASM_BINARY}; - - let test = |program_id| { - let code_id = CodeId::generate(WASM_BINARY); - let program = ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let expected_block = program.expiration_block; - assert!(TaskPoolOf::::contains( - &expected_block, - &ScheduledTask::PauseProgram(program_id) - )); - - run_to_block(2, None); - - assert!(!Gear::is_active(program_id)); - assert!(!Gear::is_initialized(program_id)); - assert!(MailboxOf::::is_empty(&USER_1)); - assert!(!TaskPoolOf::::contains( - &expected_block, - &ScheduledTask::PauseProgram(program_id) - )); - - // Program is not removed and can't be submitted again - assert_noop!( - Gear::create_program( - RuntimeOrigin::signed(USER_1), - code_id, - DEFAULT_SALT.to_vec(), - Vec::new(), - 2_000_000_000, - 0u128, - false, - ), - Error::::ProgramAlreadyExists, - ); - }; - - new_test_ext().execute_with(|| { - // exit init - let (_, exited_pid) = - submit_constructor_with_args(USER_1, DEFAULT_SALT, demo_exit_init::scheme(false), 0); - - test(exited_pid); - }); - - new_test_ext().execute_with(|| { - // failed in init - let init = Calls::builder().panic("panicked in init"); - let (_, terminated_pid) = submit_constructor_with_args( - USER_1, - DEFAULT_SALT, - Scheme::predefined( - init, - Default::default(), - Default::default(), - Default::default(), - ), - 0, - ); - - test(terminated_pid); - }); -} - #[test] fn test_create_program_works() { use demo_init_wait::WASM_BINARY; @@ -6472,1070 +6404,129 @@ fn test_create_program_simple() { factory_code.to_vec(), DEFAULT_SALT.to_vec(), EMPTY_PAYLOAD.to_vec(), - 50_000_000_000, - 0, - false, - )); - run_to_block(2, None); - - // Test create one successful in init program - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_1), - factory_id, - CreateProgram::Default.encode(), - 50_000_000_000, - 0, - false, - )); - run_to_block(3, None); - - // Test create one failing in init program - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_1), - factory_id, - CreateProgram::Custom( - vec![(child_code_hash, b"some_data".to_vec(), 300_000)] // too little gas - ) - .encode(), - 10_000_000_000, - 0, - false, - )); - run_to_block(4, None); - - // First extrinsic call with successful program creation dequeues and executes init and dispatch messages - // Second extrinsic is failing one, for each message it generates replies, which are executed (4 dequeued, 2 dispatched) - assert_total_dequeued(6 + 3 + 2); // +3 for extrinsics +2 for auto generated replies - assert_init_success(1 + 1); // +1 for submitting factory - - System::reset_events(); - - // Create multiple successful init programs - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_1), - factory_id, - CreateProgram::Custom(vec![ - (child_code_hash, b"salt1".to_vec(), 200_000_000), - (child_code_hash, b"salt2".to_vec(), 200_000_000), - ]) - .encode(), - 50_000_000_000, - 0, - false, - )); - run_to_block(5, None); - - // Create multiple successful init programs - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_1), - factory_id, - CreateProgram::Custom(vec![ - (child_code_hash, b"salt3".to_vec(), 300_000), // too little gas - (child_code_hash, b"salt4".to_vec(), 300_000), // too little gas - ]) - .encode(), - 50_000_000_000, - 0, - false, - )); - run_to_block(6, None); - - assert_total_dequeued(12 + 2 + 4); // +2 for extrinsics +4 for auto generated replies - assert_init_success(2); - }) -} - -#[test] -fn test_pausing_programs_works() { - use demo_program_factory::{CreateProgram, WASM_BINARY as PROGRAM_FACTORY_WASM_BINARY}; - init_logger(); - new_test_ext().execute_with(|| { - let factory_code = PROGRAM_FACTORY_WASM_BINARY; - let factory_id = generate_program_id(factory_code, DEFAULT_SALT); - let child_code = ProgramCodeKind::Default.to_bytes(); - let child_code_hash = generate_code_hash(&child_code); - - assert_ok!(Gear::upload_code(RuntimeOrigin::signed(USER_1), child_code,)); - - assert_ok!(Gear::upload_program( - RuntimeOrigin::signed(USER_2), - factory_code.to_vec(), - DEFAULT_SALT.to_vec(), - EMPTY_PAYLOAD.to_vec(), - 50_000_000_000, - 0, - false, - )); - - let factory_bn = System::block_number(); - run_to_next_block(None); - - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_1), - factory_id, - CreateProgram::Custom(vec![( - child_code_hash, - DEFAULT_SALT.to_vec(), - 10_000_000_000 - )]) - .encode(), - 50_000_000_000, - 0, - false, - )); - - let child_program_id = ProgramId::generate_from_program( - child_code_hash.into(), - DEFAULT_SALT, - get_last_message_id(), - ); - - run_to_next_block(None); - - let child_bn = System::block_number(); - - // check that program created via extrinsic is paused - let program = ProgramStorageOf::::get_program(factory_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let expected_block = program.expiration_block; - assert_eq!( - expected_block, - factory_bn.saturating_add(RentFreePeriodOf::::get()) - ); - assert!(TaskPoolOf::::contains( - &expected_block, - &ScheduledTask::PauseProgram(factory_id) - )); - - System::set_block_number(expected_block - 1); - Gear::set_block_number(expected_block - 1); - - run_to_next_block(None); - - assert!(!ProgramStorageOf::::program_exists(factory_id)); - assert!(ProgramStorageOf::::paused_program_exists(&factory_id)); - assert!(Gear::program_exists(factory_id)); - - // check that program created via syscall is paused - let program = ProgramStorageOf::::get_program(child_program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let expected_block = program.expiration_block; - assert_eq!( - expected_block, - child_bn.saturating_add(RentFreePeriodOf::::get()) - ); - assert!(TaskPoolOf::::contains( - &expected_block, - &ScheduledTask::PauseProgram(child_program_id) - )); - - System::set_block_number(expected_block - 1); - Gear::set_block_number(expected_block - 1); - - run_to_next_block(None); - - assert!(!ProgramStorageOf::::program_exists(child_program_id)); - assert!(ProgramStorageOf::::paused_program_exists( - &child_program_id - )); - assert!(Gear::program_exists(child_program_id)); - }) -} - -#[test] -fn resume_session_init_works() { - init_logger(); - new_test_ext().execute_with(|| { - let program_id = { - let res = upload_program_default(USER_2, ProgramCodeKind::Default); - assert_ok!(res); - res.expect("submit result was asserted") - }; - - run_to_next_block(None); - - assert!(!ProgramStorageOf::::paused_program_exists( - &program_id - )); - - // attempt to resume an active program should fail - assert_err!( - Gear::resume_session_init( - RuntimeOrigin::signed(USER_1), - program_id, - Default::default(), - Default::default(), - ), - pallet_gear_program::Error::::ProgramNotFound, - ); - - let program = ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let expected_block = program.expiration_block; - - System::set_block_number(expected_block - 1); - Gear::set_block_number(expected_block - 1); - - run_to_next_block(None); - - assert!(ProgramStorageOf::::paused_program_exists(&program_id)); - - assert_ok!(Gear::resume_session_init( - RuntimeOrigin::signed(USER_1), - program_id, - Default::default(), - Default::default(), - )); - - let (session_id, session_end_block, resume_program_id, _) = get_last_session(); - assert_eq!(resume_program_id, program_id); - assert_eq!( - session_end_block, - Gear::block_number().saturating_add(ResumeSessionDurationOf::::get()) - ); - - assert!(TaskPoolOf::::contains( - &session_end_block, - &ScheduledTask::RemoveResumeSession(session_id) - )); - - // another user can start resume session - assert_ok!(Gear::resume_session_init( - RuntimeOrigin::signed(USER_2), - program_id, - Default::default(), - Default::default(), - )); - - let (session_id_2, ..) = get_last_session(); - assert_ne!(session_id, session_id_2); - - // user is able to start several resume sessions - assert_ok!(Gear::resume_session_init( - RuntimeOrigin::signed(USER_2), - program_id, - Default::default(), - Default::default(), - )); - - let (session_id_3, ..) = get_last_session(); - assert_ne!(session_id, session_id_3); - assert_ne!(session_id_2, session_id_3); - - System::set_block_number(session_end_block - 1); - Gear::set_block_number(session_end_block - 1); - - run_to_next_block(None); - - // the session should be removed since it wasn't finished - assert!(!TaskPoolOf::::contains( - &session_end_block, - &ScheduledTask::RemoveResumeSession(session_id) - )); - - assert!(ProgramStorageOf::::paused_program_exists(&program_id)); - }) -} - -#[test] -fn state_request() { - init_logger(); - new_test_ext().execute_with(|| { - use demo_custom::{ - btree::{Request, StateRequest}, - InitMessage, WASM_BINARY, - }; - - let code = WASM_BINARY; - let program_id = generate_program_id(code, DEFAULT_SALT); - - assert_ok!(Gear::upload_program( - RuntimeOrigin::signed(USER_2), - code.to_vec(), - DEFAULT_SALT.to_vec(), - InitMessage::BTree.encode(), - 50_000_000_000, - 0, - false, - )); - - let data = [(0u32, 1u32), (2, 4), (7, 8)]; - for (key, value) in data { - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_1), - program_id, - Request::Insert(key, value).encode(), - 1_000_000_000, - 0, - false, - )); - } - - run_to_next_block(None); - - for (key, value) in data { - let ret = Gear::read_state_impl(program_id, StateRequest::ForKey(key).encode(), None) - .unwrap(); - assert_eq!( - Option::::decode(&mut ret.as_slice()).unwrap().unwrap(), - value - ); - } - - let ret = Gear::read_state_impl(program_id, StateRequest::Full.encode(), None).unwrap(); - let ret = BTreeMap::::decode(&mut ret.as_slice()).unwrap(); - let expected: BTreeMap = data.into_iter().collect(); - assert_eq!(ret, expected); - }) -} - -#[test] -fn resume_session_push_works() { - init_logger(); - new_test_ext().execute_with(|| { - use demo_custom::{btree::Request, InitMessage, WASM_BINARY}; - - let code = WASM_BINARY; - let program_id = generate_program_id(code, DEFAULT_SALT); - - assert_ok!(Gear::upload_program( - RuntimeOrigin::signed(USER_2), - code.to_vec(), - DEFAULT_SALT.to_vec(), - InitMessage::BTree.encode(), - 50_000_000_000, - 0, - false, - )); - - let request = Request::Insert(0, 1).encode(); - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_1), - program_id, - request, - 1_000_000_000, - 0, - false, - )); - - run_to_next_block(None); - - let program = ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let expected_block = program.expiration_block; - - let memory_pages = ProgramStorageOf::::get_program_data_for_pages( - program_id, - program.memory_infix, - program.pages_with_data.iter(), - ) - .unwrap(); - - System::set_block_number(expected_block - 1); - Gear::set_block_number(expected_block - 1); - - run_to_next_block(None); - - assert!(ProgramStorageOf::::paused_program_exists(&program_id)); - - assert_ok!(Gear::resume_session_init( - RuntimeOrigin::signed(USER_1), - program_id, - Default::default(), - Default::default(), - )); - - let (session_id, session_end_block, ..) = get_last_session(); - - // another user may not append memory pages to the session - assert_err!( - Gear::resume_session_push( - RuntimeOrigin::signed(USER_2), - session_id, - Default::default() - ), - pallet_gear_program::Error::::NotSessionOwner, - ); - - // append to inexistent session fails - assert_err!( - Gear::resume_session_push( - RuntimeOrigin::signed(USER_1), - session_id.wrapping_add(1), - Default::default() - ), - pallet_gear_program::Error::::ResumeSessionNotFound, - ); - - assert_ok!(Gear::resume_session_push( - RuntimeOrigin::signed(USER_1), - session_id, - memory_pages.clone().into_iter().collect() - )); - assert_eq!( - ProgramStorageOf::::resume_session_page_count(&session_id).unwrap(), - memory_pages.len() as u32 - ); - - System::set_block_number(session_end_block - 1); - Gear::set_block_number(session_end_block - 1); - - run_to_next_block(None); - - assert_err!( - Gear::resume_session_push( - RuntimeOrigin::signed(USER_1), - session_id, - memory_pages.into_iter().collect() - ), - pallet_gear_program::Error::::ResumeSessionNotFound, - ); - assert!(ProgramStorageOf::::resume_session_page_count(&session_id).is_none()); - assert!(ProgramStorageOf::::get_program_data_for_pages( - program_id, - program.memory_infix, - program.pages_with_data.iter(), - ) - .is_err()); - - assert!(ProgramStorageOf::::paused_program_exists(&program_id)); - }) -} - -#[test] -fn resume_program_works() { - init_logger(); - new_test_ext().execute_with(|| { - use demo_custom::{ - btree::{Reply, Request}, - InitMessage, WASM_BINARY, - }; - use frame_support::traits::ReservableCurrency; - - let code = WASM_BINARY; - let program_id = generate_program_id(code, DEFAULT_SALT); - - assert_ok!(Gear::upload_program( - RuntimeOrigin::signed(USER_1), - code.to_vec(), - DEFAULT_SALT.to_vec(), - InitMessage::BTree.encode(), - 50_000_000_000, - 0, - false, - )); - - let request = Request::Insert(0, 1).encode(); - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_1), - program_id, - request, - 10_000_000_000, - 0, - false, - )); - - run_to_next_block(None); - - let program = ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let expected_block = program.expiration_block; - - let memory_pages = ProgramStorageOf::::get_program_data_for_pages( - program_id, - program.memory_infix, - program.pages_with_data.iter(), - ) - .unwrap(); - - System::set_block_number(expected_block - 1); - Gear::set_block_number(expected_block - 1); - - run_to_next_block(None); - - assert!(ProgramStorageOf::::paused_program_exists(&program_id)); - - let old_nonce = as PausedProgramStorage>::NonceStorage::get(); - // start a session to bump nonce - assert_ok!(Gear::resume_session_init( - RuntimeOrigin::signed(USER_1), - program_id, - program.allocations.clone(), - program.code_hash.cast(), - )); - assert_ne!( - old_nonce, - as PausedProgramStorage>::NonceStorage::get() - ); - - assert_ok!(Gear::resume_session_init( - RuntimeOrigin::signed(USER_3), - program_id, - program.allocations.clone(), - program.code_hash.cast(), - )); - - let (session_id, session_end_block, ..) = get_last_session(); - - // start another session - assert_ok!(Gear::resume_session_init( - RuntimeOrigin::signed(USER_2), - program_id, - program.allocations, - program.code_hash.cast(), - )); - - let (session_id_2, session_end_block_2, ..) = get_last_session(); - assert_ne!(session_id, session_id_2); - - assert_ok!(Gear::resume_session_push( - RuntimeOrigin::signed(USER_3), - session_id, - memory_pages.into_iter().collect() - )); - - let block_count = ResumeMinimalPeriodOf::::get(); - // access to finish session by another user is denied - assert_err!( - Gear::resume_session_commit(RuntimeOrigin::signed(USER_1), session_id, block_count), - pallet_gear_program::Error::::NotSessionOwner, - ); - - // attempt to resume for the amount of blocks that is less than the minimum should fail - assert_err!( - Gear::resume_session_commit(RuntimeOrigin::signed(USER_3), session_id, 0,), - Error::::ResumePeriodLessThanMinimal, - ); - - // attempt to finish session with abscent binary code should fail - assert!(::CodeStorage::remove_code( - CodeId::generate(code) - )); - assert_err!( - Gear::resume_session_commit(RuntimeOrigin::signed(USER_3), session_id, block_count,), - pallet_gear_program::Error::::ProgramCodeNotFound - ); - - // resubmit binary code - assert_ok!(Gear::upload_code( - RuntimeOrigin::signed(USER_1), - code.to_vec(), - )); - - // if user doesn't have enough funds the extrinsic should fail - let to_reserve = Balances::free_balance(USER_3) - Balances::minimum_balance(); - CurrencyOf::::reserve(&USER_3, to_reserve).unwrap(); - - assert_err!( - Gear::resume_session_commit(RuntimeOrigin::signed(USER_3), session_id, block_count,), - Error::::InsufficientBalance, - ); - - let _ = CurrencyOf::::unreserve(&USER_3, to_reserve); - - // successful execution - let balance_before = Balances::free_balance(BLOCK_AUTHOR); - assert_ok!(Gear::resume_session_commit( - RuntimeOrigin::signed(USER_3), - session_id, - block_count, - )); - - let rent_fee = Gear::rent_fee_for(block_count); - assert_eq!( - Balances::free_balance(BLOCK_AUTHOR), - rent_fee + balance_before - ); - - assert!(!TaskPoolOf::::contains( - &session_end_block, - &ScheduledTask::RemoveResumeSession(session_id) - )); - - let program_change = match get_last_event() { - MockRuntimeEvent::Gear(Event::ProgramChanged { id, change }) => { - assert_eq!(id, program_id); - - change - } - _ => unreachable!(), - }; - let expiration_block = match program_change { - ProgramChangeKind::Active { expiration } => expiration, - _ => unreachable!(), - }; - assert!(TaskPoolOf::::contains( - &expiration_block, - &ScheduledTask::PauseProgram(program_id) - )); - - let program = ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - assert_eq!(program.expiration_block, expiration_block); - - // finishing the second session should succeed too. - // In the same time the user isn't charged - let balance_before = Balances::free_balance(BLOCK_AUTHOR); - assert_ok!(Gear::resume_session_commit( - RuntimeOrigin::signed(USER_2), - session_id_2, - block_count, - )); - - assert_eq!(Balances::free_balance(BLOCK_AUTHOR), balance_before); - - assert!(!TaskPoolOf::::contains( - &session_end_block_2, - &ScheduledTask::RemoveResumeSession(session_id_2) - )); - - // finish inexistent session fails - assert_err!( - Gear::resume_session_commit(RuntimeOrigin::signed(USER_1), session_id, block_count), - pallet_gear_program::Error::::ResumeSessionNotFound, - ); - - // check that program operates properly after it was resumed - run_to_next_block(None); - - System::reset_events(); - - let request = Request::List.encode(); - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_1), - program_id, - request, - 10_000_000_000, - 0, - false, - )); - - run_to_next_block(None); - - let message = maybe_any_last_message().expect("message to user should be sent"); - let reply = Reply::decode(&mut message.payload_bytes()).unwrap(); - assert!(matches!(reply, Reply::List(vec) if vec == vec![(0, 1)])); - }) -} - -#[test] -fn test_no_messages_to_paused_program() { - init_logger(); - new_test_ext().execute_with(|| { - let code = demo_wait_wake::WASM_BINARY; - let program_id = generate_program_id(code, DEFAULT_SALT); - - assert_ok!(Gear::upload_program( - RuntimeOrigin::signed(USER_2), - code.to_vec(), - DEFAULT_SALT.to_vec(), - EMPTY_PAYLOAD.to_vec(), - 50_000_000_000, - 0, - false, - )); - run_to_next_block(None); - - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_1), - program_id, - demo_wait_wake::Request::EchoWait(10).encode(), - 50_000_000_000, - 0, - false, - )); - run_to_next_block(None); - - let program = ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let expected_block = program.expiration_block; - - System::set_block_number(expected_block - 1); - Gear::set_block_number(expected_block - 1); - - run_to_next_block(None); - - assert!(WaitlistOf::::iter_key(program_id).next().is_none()); - }) -} - -#[test] -fn reservations_cleaned_in_paused_program() { - use demo_reserve_gas::InitAction; - - init_logger(); - new_test_ext().execute_with(|| { - let expiration_block = RentFreePeriodOf::::get() + 10; - assert_ok!(Gear::upload_program( - RuntimeOrigin::signed(USER_1), - demo_reserve_gas::WASM_BINARY.to_vec(), - DEFAULT_SALT.to_vec(), - InitAction::Normal(vec![ - (50_000, expiration_block.saturated_into()), - (25_000, expiration_block.saturated_into()), - ]) - .encode(), - 50_000_000_000, - 0, - false, - )); - - let program_id = get_last_program_id(); - - run_to_next_block(None); - - assert!(Gear::is_initialized(program_id)); - - let map = get_reservation_map(program_id).unwrap(); - - for (rid, slot) in &map { - assert!(TaskPoolOf::::contains( - &BlockNumberFor::::saturated_from(slot.finish), - &ScheduledTask::RemoveGasReservation(program_id, *rid) - )); - assert!(GasHandlerOf::::get_limit_node(*rid).is_ok()); - } - - let program = ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let expected_block = program.expiration_block; - - System::set_block_number(expected_block - 1); - Gear::set_block_number(expected_block - 1); - - run_to_next_block(None); - - assert!(ProgramStorageOf::::paused_program_exists(&program_id)); - - for (rid, slot) in &map { - assert!(!TaskPoolOf::::contains( - &BlockNumberFor::::saturated_from(slot.finish), - &ScheduledTask::RemoveGasReservation(program_id, *rid) - )); - assert_err!( - GasHandlerOf::::get_limit_node(*rid), - pallet_gear_gas::Error::::NodeNotFound - ); - } - }); -} - -#[test] -fn uninitialized_program_terminates_on_pause() { - use demo_reserve_gas::InitAction; - - init_logger(); - new_test_ext().execute_with(|| { - assert_ok!(Gear::upload_program( - RuntimeOrigin::signed(USER_1), - demo_reserve_gas::WASM_BINARY.to_vec(), - DEFAULT_SALT.to_vec(), - InitAction::Wait.encode(), - 50_000_000_000, - 0, - false, - )); - - let program_id = get_last_program_id(); - - run_to_next_block(None); - - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_1), - program_id, - b"0123456789".to_vec(), - 50_000_000_000, - 0, - false, - )); - - run_to_next_block(None); - - assert!(WaitlistOf::::iter_key(program_id).next().is_some()); - - let map = get_reservation_map(program_id).unwrap(); - - for (rid, slot) in &map { - assert!(TaskPoolOf::::contains( - &BlockNumberFor::::saturated_from(slot.finish), - &ScheduledTask::RemoveGasReservation(program_id, *rid) - )); - assert!(GasHandlerOf::::get_limit_node(*rid).is_ok()); - } - - let program = ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let expected_block = program.expiration_block; - - System::set_block_number(expected_block - 1); - Gear::set_block_number(expected_block - 1); - - run_to_next_block(None); - - assert!(Gear::is_terminated(program_id)); - - for (rid, slot) in &map { - assert!(!TaskPoolOf::::contains( - &BlockNumberFor::::saturated_from(slot.finish), - &ScheduledTask::RemoveGasReservation(program_id, *rid) - )); - assert_err!( - GasHandlerOf::::get_limit_node(*rid), - pallet_gear_gas::Error::::NodeNotFound - ); - } - - assert!(WaitlistOf::::iter_key(program_id).next().is_none()); - assert!(ProgramStorageOf::::waiting_init_get_messages(program_id).is_empty()); - for page in program.pages_with_data.iter() { - assert_err!( - ProgramStorageOf::::get_program_data_for_pages( - program_id, - program.memory_infix, - Some(*page).iter() - ), - pallet_gear_program::Error::::CannotFindDataForPage - ); - } - }); -} - -#[test] -fn pay_program_rent_syscall_works() { - use test_syscalls::{Kind, PAY_PROGRAM_RENT_EXPECT, WASM_BINARY as TEST_SYSCALLS_BINARY}; - - init_logger(); - new_test_ext().execute_with(|| { - let pay_rent_id = generate_program_id(TEST_SYSCALLS_BINARY, DEFAULT_SALT); - - let program_value = 10_000_000; - assert_ok!(Gear::upload_program( - RuntimeOrigin::signed(USER_2), - TEST_SYSCALLS_BINARY.to_vec(), - DEFAULT_SALT.to_vec(), - pay_rent_id.into_bytes().to_vec(), - 20_000_000_000, - program_value, + 50_000_000_000, + 0, false, )); + run_to_block(2, None); - run_to_next_block(None); - - let program = ProgramStorageOf::::get_program(pay_rent_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let old_block = program.expiration_block; - - let block_count = 2_000u32; - let rent = RentCostPerBlockOf::::get() * u128::from(block_count); + // Test create one successful in init program assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_2), - pay_rent_id, - vec![Kind::PayProgramRent( - pay_rent_id.into_origin().into(), - rent, - None - )] - .encode(), - 20_000_000_000, + RuntimeOrigin::signed(USER_1), + factory_id, + CreateProgram::Default.encode(), + 50_000_000_000, 0, false, )); + run_to_block(3, None); - run_to_next_block(None); - - let program = ProgramStorageOf::::get_program(pay_rent_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let expiration_block = program.expiration_block; - assert_eq!( - old_block + BlockNumberFor::::saturated_from(block_count), - expiration_block - ); - - // attempt to pay rent for not existing program - let pay_rent_account_id = pay_rent_id.cast::(); - let balance_before = Balances::free_balance(pay_rent_account_id); - + // Test create one failing in init program assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_2), - pay_rent_id, - vec![Kind::PayProgramRent([0u8; 32], rent, None)].encode(), - 20_000_000_000, + RuntimeOrigin::signed(USER_1), + factory_id, + CreateProgram::Custom( + vec![(child_code_hash, b"some_data".to_vec(), 300_000)] // too little gas + ) + .encode(), + 10_000_000_000, 0, false, )); + run_to_block(4, None); - run_to_next_block(None); + // First extrinsic call with successful program creation dequeues and executes init and dispatch messages + // Second extrinsic is failing one, for each message it generates replies, which are executed (4 dequeued, 2 dispatched) + assert_total_dequeued(6 + 3 + 2); // +3 for extrinsics +2 for auto generated replies + assert_init_success(1 + 1); // +1 for submitting factory - assert_eq!(balance_before, Balances::free_balance(pay_rent_account_id)); + System::reset_events(); - // try to pay greater rent than available value + // Create multiple successful init programs assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_2), - pay_rent_id, - vec![Kind::PayProgramRent( - pay_rent_id.into_origin().into(), - program_value, - None - )] + RuntimeOrigin::signed(USER_1), + factory_id, + CreateProgram::Custom(vec![ + (child_code_hash, b"salt1".to_vec(), 200_000_000), + (child_code_hash, b"salt2".to_vec(), 200_000_000), + ]) .encode(), - 20_000_000_000, + 50_000_000_000, 0, false, )); + run_to_block(5, None); - let message_id = get_last_message_id(); - - run_to_next_block(None); - - let error_text = format!( - "{PAY_PROGRAM_RENT_EXPECT}: {:?}", - GstdError::Core(ExtError::Execution(ExecutionError::NotEnoughValue).into()) - ); - - assert_failed( - message_id, - ActorExecutionErrorReplyReason::Trap(TrapExplanation::Panic(error_text.into())), - ); - - assert_eq!(balance_before, Balances::free_balance(pay_rent_account_id)); - let program = ProgramStorageOf::::get_program(pay_rent_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - assert_eq!(expiration_block, program.expiration_block); - - // try to pay for more than u32::MAX blocks + // Create multiple successful init programs assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_2), - pay_rent_id, - vec![ - Kind::PayProgramRent( - pay_rent_id.into_origin().into(), - Gear::rent_fee_for(1), - None - ), - Kind::PayProgramRent( - pay_rent_id.into_origin().into(), - Gear::rent_fee_for(u32::MAX as u64), - None - ) - ] + RuntimeOrigin::signed(USER_1), + factory_id, + CreateProgram::Custom(vec![ + (child_code_hash, b"salt3".to_vec(), 300_000), // too little gas + (child_code_hash, b"salt4".to_vec(), 300_000), // too little gas + ]) .encode(), - 20_000_000_000, - Gear::rent_fee_for(u32::MAX as u64), + 50_000_000_000, + 0, false, )); + run_to_block(6, None); - let message_id = get_last_message_id(); - - run_to_next_block(None); - - let error_text = format!( - "{PAY_PROGRAM_RENT_EXPECT}: {:?}", - GstdError::Core(ExtError::ProgramRent(ProgramRentError::MaximumBlockCountPaid).into()) - ); - assert_failed( - message_id, - ActorExecutionErrorReplyReason::Trap(TrapExplanation::Panic(error_text.into())), - ); - }); + assert_total_dequeued(12 + 2 + 4); // +2 for extrinsics +4 for auto generated replies + assert_init_success(2); + }) } #[test] -fn pay_program_rent_extrinsic_works() { +fn state_request() { init_logger(); new_test_ext().execute_with(|| { - let program_id = upload_program_default(USER_2, ProgramCodeKind::Default) - .expect("program upload should not fail"); - - run_to_next_block(None); - - let program = ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let old_block = program.expiration_block; + use demo_custom::{ + btree::{Request, StateRequest}, + InitMessage, WASM_BINARY, + }; - assert!(TaskPoolOf::::contains( - &old_block, - &ScheduledTask::PauseProgram(program_id) - )); + let code = WASM_BINARY; + let program_id = generate_program_id(code, DEFAULT_SALT); - let block_count: u64 = 10_000; - let balance_before = Balances::free_balance(USER_3); - assert_ok!(Gear::pay_program_rent( - RuntimeOrigin::signed(USER_3), - program_id, - block_count + assert_ok!(Gear::upload_program( + RuntimeOrigin::signed(USER_2), + code.to_vec(), + DEFAULT_SALT.to_vec(), + InitMessage::BTree.encode(), + 50_000_000_000, + 0, + false, )); - let extrinsic_fee = - balance_before - Balances::free_balance(USER_3) - Gear::rent_fee_for(block_count); + let data = [(0u32, 1u32), (2, 4), (7, 8)]; + for (key, value) in data { + assert_ok!(Gear::send_message( + RuntimeOrigin::signed(USER_1), + program_id, + Request::Insert(key, value).encode(), + 1_000_000_000, + 0, + false, + )); + } run_to_next_block(None); - let program = ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let expiration_block = program.expiration_block; - assert_eq!(old_block + block_count, expiration_block); - - assert!(!TaskPoolOf::::contains( - &old_block, - &ScheduledTask::PauseProgram(program_id) - )); - - assert!(TaskPoolOf::::contains( - &expiration_block, - &ScheduledTask::PauseProgram(program_id) - )); - - // attempt to pay rent for not existing program - assert_err!( - Gear::pay_program_rent(RuntimeOrigin::signed(USER_1), [0u8; 32].into(), block_count), - pallet_gear_program::Error::::ProgramNotFound, - ); - - // attempt to pay rent that is greater than payer's balance - let block_count = 100 - + BlockNumberFor::::saturated_from( - Balances::free_balance(LOW_BALANCE_USER) / RentCostPerBlockOf::::get(), + for (key, value) in data { + let ret = Gear::read_state_impl(program_id, StateRequest::ForKey(key).encode(), None) + .unwrap(); + assert_eq!( + Option::::decode(&mut ret.as_slice()).unwrap().unwrap(), + value ); - assert_err!( - Gear::pay_program_rent( - RuntimeOrigin::signed(LOW_BALANCE_USER), - program_id, - block_count - ), - pallet::Error::::InsufficientBalance - ); - - // attempt to pay for u32::MAX blocks. Some value should be refunded because of the overflow. - let _ = Balances::force_set_balance(RuntimeOrigin::root(), USER_1, u128::MAX); - let balance_before = Balances::free_balance(USER_1); - let block_count = u64::MAX; - assert_ok!(Gear::pay_program_rent( - RuntimeOrigin::signed(USER_1), - program_id, - block_count - )); + } - let paid_blocks = block_count - expiration_block; - assert!(paid_blocks < block_count); - assert_eq!( - balance_before - extrinsic_fee - Gear::rent_fee_for(paid_blocks), - Balances::free_balance(USER_1) - ); - }); + let ret = Gear::read_state_impl(program_id, StateRequest::Full.encode(), None).unwrap(); + let ret = BTreeMap::::decode(&mut ret.as_slice()).unwrap(); + let expected: BTreeMap = data.into_iter().collect(); + assert_eq!(ret, expected); + }) } #[test] @@ -14764,125 +13755,6 @@ fn test_send_to_terminated_from_program() { }) } -#[test] -fn pause_waited_uninited_program() { - use demo_init_wait::WASM_BINARY; - - init_logger(); - - // closure to get corresponding block numbers - let get_remove_block = |current_gas: u64| { - assert_ok!(Gear::upload_program( - RuntimeOrigin::signed(USER_1), - WASM_BINARY.to_vec(), - current_gas.to_le_bytes().to_vec(), - Vec::new(), - current_gas, - 0u128, - false, - )); - - let program_id = utils::get_last_program_id(); - - assert!(!Gear::is_initialized(program_id)); - assert!(Gear::is_active(program_id)); - - run_to_next_block(None); - - let (_, remove_from_waitlist_block) = get_last_message_waited(); - - let program = ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - - (remove_from_waitlist_block, program.expiration_block) - }; - - // determine such gas value that init message will be removed - // from the waitlist before an execution of the PauseProgram task - let gas = new_test_ext().execute_with(|| { - let GasInfo { - waited: init_waited, - burned, - .. - } = Gear::calculate_gas_info( - USER_1.into_origin(), - HandleKind::Init(WASM_BINARY.to_vec()), - vec![], - 0, - true, - true, - ) - .expect("calculate_gas_info failed"); - - assert!(init_waited); - - let mut current_gas = 2 * burned; - - let (mut remove_from_waitlist_block, mut expiration_block) = get_remove_block(current_gas); - - while remove_from_waitlist_block >= expiration_block { - current_gas = (current_gas + burned) / 2; - - (remove_from_waitlist_block, expiration_block) = get_remove_block(current_gas); - } - - current_gas - }); - - new_test_ext().execute_with(|| { - assert_ok!(Gear::upload_program( - RuntimeOrigin::signed(USER_1), - WASM_BINARY.to_vec(), - vec![], - Vec::new(), - gas, - 0u128, - false, - )); - - let program_id = utils::get_last_program_id(); - - assert!(!Gear::is_initialized(program_id)); - assert!(Gear::is_active(program_id)); - - run_to_next_block(None); - - let (_, remove_from_waitlist_block) = get_last_message_waited(); - - let program = ProgramStorageOf::::get_program(program_id) - .and_then(|p| ActiveProgram::try_from(p).ok()) - .expect("program should exist"); - let expiration_block = program.expiration_block; - - assert!(TaskPoolOf::::contains( - &expiration_block, - &ScheduledTask::PauseProgram(program_id) - )); - - assert!(!Gear::is_initialized(program_id)); - assert!(Gear::is_active(program_id)); - - run_to_next_block(None); - - System::set_block_number(remove_from_waitlist_block - 1); - Gear::set_block_number(remove_from_waitlist_block - 1); - - run_to_next_block(None); - - assert!(Gear::is_terminated(program_id)); - assert!(!TaskPoolOf::::contains( - &expiration_block, - &ScheduledTask::PauseProgram(program_id) - )); - - System::set_block_number(expiration_block - 1); - Gear::set_block_number(expiration_block - 1); - - run_to_next_block(None); - }) -} - #[test] fn remove_from_waitlist_after_exit_reply() { use demo_constructor::demo_wait_init_exit_reply; @@ -14901,12 +13773,6 @@ fn remove_from_waitlist_after_exit_reply() { let (waited_mid, remove_from_waitlist_block) = get_last_message_waited(); assert_eq!(init_mid, waited_mid); - assert_ok!(Gear::pay_program_rent( - RuntimeOrigin::signed(USER_1), - program_id, - remove_from_waitlist_block + 1 - )); - run_to_next_block(None); assert!(TaskPoolOf::::contains( diff --git a/pallets/gear/src/weights.rs b/pallets/gear/src/weights.rs index b0436ab5561..7bd4fc6736d 100644 --- a/pallets/gear/src/weights.rs +++ b/pallets/gear/src/weights.rs @@ -54,10 +54,6 @@ pub trait WeightInfo { fn db_read_per_kb(c: u32, ) -> Weight; fn instantiate_module_per_kb(c: u32, ) -> Weight; fn claim_value() -> Weight; - fn pay_program_rent() -> Weight; - fn resume_session_init() -> Weight; - fn resume_session_push(c: u32, ) -> Weight; - fn resume_session_commit(c: u32, ) -> Weight; fn upload_code(c: u32, ) -> Weight; fn create_program(s: u32, ) -> Weight; fn upload_program(c: u32, s: u32, ) -> Weight; @@ -217,7 +213,6 @@ pub trait WeightInfo { fn instr_i32rotl(r: u32, ) -> Weight; fn instr_i64rotr(r: u32, ) -> Weight; fn instr_i32rotr(r: u32, ) -> Weight; - fn tasks_remove_resume_session() -> Weight; fn tasks_remove_gas_reservation() -> Weight; fn tasks_send_user_message_to_mailbox() -> Weight; fn tasks_send_user_message() -> Weight; @@ -226,8 +221,6 @@ pub trait WeightInfo { fn tasks_wake_message_no_wake() -> Weight; fn tasks_remove_from_waitlist() -> Weight; fn tasks_remove_from_mailbox() -> Weight; - fn tasks_pause_program(c: u32, ) -> Weight; - fn tasks_pause_program_uninited(c: u32, ) -> Weight; fn allocation_cost() -> Weight; fn grow_cost() -> Weight; fn initial_cost() -> Weight; @@ -424,50 +417,6 @@ impl WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(12_u64)) } - fn pay_program_rent() -> Weight { - // Proof Size summary in bytes: - // Measured: `992` - // Estimated: `6932` - // Minimum execution time: 73_951_000 picoseconds. - Weight::from_parts(75_251_000, 6932) - .saturating_add(T::DbWeight::get().reads(7_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) - } - fn resume_session_init() -> Weight { - // Proof Size summary in bytes: - // Measured: `638` - // Estimated: `4103` - // Minimum execution time: 29_643_000 picoseconds. - Weight::from_parts(30_312_000, 4103) - .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) - } - /// The range of component `c` is `[0, 64]`. - fn resume_session_push(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `355` - // Estimated: `3820` - // Minimum execution time: 7_866_000 picoseconds. - Weight::from_parts(6_436_778, 3820) - // Standard Error: 35_845 - .saturating_add(Weight::from_parts(12_271_160, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) - } - /// The range of component `c` is `[0, 2044]`. - fn resume_session_commit(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `1593 + c * (16389 ±0)` - // Estimated: `7529 + c * (16389 ±0)` - // Minimum execution time: 89_187_000 picoseconds. - Weight::from_parts(89_559_000, 7529) - // Standard Error: 171_247 - .saturating_add(Weight::from_parts(53_532_435, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(11_u64)) - .saturating_add(T::DbWeight::get().writes(9_u64)) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 16389).saturating_mul(c.into())) - } /// The range of component `c` is `[0, 250]`. fn upload_code(c: u32, ) -> Weight { // Proof Size summary in bytes: @@ -2095,15 +2044,6 @@ impl WeightInfo for SubstrateWeight { // Standard Error: 5_344 .saturating_add(Weight::from_parts(650_899, 0).saturating_mul(r.into())) } - fn tasks_remove_resume_session() -> Weight { - // Proof Size summary in bytes: - // Measured: `352` - // Estimated: `3817` - // Minimum execution time: 5_677_000 picoseconds. - Weight::from_parts(6_089_000, 3817) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) - } fn tasks_remove_gas_reservation() -> Weight { // Proof Size summary in bytes: // Measured: `1107` @@ -2175,36 +2115,6 @@ impl WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().reads(14_u64)) .saturating_add(T::DbWeight::get().writes(13_u64)) } - /// The range of component `c` is `[0, 2044]`. - fn tasks_pause_program(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `2303 + c * (16400 ±0)` - // Estimated: `4854 + c * (18876 ±0)` - // Minimum execution time: 29_288_000 picoseconds. - Weight::from_parts(29_758_000, 4854) - // Standard Error: 71_310 - .saturating_add(Weight::from_parts(36_877_617, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(c.into()))) - .saturating_add(T::DbWeight::get().writes(2_u64)) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 18876).saturating_mul(c.into())) - } - /// The range of component `c` is `[0, 2044]`. - fn tasks_pause_program_uninited(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `3129 + c * (42 ±0)` - // Estimated: `8171 + c * (2517 ±0)` - // Minimum execution time: 86_496_000 picoseconds. - Weight::from_parts(80_366_450, 8171) - // Standard Error: 2_411 - .saturating_add(Weight::from_parts(1_048_389, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(13_u64)) - .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(c.into()))) - .saturating_add(T::DbWeight::get().writes(9_u64)) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 2517).saturating_mul(c.into())) - } } // For backwards compatibility and tests @@ -2395,50 +2305,6 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(15_u64)) .saturating_add(RocksDbWeight::get().writes(12_u64)) } - fn pay_program_rent() -> Weight { - // Proof Size summary in bytes: - // Measured: `992` - // Estimated: `6932` - // Minimum execution time: 73_951_000 picoseconds. - Weight::from_parts(75_251_000, 6932) - .saturating_add(RocksDbWeight::get().reads(7_u64)) - .saturating_add(RocksDbWeight::get().writes(6_u64)) - } - fn resume_session_init() -> Weight { - // Proof Size summary in bytes: - // Measured: `638` - // Estimated: `4103` - // Minimum execution time: 29_643_000 picoseconds. - Weight::from_parts(30_312_000, 4103) - .saturating_add(RocksDbWeight::get().reads(6_u64)) - .saturating_add(RocksDbWeight::get().writes(4_u64)) - } - /// The range of component `c` is `[0, 64]`. - fn resume_session_push(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `355` - // Estimated: `3820` - // Minimum execution time: 7_866_000 picoseconds. - Weight::from_parts(6_436_778, 3820) - // Standard Error: 35_845 - .saturating_add(Weight::from_parts(12_271_160, 0).saturating_mul(c.into())) - .saturating_add(RocksDbWeight::get().reads(2_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } - /// The range of component `c` is `[0, 2044]`. - fn resume_session_commit(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `1593 + c * (16389 ±0)` - // Estimated: `7529 + c * (16389 ±0)` - // Minimum execution time: 89_187_000 picoseconds. - Weight::from_parts(89_559_000, 7529) - // Standard Error: 171_247 - .saturating_add(Weight::from_parts(53_532_435, 0).saturating_mul(c.into())) - .saturating_add(RocksDbWeight::get().reads(11_u64)) - .saturating_add(RocksDbWeight::get().writes(9_u64)) - .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 16389).saturating_mul(c.into())) - } /// The range of component `c` is `[0, 250]`. fn upload_code(c: u32, ) -> Weight { // Proof Size summary in bytes: @@ -4066,15 +3932,6 @@ impl WeightInfo for () { // Standard Error: 5_344 .saturating_add(Weight::from_parts(650_899, 0).saturating_mul(r.into())) } - fn tasks_remove_resume_session() -> Weight { - // Proof Size summary in bytes: - // Measured: `352` - // Estimated: `3817` - // Minimum execution time: 5_677_000 picoseconds. - Weight::from_parts(6_089_000, 3817) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } fn tasks_remove_gas_reservation() -> Weight { // Proof Size summary in bytes: // Measured: `1107` @@ -4146,34 +4003,4 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(14_u64)) .saturating_add(RocksDbWeight::get().writes(13_u64)) } - /// The range of component `c` is `[0, 2044]`. - fn tasks_pause_program(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `2303 + c * (16400 ±0)` - // Estimated: `4854 + c * (18876 ±0)` - // Minimum execution time: 29_288_000 picoseconds. - Weight::from_parts(29_758_000, 4854) - // Standard Error: 71_310 - .saturating_add(Weight::from_parts(36_877_617, 0).saturating_mul(c.into())) - .saturating_add(RocksDbWeight::get().reads(4_u64)) - .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(c.into()))) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 18876).saturating_mul(c.into())) - } - /// The range of component `c` is `[0, 2044]`. - fn tasks_pause_program_uninited(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `3129 + c * (42 ±0)` - // Estimated: `8171 + c * (2517 ±0)` - // Minimum execution time: 86_496_000 picoseconds. - Weight::from_parts(80_366_450, 8171) - // Standard Error: 2_411 - .saturating_add(Weight::from_parts(1_048_389, 0).saturating_mul(c.into())) - .saturating_add(RocksDbWeight::get().reads(13_u64)) - .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(c.into()))) - .saturating_add(RocksDbWeight::get().writes(9_u64)) - .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 2517).saturating_mul(c.into())) - } } diff --git a/runtime/vara/src/weights/pallet_gear.rs b/runtime/vara/src/weights/pallet_gear.rs index 2e0327036c5..23106e4df24 100644 --- a/runtime/vara/src/weights/pallet_gear.rs +++ b/runtime/vara/src/weights/pallet_gear.rs @@ -54,10 +54,6 @@ pub trait WeightInfo { fn db_read_per_kb(c: u32, ) -> Weight; fn instantiate_module_per_kb(c: u32, ) -> Weight; fn claim_value() -> Weight; - fn pay_program_rent() -> Weight; - fn resume_session_init() -> Weight; - fn resume_session_push(c: u32, ) -> Weight; - fn resume_session_commit(c: u32, ) -> Weight; fn upload_code(c: u32, ) -> Weight; fn create_program(s: u32, ) -> Weight; fn upload_program(c: u32, s: u32, ) -> Weight; @@ -217,7 +213,6 @@ pub trait WeightInfo { fn instr_i32rotl(r: u32, ) -> Weight; fn instr_i64rotr(r: u32, ) -> Weight; fn instr_i32rotr(r: u32, ) -> Weight; - fn tasks_remove_resume_session() -> Weight; fn tasks_remove_gas_reservation() -> Weight; fn tasks_send_user_message_to_mailbox() -> Weight; fn tasks_send_user_message() -> Weight; @@ -226,8 +221,6 @@ pub trait WeightInfo { fn tasks_wake_message_no_wake() -> Weight; fn tasks_remove_from_waitlist() -> Weight; fn tasks_remove_from_mailbox() -> Weight; - fn tasks_pause_program(c: u32, ) -> Weight; - fn tasks_pause_program_uninited(c: u32, ) -> Weight; fn allocation_cost() -> Weight; fn grow_cost() -> Weight; fn initial_cost() -> Weight; @@ -424,50 +417,6 @@ impl pallet_gear::WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().reads(15_u64)) .saturating_add(T::DbWeight::get().writes(12_u64)) } - fn pay_program_rent() -> Weight { - // Proof Size summary in bytes: - // Measured: `992` - // Estimated: `6932` - // Minimum execution time: 73_951_000 picoseconds. - Weight::from_parts(75_251_000, 6932) - .saturating_add(T::DbWeight::get().reads(7_u64)) - .saturating_add(T::DbWeight::get().writes(6_u64)) - } - fn resume_session_init() -> Weight { - // Proof Size summary in bytes: - // Measured: `638` - // Estimated: `4103` - // Minimum execution time: 29_643_000 picoseconds. - Weight::from_parts(30_312_000, 4103) - .saturating_add(T::DbWeight::get().reads(6_u64)) - .saturating_add(T::DbWeight::get().writes(4_u64)) - } - /// The range of component `c` is `[0, 64]`. - fn resume_session_push(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `355` - // Estimated: `3820` - // Minimum execution time: 7_866_000 picoseconds. - Weight::from_parts(6_436_778, 3820) - // Standard Error: 35_845 - .saturating_add(Weight::from_parts(12_271_160, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) - } - /// The range of component `c` is `[0, 2044]`. - fn resume_session_commit(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `1593 + c * (16389 ±0)` - // Estimated: `7529 + c * (16389 ±0)` - // Minimum execution time: 89_187_000 picoseconds. - Weight::from_parts(89_559_000, 7529) - // Standard Error: 171_247 - .saturating_add(Weight::from_parts(53_532_435, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(11_u64)) - .saturating_add(T::DbWeight::get().writes(9_u64)) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 16389).saturating_mul(c.into())) - } /// The range of component `c` is `[0, 250]`. fn upload_code(c: u32, ) -> Weight { // Proof Size summary in bytes: @@ -2095,15 +2044,6 @@ impl pallet_gear::WeightInfo for SubstrateWeight { // Standard Error: 5_344 .saturating_add(Weight::from_parts(650_899, 0).saturating_mul(r.into())) } - fn tasks_remove_resume_session() -> Weight { - // Proof Size summary in bytes: - // Measured: `352` - // Estimated: `3817` - // Minimum execution time: 5_677_000 picoseconds. - Weight::from_parts(6_089_000, 3817) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) - } fn tasks_remove_gas_reservation() -> Weight { // Proof Size summary in bytes: // Measured: `1107` @@ -2175,36 +2115,6 @@ impl pallet_gear::WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().reads(14_u64)) .saturating_add(T::DbWeight::get().writes(13_u64)) } - /// The range of component `c` is `[0, 2044]`. - fn tasks_pause_program(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `2303 + c * (16400 ±0)` - // Estimated: `4854 + c * (18876 ±0)` - // Minimum execution time: 29_288_000 picoseconds. - Weight::from_parts(29_758_000, 4854) - // Standard Error: 71_310 - .saturating_add(Weight::from_parts(36_877_617, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(c.into()))) - .saturating_add(T::DbWeight::get().writes(2_u64)) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 18876).saturating_mul(c.into())) - } - /// The range of component `c` is `[0, 2044]`. - fn tasks_pause_program_uninited(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `3129 + c * (42 ±0)` - // Estimated: `8171 + c * (2517 ±0)` - // Minimum execution time: 86_496_000 picoseconds. - Weight::from_parts(80_366_450, 8171) - // Standard Error: 2_411 - .saturating_add(Weight::from_parts(1_048_389, 0).saturating_mul(c.into())) - .saturating_add(T::DbWeight::get().reads(13_u64)) - .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(c.into()))) - .saturating_add(T::DbWeight::get().writes(9_u64)) - .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 2517).saturating_mul(c.into())) - } } // For backwards compatibility and tests @@ -2395,50 +2305,6 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(15_u64)) .saturating_add(RocksDbWeight::get().writes(12_u64)) } - fn pay_program_rent() -> Weight { - // Proof Size summary in bytes: - // Measured: `992` - // Estimated: `6932` - // Minimum execution time: 73_951_000 picoseconds. - Weight::from_parts(75_251_000, 6932) - .saturating_add(RocksDbWeight::get().reads(7_u64)) - .saturating_add(RocksDbWeight::get().writes(6_u64)) - } - fn resume_session_init() -> Weight { - // Proof Size summary in bytes: - // Measured: `638` - // Estimated: `4103` - // Minimum execution time: 29_643_000 picoseconds. - Weight::from_parts(30_312_000, 4103) - .saturating_add(RocksDbWeight::get().reads(6_u64)) - .saturating_add(RocksDbWeight::get().writes(4_u64)) - } - /// The range of component `c` is `[0, 64]`. - fn resume_session_push(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `355` - // Estimated: `3820` - // Minimum execution time: 7_866_000 picoseconds. - Weight::from_parts(6_436_778, 3820) - // Standard Error: 35_845 - .saturating_add(Weight::from_parts(12_271_160, 0).saturating_mul(c.into())) - .saturating_add(RocksDbWeight::get().reads(2_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } - /// The range of component `c` is `[0, 2044]`. - fn resume_session_commit(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `1593 + c * (16389 ±0)` - // Estimated: `7529 + c * (16389 ±0)` - // Minimum execution time: 89_187_000 picoseconds. - Weight::from_parts(89_559_000, 7529) - // Standard Error: 171_247 - .saturating_add(Weight::from_parts(53_532_435, 0).saturating_mul(c.into())) - .saturating_add(RocksDbWeight::get().reads(11_u64)) - .saturating_add(RocksDbWeight::get().writes(9_u64)) - .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 16389).saturating_mul(c.into())) - } /// The range of component `c` is `[0, 250]`. fn upload_code(c: u32, ) -> Weight { // Proof Size summary in bytes: @@ -4066,15 +3932,6 @@ impl WeightInfo for () { // Standard Error: 5_344 .saturating_add(Weight::from_parts(650_899, 0).saturating_mul(r.into())) } - fn tasks_remove_resume_session() -> Weight { - // Proof Size summary in bytes: - // Measured: `352` - // Estimated: `3817` - // Minimum execution time: 5_677_000 picoseconds. - Weight::from_parts(6_089_000, 3817) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } fn tasks_remove_gas_reservation() -> Weight { // Proof Size summary in bytes: // Measured: `1107` @@ -4146,34 +4003,4 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(14_u64)) .saturating_add(RocksDbWeight::get().writes(13_u64)) } - /// The range of component `c` is `[0, 2044]`. - fn tasks_pause_program(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `2303 + c * (16400 ±0)` - // Estimated: `4854 + c * (18876 ±0)` - // Minimum execution time: 29_288_000 picoseconds. - Weight::from_parts(29_758_000, 4854) - // Standard Error: 71_310 - .saturating_add(Weight::from_parts(36_877_617, 0).saturating_mul(c.into())) - .saturating_add(RocksDbWeight::get().reads(4_u64)) - .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(c.into()))) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 18876).saturating_mul(c.into())) - } - /// The range of component `c` is `[0, 2044]`. - fn tasks_pause_program_uninited(c: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `3129 + c * (42 ±0)` - // Estimated: `8171 + c * (2517 ±0)` - // Minimum execution time: 86_496_000 picoseconds. - Weight::from_parts(80_366_450, 8171) - // Standard Error: 2_411 - .saturating_add(Weight::from_parts(1_048_389, 0).saturating_mul(c.into())) - .saturating_add(RocksDbWeight::get().reads(13_u64)) - .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(c.into()))) - .saturating_add(RocksDbWeight::get().writes(9_u64)) - .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(c.into()))) - .saturating_add(Weight::from_parts(0, 2517).saturating_mul(c.into())) - } } diff --git a/utils/wasm-gen/src/tests.rs b/utils/wasm-gen/src/tests.rs index 33c41cb2a5c..e9a9c71f8a9 100644 --- a/utils/wasm-gen/src/tests.rs +++ b/utils/wasm-gen/src/tests.rs @@ -387,6 +387,10 @@ fn error_processing_works_for_fallible_syscalls() { let fallible_syscalls = SyscallName::instrumentable() .into_iter() .filter_map(|syscall| { + if matches!(syscall, SyscallName::PayProgramRent) { + return None; + } + let invocable_syscall = InvocableSyscall::Loose(syscall); invocable_syscall.is_fallible().then_some(invocable_syscall) }); @@ -586,7 +590,6 @@ fn execute_wasm_with_custom_configs( let processor_context = ProcessorContext { message_context, max_pages: INITIAL_PAGES.into(), - rent_cost: 10, program_id, value_counter: ValueCounter::new(value), ..ProcessorContext::new_mock()