Skip to content

Commit

Permalink
fix!: adjust gas distribution formula for NEP264 (#6536)
Browse files Browse the repository at this point in the history
Adjusting formula based on @matklad suggestion. It more closely represents distributing gas based on weights if the sum of weights is greater than the amount of gas remaining at the cost of performing slightly more arithmetic.

I think this makes more sense, but hard to think about the exact implications without some benchmark of the two.
  • Loading branch information
austinabell authored Apr 6, 2022
1 parent 6be2e0e commit a7a1f2f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
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

0 comments on commit a7a1f2f

Please sign in to comment.