Skip to content
5 changes: 3 additions & 2 deletions execution/state/intra_block_state.go
Original file line number Diff line number Diff line change
Expand Up @@ -1072,8 +1072,9 @@ func (ibs *IntraBlockState) GetCommittedState(addr accounts.Address, key account
}

func (ibs *IntraBlockState) HasSelfdestructed(addr accounts.Address) (bool, error) {
destructed, _, _, err := readSelfDestruct(ibs, addr)
return destructed, err
destructed, source, _, err := readSelfDestruct(ibs, addr)
// A destruct read from the version map is an earlier transaction's, not this one's.
return destructed && source != MapRead, err
}

func (ibs *IntraBlockState) ReadVersion(addr accounts.Address, path AccountPath, key accounts.StorageKey, txIdx int) ReadResult {
Expand Down
7 changes: 6 additions & 1 deletion execution/state/revival_reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,7 @@ func TestApplySubFieldWrites_BlockBeginCodeHashKeepsOwnIndex(t *testing.T) {
}

// A wiped read after a destruct and a revival records the SelfDestruct memo it
// reads through, so HasSelfdestructed in the same tx must see the revival.
// reads through, which must hold the revival's false, not the destruct's true.
func TestWipedReadAfterRevivalKeepsSelfDestructFalse(t *testing.T) {
t.Parallel()
addr := getAddress(120)
Expand Down Expand Up @@ -587,6 +587,11 @@ func TestWipedReadAfterRevivalKeepsSelfDestructFalse(t *testing.T) {
ibs.SetTxContext(1, 3)
ibs.SetVersion(0)
require.NoError(t, tc.read(ibs))
// Before HasSelfdestructed, which records the cell itself and ignores a
// value read from the version map.
recorded, ok := ibs.versionedReads.GetSelfDestruct(addr)
require.True(t, ok)
require.False(t, recorded.Val, "the recorded read must hold the revival")
destructed, err := ibs.HasSelfdestructed(addr)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HasSelfdestructed now returns false for any MapRead, so the assertion below passes even with a stale destruct; the real guard is the recorded.Val check above.

require.NoError(t, err)
require.False(t, destructed, "the account was revived by tx 2, so it is not self-destructed")
Expand Down
105 changes: 105 additions & 0 deletions execution/state/selfdestruct_parallel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/erigontech/erigon/common"
"github.com/erigontech/erigon/common/dbg"
"github.com/erigontech/erigon/db/kv"
"github.com/erigontech/erigon/execution/chain"
"github.com/erigontech/erigon/execution/tracing"
"github.com/erigontech/erigon/execution/types/accounts"
)
Expand Down Expand Up @@ -130,6 +131,110 @@ func TestSelfdestructParallel_AbsentAccount(t *testing.T) {
assert.Empty(t, ibs.stateObjects, "absent-account Selfdestruct must not materialize a stateObject")
}

// An earlier transaction's SELFDESTRUCT leaves a deleted account, which a later
// transaction of the block has not self-destructed.
func TestHasSelfdestructed_EarlierTxDestruct(t *testing.T) {
t.Parallel()
addr := accounts.InternAddress([20]byte{0xDE, 0xAD})
acc := accounts.NewAccount()
acc.Balance = *uint256.NewInt(100)
acc.Nonce = 1
reader := &sdAccountReader{addr: addr, account: &acc}
rules := &chain.Rules{IsSpuriousDragon: true}
vm := NewVersionMap(nil)

destroyer := NewWithVersionMap(reader, vm)
destroyer.SetTxContext(1, 0)
destroyed, err := destroyer.Selfdestruct(addr, false)
require.NoError(t, err)
require.True(t, destroyed)
vm.FlushVersionedWrites(finalizedWrites(t, destroyer, rules), true)

ibs := NewWithVersionMap(reader, vm)
ibs.SetTxContext(1, 1)
// The first call records the destruct; the second is served from that record.
for range 2 {
destructed, err := ibs.HasSelfdestructed(addr)
require.NoError(t, err)
require.False(t, destructed)
}
}

// HasSelfdestructed reports the transaction's own SELFDESTRUCT whatever earlier
// transactions of the block left in the version map, so before London a second
// SELFDESTRUCT of the contract in that transaction earns no refund.
func TestHasSelfdestructed_OwnDestructAfterEarlierTx(t *testing.T) {
t.Parallel()
addr := accounts.InternAddress([20]byte{0xDE, 0xAD})
acc := accounts.NewAccount()
acc.Balance = *uint256.NewInt(100)
acc.Nonce = 1
reader := &sdAccountReader{addr: addr, account: &acc}
rules := &chain.Rules{IsSpuriousDragon: true}

type step func(t *testing.T, ibs *IntraBlockState)
destroy := func(t *testing.T, ibs *IntraBlockState) {
destroyed, err := ibs.Selfdestruct(addr, false)
require.NoError(t, err)
require.True(t, destroyed)
}
credit := func(t *testing.T, ibs *IntraBlockState) {
require.NoError(t, ibs.AddBalance(addr, *uint256.NewInt(3), tracing.BalanceChangeUnspecified))
}
// recreate follows the EVM's CREATE2: collision check, then the new contract.
recreate := func(t *testing.T, ibs *IntraBlockState) {
_, err := ibs.GetCodeHash(addr)
require.NoError(t, err)
_, err = ibs.GetNonce(addr)
require.NoError(t, err)
require.NoError(t, ibs.CreateAccount(addr, true))
require.NoError(t, ibs.SetNonce(addr, 1, tracing.NonceChangeNewContract))
require.NoError(t, ibs.SetCode(addr, []byte{0x33, 0xff}, tracing.CodeChangeContractCreation))
}
for _, tc := range []struct {
name string
earlier []step // one per earlier transaction
before step // this transaction, before its first SELFDESTRUCT
}{
{name: "no earlier write"},
{name: "destroyed earlier, re-created in this tx", earlier: []step{destroy}, before: recreate},
{name: "destroyed and re-created earlier", earlier: []step{destroy, recreate}},
{name: "destroyed, credited and re-created earlier", earlier: []step{destroy, credit, recreate}},
{name: "destroyed, credited and re-created in this tx", earlier: []step{destroy, credit}, before: recreate},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
vm := NewVersionMap(nil)
for i, run := range tc.earlier {
ibs := NewWithVersionMap(reader, vm)
ibs.SetTxContext(1, i)
run(t, ibs)
vm.FlushVersionedWrites(finalizedWrites(t, ibs, rules), true)
}

ibs := NewWithVersionMap(reader, vm)
ibs.SetTxContext(1, len(tc.earlier))
if tc.before != nil {
tc.before(t, ibs)
}
// The SELFDESTRUCT gas function asks before the opcode runs.
hasSelfdestructed := func() bool {
t.Helper()
destructed, err := ibs.HasSelfdestructed(addr)
require.NoError(t, err)
return destructed
}
require.False(t, hasSelfdestructed(), "the first SELFDESTRUCT earns the refund")
snapshot := ibs.PushSnapshot()
destroy(t, ibs)
ibs.RevertToSnapshot(snapshot, nil)
require.False(t, hasSelfdestructed(), "a reverted SELFDESTRUCT leaves the refund to the next")
destroy(t, ibs)
require.True(t, hasSelfdestructed(), "a second SELFDESTRUCT in the tx earns no refund")
})
}
}

