Skip to content

Commit

Permalink
fix(invariant): call override strategy panic (#7469)
Browse files Browse the repository at this point in the history
* fix(invariant): override call strat panic

* Add test
  • Loading branch information
grandizzy authored Mar 22, 2024
1 parent 5ecc1bf commit 9d2125b
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
12 changes: 11 additions & 1 deletion crates/evm/fuzz/src/strategies/invariants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,17 @@ pub fn override_call_strat(
.prop_flat_map(move |target_address| {
let fuzz_state = fuzz_state.clone();
let calldata_fuzz_config = calldata_fuzz_config.clone();
let (_, abi, functions) = &contracts.lock()[&target_address];

let contracts = &contracts.lock();
let (_, abi, functions) = contracts.get(&target_address).unwrap_or({
// Choose a random contract if target selected by lazy strategy is not in fuzz run
// identified contracts. This can happen when contract is created in `setUp` call
// but is not included in targetContracts.
let rand_index = rand::thread_rng().gen_range(0..contracts.iter().len());
let (_, contract_specs) = contracts.iter().nth(rand_index).unwrap();
contract_specs
});

let func = select_random_function(abi, functions);
func.prop_flat_map(move |func| {
fuzz_contract_with_calldata(&fuzz_state, &calldata_fuzz_config, target_address, func)
Expand Down
1 change: 1 addition & 0 deletions crates/forge/tests/it/invariant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ async fn test_invariant() {
async fn test_invariant_override() {
let filter = Filter::new(".*", ".*", ".*fuzz/invariant/common/InvariantReentrancy.t.sol");
let mut runner = TEST_DATA_DEFAULT.runner();
runner.test_options.invariant.fail_on_revert = false;
runner.test_options.invariant.call_override = true;
let results = runner.test_collect(&filter);

Expand Down
12 changes: 11 additions & 1 deletion testdata/default/fuzz/invariant/common/InvariantReentrancy.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import "ds-test/test.sol";

contract Malicious {
function world() public {
// Does not matter, since it will get overridden.
// add code so contract is accounted as valid sender
// see https://github.com/foundry-rs/foundry/issues/4245
payable(msg.sender).transfer(1);
}
}

Expand Down Expand Up @@ -39,6 +41,14 @@ contract InvariantReentrancy is DSTest {
vuln = new Vulnerable(address(mal));
}

// do not include `mal` in identified contracts
// see https://github.com/foundry-rs/foundry/issues/4245
function targetContracts() public view returns (address[] memory) {
address[] memory targets = new address[](1);
targets[0] = address(vuln);
return targets;
}

function invariantNotStolen() public {
require(vuln.stolen() == false, "stolen");
}
Expand Down

0 comments on commit 9d2125b

Please sign in to comment.