Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix!: adjust gas distribution formula for NEP264 #6536

Merged
merged 4 commits into from
Apr 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 6 additions & 10 deletions runtime/near-vm-logic/src/receipt_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,26 +447,22 @@ impl ReceiptManager {
return GasDistribution::NoRatios;
}

// Floor division that will ensure gas allocated is <= gas to distribute
let gas_per_weight = (unused_gas as u128 / gas_weight_sum) as Gas;

let mut distribute_gas = |index: &FunctionCallActionIndex, assigned_gas: Gas| {
let FunctionCallAction { gas, .. } =
get_fuction_call_action_mut(&mut self.action_receipts, *index);

// This operation cannot overflow because the gas_per_weight calculation is a floor
// division of the total amount of gas by the weight sum and the remainder is
// distributed exactly.
// Operation cannot overflow because the amount of assigned gas is a fraction of
// the unused gas and is using floor division.
*gas += assigned_gas;
};

let mut distributed = 0;
for (action_index, GasWeight(weight)) in &self.gas_weights {
// This can't overflow because the gas_per_weight is floor division
// of the weight sum.
let assigned_gas = gas_per_weight * weight;
// Multiplication is done in u128 with max values of u64::MAX so this cannot overflow.
// Division result can be truncated to 64 bits because gas_weight_sum >= weight.
let assigned_gas = (unused_gas as u128 * *weight as u128 / gas_weight_sum) as u64;

distribute_gas(action_index, assigned_gas);
distribute_gas(action_index, assigned_gas as u64);

distributed += assigned_gas
}
Expand Down
9 changes: 8 additions & 1 deletion runtime/near-vm-logic/src/tests/gas_counter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,14 @@ fn function_call_weight_basic_cases_test() {
]);

// Weight over u64 bounds
function_call_weight_check(&[(0, u64::MAX, 0), (0, 1000, 10_000_000_000)]);
function_call_weight_check(&[(0, u64::MAX, 9_999_999_999), (0, 1000, 1)]);

// Weight over gas limit with three function calls
function_call_weight_check(&[
(0, 10_000_000_000, 4_999_999_999),
(0, 1, 0),
(0, 10_000_000_000, 5_000_000_001),
]);

// Weights with one zero and one non-zero
function_call_weight_check(&[(0, 0, 0), (0, 1, 10_000_000_000)])
Expand Down