Skip to content

Commit

Permalink
Add check for range in blockHash op
Browse files Browse the repository at this point in the history
  • Loading branch information
Facundo MH committed May 14, 2024
1 parent 4ad0e2b commit b2f4b5e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
14 changes: 12 additions & 2 deletions cpp/vm/evmzero/interpreter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -865,7 +865,18 @@ struct Impl<OpCode::BLOCKHASH> {

static OpResult Run(uint256_t* top, Context& ctx) noexcept {
int64_t number = static_cast<int64_t>(top[0]);
top[0] = ToUint256(ctx.host->get_block_hash(number));
int64_t upper, lower;
upper = int64_t(ctx.host->get_tx_context().block_number);
if (upper < 257) {
lower = 0;
} else {
lower = upper - 256;
}
if (number >= lower && number < upper) {
top[0] = ToUint256(ctx.host->get_block_hash(number));
} else {
top[0] = 0;
}
return {};
}
};
Expand Down Expand Up @@ -1701,7 +1712,6 @@ inline OpResult Invoke(uint256_t* top, const uint8_t*, int64_t gas, Context& ctx
///////////////////////////////////////////////////////////

namespace internal {

inline bool Context::CheckJumpDest(uint256_t index_u256) noexcept {
if (index_u256[1] != 0 || index_u256[2] != 0 || index_u256[3] != 0) [[unlikely]] {
state = RunState::kErrorJump;
Expand Down
26 changes: 23 additions & 3 deletions cpp/vm/evmzero/interpreter_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2834,9 +2834,12 @@ TEST(InterpreterTest, EXTCODEHASH_StackError) {

///////////////////////////////////////////////////////////
// BLOCKHASH
TEST(InterpreterTest, BLOCKHASH) {
TEST(InterpreterTest, BLOCKHASH_inRange) {
MockHost host;
EXPECT_CALL(host, get_block_hash(21)) //
EXPECT_CALL(host, get_tx_context()) //
.Times(1)
.WillOnce(Return(evmc_tx_context{.block_number = 1000}));
EXPECT_CALL(host, get_block_hash(900)) //
.Times(1)
.WillOnce(Return(evmc::bytes32(0x0a0b0c0d)));

Expand All @@ -2845,12 +2848,29 @@ TEST(InterpreterTest, BLOCKHASH) {
.state_after = RunState::kDone,
.gas_before = 40,
.gas_after = 20,
.stack_before = {21},
.stack_before = {900},
.stack_after = {0x0a0b0c0d},
.host = &host,
});
}

TEST(InterpreterTest, BLOCKHASH_outOfRange) {
MockHost host;
EXPECT_CALL(host, get_tx_context()) //
.Times(1)
.WillOnce(Return(evmc_tx_context{.block_number = 1000}));

RunInterpreterTest({
.code = {op::BLOCKHASH},
.state_after = RunState::kDone,
.gas_before = 40,
.gas_after = 20,
.stack_before = {500},
.stack_after = {0},
.host = &host,
});
}

TEST(InterpreterTest, BLOCKHASH_OutOfGas) {
RunInterpreterTest({
.code = {op::BLOCKHASH},
Expand Down

0 comments on commit b2f4b5e

Please sign in to comment.