Skip to content

Commit b9b4347

Browse files
committed
core, core/vm: implement EIP-7708
1 parent 300f233 commit b9b4347

File tree

10 files changed

+270
-7
lines changed

10 files changed

+270
-7
lines changed

core/eth_transfer_logs_test.go

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
// Copyright 2026 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package core
18+
19+
import (
20+
"encoding/binary"
21+
"math/big"
22+
"reflect"
23+
"testing"
24+
25+
"github.com/ethereum/go-ethereum/common"
26+
"github.com/ethereum/go-ethereum/consensus/beacon"
27+
"github.com/ethereum/go-ethereum/consensus/ethash"
28+
"github.com/ethereum/go-ethereum/core/types"
29+
"github.com/ethereum/go-ethereum/crypto"
30+
"github.com/ethereum/go-ethereum/params"
31+
)
32+
33+
var ethTransferTestCode = common.FromHex("6080604052600436106100345760003560e01c8063574ffc311461003957806366e41cb714610090578063f8a8fd6d1461009a575b600080fd5b34801561004557600080fd5b5061004e6100a4565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6100986100ac565b005b6100a26100f5565b005b63deadbeef81565b7f38e80b5c85ba49b7280ccc8f22548faa62ae30d5a008a1b168fba5f47f5d1ee560405160405180910390a1631234567873ffffffffffffffffffffffffffffffffffffffff16ff5b7f24ec1d3ff24c2f6ff210738839dbc339cd45a5294d85c79361016243157aae7b60405160405180910390a163deadbeef73ffffffffffffffffffffffffffffffffffffffff166002348161014657fe5b046040516024016040516020818303038152906040527f66e41cb7000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506040518082805190602001908083835b602083106101fd57805182526020820191506020810190506020830392506101da565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d806000811461025f576040519150601f19603f3d011682016040523d82523d6000602084013e610264565b606091505b50505056fea265627a7a723158202cce817a434785d8560c200762f972d453ccd30694481be7545f9035a512826364736f6c63430005100032")
34+
35+
/*
36+
pragma solidity >=0.4.22 <0.6.0;
37+
38+
contract TestLogs {
39+
40+
address public constant target_contract = 0x00000000000000000000000000000000DeaDBeef;
41+
address payable constant selfdestruct_addr = 0x0000000000000000000000000000000012345678;
42+
43+
event Response(bool success, bytes data);
44+
event TestEvent();
45+
event TestEvent2();
46+
47+
function test() public payable {
48+
emit TestEvent();
49+
target_contract.call.value(msg.value/2)(abi.encodeWithSignature("test2()"));
50+
}
51+
function test2() public payable {
52+
emit TestEvent2();
53+
selfdestruct(selfdestruct_addr);
54+
}
55+
}
56+
*/
57+
58+
// TestEthTransferLogs tests EIP-7708 ETH transfer log output by simulating a
59+
// scenario including transaction, CALL and SELFDESTRUCT value transfers, and
60+
// also "ordinary" logs emitted. The same scenario is also tested with no value
61+
// transferred.
62+
func TestEthTransferLogs(t *testing.T) {
63+
testEthTransferLogs(t, 1_000_000_000)
64+
testEthTransferLogs(t, 0)
65+
}
66+
67+
func testEthTransferLogs(t *testing.T, value uint64) {
68+
var (
69+
key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
70+
addr1 = crypto.PubkeyToAddress(key1.PublicKey)
71+
addr2 = common.HexToAddress("cafebabe") // caller
72+
addr3 = common.HexToAddress("deadbeef") // callee
73+
addr4 = common.HexToAddress("12345678") // selfdestruct target
74+
testEvent = crypto.Keccak256Hash([]byte("TestEvent()"))
75+
testEvent2 = crypto.Keccak256Hash([]byte("TestEvent2()"))
76+
config = *params.MergedTestChainConfig
77+
signer = types.LatestSigner(&config)
78+
engine = beacon.New(ethash.NewFaker())
79+
)
80+
81+
//TODO remove this hacky config initialization when final Amsterdam config is available
82+
config.AmsterdamTime = new(uint64)
83+
blobConfig := *config.BlobScheduleConfig
84+
blobConfig.Amsterdam = blobConfig.Osaka
85+
config.BlobScheduleConfig = &blobConfig
86+
87+
gspec := &Genesis{
88+
Config: &config,
89+
Alloc: types.GenesisAlloc{
90+
addr1: {Balance: newGwei(1000000000)},
91+
addr2: {Code: ethTransferTestCode},
92+
addr3: {Code: ethTransferTestCode},
93+
},
94+
}
95+
_, blocks, receipts := GenerateChainWithGenesis(gspec, engine, 1, func(i int, b *BlockGen) {
96+
tx := types.MustSignNewTx(key1, signer, &types.DynamicFeeTx{
97+
ChainID: gspec.Config.ChainID,
98+
Nonce: 0,
99+
To: &addr2,
100+
Gas: 500_000,
101+
GasFeeCap: newGwei(5),
102+
GasTipCap: newGwei(5),
103+
Value: big.NewInt(int64(value)),
104+
Data: common.FromHex("f8a8fd6d"),
105+
})
106+
b.AddTx(tx)
107+
})
108+
109+
blockHash := blocks[0].Hash()
110+
txHash := blocks[0].Transactions()[0].Hash()
111+
addr2hash := func(addr common.Address) (hash common.Hash) {
112+
copy(hash[12:], addr[:])
113+
return
114+
}
115+
u256 := func(amount uint64) []byte {
116+
data := make([]byte, 32)
117+
binary.BigEndian.PutUint64(data[24:], amount)
118+
return data
119+
}
120+
121+
var expLogs = []*types.Log{
122+
{
123+
Address: params.SystemAddress,
124+
Topics: []common.Hash{params.EthTransferLogEvent, addr2hash(addr1), addr2hash(addr2)},
125+
Data: u256(value),
126+
},
127+
{
128+
Address: addr2,
129+
Topics: []common.Hash{testEvent},
130+
Data: nil,
131+
},
132+
{
133+
Address: params.SystemAddress,
134+
Topics: []common.Hash{params.EthTransferLogEvent, addr2hash(addr2), addr2hash(addr3)},
135+
Data: u256(value / 2),
136+
},
137+
{
138+
Address: addr3,
139+
Topics: []common.Hash{testEvent2},
140+
Data: nil,
141+
},
142+
{
143+
Address: params.SystemAddress,
144+
Topics: []common.Hash{params.EthTransferLogEvent, addr2hash(addr3), addr2hash(addr4)},
145+
Data: u256(value / 2),
146+
},
147+
}
148+
if value == 0 {
149+
// no ETH transfer logs expected with zero value
150+
expLogs = []*types.Log{expLogs[1], expLogs[3]}
151+
}
152+
for i, log := range expLogs {
153+
log.BlockNumber = 1
154+
log.BlockHash = blockHash
155+
log.BlockTimestamp = 10
156+
log.TxIndex = 0
157+
log.TxHash = txHash
158+
log.Index = uint(i)
159+
}
160+
161+
if len(expLogs) != len(receipts[0][0].Logs) {
162+
t.Fatalf("Incorrect number of logs (expected: %d, got: %d)", len(expLogs), len(receipts[0][0].Logs))
163+
}
164+
for i, log := range receipts[0][0].Logs {
165+
if !reflect.DeepEqual(expLogs[i], log) {
166+
t.Fatalf("Incorrect log at index %d (expected: %v, got: %v)", i, expLogs[i], log)
167+
}
168+
}
169+
}

