Skip to content
Smart contracts Audit finding Intermediate

positionMapping for last element in heap is not updated when extracting max element

The MaxHeap contract fails to update the positionMapping for the last element when it is moved to the root during extractMax and has the same value as its parent, leaving its index stale. This can cause incorrect indexing, wrong value updates, broken heap property, and extraction of the wrong element.

MrPotatoMagic Follow with cccz

Originally disclosed on Code4rena

Submitted by MrPotatoMagic, also found by cccz

https://github.com/code-423n4/2023-12-revolutionprotocol/blob/d42cc62b873a1b2b44f57310f9d4bbfdd875e8d6/packages/revolution/src/MaxHeap.sol#L156 https://github.com/code-423n4/2023-12-revolutionprotocol/blob/d42cc62b873a1b2b44f57310f9d4bbfdd875e8d6/packages/revolution/src/MaxHeap.sol#L94

During the extraction of the max element through the function extractMax(), the positionMapping for the last element in the heap tree is not updated when the last element is equal to its parent.

These are the following impacts:

  1. MaxHeap does not function as intended and breaks its expected functionality due to element being incorrectly indexed in the heap.
  2. When a new element is inserted to that index, the incorrectly indexed element accesses the new element’s itemId during value updates
  3. Downward heapifying will work incorrectly leading to the parent having a value smaller than its child. Thus, further breaking not only the maxHeap tree but also the binary tree spec.
  4. Error in this heapifying will lead to the incorrectly indexed element being extracted.

Note: Point 3 in the impacts above breaks an invariant of the MaxHeap tree mentioned in the README.

The MaxHeap should always maintain the property of being a binary tree in which the value in each internal node is greater than or equal to the values in the children of that node.

Proof of Concept

Here is the whole process:

  1. Let’s assume this is the current state of the maxHeap tree.
  2. The values have been made small for ease of demonstration of the issue
  3. The itemIds being used are 1,2,3,4,5 with values being 50,20,15,10,20 respectively.
  4. The current indexes of the items are 0,1,2,3,4 (since size starts from 0)
  5. The current size of the tree is 5.
  6. Over here, note that itemId 2 is the parent of itemId 5 and both have the same values 20.

Note: to view the provided image, please see the original submission here.

  1. Now let’s say the top element with itemId = 1 and value = 50 is extracted using the extractMax() function. The following occurs:
  2. On Line 174, we store the itemId at the root into the variable popped
  3. On Line 175, we replace the itemId at the root (effectively erasing it) with the last element in the heap tree i.e. itemId 5.
  4. On Line 175, size is decremented from 5 to 4 as expected.
  5. Following this on Line 178, we maxHeapify the current element at the root i.e. itemId 5 which was just set on Line 174.
File: MaxHeap.sol
171:     function extractMax() external onlyAdmin returns (uint256, uint256) {
172:         require(size > 0, "Heap is empty");
173:
174:         uint256 popped = heap[0];
175:         heap[0] = heap[--size];
176:
177:
178:         maxHeapify(0);
179:
180:         return (popped, valueMapping[popped]);
181:     }
  1. During the maxHeapify() internal function call, the following occurs:
  2. On Lines 100-101, left and right are the indexes 1 and 2 (since pos = 0)
  3. On Lines 103-105, the values of the respective itemIds 5,2,3 are extracted as 20,20,15 respectively.
  4. On Line 107, we pass the check since 0 is not >= 2 (since size/2 = 4/2 = 2)
  5. On Line 109, we do not enter the if block since in the tree now, itemId 5 at the root has value 20 which is neither less than itemId 2 with value 20 nor itemId 3 with value 15. Thus, the function returns back to extractMax() and the call ends.
File: MaxHeap.sol
099:     function maxHeapify(uint256 pos) internal {
100:         uint256 left = 2 * pos + 1;
101:         uint256 right = 2 * pos + 2;
102:
103:         uint256 posValue = valueMapping[heap[pos]];
104:         uint256 leftValue = valueMapping[heap[left]];
105:         uint256 rightValue = valueMapping[heap[right]];
106:
107:         if (pos >= (size / 2) && pos <= size) return;
108:
109:         if (posValue < leftValue || posValue < rightValue) {
110:
111:             if (leftValue > rightValue) {
112:                 swap(pos, left);
113:                 maxHeapify(left);
114:             } else {
115:                 swap(pos, right);
116:                 maxHeapify(right);
117:             }
118:         }
119:     }
  1. On observing the new state of the tree, we can see the following:
  2. ItemId 5 with value 20 has been temporarily removed from index 4 in the tree until a new item is inserted.
  3. ItemId 5 with value 20 is now the root of the tree.
  4. If we look at the details of the root node, we can see that although the heap and valueMapping mappings have been updated correctly, the positionMapping still points to index 4 for itemId 5.
  5. This issue originates because during the maxHeapify() call, the itemId 5 is not less than either of it’s child nodes as the condition in maxHeapify() demands on Line 109 above.
  6. This is the first impact on the maxHeap data structure since it does not index as expected.

