From fa5821d92d4c9464740d023b46df64a382f67b7b Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Mon, 11 Dec 2023 17:22:18 +0400 Subject: [PATCH 01/14] remove extrinsics bodies --- pallets/gear/src/lib.rs | 140 ++++++---------------------------------- 1 file changed, 19 insertions(+), 121 deletions(-) diff --git a/pallets/gear/src/lib.rs b/pallets/gear/src/lib.rs index 28ede177994..204099c850a 100644 --- a/pallets/gear/src/lib.rs +++ b/pallets/gear/src/lib.rs @@ -1653,26 +1653,11 @@ pub mod pallet { #[pallet::call_index(8)] #[pallet::weight(::WeightInfo::pay_program_rent())] pub fn pay_program_rent( - origin: OriginFor, - program_id: ProgramId, - block_count: BlockNumberFor, + _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()) + Err(Error::::ProgramRentDisabled.into()) } /// Starts a resume session of the previously paused program. @@ -1686,40 +1671,12 @@ pub mod pallet { #[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, + _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()) + Err(Error::::ProgramRentDisabled.into()) } /// Appends memory pages to the resume session. @@ -1730,22 +1687,13 @@ pub mod pallet { /// - `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))] + #[pallet::weight(DbWeightOf::::get().reads(1))] pub fn resume_session_push( - origin: OriginFor, - session_id: SessionId, - memory_pages: Vec<(GearPage, PageBuf)>, + _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()) + Err(Error::::ProgramRentDisabled.into()) } /// Finishes the program resume session. @@ -1756,63 +1704,13 @@ pub mod pallet { /// - `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)))] + #[pallet::weight(DbWeightOf::::get().reads(1))] pub fn resume_session_commit( - origin: OriginFor, - session_id: SessionId, - block_count: BlockNumberFor, + _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()) + Err(Error::::ProgramRentDisabled.into()) } } From d6894156dfc5fb51d11f0203b2bff07a651ade44 Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Mon, 11 Dec 2023 17:30:29 +0400 Subject: [PATCH 02/14] remove logic of pause program task --- pallets/gear/src/manager/task.rs | 148 ++----------------------------- 1 file changed, 8 insertions(+), 140 deletions(-) diff --git a/pallets/gear/src/manager/task.rs b/pallets/gear/src/manager/task.rs index 02d12383a28..af4bcc82081 100644 --- a/pallets/gear/src/manager/task.rs +++ b/pallets/gear/src/manager/task.rs @@ -17,48 +17,32 @@ // 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, + ProgramStorageOf, QueueOf, }; use alloc::string::ToString; use common::{ event::{ - MessageWokenRuntimeReason, MessageWokenSystemReason, ProgramChangeKind, RuntimeReason, + MessageWokenRuntimeReason, MessageWokenSystemReason, RuntimeReason, SystemReason, UserMessageReadSystemReason, }, paused_program_storage::SessionId, scheduler::*, storage::*, - ActiveProgram, Gas, Origin, PausedProgramStorage, Program, ProgramState, ProgramStorage, + Gas, Origin, PausedProgramStorage, }; 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() @@ -89,126 +73,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()); + fn pause_program(&mut self, _program_id: ProgramId) -> Gas { + log::debug!("Program rent logic is disabled."); - 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"), - } - - *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 { From ffe023e10e863ef4d2fddc622890f13ce21643e6 Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Tue, 12 Dec 2023 14:35:03 +0400 Subject: [PATCH 03/14] remove tests, disable syscall --- core-processor/src/ext.rs | 35 +- pallets/gear-debug/src/tests/mod.rs | 111 --- pallets/gear/src/tests.rs | 1051 +-------------------------- 3 files changed, 39 insertions(+), 1158 deletions(-) diff --git a/core-processor/src/ext.rs b/core-processor/src/ext.rs index 54e6b20f5bf..155e76fa0f8 100644 --- a/core-processor/src/ext.rs +++ b/core-processor/src/ext.rs @@ -1002,39 +1002,10 @@ impl Externalities for Ext { fn pay_program_rent( &mut self, - program_id: ProgramId, - rent: u128, + _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)) + Err(FallibleExtErrorCore::Unsupported.into()) } fn program_id(&self) -> Result { diff --git a/pallets/gear-debug/src/tests/mod.rs b/pallets/gear-debug/src/tests/mod.rs index 9017791a2e0..be51a377e4c 100644 --- a/pallets/gear-debug/src/tests/mod.rs +++ b/pallets/gear-debug/src/tests/mod.rs @@ -921,114 +921,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 = AccountId::from_origin(pay_rent_id.into_origin()); - 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 as u32 - 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/src/tests.rs b/pallets/gear/src/tests.rs index 63cfa56dfc9..470e8a32954 100644 --- a/pallets/gear/src/tests.rs +++ b/pallets/gear/src/tests.rs @@ -47,16 +47,16 @@ 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, + Origin as _, ProgramStorage, ReservableTree, }; use core_processor::{common::ActorExecutionErrorReplyReason, ActorPrepareMemoryError}; use frame_support::{ - assert_err, assert_noop, assert_ok, + assert_noop, assert_ok, codec::{Decode, Encode}, dispatch::Dispatchable, sp_runtime::traits::{TypedGet, Zero}, @@ -6541,1028 +6541,55 @@ fn test_create_program_simple() { } #[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(), - CodeId::from_origin(program.code_hash), - )); - assert_ne!( - old_nonce, - as PausedProgramStorage>::NonceStorage::get() - ); - - assert_ok!(Gear::resume_session_init( - RuntimeOrigin::signed(USER_3), - program_id, - program.allocations.clone(), - CodeId::from_origin(program.code_hash), - )); - - 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, - CodeId::from_origin(program.code_hash), - )); - - 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); - 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), (25_000, expiration_block),]) - .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; - +fn state_request() { 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(); + use demo_custom::{ + btree::{Request, StateRequest}, + InitMessage, WASM_BINARY, + }; - run_to_next_block(None); + let code = WASM_BINARY; + let program_id = generate_program_id(code, DEFAULT_SALT); - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_1), - program_id, - b"0123456789".to_vec(), + 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, )); - 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) + 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, )); - 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 + 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 ); } - }); -} - -#[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, - false, - )); - - 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); - 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, - 0, - false, - )); - - 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 = AccountId::from_origin(pay_rent_id.into_origin()); - let balance_before = Balances::free_balance(pay_rent_account_id); - - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_2), - pay_rent_id, - vec![Kind::PayProgramRent([0u8; 32], rent, None)].encode(), - 20_000_000_000, - 0, - false, - )); - - run_to_next_block(None); - - assert_eq!(balance_before, Balances::free_balance(pay_rent_account_id)); - - // try to pay greater rent than available value - assert_ok!(Gear::send_message( - RuntimeOrigin::signed(USER_2), - pay_rent_id, - vec![Kind::PayProgramRent( - pay_rent_id.into_origin().into(), - program_value, - None - )] - .encode(), - 20_000_000_000, - 0, - false, - )); - - 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 - 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), - None - ) - ] - .encode(), - 20_000_000_000, - Gear::rent_fee_for(u32::MAX), - false, - )); - - 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())), - ); - - // pay maximum possible rent - let block_count = u32::MAX; - assert_ne!(expiration_block, block_count); - let required_value = Gear::rent_fee_for(block_count - expiration_block); - 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(block_count), - None - )] - .encode(), - 20_000_000_000, - required_value, - false, - )); - - let message_id = get_last_message_id(); - - run_to_next_block(None); - - assert_succeed(message_id); - - // we sent with the message value that is equal to rent value for (u32::MAX - expiration_block) blocks - // so the program's balance shouldn't change. - 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!(block_count, program.expiration_block); - assert!(TaskPoolOf::::contains( - &program.expiration_block, - &ScheduledTask::PauseProgram(pay_rent_id) - )); - }); -} - -#[test] -fn pay_program_rent_extrinsic_works() { - 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; - - assert!(TaskPoolOf::::contains( - &old_block, - &ScheduledTask::PauseProgram(program_id) - )); - - let block_count = 10_000; - let balance_before = Balances::free_balance(USER_3); - assert_ok!(Gear::pay_program_rent( - RuntimeOrigin::signed(USER_3), - program_id, - block_count - )); - - let extrinsic_fee = - balance_before - Balances::free_balance(USER_3) - Gear::rent_fee_for(block_count); - - 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(), - ); - 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 balance_before = Balances::free_balance(USER_1); - let block_count = u32::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] @@ -14918,12 +13945,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( From f7ca725613469a12ec9774bdb6051faab581404b Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Tue, 12 Dec 2023 14:48:23 +0400 Subject: [PATCH 04/14] remove benches --- pallets/gear/src/benchmarking/mod.rs | 21 --------- pallets/gear/src/benchmarking/tasks.rs | 54 --------------------- pallets/gear/src/weights.rs | 62 ------------------------- runtime/vara/src/weights/pallet_gear.rs | 62 ------------------------- 4 files changed, 199 deletions(-) diff --git a/pallets/gear/src/benchmarking/mod.rs b/pallets/gear/src/benchmarking/mod.rs index b911e5bcc97..55a4659b17b 100644 --- a/pallets/gear/src/benchmarking/mod.rs +++ b/pallets/gear/src/benchmarking/mod.rs @@ -2854,27 +2854,6 @@ benchmarks! { ext_manager.remove_from_mailbox(T::AccountId::from_origin(user.into_origin()), message_id); } - tasks_pause_program { - let c in 0 .. (MAX_PAGES - 1) * (WASM_PAGE_SIZE / GEAR_PAGE_SIZE) as u32; - - let code = benchmarking::generate_wasm2(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 a7987fb9412..38a85acb658 100644 --- a/pallets/gear/src/benchmarking/tasks.rs +++ b/pallets/gear/src/benchmarking/tasks.rs @@ -44,60 +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 diff --git a/pallets/gear/src/weights.rs b/pallets/gear/src/weights.rs index b0695a26165..d8dc1a0f48f 100644 --- a/pallets/gear/src/weights.rs +++ b/pallets/gear/src/weights.rs @@ -228,8 +228,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; @@ -2197,36 +2195,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: `19878 + c * (84480 ±0)` - // Minimum execution time: 30_995_000 picoseconds. - Weight::from_parts(31_512_000, 19878) - // Standard Error: 83_380 - .saturating_add(Weight::from_parts(39_172_227, 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, 84480).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: `3181 + c * (42 ±0)` - // Estimated: `61147 + c * (2947 ±0)` - // Minimum execution time: 92_674_000 picoseconds. - Weight::from_parts(116_875_856, 61147) - // Standard Error: 2_740 - .saturating_add(Weight::from_parts(1_037_041, 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, 2947).saturating_mul(c.into())) - } } // For backwards compatibility and tests @@ -4188,34 +4156,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: `19878 + c * (84480 ±0)` - // Minimum execution time: 30_995_000 picoseconds. - Weight::from_parts(31_512_000, 19878) - // Standard Error: 83_380 - .saturating_add(Weight::from_parts(39_172_227, 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, 84480).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: `3181 + c * (42 ±0)` - // Estimated: `61147 + c * (2947 ±0)` - // Minimum execution time: 92_674_000 picoseconds. - Weight::from_parts(116_875_856, 61147) - // Standard Error: 2_740 - .saturating_add(Weight::from_parts(1_037_041, 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, 2947).saturating_mul(c.into())) - } } diff --git a/runtime/vara/src/weights/pallet_gear.rs b/runtime/vara/src/weights/pallet_gear.rs index 76d4cbfb0af..6a542b6a81c 100644 --- a/runtime/vara/src/weights/pallet_gear.rs +++ b/runtime/vara/src/weights/pallet_gear.rs @@ -228,8 +228,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; @@ -2197,36 +2195,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: `19878 + c * (84480 ±0)` - // Minimum execution time: 30_995_000 picoseconds. - Weight::from_parts(31_512_000, 19878) - // Standard Error: 83_380 - .saturating_add(Weight::from_parts(39_172_227, 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, 84480).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: `3181 + c * (42 ±0)` - // Estimated: `61147 + c * (2947 ±0)` - // Minimum execution time: 92_674_000 picoseconds. - Weight::from_parts(116_875_856, 61147) - // Standard Error: 2_740 - .saturating_add(Weight::from_parts(1_037_041, 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, 2947).saturating_mul(c.into())) - } } // For backwards compatibility and tests @@ -4188,34 +4156,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: `19878 + c * (84480 ±0)` - // Minimum execution time: 30_995_000 picoseconds. - Weight::from_parts(31_512_000, 19878) - // Standard Error: 83_380 - .saturating_add(Weight::from_parts(39_172_227, 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, 84480).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: `3181 + c * (42 ±0)` - // Estimated: `61147 + c * (2947 ±0)` - // Minimum execution time: 92_674_000 picoseconds. - Weight::from_parts(116_875_856, 61147) - // Standard Error: 2_740 - .saturating_add(Weight::from_parts(1_037_041, 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, 2947).saturating_mul(c.into())) - } } From 9be655372ce6dfa3a26799644b69935f5dbb2ea6 Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Tue, 12 Dec 2023 17:13:03 +0400 Subject: [PATCH 05/14] remove extrinsics benches --- pallets/gear/src/benchmarking/mod.rs | 163 +----------------------- pallets/gear/src/lib.rs | 4 +- pallets/gear/src/weights.rs | 92 ------------- runtime/vara/src/weights/pallet_gear.rs | 92 ------------- 4 files changed, 5 insertions(+), 346 deletions(-) diff --git a/pallets/gear/src/benchmarking/mod.rs b/pallets/gear/src/benchmarking/mod.rs index 55a4659b17b..a4786f2b698 100644 --- a/pallets/gear/src/benchmarking/mod.rs +++ b/pallets/gear/src/benchmarking/mod.rs @@ -60,10 +60,10 @@ use crate::{ schedule::{API_BENCHMARK_BATCH_SIZE, INSTR_BENCHMARK_BATCH_SIZE}, BalanceOf, BenchmarkStorage, Call, Config, CurrencyOf, Event, Ext as Externalities, GasHandlerOf, GearBank, MailboxOf, Pallet as Gear, Pallet, ProgramStorageOf, QueueOf, - RentFreePeriodOf, ResumeMinimalPeriodOf, Schedule, TaskPoolOf, + Schedule, TaskPoolOf, }; use ::alloc::{ - collections::{BTreeMap, BTreeSet}, + collections::BTreeMap, vec, }; use common::{ @@ -91,7 +91,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::{ @@ -266,39 +266,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, - CodeId::from_origin(program.code_hash), - ) - .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 { @@ -495,130 +462,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_wasm2(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_wasm2(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, CodeId::from_origin(program.code_hash)) - 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_wasm2(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_wasm2(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. // diff --git a/pallets/gear/src/lib.rs b/pallets/gear/src/lib.rs index 204099c850a..5fd033cb53c 100644 --- a/pallets/gear/src/lib.rs +++ b/pallets/gear/src/lib.rs @@ -1651,7 +1651,7 @@ pub mod pallet { /// Pay additional rent for the program. #[pallet::call_index(8)] - #[pallet::weight(::WeightInfo::pay_program_rent())] + #[pallet::weight(DbWeightOf::::get().reads(1))] pub fn pay_program_rent( _origin: OriginFor, _program_id: ProgramId, @@ -1669,7 +1669,7 @@ pub mod pallet { /// - `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())] + #[pallet::weight(DbWeightOf::::get().reads(1))] pub fn resume_session_init( _origin: OriginFor, _program_id: ProgramId, diff --git a/pallets/gear/src/weights.rs b/pallets/gear/src/weights.rs index d8dc1a0f48f..41c88564a35 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; @@ -424,50 +420,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: `21579` - // Minimum execution time: 56_262_000 picoseconds. - Weight::from_parts(58_296_000, 21579) - .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: `17486` - // Minimum execution time: 30_127_000 picoseconds. - Weight::from_parts(31_137_000, 17486) - .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: `7640` - // Minimum execution time: 7_944_000 picoseconds. - Weight::from_parts(3_967_373, 7640) - // Standard Error: 35_621 - .saturating_add(Weight::from_parts(13_338_658, 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: `43266 + c * (131112 ±0)` - // Minimum execution time: 72_793_000 picoseconds. - Weight::from_parts(73_500_000, 43266) - // Standard Error: 159_839 - .saturating_add(Weight::from_parts(53_776_845, 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, 131112).saturating_mul(c.into())) - } /// The range of component `c` is `[0, 250]`. fn upload_code(c: u32, ) -> Weight { // Proof Size summary in bytes: @@ -2385,50 +2337,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: `21579` - // Minimum execution time: 56_262_000 picoseconds. - Weight::from_parts(58_296_000, 21579) - .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: `17486` - // Minimum execution time: 30_127_000 picoseconds. - Weight::from_parts(31_137_000, 17486) - .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: `7640` - // Minimum execution time: 7_944_000 picoseconds. - Weight::from_parts(3_967_373, 7640) - // Standard Error: 35_621 - .saturating_add(Weight::from_parts(13_338_658, 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: `43266 + c * (131112 ±0)` - // Minimum execution time: 72_793_000 picoseconds. - Weight::from_parts(73_500_000, 43266) - // Standard Error: 159_839 - .saturating_add(Weight::from_parts(53_776_845, 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, 131112).saturating_mul(c.into())) - } /// The range of component `c` is `[0, 250]`. fn upload_code(c: u32, ) -> Weight { // Proof Size summary in bytes: diff --git a/runtime/vara/src/weights/pallet_gear.rs b/runtime/vara/src/weights/pallet_gear.rs index 6a542b6a81c..4a6f7c8bad8 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; @@ -424,50 +420,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: `21579` - // Minimum execution time: 56_262_000 picoseconds. - Weight::from_parts(58_296_000, 21579) - .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: `17486` - // Minimum execution time: 30_127_000 picoseconds. - Weight::from_parts(31_137_000, 17486) - .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: `7640` - // Minimum execution time: 7_944_000 picoseconds. - Weight::from_parts(3_967_373, 7640) - // Standard Error: 35_621 - .saturating_add(Weight::from_parts(13_338_658, 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: `43266 + c * (131112 ±0)` - // Minimum execution time: 72_793_000 picoseconds. - Weight::from_parts(73_500_000, 43266) - // Standard Error: 159_839 - .saturating_add(Weight::from_parts(53_776_845, 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, 131112).saturating_mul(c.into())) - } /// The range of component `c` is `[0, 250]`. fn upload_code(c: u32, ) -> Weight { // Proof Size summary in bytes: @@ -2385,50 +2337,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: `21579` - // Minimum execution time: 56_262_000 picoseconds. - Weight::from_parts(58_296_000, 21579) - .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: `17486` - // Minimum execution time: 30_127_000 picoseconds. - Weight::from_parts(31_137_000, 17486) - .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: `7640` - // Minimum execution time: 7_944_000 picoseconds. - Weight::from_parts(3_967_373, 7640) - // Standard Error: 35_621 - .saturating_add(Weight::from_parts(13_338_658, 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: `43266 + c * (131112 ±0)` - // Minimum execution time: 72_793_000 picoseconds. - Weight::from_parts(73_500_000, 43266) - // Standard Error: 159_839 - .saturating_add(Weight::from_parts(53_776_845, 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, 131112).saturating_mul(c.into())) - } /// The range of component `c` is `[0, 250]`. fn upload_code(c: u32, ) -> Weight { // Proof Size summary in bytes: From ffe5452c1d5615a64226e449507ab73804f67947 Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Tue, 12 Dec 2023 17:21:34 +0400 Subject: [PATCH 06/14] remove remove_resume_session task --- pallets/gear/src/benchmarking/mod.rs | 17 +----------- pallets/gear/src/benchmarking/tasks.rs | 37 ------------------------- pallets/gear/src/manager/task.rs | 18 ++++-------- pallets/gear/src/weights.rs | 19 ------------- runtime/vara/src/weights/pallet_gear.rs | 19 ------------- 5 files changed, 6 insertions(+), 104 deletions(-) diff --git a/pallets/gear/src/benchmarking/mod.rs b/pallets/gear/src/benchmarking/mod.rs index a4786f2b698..6a79f8f23ec 100644 --- a/pallets/gear/src/benchmarking/mod.rs +++ b/pallets/gear/src/benchmarking/mod.rs @@ -68,10 +68,9 @@ use ::alloc::{ }; use common::{ self, benchmarking, - paused_program_storage::SessionId, scheduler::{ScheduledTask, TaskHandler}, storage::{Counter, *}, - ActiveProgram, CodeMetadata, CodeStorage, GasTree, Origin, PausedProgramStorage, + ActiveProgram, CodeMetadata, CodeStorage, GasTree, Origin, ProgramStorage, ReservableTree, }; use core_processor::{ @@ -242,13 +241,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, @@ -2635,13 +2627,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(); diff --git a/pallets/gear/src/benchmarking/tasks.rs b/pallets/gear/src/benchmarking/tasks.rs index 38a85acb658..0107a1409d0 100644 --- a/pallets/gear/src/benchmarking/tasks.rs +++ b/pallets/gear/src/benchmarking/tasks.rs @@ -44,43 +44,6 @@ where Gear::::process_queue(Default::default()); } -#[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_wasm2(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/manager/task.rs b/pallets/gear/src/manager/task.rs index af4bcc82081..105657356f4 100644 --- a/pallets/gear/src/manager/task.rs +++ b/pallets/gear/src/manager/task.rs @@ -18,7 +18,7 @@ use crate::{ manager::ExtManager, weights::WeightInfo, Config, DispatchStashOf, Event, Pallet, - ProgramStorageOf, QueueOf, + QueueOf, }; use alloc::string::ToString; use common::{ @@ -29,7 +29,7 @@ use common::{ paused_program_storage::SessionId, scheduler::*, storage::*, - Gas, Origin, PausedProgramStorage, + Gas, Origin, }; use core::cmp; use gear_core::{ @@ -63,9 +63,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, } } @@ -276,13 +274,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/weights.rs b/pallets/gear/src/weights.rs index 41c88564a35..a07dc4467af 100644 --- a/pallets/gear/src/weights.rs +++ b/pallets/gear/src/weights.rs @@ -215,7 +215,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; @@ -2067,15 +2066,6 @@ impl WeightInfo for SubstrateWeight { // Standard Error: 5_878 .saturating_add(Weight::from_parts(722_117, 0).saturating_mul(r.into())) } - fn tasks_remove_resume_session() -> Weight { - // Proof Size summary in bytes: - // Measured: `352` - // Estimated: `4169` - // Minimum execution time: 5_941_000 picoseconds. - Weight::from_parts(6_194_000, 4169) - .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` @@ -3984,15 +3974,6 @@ impl WeightInfo for () { // Standard Error: 5_878 .saturating_add(Weight::from_parts(722_117, 0).saturating_mul(r.into())) } - fn tasks_remove_resume_session() -> Weight { - // Proof Size summary in bytes: - // Measured: `352` - // Estimated: `4169` - // Minimum execution time: 5_941_000 picoseconds. - Weight::from_parts(6_194_000, 4169) - .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` diff --git a/runtime/vara/src/weights/pallet_gear.rs b/runtime/vara/src/weights/pallet_gear.rs index 4a6f7c8bad8..11fcf26e3ea 100644 --- a/runtime/vara/src/weights/pallet_gear.rs +++ b/runtime/vara/src/weights/pallet_gear.rs @@ -215,7 +215,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; @@ -2067,15 +2066,6 @@ impl pallet_gear::WeightInfo for SubstrateWeight { // Standard Error: 5_878 .saturating_add(Weight::from_parts(722_117, 0).saturating_mul(r.into())) } - fn tasks_remove_resume_session() -> Weight { - // Proof Size summary in bytes: - // Measured: `352` - // Estimated: `4169` - // Minimum execution time: 5_941_000 picoseconds. - Weight::from_parts(6_194_000, 4169) - .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` @@ -3984,15 +3974,6 @@ impl WeightInfo for () { // Standard Error: 5_878 .saturating_add(Weight::from_parts(722_117, 0).saturating_mul(r.into())) } - fn tasks_remove_resume_session() -> Weight { - // Proof Size summary in bytes: - // Measured: `352` - // Estimated: `4169` - // Minimum execution time: 5_941_000 picoseconds. - Weight::from_parts(6_194_000, 4169) - .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` From 9a2ce95d96938bf69ee43e02a6780dd34ea08adb Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Wed, 13 Dec 2023 11:30:14 +0400 Subject: [PATCH 07/14] make fmt & clippy --- pallets/gear-debug/src/tests/mod.rs | 15 ++++----------- pallets/gear-debug/src/tests/utils.rs | 20 -------------------- pallets/gear/src/benchmarking/mod.rs | 12 ++++-------- pallets/gear/src/manager/task.rs | 7 +++---- pallets/gear/src/tests.rs | 3 +-- 5 files changed, 12 insertions(+), 45 deletions(-) diff --git a/pallets/gear-debug/src/tests/mod.rs b/pallets/gear-debug/src/tests/mod.rs index be51a377e4c..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; 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 6a79f8f23ec..bbf6da94ad4 100644 --- a/pallets/gear/src/benchmarking/mod.rs +++ b/pallets/gear/src/benchmarking/mod.rs @@ -59,19 +59,15 @@ use crate::{ pallet, schedule::{API_BENCHMARK_BATCH_SIZE, INSTR_BENCHMARK_BATCH_SIZE}, BalanceOf, BenchmarkStorage, Call, Config, CurrencyOf, Event, Ext as Externalities, - GasHandlerOf, GearBank, MailboxOf, Pallet as Gear, Pallet, ProgramStorageOf, QueueOf, - Schedule, TaskPoolOf, -}; -use ::alloc::{ - collections::BTreeMap, - vec, + GasHandlerOf, GearBank, MailboxOf, Pallet as Gear, Pallet, ProgramStorageOf, QueueOf, Schedule, + TaskPoolOf, }; +use ::alloc::{collections::BTreeMap, vec}; use common::{ self, benchmarking, scheduler::{ScheduledTask, TaskHandler}, storage::{Counter, *}, - ActiveProgram, CodeMetadata, CodeStorage, GasTree, Origin, - ProgramStorage, ReservableTree, + ActiveProgram, CodeMetadata, CodeStorage, GasTree, Origin, ProgramStorage, ReservableTree, }; use core_processor::{ common::{DispatchOutcome, JournalNote}, diff --git a/pallets/gear/src/manager/task.rs b/pallets/gear/src/manager/task.rs index 105657356f4..21b3826b8aa 100644 --- a/pallets/gear/src/manager/task.rs +++ b/pallets/gear/src/manager/task.rs @@ -17,14 +17,13 @@ // along with this program. If not, see . use crate::{ - manager::ExtManager, weights::WeightInfo, Config, DispatchStashOf, Event, Pallet, - QueueOf, + manager::ExtManager, weights::WeightInfo, Config, DispatchStashOf, Event, Pallet, QueueOf, }; use alloc::string::ToString; use common::{ event::{ - MessageWokenRuntimeReason, MessageWokenSystemReason, RuntimeReason, - SystemReason, UserMessageReadSystemReason, + MessageWokenRuntimeReason, MessageWokenSystemReason, RuntimeReason, SystemReason, + UserMessageReadSystemReason, }, paused_program_storage::SessionId, scheduler::*, diff --git a/pallets/gear/src/tests.rs b/pallets/gear/src/tests.rs index 470e8a32954..bc1a6f8a72a 100644 --- a/pallets/gear/src/tests.rs +++ b/pallets/gear/src/tests.rs @@ -47,8 +47,7 @@ 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, - Schedule, TaskPoolOf, WaitlistOf, + ProgramStorageOf, QueueOf, Schedule, TaskPoolOf, WaitlistOf, }; use common::{ event::*, scheduler::*, storage::*, ActiveProgram, CodeStorage, GasTree, LockId, LockableTree, From bb3b52c10af7b8db95454843364b55c7457ff2af Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Thu, 14 Dec 2023 10:05:07 +0400 Subject: [PATCH 08/14] remove extrinsics --- pallets/gear/src/lib.rs | 66 ----------------------------------------- 1 file changed, 66 deletions(-) diff --git a/pallets/gear/src/lib.rs b/pallets/gear/src/lib.rs index 93b866f7582..311262c084e 100644 --- a/pallets/gear/src/lib.rs +++ b/pallets/gear/src/lib.rs @@ -73,9 +73,7 @@ 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}; @@ -1639,70 +1637,6 @@ pub mod pallet { Ok(()) } - - /// Pay additional rent for the program. - #[pallet::call_index(8)] - #[pallet::weight(DbWeightOf::::get().reads(1))] - pub fn pay_program_rent( - _origin: OriginFor, - _program_id: ProgramId, - _block_count: BlockNumberFor, - ) -> DispatchResultWithPostInfo { - Err(Error::::ProgramRentDisabled.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(DbWeightOf::::get().reads(1))] - pub fn resume_session_init( - _origin: OriginFor, - _program_id: ProgramId, - _allocations: BTreeSet, - _code_hash: CodeId, - ) -> DispatchResultWithPostInfo { - Err(Error::::ProgramRentDisabled.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(DbWeightOf::::get().reads(1))] - pub fn resume_session_push( - _origin: OriginFor, - _session_id: SessionId, - _memory_pages: Vec<(GearPage, PageBuf)>, - ) -> DispatchResultWithPostInfo { - Err(Error::::ProgramRentDisabled.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))] - pub fn resume_session_commit( - _origin: OriginFor, - _session_id: SessionId, - _block_count: BlockNumberFor, - ) -> DispatchResultWithPostInfo { - Err(Error::::ProgramRentDisabled.into()) - } } impl Pallet From c3341a4f50ee6bedd67e8618262055f0c1fae15b Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Thu, 14 Dec 2023 10:41:54 +0400 Subject: [PATCH 09/14] remove rent logic from core-processor --- core-processor/src/common.rs | 14 -- core-processor/src/configs.rs | 4 - core-processor/src/executor.rs | 5 - core-processor/src/ext.rs | 9 - core-processor/src/handler.rs | 5 - core-processor/src/processing.rs | 13 -- gtest/src/lib.rs | 4 - gtest/src/manager.rs | 6 +- pallets/gear/src/benchmarking/mod.rs | 2 - .../benchmarking/tests/syscalls_integrity.rs | 34 +--- pallets/gear/src/benchmarking/utils.rs | 3 +- pallets/gear/src/internal.rs | 71 +------ pallets/gear/src/lib.rs | 22 +- pallets/gear/src/manager/journal.rs | 28 +-- pallets/gear/src/tests.rs | 190 +----------------- utils/wasm-gen/src/tests.rs | 1 - 16 files changed, 19 insertions(+), 392 deletions(-) diff --git a/core-processor/src/common.rs b/core-processor/src/common.rs index 26db8af94c5..6ec99100eb6 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 155e76fa0f8..16801ee4cce 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) } 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/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 366d6836464..98c7c680ac4 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::*, @@ -847,7 +846,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), }; @@ -1180,8 +1178,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/src/benchmarking/mod.rs b/pallets/gear/src/benchmarking/mod.rs index 3ed70dc675e..d591daa532a 100644 --- a/pallets/gear/src/benchmarking/mod.rs +++ b/pallets/gear/src/benchmarking/mod.rs @@ -188,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, @@ -197,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), } } diff --git a/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs b/pallets/gear/src/benchmarking/tests/syscalls_integrity.rs index 379734d72c1..571d26e4534 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() @@ -192,40 +191,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 311262c084e..a7d84d91191 100644 --- a/pallets/gear/src/lib.rs +++ b/pallets/gear/src/lib.rs @@ -113,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 VoucherOf = ::Voucher; pub(crate) type GearBank = pallet_gear_bank::Pallet; @@ -619,7 +615,7 @@ pub mod pallet { program_id, &code_info, message_id, - block_number.saturating_add(RentFreePeriodOf::::get()), + block_number, ); Self::create( @@ -1047,7 +1043,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(), } } @@ -1205,20 +1200,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: block_number, }, }; @@ -1242,10 +1236,6 @@ 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); @@ -1255,12 +1245,6 @@ pub mod pallet { pub fn run_call(max_gas: Option>) -> Call { Call::run { max_gas } } - - 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()) - } } #[pallet::call] 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/tests.rs b/pallets/gear/src/tests.rs index 1e957012787..ac04db4d966 100644 --- a/pallets/gear/src/tests.rs +++ b/pallets/gear/src/tests.rs @@ -50,8 +50,8 @@ use crate::{ ProgramStorageOf, QueueOf, Schedule, TaskPoolOf, WaitlistOf, }; use common::{ - event::*, scheduler::*, storage::*, ActiveProgram, CodeStorage, GasTree, LockId, LockableTree, - Origin as _, ProgramStorage, ReservableTree, + event::*, scheduler::*, storage::*, CodeStorage, GasTree, LockId, LockableTree, Origin as _, + ProgramStorage, ReservableTree, }; use core_processor::{common::ActorExecutionErrorReplyReason, ActorPrepareMemoryError}; use frame_support::{ @@ -6193,73 +6193,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; @@ -13791,125 +13724,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; diff --git a/utils/wasm-gen/src/tests.rs b/utils/wasm-gen/src/tests.rs index 567133a208a..9b2c96974db 100644 --- a/utils/wasm-gen/src/tests.rs +++ b/utils/wasm-gen/src/tests.rs @@ -406,7 +406,6 @@ fn execute_wasm_with_custom_configs( let processor_context = ProcessorContext { message_context, max_pages: INITIAL_PAGES.into(), - rent_cost: 10, program_id, ..ProcessorContext::new_mock() }; From a5ccaa3735373232b354347d749d6a13b87c2f4f Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Thu, 14 Dec 2023 12:01:11 +0400 Subject: [PATCH 10/14] adjust bench --- pallets/gear/src/benchmarking/mod.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/pallets/gear/src/benchmarking/mod.rs b/pallets/gear/src/benchmarking/mod.rs index d591daa532a..a496ab323af 100644 --- a/pallets/gear/src/benchmarking/mod.rs +++ b/pallets/gear/src/benchmarking/mod.rs @@ -1431,9 +1431,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; From c68d493c09e7109c436736cc9b6e53930c82e83d Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Thu, 14 Dec 2023 14:17:32 +0400 Subject: [PATCH 11/14] update generated metadata --- gsdk/src/metadata/generated.rs | 55 ---------------------------------- 1 file changed, 55 deletions(-) diff --git a/gsdk/src/metadata/generated.rs b/gsdk/src/metadata/generated.rs index b64cac4330e..ce721e073cf 100644 --- a/gsdk/src/metadata/generated.rs +++ b/gsdk/src/metadata/generated.rs @@ -2558,53 +2558,6 @@ pub mod runtime_types { #[doc = ""] #[doc = "Requires root origin (eventually, will only be set via referendum)"] set_execute_inherent { value: ::core::primitive::bool }, - #[codec(index = 8)] - #[doc = "Pay additional rent for the program."] - pay_program_rent { - program_id: runtime_types::gear_core::ids::ProgramId, - block_count: ::core::primitive::u32, - }, - #[codec(index = 9)] - #[doc = "Starts a resume session of the previously paused program."] - #[doc = ""] - #[doc = "The origin must be Signed."] - #[doc = ""] - #[doc = "Parameters:"] - #[doc = "- `program_id`: id of the program to resume."] - #[doc = "- `allocations`: memory allocations of program prior to stop."] - #[doc = "- `code_hash`: id of the program binary code."] - 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 = "Appends memory pages to the resume session."] - #[doc = ""] - #[doc = "The origin must be Signed and should be the owner of the session."] - #[doc = ""] - #[doc = "Parameters:"] - #[doc = "- `session_id`: id of the resume session."] - #[doc = "- `memory_pages`: program memory (or its part) before it was paused."] - 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 = "Finishes the program resume session."] - #[doc = ""] - #[doc = "The origin must be Signed and should be the owner of the session."] - #[doc = ""] - #[doc = "Parameters:"] - #[doc = "- `session_id`: id of the resume session."] - #[doc = "- `block_count`: the specified period of rent."] - 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 = "\n\t\t\tCustom [dispatch errors](https://docs.substrate.io/main-docs/build/events-errors/)\n\t\t\tof this pallet.\n\t\t\t"] @@ -9452,10 +9405,6 @@ pub mod calls { ClaimValue, Run, SetExecuteInherent, - PayProgramRent, - ResumeSessionInit, - ResumeSessionPush, - ResumeSessionCommit, } impl CallInfo for GearCall { const PALLET: &'static str = "Gear"; @@ -9469,10 +9418,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", } } } From 8ddaa4275e1fbdea39749507e49ce6beeebfdae2 Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Tue, 9 Jan 2024 16:03:28 +0400 Subject: [PATCH 12/14] fix review remarks --- core-processor/src/ext.rs | 4 ++-- examples/syscalls/src/wasm.rs | 1 + gcore/src/exec.rs | 2 ++ gstd/src/exec/basic.rs | 2 ++ gsys/src/lib.rs | 1 + pallets/gear/src/benchmarking/mod.rs | 5 +---- pallets/gear/src/lib.rs | 2 +- pallets/gear/src/tests.rs | 2 +- 8 files changed, 11 insertions(+), 8 deletions(-) diff --git a/core-processor/src/ext.rs b/core-processor/src/ext.rs index 16801ee4cce..a498e645619 100644 --- a/core-processor/src/ext.rs +++ b/core-processor/src/ext.rs @@ -994,9 +994,9 @@ impl Externalities for Ext { fn pay_program_rent( &mut self, _program_id: ProgramId, - _rent: u128, + rent: u128, ) -> Result<(u128, u32), Self::FallibleError> { - Err(FallibleExtErrorCore::Unsupported.into()) + Ok((rent, 0)) } fn program_id(&self) -> Result { diff --git a/examples/syscalls/src/wasm.rs b/examples/syscalls/src/wasm.rs index 9b6a8d39a1f..016cded4921 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(warnings)] 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..b145d7b71e8 100644 --- a/gcore/src/exec.rs +++ b/gcore/src/exec.rs @@ -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] pub fn pay_program_rent(program_id: ActorId, value: u128) -> Result<(u128, u32)> { let rent_pid = HashWithValue { hash: program_id.0, diff --git a/gstd/src/exec/basic.rs b/gstd/src/exec/basic.rs index 6ddd38c083d..dfbf1000e17 100644 --- a/gstd/src/exec/basic.rs +++ b/gstd/src/exec/basic.rs @@ -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] 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/pallets/gear/src/benchmarking/mod.rs b/pallets/gear/src/benchmarking/mod.rs index dba1ccab30e..d6627afe3a8 100644 --- a/pallets/gear/src/benchmarking/mod.rs +++ b/pallets/gear/src/benchmarking/mod.rs @@ -62,10 +62,7 @@ use crate::{ Ext as Externalities, GasHandlerOf, GearBank, MailboxOf, Pallet as Gear, Pallet, ProgramStorageOf, QueueOf, Schedule, TaskPoolOf, }; -use ::alloc::{ - collections::BTreeMap, - vec, -}; +use ::alloc::{collections::BTreeMap, vec}; use common::{ self, benchmarking, scheduler::{ScheduledTask, TaskHandler}, diff --git a/pallets/gear/src/lib.rs b/pallets/gear/src/lib.rs index 75ecc890dce..c3a61b89261 100644 --- a/pallets/gear/src/lib.rs +++ b/pallets/gear/src/lib.rs @@ -1199,7 +1199,7 @@ pub mod pallet { let program_event = Event::ProgramChanged { id: program_id, change: ProgramChangeKind::ProgramSet { - expiration: block_number, + expiration: u64::MAX.unique_saturated_into(), }, }; diff --git a/pallets/gear/src/tests.rs b/pallets/gear/src/tests.rs index ad7655a9da7..54d4538c475 100644 --- a/pallets/gear/src/tests.rs +++ b/pallets/gear/src/tests.rs @@ -55,7 +55,7 @@ use common::{ }; use core_processor::{common::ActorExecutionErrorReplyReason, ActorPrepareMemoryError}; use frame_support::{ - assert_noop, assert_err, assert_ok, + assert_err, assert_noop, assert_ok, codec::{Decode, Encode}, dispatch::Dispatchable, sp_runtime::traits::{TypedGet, Zero}, From f727cfc115cfd2b7be0e07e2c88f491bf692ba0c Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Tue, 9 Jan 2024 16:34:27 +0400 Subject: [PATCH 13/14] fix doc & wasm-gen tests --- gcore/src/exec.rs | 2 +- gstd/src/exec/basic.rs | 2 +- utils/wasm-gen/src/tests.rs | 4 ++++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/gcore/src/exec.rs b/gcore/src/exec.rs index b145d7b71e8..984e15a9758 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] diff --git a/gstd/src/exec/basic.rs b/gstd/src/exec/basic.rs index dfbf1000e17..fc932690b52 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] diff --git a/utils/wasm-gen/src/tests.rs b/utils/wasm-gen/src/tests.rs index 17b8d56b14e..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) }); From 4aafe148989c28ac932505f8158787e1ab07d1ad Mon Sep 17 00:00:00 2001 From: Georgy Shepelev Date: Wed, 10 Jan 2024 14:28:50 +0400 Subject: [PATCH 14/14] fix review remakrs --- examples/syscalls/src/wasm.rs | 2 +- gcore/src/exec.rs | 2 +- gstd/src/exec/basic.rs | 2 +- pallets/gear/src/lib.rs | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/syscalls/src/wasm.rs b/examples/syscalls/src/wasm.rs index 016cded4921..f25da1a924c 100644 --- a/examples/syscalls/src/wasm.rs +++ b/examples/syscalls/src/wasm.rs @@ -160,7 +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(warnings)] + #[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 984e15a9758..a5abe82ce29 100644 --- a/gcore/src/exec.rs +++ b/gcore/src/exec.rs @@ -420,7 +420,7 @@ pub fn program_id() -> ActorId { /// } /// ``` #[allow(warnings)] -#[deprecated] +#[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/gstd/src/exec/basic.rs b/gstd/src/exec/basic.rs index fc932690b52..7c61b4c400b 100644 --- a/gstd/src/exec/basic.rs +++ b/gstd/src/exec/basic.rs @@ -124,7 +124,7 @@ pub fn wake_delayed(message_id: MessageId, delay: u32) -> Result<()> { /// } /// ``` #[allow(warnings)] -#[deprecated] +#[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/pallets/gear/src/lib.rs b/pallets/gear/src/lib.rs index c3a61b89261..ab52a4fa5b4 100644 --- a/pallets/gear/src/lib.rs +++ b/pallets/gear/src/lib.rs @@ -80,7 +80,7 @@ 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::{ @@ -1199,7 +1199,7 @@ pub mod pallet { let program_event = Event::ProgramChanged { id: program_id, change: ProgramChangeKind::ProgramSet { - expiration: u64::MAX.unique_saturated_into(), + expiration: BlockNumberFor::::max_value(), }, };