Skip to content

Commit 53cac74

Browse files
authored
perf(evm): key transientAccounts by address (#4723)
## Summary `TemporaryState.transientAccounts` was keyed by `acc.Hex()`, so every `MarkAccount` and `HasSelfDestructed` call computed an EIP-55 checksum (a Keccak-256 hash) and allocated a string, and the self-destruct sweeps in `Finalize` parsed the keys back with `HexToAddress`. This keys the map by `common.Address` in both `x/evm/state` and `giga/deps/xevm/state`. - Share the destructed-account scan between the two `Finalize` sweeps - Use `uint256.IsZero` for the residual balance check - Drop a redundant nil assignment in `MarkAccount` - Add `MarkAccount`/`HasSelfDestructed` benchmarks and a self-destruct sweep test ## Benchmarks Apple M5, 8 runs × 500k iterations, benchstat (p=0.000): | Benchmark | Before | After | |---------------------|------------------|------------------| | `MarkAccount` | 645 ns, 6 allocs | 35 ns, 1 alloc | | `HasSelfDestructed` | 302 ns, 2 allocs | 7 ns, 0 allocs |
1 parent c7e2f9c commit 53cac74

11 files changed

Lines changed: 228 additions & 54 deletions

File tree

‎giga/deps/xevm/state/journal.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,8 @@ func (e *codeCacheChange) revert(s *DBImpl) {
182182
func (e *accountStatusChange) revert(s *DBImpl) {
183183
accts := s.tempState.transientAccounts
184184
if e.prev == nil {
185-
delete(accts, e.account.Hex())
185+
delete(accts, e.account)
186186
} else {
187-
accts[e.account.Hex()] = e.prev
187+
accts[e.account] = e.prev
188188
}
189189
}

‎giga/deps/xevm/state/journal_test.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,10 @@ func TestWatermarkRevert(t *testing.T) {
9292
func TestAccountStatusChangeRevert_Delete(t *testing.T) {
9393
db := &DBImpl{tempState: NewTemporaryState()}
9494
addr := common.Address{10}
95-
db.tempState.transientAccounts[addr.Hex()] = []byte{1, 2, 3}
95+
db.tempState.transientAccounts[addr] = []byte{1, 2, 3}
9696
change := &accountStatusChange{account: addr, prev: nil}
9797
change.revert(db)
98-
_, ok := db.tempState.transientAccounts[addr.Hex()]
98+
_, ok := db.tempState.transientAccounts[addr]
9999
require.False(t, ok)
100100
}
101101

@@ -105,7 +105,7 @@ func TestAccountStatusChangeRevert_Update(t *testing.T) {
105105
prev := []byte{4, 5, 6}
106106
change := &accountStatusChange{account: addr, prev: prev}
107107
change.revert(db)
108-
require.Equal(t, prev, db.tempState.transientAccounts[addr.Hex()])
108+
require.Equal(t, prev, db.tempState.transientAccounts[addr])
109109
}
110110

111111
func TestStorageOverrideInstallRevert_Delete(t *testing.T) {
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package state_test
2+
3+
import (
4+
"testing"
5+
"time"
6+
7+
"github.com/ethereum/go-ethereum/common"
8+
"github.com/ethereum/go-ethereum/core/tracing"
9+
"github.com/holiman/uint256"
10+
testkeeper "github.com/sei-protocol/sei-chain/giga/deps/testutil/keeper"
11+
"github.com/sei-protocol/sei-chain/giga/deps/xevm/state"
12+
sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types"
13+
banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types"
14+
"github.com/stretchr/testify/require"
15+
)
16+
17+
func TestFinalizeSweepsDestructedAccounts(t *testing.T) {
18+
k, baseCtx := testkeeper.MockEVMKeeper(t)
19+
baseCtx = baseCtx.WithBlockTime(time.Now())
20+
21+
accts := make([]common.Address, 16)
22+
wantSpenders := make([]string, len(accts))
23+
for i := range accts {
24+
_, accts[i] = testkeeper.MockAddressPair()
25+
wantSpenders[i] = k.GetSeiAddressOrDefault(baseCtx, accts[i]).String()
26+
}
27+
28+
ctx := baseCtx.WithMultiStore(baseCtx.MultiStore().CacheMultiStore()).WithEventManager(sdk.NewEventManager())
29+
statedb := state.NewDBImpl(ctx, k, false)
30+
for i, acc := range accts {
31+
statedb.CreateAccount(acc)
32+
statedb.SetCode(acc, []byte("code"))
33+
_, destructed := statedb.SelfDestruct6780(acc)
34+
require.True(t, destructed)
35+
residual := uint256.NewInt(1)
36+
if i%2 == 1 {
37+
residual = uint256.NewInt(999_999_999_999)
38+
}
39+
statedb.AddBalance(acc, residual, tracing.BalanceChangeTransfer)
40+
}
41+
_, err := statedb.Finalize()
42+
require.NoError(t, err)
43+
44+
require.ElementsMatch(t, wantSpenders, weiSpenders(ctx.EventManager().Events()))
45+
for _, acc := range accts {
46+
require.Empty(t, k.GetCode(ctx, acc))
47+
require.Zero(t, k.GetBalance(ctx, k.GetSeiAddressOrDefault(ctx, acc)).Sign())
48+
}
49+
}
50+
51+
func weiSpenders(events sdk.Events) []string {
52+
var spenders []string
53+
for _, e := range events {
54+
if e.Type != banktypes.EventTypeWeiSpent {
55+
continue
56+
}
57+
for _, attr := range e.Attributes {
58+
if string(attr.Key) == banktypes.AttributeKeySpender {
59+
spenders = append(spenders, string(attr.Value))
60+
}
61+
}
62+
}
63+
return spenders
64+
}

‎giga/deps/xevm/state/state.go‎

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@ package state
22

33
import (
44
"bytes"
5+
"slices"
56

67
"github.com/ethereum/go-ethereum/common"
78
"github.com/ethereum/go-ethereum/core/tracing"
89
"github.com/holiman/uint256"
910
"github.com/sei-protocol/sei-chain/giga/deps/xevm/types"
1011
storetypes "github.com/sei-protocol/sei-chain/sei-cosmos/store/types"
1112
sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types"
12-
"github.com/sei-protocol/sei-chain/utils"
1313
)
1414

1515
func (s *DBImpl) CreateAccount(acc common.Address) {
@@ -101,8 +101,7 @@ func (s *DBImpl) SelfDestruct6780(acc common.Address) (uint256.Int, bool) {
101101
return *uint256.NewInt(0), false
102102
}
103103

104-
// the Ethereum semantics of HasSelfDestructed checks if the account is self destructed in the
105-
// **CURRENT** block
104+
// HasSelfDestructed reports whether acc was self-destructed in the current transaction.
106105
func (s *DBImpl) HasSelfDestructed(acc common.Address) bool {
107106
val, found := s.getTransientAccount(acc)
108107
if !found || val == nil {
@@ -177,13 +176,9 @@ func (s *DBImpl) RevertToSnapshot(rev int) {
177176
}
178177

179178
func (s *DBImpl) handleResidualFundsInDestructedAccounts(st *TemporaryState) {
180-
for a, status := range st.transientAccounts {
181-
if !bytes.Equal(status, AccountDeleted) {
182-
continue
183-
}
184-
acc := common.HexToAddress(a)
179+
for _, acc := range st.destructedAccounts() {
185180
residual := s.GetBalance(acc)
186-
if residual.ToBig().Cmp(utils.Big0) == 0 {
181+
if residual.IsZero() {
187182
continue
188183
}
189184
s.SubBalance(acc, residual, tracing.BalanceDecreaseSelfdestructBurn)
@@ -194,12 +189,20 @@ func (s *DBImpl) handleResidualFundsInDestructedAccounts(st *TemporaryState) {
194189
}
195190

196191
func (s *DBImpl) clearAccountStateIfDestructed(st *TemporaryState) {
197-
for acc, status := range st.transientAccounts {
198-
if !bytes.Equal(status, AccountDeleted) {
199-
continue
192+
for _, acc := range st.destructedAccounts() {
193+
s.clearAccountState(acc)
194+
}
195+
}
196+
197+
func (st *TemporaryState) destructedAccounts() []common.Address {
198+
accts := make([]common.Address, 0, len(st.transientAccounts))
199+
for a, status := range st.transientAccounts {
200+
if bytes.Equal(status, AccountDeleted) {
201+
accts = append(accts, a)
200202
}
201-
s.clearAccountState(common.HexToAddress(acc))
202203
}
204+
slices.SortFunc(accts, common.Address.Cmp)
205+
return accts
203206
}
204207

205208
func (s *DBImpl) clearAccountState(acc common.Address) {
@@ -226,11 +229,8 @@ func (s *DBImpl) clearAccountCodeAndNonce(acc common.Address) {
226229
}
227230

228231
func (s *DBImpl) MarkAccount(acc common.Address, status []byte) {
229-
prev, ok := s.tempState.transientAccounts[acc.Hex()]
230-
if !ok {
231-
prev = nil
232-
}
233-
s.tempState.transientAccounts[acc.Hex()] = status
232+
prev := s.tempState.transientAccounts[acc]
233+
s.tempState.transientAccounts[acc] = status
234234
s.journal = append(s.journal, &accountStatusChange{account: acc, prev: prev})
235235
}
236236

@@ -275,7 +275,7 @@ func (s *DBImpl) setOverrideState(ov *storageOverride, addr common.Address, key,
275275
}
276276

277277
func (s *DBImpl) getTransientAccount(acc common.Address) ([]byte, bool) {
278-
val, found := s.tempState.transientAccounts[acc.Hex()]
278+
val, found := s.tempState.transientAccounts[acc]
279279
return val, found
280280
}
281281

‎giga/deps/xevm/state/statedb.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ func (o *storageOverride) deepCopy() *storageOverride {
305305
type TemporaryState struct {
306306
logs []*ethtypes.Log
307307
transientStates map[string]map[string]common.Hash
308-
transientAccounts map[string][]byte
308+
transientAccounts map[common.Address][]byte
309309
transientModuleStates map[string][]byte
310310
transientAccessLists *accessList
311311
storageOverrides map[common.Address]*storageOverride
@@ -316,7 +316,7 @@ func NewTemporaryState() *TemporaryState {
316316
return &TemporaryState{
317317
logs: []*ethtypes.Log{},
318318
transientStates: make(map[string]map[string]common.Hash),
319-
transientAccounts: make(map[string][]byte),
319+
transientAccounts: make(map[common.Address][]byte),
320320
transientModuleStates: make(map[string][]byte),
321321
transientAccessLists: &accessList{Addresses: make(map[common.Address]int), Slots: []map[common.Hash]struct{}{}},
322322
storageOverrides: make(map[common.Address]*storageOverride),
@@ -335,7 +335,7 @@ func (ts *TemporaryState) DeepCopy() *TemporaryState {
335335
res.transientStates[k][k2] = v2
336336
}
337337
}
338-
res.transientAccounts = make(map[string][]byte, len(ts.transientAccounts))
338+
res.transientAccounts = make(map[common.Address][]byte, len(ts.transientAccounts))
339339
for k, v := range ts.transientAccounts {
340340
res.transientAccounts[k] = v
341341
}

‎x/evm/state/journal.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,8 @@ func (e *codeCacheChange) revert(s *DBImpl) {
182182
func (e *accountStatusChange) revert(s *DBImpl) {
183183
accts := s.tempState.transientAccounts
184184
if e.prev == nil {
185-
delete(accts, e.account.Hex())
185+
delete(accts, e.account)
186186
} else {
187-
accts[e.account.Hex()] = e.prev
187+
accts[e.account] = e.prev
188188
}
189189
}

‎x/evm/state/journal_test.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,10 @@ func TestWatermarkRevert(t *testing.T) {
9292
func TestAccountStatusChangeRevert_Delete(t *testing.T) {
9393
db := &DBImpl{tempState: NewTemporaryState()}
9494
addr := common.Address{10}
95-
db.tempState.transientAccounts[addr.Hex()] = []byte{1, 2, 3}
95+
db.tempState.transientAccounts[addr] = []byte{1, 2, 3}
9696
change := &accountStatusChange{account: addr, prev: nil}
9797
change.revert(db)
98-
_, ok := db.tempState.transientAccounts[addr.Hex()]
98+
_, ok := db.tempState.transientAccounts[addr]
9999
require.False(t, ok)
100100
}
101101

@@ -105,7 +105,7 @@ func TestAccountStatusChangeRevert_Update(t *testing.T) {
105105
prev := []byte{4, 5, 6}
106106
change := &accountStatusChange{account: addr, prev: prev}
107107
change.revert(db)
108-
require.Equal(t, prev, db.tempState.transientAccounts[addr.Hex()])
108+
require.Equal(t, prev, db.tempState.transientAccounts[addr])
109109
}
110110

111111
func TestStorageOverrideInstallRevert_Delete(t *testing.T) {

‎x/evm/state/selfdestruct_test.go‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package state_test
2+
3+
import (
4+
"testing"
5+
"time"
6+
7+
"github.com/ethereum/go-ethereum/common"
8+
"github.com/ethereum/go-ethereum/core/tracing"
9+
"github.com/holiman/uint256"
10+
sdk "github.com/sei-protocol/sei-chain/sei-cosmos/types"
11+
banktypes "github.com/sei-protocol/sei-chain/sei-cosmos/x/bank/types"
12+
testkeeper "github.com/sei-protocol/sei-chain/testutil/keeper"
13+
"github.com/sei-protocol/sei-chain/x/evm/state"
14+
"github.com/stretchr/testify/require"
15+
)
16+
17+
func TestFinalizeSweepsDestructedAccounts(t *testing.T) {
18+
k := &testkeeper.EVMTestApp.EvmKeeper
19+
baseCtx := testkeeper.EVMTestApp.GetContextForDeliverTx([]byte{}).WithBlockTime(time.Now())
20+
21+
accts := make([]common.Address, 16)
22+
wantSpenders := make([]string, len(accts))
23+
for i := range accts {
24+
_, accts[i] = testkeeper.MockAddressPair()
25+
wantSpenders[i] = k.GetSeiAddressOrDefault(baseCtx, accts[i]).String()
26+
}
27+
28+
ctx := baseCtx.WithMultiStore(baseCtx.MultiStore().CacheMultiStore()).WithEventManager(sdk.NewEventManager())
29+
statedb := state.NewDBImpl(ctx, k, false)
30+
for i, acc := range accts {
31+
statedb.CreateAccount(acc)
32+
statedb.SetCode(acc, []byte("code"))
33+
_, destructed := statedb.SelfDestruct6780(acc)
34+
require.True(t, destructed)
35+
residual := uint256.NewInt(1)
36+
if i%2 == 1 {
37+
residual = uint256.NewInt(999_999_999_999)
38+
}
39+
statedb.AddBalance(acc, residual, tracing.BalanceChangeTransfer)
40+
}
41+
_, err := statedb.Finalize()
42+
require.NoError(t, err)
43+
44+
require.ElementsMatch(t, wantSpenders, weiSpenders(ctx.EventManager().Events()))
45+
for _, acc := range accts {
46+
require.Empty(t, k.GetCode(ctx, acc))
47+
require.Zero(t, k.GetBalance(ctx, k.GetSeiAddressOrDefault(ctx, acc)).Sign())
48+
}
49+
}
50+
51+
func weiSpenders(events sdk.Events) []string {
52+
var spenders []string
53+
for _, e := range events {
54+
if e.Type != banktypes.EventTypeWeiSpent {
55+
continue
56+
}
57+
for _, attr := range e.Attributes {
58+
if string(attr.Key) == banktypes.AttributeKeySpender {
59+
spenders = append(spenders, string(attr.Value))
60+
}
61+
}
62+
}
63+
return spenders
64+
}

0 commit comments

Comments
 (0)