Note: to view the provided image, please see the original submission here.

  1. Now let’s say an itemId 6 with a value of 3 is created using the insert() function. The following occurs:
  2. On Lines 131-133, heap[4] is updated to itemId 6, valueMapping[itemId] to 3 and positionMapping[itemId] to 4.
File: MaxHeap.sol
130:     function insert(uint256 itemId, uint256 value) public onlyAdmin {
131:         heap[size] = itemId;
132:         valueMapping[itemId] = value; // Update the value mapping
133:         positionMapping[itemId] = size; // Update the position mapping
134:
135:         uint256 current = size;
136:         while (current != 0 && valueMapping[heap[current]] > valueMapping[heap[parent(current)]]) {
137:             swap(current, parent(current));
138:             current = parent(current);
139:         }
140:         size++;
141:     }
  1. If we look at the new state of the tree now, we can observe that both the itemId 5 at the root node and the latest itemId 6 share the same indexes in the tree i.e. positionMapping for both being 4.

Note: to view the provided image, please see the original submission here.

  1. Now if we call the updateValue() function to update value for itemId 5 i.e. the root node, the following occurs:
  2. On Line 151, positionMapping[5] returns 4 as the position of the root itemId 5, which is clearly incorrect as demonstrated in point 6 above.
  3. On Line 152, oldValue stores the value of itemId 5 which is 20.
  4. Line 155 updates the valueMapping with the newValue.
  5. On Line 158, the check determines if the newValue is greater than the oldValue. Let’s divide this into two cases, one for upward heapify and one for downward heapify.
File: MaxHeap.sol
150:     function updateValue(uint256 itemId, uint256 newValue) public onlyAdmin {
151:         uint256 position = positionMapping[itemId];
152:         uint256 oldValue = valueMapping[itemId];
153:
154:         // Update the value in the valueMapping
155:         valueMapping[itemId] = newValue;
156:
157:         // Decide whether to perform upwards or downwards heapify
158:         if (newValue > oldValue) {
159:             // Upwards heapify
160:             while (position != 0 && valueMapping[heap[position]] > valueMapping[heap[parent(position)]]) {
161:                 swap(position, parent(position));
162:                 position = parent(position);
163:             }
164:         } else if (newValue < oldValue) maxHeapify(position); // Downwards heapify
165:     }
  1. If we upward heapify by setting the newValue to be greater than the oldValue 20, the following occurs:
  2. On Line 160, the condition evaluates to false. Although expected since the root node is updated, the evaluation occurs incorrectly.
  3. The first condition checks if 4 != 0, which is true. This condition should actually have evaluated to false since the root node should have position/index = 0
  4. The second condition evaluates to false. This is because the valueMapping is accessing the value for itemId 6 and comparing it to its parent itemId 2.
  5. Due to this, although we do not enter the if block, the evaluation occurs incorrectly.
File: MaxHeap.sol
159:             // Upwards heapify
160:             while (position != 0 && valueMapping[heap[position]] > valueMapping[heap[parent(position)]]) {
161:                 swap(position, parent(position));
162:                 position = parent(position);
163:             }
  1. If we downward heapify by setting the newValue (let’s say 13) to be lesser than the oldValue 20, the following occurs:
  2. On Line 164, we enter the else if block and make an internal call to maxHeapify() with position = 4 as argument instead of 0, which is incorrect.
  3. On Lines 101-102, left and right are set to indexes 9 and 10. This is incorrect and should have been 1 and 2 (children of the root node we are updating) instead of itemId 6’s children.
  4. On Lines 103-105, itemId 6’s values are retrieved i.e. 3, 0, 0 respectively.
  5. on Line 107, the condition evaluates to true since 4 >= 2 (i.e. size/2 = 5/2) and 4 <= 5 evaluate to true. Due to this we return early and the downward heapify does not occur.
  6. The impact here is that itemId 5 in the root now has a value of 13, which is smaller than it’s child node’s values i.e. 20 and 15 respectively. This not only breaks the max heap tree but also the binary tree’s spec.
  7. Now if extractMax() is called, the root node itemId 5 with value 13 is popped instead of the expected itemId 2, which has a value of 20 and is the highest valued element.