// A self-destructed address whose write set also holds field, code and storage
// writes must be applied as a pure delete: no account record is left, and its
// code and its pre-block and same-tx storage are gone.
Expand Down
4 changes: 4 additions & 0 deletions execution/tests/recreate_after_revival_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ var generatedBlockWant = map[string]struct {
"TestRevertedSelfdestructKeepsCreateEndowment/amsterdam=true": {"0x266a5cde6739b5ccf4246279e28ac5fa0134471766ab2fd259c5b20da7524afb", 201960},
"TestSelfdestructRefundAfterRecreate/berlin": {"0x6c00adbbe82a30f808465bf07c80d70793ff29bededc4ab63aab3c50cfa6e5db", 246372},
"TestSelfdestructRefundAfterRecreate/petersburg": {"0x552c5fe09dfd21423cae06da59d18cb1c44c44e0cc13bc82381217ac952fc1d5", 233172},
"TestSelfdestructRefundInTxAfterRecreate/berlin": {"0xebd30387316ce450e736cdb8f8289a7995eb0f83f574ff9a4cf5775f547f025d", 166543},
"TestSelfdestructRefundInTxAfterRecreate/petersburg": {"0xdc15d9db6c68f2f33382ae21d7e77e53415c5b8c638ee32f9e08e37f33e8c1fe", 162043},
"TestSelfdestructRefundOncePerTx/berlin": {"0x691e15c187ee18959efdd606d269e277075d5759e5fc6442fd8c0aa5381a1512", 512707},
"TestSelfdestructRefundOncePerTx/petersburg": {"0x059ac83c33d636102399a612ace142a90bacf1cb51e6ec22026aee7a1bc8342b", 1437807},
"TestStorageReadAfterRecreate/osaka": {"0x4566ac309f9379db840cddaad60371b2631881026bee2b0e39410138373c373b", 981981},
"TestStorageReadAfterRecreate/shanghai": {"0x110266e0cc2a44f0dc18346331985645aa11e6d811b16108b3157fb53b9a7fec", 1027547},
"TestTouchedStorageOnlyAccountIsAbsentForLaterTx/amsterdam": {"0xac06f2a6d73d1dcecc65cefb9006695e47caee746664fe36c70a6b7be252f187", 183600},
Expand Down
95 changes: 95 additions & 0 deletions execution/tests/selfdestruct_refund_after_recreate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package executiontests

import (
"bytes"
"math/big"
"testing"

Expand Down Expand Up @@ -85,3 +86,97 @@ func TestSelfdestructRefundAfterRecreate(t *testing.T) {
})
}
}

