From 86b4b37dd028750ec120070dd13621bfdeb5b910 Mon Sep 17 00:00:00 2001 From: bysomeone <11565373+bysomeone@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:09:26 +0800 Subject: [PATCH 1/9] fix(evm): derive internal CREATE addresses from caller nonce behind a fork EVM-internal CREATE used hash(txHash||origin), so every CREATE inside one transaction produced the same address. EVM.Create also accepted an existing account silently, so a factory deploying two children in one call had the second overwrite the first while the transaction still reported success. Gate the Ethereum behaviour behind ForkEVMContractCreateV2. Registered at MaxHeight (off by default, opt-in per chain) like ForkEVMTransferRevert: enabling it from genesis on an existing chain would rewrite historical execution. - CREATE address = CreateAddress(executing account, its nonce); the caller nonce is incremented before any create snapshot and persisted in contract state, so it survives across transactions and failed creates. - Newly created contracts start at nonce 1 (EIP-161); an account with a nonce is no longer treated as non-existent. - CREATE/CREATE2 fail with ErrContractAddressCollision (consuming the forwarded gas) when the target already has a nonce or code. - ErrCodeStoreOutOfGas rolls the creation back instead of keeping the account and pushing its address. - CREATE/CREATE2 forward 63/64 of the remaining gas (EIP-150); CREATE2 no longer halves it, and converts value precision for ETH-signed transactions the same way CREATE does. Address construction for the new path bypasses the chain33 address driver: a btc-format driver cannot parse a 0x hex string and produced an all-zero raw address. Fork-off execution is unchanged; the nonceChange KV write is gated on the same fork. Co-authored-by: Claude --- chain33.fork.toml | 2 + chain33.para.toml | 2 + .../dapp/evm/cmd/ci2/chain33.proxyminer.toml | 2 + .../evm/executor/create_compat_repro_test.go | 398 ++++++++++++++++++ plugin/dapp/evm/executor/query_test.go | 4 + plugin/dapp/evm/executor/vm/common/address.go | 8 + plugin/dapp/evm/executor/vm/runtime/evm.go | 25 +- .../evm/executor/vm/runtime/instructions.go | 38 +- plugin/dapp/evm/executor/vm/state/account.go | 12 +- plugin/dapp/evm/executor/vm/state/snapshot.go | 15 +- plugin/dapp/evm/types/evm.go | 4 + plugin/dapp/evm/types/types.go | 4 + 12 files changed, 499 insertions(+), 15 deletions(-) create mode 100644 plugin/dapp/evm/executor/create_compat_repro_test.go diff --git a/chain33.fork.toml b/chain33.fork.toml index a855a35a6..bada5286b 100644 --- a/chain33.fork.toml +++ b/chain33.fork.toml @@ -103,6 +103,8 @@ ForkEVMFixOverflow=0 ForkEVMSuicidePayer=0 # Revertible value transfers; -1 keeps the fix off (resolved to MaxHeight) ForkEVMTransferRevert=-1 +# Internal CREATE/CREATE2 follow Ethereum address derivation; -1 keeps it off +ForkEVMContractCreateV2=-1 [fork.sub.evmxgo] diff --git a/chain33.para.toml b/chain33.para.toml index a6c8915cb..bf9aaa08a 100644 --- a/chain33.para.toml +++ b/chain33.para.toml @@ -439,6 +439,8 @@ ForkEVMFixOverflow=0 ForkEVMSuicidePayer=0 # Revertible value transfers; -1 keeps the fix off (resolved to MaxHeight) ForkEVMTransferRevert=-1 +# Internal CREATE/CREATE2 follow Ethereum address derivation; -1 keeps it off +ForkEVMContractCreateV2=-1 [fork.sub.blackwhite] Enable=0 diff --git a/plugin/dapp/evm/cmd/ci2/chain33.proxyminer.toml b/plugin/dapp/evm/cmd/ci2/chain33.proxyminer.toml index 316bbd346..31124fc31 100644 --- a/plugin/dapp/evm/cmd/ci2/chain33.proxyminer.toml +++ b/plugin/dapp/evm/cmd/ci2/chain33.proxyminer.toml @@ -607,6 +607,8 @@ ForkEVMFixOverflow=0 ForkEVMSuicidePayer=0 # Revertible value transfers; -1 keeps the fix off (resolved to MaxHeight) ForkEVMTransferRevert=-1 +# Internal CREATE/CREATE2 follow Ethereum address derivation; -1 keeps it off +ForkEVMContractCreateV2=-1 [fork.sub.evmxgo] Enable=0 diff --git a/plugin/dapp/evm/executor/create_compat_repro_test.go b/plugin/dapp/evm/executor/create_compat_repro_test.go new file mode 100644 index 000000000..3f756246f --- /dev/null +++ b/plugin/dapp/evm/executor/create_compat_repro_test.go @@ -0,0 +1,398 @@ +package executor + +import ( + "bytes" + "testing" + + apimock "github.com/33cn/chain33/client/mocks" + "github.com/33cn/chain33/common/address" + ctypes "github.com/33cn/chain33/types" + vcomm "github.com/33cn/plugin/plugin/dapp/evm/executor/vm/common" + evmtypes "github.com/33cn/plugin/plugin/dapp/evm/types" + gethcommon "github.com/ethereum/go-ethereum/common" + ethcrypto "github.com/ethereum/go-ethereum/crypto" +) + +// Factory whose runtime code performs two CREATEs of the same 5-byte init code +// (0x60006000f3: return empty runtime) and returns the two resulting addresses +// as 64 bytes of return data. +// +// runtime: +// +// PUSH5 0x60006000f3; PUSH1 0x00; MSTORE ; mem[0..32] = initcode +// PUSH1 5; PUSH1 27; PUSH1 0; CREATE ; addr1 +// PUSH1 5; PUSH1 27; PUSH1 0; CREATE ; addr2 +// PUSH1 0x20; MSTORE ; mem[32..64] = addr2 +// PUSH1 0x00; MSTORE ; mem[0..32] = addr1 +// PUSH1 0x40; PUSH1 0x00; RETURN +const factoryCreateTwiceRuntime = "6460006000f3" + "600052" + "6005601b6000f0" + "6005601b6000f0" + "602052" + "600052" + "60406000f3" + +// deploy wrapper: CODECOPY runtime (34 bytes at offset 12) then RETURN it +const factoryCreateTwiceBytecode = "6022600c60003960226000f3" + factoryCreateTwiceRuntime + +// Factory whose runtime code performs a single CREATE and returns the resulting +// address as 32 bytes of return data. +const factoryCreateOnceRuntime = "6460006000f3" + "600052" + "6005601b6000f0" + "600052" + "60206000f3" + +// deploy wrapper: CODECOPY runtime (24 bytes at offset 12) then RETURN it +const factoryCreateOnceBytecode = "6018600c60003960186000f3" + factoryCreateOnceRuntime + +// CREATE2 with a constant salt and constant init code: the address is by design +// the same on both calls, so the second one must fail as a collision (EIP-1014). +const create2TwiceBytecode = "6026600c60003960266000f3" + + "6460006000f3" + "600052" + + "60016005601b6000f5" + + "60016005601b6000f5" + + "602052" + "600052" + "60406000f3" + +// deployContract deploys bytecode and applies the resulting KV set the way the +// block executor does between transactions. +func deployContract(t *testing.T, cfg *ctypes.Chain33Config, exec *EVMExecutor, bytecode string) string { + t.Helper() + execAddr := address.ExecAddress(cfg.ExecName(evmtypes.ExecutorName)) + action := &evmtypes.EVMContractAction{Code: vcomm.FromHex(bytecode), ContractAddr: execAddr} + tx := &ctypes.Transaction{ + ChainID: cfg.GetChainID(), + Execer: []byte(cfg.ExecName(evmtypes.ExecutorName)), + Payload: ctypes.Encode(action), + Fee: 1e6, To: execAddr, Nonce: 0, + } + signTx(tx, roleDeployer) + resetEvmExecAddress(cfg) + r, err := exec.Exec(tx, 0) + if err != nil || r == nil || r.Ty != ctypes.ExecOk { + t.Fatalf("deploy: err=%v ty=%d", err, r.GetTy()) + } + addr := vcomm.NewContractAddress(*vcomm.StringToAddress(tx.From()), tx.Hash()).String() + for _, kv := range r.KV { + if err := exec.GetStateDB().Set(kv.Key, kv.Value); err != nil { + t.Fatalf("apply deploy kv: %v", err) + } + } + return addr +} + +// callRet runs a call and returns the receipt plus the EVM return data. +func callRet(t *testing.T, cfg *ctypes.Chain33Config, exec *EVMExecutor, addr string) (*ctypes.Receipt, []byte, error) { + t.Helper() + r, err := exec.Exec(makeCallTx(cfg, roleDeployer, addr, nil, 0), 0) + if err != nil || r == nil { + return r, nil, err + } + var ret []byte + for _, lg := range r.Logs { + if lg.Ty != evmtypes.TyLogCallContract { + continue + } + var cr evmtypes.ReceiptEVMContract + if err := ctypes.Decode(lg.Log, &cr); err != nil { + t.Fatalf("decode receipt: %v", err) + } + ret = cr.Ret + } + return r, ret, nil +} + +// newTestExecutorFrom builds another executor over the same state/local DB, used +// to prove that state written by one transaction is visible to the next one. +func newTestExecutorFrom(t *testing.T, cfg *ctypes.Chain33Config, height int64, src *EVMExecutor) *EVMExecutor { + t.Helper() + api := new(apimock.QueueProtocolAPI) + api.On("GetConfig").Return(cfg) + + exec := NewEVMExecutor() + exec.SetAPI(api) + exec.SetLocalDB(src.GetLocalDB()) + exec.SetStateDB(src.GetStateDB()) + exec.SetEnv(height, 0, 0) + exec.CheckInit() + return exec +} + +// contractCreateV2ForkHeight is above the execution height (0) used by the +// tests below, so setting it keeps the fork disabled. +const contractCreateV2ForkHeight = 1000 + +func enableContractCreateV2(cfg *ctypes.Chain33Config) { + cfg.SetDappFork("evm", evmtypes.ForkEVMContractCreateV2, 0) +} + +func disableContractCreateV2(cfg *ctypes.Chain33Config) { + cfg.SetDappFork("evm", evmtypes.ForkEVMContractCreateV2, contractCreateV2ForkHeight) +} + +// resetEvmExecAddress refreshes the package-level exec address caches. They are +// computed once by Init, and other tests in this package switch the global EVM +// address driver (query_test.go), which leaves the caches stale and makes the +// executor treat a deploy as a plain transfer. +func resetEvmExecAddress(cfg *ctypes.Chain33Config) { + evmExecAddress = vcomm.StringToAddress(address.ExecAddress(cfg.ExecName(evmtypes.ExecutorName))).String() + evmExecFormatAddress = address.FormatEthAddress(evmExecAddress) +} + +// readContractNonce reads the persisted EVM nonce of a contract account. +func readContractNonce(t *testing.T, exec *EVMExecutor, addr string) uint64 { + t.Helper() + key := []byte("mavl-" + evmtypes.ExecutorName + "-state: " + addr) + raw, err := exec.GetStateDB().Get(key) + if err != nil { + return 0 + } + var st evmtypes.EVMContractState + if err := ctypes.Decode(raw, &st); err != nil { + t.Fatalf("decode contract state: %v", err) + } + return uint64(st.GetNonce()) +} + +// ethCreateAddress computes the ethereum CREATE address for a chain33-format +// contract address at the given nonce. +func ethCreateAddress(t *testing.T, chain33Addr string, nonce uint64) gethcommon.Address { + t.Helper() + raw := vcomm.StringToAddress(chain33Addr) + if raw == nil { + t.Fatalf("bad contract address %q", chain33Addr) + } + return ethcrypto.CreateAddress(gethcommon.BytesToAddress(raw.Bytes()), nonce) +} + +func TestInternalCreateAddressForkOff(t *testing.T) { + cfg := newTestConfig(t) + disableContractCreateV2(cfg) + exec := newTestExecutor(t, cfg, 0) + + factoryAddr := deployContract(t, cfg, exec, factoryCreateTwiceBytecode) + t.Logf("factory deployed at %s", factoryAddr) + + r, ret, err := callRet(t, cfg, exec, factoryAddr) + if err != nil { + t.Fatalf("call factory err: %v", err) + } + if r == nil || r.Ty != ctypes.ExecOk { + t.Fatalf("call factory bad receipt: %+v", r) + } + if len(ret) != 64 { + t.Fatalf("unexpected return length %d: %s", len(ret), vcomm.Bytes2Hex(ret)) + } + addr1 := vcomm.BytesToAddress(ret[:32]) + addr2 := vcomm.BytesToAddress(ret[32:]) + t.Logf("create #1 -> %s", addr1.String()) + t.Logf("create #2 -> %s", addr2.String()) + + // fork 关闭时保持旧行为:同一笔交易内两次 CREATE 得到同一个地址。 + if !bytes.Equal(addr1.Bytes(), addr2.Bytes()) { + t.Fatalf("fork off should keep the legacy behavior, got %s and %s", addr1.String(), addr2.String()) + } +} + +func TestInternalCreateAddressForkOn(t *testing.T) { + cfg := newTestConfig(t) + enableContractCreateV2(cfg) + exec := newTestExecutor(t, cfg, 0) + + factoryAddr := deployContract(t, cfg, exec, factoryCreateTwiceBytecode) + t.Logf("factory deployed at %s", factoryAddr) + + r, ret, err := callRet(t, cfg, exec, factoryAddr) + if err != nil { + t.Fatalf("call factory err: %v", err) + } + if r == nil || r.Ty != ctypes.ExecOk { + t.Fatalf("call factory bad receipt: %+v", r) + } + if len(ret) != 64 { + t.Fatalf("unexpected return length %d: %s", len(ret), vcomm.Bytes2Hex(ret)) + } + addr1 := vcomm.BytesToAddress(ret[:32]) + addr2 := vcomm.BytesToAddress(ret[32:]) + t.Logf("create #1 -> %s", addr1.String()) + t.Logf("create #2 -> %s", addr2.String()) + + if addr1 == addr2 { + t.Fatalf("BUG: both CREATEs in one tx returned the same address %s", addr1.String()) + } + want1 := ethCreateAddress(t, factoryAddr, 1) + want2 := ethCreateAddress(t, factoryAddr, 2) + if !bytes.Equal(addr1.Bytes(), want1.Bytes()) { + t.Fatalf("create #1 = %s, want %s", addr1.String(), gethcommon.BytesToAddress(want1.Bytes()).Hex()) + } + if !bytes.Equal(addr2.Bytes(), want2.Bytes()) { + t.Fatalf("create #2 = %s, want %s", addr2.String(), gethcommon.BytesToAddress(want2.Bytes()).Hex()) + } + t.Logf("create #1 matches CreateAddress(factory, 1) = %s", want1.Hex()) + t.Logf("create #2 matches CreateAddress(factory, 2) = %s", want2.Hex()) +} + +func TestCreate2CollisionForkOn(t *testing.T) { + cfg := newTestConfig(t) + enableContractCreateV2(cfg) + exec := newTestExecutor(t, cfg, 0) + addr := deployContract(t, cfg, exec, create2TwiceBytecode) + + r, ret, err := callRet(t, cfg, exec, addr) + if err != nil { + t.Fatalf("call: %v", err) + } + if r == nil || r.Ty != ctypes.ExecOk { + t.Fatalf("bad receipt: %+v", r) + } + if len(ret) != 64 { + t.Fatalf("unexpected return length %d", len(ret)) + } + a1 := vcomm.BytesToAddress(ret[:32]) + a2 := vcomm.BytesToAddress(ret[32:]) + t.Logf("create2 #1 -> %s", a1.String()) + t.Logf("create2 #2 -> %s", a2.String()) + if a1 == (vcomm.Address{}) { + t.Fatalf("first CREATE2 should succeed") + } + if a2 != (vcomm.Address{}) { + t.Fatalf("second CREATE2 to an occupied address returned %s instead of failing", a2.String()) + } +} + +func TestCreateNoncePersistsAcrossTransactions(t *testing.T) { + cfg := newTestConfig(t) + enableContractCreateV2(cfg) + exec := newTestExecutor(t, cfg, 0) + + factoryAddr := deployContract(t, cfg, exec, factoryCreateOnceBytecode) + t.Logf("factory deployed at %s", factoryAddr) + + callAndApply := func(e *EVMExecutor) vcomm.Address { + r, ret, err := callRet(t, cfg, e, factoryAddr) + if err != nil { + t.Fatalf("call factory err: %v", err) + } + if r == nil || r.Ty != ctypes.ExecOk { + t.Fatalf("call factory bad receipt: %+v", r) + } + if len(ret) != 32 { + t.Fatalf("unexpected return length %d", len(ret)) + } + applyReceiptKV(t, e, r) + return vcomm.BytesToAddress(ret) + } + + // Transaction #1: factory nonce goes 1 -> 2, the new contract is + // CreateAddress(factory, 1). + addr1 := callAndApply(exec) + want1 := ethCreateAddress(t, factoryAddr, 1) + if !bytes.Equal(addr1.Bytes(), want1.Bytes()) { + t.Fatalf("tx #1 address = %s, want %s", addr1.String(), want1.Hex()) + } + t.Logf("tx #1 -> %s (nonce 1)", addr1.String()) + + // The incremented nonce must be part of the receipt KV written to state. + var state evmtypes.EVMContractState + stateKey := []byte("mavl-" + evmtypes.ExecutorName + "-state: " + factoryAddr) + stateKV, err := exec.GetStateDB().Get(stateKey) + if err != nil { + t.Fatalf("read factory state: %v", err) + } + if err := ctypes.Decode(stateKV, &state); err != nil { + t.Fatalf("decode factory state: %v", err) + } + if state.GetNonce() != 2 { + t.Fatalf("factory nonce persisted = %d, want 2", state.GetNonce()) + } + t.Logf("factory nonce persisted to state: %d", state.GetNonce()) + + // Transaction #2 uses a fresh executor over the same DB: the address must + // come from the persisted nonce (2), not from the in-memory cache. + exec2 := newTestExecutorFrom(t, cfg, 0, exec) + addr2 := callAndApply(exec2) + want2 := ethCreateAddress(t, factoryAddr, 2) + if !bytes.Equal(addr2.Bytes(), want2.Bytes()) { + t.Fatalf("tx #2 address = %s, want %s", addr2.String(), want2.Hex()) + } + t.Logf("tx #2 -> %s (nonce 2)", addr2.String()) + + // Transaction #3 continues the sequence. + exec3 := newTestExecutorFrom(t, cfg, 0, exec2) + addr3 := callAndApply(exec3) + want3 := ethCreateAddress(t, factoryAddr, 3) + if !bytes.Equal(addr3.Bytes(), want3.Bytes()) { + t.Fatalf("tx #3 address = %s, want %s", addr3.String(), want3.Hex()) + } + t.Logf("tx #3 -> %s (nonce 3)", addr3.String()) +} + +// factory whose single CREATE always fails: the init code reverts. +// +// PUSH5 0x60006000fd; PUSH1 0; MSTORE +// PUSH1 5; PUSH1 27; PUSH1 0; CREATE; STOP +const factoryCreateRevertingChildRuntime = "6460006000fd" + "600052" + "6005601b6000f0" + "00" + +// deploy wrapper: CODECOPY runtime (17 bytes at offset 12) then RETURN it +const factoryCreateRevertingChildBytecode = "6011600c60003960116000f3" + factoryCreateRevertingChildRuntime + +// fork off: the address must stay the legacy hash(txHash||origin), and no nonce +// may be written to the contract state. +func TestInternalCreateAddressForkOffLegacy(t *testing.T) { + cfg := newTestConfig(t) + disableContractCreateV2(cfg) + exec := newTestExecutor(t, cfg, 0) + + factoryAddr := deployContract(t, cfg, exec, factoryCreateTwiceBytecode) + + tx := makeCallTx(cfg, roleDeployer, factoryAddr, nil, 0) + resetEvmExecAddress(cfg) + r, err := exec.Exec(tx, 0) + if err != nil || r == nil || r.Ty != ctypes.ExecOk { + t.Fatalf("call factory: err=%v ty=%d", err, r.GetTy()) + } + _, ret := receiptRet(t, r) + if len(ret) != 64 { + t.Fatalf("unexpected return length %d", len(ret)) + } + + legacy := vcomm.NewContractAddress(*vcomm.StringToAddress(tx.From()), tx.Hash()) + want := vcomm.LeftPadBytes(legacy.Bytes(), 32) + for i, got := range [][]byte{ret[:32], ret[32:]} { + if !bytes.Equal(got, want) { + t.Fatalf("create #%d = %x, want legacy %x", i+1, got, want) + } + } + if nonce := readContractNonce(t, exec, factoryAddr); nonce != 0 { + t.Fatalf("fork off wrote nonce %d to contract state", nonce) + } +} + +// fork on: a failed CREATE still consumes one nonce, like go-ethereum. +func TestCreateFailureStillIncrementsNonce(t *testing.T) { + cfg := newTestConfig(t) + enableContractCreateV2(cfg) + exec := newTestExecutor(t, cfg, 0) + + factoryAddr := deployContract(t, cfg, exec, factoryCreateRevertingChildBytecode) + if nonce := readContractNonce(t, exec, factoryAddr); nonce != 1 { + t.Fatalf("new contract nonce = %d, want 1 (EIP-161)", nonce) + } + + r, _, err := callRet(t, cfg, exec, factoryAddr) + if err != nil || r == nil || r.Ty != ctypes.ExecOk { + t.Fatalf("call factory: err=%v ty=%d", err, r.GetTy()) + } + applyReceiptKV(t, exec, r) + + if nonce := readContractNonce(t, exec, factoryAddr); nonce != 2 { + t.Fatalf("factory nonce after failed CREATE = %d, want 2", nonce) + } +} + +// receiptRet extracts the EVM return data from a receipt. +func receiptRet(t *testing.T, r *ctypes.Receipt) (*evmtypes.ReceiptEVMContract, []byte) { + t.Helper() + for _, lg := range r.Logs { + if lg.Ty != evmtypes.TyLogCallContract { + continue + } + var cr evmtypes.ReceiptEVMContract + if err := ctypes.Decode(lg.Log, &cr); err != nil { + t.Fatalf("decode receipt: %v", err) + } + return &cr, cr.Ret + } + return nil, nil +} diff --git a/plugin/dapp/evm/executor/query_test.go b/plugin/dapp/evm/executor/query_test.go index dd5ebb4e9..9926d414f 100644 --- a/plugin/dapp/evm/executor/query_test.go +++ b/plugin/dapp/evm/executor/query_test.go @@ -188,7 +188,11 @@ func initEvmExeccutor(t *testing.T, api *apimock.QueueProtocolAPI) *EVMExecutor driver, err := address.LoadDriver(2, -1) assert.Equal(t, nil, err) + // The EVM address driver is package-global: restore it so the switch does + // not leak into other tests (test order is not guaranteed). + prevDriver := vcomm.GetEvmAddressDriver() vcomm.InitEvmAddressDriver(driver) + t.Cleanup(func() { vcomm.InitEvmAddressDriver(prevDriver) }) var exec = NewEVMExecutor() exec.SetAPI(api) statDB, err := dbm.NewGoMemDB("state", "state", 1024) diff --git a/plugin/dapp/evm/executor/vm/common/address.go b/plugin/dapp/evm/executor/vm/common/address.go index 14d8d602f..f8d1cc55a 100644 --- a/plugin/dapp/evm/executor/vm/common/address.go +++ b/plugin/dapp/evm/executor/vm/common/address.go @@ -161,6 +161,14 @@ func NewEvmContractAddress(b Address, nonce uint64) Address { return a } +// NewEvmContractAddressRaw 通过nonce创建合约地址,raw 直接取以太坊地址的 20 字节, +// 不经过 chain33 地址驱动的 FormatAddr/FromString 往返转换。 +// btc 类地址驱动无法解析 0x 十六进制串,往返会得到全零 raw,内部 CREATE 必须用本方法。 +func NewEvmContractAddressRaw(b Address, nonce uint64) Address { + execAddr := ethcrypto.CreateAddress(common.BytesToAddress(b.Bytes()), nonce) + return BytesToAddress(execAddr.Bytes()) +} + // PubKey2Address pub key to address func PubKey2Address(pub []byte) Address { diff --git a/plugin/dapp/evm/executor/vm/runtime/evm.go b/plugin/dapp/evm/executor/vm/runtime/evm.go index cb916a6d7..cee3678cf 100644 --- a/plugin/dapp/evm/executor/vm/runtime/evm.go +++ b/plugin/dapp/evm/executor/vm/runtime/evm.go @@ -198,6 +198,12 @@ func (evm *EVM) CheckIsEthTx() bool { return evm.isEthTx } +// IsContractCreateV2 内部 CREATE/CREATE2 是否按以太坊语义执行(fork 门控) +func (evm *EVM) IsContractCreateV2() bool { + return evm.cfg != nil && evm.BlockNumber != nil && + evm.cfg.IsDappFork(evm.BlockNumber.Int64(), evmtypes.ExecutorName, evmtypes.ForkEVMContractCreateV2) +} + // 封装合约的各种调用逻辑中通用的预检查逻辑 func (evm *EVM) preCheck(caller ContractRef, value uint64) (pass bool, err error) { // 检查调用深度是否合法 @@ -537,6 +543,19 @@ func (evm *EVM) Create(caller ContractRef, contractAddr common.Address, code []b return nil, -1, gas, berr } + // 以太坊语义(fork 门控):先递增调用者 nonce,再检查目标地址是否已被占用。 + // nonce 递增必须在快照之前,这样创建失败时 nonce 仍然生效。 + if evm.IsContractCreateV2() { + callerAddr := caller.Address() + nonce := evm.StateDB.GetNonce(callerAddr.String()) + evm.StateDB.SetNonce(callerAddr.String(), nonce+1) + + if evm.StateDB.GetNonce(contractAddr.String()) != 0 || evm.StateDB.GetCodeSize(contractAddr.String()) > 0 { + log.Error("evm contract address collision", "caller", callerAddr.String(), "contractAddr", contractAddr.String()) + return nil, -1, 0, model.ErrContractAddressCollision + } + } + // 向合约地址转账 cfg := evm.StateDB.GetConfig() // From ForkEVMTransferRevert on, the snapshot is taken before the transfer so that a @@ -576,6 +595,10 @@ func (evm *EVM) Create(caller ContractRef, contractAddr common.Address, code []b snapshot = evm.StateDB.Snapshot() } evm.StateDB.CreateAccount(contractAddr.String(), contract.CallerAddress.String(), execName, alias) + if evm.IsContractCreateV2() { + // EIP-161:新建合约账户的 nonce 初始化为 1 + evm.StateDB.SetNonce(contractAddr.String(), 1) + } if EVMDebugOn == evm.VMConfig.Debug && evm.depth == 0 { evm.VMConfig.Tracer.CaptureStart(caller.Address(), contractAddr, true, code, gas, 0) @@ -598,7 +621,7 @@ func (evm *EVM) Create(caller ContractRef, contractAddr common.Address, code []b // 如果合约代码超大,或者出现除Gas不足外的其它错误情况 // 则回滚本次合约创建操作 - if maxCodeSizeExceeded || (err != nil && err != model.ErrCodeStoreOutOfGas) { + if maxCodeSizeExceeded || (err != nil && (err != model.ErrCodeStoreOutOfGas || evm.IsContractCreateV2())) { evm.StateDB.RevertToSnapshot(snapshot) // 如果之前步骤出错,且没有回滚过,则扣除Gas diff --git a/plugin/dapp/evm/executor/vm/runtime/instructions.go b/plugin/dapp/evm/executor/vm/runtime/instructions.go index e140cbff1..0cdda30cc 100644 --- a/plugin/dapp/evm/executor/vm/runtime/instructions.go +++ b/plugin/dapp/evm/executor/vm/runtime/instructions.go @@ -642,10 +642,21 @@ func opCreate(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { gas = callContext.contract.Gas ) + if evm.IsContractCreateV2() { + // EIP-150:CREATE 最多使用剩余 Gas 的 63/64 + gas = gas - gas/64 + } + callContext.contract.UseGas(gas) stackvalue := size addr := common.NewContractAddress(evm.Origin, evm.TxHash) + if evm.IsContractCreateV2() { + // 以太坊语义:地址由调用者地址与调用者 nonce 派生 + creator := callContext.contract.Address() + nonce := evm.StateDB.GetNonce(creator.String()) + addr = common.NewEvmContractAddressRaw(creator, nonce) + } if !value.IsZero() && evm.CheckIsEthTx() { // value 是coins的值,opcall 中默认是 1e18,框架默认coins 1e8 ,需要对value 处理成精度1e8的值 @@ -660,7 +671,8 @@ func opCreate(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { res, _, returnGas, suberr := evm.Create(callContext.contract, addr, input, gas, "innerContract", "", value.Uint64()) // 出错时压栈0,否则压栈创建出来的合约对象的地址 - if suberr != nil && suberr != model.ErrCodeStoreOutOfGas { + // fork 开启时 ErrCodeStoreOutOfGas 与其它错误一致,整体失败并压栈0 + if suberr != nil && (suberr != model.ErrCodeStoreOutOfGas || evm.IsContractCreateV2()) { log15.Error("evm contract opCreate instruction error,value", suberr, value) stackvalue.Clear() } else { @@ -688,7 +700,12 @@ func opCreate2(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { ) // Apply EIP150 - gas = gas / 2 + if evm.IsContractCreateV2() { + // EIP-150:CREATE2 最多使用剩余 Gas 的 63/64 + gas = gas - gas/64 + } else { + gas = gas / 2 + } callContext.contract.UseGas(gas) // reuse size int for stackvalue stackvalue := size @@ -697,6 +714,16 @@ func opCreate2(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { if !endowment.IsZero() { bigEndowment = endowment.ToBig() } + if evm.IsContractCreateV2() && !endowment.IsZero() && evm.CheckIsEthTx() { + // value 是coins的值,opcall 中默认是 1e18,框架默认coins 1e8 ,需要对value 处理成精度1e8的值 + newValue := evm.ethPrecision2Chain33Standard(endowment.ToBig()) + bigValue, overflow := uint256.FromBig(newValue) + if overflow { + panic("opCreate2: value wrong format") + } + endowment = *bigValue + bigEndowment = endowment.ToBig() + } //res, addr, returnGas, suberr := evm.Create2(callContext.contract, input, gas, // bigEndowment, &salt) @@ -713,13 +740,8 @@ func opCreate2(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { log15.Info("opCreate2", "callContext.contract.Address()", callContext.contract.Address(), "salt", saltStr, "suberr", suberr) // 出错时压栈0,否则压栈创建出来的合约对象的地址 - if suberr != nil && suberr != model.ErrCodeStoreOutOfGas { - log15.Error("evm contract opCreate instruction error,endowment,salt", suberr, bigEndowment, salt) - stackvalue.Clear() - } else { - stackvalue.SetBytes(newContractAddr.Bytes()) - } if suberr != nil { + log15.Error("evm contract opCreate instruction error,endowment,salt", suberr, bigEndowment, salt) stackvalue.Clear() } else { stackvalue.SetBytes(newContractAddr.Bytes()) diff --git a/plugin/dapp/evm/executor/vm/state/account.go b/plugin/dapp/evm/executor/vm/state/account.go index 5460d7bf1..da2bb34f3 100644 --- a/plugin/dapp/evm/executor/vm/state/account.go +++ b/plugin/dapp/evm/executor/vm/state/account.go @@ -292,7 +292,17 @@ func (ca *ContractAccount) HasSuicided() bool { // Empty 是否为空对象 func (ca *ContractAccount) Empty() bool { - return ca.Data.GetCodeHash() == nil || len(ca.Data.GetCodeHash()) == 0 + if ca.Data.GetCodeHash() != nil && len(ca.Data.GetCodeHash()) != 0 { + return false + } + // fork 开启后采用以太坊语义:有 nonce 的账户非空 + if ca.State.GetNonce() != 0 && ca.mdb != nil && ca.mdb.api != nil { + cfg := ca.mdb.api.GetConfig() + if cfg != nil && cfg.IsDappFork(ca.mdb.blockHeight, evmtypes.ExecutorName, evmtypes.ForkEVMContractCreateV2) { + return false + } + } + return true } // SetNonce 设置nonce值 diff --git a/plugin/dapp/evm/executor/vm/state/snapshot.go b/plugin/dapp/evm/executor/vm/state/snapshot.go index 8151837a4..c944c8e79 100644 --- a/plugin/dapp/evm/executor/vm/state/snapshot.go +++ b/plugin/dapp/evm/executor/vm/state/snapshot.go @@ -250,11 +250,16 @@ func (ch nonceChange) revert(mdb *MemoryStateDB) error { } func (ch nonceChange) getData(mdb *MemoryStateDB) []*types.KeyValue { - // nonce目前没有应用场景,而且每次调用都会变更,暂时先不写到状态数据库中 - //acc := mdb.accounts[ch.account] - //if acc != nil { - // return acc.GetStateKV() - //} + // nonce 只在 ForkEVMContractCreateV2 之后参与状态,必须与调用侧同样门控: + // 该变更会写入合约状态 KV,未门控时任何新增的 SetNonce 都会改变历史区块的哈希。 + if mdb.api == nil || mdb.api.GetConfig() == nil || + !mdb.api.GetConfig().IsDappFork(mdb.blockHeight, evmtypes.ExecutorName, evmtypes.ForkEVMContractCreateV2) { + return nil + } + acc := mdb.accounts[ch.account] + if acc != nil { + return acc.GetStateKV() + } return nil } diff --git a/plugin/dapp/evm/types/evm.go b/plugin/dapp/evm/types/evm.go index 8b43b653c..b6a5477de 100644 --- a/plugin/dapp/evm/types/evm.go +++ b/plugin/dapp/evm/types/evm.go @@ -55,6 +55,10 @@ func InitFork(cfg *types.Chain33Config) { // not configure the key, rewriting historical execution. A chain that wants the fix sets // a concrete height under [fork.sub.evm]; initForkConfig overrides this default. cfg.RegisterDappFork(ExecutorName, ForkEVMTransferRevert, types.MaxHeight) + // 内部CREATE/CREATE2采用以太坊地址派生(caller nonce)、nonce递增与地址碰撞检查。 + // 与 ForkEVMTransferRevert 同理:默认关闭(MaxHeight),需要该修复的链在 + // [fork.sub.evm] 里显式配置高度,避免对存量链追溯生效。 + cfg.RegisterDappFork(ExecutorName, ForkEVMContractCreateV2, types.MaxHeight) } // InitExecutor ... diff --git a/plugin/dapp/evm/types/types.go b/plugin/dapp/evm/types/types.go index d831621b8..53c864c37 100644 --- a/plugin/dapp/evm/types/types.go +++ b/plugin/dapp/evm/types/types.go @@ -66,6 +66,10 @@ const ( // cache while its receipt KV is dropped, so a later call in the same tx can spend the // phantom balance. Registered in InitFork at MaxHeight, so chains must opt in explicitly. ForkEVMTransferRevert = "ForkEVMTransferRevert" + // ForkEVMContractCreateV2 内部CREATE/CREATE2采用以太坊地址派生(caller nonce)、nonce递增与地址碰撞检查。 + // fork 前创建的合约没有 nonce 记录(视为0),其 fork 后的首次 CREATE 从 nonce 0 派生, + // 与以太坊(合约 nonce 从1开始)不完全一致;fork 后创建的合约派生的子合约地址与以太坊完全相同。 + ForkEVMContractCreateV2 = "ForkEVMContractCreateV2" ) var ( From 4a89f1cab9b666ebbbea39b592c3c521e093f562 Mon Sep 17 00:00:00 2001 From: bysomeone <11565373+bysomeone@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:36:29 +0800 Subject: [PATCH 2/9] test(evm): drop redundant uint64 conversion flagged by unconvert Co-authored-by: Claude --- plugin/dapp/evm/executor/create_compat_repro_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/dapp/evm/executor/create_compat_repro_test.go b/plugin/dapp/evm/executor/create_compat_repro_test.go index 3f756246f..ebaa76768 100644 --- a/plugin/dapp/evm/executor/create_compat_repro_test.go +++ b/plugin/dapp/evm/executor/create_compat_repro_test.go @@ -142,7 +142,7 @@ func readContractNonce(t *testing.T, exec *EVMExecutor, addr string) uint64 { if err := ctypes.Decode(raw, &st); err != nil { t.Fatalf("decode contract state: %v", err) } - return uint64(st.GetNonce()) + return st.GetNonce() } // ethCreateAddress computes the ethereum CREATE address for a chain33-format From 11a05813bcc6baa8e6f39b76492f66c98758eb01 Mon Sep 17 00:00:00 2001 From: bysomeone <11565373+bysomeone@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:48:08 +0800 Subject: [PATCH 3/9] fix(ci): assert the coins delta after the evm2 ticket withdraw withdrawTicketBalance compared the post-withdraw coins balance with the pre-withdraw ticket balance. The ticket balance also grows with mining rewards, so the check only held when it happened to be exactly 100000 and failed intermittently otherwise (observed 100005 vs 100001 on the same head). Record the coins balance before the withdraw and assert the increase is the withdrawn amount, allowing a small tolerance for fees and rounding. Co-authored-by: Claude --- plugin/dapp/evm/cmd/ci2/docker-compose.sh | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/plugin/dapp/evm/cmd/ci2/docker-compose.sh b/plugin/dapp/evm/cmd/ci2/docker-compose.sh index 471b24242..3b57096ed 100755 --- a/plugin/dapp/evm/cmd/ci2/docker-compose.sh +++ b/plugin/dapp/evm/cmd/ci2/docker-compose.sh @@ -394,6 +394,10 @@ function withdrawTicketBalance(){ local balance=$(echo "${result}" | jq -r ".balance") tbalance=$(printf "%.0f\n" $balance) echo "ticket balance:${tbalance},addr:${m4normalAddr},timestamp:$(date +"%s")" + # The ticket balance also grows with mining rewards, so it cannot be used as + # the expected coin balance after the withdraw. Compare the coins delta. + local coinsBefore=$(${CLI} account balance -a "${m4normalAddr}" -e coins | jq -r ".balance") + echo "coins balance before withdraw:${coinsBefore}" local withdrawTx=$( ${CLI} coins withdraw -e ticket -a 100000 -n "take test money") echo "withdraw rawTx:${withdrawTx}" @@ -409,14 +413,14 @@ function withdrawTicketBalance(){ fi echo "withdraw hash:${hash}" chain33_QueryTx ${hash} ${MCli} - #check coins balance - local result=$(${CLI} account balance -a "${m4normalAddr}" -e coins) - local balance=$(echo "${result}" | jq -r ".balance") - echo "coldminer addr coins balance:${balance}" - local checkBalance=$(printf "%.0f\n" $balance) - echo "checkBalance: $(("${checkBalance}")) " - if [ $((checkBalance)) -lt $((tbalance)) ]; then - exit 1 + #check coins balance: the withdraw moves exactly 100000 into the coins account, + #minus the transaction fee; allow a small tolerance for fees and rounding. + local coinsAfter=$(${CLI} account balance -a "${m4normalAddr}" -e coins | jq -r ".balance") + echo "coldminer addr coins balance after withdraw:${coinsAfter}" + if ! awk -v before="${coinsBefore}" -v after="${coinsAfter}" \ + 'BEGIN { exit !((after - before) >= 99999.9) }'; then + echo "withdraw balance check failed: before=${coinsBefore} after=${coinsAfter}" + exit 1 fi } From 6caa95d0749c7a3563747fa70c4553ffe3a1a119 Mon Sep 17 00:00:00 2001 From: bysomeone <11565373+bysomeone@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:16:02 +0800 Subject: [PATCH 4/9] fix(ci): widen the evm2 withdraw balance check boundary The withdraw moves 100000 coins minus a ~0.1 coin fee, so the expected increase is exactly 99999.9 and the previous 99999.9 lower bound sat on the floating-point boundary: the same balances can compare either side of it depending on their magnitude and on the awk implementation. Use a 99999 lower bound instead, and make jq fail on a missing balance rather than silently comparing a null as zero. Co-authored-by: Claude --- plugin/dapp/evm/cmd/ci2/docker-compose.sh | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/plugin/dapp/evm/cmd/ci2/docker-compose.sh b/plugin/dapp/evm/cmd/ci2/docker-compose.sh index 3b57096ed..95812eaa7 100755 --- a/plugin/dapp/evm/cmd/ci2/docker-compose.sh +++ b/plugin/dapp/evm/cmd/ci2/docker-compose.sh @@ -396,7 +396,7 @@ function withdrawTicketBalance(){ echo "ticket balance:${tbalance},addr:${m4normalAddr},timestamp:$(date +"%s")" # The ticket balance also grows with mining rewards, so it cannot be used as # the expected coin balance after the withdraw. Compare the coins delta. - local coinsBefore=$(${CLI} account balance -a "${m4normalAddr}" -e coins | jq -r ".balance") + local coinsBefore=$(${CLI} account balance -a "${m4normalAddr}" -e coins | jq -er ".balance") echo "coins balance before withdraw:${coinsBefore}" local withdrawTx=$( ${CLI} coins withdraw -e ticket -a 100000 -n "take test money") @@ -413,12 +413,13 @@ function withdrawTicketBalance(){ fi echo "withdraw hash:${hash}" chain33_QueryTx ${hash} ${MCli} - #check coins balance: the withdraw moves exactly 100000 into the coins account, - #minus the transaction fee; allow a small tolerance for fees and rounding. - local coinsAfter=$(${CLI} account balance -a "${m4normalAddr}" -e coins | jq -r ".balance") + #check coins balance: the withdraw moves 100000 into the coins account minus the + #transaction fee (~0.1), so require a lower bound with margin instead of an exact + #value: the boundary is sensitive to floating-point rounding of the balances. + local coinsAfter=$(${CLI} account balance -a "${m4normalAddr}" -e coins | jq -er ".balance") echo "coldminer addr coins balance after withdraw:${coinsAfter}" if ! awk -v before="${coinsBefore}" -v after="${coinsAfter}" \ - 'BEGIN { exit !((after - before) >= 99999.9) }'; then + 'BEGIN { exit !((after - before) >= 99999) }'; then echo "withdraw balance check failed: before=${coinsBefore} after=${coinsAfter}" exit 1 fi From 79a8405ff6b84006e4a14f1845738c8cfd017ade Mon Sep 17 00:00:00 2001 From: bysomeone <11565373+bysomeone@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:16:02 +0800 Subject: [PATCH 5/9] test(evm): cover the failed-create value rollback with transfer revert ForkEVMContractCreateV2 and ForkEVMTransferRevert are independent forks, but the full Ethereum semantics need both: this fork keeps the nonce of a failed CREATE, and the transfer-revert fork rolls back the value attached to it. Add a test that enables both, and document the pairing next to the fork. Co-authored-by: Claude --- .../evm/executor/create_compat_repro_test.go | 39 +++++++++++++++++++ plugin/dapp/evm/types/types.go | 2 + 2 files changed, 41 insertions(+) diff --git a/plugin/dapp/evm/executor/create_compat_repro_test.go b/plugin/dapp/evm/executor/create_compat_repro_test.go index ebaa76768..703f35a17 100644 --- a/plugin/dapp/evm/executor/create_compat_repro_test.go +++ b/plugin/dapp/evm/executor/create_compat_repro_test.go @@ -381,6 +381,45 @@ func TestCreateFailureStillIncrementsNonce(t *testing.T) { } } +// factory that CREATEs one child with value 1 whose init code reverts. +// +// PUSH5 0x60006000fd; PUSH1 0; MSTORE +// PUSH1 5; PUSH1 27; PUSH1 1; CREATE; STOP +const factoryCreateWithValueRuntime = "6460006000fd" + "600052" + "6005601b6001f0" + "00" + +// deploy wrapper: CODECOPY runtime (17 bytes at offset 12) then RETURN it +const factoryCreateWithValueBytecode = "6011600c60003960116000f3" + factoryCreateWithValueRuntime + +// A failed CREATE consumes a nonce; with ForkEVMTransferRevert enabled the value +// attached to the CREATE is rolled back as well. +func TestFailedCreateRollsBackValueWithTransferRevert(t *testing.T) { + cfg := newTestConfig(t) + enableContractCreateV2(cfg) + cfg.SetDappFork("evm", evmtypes.ForkEVMTransferRevert, 0) + exec := newTestExecutor(t, cfg, 0) + + factoryAddr := deployContract(t, cfg, exec, factoryCreateWithValueBytecode) + fundAddr(t, exec, factoryAddr, 1000) + before := exec.mStateDB.GetBalance(factoryAddr) + + r, _, err := callRet(t, cfg, exec, factoryAddr) + if err != nil || r == nil || r.Ty != ctypes.ExecOk { + t.Fatalf("call factory: err=%v ty=%d", err, r.GetTy()) + } + applyReceiptKV(t, exec, r) + + if after := exec.mStateDB.GetBalance(factoryAddr); after != before { + t.Fatalf("factory balance %d -> %d, value was not rolled back", before, after) + } + if nonce := readContractNonce(t, exec, factoryAddr); nonce != 2 { + t.Fatalf("factory nonce after failed CREATE = %d, want 2", nonce) + } + child := ethCreateAddress(t, factoryAddr, 1) + if bal := exec.mStateDB.GetBalance(vcomm.BytesToAddress(child.Bytes()).String()); bal != 0 { + t.Fatalf("failed create address holds %d coins", bal) + } +} + // receiptRet extracts the EVM return data from a receipt. func receiptRet(t *testing.T, r *ctypes.Receipt) (*evmtypes.ReceiptEVMContract, []byte) { t.Helper() diff --git a/plugin/dapp/evm/types/types.go b/plugin/dapp/evm/types/types.go index 53c864c37..c2f12a609 100644 --- a/plugin/dapp/evm/types/types.go +++ b/plugin/dapp/evm/types/types.go @@ -69,6 +69,8 @@ const ( // ForkEVMContractCreateV2 内部CREATE/CREATE2采用以太坊地址派生(caller nonce)、nonce递增与地址碰撞检查。 // fork 前创建的合约没有 nonce 记录(视为0),其 fork 后的首次 CREATE 从 nonce 0 派生, // 与以太坊(合约 nonce 从1开始)不完全一致;fork 后创建的合约派生的子合约地址与以太坊完全相同。 + // 与 ForkEVMTransferRevert 同高开启才是完整的以太坊语义:只开本 fork 时, + // 创建失败会保留已递增的 nonce,但不会回滚随 CREATE 转账的 value。 ForkEVMContractCreateV2 = "ForkEVMContractCreateV2" ) From 4702c96780ae486fe3feeb9c91d63d5b9d988d11 Mon Sep 17 00:00:00 2001 From: bysomeone <11565373+bysomeone@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:08:16 +0800 Subject: [PATCH 6/9] refactor(evm): rename the compatibility fork to ForkEVMCompat The fork now covers the whole Ethereum compatibility set (CREATE semantics, new opcodes and the gas schedule), so a semantic name without a version suffix is clearer: there is no "V1" fork to pair with. Co-authored-by: Claude --- chain33.fork.toml | 4 +-- chain33.para.toml | 4 +-- .../dapp/evm/cmd/ci2/chain33.proxyminer.toml | 4 +-- .../evm/executor/create_compat_repro_test.go | 26 +++++++++---------- plugin/dapp/evm/executor/vm/runtime/evm.go | 12 ++++----- .../evm/executor/vm/runtime/instructions.go | 10 +++---- plugin/dapp/evm/executor/vm/state/account.go | 2 +- plugin/dapp/evm/executor/vm/state/snapshot.go | 4 +-- plugin/dapp/evm/types/evm.go | 2 +- plugin/dapp/evm/types/types.go | 18 ++++++++----- 10 files changed, 46 insertions(+), 40 deletions(-) diff --git a/chain33.fork.toml b/chain33.fork.toml index bada5286b..335be59ca 100644 --- a/chain33.fork.toml +++ b/chain33.fork.toml @@ -103,8 +103,8 @@ ForkEVMFixOverflow=0 ForkEVMSuicidePayer=0 # Revertible value transfers; -1 keeps the fix off (resolved to MaxHeight) ForkEVMTransferRevert=-1 -# Internal CREATE/CREATE2 follow Ethereum address derivation; -1 keeps it off -ForkEVMContractCreateV2=-1 +# Ethereum EVM compatibility set (opcodes/gas/CREATE); -1 keeps it off +ForkEVMCompat=-1 [fork.sub.evmxgo] diff --git a/chain33.para.toml b/chain33.para.toml index bf9aaa08a..8d1756599 100644 --- a/chain33.para.toml +++ b/chain33.para.toml @@ -439,8 +439,8 @@ ForkEVMFixOverflow=0 ForkEVMSuicidePayer=0 # Revertible value transfers; -1 keeps the fix off (resolved to MaxHeight) ForkEVMTransferRevert=-1 -# Internal CREATE/CREATE2 follow Ethereum address derivation; -1 keeps it off -ForkEVMContractCreateV2=-1 +# Ethereum EVM compatibility set (opcodes/gas/CREATE); -1 keeps it off +ForkEVMCompat=-1 [fork.sub.blackwhite] Enable=0 diff --git a/plugin/dapp/evm/cmd/ci2/chain33.proxyminer.toml b/plugin/dapp/evm/cmd/ci2/chain33.proxyminer.toml index 31124fc31..0a7fc6be4 100644 --- a/plugin/dapp/evm/cmd/ci2/chain33.proxyminer.toml +++ b/plugin/dapp/evm/cmd/ci2/chain33.proxyminer.toml @@ -607,8 +607,8 @@ ForkEVMFixOverflow=0 ForkEVMSuicidePayer=0 # Revertible value transfers; -1 keeps the fix off (resolved to MaxHeight) ForkEVMTransferRevert=-1 -# Internal CREATE/CREATE2 follow Ethereum address derivation; -1 keeps it off -ForkEVMContractCreateV2=-1 +# Ethereum EVM compatibility set (opcodes/gas/CREATE); -1 keeps it off +ForkEVMCompat=-1 [fork.sub.evmxgo] Enable=0 diff --git a/plugin/dapp/evm/executor/create_compat_repro_test.go b/plugin/dapp/evm/executor/create_compat_repro_test.go index 703f35a17..fd068b01b 100644 --- a/plugin/dapp/evm/executor/create_compat_repro_test.go +++ b/plugin/dapp/evm/executor/create_compat_repro_test.go @@ -109,16 +109,16 @@ func newTestExecutorFrom(t *testing.T, cfg *ctypes.Chain33Config, height int64, return exec } -// contractCreateV2ForkHeight is above the execution height (0) used by the +// evmCompatForkHeight is above the execution height (0) used by the // tests below, so setting it keeps the fork disabled. -const contractCreateV2ForkHeight = 1000 +const evmCompatForkHeight = 1000 -func enableContractCreateV2(cfg *ctypes.Chain33Config) { - cfg.SetDappFork("evm", evmtypes.ForkEVMContractCreateV2, 0) +func enableEVMCompat(cfg *ctypes.Chain33Config) { + cfg.SetDappFork("evm", evmtypes.ForkEVMCompat, 0) } -func disableContractCreateV2(cfg *ctypes.Chain33Config) { - cfg.SetDappFork("evm", evmtypes.ForkEVMContractCreateV2, contractCreateV2ForkHeight) +func disableEVMCompat(cfg *ctypes.Chain33Config) { + cfg.SetDappFork("evm", evmtypes.ForkEVMCompat, evmCompatForkHeight) } // resetEvmExecAddress refreshes the package-level exec address caches. They are @@ -158,7 +158,7 @@ func ethCreateAddress(t *testing.T, chain33Addr string, nonce uint64) gethcommon func TestInternalCreateAddressForkOff(t *testing.T) { cfg := newTestConfig(t) - disableContractCreateV2(cfg) + disableEVMCompat(cfg) exec := newTestExecutor(t, cfg, 0) factoryAddr := deployContract(t, cfg, exec, factoryCreateTwiceBytecode) @@ -187,7 +187,7 @@ func TestInternalCreateAddressForkOff(t *testing.T) { func TestInternalCreateAddressForkOn(t *testing.T) { cfg := newTestConfig(t) - enableContractCreateV2(cfg) + enableEVMCompat(cfg) exec := newTestExecutor(t, cfg, 0) factoryAddr := deployContract(t, cfg, exec, factoryCreateTwiceBytecode) @@ -225,7 +225,7 @@ func TestInternalCreateAddressForkOn(t *testing.T) { func TestCreate2CollisionForkOn(t *testing.T) { cfg := newTestConfig(t) - enableContractCreateV2(cfg) + enableEVMCompat(cfg) exec := newTestExecutor(t, cfg, 0) addr := deployContract(t, cfg, exec, create2TwiceBytecode) @@ -253,7 +253,7 @@ func TestCreate2CollisionForkOn(t *testing.T) { func TestCreateNoncePersistsAcrossTransactions(t *testing.T) { cfg := newTestConfig(t) - enableContractCreateV2(cfg) + enableEVMCompat(cfg) exec := newTestExecutor(t, cfg, 0) factoryAddr := deployContract(t, cfg, exec, factoryCreateOnceBytecode) @@ -331,7 +331,7 @@ const factoryCreateRevertingChildBytecode = "6011600c60003960116000f3" + factory // may be written to the contract state. func TestInternalCreateAddressForkOffLegacy(t *testing.T) { cfg := newTestConfig(t) - disableContractCreateV2(cfg) + disableEVMCompat(cfg) exec := newTestExecutor(t, cfg, 0) factoryAddr := deployContract(t, cfg, exec, factoryCreateTwiceBytecode) @@ -362,7 +362,7 @@ func TestInternalCreateAddressForkOffLegacy(t *testing.T) { // fork on: a failed CREATE still consumes one nonce, like go-ethereum. func TestCreateFailureStillIncrementsNonce(t *testing.T) { cfg := newTestConfig(t) - enableContractCreateV2(cfg) + enableEVMCompat(cfg) exec := newTestExecutor(t, cfg, 0) factoryAddr := deployContract(t, cfg, exec, factoryCreateRevertingChildBytecode) @@ -394,7 +394,7 @@ const factoryCreateWithValueBytecode = "6011600c60003960116000f3" + factoryCreat // attached to the CREATE is rolled back as well. func TestFailedCreateRollsBackValueWithTransferRevert(t *testing.T) { cfg := newTestConfig(t) - enableContractCreateV2(cfg) + enableEVMCompat(cfg) cfg.SetDappFork("evm", evmtypes.ForkEVMTransferRevert, 0) exec := newTestExecutor(t, cfg, 0) diff --git a/plugin/dapp/evm/executor/vm/runtime/evm.go b/plugin/dapp/evm/executor/vm/runtime/evm.go index cee3678cf..e5088db56 100644 --- a/plugin/dapp/evm/executor/vm/runtime/evm.go +++ b/plugin/dapp/evm/executor/vm/runtime/evm.go @@ -198,10 +198,10 @@ func (evm *EVM) CheckIsEthTx() bool { return evm.isEthTx } -// IsContractCreateV2 内部 CREATE/CREATE2 是否按以太坊语义执行(fork 门控) -func (evm *EVM) IsContractCreateV2() bool { +// IsEVMCompat 以太坊 EVM 兼容性(指令/计价/CREATE)是否开启(fork 门控) +func (evm *EVM) IsEVMCompat() bool { return evm.cfg != nil && evm.BlockNumber != nil && - evm.cfg.IsDappFork(evm.BlockNumber.Int64(), evmtypes.ExecutorName, evmtypes.ForkEVMContractCreateV2) + evm.cfg.IsDappFork(evm.BlockNumber.Int64(), evmtypes.ExecutorName, evmtypes.ForkEVMCompat) } // 封装合约的各种调用逻辑中通用的预检查逻辑 @@ -545,7 +545,7 @@ func (evm *EVM) Create(caller ContractRef, contractAddr common.Address, code []b // 以太坊语义(fork 门控):先递增调用者 nonce,再检查目标地址是否已被占用。 // nonce 递增必须在快照之前,这样创建失败时 nonce 仍然生效。 - if evm.IsContractCreateV2() { + if evm.IsEVMCompat() { callerAddr := caller.Address() nonce := evm.StateDB.GetNonce(callerAddr.String()) evm.StateDB.SetNonce(callerAddr.String(), nonce+1) @@ -595,7 +595,7 @@ func (evm *EVM) Create(caller ContractRef, contractAddr common.Address, code []b snapshot = evm.StateDB.Snapshot() } evm.StateDB.CreateAccount(contractAddr.String(), contract.CallerAddress.String(), execName, alias) - if evm.IsContractCreateV2() { + if evm.IsEVMCompat() { // EIP-161:新建合约账户的 nonce 初始化为 1 evm.StateDB.SetNonce(contractAddr.String(), 1) } @@ -621,7 +621,7 @@ func (evm *EVM) Create(caller ContractRef, contractAddr common.Address, code []b // 如果合约代码超大,或者出现除Gas不足外的其它错误情况 // 则回滚本次合约创建操作 - if maxCodeSizeExceeded || (err != nil && (err != model.ErrCodeStoreOutOfGas || evm.IsContractCreateV2())) { + if maxCodeSizeExceeded || (err != nil && (err != model.ErrCodeStoreOutOfGas || evm.IsEVMCompat())) { evm.StateDB.RevertToSnapshot(snapshot) // 如果之前步骤出错,且没有回滚过,则扣除Gas diff --git a/plugin/dapp/evm/executor/vm/runtime/instructions.go b/plugin/dapp/evm/executor/vm/runtime/instructions.go index 0cdda30cc..f716ae81f 100644 --- a/plugin/dapp/evm/executor/vm/runtime/instructions.go +++ b/plugin/dapp/evm/executor/vm/runtime/instructions.go @@ -642,7 +642,7 @@ func opCreate(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { gas = callContext.contract.Gas ) - if evm.IsContractCreateV2() { + if evm.IsEVMCompat() { // EIP-150:CREATE 最多使用剩余 Gas 的 63/64 gas = gas - gas/64 } @@ -651,7 +651,7 @@ func opCreate(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { stackvalue := size addr := common.NewContractAddress(evm.Origin, evm.TxHash) - if evm.IsContractCreateV2() { + if evm.IsEVMCompat() { // 以太坊语义:地址由调用者地址与调用者 nonce 派生 creator := callContext.contract.Address() nonce := evm.StateDB.GetNonce(creator.String()) @@ -672,7 +672,7 @@ func opCreate(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { // 出错时压栈0,否则压栈创建出来的合约对象的地址 // fork 开启时 ErrCodeStoreOutOfGas 与其它错误一致,整体失败并压栈0 - if suberr != nil && (suberr != model.ErrCodeStoreOutOfGas || evm.IsContractCreateV2()) { + if suberr != nil && (suberr != model.ErrCodeStoreOutOfGas || evm.IsEVMCompat()) { log15.Error("evm contract opCreate instruction error,value", suberr, value) stackvalue.Clear() } else { @@ -700,7 +700,7 @@ func opCreate2(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { ) // Apply EIP150 - if evm.IsContractCreateV2() { + if evm.IsEVMCompat() { // EIP-150:CREATE2 最多使用剩余 Gas 的 63/64 gas = gas - gas/64 } else { @@ -714,7 +714,7 @@ func opCreate2(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { if !endowment.IsZero() { bigEndowment = endowment.ToBig() } - if evm.IsContractCreateV2() && !endowment.IsZero() && evm.CheckIsEthTx() { + if evm.IsEVMCompat() && !endowment.IsZero() && evm.CheckIsEthTx() { // value 是coins的值,opcall 中默认是 1e18,框架默认coins 1e8 ,需要对value 处理成精度1e8的值 newValue := evm.ethPrecision2Chain33Standard(endowment.ToBig()) bigValue, overflow := uint256.FromBig(newValue) diff --git a/plugin/dapp/evm/executor/vm/state/account.go b/plugin/dapp/evm/executor/vm/state/account.go index da2bb34f3..2bd32b203 100644 --- a/plugin/dapp/evm/executor/vm/state/account.go +++ b/plugin/dapp/evm/executor/vm/state/account.go @@ -298,7 +298,7 @@ func (ca *ContractAccount) Empty() bool { // fork 开启后采用以太坊语义:有 nonce 的账户非空 if ca.State.GetNonce() != 0 && ca.mdb != nil && ca.mdb.api != nil { cfg := ca.mdb.api.GetConfig() - if cfg != nil && cfg.IsDappFork(ca.mdb.blockHeight, evmtypes.ExecutorName, evmtypes.ForkEVMContractCreateV2) { + if cfg != nil && cfg.IsDappFork(ca.mdb.blockHeight, evmtypes.ExecutorName, evmtypes.ForkEVMCompat) { return false } } diff --git a/plugin/dapp/evm/executor/vm/state/snapshot.go b/plugin/dapp/evm/executor/vm/state/snapshot.go index c944c8e79..972bca739 100644 --- a/plugin/dapp/evm/executor/vm/state/snapshot.go +++ b/plugin/dapp/evm/executor/vm/state/snapshot.go @@ -250,10 +250,10 @@ func (ch nonceChange) revert(mdb *MemoryStateDB) error { } func (ch nonceChange) getData(mdb *MemoryStateDB) []*types.KeyValue { - // nonce 只在 ForkEVMContractCreateV2 之后参与状态,必须与调用侧同样门控: + // nonce 只在 ForkEVMCompat 之后参与状态,必须与调用侧同样门控: // 该变更会写入合约状态 KV,未门控时任何新增的 SetNonce 都会改变历史区块的哈希。 if mdb.api == nil || mdb.api.GetConfig() == nil || - !mdb.api.GetConfig().IsDappFork(mdb.blockHeight, evmtypes.ExecutorName, evmtypes.ForkEVMContractCreateV2) { + !mdb.api.GetConfig().IsDappFork(mdb.blockHeight, evmtypes.ExecutorName, evmtypes.ForkEVMCompat) { return nil } acc := mdb.accounts[ch.account] diff --git a/plugin/dapp/evm/types/evm.go b/plugin/dapp/evm/types/evm.go index b6a5477de..783ffd20a 100644 --- a/plugin/dapp/evm/types/evm.go +++ b/plugin/dapp/evm/types/evm.go @@ -58,7 +58,7 @@ func InitFork(cfg *types.Chain33Config) { // 内部CREATE/CREATE2采用以太坊地址派生(caller nonce)、nonce递增与地址碰撞检查。 // 与 ForkEVMTransferRevert 同理:默认关闭(MaxHeight),需要该修复的链在 // [fork.sub.evm] 里显式配置高度,避免对存量链追溯生效。 - cfg.RegisterDappFork(ExecutorName, ForkEVMContractCreateV2, types.MaxHeight) + cfg.RegisterDappFork(ExecutorName, ForkEVMCompat, types.MaxHeight) } // InitExecutor ... diff --git a/plugin/dapp/evm/types/types.go b/plugin/dapp/evm/types/types.go index c2f12a609..092ff471e 100644 --- a/plugin/dapp/evm/types/types.go +++ b/plugin/dapp/evm/types/types.go @@ -66,12 +66,18 @@ const ( // cache while its receipt KV is dropped, so a later call in the same tx can spend the // phantom balance. Registered in InitFork at MaxHeight, so chains must opt in explicitly. ForkEVMTransferRevert = "ForkEVMTransferRevert" - // ForkEVMContractCreateV2 内部CREATE/CREATE2采用以太坊地址派生(caller nonce)、nonce递增与地址碰撞检查。 - // fork 前创建的合约没有 nonce 记录(视为0),其 fork 后的首次 CREATE 从 nonce 0 派生, - // 与以太坊(合约 nonce 从1开始)不完全一致;fork 后创建的合约派生的子合约地址与以太坊完全相同。 - // 与 ForkEVMTransferRevert 同高开启才是完整的以太坊语义:只开本 fork 时, - // 创建失败会保留已递增的 nonce,但不会回滚随 CREATE 转账的 value。 - ForkEVMContractCreateV2 = "ForkEVMContractCreateV2" + // ForkEVMCompat aligns the interpreter with Ethereum behind a single activation height: + // - internal CREATE/CREATE2: address from the executing account and its nonce, nonce + // increment persisted, address collision check, EIP-150 63/64 gas; + // - opcodes PUSH0, BASEFEE, MCOPY, TLOAD/TSTORE; + // - gas: EIP-2200/2929/3529 (net SSTORE metering, cold/warm access, refund cap) and + // refunds actually applied to the used gas. + // Contracts created before the fork have no nonce record (treated as 0), so their first + // post-fork internal CREATE does not match Ethereum exactly; contracts created after the + // fork match exactly. + // Enable it at the same height as ForkEVMTransferRevert: the latter rolls back the value + // attached to a failed CREATE, which this fork alone does not do. + ForkEVMCompat = "ForkEVMCompat" ) var ( From 19e346b789bfe4fa12b2eb1ebfb97d618dbe226b Mon Sep 17 00:00:00 2001 From: bysomeone <11565373+bysomeone@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:35:48 +0800 Subject: [PATCH 7/9] feat(evm): add PUSH0 and BASEFEE behind ForkEVMCompat Solidity 0.8.20 and later emit PUSH0 by default, so a contract built with a current solc cannot be deployed without it. The fork selects a Berlin-based instruction set that adds PUSH0 (0x5f) and BASEFEE (0x48); the chain has no base-fee mechanism, so BASEFEE pushes zero. Both cost 2 gas. Fork off keeps the existing instruction set, so the two bytes remain invalid and nothing else changes. Co-Authored-By: Claude Code --- .../opcodes_compat_integration_test.go | 114 ++++++++++++++++++ .../evm/executor/vm/runtime/instructions.go | 12 ++ .../evm/executor/vm/runtime/interpreter.go | 3 + .../evm/executor/vm/runtime/jump_table.go | 22 ++++ .../dapp/evm/executor/vm/runtime/opcodes.go | 9 ++ plugin/dapp/evm/types/types.go | 4 +- 6 files changed, 161 insertions(+), 3 deletions(-) create mode 100644 plugin/dapp/evm/executor/opcodes_compat_integration_test.go diff --git a/plugin/dapp/evm/executor/opcodes_compat_integration_test.go b/plugin/dapp/evm/executor/opcodes_compat_integration_test.go new file mode 100644 index 000000000..27f0d91f8 --- /dev/null +++ b/plugin/dapp/evm/executor/opcodes_compat_integration_test.go @@ -0,0 +1,114 @@ +// Copyright Fuzamei Corp. 2018 All Rights Reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package executor + +// Fork-gated coverage for the opcodes enabled by ForkEVMCompat: PUSH0 (EIP-3855) and +// BASEFEE (EIP-3198). + +import ( + "encoding/binary" + "testing" + + ctypes "github.com/33cn/chain33/types" + evmtypes "github.com/33cn/plugin/plugin/dapp/evm/types" + "github.com/stretchr/testify/require" +) + +// Runtime bytecode for the enabled-fork cases. Each program stores its result at memory +// offset 0 and returns one 32-byte word. + +// PUSH0; ISZERO; MSTORE(0, 1); RETURN(0, 32) +var push0Code = []byte{ + 0x5f, // PUSH0 + 0x15, // ISZERO -> 1 + 0x60, 0x00, // PUSH1 0 (memory offset) + 0x52, // MSTORE + 0x60, 0x20, // PUSH1 32 (return size) + 0x60, 0x00, // PUSH1 0 (return offset) + 0xf3, // RETURN +} + +// BASEFEE; ISZERO; MSTORE(0, 1); RETURN(0, 32) +var baseFeeCode = []byte{ + 0x48, // BASEFEE + 0x15, // ISZERO -> 1 + 0x60, 0x00, // PUSH1 0 + 0x52, // MSTORE + 0x60, 0x20, // PUSH1 32 + 0x60, 0x00, // PUSH1 0 + 0xf3, // RETURN +} + +func callReturnData(t *testing.T, receipt *ctypes.Receipt) []byte { + t.Helper() + for _, log := range receipt.GetLogs() { + if log.GetTy() != evmtypes.TyLogCallContract { + continue + } + var contract evmtypes.ReceiptEVMContract + require.NoError(t, ctypes.Decode(log.GetLog(), &contract)) + return contract.Ret + } + t.Fatal("receipt has no TyLogCallContract log") + return nil +} + +func callContract(t *testing.T, cfg *ctypes.Chain33Config, exec *EVMExecutor, contractAddr string, input []byte) *ctypes.Receipt { + t.Helper() + receipt, err := exec.Exec(makeCallTx(cfg, roleLegitUser, contractAddr, input, 0), 0) + require.NoError(t, err) + require.Equal(t, int32(ctypes.ExecOk), receipt.GetTy()) + applyReceiptKV(t, exec, receipt) + return receipt +} + +func uint64Word(v uint64) []byte { + word := make([]byte, 32) + binary.BigEndian.PutUint64(word[24:], v) + return word +} + +func TestEVMCompatOpcodesDisabled(t *testing.T) { + restoreBtcAddressDriver(t) + cfg := newTestConfig(t) + disableEVMCompat(cfg) + exec := newTestExecutor(t, cfg, 0) + + // The new bytes must stay invalid opcodes when the fork is off. Only the byte that is + // actually executed matters, so a single unknown opcode followed by STOP is enough. + for _, tc := range []struct { + name string + op byte + }{ + {"PUSH0", 0x5f}, + {"BASEFEE", 0x48}, + } { + t.Run(tc.name, func(t *testing.T) { + contractAddr := deployCode(t, cfg, exec, []byte{tc.op, 0x00}) + _, err := exec.Exec(makeCallTx(cfg, roleLegitUser, contractAddr, nil, 0), 0) + require.Error(t, err) + require.Contains(t, err.Error(), "invalid opcode") + }) + } +} + +func TestEVMCompatOpcodesEnabled(t *testing.T) { + restoreBtcAddressDriver(t) + cfg := newTestConfig(t) + enableEVMCompat(cfg) + exec := newTestExecutor(t, cfg, 0) + + t.Run("PUSH0", func(t *testing.T) { + contractAddr := deployCode(t, cfg, exec, push0Code) + ret := callReturnData(t, callContract(t, cfg, exec, contractAddr, nil)) + require.Equal(t, uint64Word(1), ret, "PUSH0 must push zero, so ISZERO yields one") + }) + + t.Run("BASEFEE", func(t *testing.T) { + contractAddr := deployCode(t, cfg, exec, baseFeeCode) + ret := callReturnData(t, callContract(t, cfg, exec, contractAddr, nil)) + require.Equal(t, uint64Word(1), ret, "BASEFEE returns zero because chain33 has no base fee") + }) +} diff --git a/plugin/dapp/evm/executor/vm/runtime/instructions.go b/plugin/dapp/evm/executor/vm/runtime/instructions.go index f716ae81f..fb0fc9bb7 100644 --- a/plugin/dapp/evm/executor/vm/runtime/instructions.go +++ b/plugin/dapp/evm/executor/vm/runtime/instructions.go @@ -532,6 +532,18 @@ func opMstore8(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { return nil, nil } +// PUSH0 指令,将零压入栈(EIP-3855) +func opPush0(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { + callContext.stack.push(new(uint256.Int)) + return nil, nil +} + +// BASEFEE 指令,chain33 没有 base fee 机制,固定返回 0 +func opBaseFee(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { + callContext.stack.push(new(uint256.Int)) + return nil, nil +} + // 加载合约状态数据 func opSload(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { loc := callContext.stack.peek() diff --git a/plugin/dapp/evm/executor/vm/runtime/interpreter.go b/plugin/dapp/evm/executor/vm/runtime/interpreter.go index 5c6963e0a..3b284676d 100644 --- a/plugin/dapp/evm/executor/vm/runtime/interpreter.go +++ b/plugin/dapp/evm/executor/vm/runtime/interpreter.go @@ -56,6 +56,9 @@ func NewInterpreter(evm *EVM, cfg Config) *Interpreter { //这里需要替换为最新得指令集 cfg.JumpTable = berlinInstructionSet } + if evm.IsEVMCompat() { + cfg.JumpTable = evmCompatInstructionSet + } } return &Interpreter{ diff --git a/plugin/dapp/evm/executor/vm/runtime/jump_table.go b/plugin/dapp/evm/executor/vm/runtime/jump_table.go index 0fb7c0a8e..ce5fe795c 100644 --- a/plugin/dapp/evm/executor/vm/runtime/jump_table.go +++ b/plugin/dapp/evm/executor/vm/runtime/jump_table.go @@ -52,11 +52,33 @@ var ( constantinopleInstructionSet = newConstantinopleInstructionSet() istanbulInstructionSet = newIstanbulInstructionSet() berlinInstructionSet = newBerlinInstructionSet() + evmCompatInstructionSet = newEVMCompatInstructionSet() ) // JumpTable contains the EVM opcodes supported at a given fork. type JumpTable [256]*operation +// newEVMCompatInstructionSet returns the Berlin set extended with the opcodes enabled by +// ForkEVMCompat: PUSH0 (EIP-3855) and BASEFEE (EIP-3198). +func newEVMCompatInstructionSet() JumpTable { + instructionSet := newBerlinInstructionSet() + + instructionSet[PUSH0] = &operation{ + execute: opPush0, + constantGas: GasQuickStep, + minStack: minStack(0, 1), + maxStack: maxStack(0, 1), + } + instructionSet[BASEFEE] = &operation{ + execute: opBaseFee, + constantGas: GasQuickStep, + minStack: minStack(0, 1), + maxStack: maxStack(0, 1), + } + + return instructionSet +} + // newBerlinInstructionSet returns the frontier, homestead, byzantium, // contantinople, istanbul, petersburg and berlin instructions. func newBerlinInstructionSet() JumpTable { diff --git a/plugin/dapp/evm/executor/vm/runtime/opcodes.go b/plugin/dapp/evm/executor/vm/runtime/opcodes.go index fd6377e78..29fcf410d 100644 --- a/plugin/dapp/evm/executor/vm/runtime/opcodes.go +++ b/plugin/dapp/evm/executor/vm/runtime/opcodes.go @@ -92,6 +92,7 @@ func initMap() { GASLIMIT: "GASLIMIT", CHAINID: "CHAINID", SELFBALANCE: "SELFBALANCE", + BASEFEE: "BASEFEE", // 0x50 range - 'storage' and execution POP: "POP", @@ -114,6 +115,7 @@ func initMap() { RETURNSUB: "RETURNSUB", // 0x60 range - push + PUSH0: "PUSH0", PUSH1: "PUSH1", PUSH2: "PUSH2", PUSH3: "PUSH3", @@ -326,6 +328,8 @@ const ( CHAINID OpCode = 0x46 // SELFBALANCE op SELFBALANCE OpCode = 0x47 + // BASEFEE op + BASEFEE OpCode = 0x48 ) const ( @@ -361,6 +365,11 @@ const ( JUMPSUB ) +const ( + // PUSH0 op,将零压入栈(EIP-3855) + PUSH0 OpCode = 0x5f +) + const ( // PUSH1 0x60 栈操作 PUSH1 OpCode = 0x60 + iota diff --git a/plugin/dapp/evm/types/types.go b/plugin/dapp/evm/types/types.go index 092ff471e..5499ba655 100644 --- a/plugin/dapp/evm/types/types.go +++ b/plugin/dapp/evm/types/types.go @@ -69,9 +69,7 @@ const ( // ForkEVMCompat aligns the interpreter with Ethereum behind a single activation height: // - internal CREATE/CREATE2: address from the executing account and its nonce, nonce // increment persisted, address collision check, EIP-150 63/64 gas; - // - opcodes PUSH0, BASEFEE, MCOPY, TLOAD/TSTORE; - // - gas: EIP-2200/2929/3529 (net SSTORE metering, cold/warm access, refund cap) and - // refunds actually applied to the used gas. + // - opcodes PUSH0 and BASEFEE. // Contracts created before the fork have no nonce record (treated as 0), so their first // post-fork internal CREATE does not match Ethereum exactly; contracts created after the // fork match exactly. From ce1904efb6e0d48f26fa53e774d1657161ea83bd Mon Sep 17 00:00:00 2001 From: bysomeone <11565373+bysomeone@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:13:00 +0800 Subject: [PATCH 8/9] fix(evm): align pre-fork contract nonces and the top-level create path A contract deployed before the fork has code but no stored nonce, so its first post-fork internal CREATE used nonce 0 where Ethereum uses 1. Under the fork such an account is now treated as nonce 1, through one helper shared by the address derivation and the increment. The top-level ETH-signed deploy now builds the address from the raw 20 bytes instead of round-tripping through the address driver, which under a btc driver produced an all-zero address, and it applies the same nonce/code collision rule as the internal create, so a balance-only address can be deployed to. The runtime fork checks read the height from the state DB, the same source the state layer and the interpreter use. The account emptiness helper drops its nonce branch: an account with a nonce but no code cannot be loaded from state, so the branch never decided anything. Tests cover the 63/64 forwarding for both creates, a create inside a constructor, CREATE2 incrementing the caller nonce, the pre-fork nonce rule, the top-level raw address and balance-only collision, and the fork key in the three shipped configurations. The ci2 withdraw check no longer hides a jq failure behind a local declaration, so a failed read fails the script instead of asserting against a zero. Co-Authored-By: Claude Code --- plugin/dapp/evm/cmd/ci2/docker-compose.sh | 12 +- plugin/dapp/evm/executor/exec.go | 14 +- plugin/dapp/evm/executor/fork_config_test.go | 82 ++++++ .../executor/top_level_create_compat_test.go | 91 +++++++ plugin/dapp/evm/executor/vm/runtime/evm.go | 37 ++- .../executor/vm/runtime/evm_compat_test.go | 248 ++++++++++++++++++ .../evm/executor/vm/runtime/instructions.go | 3 +- plugin/dapp/evm/executor/vm/state/account.go | 7 - plugin/dapp/evm/types/types.go | 5 +- 9 files changed, 474 insertions(+), 25 deletions(-) create mode 100644 plugin/dapp/evm/executor/fork_config_test.go create mode 100644 plugin/dapp/evm/executor/top_level_create_compat_test.go create mode 100644 plugin/dapp/evm/executor/vm/runtime/evm_compat_test.go diff --git a/plugin/dapp/evm/cmd/ci2/docker-compose.sh b/plugin/dapp/evm/cmd/ci2/docker-compose.sh index 95812eaa7..3e6e7172e 100755 --- a/plugin/dapp/evm/cmd/ci2/docker-compose.sh +++ b/plugin/dapp/evm/cmd/ci2/docker-compose.sh @@ -396,7 +396,11 @@ function withdrawTicketBalance(){ echo "ticket balance:${tbalance},addr:${m4normalAddr},timestamp:$(date +"%s")" # The ticket balance also grows with mining rewards, so it cannot be used as # the expected coin balance after the withdraw. Compare the coins delta. - local coinsBefore=$(${CLI} account balance -a "${m4normalAddr}" -e coins | jq -er ".balance") + local coinsBefore + coinsBefore=$(${CLI} account balance -a "${m4normalAddr}" -e coins | jq -er ".balance") || { + echo "failed to read coins balance before withdraw" + exit 1 + } echo "coins balance before withdraw:${coinsBefore}" local withdrawTx=$( ${CLI} coins withdraw -e ticket -a 100000 -n "take test money") @@ -416,7 +420,11 @@ function withdrawTicketBalance(){ #check coins balance: the withdraw moves 100000 into the coins account minus the #transaction fee (~0.1), so require a lower bound with margin instead of an exact #value: the boundary is sensitive to floating-point rounding of the balances. - local coinsAfter=$(${CLI} account balance -a "${m4normalAddr}" -e coins | jq -er ".balance") + local coinsAfter + coinsAfter=$(${CLI} account balance -a "${m4normalAddr}" -e coins | jq -er ".balance") || { + echo "failed to read coins balance after withdraw" + exit 1 + } echo "coldminer addr coins balance after withdraw:${coinsAfter}" if ! awk -v before="${coinsBefore}" -v after="${coinsAfter}" \ 'BEGIN { exit !((after - before) >= 99999) }'; then diff --git a/plugin/dapp/evm/executor/exec.go b/plugin/dapp/evm/executor/exec.go index d51ac1773..b27f41495 100644 --- a/plugin/dapp/evm/executor/exec.go +++ b/plugin/dapp/evm/executor/exec.go @@ -131,12 +131,22 @@ func (evm *EVMExecutor) innerExec(msg *common.Message, txHash []byte, sigType in } else if isCreate { if types.IsEthSignID(sigType) { // 通过ethsign 签名的兼容交易 采用from+nonce 创建合约地址 - contractAddr = evm.createEvmContractAddress(msg.From(), uint64(msg.Nonce())) + if env.IsEVMCompat() { + // raw 取以太坊地址的 20 字节,不经过地址驱动往返(btc 驱动会把 0x 地址转成全零) + contractAddr = common.NewEvmContractAddressRaw(msg.From(), uint64(msg.Nonce())) + } else { + contractAddr = evm.createEvmContractAddress(msg.From(), uint64(msg.Nonce())) + } } else { contractAddr = evm.createContractAddress(msg.From(), txHash) } contractAddrStr = contractAddr.String() - if !env.StateDB.Empty(contractAddrStr) { + if env.IsEVMCompat() { + // 与内部 CREATE 同一条规则:nonce 非零或代码非空才算冲突,仅有余额可以部署 + if env.ContractAddressCollision(contractAddr) { + return receipt, model.ErrContractAddressCollision + } + } else if !env.StateDB.Empty(contractAddrStr) { return receipt, model.ErrContractAddressCollision } // 只有新创建的合约才能生成合约名称 diff --git a/plugin/dapp/evm/executor/fork_config_test.go b/plugin/dapp/evm/executor/fork_config_test.go new file mode 100644 index 000000000..12631932b --- /dev/null +++ b/plugin/dapp/evm/executor/fork_config_test.go @@ -0,0 +1,82 @@ +// Copyright Fuzamei Corp. 2018 All Rights Reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package executor + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "testing" + + ctypes "github.com/33cn/chain33/types" + evmtypes "github.com/33cn/plugin/plugin/dapp/evm/types" + "github.com/stretchr/testify/require" +) + +// TestForkEVMCompatForkRegisteredOffByDefault pins the code-side default: the fork is +// registered at MaxHeight, so a chain that does not configure it never activates it. +func TestForkEVMCompatForkRegisteredOffByDefault(t *testing.T) { + cfg := newTestConfig(t) + require.Equal(t, int64(ctypes.MaxHeight), cfg.GetDappFork(evmtypes.ExecutorName, evmtypes.ForkEVMCompat)) + require.False(t, cfg.IsDappFork(1_000_000, evmtypes.ExecutorName, evmtypes.ForkEVMCompat)) +} + +// TestForkEVMCompatDeclaredInConfigs asserts that every tracked chain config carries +// ForkEVMCompat inside its [fork.sub.evm] section. initForkConfig panics on a missing +// key, so a config released without it cannot start a node. +func TestForkEVMCompatDeclaredInConfigs(t *testing.T) { + repoRoot := filepath.Join("..", "..", "..", "..") + for _, rel := range []string{ + "chain33.para.toml", + "chain33.fork.toml", + filepath.Join("plugin", "dapp", "evm", "cmd", "ci2", "chain33.proxyminer.toml"), + } { + t.Run(rel, func(t *testing.T) { + data, err := os.ReadFile(filepath.Join(repoRoot, rel)) + require.NoError(t, err) + text := string(data) + require.Contains(t, text, "[fork.sub.evm]", "%s has no evm fork section", rel) + + raw, ok := sectionValue(text, "[fork.sub.evm]", evmtypes.ForkEVMCompat) + require.Truef(t, ok, "%s: [fork.sub.evm] is missing %s (initForkConfig panics)", + rel, evmtypes.ForkEVMCompat) + val, parseErr := strconv.ParseInt(raw, 10, 64) + require.NoErrorf(t, parseErr, "%s: %s=%q is not an integer", rel, evmtypes.ForkEVMCompat, raw) + // Repository configs ship the fork disabled (-1 is loaded as MaxHeight). A chain + // that enables it sets a concrete height in its own deployment config. + require.Equalf(t, int64(-1), val, "%s: %s=%d must stay disabled in the repository config", + rel, evmtypes.ForkEVMCompat, val) + }) + } +} + +// sectionValue returns the raw value of key inside [section], ignoring the same key in +// other sections and commented-out entries. +func sectionValue(text, section, key string) (string, bool) { + inSection := false + for _, line := range strings.Split(text, "\n") { + line = strings.TrimSpace(line) + if i := strings.Index(line, "#"); i >= 0 { + line = strings.TrimSpace(line[:i]) + } + if line == "" { + continue + } + if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { + inSection = line == section + continue + } + if !inSection { + continue + } + k, v, found := strings.Cut(line, "=") + if !found || strings.TrimSpace(k) != key { + continue + } + return strings.TrimSpace(v), true + } + return "", false +} diff --git a/plugin/dapp/evm/executor/top_level_create_compat_test.go b/plugin/dapp/evm/executor/top_level_create_compat_test.go new file mode 100644 index 000000000..677bfcbcd --- /dev/null +++ b/plugin/dapp/evm/executor/top_level_create_compat_test.go @@ -0,0 +1,91 @@ +// Copyright Fuzamei Corp. 2018 All Rights Reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package executor + +import ( + "bytes" + "testing" + + "github.com/33cn/chain33/common/address" + ctypes "github.com/33cn/chain33/types" + gethcommon "github.com/ethereum/go-ethereum/common" + ethcrypto "github.com/ethereum/go-ethereum/crypto" + "github.com/stretchr/testify/require" + + vcomm "github.com/33cn/plugin/plugin/dapp/evm/executor/vm/common" + evmtypes "github.com/33cn/plugin/plugin/dapp/evm/types" +) + +// TestTopLevelETHSignedCreateUsesRawAddressUnderFork deploys with an ETH-signed CREATE +// while the BTC address driver is active. Under ForkEVMCompat the contract address must be +// the raw 20-byte CreateAddress(sender, txNonce); the driver round trip would zero it. +func TestTopLevelETHSignedCreateUsesRawAddressUnderFork(t *testing.T) { + restoreBtcAddressDriver(t) + cfg := newTestConfig(t) + enableEVMCompat(cfg) + exec := newTestExecutor(t, cfg, 0) + + execAddr := address.ExecAddress(cfg.ExecName(evmtypes.ExecutorName)) + action := &evmtypes.EVMContractAction{Code: vcomm.FromHex("60006000f3"), ContractAddr: execAddr} + tx := &ctypes.Transaction{ + ChainID: cfg.GetChainID(), + Execer: []byte(cfg.ExecName(evmtypes.ExecutorName)), + Payload: ctypes.Encode(action), + Fee: 1e6, To: execAddr, Nonce: 0, + } + signTx(tx, roleDeployer) + // Use the ETH signature id the executor dispatches on (signTx only sets the crypto id). + tx.Signature.Ty = ctypes.EncodeSignID(ctypes.SECP256K1ETH, ctypes.EthAddressID) + resetEvmExecAddress(cfg) + + receipt, err := exec.Exec(tx, 0) + require.NoError(t, err) + require.Equal(t, int32(ctypes.ExecOk), receipt.GetTy()) + + sender := vcomm.StringToAddress(tx.From()) + require.NotNil(t, sender) + raw := ethcrypto.CreateAddress(gethcommon.BytesToAddress(sender.Bytes()), uint64(tx.Nonce)) + want := vcomm.BytesToAddress(raw.Bytes()) + + wantKey := []byte("mavl-" + evmtypes.ExecutorName + "-data: " + want.String()) + for _, kv := range receipt.GetKV() { + if bytes.Equal(kv.GetKey(), wantKey) { + return + } + } + t.Fatalf("no contract data KV at the raw ETH address %s", want.String()) +} + +// TestTopLevelCreateAllowsBalanceOnlyAddressUnderFork pre-funds the derived contract +// address with coins only: under ForkEVMCompat that is not a collision (only nonce or +// code is), so the deploy succeeds. +func TestTopLevelCreateAllowsBalanceOnlyAddressUnderFork(t *testing.T) { + restoreBtcAddressDriver(t) + cfg := newTestConfig(t) + enableEVMCompat(cfg) + exec := newTestExecutor(t, cfg, 0) + + execAddr := address.ExecAddress(cfg.ExecName(evmtypes.ExecutorName)) + action := &evmtypes.EVMContractAction{Code: vcomm.FromHex("60006000f3"), ContractAddr: execAddr} + tx := &ctypes.Transaction{ + ChainID: cfg.GetChainID(), + Execer: []byte(cfg.ExecName(evmtypes.ExecutorName)), + Payload: ctypes.Encode(action), + Fee: 1e6, To: execAddr, Nonce: 0, + } + signTx(tx, roleDeployer) + tx.Signature.Ty = ctypes.EncodeSignID(ctypes.SECP256K1ETH, ctypes.EthAddressID) + resetEvmExecAddress(cfg) + + sender := vcomm.StringToAddress(tx.From()) + require.NotNil(t, sender) + raw := ethcrypto.CreateAddress(gethcommon.BytesToAddress(sender.Bytes()), uint64(tx.Nonce)) + target := vcomm.BytesToAddress(raw.Bytes()) + fundAddr(t, exec, target.String(), 100) + + receipt, err := exec.Exec(tx, 0) + require.NoError(t, err) + require.Equal(t, int32(ctypes.ExecOk), receipt.GetTy()) +} diff --git a/plugin/dapp/evm/executor/vm/runtime/evm.go b/plugin/dapp/evm/executor/vm/runtime/evm.go index e5088db56..af318454f 100644 --- a/plugin/dapp/evm/executor/vm/runtime/evm.go +++ b/plugin/dapp/evm/executor/vm/runtime/evm.go @@ -199,9 +199,29 @@ func (evm *EVM) CheckIsEthTx() bool { } // IsEVMCompat 以太坊 EVM 兼容性(指令/计价/CREATE)是否开启(fork 门控) +// 高度取状态机的区块高度,与 state 层和 NewInterpreter 的 fork 判定使用同一来源。 func (evm *EVM) IsEVMCompat() bool { - return evm.cfg != nil && evm.BlockNumber != nil && - evm.cfg.IsDappFork(evm.BlockNumber.Int64(), evmtypes.ExecutorName, evmtypes.ForkEVMCompat) + if evm.cfg == nil || evm.StateDB == nil { + return false + } + return evm.cfg.IsDappFork(evm.StateDB.GetBlockHeight(), evmtypes.ExecutorName, evmtypes.ForkEVMCompat) +} + +// accountNonce 返回派生 CREATE 地址与递增时使用的账户 nonce。 +// fork 开启后,已有代码但没有 nonce 记录的账户(fork 前部署的合约)按 nonce 1 处理, +// 使其第一次内部 CREATE 与以太坊一致;fork 关闭时直接返回已存 nonce。 +func (evm *EVM) accountNonce(addr common.Address) uint64 { + nonce := evm.StateDB.GetNonce(addr.String()) + if nonce == 0 && evm.IsEVMCompat() && evm.StateDB.GetCodeSize(addr.String()) > 0 { + return 1 + } + return nonce +} + +// ContractAddressCollision 判断目标地址是否已被占用。 +// 顶层与内部 CREATE 共用同一条规则:nonce 非零或代码非空即冲突;仅有余额不算冲突。 +func (evm *EVM) ContractAddressCollision(addr common.Address) bool { + return evm.StateDB.GetNonce(addr.String()) != 0 || evm.StateDB.GetCodeSize(addr.String()) > 0 } // 封装合约的各种调用逻辑中通用的预检查逻辑 @@ -276,7 +296,7 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas to := AccountRef(addr) // 向合约地址转账 cfg := evm.StateDB.GetConfig() - if cfg.IsDappFork(evm.BlockNumber.Int64(), "evm", evmtypes.ForkEVMFixOverflow) { + if cfg.IsDappFork(evm.StateDB.GetBlockHeight(), "evm", evmtypes.ForkEVMFixOverflow) { if value > 0 && !evm.Transfer(evm.StateDB, caller.Address(), to.Address(), value) { log.Error("evm call transfer failed", "caller", caller.Address().String(), "to", to.Address().String(), "value", value) evm.StateDB.RevertToSnapshot(snapshot) @@ -288,7 +308,7 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas log.Info("evm call", "caller address", caller.Address().String(), "contract address", to.Address().String(), "value", value) // 从ForkV20EVMState开始,状态数据存储发生变更,需要做数据迁移 cfg = evm.StateDB.GetConfig() - if cfg.IsDappFork(evm.BlockNumber.Int64(), "evm", evmtypes.ForkEVMState) { + if cfg.IsDappFork(evm.StateDB.GetBlockHeight(), "evm", evmtypes.ForkEVMState) { evm.StateDB.TransferStateData(addr.String()) } @@ -547,10 +567,9 @@ func (evm *EVM) Create(caller ContractRef, contractAddr common.Address, code []b // nonce 递增必须在快照之前,这样创建失败时 nonce 仍然生效。 if evm.IsEVMCompat() { callerAddr := caller.Address() - nonce := evm.StateDB.GetNonce(callerAddr.String()) - evm.StateDB.SetNonce(callerAddr.String(), nonce+1) + evm.StateDB.SetNonce(callerAddr.String(), evm.accountNonce(callerAddr)+1) - if evm.StateDB.GetNonce(contractAddr.String()) != 0 || evm.StateDB.GetCodeSize(contractAddr.String()) > 0 { + if evm.ContractAddressCollision(contractAddr) { log.Error("evm contract address collision", "caller", callerAddr.String(), "contractAddr", contractAddr.String()) return nil, -1, 0, model.ErrContractAddressCollision } @@ -560,11 +579,11 @@ func (evm *EVM) Create(caller ContractRef, contractAddr common.Address, code []b cfg := evm.StateDB.GetConfig() // From ForkEVMTransferRevert on, the snapshot is taken before the transfer so that a // failed create also reverts the attached value (see transferChange.revert). - snapshotBeforeTransfer := cfg.IsDappFork(evm.BlockNumber.Int64(), "evm", evmtypes.ForkEVMTransferRevert) + snapshotBeforeTransfer := cfg.IsDappFork(evm.StateDB.GetBlockHeight(), "evm", evmtypes.ForkEVMTransferRevert) if snapshotBeforeTransfer { snapshot = evm.StateDB.Snapshot() } - if cfg.IsDappFork(evm.BlockNumber.Int64(), "evm", evmtypes.ForkEVMFixOverflow) { + if cfg.IsDappFork(evm.StateDB.GetBlockHeight(), "evm", evmtypes.ForkEVMFixOverflow) { if value > 0 && !evm.Transfer(evm.StateDB, caller.Address(), contractAddr, value) { if snapshotBeforeTransfer { evm.StateDB.RevertToSnapshot(snapshot) diff --git a/plugin/dapp/evm/executor/vm/runtime/evm_compat_test.go b/plugin/dapp/evm/executor/vm/runtime/evm_compat_test.go new file mode 100644 index 000000000..eed784530 --- /dev/null +++ b/plugin/dapp/evm/executor/vm/runtime/evm_compat_test.go @@ -0,0 +1,248 @@ +// Copyright Fuzamei Corp. 2018 All Rights Reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package runtime + +// ForkEVMCompat 的运行时边界:fork 前部署合约的 nonce 对齐、CREATE/CREATE2 的 +// EIP-150 63/64 转发、CREATE2 递增调用者 nonce、构造函数内的 CREATE,以及 +// ForkEVMTransferRevert 关闭时失败 CREATE 保留附带金额。 + +import ( + "bytes" + "math/big" + "strings" + "testing" + + ctypes "github.com/33cn/chain33/types" + "github.com/holiman/uint256" + "github.com/stretchr/testify/require" + + vcomm "github.com/33cn/plugin/plugin/dapp/evm/executor/vm/common" + vcommcrypto "github.com/33cn/plugin/plugin/dapp/evm/executor/vm/common/crypto" + evmtypes "github.com/33cn/plugin/plugin/dapp/evm/types" + gethcommon "github.com/ethereum/go-ethereum/common" + ethcrypto "github.com/ethereum/go-ethereum/crypto" +) + +// newCompatEnv builds a VM environment whose ForkEVMCompat resolves at compatHeight. +// The default configstring keeps every other fork at its registered default. +func newCompatEnv(t *testing.T, compatHeight int64) *gapEnv { + t.Helper() + cfgStr := strings.Replace(ctypes.GetDefaultCfgstring(), `Title="local"`, `Title="test"`, 1) + if !strings.Contains(cfgStr, "[exec.sub.evm]") { + cfgStr += "\n[exec.sub.evm]\nethMapFromExecutor=\"coins\"\nethMapFromSymbol=\"bty\"\n" + } + cfg := ctypes.NewChain33Config(cfgStr) + require.False(t, cfg.IsLocal(), "a local config would force every fork to height 0") + cfg.SetDappFork(evmtypes.ExecutorName, evmtypes.ForkEVMCompat, compatHeight) + require.Equal(t, compatHeight, cfg.GetDappFork(evmtypes.ExecutorName, evmtypes.ForkEVMCompat)) + require.Equal(t, compatHeight <= gapTestHeight, + cfg.IsDappFork(gapTestHeight, evmtypes.ExecutorName, evmtypes.ForkEVMCompat)) + return newGapEnvWithCfg(t, cfg, "evm-compat") +} + +// gasProbeInit returns init code whose first instruction is GAS. The GAS opcode pushes +// its own post-cost remaining gas, and RETURN hands that word back as the deployed code, +// so the child's initial allowance is readable from the stored code. +// +// GAS; PUSH1 0; MSTORE; PUSH1 32; PUSH1 0; RETURN +func gasProbeInit() []byte { + return []byte{0x5a, 0x60, 0x00, 0x52, 0x60, 0x20, 0x60, 0x00, 0xf3} +} + +func gasFromCode(t *testing.T, code []byte) uint64 { + t.Helper() + require.Len(t, code, 32, "gas probe must deploy a 32-byte word") + return new(big.Int).SetBytes(code).Uint64() +} + +// persistedNonce reads the nonce from the account's state KV in the journaled changes. +func persistedNonce(t *testing.T, env *gapEnv, account vcomm.Address) uint64 { + t.Helper() + kvs, _ := env.mdb.GetChangedData(0) + stateKey := []byte("mavl-" + evmtypes.ExecutorName + "-state: " + account.String()) + for _, kv := range kvs { + if !bytes.Equal(kv.GetKey(), stateKey) { + continue + } + var state evmtypes.EVMContractState + require.NoError(t, ctypes.Decode(kv.GetValue(), &state)) + return state.GetNonce() + } + t.Fatalf("no state KV for %s", account.String()) + return 0 +} + +// TestCreateEIP150GasForwarding pins the child allowance for CREATE: the child receives +// 63/64 of the caller's remaining gas (EIP-150); the probe reports that minus GAS's cost. +func TestCreateEIP150GasForwarding(t *testing.T) { + env := newCompatEnv(t, 0) + caller, parent := addr(0x11), addr(0x12) + env.deploy(parent, caller, []byte{0x00}) + + const gasBefore = uint64(1_000_000) + init := gasProbeInit() + mem := NewMemory() + mem.Resize(uint64(len(init))) + mem.Set(0, uint64(len(init)), init) + stack := newstack() + stack.push(new(uint256.Int).SetUint64(uint64(len(init)))) // size + stack.push(new(uint256.Int).SetUint64(0)) // offset + stack.push(new(uint256.Int).SetUint64(0)) // value + + // Open a snapshot so the nonce increment is journaled and visible in the changed data. + env.mdb.Snapshot() + + contract := NewContract(AccountRef(caller), AccountRef(parent), big.NewInt(0), gasBefore) + callContext := &callCtx{memory: mem, stack: stack, contract: contract} + pc := uint64(0) + _, err := opCreate(&pc, env.evm, callContext) + require.NoError(t, err) + + child := vcomm.BytesToAddress(ethcrypto.CreateAddress(gethcommon.BytesToAddress(parent.Bytes()), 1).Bytes()) + forwarded := gasBefore - gasBefore/64 + require.Equal(t, forwarded-2, gasFromCode(t, env.mdb.GetCode(child.String())), + "CREATE must forward 63/64 of the remaining gas") + // The pre-fork account (code, no stored nonce) counts as nonce 1 and is incremented to 2, + // and that value reaches the persisted state KV. + require.Equal(t, uint64(2), env.mdb.GetNonce(parent.String())) + require.Equal(t, uint64(2), persistedNonce(t, env, parent)) +} + +// TestContractAddressCollisionRule pins the shared collision predicate: a balance alone +// is not a collision, while a non-zero nonce or code is. +func TestContractAddressCollisionRule(t *testing.T) { + env := newCompatEnv(t, 0) + caller := addr(0x61) + env.fund(caller, 100) + balanceOnly := addr(0x62) + env.mdb.AddBalance(balanceOnly.String(), caller.String(), 100) + require.Equal(t, uint64(100), env.mdb.GetBalance(balanceOnly.String())) + require.False(t, env.evm.ContractAddressCollision(balanceOnly), "a balance alone must not collide") + + withCode := addr(0x63) + env.mdb.CreateAccount(withCode.String(), caller.String(), "evm.test", "") + env.mdb.SetCode(withCode.String(), []byte{0x00}) + require.True(t, env.evm.ContractAddressCollision(withCode), "code must collide") + + withNonce := addr(0x64) + env.mdb.CreateAccount(withNonce.String(), caller.String(), "evm.test", "") + env.mdb.SetNonce(withNonce.String(), 1) + require.True(t, env.evm.ContractAddressCollision(withNonce), "a non-zero nonce must collide") +} + +// TestCreate2EIP150GasForwarding pins the same 63/64 rule for CREATE2. +func TestCreate2EIP150GasForwarding(t *testing.T) { + env := newCompatEnv(t, 0) + caller, parent := addr(0x21), addr(0x22) + env.deploy(parent, caller, []byte{0x00}) + + const gasBefore = uint64(1_000_000) + init := gasProbeInit() + salt := uint256.NewInt(0x1234) + mem := NewMemory() + mem.Resize(uint64(len(init))) + mem.Set(0, uint64(len(init)), init) + stack := newstack() + stack.push(salt) // salt + stack.push(new(uint256.Int).SetUint64(uint64(len(init)))) // size + stack.push(new(uint256.Int).SetUint64(0)) // offset + stack.push(new(uint256.Int).SetUint64(0)) // endowment + + contract := NewContract(AccountRef(caller), AccountRef(parent), big.NewInt(0), gasBefore) + callContext := &callCtx{memory: mem, stack: stack, contract: contract} + pc := uint64(0) + _, err := opCreate2(&pc, env.evm, callContext) + require.NoError(t, err) + + saltBytes := salt.Bytes32() + child := vcommcrypto.CreateAddress2(parent, saltBytes, vcommcrypto.Keccak256(init)) + forwarded := gasBefore - gasBefore/64 + require.Equal(t, forwarded-2, gasFromCode(t, env.mdb.GetCode(child.String())), + "CREATE2 must forward 63/64 of the remaining gas") + // CREATE2 also increments the caller nonce. + require.Equal(t, uint64(2), env.mdb.GetNonce(parent.String())) +} + +// TestAccountNonceForPreForkContract pins the shared nonce helper: an account with code +// but no stored nonce counts as 1 under the fork and 0 without it. +func TestAccountNonceForPreForkContract(t *testing.T) { + for _, tc := range []struct { + name string + compatAt int64 + wantNonce uint64 + }{ + {"fork off keeps the stored nonce", ctypes.MaxHeight, 0}, + {"fork on treats code-only account as 1", 0, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + env := newCompatEnv(t, tc.compatAt) + account := addr(0x31) + env.mdb.CreateAccount(account.String(), account.String(), "evm.test", "") + env.mdb.SetCode(account.String(), []byte{0x00}) + require.Equal(t, uint64(0), env.mdb.GetNonce(account.String())) + require.Equal(t, tc.wantNonce, env.evm.accountNonce(account)) + }) + } +} + +// buildConstructorCreate returns init code that CREATEs childInit from memory and then +// stops with an empty runtime body. +func buildConstructorCreate(childInit []byte) []byte { + if len(childInit) > 32 { + panic("childInit longer than one word") + } + code := []byte{byte(0x5f + len(childInit))} + code = append(code, childInit...) + code = append(code, + 0x60, 0x00, // PUSH1 0 + 0x52, // MSTORE + 0x60, byte(len(childInit)), // PUSH1 size + 0x60, byte(32-len(childInit)), // PUSH1 offset + 0x60, 0x00, // PUSH1 value + 0xf0, // CREATE + 0x50, // POP + 0x00, // STOP + ) + return code +} + +// TestCreateInsideConstructor covers a CREATE issued while the caller contract is still +// running its constructor: it sees nonce 1 (EIP-161) and the child is deployed. +func TestCreateInsideConstructor(t *testing.T) { + env := newCompatEnv(t, 0) + caller, contractA := addr(0x41), addr(0x42) + + // Child init code returns the one-byte runtime 0x2a: + // PUSH1 0x2a; PUSH1 0; MSTORE8; PUSH1 1; PUSH1 0; RETURN + childInit := []byte{0x60, 0x2a, 0x60, 0x00, 0x53, 0x60, 0x01, 0x60, 0x00, 0xf3} + init := buildConstructorCreate(childInit) + + _, _, _, err := env.evm.Create(AccountRef(caller), contractA, init, 5_000_000, "innerContract", "", 0) + require.NoError(t, err) + + child := vcomm.BytesToAddress(ethcrypto.CreateAddress(gethcommon.BytesToAddress(contractA.Bytes()), 1).Bytes()) + require.Equal(t, []byte{0x2a}, env.mdb.GetCode(child.String())) + require.Equal(t, uint64(2), env.mdb.GetNonce(contractA.String()), + "the constructor starts at nonce 1 and its CREATE increments it") +} + +// TestCompatCreateKeepsValueWithoutTransferRevert documents the boundary between the two +// forks: ForkEVMCompat alone does not roll back the value attached to a failed CREATE. +func TestCompatCreateKeepsValueWithoutTransferRevert(t *testing.T) { + env := newCompatEnv(t, 0) + require.Equal(t, int64(ctypes.MaxHeight), + env.cfg.GetDappFork(evmtypes.ExecutorName, evmtypes.ForkEVMTransferRevert)) + + const stash = int64(1000) + const attached = uint64(5) + caller, parent := addr(0x51), addr(0x52) + env.fund(parent, stash) + env.deploy(parent, caller, buildCreateWithValueCode(attached, []byte{0xfe})) + + _, _, _, err := env.evm.Call(AccountRef(caller), parent, nil, 5_000_000, 0) + require.NoError(t, err) + require.Equal(t, stash-int64(attached), env.balance(parent), + "without ForkEVMTransferRevert the failed CREATE keeps the attached value") +} diff --git a/plugin/dapp/evm/executor/vm/runtime/instructions.go b/plugin/dapp/evm/executor/vm/runtime/instructions.go index fb0fc9bb7..dbda29194 100644 --- a/plugin/dapp/evm/executor/vm/runtime/instructions.go +++ b/plugin/dapp/evm/executor/vm/runtime/instructions.go @@ -666,8 +666,7 @@ func opCreate(pc *uint64, evm *EVM, callContext *callCtx) ([]byte, error) { if evm.IsEVMCompat() { // 以太坊语义:地址由调用者地址与调用者 nonce 派生 creator := callContext.contract.Address() - nonce := evm.StateDB.GetNonce(creator.String()) - addr = common.NewEvmContractAddressRaw(creator, nonce) + addr = common.NewEvmContractAddressRaw(creator, evm.accountNonce(creator)) } if !value.IsZero() && evm.CheckIsEthTx() { diff --git a/plugin/dapp/evm/executor/vm/state/account.go b/plugin/dapp/evm/executor/vm/state/account.go index 2bd32b203..d448e5ab0 100644 --- a/plugin/dapp/evm/executor/vm/state/account.go +++ b/plugin/dapp/evm/executor/vm/state/account.go @@ -295,13 +295,6 @@ func (ca *ContractAccount) Empty() bool { if ca.Data.GetCodeHash() != nil && len(ca.Data.GetCodeHash()) != 0 { return false } - // fork 开启后采用以太坊语义:有 nonce 的账户非空 - if ca.State.GetNonce() != 0 && ca.mdb != nil && ca.mdb.api != nil { - cfg := ca.mdb.api.GetConfig() - if cfg != nil && cfg.IsDappFork(ca.mdb.blockHeight, evmtypes.ExecutorName, evmtypes.ForkEVMCompat) { - return false - } - } return true } diff --git a/plugin/dapp/evm/types/types.go b/plugin/dapp/evm/types/types.go index 5499ba655..995f9ec7e 100644 --- a/plugin/dapp/evm/types/types.go +++ b/plugin/dapp/evm/types/types.go @@ -70,9 +70,8 @@ const ( // - internal CREATE/CREATE2: address from the executing account and its nonce, nonce // increment persisted, address collision check, EIP-150 63/64 gas; // - opcodes PUSH0 and BASEFEE. - // Contracts created before the fork have no nonce record (treated as 0), so their first - // post-fork internal CREATE does not match Ethereum exactly; contracts created after the - // fork match exactly. + // An account that already holds code but has no stored nonce (a contract deployed before + // the fork) is treated as nonce 1, so its first post-fork internal CREATE matches Ethereum. // Enable it at the same height as ForkEVMTransferRevert: the latter rolls back the value // attached to a failed CREATE, which this fork alone does not do. ForkEVMCompat = "ForkEVMCompat" From 5e7c8e7b1ff9572a3733095ccde1214834c81c78 Mon Sep 17 00:00:00 2001 From: bysomeone <11565373+bysomeone@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:16:57 +0800 Subject: [PATCH 9/9] fix(dpos): return instead of dereferencing a missing genesis document StartConsensus is started as a goroutine by SetQueueClient. When the node is configured as a validator but its client was built without a genesis document, MakeGenesisValidatorMgr dereferences nil and the panic takes the process down. Log and return instead; a node without a genesis document cannot build a validator set anyway. Co-Authored-By: Claude Code --- plugin/consensus/dpos/dpos.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/plugin/consensus/dpos/dpos.go b/plugin/consensus/dpos/dpos.go index ac93bb503..851de9c7a 100644 --- a/plugin/consensus/dpos/dpos.go +++ b/plugin/consensus/dpos/dpos.go @@ -301,6 +301,12 @@ OuterLoop: return } + // genesisDoc 由 NewClient 传入,缺省时无法构造验证人集合,直接返回而不是空指针崩溃 + if client.genesisDoc == nil { + dposlog.Error("StartConsensus", "msg", "genesis doc is nil, skip consensus") + return + } + var valMgr ValidatorMgr valMgrTmp, err := MakeGenesisValidatorMgr(client.genesisDoc) if err != nil {