File: MaxHeap.sol
164:         } else if (newValue < oldValue) maxHeapify(position); // Downwards heapify

maxHeapify() function:

File: MaxHeap.sol
099:     function maxHeapify(uint256 pos) internal {
100:         uint256 left = 2 * pos + 1;
101:         uint256 right = 2 * pos + 2;
102:
103:         uint256 posValue = valueMapping[heap[pos]];
104:         uint256 leftValue = valueMapping[heap[left]];
105:         uint256 rightValue = valueMapping[heap[right]];
106:
107:         if (pos >= (size / 2) && pos <= size) return;
108:
109:         if (posValue < leftValue || posValue < rightValue) {
110:
111:             if (leftValue > rightValue) {
112:                 swap(pos, left);
113:                 maxHeapify(left);
114:             } else {
115:                 swap(pos, right);
116:                 maxHeapify(right);
117:             }
118:         }
119:     }
  1. Here is how the max heap binary tree looks finally.

Note: to view the provided image, please see the original submission here.

Some points to note about this issue:

  1. The downward heapifying issue has been demonstrated to display an additional impact to the already existing impact of incorrect indexing and max heap tree spec violation.
  2. Although downward heapifying does not work in the codebase currently since downvoting does not exist, it can be introduced in the future based on sponsor’s comments (see below). This would break the protocol functionality as demonstrated in this issue. This is because the data structure can change its admin to a future CultureIndex contract that supports downvoting but the CultureIndex cannot start using a new data structure since the max heap has existing data stored in it.
  3. Even if there is no concept of downvoting, MaxHeap is expected to fully implement the maxHeap spec and functionality requirements (see below), which it does not implement correctly.

Note: to view the provided image, please see the original submission here.

Recommended Mitigation Steps

The most straightforward solution to this would be to consider this type of case in the extractMax() function itself.

The following check ensures that if the last element is equal to the parent and it is greater than equal to the right index of the root node (i.e. index 2), we update the positionMapping correctly to 0. This check needs to be placed after this statement.

if (heap[size] == parent(size) && heap[size] >= heap[2]) {
    positionMapping[heap[0]] = 0;
}

rocketman-21 (Revolution) commented:

Not updating the positionMapping after extract max was an oversight on my end, I think this is legit.

New extract max:

    /// @notice Extract the maximum element from the heap
    /// @dev The function will revert if the heap is empty
    /// The values for the popped node are removed from the items mapping
    /// @return The maximum element from the heap
    function extractMax() external onlyAdmin returns (uint256, uint256) {
        if (size == 0) revert EMPTY_HEAP();

        // itemId of the node with the max value at the root of the heap
        uint256 popped = heap[0];

        // get priority value of the popped node
        uint256 returnValue = items[popped].value;

        // remove popped node values from the items mapping for the popped node
        delete items[popped];

        // set the root node to the farthest leaf node and decrement the size
        heap[0] = heap[--size];

        // update the heap index for the previously farthest leaf node
        items[heap[0]].heapIndex = 0;

        //delete the farthest leaf node
        delete heap[size];

        //maintain heap property
        maxHeapify(0);

        return (popped, returnValue);
    }

https://github.com/collectivexyz/revolution-protocol/blob/941719c8f3c168d6d53e38528336ec6cf5df17c5/packages/revolution/src/culture-index/MaxHeap.sol#L187

0xTheC0der (Judge) commented: Although I acknowledge that this is a good and severe find, any PoC so far was only focused on MaxHeap itself and not its current usage through the main entry points of the protocol. Therefore, Medium severity seems appropriate since further impacts on the main functionality of the protocol need to be proven.

Note: See full discussion here.


The original report as published on Code4rena, by MrPotatoMagic. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

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 extractMax function does not update the positionMapping for the element moved to the root when that element's value equals its parent's value, because the subsequent maxHeapify call returns early without swapping.

Impact

The heap no longer maintains the max-heap property, so the wrong element can be extracted and value updates may affect the wrong item; the report notes that downward heapify is not currently used but could be in the future.

What the attacker needed

Admin privileges to call extractMax and insert; heap contains elements with equal values

The fix

The extractMax function should update the positionMapping for the element moved to the root, for example by setting it to 0 after the move, as shown in the sponsor's revised code.

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 heap is a tree-like data structure where the largest value is always at the top. The contract keeps a map that records where each item sits in the tree. When the top item is removed, the last item is moved to the top, but if it has the same value as its parent, the map is not updated, so later operations use the wrong position.

What is Smart contracts?

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.

More by MrPotatoMagic

View all

17 more disclosed reports, best first.

More from Revolution Protocol

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.