Ineffective TWAV Implementation
The time-weighted average valuation (TWAV) implementation only averages over four observations, which can be updated every block, making it effectively an observation-weighted average over a very short window. An attacker could manipulate the valuation to reject a buyout and then dump tokens within about one minute.
Originally disclosed on Code4rena
Submitted by xiaoming90, also found by hyh
The current TWAV implementation consists of an array of 4 observations/valuations called twavObservations. Whenever, the new valuation is updated, the new cumulative valuation will be appended to the twavObservations array and the oldest observation/valuation will be removed from the twavObservations array.
Description of current TWAV implementation can be found at https://github.com/NibblNFT/nibbl-smartcontracts#twavsol
- Time-weighted average valuation
- Uses an array of length 4 which stores cumulative valuation and timestamp.
- TWAV is calculated between the most and least recent observations recorded in the array.
- TWAV array is updated only when the system is in buyout state. In case of buyout rejection, the array is reset.
/// @notice current index of twavObservations index
uint8 public twavObservationsIndex;
uint8 private constant TWAV_BLOCK_NUMBERS = 4; //TWAV of last 4 Blocks
uint32 public lastBlockTimeStamp;
/// @notice record of TWAV
TwavObservation[TWAV_BLOCK_NUMBERS] public twavObservations;
/// @notice updates twavObservations array
/// @param _blockTimestamp timestamp of the block
/// @param _valuation current valuation
function _updateTWAV(uint256 _valuation, uint32 _blockTimestamp) internal {
uint32 _timeElapsed;
unchecked {
_timeElapsed = _blockTimestamp - lastBlockTimeStamp;
}
uint256 _prevCumulativeValuation = twavObservations[((twavObservationsIndex + TWAV_BLOCK_NUMBERS) - 1) % TWAV_BLOCK_NUMBERS].cumulativeValuation;
twavObservations[twavObservationsIndex] = TwavObservation(_blockTimestamp, _prevCumulativeValuation + (_valuation * _timeElapsed)); //add the previous observation to make it cumulative
twavObservationsIndex = (twavObservationsIndex + 1) % TWAV_BLOCK_NUMBERS;
lastBlockTimeStamp = _blockTimestamp;
}
Within the NibblVault contract, the _updateTWAV function will be called whenever the following events happen during the buyout period:
NibbleVault.buy()andNibbleVault.Sell()functions are calledNibbleVault.initiateBuyoutfunction is calledNibbleVault.updateTWAVfunction is called
Per the code and comment of _getTwav() function, the function will return the TWAV of the last four (4) blocks. This function can be called by anyone.
/// @notice returns the TWAV of the last 4 blocks
/// @return _twav TWAV of the last 4 blocks
function _getTwav() internal view returns(uint256 _twav){
if (twavObservations[TWAV_BLOCK_NUMBERS - 1].timestamp != 0) {
uint8 _index = ((twavObservationsIndex + TWAV_BLOCK_NUMBERS) - 1) % TWAV_BLOCK_NUMBERS;
TwavObservation memory _twavObservationCurrent = twavObservations[(_index)];
TwavObservation memory _twavObservationPrev = twavObservations[(_index + 1) % TWAV_BLOCK_NUMBERS];
_twav = (_twavObservationCurrent.cumulativeValuation - _twavObservationPrev.cumulativeValuation) / (_twavObservationCurrent.timestamp - _twavObservationPrev.timestamp);
}
}
Time weighted average valuation (TWAV) is supposed to be the average value of a security over a specified time (e.g. 15 minutes, 1 hour, 24 hours). However, based on the above implementation of the _getTwav function, it is not the average value of a security over a specific time.
A user could call the updateTWAV function to add the new valuation/observation to the twavObservations array each time a new Ethereum block is mined. As such, the current implementation becomes the average value of a security over a specific number of observations (in this case 4 observations), thus it can be considered as Observation weighted average valuation (OWAV).
There is a fundamental difference between TWAV and OWAV.
Proof of Concept
In Ethereum, the average block time is around 15 seconds, so the time to take to mine 4 blocks will be 1 minute. As such, in term of TWAV, the current implementation only have a period of 1 minute, which is too short to prevent price manipulation.
The following shows an example where it is possible to buy tokens→ increase the valuation above the rejection valuation→ reject the buyout→ dump the tokens within 1 minute:
Assume that a buyer has triggered a buyout on the vault/NFT, and the buyout rejection price is 120 ETH and the current valuation is 100 ETH. Further assume that all elements in the twavObservations array have already been populated.
Note: Fees are ignored to illustrate the issue.
- Block 100 at Time 0 - Attacker called
buyfunction to increase the current valuation to 120 ETH attempting to reject the buyout. - Block 101 at Time 15 - Attacker called
updateTWAVfunction. The current valuation (120 ETH) will be replaced the first element intwavObservationsarray. - Block 102 at Time 30 - Attacker called
updateTWAVfunction. The current valuation (120 ETH) will be replaced the second element intwavObservationsarray. - Block 103 at Time 45 - Attacker called
updateTWAVfunction. The current valuation (120 ETH) will be replaced the third element intwavObservationsarray. - Block 104 at Time 60 - Attacker called
sellfunction to sell/dump all his shares. Within thesellfunction,_updateTWAVwill be first called, thus the current valuation (120 ETH) will be replaced the fourth element intwavObservationsarray. Then, the_rejectBuyout()will be called, and the_getTwavfunction will be triggered. At this point, the TWAV valuation is finally 120 ETH, thus the buyout is rejected. Subseqently, attacker’s shares are burned, and attacker get back his funds.
Since attacker could perform the above attack within 1 minute, it is very unlikely that the attackers will lose money to arbitrageurs as it takes some time for the arbitrageurs to notice such an opportunity.
Attacker could also front-run or set a higher gas fee to ensure that their transaction get mined in the next block to minimize the attack window period.
Impact
Buyout can be easily rejected by attackers
Recommended Mitigation Steps
Implement a proper TWAV that provides the average value of a security over a specified time. The time period/windows of the TWAV must be explicitly defined (e.g. 15 minutes, 1 hour, 24 hours) in the contract.
There are trade offs when choosing the length of the period of time to calculate a TWAP. Longer periods are better to protect against price manipulation, but come at the expense of a slower, and potentially less accurate, price. Thus, the team should determine the optimal period.
Consider referencing the popular Uniswap V2 TWAP design (https://docs.uniswap.org/protocol/V2/concepts/core-concepts/oracles)
mundhrakeshav (Nibbl) disagreed with severity
I had a Low Risk (#142) associated with
_getTWAVtoo. I’m not sure it even averages over 4 observations.
Some comments, as I personally don’t think it’s an high security issue:
- the primary goal of the TWAV here is to avoid manipulations within the same block. As long as it’s over multiple blocks, the attackers takes a risk as there could be arbitrages, so the attack risk is mitigated.
- the main assumption of the issue is: “it takes some time for the arbitrageurs to notice such an opportunity, and the 4 block window is too short.” which seems false when you check on chain data: arbitrageurs are frequently super quick to react as it’s their primary job: the first to check an opportunity takes it.
HardlyDifficult (judge) decreased severity to Medium and commented:
Great summary @Picodes , I agree with both points.
Lowering this to a Medium risk. I may be incorrect, but it seems a secondary goal of Twap is price smoothing to avoid scenarios like what was outlined here. If that’s correct then this impacts the function of the protocol and the recommendation is a good consideration.
Same here, TWAP is essential to the protocol, while the ability to manipulate the price during last minute breaks the core logic of price discovery by greatly reducing the number of participants. The rationale that 4 blocks are enough and arbitrage is generally quick is sufficient for mainstream cases only, all other trading is at risk of direct manipulation, which is existential risk for the protocol. Can’t see why the team pressing for medium here.
HardlyDifficult (judge) commented:
Same here, TWAP is essential to the protocol, while the ability to manipulate the price during last minute breaks the core logic of price discovery by greatly reducing the number of participants. The rationale that 4 blocks are enough and arbitrage is generally quick is sufficient for mainstream cases only, all other trading is at risk of direct manipulation, which is existential risk for the protocol. Can’t see why the team pressing for medium here.
The stated goal of using Twap in their documentation is the same as above, to prevent same-block attacks. It seems the concern is the implicit behavior expected from using a “time weighted” variable. Personally I agree this seems like an area they may want to revisit. However the system behaves correctly and there is a tiny window for bots to respond.
@mundhrakeshav @Picodes would you mind elaborating here as well?
mundhrakeshav (Nibbl) commented:
Yeah, makes sense. We do plan to increase the array length.
I fully agree with both of you: it’d be indeed better to increase the array length to increase the robustness, but I still feel this is a medium issue as the system works as intended
The system formally/technically works as intended, but being a price discovery engine, where participants having incentives to try to determine the NFT price, it will not be used if the window for such a discovery is mere 4 blocks. Formally the bots will have space to react. Realistically it will happen in the most mainstream cases only, when price discovery isn’t much needed. I.e. exactly when the system can bring in something new, adding a mechanics for ‘slow’ usual users to add price information, it will not work as the set of participants who can add the information to the metric (react to move the price) is shrunk by a tiny reaction window. Who will take part in a price discovery game knowing that last minute bots are always can surface? Quite not everyone. This reduces the traction, and so the amount of information brought in by the system, as this is the users who bring in the additional signal, and ultimately it will be a piece of well known NFTs synched with main market with bots, adding no value to it. I.e. the system will work technically, but economically it will not make much sense, so will not be widely used by market actors and can end up provide little value to broad market. This is what I mean by existential risk, which is, of course high.
I just feel that here and in general in C4 economic issues are tend to be underestimated, while having one usually tend to be a game changing aspect for a project.
IllIllI000 (warden) commented:
@HardlyDifficult If the sponsor had used the term OWAV rather than TWAV, would this still be a medium-severity issue? It seems as though they knew the behavior they wanted (at least four user interactions where the average price is above the threshold) and just used the wrong term to describe it. I didn’t file this issue because it seemed that way. The screenshot in this issue shows that they’re interested in interactions, not duration of time https://github.com/code-423n4/2022-06-nibbl-findings/issues/144. It’s possible they confirmed the issue because they weren’t aware that comment vs code consistency issues are usually categorized as low risk
HardlyDifficult (judge) commented:
Great points @dmitriia and @IllIllI000 ! Both are compelling. This is certainly a grey area.
Given how significantly this impacts how users would potentially view and interact with the system, I’m inclined to leave this a Medium risk instead of downgrading to Low, falling under “the function of the protocol or its availability could be impacted”.
And since this was intentional design and there is a window for bots to respond, I don’t feel that High risk is justified.
I’m happy to continue here or on Discord, and would love more input if others want to chime in on the severity here. I don’t feel strongly but do think that Medium is the best fit here.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
Likely the TWAV implementation uses a fixed-size array of four observations and updates it on every block, so the average is over a very short time window rather than a specified duration.
Impact
Buyout can be easily rejected by attackers, though the judge noted there is a tiny window for bots to respond and the system behaves as intended.
What the attacker needed
Buyout in progress; attacker has funds to buy tokens; attacker can send transactions each block
The fix
Implement a proper TWAV that averages over a specified time period (e.g., 15 minutes, 1 hour, 24 hours) and explicitly define that window in the contract.
How it was found
- Attacker calls buy to increase valuation above rejection price.
- Attacker calls updateTWAV in the next block.
- Attacker calls updateTWAV again in the following block.
- Attacker calls updateTWAV again in the next block.
- Attacker calls sell, which updates TWAV and triggers buyout rejection, then gets funds back.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
A smart contract uses a price average to decide if a buyout offer should be rejected. The average is supposed to be over time, but it actually only looks at the last four updates, which can happen in four blocks (about one minute). An attacker can quickly push the price up, trigger the rejection, and then sell before the price falls back.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.