-
Notifications
You must be signed in to change notification settings - Fork 43
CERT 8687 Realistic example #167
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nivcertora
wants to merge
5
commits into
cli-beta
Choose a base branch
from
niv/CERT-8687-RequireInv
base: cli-beta
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
# Sorted Array Invariant Example | ||
|
||
This folder illustrates how the **new** `requireInvariant` semantics handle a **sorted array** property more accurately than the old semantics. We have: | ||
|
||
## Key Points | ||
|
||
- **Old semantics**: Using `requireInvariant` in non-boundary contexts (e.g., hooks, summaries) could lead to false verification results. The invariant might be incorrectly considered satisfied inline, missing real violations. | ||
- **New semantics**: `requireInvariant` is enforced only at valid rule boundaries (e.g., after function calls, subcalls, or havocs if `strong`). This ensures that violations are properly detected. | ||
|
||
--- | ||
|
||
## Example Overview | ||
|
||
### Solidity Contract: `SortedArray.sol` | ||
- **`arr`**: Public array, intended to remain sorted. | ||
- **`insert(uint256 val)`**: Inserts `val` into the correct position in ascending order. | ||
- **`remove(uint256 index)`**: Removes the element at `index`, shifting subsequent elements. | ||
- **`readAt(uint256 index)`**: Returns `arr[index]`, used to trigger CVL read hooks. | ||
|
||
### CVL Specification | ||
- **Invariant**: | ||
`isSorted(uint256 i)` requires that for each valid `i`, `arr[i] <= arr[i+1]`. | ||
- **Hooks**: | ||
On every read or write to `arr[index]`, `requireInvariant isSorted(index)` is invoked. | ||
|
||
--- | ||
|
||
## Demonstration: Correctness and Bug Detection | ||
|
||
### Correct Implementation | ||
|
||
- **Old semantics**: | ||
[View Output](https://prover.certora.com/output/40726/1636fb234bc74a1bba7f7ee9678b9c4f/?anonymousKey=ff15dfcf8a4da66107d4d7c7f04a49416e992b4d) | ||
*May incorrectly verify even if the array is temporarily unsorted.* | ||
|
||
- **New semantics**: | ||
[View Output](https://prover.certora.com/output/40726/5811d2a30ded4dcea82460a2d1d080ac/?anonymousKey=f296e69f8f0ea379cfba6801f1e4fee8f4d39c91) | ||
*Correctly enforces the invariant at rule boundaries.* | ||
|
||
### Buggy Implementation | ||
|
||
- **Old semantics**: | ||
[View Output](https://prover.certora.com/output/40726/ca7307d763104f8abdc1dc900d1c4e5e/?anonymousKey=2b6d5374b36f9e4990c7d825e6c9bb8a292db9d8) | ||
*Fails to catch the violation.* | ||
|
||
- **New semantics**: | ||
[View Output](https://prover.certora.com/output/40726/006db65557f94285af8bdbe0b8d1408f/?anonymousKey=abefdb1b51401cc4ed93ef57e70f4ed5b43bf579) | ||
*Correctly detects the violation.* | ||
|
||
--- | ||
|
||
## How to Run | ||
|
||
1. Make sure you have the Certora CLI installed. | ||
2. Run the specification: | ||
```bash | ||
certoraRun SortedArray.conf | ||
``` | ||
|
||
--- |
9 changes: 9 additions & 0 deletions
9
CVLByExample/Invariant/RequireInvariantArray/SortedArray.conf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
{ | ||
"files": ["SortedArray.sol"], | ||
"verify": "SortedArray:SortedArray.spec", | ||
"solc": "solc8.25", | ||
"msg": "Verifying sorted array invariant", | ||
"loop_iter": "5", | ||
"optimistic_loop": true, | ||
"rule_sanity" : "basic" | ||
} |
51 changes: 51 additions & 0 deletions
51
CVLByExample/Invariant/RequireInvariantArray/SortedArray.sol
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
// SPDX-License-Identifier: MIT | ||
pragma solidity ^0.8.0; | ||
|
||
/** | ||
* @title SortedArray | ||
* @notice A simple contract maintaining a sorted array of uint256 | ||
*/ | ||
contract SortedArray { | ||
uint256[] public arr; | ||
|
||
/** | ||
* @notice Inserts a new value into the array, keeping it sorted in ascending order. | ||
* @param val The value to insert | ||
*/ | ||
function insert(uint256 val) external { | ||
// Simple linear approach: | ||
// 1. Find the position where 'val' should go. | ||
// 2. Insert it there, shifting subsequent elements. | ||
uint256 pos = 0; | ||
while (pos < arr.length && arr[pos] <= val) { | ||
pos++; | ||
} | ||
|
||
// Insert by pushing a dummy at the end, then shifting | ||
arr.push(val); // extends array by 1 | ||
for (uint256 i = arr.length - 1; i > pos; i--) { | ||
arr[i] = arr[i - 1]; | ||
} | ||
arr[pos] = val; | ||
} | ||
|
||
/** | ||
* @notice Removes the element at index `index`. | ||
* @dev For simplicity, just shift down from 'index' onward; last element is pop'd. | ||
*/ | ||
function remove(uint256 index) external { | ||
require(index < arr.length, "Index out of range"); | ||
for (uint256 i = index; i < arr.length - 1; i++) { | ||
arr[i] = arr[i + 1]; | ||
} | ||
arr.pop(); // remove the last element | ||
} | ||
|
||
/** | ||
* @notice Returns the element at index `index`. | ||
* @dev Exposes array reads to demonstrate the read hook in CVL. | ||
*/ | ||
function readAt(uint256 index) external view returns (uint256) { | ||
return arr[index]; | ||
} | ||
} |
29 changes: 29 additions & 0 deletions
29
CVLByExample/Invariant/RequireInvariantArray/SortedArray.spec
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
|
||
|
||
// --------------------------------------------------------------- | ||
// Define the sorted invariant: arr[i] <= arr[i+1] for all valid i | ||
// --------------------------------------------------------------- | ||
// Check array bounds carefully to avoid out-of-range checks | ||
invariant isSorted(uint256 i) | ||
i < currentContract.arr.length - 1 => currentContract.arr[i] <= currentContract.arr[require_uint256(i + 1)] ; | ||
|
||
|
||
// ---------------------------------------------------------------- | ||
// An incorrect invariant that is not violated in the old semantics | ||
// ---------------------------------------------------------------- | ||
invariant incorrect(uint256 i) | ||
i < currentContract.arr.length => currentContract.arr[i] == 71; | ||
|
||
|
||
// ---------------------------------------------------------------------------- | ||
// Load and Store Hooks: whenever 'arr[i]' is accessed assume the invariants | ||
// ---------------------------------------------------------------------------- | ||
hook Sload uint256 ret currentContract.arr[INDEX uint256 index] { | ||
requireInvariant isSorted(index); | ||
requireInvariant incorrect(index); | ||
} | ||
|
||
hook Sstore currentContract.arr[INDEX uint256 index] uint256 val { | ||
requireInvariant isSorted(index); | ||
requireInvariant incorrect(index); | ||
} |
52 changes: 52 additions & 0 deletions
52
CVLByExample/Invariant/RequireInvariantArray/SortedArrayBug.sol
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
// SPDX-License-Identifier: MIT | ||
pragma solidity ^0.8.0; | ||
|
||
/** | ||
* @title SortedArray | ||
* @notice A simple contract maintaining a sorted array of uint256 | ||
*/ | ||
contract SortedArray { | ||
uint256[] public arr; | ||
|
||
/** | ||
* @notice Inserts a new value into the array, keeping it sorted in ascending order. | ||
* @param val The value to insert | ||
*/ | ||
function insert(uint256 val) external { | ||
// Simple linear approach: | ||
// 1. Find the position where 'val' should go. | ||
// 2. Insert it there, shifting subsequent elements. | ||
uint256 pos = 0; | ||
while (pos < arr.length && arr[pos] <= val) { | ||
pos++; | ||
} | ||
|
||
// Insert by pushing a dummy at the end, then shifting | ||
arr.push(val); // extends array by 1 | ||
for (uint256 i = arr.length - 1; i > pos; i--) { | ||
arr[i] = arr[i - 1]; | ||
} | ||
// push to the wrongs place | ||
arr[pos++] = val; | ||
} | ||
|
||
/** | ||
* @notice Removes the element at index `index`. | ||
* @dev For simplicity, just shift down from 'index' onward; last element is pop'd. | ||
*/ | ||
function remove(uint256 index) external { | ||
require(index < arr.length, "Index out of range"); | ||
for (uint256 i = index; i < arr.length - 1; i++) { | ||
arr[i] = arr[i + 1]; | ||
} | ||
arr.pop(); // remove the last element | ||
} | ||
|
||
/** | ||
* @notice Returns the element at index `index`. | ||
* @dev Exposes array reads to demonstrate the read hook in CVL. | ||
*/ | ||
function readAt(uint256 index) external view returns (uint256) { | ||
return arr[index]; | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.