From b55781be3f693ff0cfac76d67ab89c7beb6dd913 Mon Sep 17 00:00:00 2001 From: BananaLF <864685021@qq.com> Date: Fri, 28 Apr 2023 17:28:19 +0800 Subject: [PATCH 1/2] add cmbridge precompile contract --- core/vm/cmbridge.go | 56 ++++++++++++++++++++++++++++++++++++++++ core/vm/cmbridge_test.go | 7 +++++ core/vm/contracts.go | 3 +++ core/vm/errors.go | 25 +++++++++--------- core/vm/evm.go | 20 ++++++++------ 5 files changed, 91 insertions(+), 20 deletions(-) create mode 100644 core/vm/cmbridge.go create mode 100644 core/vm/cmbridge_test.go diff --git a/core/vm/cmbridge.go b/core/vm/cmbridge.go new file mode 100644 index 0000000000..cfe73e7473 --- /dev/null +++ b/core/vm/cmbridge.go @@ -0,0 +1,56 @@ +package vm + +import ( + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" + "math/big" +) + +var ( + //cmBridgeContractAddress is 0xDb327e55CA2C68b23f83a0fbe29b592702e1d4d7 + cmBridgeContractAddress = common.BytesToAddress(crypto.Keccak256([]byte("cm_bridge"))[12:]) +) + +type CallToWasmByPrecompile func(ctx OKContext, caller, to common.Address, value *big.Int, input []byte, remainGas uint64) ([]byte, uint64, error) + +type OKContext interface { + GetEVMStateDB() StateDB +} + +// cmBridge implemented as a native contract. +type cmBridge struct { + context OKContext //OK chain add new Context + // Context provides auxiliary blockchain related information + EvmContext BlockContext + callToWasm CallToWasmByPrecompile + caller common.Address + to common.Address + value *big.Int +} + +// RequiredGas returns the gas required to execute the pre-compiled contract. +// +// This method does not require any overflow checking as the input size gas costs +// required for anything significant is so high it's impossible to pay for. +// we can cost some gas +func (c *cmBridge) RequiredGas(input []byte) uint64 { + panic("cmBridge not support of implement") +} +func (c *cmBridge) Run(in []byte) ([]byte, error) { + panic("cmBridge not support of implement") +} + +func (c *cmBridge) CustomRun(in []byte, remainGas uint64) ([]byte, uint64, error) { + // cmBridge can not got coin, when can cmBridgeContract may be send coin to cmBridgeContractAddress, so we must send coin back to caller. + if c.value.Sign() != 0 && !c.EvmContext.CanTransfer(c.context.GetEVMStateDB(), cmBridgeContractAddress, c.value) { + return nil, 0, ErrCMBirdgeInsufficientBalance + } + + c.EvmContext.Transfer(c.context.GetEVMStateDB(), cmBridgeContractAddress, c.caller, c.value) + // after send coin back to caller, we send coin + return c.callToWasm(c.context, c.caller, c.to, c.value, in, remainGas) +} + +func NewCMBridge(context OKContext, evmContext BlockContext, callToWasm CallToWasmByPrecompile, caller, to common.Address, value *big.Int) *cmBridge { + return &cmBridge{context: context, EvmContext: evmContext, callToWasm: callToWasm, caller: caller, to: to, value: value} +} diff --git a/core/vm/cmbridge_test.go b/core/vm/cmbridge_test.go new file mode 100644 index 0000000000..e9404b1ec1 --- /dev/null +++ b/core/vm/cmbridge_test.go @@ -0,0 +1,7 @@ +package vm + +import "testing" + +func TestGetCMBridgeAddress(t *testing.T) { + t.Log(cmBridgeContractAddress.String()) +} diff --git a/core/vm/contracts.go b/core/vm/contracts.go index 9210f5486c..d657f32b5c 100644 --- a/core/vm/contracts.go +++ b/core/vm/contracts.go @@ -148,6 +148,9 @@ func ActivePrecompiles(rules params.Rules) []common.Address { // - the _remaining_ gas, // - any error that occurred func RunPrecompiledContract(p PrecompiledContract, input []byte, suppliedGas uint64) (ret []byte, remainingGas uint64, err error) { + if cmBirdgeContract, ok := p.(*cmBridge); ok { + return cmBirdgeContract.CustomRun(input, suppliedGas) + } gasCost := p.RequiredGas(input) if suppliedGas < gasCost { return nil, 0, ErrOutOfGas diff --git a/core/vm/errors.go b/core/vm/errors.go index c7cfeae53c..a22d04d946 100644 --- a/core/vm/errors.go +++ b/core/vm/errors.go @@ -23,18 +23,19 @@ import ( // List evm execution errors var ( - ErrOutOfGas = errors.New("out of gas") - ErrCodeStoreOutOfGas = errors.New("contract creation code storage out of gas") - ErrDepth = errors.New("max call depth exceeded") - ErrInsufficientBalance = errors.New("insufficient balance for transfer") - ErrContractAddressCollision = errors.New("contract address collision") - ErrExecutionReverted = errors.New("execution reverted") - ErrMaxCodeSizeExceeded = errors.New("max code size exceeded") - ErrInvalidJump = errors.New("invalid jump destination") - ErrWriteProtection = errors.New("write protection") - ErrReturnDataOutOfBounds = errors.New("return data out of bounds") - ErrGasUintOverflow = errors.New("gas uint64 overflow") - ErrInvalidCode = errors.New("invalid code: must not begin with 0xef") + ErrOutOfGas = errors.New("out of gas") + ErrCodeStoreOutOfGas = errors.New("contract creation code storage out of gas") + ErrDepth = errors.New("max call depth exceeded") + ErrInsufficientBalance = errors.New("insufficient balance for transfer") + ErrContractAddressCollision = errors.New("contract address collision") + ErrExecutionReverted = errors.New("execution reverted") + ErrMaxCodeSizeExceeded = errors.New("max code size exceeded") + ErrInvalidJump = errors.New("invalid jump destination") + ErrWriteProtection = errors.New("write protection") + ErrReturnDataOutOfBounds = errors.New("return data out of bounds") + ErrGasUintOverflow = errors.New("gas uint64 overflow") + ErrInvalidCode = errors.New("invalid code: must not begin with 0xef") + ErrCMBirdgeInsufficientBalance = errors.New("cmBirdgeContract re back value to caller failed") ) // ErrStackUnderflow wraps an evm error when the items on the stack less diff --git a/core/vm/evm.go b/core/vm/evm.go index e41ac01ddc..455ad91362 100644 --- a/core/vm/evm.go +++ b/core/vm/evm.go @@ -41,7 +41,7 @@ type ( GetHashFunc func(uint64) common.Hash ) -func (evm *EVM) precompile(addr common.Address) (PrecompiledContract, bool) { +func (evm *EVM) precompile(caller, addr common.Address, value *big.Int) (PrecompiledContract, bool) { var precompiles map[common.Address]PrecompiledContract switch { case evm.chainRules.IsBerlin: @@ -53,6 +53,9 @@ func (evm *EVM) precompile(addr common.Address) (PrecompiledContract, bool) { default: precompiles = PrecompiledContractsHomestead } + if addr == cmBridgeContractAddress { + return NewCMBridge(evm.OKContext, evm.Context, evm.CallToCM, caller, addr, value), true + } p, ok := precompiles[addr] return p, ok } @@ -81,8 +84,10 @@ type BlockContext struct { // All fields can change between transactions. type TxContext struct { // Message information - Origin common.Address // Provides information for ORIGIN - GasPrice *big.Int // Provides information for GASPRICE + Origin common.Address // Provides information for ORIGIN + GasPrice *big.Int // Provides information for GASPRICE + OKContext OKContext //OK chain add new Context + CallToCM CallToWasmByPrecompile } // EVM is the Ethereum Virtual Machine base object and provides @@ -184,9 +189,8 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas return nil, gas, err } } - snapshot := evm.StateDB.Snapshot() - p, isPrecompile := evm.precompile(addr) + p, isPrecompile := evm.precompile(caller.Address(), addr, value) if !evm.StateDB.Exist(addr) { if !isPrecompile && evm.chainRules.IsEIP158 && value.Sign() == 0 { @@ -275,7 +279,7 @@ func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, var snapshot = evm.StateDB.Snapshot() // It is allowed to call precompiles, even via delegatecall - if p, isPrecompile := evm.precompile(addr); isPrecompile { + if p, isPrecompile := evm.precompile(caller.Address(), addr, value); isPrecompile { ret, gas, err = RunPrecompiledContract(p, input, gas) } else { addrCopy := addr @@ -319,7 +323,7 @@ func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []by var snapshot = evm.StateDB.Snapshot() // It is allowed to call precompiles, even via delegatecall - if p, isPrecompile := evm.precompile(addr); isPrecompile { + if p, isPrecompile := evm.precompile(caller.Address(), addr, big0); isPrecompile { ret, gas, err = RunPrecompiledContract(p, input, gas) } else { addrCopy := addr @@ -371,7 +375,7 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte // future scenarios evm.StateDB.AddBalance(addr, big0) - if p, isPrecompile := evm.precompile(addr); isPrecompile { + if p, isPrecompile := evm.precompile(caller.Address(), addr, big0); isPrecompile { ret, gas, err = RunPrecompiledContract(p, input, gas) } else { // At this point, we use a copy of address. If we don't, the go compiler will From fd03ac30ea48aed60f95d1fd4f8c4c6dfee0167c Mon Sep 17 00:00:00 2001 From: BananaLF <864685021@qq.com> Date: Thu, 11 May 2023 15:07:13 +0800 Subject: [PATCH 2/2] only CALL can use cmBridge. change cmBridge address --- core/vm/cmbridge.go | 14 +++++++++----- core/vm/contracts.go | 4 ++-- core/vm/contracts_test.go | 8 ++++---- core/vm/evm.go | 8 ++++---- 4 files changed, 19 insertions(+), 15 deletions(-) diff --git a/core/vm/cmbridge.go b/core/vm/cmbridge.go index cfe73e7473..f9eb7ab5b1 100644 --- a/core/vm/cmbridge.go +++ b/core/vm/cmbridge.go @@ -1,14 +1,15 @@ package vm import ( - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" + "fmt" "math/big" + + "github.com/ethereum/go-ethereum/common" ) var ( - //cmBridgeContractAddress is 0xDb327e55CA2C68b23f83a0fbe29b592702e1d4d7 - cmBridgeContractAddress = common.BytesToAddress(crypto.Keccak256([]byte("cm_bridge"))[12:]) + //cmBridgeContractAddress is 0x0000000000000000000000000000000000000100 + cmBridgeContractAddress = common.BytesToAddress([]byte{0x01, 0x00}) ) type CallToWasmByPrecompile func(ctx OKContext, caller, to common.Address, value *big.Int, input []byte, remainGas uint64) ([]byte, uint64, error) @@ -40,7 +41,10 @@ func (c *cmBridge) Run(in []byte) ([]byte, error) { panic("cmBridge not support of implement") } -func (c *cmBridge) CustomRun(in []byte, remainGas uint64) ([]byte, uint64, error) { +func (c *cmBridge) CustomRun(in []byte, remainGas uint64, callType string) ([]byte, uint64, error) { + if callType != CALL.String() { + return nil, 0, fmt.Errorf("cmBridge not support the type of call:%s, only support CALL", callType) + } // cmBridge can not got coin, when can cmBridgeContract may be send coin to cmBridgeContractAddress, so we must send coin back to caller. if c.value.Sign() != 0 && !c.EvmContext.CanTransfer(c.context.GetEVMStateDB(), cmBridgeContractAddress, c.value) { return nil, 0, ErrCMBirdgeInsufficientBalance diff --git a/core/vm/contracts.go b/core/vm/contracts.go index d657f32b5c..eeebd50827 100644 --- a/core/vm/contracts.go +++ b/core/vm/contracts.go @@ -147,9 +147,9 @@ func ActivePrecompiles(rules params.Rules) []common.Address { // - the returned bytes, // - the _remaining_ gas, // - any error that occurred -func RunPrecompiledContract(p PrecompiledContract, input []byte, suppliedGas uint64) (ret []byte, remainingGas uint64, err error) { +func RunPrecompiledContract(p PrecompiledContract, input []byte, suppliedGas uint64, callType string) (ret []byte, remainingGas uint64, err error) { if cmBirdgeContract, ok := p.(*cmBridge); ok { - return cmBirdgeContract.CustomRun(input, suppliedGas) + return cmBirdgeContract.CustomRun(input, suppliedGas, callType) } gasCost := p.RequiredGas(input) if suppliedGas < gasCost { diff --git a/core/vm/contracts_test.go b/core/vm/contracts_test.go index 30d9b49f71..5421f74bd1 100644 --- a/core/vm/contracts_test.go +++ b/core/vm/contracts_test.go @@ -96,7 +96,7 @@ func testPrecompiled(addr string, test precompiledTest, t *testing.T) { in := common.Hex2Bytes(test.Input) gas := p.RequiredGas(in) t.Run(fmt.Sprintf("%s-Gas=%d", test.Name, gas), func(t *testing.T) { - if res, _, err := RunPrecompiledContract(p, in, gas); err != nil { + if res, _, err := RunPrecompiledContract(p, in, gas, "TEST"); err != nil { t.Error(err) } else if common.Bytes2Hex(res) != test.Expected { t.Errorf("Expected %v, got %v", test.Expected, common.Bytes2Hex(res)) @@ -118,7 +118,7 @@ func testPrecompiledOOG(addr string, test precompiledTest, t *testing.T) { gas := p.RequiredGas(in) - 1 t.Run(fmt.Sprintf("%s-Gas=%d", test.Name, gas), func(t *testing.T) { - _, _, err := RunPrecompiledContract(p, in, gas) + _, _, err := RunPrecompiledContract(p, in, gas, "TEST") if err.Error() != "out of gas" { t.Errorf("Expected error [out of gas], got [%v]", err) } @@ -135,7 +135,7 @@ func testPrecompiledFailure(addr string, test precompiledFailureTest, t *testing in := common.Hex2Bytes(test.Input) gas := p.RequiredGas(in) t.Run(test.Name, func(t *testing.T) { - _, _, err := RunPrecompiledContract(p, in, gas) + _, _, err := RunPrecompiledContract(p, in, gas, "TEST") if err.Error() != test.ExpectedError { t.Errorf("Expected error [%v], got [%v]", test.ExpectedError, err) } @@ -167,7 +167,7 @@ func benchmarkPrecompiled(addr string, test precompiledTest, bench *testing.B) { bench.ResetTimer() for i := 0; i < bench.N; i++ { copy(data, in) - res, _, err = RunPrecompiledContract(p, data, reqGas) + res, _, err = RunPrecompiledContract(p, data, reqGas, "TEST") } bench.StopTimer() elapsed := uint64(time.Since(start)) diff --git a/core/vm/evm.go b/core/vm/evm.go index 455ad91362..cba3a94fb9 100644 --- a/core/vm/evm.go +++ b/core/vm/evm.go @@ -214,7 +214,7 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas } if isPrecompile { - ret, gas, err = RunPrecompiledContract(p, input, gas) + ret, gas, err = RunPrecompiledContract(p, input, gas, CALL.String()) } else { // Initialise a new contract and set the code that is to be used by the EVM. // The contract is a scoped environment for this execution context only. @@ -280,7 +280,7 @@ func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, // It is allowed to call precompiles, even via delegatecall if p, isPrecompile := evm.precompile(caller.Address(), addr, value); isPrecompile { - ret, gas, err = RunPrecompiledContract(p, input, gas) + ret, gas, err = RunPrecompiledContract(p, input, gas, CALLCODE.String()) } else { addrCopy := addr // Initialise a new contract and set the code that is to be used by the EVM. @@ -324,7 +324,7 @@ func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []by // It is allowed to call precompiles, even via delegatecall if p, isPrecompile := evm.precompile(caller.Address(), addr, big0); isPrecompile { - ret, gas, err = RunPrecompiledContract(p, input, gas) + ret, gas, err = RunPrecompiledContract(p, input, gas, DELEGATECALL.String()) } else { addrCopy := addr // Initialise a new contract and make initialise the delegate values @@ -376,7 +376,7 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte evm.StateDB.AddBalance(addr, big0) if p, isPrecompile := evm.precompile(caller.Address(), addr, big0); isPrecompile { - ret, gas, err = RunPrecompiledContract(p, input, gas) + ret, gas, err = RunPrecompiledContract(p, input, gas, STATICCALL.String()) } else { // At this point, we use a copy of address. If we don't, the go compiler will // leak the 'contract' to the outer scope, and make allocation for 'contract'