Skip to content

execution/state: report only the current transaction's self-destruct - #26228

Open
canepat wants to merge 8 commits into
mainfrom
canepat/prestate-selfdestruct-scope
Open

canepat wants to merge 8 commits into
mainfrom
canepat/prestate-selfdestruct-scope

Conversation

@canepat

@canepat canepat commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

HasSelfdestructed on the versioned state returned an earlier transaction's self-destruct from the version map, so debug_traceBlockByNumber with prestateTracer diffMode dropped that account, e.g. a coinbase's fee credit, from a later transaction's trace while debug_traceTransaction reported it. Before London the SELFDESTRUCT gas functions ask the same question, so parallel execution skipped the refund for a re-created contract destroying itself in a later transaction and rejected the block on gas used.

  • TestTraceBlockPrestateDiffAfterSelfdestruct, TestHasSelfdestructed_EarlierTxDestruct and TestSelfdestructRefundInTxAfterRecreate fail on main, pass with the fix.
  • TestWipedReadAfterRevivalKeepsSelfDestructFalse also asserts the recorded read, which HasSelfdestructed no longer exposes.

On the versioned state HasSelfdestructed also returned a destruct an
earlier transaction of the block wrote to the version map, so the
prestate tracer in diff mode dropped that account from a later
transaction's block trace, e.g. a coinbase's fee credit, while
debug_traceTransaction reported it.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues remain for the change that limits reported self-destruct status to the current transaction.

No open issues 🎉

What changed in this PR

This PR makes HasSelfdestructed report only the current transaction’s self-destruct status, preventing earlier transactions from incorrectly affecting later prestate traces.

Changes:

  • Exclude self-destruct values read from the version map from the reported status.
  • Add regression tests for transaction-local status and consistent block-versus-transaction prestate traces.
  • Strengthen the revival test by checking the recorded versioned read directly.
File Description
rpc/​jsonrpc/​debug_api_test.go Tests trace consistency and preservation of a later coinbase fee credit.
execution/​state/​selfdestruct_parallel_test.go Tests that an earlier transaction’s self-destruct is not reported for a later transaction.
execution/​state/​revival_reader_test.go Verifies that the recorded read reflects account revival.
execution/​state/​intra_block_state.go Limits reported self-destruct status to the current transaction.

Review effort: Balanced

@canepat
canepat marked this pull request as ready for review November 13, 2026 10:24
@yperbasis
yperbasis requested review from chfast and a max review from Copilot November 13, 2026 12:52

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The test header still misstates the regression check and should describe verifying that the recorded SelfDestruct read contains the revival’s false value.

1 open issue

Review effort: Max

Comment thread execution/state/revival_reader_test.go Resolved

@yperbasis yperbasis left a comment

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.

Approving.

Point one: this also fixes block execution, and no test pins that part. Before London both SELFDESTRUCT gas functions ask HasSelfdestructed whether to add the refund. On main a wiped read records the earlier transaction's destruct in the read set, and the gas function gets that record back and skips the refund.

A block that shows it: X destroys itself, another contract's SELFDESTRUCT sends wei to X, the same CREATE2 deploys X again, and in the next transaction X reads a slot and destroys itself. On Berlin, main charges that last transaction 28107 gas, the non-versioned generator charges 14054, and parallel import rejects the block: invalid block, gas used by execution: 180596, in header: 166543. With this PR all three agree.

TestSelfdestructRefundAfterRecreate only covers the case where the re-creating transaction destroys X itself. Could you add the later-transaction case next to it and mention the refund in the description? This one fails on main and passes here:

test
// 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)
			})
		})
	}
}

generatedBlockWant entries, as the non-versioned generator built them:

"TestSelfdestructRefundInTxAfterRecreate/berlin":     {"0xebd30387316ce450e736cdb8f8289a7995eb0f83f574ff9a4cf5775f547f025d", 166543},
"TestSelfdestructRefundInTxAfterRecreate/petersburg": {"0xdc15d9db6c68f2f33382ae21d7e77e53415c5b8c638ee32f9e08e37f33e8c1fe", 162043},

release/3.8 rejects the same block with the parallel executor, so a backport may be worth it.

Point two: in TestWipedReadAfterRevivalKeepsSelfDestructFalse the HasSelfdestructed call runs before the record check and records the cell itself, so require.True(t, ok) cannot fail: the test still passes when recordWipedSelfDestruct records nothing. Checking the record first fixes it. The doc comment also says again that HasSelfdestructed must see the revival, which is no longer what the test checks.

Point three, not for this PR: in diff mode prestateTracer puts {"codeHash":"0x00…00"} into post for an account that does not exist before or after the transaction. The previous code hash defaults to the empty hash, and GetCodeHash of an absent account is zero. debug_traceTransaction already prints it for a zero-value call to an address that never existed; after this PR the block trace prints it too for an account an earlier transaction destroyed. Worth a follow-up issue.

@lupin012

Copy link
Copy Markdown
Contributor

@canepat, @yperbasis
I tried to find this case on mainnet to add an rpc-tests fixture, but I could not find one after hours of scans.

Check on a hive chain: geth vs erigon main vs erigon with this PR

