balancer / balancer-core

Balancer on the EVM
GNU General Public License v3.0
333 stars 168 forks source link

bpow can take a very large amount of gas to compute certain values #207

Closed ggrieco-tob closed 4 years ago

ggrieco-tob commented 4 years ago

Severity: Undetermined Difficulty: High

Description

The computation of certain values using bpow can take a very large amount of gas, making them practically impossible to afford by users.

The bpow function uses specific code to approximate the value to compute iteratively:

https://github.com/balancer-labs/balancer-core/blob/60486e121b42374818c6522dfeb4d783d00fd0a4/contracts/BNum.sol#L128-L163

However, certain corner cases could take a huge amount of gas to compute, for instance: bpow(1,824633729024) will take an amount of gas near the block limit.

Exploit Scenario

Bob creates a new pool. Eve performs certain operation to force users to indirectly call bpow with larger and larger gas amounts to finish. Eventually, the pool is so expensive that the users cannot longer use it.

Recommendation

Short term, limit the amount of iterations uses during the bpow computation.

Long term, consider to use Echidna and Manticore to ensure that there are no corner cases requiring large amounts of gas to compute.

FernandoMartinelli commented 4 years ago

Since this is an internal function we are sure that it will be used with exponents limited by the ratio limitations. Exponents are always either:

Since we limit weights to be between BONE and 50BONE and the max sum to be 50BONE we make sure that the exponents are always between 1/50 and 50.

We could add an extra require to check these boundaries to make sure this function is not exploited, but I don't think it is necessary since the result of such an exploit would be using up all the gas available and reverting, not really a problem for us.

ggrieco-tob commented 4 years ago

I manually verified if it possible to force the exponent to very large values and I agree with your analysis: this looks like a false positive. The only warning is to be very carefully when using the bpow function in your code, since any future use of it in this or other contracts can introduce potential issues.