// Before London, one block: X destroys itself, another contract's SELFDESTRUCT
// sends 3 wei to X, and the same CREATE2 deploys X again. In the next tx X reads
// slot 1 and destroys itself, which earns the SELFDESTRUCT refund as its first
// destruct did: X has not destroyed itself before in that tx.
func TestSelfdestructRefundInTxAfterRecreate(t *testing.T) {
runtime := program.New().Push(1).Op(vm.SLOAD, vm.POP, vm.CALLER, vm.SELFDESTRUCT).Bytes()
init := program.New().ReturnViaCodeCopy(runtime)
factory := common.HexToAddress("0xfac7")
x := types.CreateAddress2(factory, [32]byte{}, accounts.InternCodeHash(crypto.Keccak256Hash(init.Bytes())))
donor := common.HexToAddress("0xd040")

petersburg := chain.TestChainBerlinConfig.Copy()
petersburg.IstanbulBlock, petersburg.MuirGlacierBlock, petersburg.BerlinBlock = nil, nil, nil
for _, fork := range []struct {
name string
config *chain.Config
}{{"petersburg", petersburg}, {"berlin", chain.TestChainBerlinConfig}} {
t.Run(fork.name, func(t *testing.T) {
alloc := types.GenesisAlloc{
factory: {Code: program.New().Create2(init.Bytes(), 0).Op(vm.STOP).Bytes()},
donor: {Code: program.New().Selfdestruct(x).Bytes(), Balance: big.NewInt(3)},
}
keys := revivalKeys(t, alloc, 5)
gspec := &types.Genesis{Config: fork.config, GasLimit: 30_000_000, Alloc: alloc}
chainPack := buildBlockSerially(t, gspec, keys, common.Address{1}, 10_000_000_000, []revivalCall{
{to: factory},
{to: x},
{to: donor},
{to: factory},
{to: x},
})
receipts := chainPack.Receipts[0]
require.Equal(t, receipts[1].GasUsed, receipts[4].GasUsed, "the re-created X earns the SELFDESTRUCT refund")
importInParallel(t, gspec, keys[0], chainPack, func(t *testing.T, st *state.IntraBlockState) {
exists, err := st.Exist(accounts.InternAddress(x))
require.NoError(t, err)
require.False(t, exists)
})
})
}
}