Chain. The hive rpc-compat chain has no SELFDESTRUCT, so I generated one with hivechain, using the same parameters as mkchain.sh plus one extra block (block 43) where:

  • tx 0 creates a contract that destroys itself at once; that contract is also the block's coinbase;
  • tx 1 is a plain transfer, which pays its tip to the coinbase that was just destroyed.

Check. On block 43, with prestateTracer {"diffMode": true}, I compared each tx's result in debug_traceBlockByNumber with debug_traceTransaction of the same tx, and compared the clients against each other.

Client Block trace = single-tx trace tx 1: post[coinbase] in the block trace
geth 1.17.11-unstable (18bf8070a) ✅ all 5 txs {"balance": "0x5208"}
erigon main (f9da00be8f, PR base) ❌ txs 1–4 differ missing
erigon with this PR (62fea77de9) ✅ all 5 txs {"balance": "0x5208"}
  • erigon main: in the block trace, the coinbase is missing from the post of txs 1, 2, 3 and 4. The single-tx trace is correct and matches geth.
  • erigon with this PR: both the block trace and the single-tx trace match geth for every tx.

Copilot AI max review requested due to automatic review settings November 13, 2026 22:22
@canepat

canepat commented Nov 13, 2026 •

Copy link
Copy Markdown
Member Author

Thanks.

@yperbasis

  1. Added TestSelfdestructRefundInTxAfterRecreate in 57506db next to TestSelfdestructRefundAfterRecreate, with its generatedBlockWant entries. It fails without the fix and passes with it. The description now mentions the refund.
  2. Fixed in 80cb0ec: the record is checked before HasSelfdestructed, and the doc comment says what the test checks. With recordWipedSelfDestruct recording nothing, the test now fails on ok.
  3. Handing this over to @lupin012 for a follow-up issue.

@lupin012
You might consider to upstream a PR on hive rpc-compat tests with your extended chain and 2 fixtures to cover this cross-endpoint incompatibility between debug_traceBlockByNumber and debug_traceTransaction.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Consensus-critical pre-London SELFDESTRUCT refund semantics depend on an unenforced read-path invariant, requiring maintainer confirmation and parallel re-execution over pre-London history.

No open issues 🎉

1 resolved since last review

Review effort: Max

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.

Copilot AI max review requested due to automatic review settings November 14, 2026 07:31
@canepat

canepat commented Nov 14, 2026

Copy link
Copy Markdown
Member Author

Reply to Copilot's last review:

Consensus-critical pre-London SELFDESTRUCT refund semantics depend on an unenforced read-path invariant, requiring maintainer confirmation and parallel re-execution over pre-London history.

The invariant is that a transaction's own SELFDESTRUCT never reads back as MapRead. It holds because the destruct marks the address dirty in the journal, which bypasses the warm read set, and versionedReadCore serves the transaction's own SelfDestructPath write as WriteSetRead, also over an earlier transaction's destruct. Two tests now enforce it:

  • 8dd7aaa TestHasSelfdestructed_OwnDestructAfterEarlierTx: five version-map histories (no earlier write; destroyed, then re-created in this or an earlier transaction, with and without a credit in between). Each calls HasSelfdestructed as the gas function does, around a reverted and then a real SELFDESTRUCT. It fails if HasSelfdestructed also drops WriteSetRead, if versionedReadCore ignores the own SelfDestructPath write after an earlier destruct, or if warmReadable ignores the journal's dirty mark.
  • 95641a8 TestSelfdestructRefundOncePerTx: one Petersburg and one Berlin block. X destroys itself twice in one transaction, is revived and re-created, destroys itself in a reverted call and then for real, and is re-created and destroys itself twice again. Gas is pinned by the non-versioned generator, and the block is imported with 1, 2, 4 and 8 workers. It fails when the own destruct is not reported (a second refund).

Both tests also fail on main. After a destroy, a credit and a re-create in earlier transactions, the version map's latest SelfDestructPath cell is still the destruct, so the first read records a stale true. After a reverted SELFDESTRUCT, the warm path returns that record, and the next SELFDESTRUCT in the transaction loses its refund. Excluding MapRead covers this case too.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

The consensus-critical pre-London SELFDESTRUCT refund change depends on MapRead never containing the current transaction’s own destruct and requires runtime validation against historical blocks.

No open issues 🎉

Review effort: Max

@canepat
canepat added this pull request to the merge queue Nov 14, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 14, 2026
@AskAlexSharov
AskAlexSharov added this pull request to the merge queue Nov 14, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 14, 2026
@AskAlexSharov
AskAlexSharov added this pull request to the merge queue Nov 15, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 15, 2026
@canepat
canepat added this pull request to the merge queue Nov 15, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 15, 2026
@yperbasis yperbasis added this to the 3.9.0 milestone Nov 16, 2026
@AskAlexSharov
AskAlexSharov added this pull request to the merge queue Nov 16, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 16, 2026
Copilot AI max review requested due to automatic review settings November 16, 2026 22:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The regression test can pass with the original bug when parallel tracing isolates transaction state, so it must force sequential replay to reliably exercise the affected shared-state path.

1 open issue

Review effort: Max

var blockTraces []struct {
Result json.RawMessage `json:"result"`
}
readGasTrace(t, &blockTraces, func(stream *jsonstream.Stream) error {

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants