Skip to content

Commit

Permalink
remove get_gas_burned
Browse files Browse the repository at this point in the history
  • Loading branch information
gshep committed Jun 13, 2022
1 parent e303ee1 commit bb3ce7e
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 206 deletions.
209 changes: 4 additions & 205 deletions pallets/gear/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,20 @@
use crate as pallet_gear;
use crate::{
ext::LazyPagesExt,
manager::{ExtManager, HandleKind},
manager::ExtManager,
*,
};
use alloc::format;
use common::{self, lazy_pages, Origin as _, ValueTree};
use common::{self, lazy_pages, Origin as _};
use core_processor::{
common::{DispatchOutcome, DispatchOutcome as CoreDispatchOutcome, JournalNote},
common::{DispatchOutcome, JournalNote},
configs::{AllocationsConfig, BlockInfo},
Ext,
};
use frame_support::{
construct_runtime,
pallet_prelude::*,
parameter_types,
traits::{Currency, FindAuthor, Get},
traits::{Currency, FindAuthor},
};
use frame_system as system;
use gear_backend_sandbox::SandboxEnvironment;
Expand Down Expand Up @@ -345,203 +344,3 @@ pub fn run_with_ext_copy<R, F: FnOnce() -> R>(f: F) -> R {

result
}

pub fn get_gas_burned<T>(
source: H256,
kind: HandleKind,
payload: Vec<u8>,
gas_limit: Option<u64>,
value: u128,
) -> Result<u64, Vec<u8>>
where
T: crate::Config,
T::AccountId: common::Origin,
{
run_with_ext_copy(|| get_gas_burned_internal::<T>(source, kind, payload, gas_limit, value))
}

fn get_gas_burned_internal<T>(
source: H256,
kind: HandleKind,
payload: Vec<u8>,
gas_limit: Option<u64>,
value: u128,
) -> Result<u64, Vec<u8>>
where
T: crate::Config,
T::AccountId: common::Origin,
{
let schedule = T::Schedule::get();
let mut ext_manager = ExtManager::<T>::default();

let bn: u64 = <frame_system::Pallet<T>>::block_number().unique_saturated_into();
let root_message_id = MessageId::from(bn);

let dispatch = match kind {
HandleKind::Init(ref code) => {
let program_id = ProgramId::generate(CodeId::generate(code), b"gas_spent_salt");

let schedule = T::Schedule::get();
let code = Code::try_new(
code.clone(),
schedule.instruction_weights.version,
|module| schedule.rules(module),
)
.map_err(|_| b"Code failed to load: {}".to_vec())?;

let code_and_id = CodeAndId::new(code);
let code_id = code_and_id.code_id();

let _ = crate::Pallet::<T>::set_code_with_metadata(code_and_id, source);

ExtManager::<T>::default().set_program(program_id, code_id, root_message_id);

Dispatch::new(
DispatchKind::Init,
Message::new(
root_message_id,
ProgramId::from_origin(source),
program_id,
payload,
Some(u64::MAX),
value,
None,
),
)
}
HandleKind::Handle(dest) => Dispatch::new(
DispatchKind::Handle,
Message::new(
root_message_id,
ProgramId::from_origin(source),
ProgramId::from_origin(dest),
payload,
Some(u64::MAX),
value,
None,
),
),
HandleKind::Reply(msg_id, exit_code) => {
let msg = MailboxOf::<T>::remove(
<T::AccountId as common::Origin>::from_origin(source),
MessageId::from_origin(msg_id),
)
.map_err(|_| b"Internal error: unable to find message in mailbox".to_vec())?;
Dispatch::new(
DispatchKind::Reply,
Message::new(
root_message_id,
ProgramId::from_origin(source),
msg.source(),
payload,
Some(u64::MAX),
value,
Some((msg.id(), exit_code)),
),
)
}
};

let initial_gas = gas_limit.unwrap_or_else(<T as pallet_gas::Config>::BlockGasLimit::get);
T::GasHandler::create(
source.into_origin(),
root_message_id.into_origin(),
initial_gas,
)
.map_err(|_| b"Internal error: unable to create gas handler".to_vec())?;

let dispatch = dispatch.into_stored();

QueueOf::<T>::clear();

QueueOf::<T>::queue(dispatch).map_err(|_| b"Messages storage corrupted".to_vec())?;

let block_info = BlockInfo {
height: <frame_system::Pallet<T>>::block_number().unique_saturated_into(),
timestamp: <pallet_timestamp::Pallet<T>>::get().unique_saturated_into(),
};

let existential_deposit = <T as Config>::Currency::minimum_balance().unique_saturated_into();

let mut burned = 0;

while let Some(queued_dispatch) =
QueueOf::<T>::dequeue().map_err(|_| b"MQ storage corrupted".to_vec())?
{
let actor_id = queued_dispatch.destination();

let lazy_pages_enabled =
cfg!(feature = "lazy-pages") && lazy_pages::try_to_enable_lazy_pages();

let actor = ext_manager
.get_executable_actor(actor_id, !lazy_pages_enabled)
.ok_or_else(|| b"Program not found in the storage".to_vec())?;

let allocations_config = AllocationsConfig {
max_pages: gear_core::memory::WasmPageNumber(schedule.limits.memory_pages),
init_cost: schedule.memory_weights.initial_cost,
alloc_cost: schedule.memory_weights.allocation_cost,
mem_grow_cost: schedule.memory_weights.grow_cost,
load_page_cost: schedule.memory_weights.load_cost,
};

let gas_limit = T::GasHandler::get_limit(queued_dispatch.id().into_origin())
.ok()
.flatten()
.ok_or_else(|| b"Internal error: unable to get gas limit after execution".to_vec())?;

let journal = if lazy_pages_enabled {
core_processor::process::<LazyPagesExt, SandboxEnvironment<_>>(
Some(actor),
queued_dispatch.into_incoming(gas_limit),
block_info,
allocations_config,
existential_deposit,
ProgramId::from_origin(source),
actor_id,
u64::MAX,
T::OutgoingLimit::get(),
schedule.host_fn_weights.clone().into_core(),
["gr_gas_available"].into(),
)
} else {
core_processor::process::<Ext, SandboxEnvironment<_>>(
Some(actor),
queued_dispatch.into_incoming(gas_limit),
block_info,
allocations_config,
existential_deposit,
ProgramId::from_origin(source),
actor_id,
u64::MAX,
T::OutgoingLimit::get(),
schedule.host_fn_weights.clone().into_core(),
["gr_gas_available"].into(),
)
};

// TODO: Check whether we charge gas fee for submitting code after #646
for note in &journal {
match note {
JournalNote::GasBurned { amount, .. } => {
burned += amount;
}
JournalNote::MessageDispatched {
outcome: CoreDispatchOutcome::MessageTrap { trap, .. },
..
} => {
return Err(format!(
"Program terminated with a trap: {}",
trap.clone().unwrap_or_else(|| "No reason".to_string())
)
.into_bytes());
}
_ => {}
}
}

core_processor::handle_journal(journal, &mut ext_manager);
}

Ok(burned)
}
2 changes: 1 addition & 1 deletion pallets/gear/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
use crate::{
manager::HandleKind,
mock::{
calc_handle_gas_spent, get_gas_burned, new_test_ext, run_to_block, Event as MockEvent,
calc_handle_gas_spent, new_test_ext, run_to_block, Event as MockEvent,
Gear, GearProgram, Origin, System, Test, BLOCK_AUTHOR, LOW_BALANCE_USER, USER_1, USER_2,
USER_3,
},
Expand Down

0 comments on commit bb3ce7e

Please sign in to comment.