contracts: Fix double charge of gas for host functions (#3361)

This PR is fixing a bug in the sync mechanism between wasmi and
pallet-contracts. This bug leads to essentially double charging all the
gas that was used during the execution of the host function. When the
`call` host function is used for recursion this will lead to a quadratic
amount of gas consumption with regard to the nesting depth.We also took
the chance to refactor the code in question and improve the rust docs.

The bug was caused by not updating `GasMeter::executor_consumed`
(previously `engine_consumed`) when leaving the host function. This lead
to the value being stale (too low) when entering another host function.

---------

Co-authored-by: PG Herveou <pgherveou@gmail.com>
This commit is contained in:
Alexander Theißen
2024-02-21 18:14:48 +08:00
committed by GitHub
parent 579ef32ddd
commit f3a6b6dcea
6 changed files with 193 additions and 51 deletions
+17 -20
View File
@@ -638,37 +638,34 @@ fn expand_functions(def: &EnvDef, expand_blocks: bool, host_state: TokenStream2)
};
let sync_gas_before = if expand_blocks {
quote! {
// Gas left in the gas meter right before switching to engine execution.
let __gas_before__ = {
let engine_consumed_total =
// Write gas from wasmi into pallet-contracts before entering the host function.
let __gas_left_before__ = {
let executor_total =
__caller__.fuel_consumed().expect("Fuel metering is enabled; qed");
let gas_meter = __caller__.data_mut().ext().gas_meter_mut();
gas_meter
.charge_fuel(engine_consumed_total)
__caller__
.data_mut()
.ext()
.gas_meter_mut()
.sync_from_executor(executor_total)
.map_err(TrapReason::from)
.map_err(#into_host)?
.ref_time()
};
}
} else {
quote! { }
};
// Gas left in the gas meter right after returning from engine execution.
// Write gas from pallet-contracts into wasmi after leaving the host function.
let sync_gas_after = if expand_blocks {
quote! {
let mut gas_after = __caller__.data_mut().ext().gas_meter().gas_left().ref_time();
let mut host_consumed = __gas_before__.saturating_sub(gas_after);
// Possible undercharge of at max 1 fuel here, if host consumed less than `instruction_weights.base`
// Not a problem though, as soon as host accounts its spent gas properly.
let fuel_consumed = host_consumed
.checked_div(__caller__.data_mut().ext().schedule().instruction_weights.base as u64)
.ok_or(Error::<E::T>::InvalidSchedule)
.map_err(TrapReason::from)
.map_err(#into_host)?;
let fuel_consumed = __caller__
.data_mut()
.ext()
.gas_meter_mut()
.sync_to_executor(__gas_left_before__)
.map_err(TrapReason::from)?;
__caller__
.consume_fuel(fuel_consumed)
.map_err(|_| TrapReason::from(Error::<E::T>::OutOfGas))
.map_err(#into_host)?;
.consume_fuel(fuel_consumed.into())
.map_err(|_| TrapReason::from(Error::<E::T>::OutOfGas))?;
}
} else {
quote! { }