code-423n4 / 2023-05-ajna-findings

2 stars 0 forks source link

Risk of Gas Limit Exceedance During Proposal Sorting #431

Closed code423n4 closed 1 year ago

code423n4 commented 1 year ago

Lines of code

https://github.com/code-423n4/2023-05-ajna/blob/276942bc2f97488d07b887c8edceaaab7a5c3964/ajna-grants/src/grants/base/StandardFunding.sol#L816-L833

Vulnerability details

Impact

The array of up to 10 proposals using the insertion sort algorithm in _insertionSortProposalsByVotes function in the StandardFunding.sol contract but, if the number of proposals exceeds 10, the sorting process may cause the function to exceed the block gas limit, resulting in the transaction failure. As a result, the screeningVote function may not be executed, leading to incorrect sorting of proposals, potential loss of funds, or incorrect allocation of resources. This vulnerability can severely impact the functionality of the smart contract.

Proof of Concept

    function _insertionSortProposalsByVotes(
        uint256[] storage proposals_,
        uint256 targetProposalId_
    ) internal {
        while (
            targetProposalId_ != 0
            &&
            _standardFundingProposals[proposals_[targetProposalId_]].votesReceived > _standardFundingProposals[proposals_[targetProposalId_ - 1]].votesReceived
        ) {
            // swap values if left item < right item
            uint256 temp = proposals_[targetProposalId_ - 1];

            proposals_[targetProposalId_ - 1] = proposals_[targetProposalId_];
            proposals_[targetProposalId_] = temp;

            unchecked { --targetProposalId_; }
        }
    }

The while loop iterates over the proposals and sorts them based on the number of votes received. However, the insertion sort algorithm used in this code block is inefficient for large numbers of proposals, as it has a time complexity of O(n^2). As a result, when the number of proposals exceeds 10, the sorting process may exceed the block gas limit, causing the transaction to fail.

Tools Used

vscode

Recommended Mitigation Steps

I suggest using a more efficient sorting algorithm that can handle a larger number of proposals without exceeding the block gas limit. For example, the contract could use the QuickSort algorithm, which has a time complexity of O(n log n) and is more suitable for sorting larger arrays.

Assessed type

Other

c4-judge commented 1 year ago

Picodes marked the issue as unsatisfactory: Invalid