diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f21495876a9..9c149205efaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,10 @@ Ref: https://keepachangelog.com/en/1.0.0/ ## Unreleased +### State Machine Breaking + +* [#10](https://github.com/evmos/go-ethereum/pull/10) Support stateful precompiled contracts. + ### Improvements * [#8](https://github.com/evmos/go-ethereum/pull/8) Add `Address` function to `PrecompiledContract` interface. 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 0035be55943a..c668b29e5d3b 100644 --- a/core/vm/contracts.go +++ b/core/vm/contracts.go @@ -39,8 +39,13 @@ import ( // contract. type PrecompiledContract interface { ContractRef - RequiredGas(input []byte) uint64 // RequiredPrice calculates the contract gas use - Run(input []byte) ([]byte, error) // Run runs the precompiled contract + // IsStateful returns true if the precompile contract can execute a state + // transition or if it can access the StateDB. + IsStateful() bool + // 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 @@ -256,14 +261,40 @@ func ValidatePrecompiles( // - 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. @@ -275,32 +306,35 @@ func (ecrecover) Address() common.Address { return common.BytesToAddress([]byte{1}) } +// IsStateful returns false. +func (ecrecover) IsStateful() bool { return false } + 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 @@ -319,6 +353,9 @@ func (sha256hash) Address() common.Address { return common.BytesToAddress([]byte{2}) } +// IsStateful returns false. +func (sha256hash) IsStateful() bool { return false } + // 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 @@ -327,8 +364,8 @@ 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 } @@ -341,6 +378,9 @@ func (ripemd160hash) Address() common.Address { return common.BytesToAddress([]byte{3}) } +// IsStateful returns false. +func (ripemd160hash) IsStateful() bool { return false } + // 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 @@ -349,9 +389,9 @@ 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 } @@ -364,6 +404,9 @@ func (dataCopy) Address() common.Address { return common.BytesToAddress([]byte{4}) } +// IsStateful returns false. +func (dataCopy) IsStateful() bool { return false } + // 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 @@ -372,8 +415,8 @@ 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 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. @@ -384,6 +427,7 @@ type bigModExp struct { var ( big0 = big.NewInt(0) big1 = big.NewInt(1) + big2 = big.NewInt(2) big3 = big.NewInt(3) big4 = big.NewInt(4) big7 = big.NewInt(7) @@ -434,6 +478,9 @@ func (bigModExp) Address() common.Address { return common.BytesToAddress([]byte{5}) } +// IsStateful returns false. +func (bigModExp) IsStateful() bool { return false } + // RequiredGas returns the gas required to execute the pre-compiled contract. func (c *bigModExp) RequiredGas(input []byte) uint64 { var ( @@ -505,16 +552,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 { @@ -522,9 +569,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)) ) if mod.BitLen() == 0 { // Modulo 0 is undefined, return zero @@ -579,13 +626,16 @@ func (bn256AddIstanbul) Address() common.Address { return common.BytesToAddress([]byte{6}) } +// IsStateful returns false. +func (bn256AddIstanbul) IsStateful() bool { return false } + // 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 @@ -598,13 +648,16 @@ func (bn256AddByzantium) Address() common.Address { return common.BytesToAddress([]byte{6}) } +// IsStateful returns false. +func (bn256AddByzantium) IsStateful() bool { return false } + // 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 @@ -629,13 +682,16 @@ func (bn256ScalarMulIstanbul) Address() common.Address { return common.BytesToAddress([]byte{7}) } +// IsStateful returns false. +func (bn256ScalarMulIstanbul) IsStateful() bool { return false } + // 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 @@ -648,13 +704,16 @@ func (bn256ScalarMulByzantium) Address() common.Address { return common.BytesToAddress([]byte{7}) } +// IsStateful returns false. +func (bn256ScalarMulByzantium) IsStateful() bool { return false } + // 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 ( @@ -709,13 +768,16 @@ func (bn256PairingIstanbul) Address() common.Address { return common.BytesToAddress([]byte{8}) } +// IsStateful returns false. +func (bn256PairingIstanbul) IsStateful() bool { return false } + // 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 @@ -728,13 +790,16 @@ func (bn256PairingByzantium) Address() common.Address { return common.BytesToAddress([]byte{8}) } +// IsStateful returns false. +func (bn256PairingByzantium) IsStateful() bool { return false } + // 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{} @@ -745,6 +810,9 @@ func (blake2F) Address() common.Address { return common.BytesToAddress([]byte{9}) } +// IsStateful returns false. +func (blake2F) IsStateful() bool { return false } + 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. @@ -765,18 +833,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 @@ -784,14 +852,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) @@ -820,16 +888,19 @@ func (bls12381G1Add) Address() common.Address { return common.BytesToAddress([]byte{10}) } +// IsStateful returns false. +func (bls12381G1Add) IsStateful() bool { return false } + // 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 @@ -839,11 +910,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 } @@ -864,16 +935,19 @@ func (bls12381G1Mul) Address() common.Address { return common.BytesToAddress([]byte{11}) } +// IsStateful returns false. +func (bls12381G1Mul) IsStateful() bool { return false } + // 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 @@ -883,11 +957,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() @@ -906,6 +980,9 @@ func (bls12381G1MultiExp) Address() common.Address { return common.BytesToAddress([]byte{12}) } +// IsStateful returns false. +func (bls12381G1MultiExp) IsStateful() bool { return false } + // 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 @@ -925,12 +1002,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 @@ -945,11 +1022,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) @@ -969,16 +1046,19 @@ func (bls12381G2Add) Address() common.Address { return common.BytesToAddress([]byte{13}) } +// IsStateful returns false. +func (bls12381G2Add) IsStateful() bool { return false } + // 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 @@ -989,11 +1069,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 } @@ -1013,16 +1093,19 @@ func (bls12381G2Mul) Address() common.Address { return common.BytesToAddress([]byte{14}) } +// IsStateful returns false. +func (bls12381G2Mul) IsStateful() bool { return false } + // 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 @@ -1032,11 +1115,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() @@ -1055,6 +1138,9 @@ func (bls12381G2MultiExp) Address() common.Address { return common.BytesToAddress([]byte{15}) } +// IsStateful returns false. +func (bls12381G2MultiExp) IsStateful() bool { return false } + // 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 @@ -1074,12 +1160,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 @@ -1094,11 +1180,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) @@ -1118,20 +1204,23 @@ func (bls12381Pairing) Address() common.Address { return common.BytesToAddress([]byte{16}) } +// IsStateful returns false. +func (bls12381Pairing) IsStateful() bool { return false } + // 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 } @@ -1145,12 +1234,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 } @@ -1203,21 +1292,24 @@ func (bls12381MapG1) Address() common.Address { return common.BytesToAddress([]byte{17}) } +// IsStateful returns false. +func (bls12381MapG1) IsStateful() bool { return false } + // 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 } @@ -1244,27 +1336,30 @@ func (bls12381MapG2) Address() common.Address { return common.BytesToAddress([]byte{18}) } +// IsStateful returns false. +func (bls12381MapG2) IsStateful() bool { return false } + // 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 ff0878e85be1..3e96a3624fac 100644 --- a/core/vm/evm.go +++ b/core/vm/evm.go @@ -209,7 +209,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 = 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. @@ -272,7 +272,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(addr); isPrecompile { - ret, gas, err = RunPrecompiledContract(p, input, gas) + ret, gas, err = evm.RunPrecompiledContract(p, caller, input, gas, value, false) } else { addrCopy := addr // Initialise a new contract and set the code that is to be used by the EVM. @@ -313,7 +313,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(addr); isPrecompile { - ret, gas, err = RunPrecompiledContract(p, input, gas) + ret, gas, err = evm.RunPrecompiledContract(p, caller, input, gas, nil, true) } else { addrCopy := addr // Initialise a new contract and make initialise the delegate values @@ -362,7 +362,8 @@ func (evm *EVM) StaticCall(caller ContractRef, addr common.Address, input []byte } if p, isPrecompile := evm.Precompile(addr); isPrecompile { - ret, gas, err = RunPrecompiledContract(p, input, gas) + // 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/jump_table.go b/core/vm/jump_table.go index a232c88a2fc2..ffe33bb014fc 100644 --- a/core/vm/jump_table.go +++ b/core/vm/jump_table.go @@ -24,7 +24,7 @@ import ( type ( executionFunc func(pc *uint64, interpreter *EVMInterpreter, callContext *ScopeContext) ([]byte, error) - gasFunc func(*EVM, *Contract, *Stack, *Memory, uint64) (uint64, error) // last parameter is the requested memory size as a uint64 + gasFunc func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) // memorySizeFunc returns the required size, and whether the operation overflowed a uint64 memorySizeFunc func(*Stack) (size uint64, overflow bool) ) diff --git a/eth/tracers/internal/tracetest/calltrace_test.go b/eth/tracers/internal/tracetest/calltrace_test.go index d2c50656d9a8..437cc4c62b4f 100644 --- a/eth/tracers/internal/tracetest/calltrace_test.go +++ b/eth/tracers/internal/tracetest/calltrace_test.go @@ -315,7 +315,7 @@ func benchTracer(tracerName string, test *callTracerTest, b *testing.B) { // Tx to A, A calls B with zero value. B does not already exist. // Expected: that enter/exit is invoked and the inner call is shown in the result func TestZeroValueToNotExitCall(t *testing.T) { - var to = common.HexToAddress("0x00000000000000000000000000000000deadbeef") + to := common.HexToAddress("0x00000000000000000000000000000000deadbeef") privkey, err := crypto.HexToECDSA("0000000000000000deadbeef00000000000000000000000000000000deadbeef") if err != nil { t.Fatalf("err %v", err) @@ -343,12 +343,12 @@ func TestZeroValueToNotExitCall(t *testing.T) { Difficulty: big.NewInt(0x30000), GasLimit: uint64(6000000), } - var code = []byte{ + code := []byte{ byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), // in and outs zero byte(vm.DUP1), byte(vm.PUSH1), 0xff, byte(vm.GAS), // value=0,address=0xff, gas=GAS byte(vm.CALL), } - var alloc = core.GenesisAlloc{ + alloc := core.GenesisAlloc{ to: core.GenesisAccount{ Nonce: 1, Code: code, diff --git a/tests/fuzzers/bls12381/precompile_fuzzer.go b/tests/fuzzers/bls12381/precompile_fuzzer.go index bc3c45652603..99e8c1c4a37d 100644 --- a/tests/fuzzers/bls12381/precompile_fuzzer.go +++ b/tests/fuzzers/bls12381/precompile_fuzzer.go @@ -90,7 +90,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)) }