// Before London, one block: X destroys itself twice in one tx, another
// contract's SELFDESTRUCT sends 3 wei to X, and the same CREATE2 deploys X
// again. In the next tx X's first SELFDESTRUCT runs in a reverted call, and X
// is then deployed again and destroys itself twice in one tx. Each tx earns
// one SELFDESTRUCT refund; its calldata lifts the refund cap above two.
func TestSelfdestructRefundOncePerTx(t *testing.T) {
runtime := program.New().Op(vm.CALLER, vm.SELFDESTRUCT).Bytes()
init := program.New().ReturnViaCodeCopy(runtime)
factory := common.HexToAddress("0xfac7")
x := types.CreateAddress2(factory, [32]byte{}, accounts.InternCodeHash(crypto.Keccak256Hash(init.Bytes())))
donor := common.HexToAddress("0xd040")
twice := common.HexToAddress("0x7e1ce")
reverter := common.HexToAddress("0x2e7e2")
afterRevert := common.HexToAddress("0xaf7e2")
burn := bytes.Repeat([]byte{0xff}, 6000)

petersburg := chain.TestChainBerlinConfig.Copy()
petersburg.IstanbulBlock, petersburg.MuirGlacierBlock, petersburg.BerlinBlock = nil, nil, nil
for _, fork := range []struct {
name string
config *chain.Config
}{{"petersburg", petersburg}, {"berlin", chain.TestChainBerlinConfig}} {
t.Run(fork.name, func(t *testing.T) {
alloc := types.GenesisAlloc{
factory: {Code: program.New().Create2(init.Bytes(), 0).Op(vm.STOP).Bytes()},
donor: {Code: program.New().Selfdestruct(x).Bytes(), Balance: big.NewInt(3)},
twice: {Code: program.New().Call(nil, x, 0, 0, 0, 0, 0).Op(vm.POP).Call(nil, x, 0, 0, 0, 0, 0).Op(vm.STOP).Bytes()},
reverter: {Code: program.New().Call(nil, x, 0, 0, 0, 0, 0).Push(0).Push(0).Op(vm.REVERT).Bytes()},
afterRevert: {Code: program.New().Call(nil, reverter, 0, 0, 0, 0, 0).Op(vm.POP).Call(nil, x, 0, 0, 0, 0, 0).Op(vm.STOP).Bytes()},
}
keys := revivalKeys(t, alloc, 7)
gspec := &types.Genesis{Config: fork.config, GasLimit: 30_000_000, Alloc: alloc}
chainPack := buildBlockSerially(t, gspec, keys, common.Address{1}, 10_000_000_000, []revivalCall{
{to: factory},
{to: twice, data: burn},
{to: donor},
{to: factory},
{to: afterRevert, data: burn},
{to: factory},
{to: twice, data: burn},
})
receipts := chainPack.Receipts[0]
require.Equal(t, receipts[1].GasUsed, receipts[6].GasUsed, "the re-created X earns one refund, as the first did")
importInParallel(t, gspec, keys[0], chainPack, func(t *testing.T, st *state.IntraBlockState) {
exists, err := st.Exist(accounts.InternAddress(x))
require.NoError(t, err)
require.False(t, exists)
})
})
}
}
66 changes: 66 additions & 0 deletions rpc/jsonrpc/debug_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,72 @@ func TestTraceBlockByHashPrestateTracerCreate2MemoryOverflow(t *testing.T) {
require.Zero(t, coinbasePrestate.Nonce)
}

