Skip to content

feat: PrecompileEnvironment.ReentrancyGuard() #212

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

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions core/vm/contracts.libevm.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,9 +190,22 @@ type PrecompileEnvironment interface {
// Invalidate invalidates the transaction calling this precompile.
InvalidateExecution(error)

// ReentrancyGuard returns [ErrExecutionReverted] i.f.f. it has already been
// called with the same `key` by the same contract, in the same transaction.
// It otherwise returns nil. The `key` MAY be nil.
//
// Contract equality is defined as the [libevm.AddressContext] "self"
// address being the same under EVM semantics.
ReentrancyGuard(key []byte) error

// Call is equivalent to [EVM.Call] except that the `caller` argument is
// removed and automatically determined according to the type of call that
// invoked the precompile.
//
// WARNING: using this method makes the precompile susceptible to reentrancy
// attacks as with a regular contract. The `ReentrancyGuard()` method, the
// Checks-Effects-Interactions pattern, or some other protection MUST be
// used in conjunction with `Call()`.
Call(addr common.Address, input []byte, gas uint64, value *uint256.Int, _ ...CallOption) (ret []byte, _ error)
}

Expand Down
42 changes: 42 additions & 0 deletions core/vm/contracts.libevm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -877,3 +877,45 @@ func TestPrecompileCallWithTracer(t *testing.T) {
require.NoErrorf(t, json.Unmarshal(gotJSON, &got), "json.Unmarshal(%T.GetResult(), %T)", tracer, &got)
require.Equal(t, value, got[contract].Storage[zeroHash], "value loaded with SLOAD")
}

func TestReentrancyGuard(t *testing.T) {
sut := common.HexToAddress("7E57ED")
eve := common.HexToAddress("BAD")
eveCalled := false

zero := func() *uint256.Int {
return uint256.NewInt(0)
}

returnIfGuarded := []byte("guarded")

hooks := &hookstest.Stub{
PrecompileOverrides: map[common.Address]libevm.PrecompiledContract{
eve: vm.NewStatefulPrecompile(func(env vm.PrecompileEnvironment, input []byte) (ret []byte, err error) {
eveCalled = true
return env.Call(sut, []byte{}, env.Gas(), zero()) // i.e. reenter
}),
sut: vm.NewStatefulPrecompile(func(env vm.PrecompileEnvironment, input []byte) (ret []byte, err error) {
// The argument is optional and used only to allow more than one
// guard in a contract.
if err := env.ReentrancyGuard(nil); err != nil {
return returnIfGuarded, err
}
if env.Addresses().EVMSemantic.Caller == eve {
// A real precompile MUST NOT panic under any circumstances.
// It is done here to avoid a loop should the guard not
// work.
panic("reentrancy")
}
return env.Call(eve, []byte{}, env.Gas(), zero())
}),
},
}
hooks.Register(t)

_, evm := ethtest.NewZeroEVM(t)
got, _, err := evm.Call(vm.AccountRef{}, sut, []byte{}, 1e6, zero())
require.True(t, eveCalled, "Malicious contract called")
assert.Equal(t, err, vm.ErrExecutionReverted, "Precompile reverted")
assert.Equal(t, returnIfGuarded, got, "Precompile reverted with expected data")
}
16 changes: 16 additions & 0 deletions core/vm/environment.libevm.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"github.com/ava-labs/libevm/common"
"github.com/ava-labs/libevm/common/math"
"github.com/ava-labs/libevm/core/types"
"github.com/ava-labs/libevm/crypto"
"github.com/ava-labs/libevm/libevm"
"github.com/ava-labs/libevm/libevm/options"
"github.com/ava-labs/libevm/params"
Expand Down Expand Up @@ -111,6 +112,21 @@ func (e *environment) BlockHeader() (types.Header, error) {
return *hdr, nil
}

func reentrancyGuardSlot(key []byte) common.Hash {
return crypto.Keccak256Hash([]byte("libevm-reentrancy-guard"), key)
}

func (e *environment) ReentrancyGuard(key []byte) error {
self := e.Addresses().EVMSemantic.Self
slot := reentrancyGuardSlot(key)

if e.evm.StateDB.GetTransientState(self, slot) != (common.Hash{}) {
return ErrExecutionReverted
}
e.evm.StateDB.SetTransientState(self, slot, common.Hash{1})
return nil
}

func (e *environment) Call(addr common.Address, input []byte, gas uint64, value *uint256.Int, opts ...CallOption) ([]byte, error) {
return e.callContract(Call, addr, input, gas, value, opts...)
}
Expand Down