Skip to content

Commit cab1cff

Browse files
rjl493456442karalabe
authored andcommitted
core, crypto, params: implement CREATE2 evm instrction (#17196)
* core, crypto, params: implement CREATE2 evm instrction * core/vm: add opcode to string mapping * core: remove past fork checking * core, crypto: use option2 to generate new address
1 parent 2909f6d commit cab1cff

8 files changed

Lines changed: 94 additions & 17 deletions

File tree

‎core/vm/evm.go‎

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -319,9 +319,8 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte
319319
return ret, contract.Gas, err
320320
}
321321

322-
// Create creates a new contract using code as deployment code.
323-
func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
324-
322+
// create creates a new contract using code as deployment code.
323+
func (evm *EVM) create(caller ContractRef, code []byte, gas uint64, value *big.Int, address common.Address) ([]byte, common.Address, uint64, error) {
325324
// Depth check execution. Fail if we're trying to execute above the
326325
// limit.
327326
if evm.depth > int(params.CallCreateDepth) {
@@ -330,39 +329,38 @@ func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.I
330329
if !evm.CanTransfer(evm.StateDB, caller.Address(), value) {
331330
return nil, common.Address{}, gas, ErrInsufficientBalance
332331
}
333-
// Ensure there's no existing contract already at the designated address
334332
nonce := evm.StateDB.GetNonce(caller.Address())
335333
evm.StateDB.SetNonce(caller.Address(), nonce+1)
336334

337-
contractAddr = crypto.CreateAddress(caller.Address(), nonce)
338-
contractHash := evm.StateDB.GetCodeHash(contractAddr)
339-
if evm.StateDB.GetNonce(contractAddr) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
335+
// Ensure there's no existing contract already at the designated address
336+
contractHash := evm.StateDB.GetCodeHash(address)
337+
if evm.StateDB.GetNonce(address) != 0 || (contractHash != (common.Hash{}) && contractHash != emptyCodeHash) {
340338
return nil, common.Address{}, 0, ErrContractAddressCollision
341339
}
342340
// Create a new account on the state
343341
snapshot := evm.StateDB.Snapshot()
344-
evm.StateDB.CreateAccount(contractAddr)
342+
evm.StateDB.CreateAccount(address)
345343
if evm.ChainConfig().IsEIP158(evm.BlockNumber) {
346-
evm.StateDB.SetNonce(contractAddr, 1)
344+
evm.StateDB.SetNonce(address, 1)
347345
}
348-
evm.Transfer(evm.StateDB, caller.Address(), contractAddr, value)
346+
evm.Transfer(evm.StateDB, caller.Address(), address, value)
349347

350348
// initialise a new contract and set the code that is to be used by the
351349
// EVM. The contract is a scoped environment for this execution context
352350
// only.
353-
contract := NewContract(caller, AccountRef(contractAddr), value, gas)
354-
contract.SetCallCode(&contractAddr, crypto.Keccak256Hash(code), code)
351+
contract := NewContract(caller, AccountRef(address), value, gas)
352+
contract.SetCallCode(&address, crypto.Keccak256Hash(code), code)
355353

356354
if evm.vmConfig.NoRecursion && evm.depth > 0 {
357-
return nil, contractAddr, gas, nil
355+
return nil, address, gas, nil
358356
}
359357

360358
if evm.vmConfig.Debug && evm.depth == 0 {
361-
evm.vmConfig.Tracer.CaptureStart(caller.Address(), contractAddr, true, code, gas, value)
359+
evm.vmConfig.Tracer.CaptureStart(caller.Address(), address, true, code, gas, value)
362360
}
363361
start := time.Now()
364362

365-
ret, err = run(evm, contract, nil)
363+
ret, err := run(evm, contract, nil)
366364

367365
// check whether the max code size has been exceeded
368366
maxCodeSizeExceeded := evm.ChainConfig().IsEIP158(evm.BlockNumber) && len(ret) > params.MaxCodeSize
@@ -373,7 +371,7 @@ func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.I
373371
if err == nil && !maxCodeSizeExceeded {
374372
createDataGas := uint64(len(ret)) * params.CreateDataGas
375373
if contract.UseGas(createDataGas) {
376-
evm.StateDB.SetCode(contractAddr, ret)
374+
evm.StateDB.SetCode(address, ret)
377375
} else {
378376
err = ErrCodeStoreOutOfGas
379377
}
@@ -395,7 +393,23 @@ func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.I
395393
if evm.vmConfig.Debug && evm.depth == 0 {
396394
evm.vmConfig.Tracer.CaptureEnd(ret, gas-contract.Gas, time.Since(start), err)
397395
}
398-
return ret, contractAddr, contract.Gas, err
396+
return ret, address, contract.Gas, err
397+
398+
}
399+
400+
// Create creates a new contract using code as deployment code.
401+
func (evm *EVM) Create(caller ContractRef, code []byte, gas uint64, value *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
402+
contractAddr = crypto.CreateAddress(caller.Address(), evm.StateDB.GetNonce(caller.Address()))
403+
return evm.create(caller, code, gas, value, contractAddr)
404+
}
405+
406+
// Create2 creates a new contract using code as deployment code.
407+
//
408+
// The different between Create2 with Create is Create2 uses sha3(msg.sender ++ salt ++ init_code)[12:]
409+
// instead of the usual sender-and-nonce-hash as the address where the contract is initialized at.
410+
func (evm *EVM) Create2(caller ContractRef, code []byte, gas uint64, endowment *big.Int, salt *big.Int) (ret []byte, contractAddr common.Address, leftOverGas uint64, err error) {
411+
contractAddr = crypto.CreateAddress2(caller.Address(), common.BigToHash(salt), code)
412+
return evm.create(caller, code, gas, endowment, contractAddr)
399413
}
400414

401415
// ChainConfig returns the environment's chain configuration

‎core/vm/gas_table.go‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,18 @@ func gasCreate(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, m
289289
return gas, nil
290290
}
291291

292+
func gasCreate2(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
293+
var overflow bool
294+
gas, err := memoryGasCost(mem, memorySize)
295+
if err != nil {
296+
return 0, err
297+
}
298+
if gas, overflow = math.SafeAdd(gas, params.Create2Gas); overflow {
299+
return 0, errGasUintOverflow
300+
}
301+
return gas, nil
302+
}
303+
292304
func gasBalance(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
293305
return gt.Balance, nil
294306
}

‎core/vm/instructions.go‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -665,6 +665,34 @@ func opCreate(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *S
665665
return nil, nil
666666
}
667667

668+
func opCreate2(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
669+
var (
670+
endowment = stack.pop()
671+
offset, size = stack.pop(), stack.pop()
672+
salt = stack.pop()
673+
input = memory.Get(offset.Int64(), size.Int64())
674+
gas = contract.Gas
675+
)
676+
677+
// Apply EIP150
678+
gas -= gas / 64
679+
contract.UseGas(gas)
680+
res, addr, returnGas, suberr := evm.Create2(contract, input, gas, endowment, salt)
681+
// Push item on the stack based on the returned error.
682+
if suberr != nil {
683+
stack.push(evm.interpreter.intPool.getZero())
684+
} else {
685+
stack.push(addr.Big())
686+
}
687+
contract.Gas += returnGas
688+
evm.interpreter.intPool.put(endowment, offset, size, salt)
689+
690+
if suberr == errExecutionReverted {
691+
return res, nil
692+
}
693+
return nil, nil
694+
}
695+
668696
func opCall(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
669697
// Pop gas. The actual gas in in evm.callGasTemp.
670698
evm.interpreter.intPool.put(stack.pop())

‎core/vm/jump_table.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,15 @@ func newConstantinopleInstructionSet() [256]operation {
8080
validateStack: makeStackFunc(2, 1),
8181
valid: true,
8282
}
83+
instructionSet[CREATE2] = operation{
84+
execute: opCreate2,
85+
gasCost: gasCreate2,
86+
validateStack: makeStackFunc(4, 1),
87+
memorySize: memoryCreate2,
88+
valid: true,
89+
writes: true,
90+
returns: true,
91+
}
8392
return instructionSet
8493
}
8594

‎core/vm/memory_table.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ func memoryCreate(stack *Stack) *big.Int {
5858
return calcMemSize(stack.Back(1), stack.Back(2))
5959
}
6060

61+
func memoryCreate2(stack *Stack) *big.Int {
62+
return calcMemSize(stack.Back(1), stack.Back(2))
63+
}
64+
6165
func memoryCall(stack *Stack) *big.Int {
6266
x := calcMemSize(stack.Back(5), stack.Back(6))
6367
y := calcMemSize(stack.Back(3), stack.Back(4))

‎core/vm/opcodes.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ const (
209209
CALLCODE
210210
RETURN
211211
DELEGATECALL
212+
CREATE2
212213
STATICCALL = 0xfa
213214

214215
REVERT = 0xfd
@@ -370,6 +371,7 @@ var opCodeToString = map[OpCode]string{
370371
RETURN: "RETURN",
371372
CALLCODE: "CALLCODE",
372373
DELEGATECALL: "DELEGATECALL",
374+
CREATE2: "CREATE2",
373375
STATICCALL: "STATICCALL",
374376
REVERT: "REVERT",
375377
SELFDESTRUCT: "SELFDESTRUCT",
@@ -521,6 +523,7 @@ var stringToOp = map[string]OpCode{
521523
"LOG3": LOG3,
522524
"LOG4": LOG4,
523525
"CREATE": CREATE,
526+
"CREATE2": CREATE2,
524527
"CALL": CALL,
525528
"RETURN": RETURN,
526529
"CALLCODE": CALLCODE,

‎crypto/crypto.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,12 @@ func CreateAddress(b common.Address, nonce uint64) common.Address {
7676
return common.BytesToAddress(Keccak256(data)[12:])
7777
}
7878

79+
// CreateAddress2 creates an ethereum address given the address bytes, initial
80+
// contract code and a salt.
81+
func CreateAddress2(b common.Address, salt common.Hash, code []byte) common.Address {
82+
return common.BytesToAddress(Keccak256([]byte{0xff}, b.Bytes(), salt.Bytes(), code)[12:])
83+
}
84+
7985
// ToECDSA creates a private key with the given D value.
8086
func ToECDSA(d []byte) (*ecdsa.PrivateKey, error) {
8187
return toECDSA(d, true)

‎params/protocol_params.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ const (
5757
TierStepGas uint64 = 0 // Once per operation, for a selection of them.
5858
LogTopicGas uint64 = 375 // Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas.
5959
CreateGas uint64 = 32000 // Once per CREATE operation & contract-creation transaction.
60+
Create2Gas uint64 = 32000 // Once per CREATE2 operation
6061
SuicideRefundGas uint64 = 24000 // Refunded following a suicide operation.
6162
MemoryGas uint64 = 3 // Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL.
6263
TxDataNonZeroGas uint64 = 68 // Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions.

0 commit comments

Comments
 (0)