// TestTraceBlockPrestateDiffAfterSelfdestruct: a transaction touching an account
// an earlier transaction of the block destroyed traces in the block as it does alone.
func TestTraceBlockPrestateDiffAfterSelfdestruct(t *testing.T) {
key, err := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
require.NoError(t, err)
sender := crypto.PubkeyToAddress(key.PublicKey)
m := execmoduletester.New(t, execmoduletester.WithKey(key), execmoduletester.WithGenesisSpec(&types.Genesis{
Config: chain.TestChainOsakaConfig.Copy(),
GasLimit: 60_000_000,
Alloc: types.GenesisAlloc{sender: {Balance: big.NewInt(1e18)}},
}))
// Transaction 0 creates and destroys the coinbase; transaction 1 pays it a tip.
coinbase := types.CreateAddress(sender, 0)
beneficiary := common.HexToAddress("0x3000")
selfdestruct := append(append([]byte{byte(vm.PUSH20)}, beneficiary[:]...), byte(vm.SELFDESTRUCT))
gasPrice := uint256.NewInt(1_000_000_000)
signer := types.LatestSignerForChainID(m.ChainConfig.ChainID)
generated, err := m.GenerateChain(1, func(_ int, gen *blockgen.BlockGen) {
gen.SetCoinbase(coinbase)
for _, txn := range []types.Transaction{
types.NewContractCreation(0, uint256.NewInt(1), 500_000, gasPrice, selfdestruct),
types.NewTransaction(1, common.HexToAddress("0x4000"), uint256.NewInt(1), 500_000, gasPrice, nil),
} {
signed, err := types.SignTx(txn, *signer, key)
require.NoError(t, err)
gen.AddTx(signed)
}
})
require.NoError(t, err)
require.NoError(t, m.InsertChain(generated))
for _, receipt := range generated.Receipts[0] {
require.Equal(t, types.ReceiptStatusSuccessful, receipt.Status)
}

api := newDebugApiForTest(m)
tracer, tracerConfig := "prestateTracer", json.RawMessage(`{"diffMode":true}`)
config := &tracersConfig.TraceConfig{Tracer: &tracer, TracerConfig: &tracerConfig}
var blockTraces []struct {
Result json.RawMessage `json:"result"`
}
readGasTrace(t, &blockTraces, func(stream *jsonstream.Stream) error {
return api.TraceBlockByNumber(m.Ctx, 1, config, stream)
})
block := generated.Blocks[0]
require.Len(t, blockTraces, len(block.Transactions()))
for i, txn := range block.Transactions() {
var txnTrace json.RawMessage
readGasTrace(t, &txnTrace, func(stream *jsonstream.Stream) error {
return api.TraceTransaction(m.Ctx, txn.Hash(), config, stream)
})
require.JSONEq(t, string(txnTrace), string(blockTraces[i].Result), "transaction %d", i)
}

var diff struct {
Post map[common.Address]struct {
Balance *hexutil.U256 `json:"balance"`
} `json:"post"`
}
require.NoError(t, json.Unmarshal(blockTraces[1].Result, &diff))
post, ok := diff.Post[coinbase]
require.True(t, ok, "%s", blockTraces[1].Result)
tip := new(uint256.Int).Sub(gasPrice, block.BaseFee())
tip.Mul(tip, uint256.NewInt(generated.Receipts[0][1].GasUsed))
require.Equal(t, (*hexutil.U256)(tip), post.Balance)
}

func TestTraceTransaction(t *testing.T) {
m, _, _ := rpcdaemontest.CreateTestExecModule(t)
api := newDebugApiForTest(m)
Expand Down
Loading