core/evm.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"github.com/ethereum/go-ethereum/core/tracing"
2626
"github.com/ethereum/go-ethereum/core/types"
2727
"github.com/ethereum/go-ethereum/core/vm"
28+
"github.com/ethereum/go-ethereum/params"
2829
"github.com/holiman/uint256"
2930
)
3031

@@ -138,7 +139,10 @@ func CanTransfer(db vm.StateDB, addr common.Address, amount *uint256.Int) bool {
138139
}
139140

140141
// Transfer subtracts amount from sender and adds amount to recipient using the given Db
141-
func Transfer(db vm.StateDB, sender, recipient common.Address, amount *uint256.Int) {
142+
func Transfer(db vm.StateDB, sender, recipient common.Address, amount *uint256.Int, blockNumber *big.Int, rules *params.Rules) {
142143
db.SubBalance(sender, amount, tracing.BalanceChangeTransfer)
143144
db.AddBalance(recipient, amount, tracing.BalanceChangeTransfer)
145+
if rules.IsAmsterdam && !amount.IsZero() && sender != recipient {
146+
db.AddLog(types.EthTransferLog(blockNumber, sender, recipient, amount))
147+
}
144148
}

core/state/statedb.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,28 @@ func (s *StateDB) GetRefund() uint64 {
745745
return s.refund
746746
}
747747

748+
type RemovedAccountWithBalance struct {
749+
Address common.Address
750+
Balance *uint256.Int
751+
}
752+
753+
// GetRemovedAccountsWithBalance returns a list of accounts scheduled for
754+
// removal which still have positive balance. The purpose of this function is
755+
// to handle a corner case of EIP-7708 where a self-destructed account might
756+
// still receive funds between sending/burning its previous balance and actual
757+
// removal. In this case the burning of these remaining balances still need to
758+
// be logged.
759+
// Specification EIP-7708: https://eips.ethereum.org/EIPS/eip-7708
760+
func (s *StateDB) GetRemovedAccountsWithBalance() (list []RemovedAccountWithBalance) {
761+
for addr := range s.journal.dirties {
762+
if obj, exist := s.stateObjects[addr]; exist &&
763+
obj.selfDestructed && !obj.Balance().IsZero() {
764+
list = append(list, RemovedAccountWithBalance{Address: obj.address, Balance: obj.Balance()})
765+
}
766+
}
767+
return list
768+
}
769+
748770
// Finalise finalises the state by removing the destructed objects and clears
749771
// the journal as well as the refunds. Finalise, however, will not push any updates
750772
// into the tries just yet. Only IntermediateRoot or Commit will do that.

core/state_processor.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"context"
2121
"fmt"
2222
"math/big"
23+
"sort"
2324

2425
"github.com/ethereum/go-ethereum/common"
2526
"github.com/ethereum/go-ethereum/consensus/misc"
@@ -173,6 +174,18 @@ func ApplyTransactionWithEVM(msg *Message, gp *GasPool, statedb *state.StateDB,
173174
if err != nil {
174175
return nil, err
175176
}
177+
if evm.ChainConfig().IsAmsterdam(blockNumber, blockTime) {
178+
// Emit Selfdesctruct logs where accounts with non-empty balances have been deleted
179+
removedWithBalance := statedb.GetRemovedAccountsWithBalance()
180+
if removedWithBalance != nil {
181+
sort.Slice(removedWithBalance, func(i, j int) bool {
182+
return removedWithBalance[i].Address.Cmp(removedWithBalance[j].Address) < 0
183+
})
184+
for _, sd := range removedWithBalance {
185+
statedb.AddLog(types.EthSelfDestructLog(blockNumber, sd.Address, sd.Balance))
186+
}
187+
}
188+
}
176189
// Update the state with pending changes.
177190
var root []byte
178191
if evm.ChainConfig().IsByzantium(blockNumber) {

core/types/log.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,12 @@
1717
package types
1818

1919
import (
20+
"math/big"
21+
2022
"github.com/ethereum/go-ethereum/common"
2123
"github.com/ethereum/go-ethereum/common/hexutil"
24+
"github.com/ethereum/go-ethereum/params"
25+
"github.com/holiman/uint256"
2226
)
2327

2428
//go:generate go run ../../rlp/rlpgen -type Log -out gen_log_rlp.go
@@ -62,3 +66,38 @@ type logMarshaling struct {
6266
BlockTimestamp hexutil.Uint64
6367
Index hexutil.Uint
6468
}
69+
70+
// EthTransferLog creates and ETH transfer log according to EIP-7708.
71+
// Specification: https://eips.ethereum.org/EIPS/eip-7708
72+
func EthTransferLog(blockNumber *big.Int, from, to common.Address, amount *uint256.Int) *Log {
73+
amount32 := amount.Bytes32()
74+
return &Log{
75+
Address: params.SystemAddress,
76+
Topics: []common.Hash{
77+
params.EthTransferLogEvent,
78+
common.BytesToHash(from.Bytes()),
79+
common.BytesToHash(to.Bytes()),
80+
},
81+
Data: amount32[:],
82+
// This is a non-consensus field, but assigned here because
83+
// core/state doesn't know the current block number.
84+
BlockNumber: blockNumber.Uint64(),
85+
}
86+
}
87+
88+
// EthSelfDestructLog creates and ETH self-destruct burn log according to EIP-7708.
89+
// Specification: https://eips.ethereum.org/EIPS/eip-7708
90+
func EthSelfDestructLog(blockNumber *big.Int, from common.Address, amount *uint256.Int) *Log {
91+
amount32 := amount.Bytes32()
92+
return &Log{
93+
Address: params.SystemAddress,
94+
Topics: []common.Hash{
95+
params.EthSelfDestructLogEvent,
96+
common.BytesToHash(from.Bytes()),
97+
},
98+
Data: amount32[:],
99+
// This is a non-consensus field, but assigned here because
100+
// core/state doesn't know the current block number.
101+
BlockNumber: blockNumber.Uint64(),
102+
}
103+
}

core/vm/evm.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ type (
3535
// CanTransferFunc is the signature of a transfer guard function
3636
CanTransferFunc func(StateDB, common.Address, *uint256.Int) bool
3737
// TransferFunc is the signature of a transfer function
38-
TransferFunc func(StateDB, common.Address, common.Address, *uint256.Int)
38+
TransferFunc func(StateDB, common.Address, common.Address, *uint256.Int, *big.Int, *params.Rules)
3939
// GetHashFunc returns the n'th block hash in the blockchain
4040
// and is used by the BLOCKHASH EVM op code.
4141
GetHashFunc func(uint64) common.Hash
@@ -283,8 +283,9 @@ func (evm *EVM) Call(caller common.Address, addr common.Address, input []byte, g
283283
// Calling this is required even for zero-value transfers,
284284
// to ensure the state clearing mechanism is applied.
285285
if !syscall {
286-
evm.Context.Transfer(evm.StateDB, caller, addr, value)
286+
evm.Context.Transfer(evm.StateDB, caller, addr, value, evm.Context.BlockNumber, &evm.chainRules)
287287
}
288+
288289
if isPrecompile {
289290
var stateDB StateDB
290291
if evm.chainRules.IsAmsterdam {
@@ -567,7 +568,7 @@ func (evm *EVM) create(caller common.Address, code []byte, gas uint64, value *ui
567568
}
568569
gas = gas - consumed
569570
}
570-
evm.Context.Transfer(evm.StateDB, caller, address, value)
571+
evm.Context.Transfer(evm.StateDB, caller, address, value, evm.Context.BlockNumber, &evm.chainRules)
571572

572573
// Initialise a new contract and set the code that is to be used by the EVM.
573574
// The contract is a scoped environment for this execution context only.

core/vm/gas_table_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ func TestEIP2200(t *testing.T) {
9494

9595
vmctx := BlockContext{
9696
CanTransfer: func(StateDB, common.Address, *uint256.Int) bool { return true },
97-
Transfer: func(StateDB, common.Address, common.Address, *uint256.Int) {},
97+
Transfer: func(StateDB, common.Address, common.Address, *uint256.Int, *big.Int, *params.Rules) {},
9898
}
9999
evm := NewEVM(vmctx, statedb, params.AllEthashProtocolChanges, Config{ExtraEips: []int{2200}})
100100

@@ -144,7 +144,7 @@ func TestCreateGas(t *testing.T) {
144144
statedb.Finalise(true)
145145
vmctx := BlockContext{
146146
CanTransfer: func(StateDB, common.Address, *uint256.Int) bool { return true },
147-
Transfer: func(StateDB, common.Address, common.Address, *uint256.Int) {},
147+
Transfer: func(StateDB, common.Address, common.Address, *uint256.Int, *big.Int, *params.Rules) {},
148148
BlockNumber: big.NewInt(0),
149149
}
150150
config := Config{}

core/vm/instructions.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -934,6 +934,13 @@ func opSelfdestruct6780(pc *uint64, evm *EVM, scope *ScopeContext) ([]byte, erro
934934
evm.StateDB.SubBalance(this, balance, tracing.BalanceDecreaseSelfdestruct)
935935
evm.StateDB.AddBalance(beneficiary, balance, tracing.BalanceIncreaseSelfdestruct)
936936
}
937+
if evm.chainRules.IsAmsterdam && !balance.IsZero() {
938+
if this != beneficiary {
939+
evm.StateDB.AddLog(types.EthTransferLog(evm.Context.BlockNumber, this, beneficiary, balance))
940+
} else if newContract {
941+
evm.StateDB.AddLog(types.EthSelfDestructLog(evm.Context.BlockNumber, this, balance))
942+
}
943+
}
937944

938945
if tracer := evm.Config.Tracer; tracer != nil {
939946
if tracer.OnEnter != nil {

core/vm/interpreter_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ var loopInterruptTests = []string{
4040
func TestLoopInterrupt(t *testing.T) {
4141
address := common.BytesToAddress([]byte("contract"))
4242
vmctx := BlockContext{
43-
Transfer: func(StateDB, common.Address, common.Address, *uint256.Int) {},
43+
Transfer: func(StateDB, common.Address, common.Address, *uint256.Int, *big.Int, *params.Rules) {},
4444
}
4545

4646
for i, tt := range loopInterruptTests {

params/protocol_params.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,3 +220,11 @@ var (
220220
ConsolidationQueueAddress = common.HexToAddress("0x0000BBdDc7CE488642fb579F8B00f3a590007251")
221221
ConsolidationQueueCode = common.FromHex("3373fffffffffffffffffffffffffffffffffffffffe1460d35760115f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1461019a57600182026001905f5b5f82111560685781019083028483029004916001019190604d565b9093900492505050366060146088573661019a573461019a575f5260205ff35b341061019a57600154600101600155600354806004026004013381556001015f358155600101602035815560010160403590553360601b5f5260605f60143760745fa0600101600355005b6003546002548082038060021160e7575060025b5f5b8181146101295782810160040260040181607402815460601b815260140181600101548152602001816002015481526020019060030154905260010160e9565b910180921461013b5790600255610146565b90505f6002555f6003555b5f54807fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff141561017357505f5b6001546001828201116101885750505f61018e565b01600190035b5f555f6001556074025ff35b5f5ffd")
222222
)
223+
224+
// System log events.
225+
var (
226+
// EIP-7708 - System logs emitted for ETH transfer and self-destruct balance burn
227+
EthTransferLogEvent = common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") // keccak256('Transfer(address,address,uint256)')
228+
EthSelfDestructLogEvent = common.HexToHash("0x4bfaba3443c1a1836cd362418edc679fc96cae8449cbefccb6457cdf2c943083") // keccak256('Selfdestruct(address,uint256)')
229+
230+
)

0 commit comments

Comments
 (0)