diff --git a/core/state_transition.go b/core/state_transition.go index 72f975775c1b..b64c247ae09d 100644 --- a/core/state_transition.go +++ b/core/state_transition.go @@ -361,7 +361,7 @@ func (st *StateTransition) TransitionDb() (*ExecutionResult, error) { // Execute the preparatory steps for state transition which includes: // - prepare accessList(post-berlin) // - reset transient storage(eip 1153) - st.state.Prepare(rules, msg.From, st.evm.Context.Coinbase, msg.To, vm.ActivePrecompiles(rules), msg.AccessList) + st.state.Prepare(rules, msg.From, st.evm.Context.Coinbase, msg.To, st.evm.ActivePrecompiles(rules), msg.AccessList) var ( ret []byte diff --git a/core/vm/contract.go b/core/vm/contract.go index bb0902969ec7..cf820ce274a7 100644 --- a/core/vm/contract.go +++ b/core/vm/contract.go @@ -25,6 +25,7 @@ import ( // ContractRef is a reference to the contract's backing object type ContractRef interface { + // Address returns the contract's address Address() common.Address } @@ -58,12 +59,13 @@ type Contract struct { CodeAddr *common.Address Input []byte - Gas uint64 - value *big.Int + Gas uint64 + value *big.Int + isPrecompile bool } // NewContract returns a new contract environment for the execution of EVM. -func NewContract(caller ContractRef, object ContractRef, value *big.Int, gas uint64) *Contract { +func NewContract(caller, object ContractRef, value *big.Int, gas uint64) *Contract { c := &Contract{CallerAddress: caller.Address(), caller: caller, self: object} if parent, ok := caller.(*Contract); ok { @@ -82,7 +84,34 @@ func NewContract(caller ContractRef, object ContractRef, value *big.Int, gas uin return c } +// NewPrecompile returns a new instance of a precompiled contract environment for the execution of EVM. +func NewPrecompile(caller, object ContractRef, value *big.Int, gas uint64) *Contract { + c := &Contract{ + CallerAddress: caller.Address(), + caller: caller, + self: object, + isPrecompile: true, + } + + // Gas should be a pointer so it can safely be reduced through the run + // This pointer will be off the state transition + c.Gas = gas + // ensures a value is set + c.value = value + + return c +} + +// IsPrecompile returns true if the contract is a precompiled contract environment +func (c Contract) IsPrecompile() bool { + return c.isPrecompile +} + func (c *Contract) validJumpdest(dest *uint256.Int) bool { + if c.isPrecompile { + return false + } + udest, overflow := dest.Uint64WithOverflow() // PC cannot go beyond len(code) and certainly can't be bigger than 63bits. // Don't bother checking for JUMPDEST in that case. @@ -99,6 +128,10 @@ func (c *Contract) validJumpdest(dest *uint256.Int) bool { // isCode returns true if the provided PC location is an actual opcode, as // opposed to a data-segment following a PUSHN operation. func (c *Contract) isCode(udest uint64) bool { + if c.isPrecompile { + return false + } + // Do we already have an analysis laying around? if c.analysis != nil { return c.analysis.codeSegment(udest) @@ -132,6 +165,9 @@ func (c *Contract) isCode(udest uint64) bool { // AsDelegate sets the contract to be a delegate call and returns the current // contract (for chaining calls) func (c *Contract) AsDelegate() *Contract { + if c.isPrecompile { + return c + } // NOTE: caller must, at all times be a contract. It should never happen // that caller is something other than a Contract. parent := c.caller.(*Contract) @@ -180,6 +216,10 @@ func (c *Contract) Value() *big.Int { // SetCallCode sets the code of the contract and address of the backing data // object func (c *Contract) SetCallCode(addr *common.Address, hash common.Hash, code []byte) { + if c.isPrecompile { + return + } + c.Code = code c.CodeHash = hash c.CodeAddr = addr @@ -188,6 +228,10 @@ func (c *Contract) SetCallCode(addr *common.Address, hash common.Hash, code []by // SetCodeOptionalHash can be used to provide code, but it's optional to provide hash. // In case hash is not provided, the jumpdest analysis will not be saved to the parent context func (c *Contract) SetCodeOptionalHash(addr *common.Address, codeAndHash *codeAndHash) { + if c.isPrecompile { + return + } + c.Code = codeAndHash.code c.CodeHash = codeAndHash.hash c.CodeAddr = addr diff --git a/core/vm/contracts.go b/core/vm/contracts.go index aa4a3f13df5e..c8d9a2592ed8 100644 --- a/core/vm/contracts.go +++ b/core/vm/contracts.go @@ -17,9 +17,11 @@ package vm import ( + "bytes" "crypto/sha256" "encoding/binary" "errors" + "fmt" "math/big" "github.com/ethereum/go-ethereum/common" @@ -36,98 +38,128 @@ import ( // requires a deterministic gas count based on the input size of the Run method of the // contract. type PrecompiledContract interface { - RequiredGas(input []byte) uint64 // RequiredPrice calculates the contract gas use - Run(input []byte) ([]byte, error) // Run runs the precompiled contract + ContractRef + // RequiredPrice calculates the contract gas used + RequiredGas(input []byte) uint64 + // Run runs the precompiled contract + Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) } // PrecompiledContractsHomestead contains the default set of pre-compiled Ethereum // contracts used in the Frontier and Homestead releases. var PrecompiledContractsHomestead = map[common.Address]PrecompiledContract{ - common.BytesToAddress([]byte{1}): &ecrecover{}, - common.BytesToAddress([]byte{2}): &sha256hash{}, - common.BytesToAddress([]byte{3}): &ripemd160hash{}, - common.BytesToAddress([]byte{4}): &dataCopy{}, + ecrecover{}.Address(): &ecrecover{}, + sha256hash{}.Address(): &sha256hash{}, + ripemd160hash{}.Address(): &ripemd160hash{}, + dataCopy{}.Address(): &dataCopy{}, } // PrecompiledContractsByzantium contains the default set of pre-compiled Ethereum // contracts used in the Byzantium release. var PrecompiledContractsByzantium = map[common.Address]PrecompiledContract{ - common.BytesToAddress([]byte{1}): &ecrecover{}, - common.BytesToAddress([]byte{2}): &sha256hash{}, - common.BytesToAddress([]byte{3}): &ripemd160hash{}, - common.BytesToAddress([]byte{4}): &dataCopy{}, - common.BytesToAddress([]byte{5}): &bigModExp{eip2565: false}, - common.BytesToAddress([]byte{6}): &bn256AddByzantium{}, - common.BytesToAddress([]byte{7}): &bn256ScalarMulByzantium{}, - common.BytesToAddress([]byte{8}): &bn256PairingByzantium{}, + ecrecover{}.Address(): &ecrecover{}, + sha256hash{}.Address(): &sha256hash{}, + ripemd160hash{}.Address(): &ripemd160hash{}, + dataCopy{}.Address(): &dataCopy{}, + bigModExp{}.Address(): &bigModExp{eip2565: false}, + bn256AddByzantium{}.Address(): &bn256AddByzantium{}, + bn256ScalarMulByzantium{}.Address(): &bn256ScalarMulByzantium{}, + bn256PairingByzantium{}.Address(): &bn256PairingByzantium{}, } // PrecompiledContractsIstanbul contains the default set of pre-compiled Ethereum // contracts used in the Istanbul release. var PrecompiledContractsIstanbul = map[common.Address]PrecompiledContract{ - common.BytesToAddress([]byte{1}): &ecrecover{}, - common.BytesToAddress([]byte{2}): &sha256hash{}, - common.BytesToAddress([]byte{3}): &ripemd160hash{}, - common.BytesToAddress([]byte{4}): &dataCopy{}, - common.BytesToAddress([]byte{5}): &bigModExp{eip2565: false}, - common.BytesToAddress([]byte{6}): &bn256AddIstanbul{}, - common.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{}, - common.BytesToAddress([]byte{8}): &bn256PairingIstanbul{}, - common.BytesToAddress([]byte{9}): &blake2F{}, + ecrecover{}.Address(): &ecrecover{}, + sha256hash{}.Address(): &sha256hash{}, + ripemd160hash{}.Address(): &ripemd160hash{}, + dataCopy{}.Address(): &dataCopy{}, + bigModExp{}.Address(): &bigModExp{eip2565: false}, + bn256AddIstanbul{}.Address(): &bn256AddIstanbul{}, + bn256ScalarMulIstanbul{}.Address(): &bn256ScalarMulIstanbul{}, + bn256PairingIstanbul{}.Address(): &bn256PairingIstanbul{}, + blake2F{}.Address(): &blake2F{}, } // PrecompiledContractsBerlin contains the default set of pre-compiled Ethereum // contracts used in the Berlin release. var PrecompiledContractsBerlin = map[common.Address]PrecompiledContract{ - common.BytesToAddress([]byte{1}): &ecrecover{}, - common.BytesToAddress([]byte{2}): &sha256hash{}, - common.BytesToAddress([]byte{3}): &ripemd160hash{}, - common.BytesToAddress([]byte{4}): &dataCopy{}, - common.BytesToAddress([]byte{5}): &bigModExp{eip2565: true}, - common.BytesToAddress([]byte{6}): &bn256AddIstanbul{}, - common.BytesToAddress([]byte{7}): &bn256ScalarMulIstanbul{}, - common.BytesToAddress([]byte{8}): &bn256PairingIstanbul{}, - common.BytesToAddress([]byte{9}): &blake2F{}, + ecrecover{}.Address(): &ecrecover{}, + sha256hash{}.Address(): &sha256hash{}, + ripemd160hash{}.Address(): &ripemd160hash{}, + dataCopy{}.Address(): &dataCopy{}, + bigModExp{}.Address(): &bigModExp{eip2565: true}, + bn256AddIstanbul{}.Address(): &bn256AddIstanbul{}, + bn256ScalarMulIstanbul{}.Address(): &bn256ScalarMulIstanbul{}, + bn256PairingIstanbul{}.Address(): &bn256PairingIstanbul{}, + blake2F{}.Address(): &blake2F{}, } // PrecompiledContractsBLS contains the set of pre-compiled Ethereum // contracts specified in EIP-2537. These are exported for testing purposes. var PrecompiledContractsBLS = map[common.Address]PrecompiledContract{ - common.BytesToAddress([]byte{10}): &bls12381G1Add{}, - common.BytesToAddress([]byte{11}): &bls12381G1Mul{}, - common.BytesToAddress([]byte{12}): &bls12381G1MultiExp{}, - common.BytesToAddress([]byte{13}): &bls12381G2Add{}, - common.BytesToAddress([]byte{14}): &bls12381G2Mul{}, - common.BytesToAddress([]byte{15}): &bls12381G2MultiExp{}, - common.BytesToAddress([]byte{16}): &bls12381Pairing{}, - common.BytesToAddress([]byte{17}): &bls12381MapG1{}, - common.BytesToAddress([]byte{18}): &bls12381MapG2{}, + bls12381G1Add{}.Address(): &bls12381G1Add{}, + bls12381G1Mul{}.Address(): &bls12381G1Mul{}, + bls12381G1MultiExp{}.Address(): &bls12381G1MultiExp{}, + bls12381G2Add{}.Address(): &bls12381G2Add{}, + bls12381G2Mul{}.Address(): &bls12381G2Mul{}, + bls12381G2MultiExp{}.Address(): &bls12381G2MultiExp{}, + bls12381Pairing{}.Address(): &bls12381Pairing{}, + bls12381MapG1{}.Address(): &bls12381MapG1{}, + bls12381MapG2{}.Address(): &bls12381MapG2{}, } var ( - PrecompiledAddressesBerlin []common.Address - PrecompiledAddressesIstanbul []common.Address - PrecompiledAddressesByzantium []common.Address - PrecompiledAddressesHomestead []common.Address -) - -func init() { - for k := range PrecompiledContractsHomestead { - PrecompiledAddressesHomestead = append(PrecompiledAddressesHomestead, k) + // PrecompiledAddressesBerlin defines the default set of pre-compiled + // Ethereum contract addresses used in the Berlin release. + PrecompiledAddressesBerlin = []common.Address{ + ecrecover{}.Address(), + sha256hash{}.Address(), + ripemd160hash{}.Address(), + dataCopy{}.Address(), + bigModExp{}.Address(), + bn256AddIstanbul{}.Address(), + bn256ScalarMulIstanbul{}.Address(), + bn256PairingIstanbul{}.Address(), + blake2F{}.Address(), } - for k := range PrecompiledContractsByzantium { - PrecompiledAddressesByzantium = append(PrecompiledAddressesByzantium, k) + // PrecompiledAddressesIstanbul defines the default set of pre-compiled + // Ethereum contract addresses used in the Istanbul release. + PrecompiledAddressesIstanbul = []common.Address{ + ecrecover{}.Address(), + sha256hash{}.Address(), + ripemd160hash{}.Address(), + dataCopy{}.Address(), + bigModExp{}.Address(), + bn256AddIstanbul{}.Address(), + bn256ScalarMulIstanbul{}.Address(), + bn256PairingIstanbul{}.Address(), + blake2F{}.Address(), } - for k := range PrecompiledContractsIstanbul { - PrecompiledAddressesIstanbul = append(PrecompiledAddressesIstanbul, k) + // PrecompiledAddressesByzantium defines the default set of pre-compiled + // Ethereum contract addresses used in the Byzantium release. + PrecompiledAddressesByzantium = []common.Address{ + ecrecover{}.Address(), + sha256hash{}.Address(), + ripemd160hash{}.Address(), + dataCopy{}.Address(), + bigModExp{}.Address(), + bn256AddByzantium{}.Address(), + bn256ScalarMulByzantium{}.Address(), + bn256PairingByzantium{}.Address(), } - for k := range PrecompiledContractsBerlin { - PrecompiledAddressesBerlin = append(PrecompiledAddressesBerlin, k) + // PrecompiledAddressesHomestead defines the default set of pre-compiled + // Ethereum contract addresses used in the Homestead release. + PrecompiledAddressesHomestead = []common.Address{ + ecrecover{}.Address(), + sha256hash{}.Address(), + ripemd160hash{}.Address(), + dataCopy{}.Address(), } -} +) -// ActivePrecompiles returns the precompiles enabled with the current configuration. -func ActivePrecompiles(rules params.Rules) []common.Address { +// DefaultActivePrecompiles returns the set of precompiles enabled with the default configuration. +func DefaultActivePrecompiles(rules params.Rules) []common.Address { switch { case rules.IsBerlin: return PrecompiledAddressesBerlin @@ -140,50 +172,163 @@ func ActivePrecompiles(rules params.Rules) []common.Address { } } +// DefaultPrecompiles define the mapping of address and precompiles from the default configuration +func DefaultPrecompiles(rules params.Rules) (precompiles map[common.Address]PrecompiledContract) { + switch { + case rules.IsBerlin: + precompiles = PrecompiledContractsBerlin + case rules.IsIstanbul: + precompiles = PrecompiledContractsIstanbul + case rules.IsByzantium: + precompiles = PrecompiledContractsByzantium + default: + precompiles = PrecompiledContractsHomestead + } + + return precompiles +} + +// ActivePrecompiles returns the precompiles enabled with the current configuration. +// +// NOTE: The rules argument is ignored as the active precompiles can be set via the WithPrecompiles +// method according to the chain rules from the current block context. +func (evm *EVM) ActivePrecompiles(_ params.Rules) []common.Address { + return evm.activePrecompiles +} + +// Precompile returns a precompiled contract for the given address. This +// function returns false if the address is not a registered precompile. +func (evm *EVM) Precompile(addr common.Address) (PrecompiledContract, bool) { + p, ok := evm.precompiles[addr] + return p, ok +} + +// WithPrecompiles sets the precompiled contracts and the slice of actives precompiles. +// IMPORTANT: This function does NOT validate the precompiles provided to the EVM. The caller should +// use the ValidatePrecompiles function for this purpose prior to calling WithPrecompiles. +func (evm *EVM) WithPrecompiles( + precompiles map[common.Address]PrecompiledContract, + activePrecompiles []common.Address, +) { + evm.precompiles = precompiles + evm.activePrecompiles = activePrecompiles +} + +// ValidatePrecompiles validates the precompile map against the active +// precompile slice. +// It returns an error if the precompiled contract map has a different length +// than the slice of active contract addresses. This function also checks for +// duplicates, invalid addresses and empty precompile contract instances. +func ValidatePrecompiles( + precompiles map[common.Address]PrecompiledContract, + activePrecompiles []common.Address, +) error { + if len(precompiles) != len(activePrecompiles) { + return fmt.Errorf("precompiles length mismatch (expected %d, got %d)", len(precompiles), len(activePrecompiles)) + } + + dupActivePrecompiles := make(map[common.Address]bool) + + for _, addr := range activePrecompiles { + if dupActivePrecompiles[addr] { + return fmt.Errorf("duplicate active precompile: %s", addr) + } + + precompile, ok := precompiles[addr] + if !ok { + return fmt.Errorf("active precompile address doesn't exist in precompiles map: %s", addr) + } + + if precompile == nil { + return fmt.Errorf("precompile contract cannot be nil: %s", addr) + } + + if bytes.Equal(addr.Bytes(), common.Address{}.Bytes()) { + return fmt.Errorf("precompile cannot be the zero address: %s", addr) + } + + dupActivePrecompiles[addr] = true + } + + return nil +} + // RunPrecompiledContract runs and evaluates the output of a precompiled contract. // It returns // - 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 (evm *EVM) RunPrecompiledContract( + p PrecompiledContract, + caller ContractRef, + input []byte, + suppliedGas uint64, + value *big.Int, + readOnly bool, +) (ret []byte, remainingGas uint64, err error) { + return runPrecompiledContract(evm, p, caller, input, suppliedGas, value, readOnly) +} + +func runPrecompiledContract( + evm *EVM, + p PrecompiledContract, + caller ContractRef, + input []byte, + suppliedGas uint64, + value *big.Int, + readOnly bool, +) (ret []byte, remainingGas uint64, err error) { + addrCopy := p.Address() + inputCopy := make([]byte, len(input)) + copy(inputCopy, input) + + contract := NewPrecompile(caller, AccountRef(addrCopy), value, suppliedGas) + contract.Input = inputCopy + gasCost := p.RequiredGas(input) - if suppliedGas < gasCost { - return nil, 0, ErrOutOfGas + if !contract.UseGas(gasCost) { + return nil, contract.Gas, ErrOutOfGas } - suppliedGas -= gasCost - output, err := p.Run(input) - return output, suppliedGas, err + + output, err := p.Run(evm, contract, readOnly) + return output, contract.Gas, err } // ECRECOVER implemented as a native contract. type ecrecover struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (ecrecover) Address() common.Address { + return common.BytesToAddress([]byte{1}) +} + func (c *ecrecover) RequiredGas(input []byte) uint64 { return params.EcrecoverGas } -func (c *ecrecover) Run(input []byte) ([]byte, error) { +func (c *ecrecover) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { const ecRecoverInputLength = 128 - input = common.RightPadBytes(input, ecRecoverInputLength) + contract.Input = common.RightPadBytes(contract.Input, ecRecoverInputLength) // "input" is (hash, v, r, s), each 32 bytes // but for ecrecover we want (r, s, v) - r := new(big.Int).SetBytes(input[64:96]) - s := new(big.Int).SetBytes(input[96:128]) - v := input[63] - 27 + r := new(big.Int).SetBytes(contract.Input[64:96]) + s := new(big.Int).SetBytes(contract.Input[96:128]) + v := contract.Input[63] - 27 // tighter sig s values input homestead only apply to tx sigs - if !allZero(input[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) { + if !allZero(contract.Input[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) { return nil, nil } // We must make sure not to modify the 'input', so placing the 'v' along with // the signature needs to be done on a new allocation sig := make([]byte, 65) - copy(sig, input[64:128]) + copy(sig, contract.Input[64:128]) sig[64] = v // v needs to be at the end for libsecp256k1 - pubKey, err := crypto.Ecrecover(input[:32], sig) + pubKey, err := crypto.Ecrecover(contract.Input[:32], sig) // make sure the public key is a valid one if err != nil { return nil, nil @@ -196,6 +341,12 @@ func (c *ecrecover) Run(input []byte) ([]byte, error) { // SHA256 implemented as a native contract. type sha256hash struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (sha256hash) Address() common.Address { + return common.BytesToAddress([]byte{2}) +} + // 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 @@ -203,14 +354,21 @@ type sha256hash struct{} func (c *sha256hash) RequiredGas(input []byte) uint64 { return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas } -func (c *sha256hash) Run(input []byte) ([]byte, error) { - h := sha256.Sum256(input) + +func (c *sha256hash) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { + h := sha256.Sum256(contract.Input) return h[:], nil } // RIPEMD160 implemented as a native contract. type ripemd160hash struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (ripemd160hash) Address() common.Address { + return common.BytesToAddress([]byte{3}) +} + // 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 @@ -218,15 +376,22 @@ type ripemd160hash struct{} func (c *ripemd160hash) RequiredGas(input []byte) uint64 { return uint64(len(input)+31)/32*params.Ripemd160PerWordGas + params.Ripemd160BaseGas } -func (c *ripemd160hash) Run(input []byte) ([]byte, error) { + +func (c *ripemd160hash) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { ripemd := ripemd160.New() - ripemd.Write(input) + ripemd.Write(contract.Input) return common.LeftPadBytes(ripemd.Sum(nil), 32), nil } // data copy implemented as a native contract. type dataCopy struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (dataCopy) Address() common.Address { + return common.BytesToAddress([]byte{4}) +} + // 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 @@ -234,8 +399,9 @@ type dataCopy struct{} func (c *dataCopy) RequiredGas(input []byte) uint64 { return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas } -func (c *dataCopy) Run(in []byte) ([]byte, error) { - return common.CopyBytes(in), nil + +func (c *dataCopy) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { + return common.CopyBytes(contract.Input), nil } // bigModExp implements a native big integer exponential modular operation. @@ -289,6 +455,12 @@ func modexpMultComplexity(x *big.Int) *big.Int { return x } +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bigModExp) Address() common.Address { + return common.BytesToAddress([]byte{5}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bigModExp) RequiredGas(input []byte) uint64 { var ( @@ -360,16 +532,16 @@ func (c *bigModExp) RequiredGas(input []byte) uint64 { return gas.Uint64() } -func (c *bigModExp) Run(input []byte) ([]byte, error) { +func (c *bigModExp) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { var ( - baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64() - expLen = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64() - modLen = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64() + baseLen = new(big.Int).SetBytes(getData(contract.Input, 0, 32)).Uint64() + expLen = new(big.Int).SetBytes(getData(contract.Input, 32, 32)).Uint64() + modLen = new(big.Int).SetBytes(getData(contract.Input, 64, 32)).Uint64() ) - if len(input) > 96 { - input = input[96:] + if len(contract.Input) > 96 { + contract.Input = contract.Input[96:] } else { - input = input[:0] + contract.Input = contract.Input[:0] } // Handle a special case when both the base and mod length is zero if baseLen == 0 && modLen == 0 { @@ -377,9 +549,9 @@ func (c *bigModExp) Run(input []byte) ([]byte, error) { } // Retrieve the operands and execute the exponentiation var ( - base = new(big.Int).SetBytes(getData(input, 0, baseLen)) - exp = new(big.Int).SetBytes(getData(input, baseLen, expLen)) - mod = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen)) + base = new(big.Int).SetBytes(getData(contract.Input, 0, baseLen)) + exp = new(big.Int).SetBytes(getData(contract.Input, baseLen, expLen)) + mod = new(big.Int).SetBytes(getData(contract.Input, baseLen+expLen, modLen)) v []byte ) switch { @@ -435,26 +607,38 @@ func runBn256Add(input []byte) ([]byte, error) { // Istanbul consensus rules. type bn256AddIstanbul struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bn256AddIstanbul) Address() common.Address { + return common.BytesToAddress([]byte{6}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bn256AddIstanbul) RequiredGas(input []byte) uint64 { return params.Bn256AddGasIstanbul } -func (c *bn256AddIstanbul) Run(input []byte) ([]byte, error) { - return runBn256Add(input) +func (c *bn256AddIstanbul) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { + return runBn256Add(contract.Input) } // bn256AddByzantium implements a native elliptic curve point addition // conforming to Byzantium consensus rules. type bn256AddByzantium struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bn256AddByzantium) Address() common.Address { + return common.BytesToAddress([]byte{6}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bn256AddByzantium) RequiredGas(input []byte) uint64 { return params.Bn256AddGasByzantium } -func (c *bn256AddByzantium) Run(input []byte) ([]byte, error) { - return runBn256Add(input) +func (c *bn256AddByzantium) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { + return runBn256Add(contract.Input) } // runBn256ScalarMul implements the Bn256ScalarMul precompile, referenced by @@ -473,26 +657,38 @@ func runBn256ScalarMul(input []byte) ([]byte, error) { // multiplication conforming to Istanbul consensus rules. type bn256ScalarMulIstanbul struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bn256ScalarMulIstanbul) Address() common.Address { + return common.BytesToAddress([]byte{7}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bn256ScalarMulIstanbul) RequiredGas(input []byte) uint64 { return params.Bn256ScalarMulGasIstanbul } -func (c *bn256ScalarMulIstanbul) Run(input []byte) ([]byte, error) { - return runBn256ScalarMul(input) +func (c *bn256ScalarMulIstanbul) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { + return runBn256ScalarMul(contract.Input) } // bn256ScalarMulByzantium implements a native elliptic curve scalar // multiplication conforming to Byzantium consensus rules. type bn256ScalarMulByzantium struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bn256ScalarMulByzantium) Address() common.Address { + return common.BytesToAddress([]byte{7}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bn256ScalarMulByzantium) RequiredGas(input []byte) uint64 { return params.Bn256ScalarMulGasByzantium } -func (c *bn256ScalarMulByzantium) Run(input []byte) ([]byte, error) { - return runBn256ScalarMul(input) +func (c *bn256ScalarMulByzantium) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { + return runBn256ScalarMul(contract.Input) } var ( @@ -541,30 +737,48 @@ func runBn256Pairing(input []byte) ([]byte, error) { // conforming to Istanbul consensus rules. type bn256PairingIstanbul struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bn256PairingIstanbul) Address() common.Address { + return common.BytesToAddress([]byte{8}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bn256PairingIstanbul) RequiredGas(input []byte) uint64 { return params.Bn256PairingBaseGasIstanbul + uint64(len(input)/192)*params.Bn256PairingPerPointGasIstanbul } -func (c *bn256PairingIstanbul) Run(input []byte) ([]byte, error) { - return runBn256Pairing(input) +func (c *bn256PairingIstanbul) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { + return runBn256Pairing(contract.Input) } // bn256PairingByzantium implements a pairing pre-compile for the bn256 curve // conforming to Byzantium consensus rules. type bn256PairingByzantium struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bn256PairingByzantium) Address() common.Address { + return common.BytesToAddress([]byte{8}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bn256PairingByzantium) RequiredGas(input []byte) uint64 { return params.Bn256PairingBaseGasByzantium + uint64(len(input)/192)*params.Bn256PairingPerPointGasByzantium } -func (c *bn256PairingByzantium) Run(input []byte) ([]byte, error) { - return runBn256Pairing(input) +func (c *bn256PairingByzantium) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { + return runBn256Pairing(contract.Input) } type blake2F struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (blake2F) Address() common.Address { + return common.BytesToAddress([]byte{9}) +} + func (c *blake2F) RequiredGas(input []byte) uint64 { // If the input is malformed, we can't calculate the gas, return 0 and let the // actual call choke and fault. @@ -585,18 +799,18 @@ var ( errBlake2FInvalidFinalFlag = errors.New("invalid final flag") ) -func (c *blake2F) Run(input []byte) ([]byte, error) { +func (c *blake2F) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { // Make sure the input is valid (correct length and final flag) - if len(input) != blake2FInputLength { + if len(contract.Input) != blake2FInputLength { return nil, errBlake2FInvalidInputLength } - if input[212] != blake2FNonFinalBlockBytes && input[212] != blake2FFinalBlockBytes { + if contract.Input[212] != blake2FNonFinalBlockBytes && contract.Input[212] != blake2FFinalBlockBytes { return nil, errBlake2FInvalidFinalFlag } // Parse the input into the Blake2b call parameters var ( - rounds = binary.BigEndian.Uint32(input[0:4]) - final = input[212] == blake2FFinalBlockBytes + rounds = binary.BigEndian.Uint32(contract.Input[0:4]) + final = contract.Input[212] == blake2FFinalBlockBytes h [8]uint64 m [16]uint64 @@ -604,14 +818,14 @@ func (c *blake2F) Run(input []byte) ([]byte, error) { ) for i := 0; i < 8; i++ { offset := 4 + i*8 - h[i] = binary.LittleEndian.Uint64(input[offset : offset+8]) + h[i] = binary.LittleEndian.Uint64(contract.Input[offset : offset+8]) } for i := 0; i < 16; i++ { offset := 68 + i*8 - m[i] = binary.LittleEndian.Uint64(input[offset : offset+8]) + m[i] = binary.LittleEndian.Uint64(contract.Input[offset : offset+8]) } - t[0] = binary.LittleEndian.Uint64(input[196:204]) - t[1] = binary.LittleEndian.Uint64(input[204:212]) + t[0] = binary.LittleEndian.Uint64(contract.Input[196:204]) + t[1] = binary.LittleEndian.Uint64(contract.Input[204:212]) // Execute the compression function, extract and return the result blake2b.F(&h, m, t, final, rounds) @@ -634,16 +848,22 @@ var ( // bls12381G1Add implements EIP-2537 G1Add precompile. type bls12381G1Add struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bls12381G1Add) Address() common.Address { + return common.BytesToAddress([]byte{10}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381G1Add) RequiredGas(input []byte) uint64 { return params.Bls12381G1AddGas } -func (c *bls12381G1Add) Run(input []byte) ([]byte, error) { +func (c *bls12381G1Add) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { // Implements EIP-2537 G1Add precompile. // > G1 addition call expects `256` bytes as an input that is interpreted as byte concatenation of two G1 points (`128` bytes each). // > Output is an encoding of addition operation result - single G1 point (`128` bytes). - if len(input) != 256 { + if len(contract.Input) != 256 { return nil, errBLS12381InvalidInputLength } var err error @@ -653,11 +873,11 @@ func (c *bls12381G1Add) Run(input []byte) ([]byte, error) { g := bls12381.NewG1() // Decode G1 point p_0 - if p0, err = g.DecodePoint(input[:128]); err != nil { + if p0, err = g.DecodePoint(contract.Input[:128]); err != nil { return nil, err } // Decode G1 point p_1 - if p1, err = g.DecodePoint(input[128:]); err != nil { + if p1, err = g.DecodePoint(contract.Input[128:]); err != nil { return nil, err } @@ -672,16 +892,22 @@ func (c *bls12381G1Add) Run(input []byte) ([]byte, error) { // bls12381G1Mul implements EIP-2537 G1Mul precompile. type bls12381G1Mul struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bls12381G1Mul) Address() common.Address { + return common.BytesToAddress([]byte{11}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381G1Mul) RequiredGas(input []byte) uint64 { return params.Bls12381G1MulGas } -func (c *bls12381G1Mul) Run(input []byte) ([]byte, error) { +func (c *bls12381G1Mul) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { // Implements EIP-2537 G1Mul precompile. // > G1 multiplication call expects `160` bytes as an input that is interpreted as byte concatenation of encoding of G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). // > Output is an encoding of multiplication operation result - single G1 point (`128` bytes). - if len(input) != 160 { + if len(contract.Input) != 160 { return nil, errBLS12381InvalidInputLength } var err error @@ -691,11 +917,11 @@ func (c *bls12381G1Mul) Run(input []byte) ([]byte, error) { g := bls12381.NewG1() // Decode G1 point - if p0, err = g.DecodePoint(input[:128]); err != nil { + if p0, err = g.DecodePoint(contract.Input[:128]); err != nil { return nil, err } // Decode scalar value - e := new(big.Int).SetBytes(input[128:]) + e := new(big.Int).SetBytes(contract.Input[128:]) // Compute r = e * p_0 r := g.New() @@ -708,6 +934,12 @@ func (c *bls12381G1Mul) Run(input []byte) ([]byte, error) { // bls12381G1MultiExp implements EIP-2537 G1MultiExp precompile. type bls12381G1MultiExp struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bls12381G1MultiExp) Address() common.Address { + return common.BytesToAddress([]byte{12}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381G1MultiExp) RequiredGas(input []byte) uint64 { // Calculate G1 point, scalar value pair length @@ -727,12 +959,12 @@ func (c *bls12381G1MultiExp) RequiredGas(input []byte) uint64 { return (uint64(k) * params.Bls12381G1MulGas * discount) / 1000 } -func (c *bls12381G1MultiExp) Run(input []byte) ([]byte, error) { +func (c *bls12381G1MultiExp) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { // Implements EIP-2537 G1MultiExp precompile. // G1 multiplication call expects `160*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G1 point (`128` bytes) and encoding of a scalar value (`32` bytes). // Output is an encoding of multiexponentiation operation result - single G1 point (`128` bytes). - k := len(input) / 160 - if len(input) == 0 || len(input)%160 != 0 { + k := len(contract.Input) / 160 + if len(contract.Input) == 0 || len(contract.Input)%160 != 0 { return nil, errBLS12381InvalidInputLength } var err error @@ -747,11 +979,11 @@ func (c *bls12381G1MultiExp) Run(input []byte) ([]byte, error) { off := 160 * i t0, t1, t2 := off, off+128, off+160 // Decode G1 point - if points[i], err = g.DecodePoint(input[t0:t1]); err != nil { + if points[i], err = g.DecodePoint(contract.Input[t0:t1]); err != nil { return nil, err } // Decode scalar value - scalars[i] = new(big.Int).SetBytes(input[t1:t2]) + scalars[i] = new(big.Int).SetBytes(contract.Input[t1:t2]) } // Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1) @@ -765,16 +997,22 @@ func (c *bls12381G1MultiExp) Run(input []byte) ([]byte, error) { // bls12381G2Add implements EIP-2537 G2Add precompile. type bls12381G2Add struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bls12381G2Add) Address() common.Address { + return common.BytesToAddress([]byte{13}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381G2Add) RequiredGas(input []byte) uint64 { return params.Bls12381G2AddGas } -func (c *bls12381G2Add) Run(input []byte) ([]byte, error) { +func (c *bls12381G2Add) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { // Implements EIP-2537 G2Add precompile. // > G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each). // > Output is an encoding of addition operation result - single G2 point (`256` bytes). - if len(input) != 512 { + if len(contract.Input) != 512 { return nil, errBLS12381InvalidInputLength } var err error @@ -785,11 +1023,11 @@ func (c *bls12381G2Add) Run(input []byte) ([]byte, error) { r := g.New() // Decode G2 point p_0 - if p0, err = g.DecodePoint(input[:256]); err != nil { + if p0, err = g.DecodePoint(contract.Input[:256]); err != nil { return nil, err } // Decode G2 point p_1 - if p1, err = g.DecodePoint(input[256:]); err != nil { + if p1, err = g.DecodePoint(contract.Input[256:]); err != nil { return nil, err } @@ -803,16 +1041,22 @@ func (c *bls12381G2Add) Run(input []byte) ([]byte, error) { // bls12381G2Mul implements EIP-2537 G2Mul precompile. type bls12381G2Mul struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bls12381G2Mul) Address() common.Address { + return common.BytesToAddress([]byte{14}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381G2Mul) RequiredGas(input []byte) uint64 { return params.Bls12381G2MulGas } -func (c *bls12381G2Mul) Run(input []byte) ([]byte, error) { +func (c *bls12381G2Mul) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { // Implements EIP-2537 G2MUL precompile logic. // > G2 multiplication call expects `288` bytes as an input that is interpreted as byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). // > Output is an encoding of multiplication operation result - single G2 point (`256` bytes). - if len(input) != 288 { + if len(contract.Input) != 288 { return nil, errBLS12381InvalidInputLength } var err error @@ -822,11 +1066,11 @@ func (c *bls12381G2Mul) Run(input []byte) ([]byte, error) { g := bls12381.NewG2() // Decode G2 point - if p0, err = g.DecodePoint(input[:256]); err != nil { + if p0, err = g.DecodePoint(contract.Input[:256]); err != nil { return nil, err } // Decode scalar value - e := new(big.Int).SetBytes(input[256:]) + e := new(big.Int).SetBytes(contract.Input[256:]) // Compute r = e * p_0 r := g.New() @@ -839,6 +1083,12 @@ func (c *bls12381G2Mul) Run(input []byte) ([]byte, error) { // bls12381G2MultiExp implements EIP-2537 G2MultiExp precompile. type bls12381G2MultiExp struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bls12381G2MultiExp) Address() common.Address { + return common.BytesToAddress([]byte{15}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381G2MultiExp) RequiredGas(input []byte) uint64 { // Calculate G2 point, scalar value pair length @@ -858,12 +1108,12 @@ func (c *bls12381G2MultiExp) RequiredGas(input []byte) uint64 { return (uint64(k) * params.Bls12381G2MulGas * discount) / 1000 } -func (c *bls12381G2MultiExp) Run(input []byte) ([]byte, error) { +func (c *bls12381G2MultiExp) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { // Implements EIP-2537 G2MultiExp precompile logic // > G2 multiplication call expects `288*k` bytes as an input that is interpreted as byte concatenation of `k` slices each of them being a byte concatenation of encoding of G2 point (`256` bytes) and encoding of a scalar value (`32` bytes). // > Output is an encoding of multiexponentiation operation result - single G2 point (`256` bytes). - k := len(input) / 288 - if len(input) == 0 || len(input)%288 != 0 { + k := len(contract.Input) / 288 + if len(contract.Input) == 0 || len(contract.Input)%288 != 0 { return nil, errBLS12381InvalidInputLength } var err error @@ -878,11 +1128,11 @@ func (c *bls12381G2MultiExp) Run(input []byte) ([]byte, error) { off := 288 * i t0, t1, t2 := off, off+256, off+288 // Decode G1 point - if points[i], err = g.DecodePoint(input[t0:t1]); err != nil { + if points[i], err = g.DecodePoint(contract.Input[t0:t1]); err != nil { return nil, err } // Decode scalar value - scalars[i] = new(big.Int).SetBytes(input[t1:t2]) + scalars[i] = new(big.Int).SetBytes(contract.Input[t1:t2]) } // Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1) @@ -896,20 +1146,26 @@ func (c *bls12381G2MultiExp) Run(input []byte) ([]byte, error) { // bls12381Pairing implements EIP-2537 Pairing precompile. type bls12381Pairing struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bls12381Pairing) Address() common.Address { + return common.BytesToAddress([]byte{16}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381Pairing) RequiredGas(input []byte) uint64 { return params.Bls12381PairingBaseGas + uint64(len(input)/384)*params.Bls12381PairingPerPairGas } -func (c *bls12381Pairing) Run(input []byte) ([]byte, error) { +func (c *bls12381Pairing) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { // Implements EIP-2537 Pairing precompile logic. // > Pairing call expects `384*k` bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure: // > - `128` bytes of G1 point encoding // > - `256` bytes of G2 point encoding // > Output is a `32` bytes where last single byte is `0x01` if pairing result is equal to multiplicative identity in a pairing target field and `0x00` otherwise // > (which is equivalent of Big Endian encoding of Solidity values `uint256(1)` and `uin256(0)` respectively). - k := len(input) / 384 - if len(input) == 0 || len(input)%384 != 0 { + k := len(contract.Input) / 384 + if len(contract.Input) == 0 || len(contract.Input)%384 != 0 { return nil, errBLS12381InvalidInputLength } @@ -923,12 +1179,12 @@ func (c *bls12381Pairing) Run(input []byte) ([]byte, error) { t0, t1, t2 := off, off+128, off+384 // Decode G1 point - p1, err := g1.DecodePoint(input[t0:t1]) + p1, err := g1.DecodePoint(contract.Input[t0:t1]) if err != nil { return nil, err } // Decode G2 point - p2, err := g2.DecodePoint(input[t1:t2]) + p2, err := g2.DecodePoint(contract.Input[t1:t2]) if err != nil { return nil, err } @@ -975,21 +1231,27 @@ func decodeBLS12381FieldElement(in []byte) ([]byte, error) { // bls12381MapG1 implements EIP-2537 MapG1 precompile. type bls12381MapG1 struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bls12381MapG1) Address() common.Address { + return common.BytesToAddress([]byte{17}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381MapG1) RequiredGas(input []byte) uint64 { return params.Bls12381MapG1Gas } -func (c *bls12381MapG1) Run(input []byte) ([]byte, error) { +func (c *bls12381MapG1) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { // Implements EIP-2537 Map_To_G1 precompile. // > Field-to-curve call expects `64` bytes an an input that is interpreted as a an element of the base field. // > Output of this call is `128` bytes and is G1 point following respective encoding rules. - if len(input) != 64 { + if len(contract.Input) != 64 { return nil, errBLS12381InvalidInputLength } // Decode input field element - fe, err := decodeBLS12381FieldElement(input) + fe, err := decodeBLS12381FieldElement(contract.Input) if err != nil { return nil, err } @@ -1010,27 +1272,33 @@ func (c *bls12381MapG1) Run(input []byte) ([]byte, error) { // bls12381MapG2 implements EIP-2537 MapG2 precompile. type bls12381MapG2 struct{} +// Address defines the precompiled contract address. This MUST match the address +// set in the precompiled contract map. +func (bls12381MapG2) Address() common.Address { + return common.BytesToAddress([]byte{18}) +} + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bls12381MapG2) RequiredGas(input []byte) uint64 { return params.Bls12381MapG2Gas } -func (c *bls12381MapG2) Run(input []byte) ([]byte, error) { +func (c *bls12381MapG2) Run(evm *EVM, contract *Contract, readonly bool) ([]byte, error) { // Implements EIP-2537 Map_FP2_TO_G2 precompile logic. // > Field-to-curve call expects `128` bytes an an input that is interpreted as a an element of the quadratic extension field. // > Output of this call is `256` bytes and is G2 point following respective encoding rules. - if len(input) != 128 { + if len(contract.Input) != 128 { return nil, errBLS12381InvalidInputLength } // Decode input field element fe := make([]byte, 96) - c0, err := decodeBLS12381FieldElement(input[:64]) + c0, err := decodeBLS12381FieldElement(contract.Input[:64]) if err != nil { return nil, err } copy(fe[48:], c0) - c1, err := decodeBLS12381FieldElement(input[64:]) + c1, err := decodeBLS12381FieldElement(contract.Input[64:]) if err != nil { return nil, err } diff --git a/core/vm/contracts_test.go b/core/vm/contracts_test.go index b22d999e6cd9..1d4417c5b9af 100644 --- a/core/vm/contracts_test.go +++ b/core/vm/contracts_test.go @@ -20,6 +20,7 @@ import ( "bytes" "encoding/json" "fmt" + "math/big" "os" "testing" "time" @@ -96,7 +97,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(nil, p, AccountRef(common.Address{}), in, gas, new(big.Int), false); 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 +119,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(nil, p, AccountRef(common.Address{}), in, gas, new(big.Int), false) if err.Error() != "out of gas" { t.Errorf("Expected error [out of gas], got [%v]", err) } @@ -135,7 +136,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(nil, p, AccountRef(common.Address{}), in, gas, new(big.Int), false) if err.Error() != test.ExpectedError { t.Errorf("Expected error [%v], got [%v]", test.ExpectedError, err) } @@ -167,7 +168,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(nil, p, AccountRef(common.Address{}), in, reqGas, new(big.Int), false) } bench.StopTimer() elapsed := uint64(time.Since(start)) @@ -179,7 +180,7 @@ func benchmarkPrecompiled(addr string, test precompiledTest, bench *testing.B) { // Keep it as uint64, multiply 100 to get two digit float later mgasps := (100 * 1000 * gasUsed) / elapsed bench.ReportMetric(float64(mgasps)/100, "mgas/s") - //Check if it is correct + // Check if it is correct if err != nil { bench.Error(err) return diff --git a/core/vm/evm.go b/core/vm/evm.go index 01017572d178..67f4ac1f6606 100644 --- a/core/vm/evm.go +++ b/core/vm/evm.go @@ -40,22 +40,6 @@ type ( GetHashFunc func(uint64) common.Hash ) -func (evm *EVM) precompile(addr common.Address) (PrecompiledContract, bool) { - var precompiles map[common.Address]PrecompiledContract - switch { - case evm.chainRules.IsBerlin: - precompiles = PrecompiledContractsBerlin - case evm.chainRules.IsIstanbul: - precompiles = PrecompiledContractsIstanbul - case evm.chainRules.IsByzantium: - precompiles = PrecompiledContractsByzantium - default: - precompiles = PrecompiledContractsHomestead - } - p, ok := precompiles[addr] - return p, ok -} - // BlockContext provides the EVM with auxiliary information. Once provided // it shouldn't be modified. type BlockContext struct { @@ -112,13 +96,17 @@ type EVM struct { Config Config // global (to this context) ethereum virtual machine // used throughout the execution of the tx. - interpreter *EVMInterpreter + interpreter Interpreter // abort is used to abort the EVM calling operations abort atomic.Bool // callGasTemp holds the gas available for the current call. This is needed because the // available gas is calculated in gasCall* according to the 63/64 rule and later // applied in opCall*. callGasTemp uint64 + // precompiles defines the precompiled contracts used by the EVM + precompiles map[common.Address]PrecompiledContract + // activePrecompiles defines the precompiles that are currently active + activePrecompiles []common.Address } // NewEVM returns a new EVM. The returned EVM is not thread safe and should @@ -132,7 +120,11 @@ func NewEVM(blockCtx BlockContext, txCtx TxContext, statedb StateDB, chainConfig chainConfig: chainConfig, chainRules: chainConfig.Rules(blockCtx.BlockNumber, blockCtx.Random != nil, blockCtx.Time), } + // set the default precompiles + evm.activePrecompiles = DefaultActivePrecompiles(evm.chainRules) + evm.precompiles = DefaultPrecompiles(evm.chainRules) evm.interpreter = NewEVMInterpreter(evm) + return evm } @@ -155,10 +147,15 @@ func (evm *EVM) Cancelled() bool { } // Interpreter returns the current interpreter -func (evm *EVM) Interpreter() *EVMInterpreter { +func (evm *EVM) Interpreter() Interpreter { return evm.interpreter } +// WithInterpreter sets the interpreter to the EVM instance +func (evm *EVM) WithInterpreter(interpreter Interpreter) { + evm.interpreter = interpreter +} + // SetBlockContext updates the block context of the EVM. func (evm *EVM) SetBlockContext(blockCtx BlockContext) { evm.Context = blockCtx @@ -181,7 +178,7 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas return nil, gas, ErrInsufficientBalance } snapshot := evm.StateDB.Snapshot() - p, isPrecompile := evm.precompile(addr) + p, isPrecompile := evm.Precompile(addr) debug := evm.Config.Tracer != nil if !evm.StateDB.Exist(addr) { @@ -218,8 +215,9 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas } } + // It is allowed to call precompiles, even via call -- as opposed to callcode, staticcall and delegatecall it can also modify state if isPrecompile { - ret, gas, err = RunPrecompiledContract(p, input, gas) + ret, gas, err = evm.RunPrecompiledContract(p, caller, input, gas, value, false) } 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. @@ -270,7 +268,7 @@ func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) { return nil, gas, ErrInsufficientBalance } - var snapshot = evm.StateDB.Snapshot() + snapshot := evm.StateDB.Snapshot() // Invoke tracer hooks that signal entering/exiting a call frame if evm.Config.Tracer != nil { @@ -280,9 +278,9 @@ func (evm *EVM) CallCode(caller ContractRef, addr common.Address, input []byte, }(gas) } - // It is allowed to call precompiles, even via delegatecall - if p, isPrecompile := evm.precompile(addr); isPrecompile { - ret, gas, err = RunPrecompiledContract(p, input, gas) + // It is allowed to call precompiles, even via callcode, but only for reading + if p, isPrecompile := evm.Precompile(addr); isPrecompile { + ret, gas, err = evm.RunPrecompiledContract(p, caller, input, gas, value, true) } else { addrCopy := addr // Initialise a new contract and set the code that is to be used by the EVM. @@ -311,7 +309,7 @@ func (evm *EVM) DelegateCall(caller ContractRef, addr common.Address, input []by if evm.depth > int(params.CallCreateDepth) { return nil, gas, ErrDepth } - var snapshot = evm.StateDB.Snapshot() + snapshot := evm.StateDB.Snapshot() // Invoke tracer hooks that signal entering/exiting a call frame if evm.Config.Tracer != nil { @@ -326,8 +324,8 @@ 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(addr); isPrecompile { - ret, gas, err = RunPrecompiledContract(p, input, gas) + if p, isPrecompile := evm.Precompile(addr); isPrecompile { + ret, gas, err = evm.RunPrecompiledContract(p, caller, input, gas, nil, true) } else { addrCopy := addr // Initialise a new contract and make initialise the delegate values @@ -359,7 +357,7 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte // after all empty accounts were deleted, so this is not required. However, if we omit this, // then certain tests start failing; stRevertTest/RevertPrecompiledTouchExactOOG.json. // We could change this, but for now it's left for legacy reasons - var snapshot = evm.StateDB.Snapshot() + snapshot := evm.StateDB.Snapshot() // We do an AddBalance of zero here, just in order to trigger a touch. // This doesn't matter on Mainnet, where all empties are gone at the time of Byzantium, @@ -375,8 +373,9 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte }(gas) } - if p, isPrecompile := evm.precompile(addr); isPrecompile { - ret, gas, err = RunPrecompiledContract(p, input, gas) + if p, isPrecompile := evm.Precompile(addr); isPrecompile { + // Note: delegate call is not allowed to modify state on precompiles + ret, gas, err = evm.RunPrecompiledContract(p, caller, input, gas, new(big.Int), true) } 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' diff --git a/core/vm/instructions_test.go b/core/vm/instructions_test.go index 61f001a692c3..c640f03f6b56 100644 --- a/core/vm/instructions_test.go +++ b/core/vm/instructions_test.go @@ -102,10 +102,10 @@ func init() { func testTwoOperandOp(t *testing.T, tests []TwoOperandTestcase, opFn executionFunc, name string) { var ( - env = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{}) - stack = newstack() - pc = uint64(0) - evmInterpreter = env.interpreter + env = NewEVM(BlockContext{}, TxContext{}, nil, params.TestChainConfig, Config{}) + stack = newstack() + pc = uint64(0) + interpreter = env.interpreter ) for i, test := range tests { @@ -114,7 +114,7 @@ func testTwoOperandOp(t *testing.T, tests []TwoOperandTestcase, opFn executionFu expected := new(uint256.Int).SetBytes(common.Hex2Bytes(test.Expected)) stack.push(x) stack.push(y) - opFn(&pc, evmInterpreter, &ScopeContext{nil, stack, nil}) + opFn(&pc, interpreter.(*EVMInterpreter), &ScopeContext{nil, stack, nil}) if len(stack.data) != 1 { t.Errorf("Expected one item on stack after %v, got %d: ", name, len(stack.data)) } @@ -256,7 +256,7 @@ func TestWriteExpectedValues(t *testing.T) { y := new(uint256.Int).SetBytes(common.Hex2Bytes(param.y)) stack.push(x) stack.push(y) - opFn(&pc, interpreter, &ScopeContext{nil, stack, nil}) + opFn(&pc, interpreter.(*EVMInterpreter), &ScopeContext{nil, stack, nil}) actual := stack.pop() result[i] = TwoOperandTestcase{param.x, param.y, fmt.Sprintf("%064x", actual)} } @@ -726,12 +726,12 @@ func TestRandom(t *testing.T) { {name: "hash(0x010203)", random: crypto.Keccak256Hash([]byte{0x01, 0x02, 0x03})}, } { var ( - env = NewEVM(BlockContext{Random: &tt.random}, TxContext{}, nil, params.TestChainConfig, Config{}) - stack = newstack() - pc = uint64(0) - evmInterpreter = env.interpreter + env = NewEVM(BlockContext{Random: &tt.random}, TxContext{}, nil, params.TestChainConfig, Config{}) + stack = newstack() + pc = uint64(0) + interpreter = env.interpreter ) - opRandom(&pc, evmInterpreter, &ScopeContext{nil, stack, nil}) + opRandom(&pc, interpreter.(*EVMInterpreter), &ScopeContext{nil, stack, nil}) if len(stack.data) != 1 { t.Errorf("Expected one item on stack after %v, got %d: ", tt.name, len(stack.data)) } diff --git a/core/vm/interface.go b/core/vm/interface.go index b83f78307eb7..8f8d1b974446 100644 --- a/core/vm/interface.go +++ b/core/vm/interface.go @@ -90,3 +90,13 @@ type CallContext interface { // Create creates a new contract Create(env *EVM, me ContractRef, data []byte, gas, value *big.Int) ([]byte, common.Address, error) } + +// Interpreter is used to run Ethereum based contracts and will utilize the +// passed environment to query external sources for state information. +// The Interpreter will run the byte code VM based on the passed +// configuration. +type Interpreter interface { + // Run loops and evaluates the contract's code with the given input data and returns + // the return byte-slice and an error if one occurred. + Run(contract *Contract, input []byte, static bool) ([]byte, error) +} diff --git a/core/vm/interpreter.go b/core/vm/interpreter.go index 5b2082bc9e90..a6a26dfb57c4 100644 --- a/core/vm/interpreter.go +++ b/core/vm/interpreter.go @@ -39,6 +39,8 @@ type ScopeContext struct { Contract *Contract } +var _ Interpreter = &EVMInterpreter{} + // EVMInterpreter represents an EVM interpreter type EVMInterpreter struct { evm *EVM diff --git a/core/vm/runtime/runtime.go b/core/vm/runtime/runtime.go index 005ef0c754ae..f536a552bf2d 100644 --- a/core/vm/runtime/runtime.go +++ b/core/vm/runtime/runtime.go @@ -117,7 +117,7 @@ func Execute(code, input []byte, cfg *Config) ([]byte, *state.StateDB, error) { // Execute the preparatory steps for state transition which includes: // - prepare accessList(post-berlin) // - reset transient storage(eip 1153) - cfg.State.Prepare(rules, cfg.Origin, cfg.Coinbase, &address, vm.ActivePrecompiles(rules), nil) + cfg.State.Prepare(rules, cfg.Origin, cfg.Coinbase, &address, vm.DefaultActivePrecompiles(rules), nil) cfg.State.CreateAccount(address) // set the receiver's (the executing contract) code for execution. cfg.State.SetCode(address, code) @@ -150,7 +150,7 @@ func Create(input []byte, cfg *Config) ([]byte, common.Address, uint64, error) { // Execute the preparatory steps for state transition which includes: // - prepare accessList(post-berlin) // - reset transient storage(eip 1153) - cfg.State.Prepare(rules, cfg.Origin, cfg.Coinbase, nil, vm.ActivePrecompiles(rules), nil) + cfg.State.Prepare(rules, cfg.Origin, cfg.Coinbase, nil, vm.DefaultActivePrecompiles(rules), nil) // Call the code with the given configuration. code, address, leftOverGas, err := vmenv.Create( sender, @@ -178,7 +178,7 @@ func Call(address common.Address, input []byte, cfg *Config) ([]byte, uint64, er // Execute the preparatory steps for state transition which includes: // - prepare accessList(post-berlin) // - reset transient storage(eip 1153) - statedb.Prepare(rules, cfg.Origin, cfg.Coinbase, &address, vm.ActivePrecompiles(rules), nil) + statedb.Prepare(rules, cfg.Origin, cfg.Coinbase, &address, vm.DefaultActivePrecompiles(rules), nil) // Call the code with the given configuration. ret, leftOverGas, err := vmenv.Call( diff --git a/eth/tracers/js/goja.go b/eth/tracers/js/goja.go index 2a2789e93d31..0cd9bf90ad07 100644 --- a/eth/tracers/js/goja.go +++ b/eth/tracers/js/goja.go @@ -246,7 +246,7 @@ func (t *jsTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Addr t.ctx["block"] = t.vm.ToValue(env.Context.BlockNumber.Uint64()) // Update list of precompiles based on current block rules := env.ChainConfig().Rules(env.Context.BlockNumber, env.Context.Random != nil, env.Context.Time) - t.activePrecompiles = vm.ActivePrecompiles(rules) + t.activePrecompiles = env.ActivePrecompiles(rules) } // CaptureState implements the Tracer interface to trace a single step of VM execution. diff --git a/eth/tracers/native/4byte.go b/eth/tracers/native/4byte.go index 5a2c4f91115f..4da983df028b 100644 --- a/eth/tracers/native/4byte.go +++ b/eth/tracers/native/4byte.go @@ -82,7 +82,7 @@ func (t *fourByteTracer) store(id []byte, size int) { func (t *fourByteTracer) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { // Update list of precompiles based on current block rules := env.ChainConfig().Rules(env.Context.BlockNumber, env.Context.Random != nil, env.Context.Time) - t.activePrecompiles = vm.ActivePrecompiles(rules) + t.activePrecompiles = env.ActivePrecompiles(rules) // Save the outer calldata also if len(input) >= 4 { diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index b7ad30a6eacd..344ad1cf0621 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -1450,7 +1450,7 @@ func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrH } isPostMerge := header.Difficulty.Cmp(common.Big0) == 0 // Retrieve the precompiles since they don't need to be added to the access list - precompiles := vm.ActivePrecompiles(b.ChainConfig().Rules(header.Number, isPostMerge, header.Time)) + precompiles := vm.DefaultActivePrecompiles(b.ChainConfig().Rules(header.Number, isPostMerge, header.Time)) // Create an initial tracer prevTracer := logger.NewAccessListTracer(nil, args.from(), to, precompiles) diff --git a/tests/fuzzers/bls12381/precompile_fuzzer.go b/tests/fuzzers/bls12381/precompile_fuzzer.go index cab2bcba3863..537c72984c53 100644 --- a/tests/fuzzers/bls12381/precompile_fuzzer.go +++ b/tests/fuzzers/bls12381/precompile_fuzzer.go @@ -92,7 +92,9 @@ func fuzz(id byte, data []byte) int { } cpy := make([]byte, len(data)) copy(cpy, data) - _, err := precompile.Run(cpy) + contract := vm.NewPrecompile(vm.AccountRef(common.Address{}), precompile, common.Big0, gas) + contract.Input = cpy + _, err := precompile.Run(nil, contract, false) if !bytes.Equal(cpy, data) { panic(fmt.Sprintf("input data modified, precompile %d: %x %x", id, data, cpy)) } diff --git a/tests/state_test.go b/tests/state_test.go index 9d3862e1dc7c..b355d5010b8e 100644 --- a/tests/state_test.go +++ b/tests/state_test.go @@ -238,7 +238,7 @@ func runBenchmark(b *testing.B, t *StateTest) { b.ResetTimer() for n := 0; n < b.N; n++ { snapshot := statedb.Snapshot() - statedb.Prepare(rules, msg.From, context.Coinbase, msg.To, vm.ActivePrecompiles(rules), msg.AccessList) + statedb.Prepare(rules, msg.From, context.Coinbase, msg.To, evm.ActivePrecompiles(rules), msg.AccessList) b.StartTimer() start := time.Now()