Skip to content

Commit 910e897

Browse files
authored
feat: reentrancy.Guard for stateful precompiles (#212)
## Why this should be merged The `vm.PrecompileEnvironment.Call()` method requires careful usage because of reentrancy vulnerabilities (this is common to all outgoing `CALL`s in the EVM, not just stateful precompiles). This package provides a common method of protection, a reentrancy guard. ## How this works Provides a function that returns `vm.ErrExecutionReverted` if called twice, by the same contract, in the same transaction, with the same identifier. ## How this was tested Unit and integration tests.
1 parent 35926db commit 910e897

File tree

3 files changed

+195
-0
lines changed

3 files changed

+195
-0
lines changed

core/vm/contracts.libevm.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,11 @@ type PrecompileEnvironment interface {
220220
// Call is equivalent to [EVM.Call] except that the `caller` argument is
221221
// removed and automatically determined according to the type of call that
222222
// invoked the precompile.
223+
//
224+
// WARNING: using this method makes the precompile susceptible to reentrancy
225+
// attacks as with a regular contract. The Checks-Effects-Interactions
226+
// pattern, libevm's `reentrancy` package, or some other protection MUST be
227+
// used in conjunction with `Call()`.
223228
Call(addr common.Address, input []byte, gas uint64, value *uint256.Int, _ ...CallOption) (ret []byte, _ error)
224229
}
225230

libevm/reentrancy/guard.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Copyright 2025 the libevm authors.
2+
//
3+
// The libevm additions to go-ethereum are free software: you can redistribute
4+
// them and/or modify them under the terms of the GNU Lesser General Public License
5+
// as published by the Free Software Foundation, either version 3 of the License,
6+
// or (at your option) any later version.
7+
//
8+
// The libevm additions are distributed in the hope that they will be useful,
9+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
11+
// General Public License for more details.
12+
//
13+
// You should have received a copy of the GNU Lesser General Public License
14+
// along with the go-ethereum library. If not, see
15+
// <http://www.gnu.org/licenses/>.
16+
17+
// Package reentrancy provides a reentrancy guard for stateful precompiles that
18+
// make outgoing calls to other contracts.
19+
//
20+
// Reentrancy occurs when the contract (C) called by a precompile (P) makes a
21+
// further call back into P, which may result in theft of funds (see DAO hack).
22+
// A reentrancy guard detects these recursive calls and reverts.
23+
package reentrancy
24+
25+
import (
26+
"github.com/ava-labs/libevm/common"
27+
"github.com/ava-labs/libevm/core/vm"
28+
"github.com/ava-labs/libevm/crypto"
29+
"github.com/ava-labs/libevm/libevm"
30+
)
31+
32+
var slotPreimagePrefix = []byte("libevm-reentrancy-guard-")
33+
34+
// Guard returns [vm.ErrExecutionReverted] i.f.f. it has already been called
35+
// with the same `key`, by the same contract, in the same transaction. It
36+
// otherwise returns nil. The `key` MAY be nil.
37+
//
38+
// Contract equality is defined as the [libevm.AddressContext] "self" address
39+
// being the same under EVM semantics.
40+
func Guard(env vm.PrecompileEnvironment, key []byte) error {
41+
self := env.Addresses().EVMSemantic.Self
42+
slot := crypto.Keccak256Hash(slotPreimagePrefix, key)
43+
44+
sdb := env.StateDB()
45+
if sdb.GetTransientState(self, slot) != (common.Hash{}) {
46+
return vm.ErrExecutionReverted
47+
}
48+
sdb.SetTransientState(self, slot, common.Hash{1})
49+
return nil
50+
}
51+
52+
// Keep the `libevm` import to allow the linked comment on [Guard]. The package
53+
// is imported by `vm` anyway so this is a noop but it improves developer
54+
// experience.
55+
var _ = (*libevm.AddressContext)(nil)

libevm/reentrancy/guard_test.go

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
// Copyright 2025 the libevm authors.
2+
//
3+
// The libevm additions to go-ethereum are free software: you can redistribute
4+
// them and/or modify them under the terms of the GNU Lesser General Public License
5+
// as published by the Free Software Foundation, either version 3 of the License,
6+
// or (at your option) any later version.
7+
//
8+
// The libevm additions are distributed in the hope that they will be useful,
9+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
11+
// General Public License for more details.
12+
//
13+
// You should have received a copy of the GNU Lesser General Public License
14+
// along with the go-ethereum library. If not, see
15+
// <http://www.gnu.org/licenses/>.
16+
17+
package reentrancy
18+
19+
import (
20+
"testing"
21+
22+
"github.com/holiman/uint256"
23+
"github.com/stretchr/testify/assert"
24+
"github.com/stretchr/testify/require"
25+
26+
"github.com/ava-labs/libevm/common"
27+
"github.com/ava-labs/libevm/core/rawdb"
28+
"github.com/ava-labs/libevm/core/state"
29+
"github.com/ava-labs/libevm/core/types"
30+
"github.com/ava-labs/libevm/core/vm"
31+
"github.com/ava-labs/libevm/crypto"
32+
"github.com/ava-labs/libevm/libevm"
33+
"github.com/ava-labs/libevm/libevm/ethtest"
34+
"github.com/ava-labs/libevm/libevm/hookstest"
35+
)
36+
37+
func TestGuardIntegration(t *testing.T) {
38+
sut := common.HexToAddress("7E57ED")
39+
eve := common.HexToAddress("BAD")
40+
eveCalled := false
41+
42+
zero := func() *uint256.Int {
43+
return uint256.NewInt(0)
44+
}
45+
46+
returnIfGuarded := []byte("guarded")
47+
48+
hooks := &hookstest.Stub{
49+
PrecompileOverrides: map[common.Address]libevm.PrecompiledContract{
50+
eve: vm.NewStatefulPrecompile(func(env vm.PrecompileEnvironment, input []byte) (ret []byte, err error) {
51+
eveCalled = true
52+
return env.Call(sut, []byte{}, env.Gas(), zero()) // i.e. reenter
53+
}),
54+
sut: vm.NewStatefulPrecompile(func(env vm.PrecompileEnvironment, input []byte) (ret []byte, err error) {
55+
// The argument is optional and used only to allow more than one
56+
// guard in a contract, tested in a separate unit test.
57+
if err := Guard(env, nil); err != nil {
58+
return returnIfGuarded, err
59+
}
60+
if env.Addresses().EVMSemantic.Caller == eve {
61+
// A real precompile MUST NOT panic under any circumstances.
62+
// It is done here to avoid a loop should the guard not
63+
// work.
64+
panic("reentrancy")
65+
}
66+
return env.Call(eve, []byte{}, env.Gas(), zero())
67+
}),
68+
},
69+
}
70+
hooks.Register(t)
71+
72+
_, evm := ethtest.NewZeroEVM(t)
73+
got, _, err := evm.Call(vm.AccountRef{}, sut, []byte{}, 1e6, zero())
74+
require.True(t, eveCalled, "Malicious contract called")
75+
// The error is propagated Guard() -> reentered SUT -> Eve -> top-level SUT -> evm.Call()
76+
// This MUST NOT be [assert.ErrorIs] as such errors are never wrapped in geth.
77+
assert.Equal(t, err, vm.ErrExecutionReverted, "Precompile reverted")
78+
assert.Equal(t, returnIfGuarded, got, "Precompile reverted with expected data")
79+
}
80+
81+
type envStub struct {
82+
self common.Address
83+
db *state.StateDB
84+
vm.PrecompileEnvironment
85+
}
86+
87+
func (s *envStub) Addresses() *libevm.AddressContext {
88+
return &libevm.AddressContext{
89+
EVMSemantic: libevm.CallerAndSelf{
90+
Self: s.self,
91+
},
92+
}
93+
}
94+
95+
func (s *envStub) StateDB() vm.StateDB {
96+
return s.db
97+
}
98+
99+
func TestGuard(t *testing.T) {
100+
db, err := state.New(types.EmptyRootHash, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
101+
require.NoError(t, err, "state.New()")
102+
env := &envStub{db: db}
103+
104+
addr0 := common.Address{}
105+
addr1 := common.Address{1}
106+
key0 := []byte{0}
107+
key1 := []byte{1}
108+
109+
// All tests run on the same [envStub] so are dependent on the effects of
110+
// the one(s) before.
111+
tests := []struct {
112+
self common.Address
113+
key []byte
114+
want error
115+
}{
116+
{addr0, key0, nil},
117+
{addr0, key0, vm.ErrExecutionReverted},
118+
{addr0, key1, nil},
119+
{addr1, key0, nil},
120+
{addr1, key1, nil},
121+
{addr1, key1, vm.ErrExecutionReverted},
122+
{addr0, key1, vm.ErrExecutionReverted},
123+
}
124+
125+
history := make(map[common.Hash]bool) // for better error reporting
126+
for _, tt := range tests {
127+
h := crypto.Keccak256Hash(tt.self[:], tt.key)
128+
already := history[h]
129+
history[h] = true
130+
131+
env.self = tt.self
132+
// Tests are dependent so we don't use assert.Equalf.
133+
require.Equalf(t, tt.want, Guard(env, tt.key), "Guard([self=%v], %#x) when already called = %t", tt.self, tt.key, already)
134+
}
135+
}

0 commit comments

Comments
 (0)