gitlab.com/flarenetwork/coreth@v0.1.1/core/vm/contracts.go (about)

     1  // (c) 2019-2020, Ava Labs, Inc.
     2  //
     3  // This file is a derived work, based on the go-ethereum library whose original
     4  // notices appear below.
     5  //
     6  // It is distributed under a license compatible with the licensing terms of the
     7  // original code from which it is derived.
     8  //
     9  // Much love to the original authors for their work.
    10  // **********
    11  // Copyright 2014 The go-ethereum Authors
    12  // This file is part of the go-ethereum library.
    13  //
    14  // The go-ethereum library is free software: you can redistribute it and/or modify
    15  // it under the terms of the GNU Lesser General Public License as published by
    16  // the Free Software Foundation, either version 3 of the License, or
    17  // (at your option) any later version.
    18  //
    19  // The go-ethereum library is distributed in the hope that it will be useful,
    20  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    21  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    22  // GNU Lesser General Public License for more details.
    23  //
    24  // You should have received a copy of the GNU Lesser General Public License
    25  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    26  
    27  package vm
    28  
    29  import (
    30  	"crypto/sha256"
    31  	"encoding/binary"
    32  	"errors"
    33  	"math/big"
    34  
    35  	"github.com/ethereum/go-ethereum/common"
    36  	"github.com/ethereum/go-ethereum/common/math"
    37  	"github.com/ethereum/go-ethereum/crypto"
    38  	"github.com/ethereum/go-ethereum/crypto/blake2b"
    39  	"github.com/ethereum/go-ethereum/crypto/bls12381"
    40  	"github.com/ethereum/go-ethereum/crypto/bn256"
    41  	"gitlab.com/flarenetwork/coreth/params"
    42  
    43  	//lint:ignore SA1019 Needed for precompile
    44  	"golang.org/x/crypto/ripemd160"
    45  )
    46  
    47  // PrecompiledContract is the basic interface for native Go contracts. The implementation
    48  // requires a deterministic gas count based on the input size of the Run method of the
    49  // contract.
    50  type PrecompiledContract interface {
    51  	RequiredGas(input []byte) uint64  // RequiredPrice calculates the contract gas use
    52  	Run(input []byte) ([]byte, error) // Run runs the precompiled contract
    53  }
    54  
    55  // PrecompiledContractsHomestead contains the default set of pre-compiled Ethereum
    56  // contracts used in the Frontier and Homestead releases.
    57  var PrecompiledContractsHomestead = map[common.Address]StatefulPrecompiledContract{
    58  	common.BytesToAddress([]byte{1}): newWrappedPrecompiledContract(&ecrecover{}),
    59  	common.BytesToAddress([]byte{2}): newWrappedPrecompiledContract(&sha256hash{}),
    60  	common.BytesToAddress([]byte{3}): newWrappedPrecompiledContract(&ripemd160hash{}),
    61  	common.BytesToAddress([]byte{4}): newWrappedPrecompiledContract(&dataCopy{}),
    62  }
    63  
    64  // PrecompiledContractsByzantium contains the default set of pre-compiled Ethereum
    65  // contracts used in the Byzantium release.
    66  var PrecompiledContractsByzantium = map[common.Address]StatefulPrecompiledContract{
    67  	common.BytesToAddress([]byte{1}): newWrappedPrecompiledContract(&ecrecover{}),
    68  	common.BytesToAddress([]byte{2}): newWrappedPrecompiledContract(&sha256hash{}),
    69  	common.BytesToAddress([]byte{3}): newWrappedPrecompiledContract(&ripemd160hash{}),
    70  	common.BytesToAddress([]byte{4}): newWrappedPrecompiledContract(&dataCopy{}),
    71  	common.BytesToAddress([]byte{5}): newWrappedPrecompiledContract(&bigModExp{eip2565: false}),
    72  	common.BytesToAddress([]byte{6}): newWrappedPrecompiledContract(&bn256AddByzantium{}),
    73  	common.BytesToAddress([]byte{7}): newWrappedPrecompiledContract(&bn256ScalarMulByzantium{}),
    74  	common.BytesToAddress([]byte{8}): newWrappedPrecompiledContract(&bn256PairingByzantium{}),
    75  }
    76  
    77  // PrecompiledContractsIstanbul contains the default set of pre-compiled Ethereum
    78  // contracts used in the Istanbul release.
    79  var PrecompiledContractsIstanbul = map[common.Address]StatefulPrecompiledContract{
    80  	common.BytesToAddress([]byte{1}): newWrappedPrecompiledContract(&ecrecover{}),
    81  	common.BytesToAddress([]byte{2}): newWrappedPrecompiledContract(&sha256hash{}),
    82  	common.BytesToAddress([]byte{3}): newWrappedPrecompiledContract(&ripemd160hash{}),
    83  	common.BytesToAddress([]byte{4}): newWrappedPrecompiledContract(&dataCopy{}),
    84  	common.BytesToAddress([]byte{5}): newWrappedPrecompiledContract(&bigModExp{eip2565: false}),
    85  	common.BytesToAddress([]byte{6}): newWrappedPrecompiledContract(&bn256AddIstanbul{}),
    86  	common.BytesToAddress([]byte{7}): newWrappedPrecompiledContract(&bn256ScalarMulIstanbul{}),
    87  	common.BytesToAddress([]byte{8}): newWrappedPrecompiledContract(&bn256PairingIstanbul{}),
    88  	common.BytesToAddress([]byte{9}): newWrappedPrecompiledContract(&blake2F{}),
    89  }
    90  
    91  // PrecompiledContractsApricotPhase2 contains the default set of pre-compiled Ethereum
    92  // contracts used in the Apricot Phase 2 release.
    93  var PrecompiledContractsApricotPhase2 = map[common.Address]StatefulPrecompiledContract{
    94  	common.BytesToAddress([]byte{1}): newWrappedPrecompiledContract(&ecrecover{}),
    95  	common.BytesToAddress([]byte{2}): newWrappedPrecompiledContract(&sha256hash{}),
    96  	common.BytesToAddress([]byte{3}): newWrappedPrecompiledContract(&ripemd160hash{}),
    97  	common.BytesToAddress([]byte{4}): newWrappedPrecompiledContract(&dataCopy{}),
    98  	common.BytesToAddress([]byte{5}): newWrappedPrecompiledContract(&bigModExp{eip2565: true}),
    99  	common.BytesToAddress([]byte{6}): newWrappedPrecompiledContract(&bn256AddIstanbul{}),
   100  	common.BytesToAddress([]byte{7}): newWrappedPrecompiledContract(&bn256ScalarMulIstanbul{}),
   101  	common.BytesToAddress([]byte{8}): newWrappedPrecompiledContract(&bn256PairingIstanbul{}),
   102  	common.BytesToAddress([]byte{9}): newWrappedPrecompiledContract(&blake2F{}),
   103  	genesisContractAddr:              &deprecatedContract{},
   104  	nativeAssetBalanceAddr:           &nativeAssetBalance{gasCost: params.AssetBalanceApricot},
   105  	nativeAssetCallAddr:              &nativeAssetCall{gasCost: params.AssetCallApricot},
   106  }
   107  
   108  var (
   109  	PrecompiledAddressesApricotPhase2 []common.Address
   110  	PrecompiledAddressesIstanbul      []common.Address
   111  	PrecompiledAddressesByzantium     []common.Address
   112  	PrecompiledAddressesHomestead     []common.Address
   113  )
   114  
   115  func init() {
   116  	for k := range PrecompiledContractsHomestead {
   117  		PrecompiledAddressesHomestead = append(PrecompiledAddressesHomestead, k)
   118  	}
   119  	for k := range PrecompiledContractsByzantium {
   120  		PrecompiledAddressesByzantium = append(PrecompiledAddressesByzantium, k)
   121  	}
   122  	for k := range PrecompiledContractsIstanbul {
   123  		PrecompiledAddressesIstanbul = append(PrecompiledAddressesIstanbul, k)
   124  	}
   125  	for k := range PrecompiledContractsApricotPhase2 {
   126  		PrecompiledAddressesApricotPhase2 = append(PrecompiledAddressesApricotPhase2, k)
   127  	}
   128  }
   129  
   130  // ActivePrecompiles returns the precompiles enabled with the current configuration.
   131  func ActivePrecompiles(rules params.Rules) []common.Address {
   132  	switch {
   133  	case rules.IsApricotPhase2:
   134  		return PrecompiledAddressesApricotPhase2
   135  	case rules.IsIstanbul:
   136  		return PrecompiledAddressesIstanbul
   137  	case rules.IsByzantium:
   138  		return PrecompiledAddressesByzantium
   139  	default:
   140  		return PrecompiledAddressesHomestead
   141  	}
   142  }
   143  
   144  // RunPrecompiledContract runs and evaluates the output of a precompiled contract.
   145  // It returns
   146  // - the returned bytes,
   147  // - the _remaining_ gas,
   148  // - any error that occurred
   149  func RunPrecompiledContract(p PrecompiledContract, input []byte, suppliedGas uint64) (ret []byte, remainingGas uint64, err error) {
   150  	gasCost := p.RequiredGas(input)
   151  	if suppliedGas < gasCost {
   152  		return nil, 0, ErrOutOfGas
   153  	}
   154  	suppliedGas -= gasCost
   155  	output, err := p.Run(input)
   156  	return output, suppliedGas, err
   157  }
   158  
   159  // ECRECOVER implemented as a native contract.
   160  type ecrecover struct{}
   161  
   162  func (c *ecrecover) RequiredGas(input []byte) uint64 {
   163  	return params.EcrecoverGas
   164  }
   165  
   166  func (c *ecrecover) Run(input []byte) ([]byte, error) {
   167  	const ecRecoverInputLength = 128
   168  
   169  	input = common.RightPadBytes(input, ecRecoverInputLength)
   170  	// "input" is (hash, v, r, s), each 32 bytes
   171  	// but for ecrecover we want (r, s, v)
   172  
   173  	r := new(big.Int).SetBytes(input[64:96])
   174  	s := new(big.Int).SetBytes(input[96:128])
   175  	v := input[63] - 27
   176  
   177  	// tighter sig s values input homestead only apply to tx sigs
   178  	if !allZero(input[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) {
   179  		return nil, nil
   180  	}
   181  	// We must make sure not to modify the 'input', so placing the 'v' along with
   182  	// the signature needs to be done on a new allocation
   183  	sig := make([]byte, 65)
   184  	copy(sig, input[64:128])
   185  	sig[64] = v
   186  	// v needs to be at the end for libsecp256k1
   187  	pubKey, err := crypto.Ecrecover(input[:32], sig)
   188  	// make sure the public key is a valid one
   189  	if err != nil {
   190  		return nil, nil
   191  	}
   192  
   193  	// the first byte of pubkey is bitcoin heritage
   194  	return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32), nil
   195  }
   196  
   197  // SHA256 implemented as a native contract.
   198  type sha256hash struct{}
   199  
   200  // RequiredGas returns the gas required to execute the pre-compiled contract.
   201  //
   202  // This method does not require any overflow checking as the input size gas costs
   203  // required for anything significant is so high it's impossible to pay for.
   204  func (c *sha256hash) RequiredGas(input []byte) uint64 {
   205  	return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas
   206  }
   207  func (c *sha256hash) Run(input []byte) ([]byte, error) {
   208  	h := sha256.Sum256(input)
   209  	return h[:], nil
   210  }
   211  
   212  // RIPEMD160 implemented as a native contract.
   213  type ripemd160hash struct{}
   214  
   215  // RequiredGas returns the gas required to execute the pre-compiled contract.
   216  //
   217  // This method does not require any overflow checking as the input size gas costs
   218  // required for anything significant is so high it's impossible to pay for.
   219  func (c *ripemd160hash) RequiredGas(input []byte) uint64 {
   220  	return uint64(len(input)+31)/32*params.Ripemd160PerWordGas + params.Ripemd160BaseGas
   221  }
   222  func (c *ripemd160hash) Run(input []byte) ([]byte, error) {
   223  	ripemd := ripemd160.New()
   224  	ripemd.Write(input)
   225  	return common.LeftPadBytes(ripemd.Sum(nil), 32), nil
   226  }
   227  
   228  // data copy implemented as a native contract.
   229  type dataCopy struct{}
   230  
   231  // RequiredGas returns the gas required to execute the pre-compiled contract.
   232  //
   233  // This method does not require any overflow checking as the input size gas costs
   234  // required for anything significant is so high it's impossible to pay for.
   235  func (c *dataCopy) RequiredGas(input []byte) uint64 {
   236  	return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas
   237  }
   238  func (c *dataCopy) Run(in []byte) ([]byte, error) {
   239  	return in, nil
   240  }
   241  
   242  // bigModExp implements a native big integer exponential modular operation.
   243  type bigModExp struct {
   244  	eip2565 bool
   245  }
   246  
   247  var (
   248  	big0      = big.NewInt(0)
   249  	big1      = big.NewInt(1)
   250  	big3      = big.NewInt(3)
   251  	big4      = big.NewInt(4)
   252  	big7      = big.NewInt(7)
   253  	big8      = big.NewInt(8)
   254  	big16     = big.NewInt(16)
   255  	big20     = big.NewInt(20)
   256  	big32     = big.NewInt(32)
   257  	big64     = big.NewInt(64)
   258  	big96     = big.NewInt(96)
   259  	big480    = big.NewInt(480)
   260  	big1024   = big.NewInt(1024)
   261  	big3072   = big.NewInt(3072)
   262  	big199680 = big.NewInt(199680)
   263  )
   264  
   265  // modexpMultComplexity implements bigModexp multComplexity formula, as defined in EIP-198
   266  //
   267  // def mult_complexity(x):
   268  //    if x <= 64: return x ** 2
   269  //    elif x <= 1024: return x ** 2 // 4 + 96 * x - 3072
   270  //    else: return x ** 2 // 16 + 480 * x - 199680
   271  //
   272  // where is x is max(length_of_MODULUS, length_of_BASE)
   273  func modexpMultComplexity(x *big.Int) *big.Int {
   274  	switch {
   275  	case x.Cmp(big64) <= 0:
   276  		x.Mul(x, x) // x ** 2
   277  	case x.Cmp(big1024) <= 0:
   278  		// (x ** 2 // 4 ) + ( 96 * x - 3072)
   279  		x = new(big.Int).Add(
   280  			new(big.Int).Div(new(big.Int).Mul(x, x), big4),
   281  			new(big.Int).Sub(new(big.Int).Mul(big96, x), big3072),
   282  		)
   283  	default:
   284  		// (x ** 2 // 16) + (480 * x - 199680)
   285  		x = new(big.Int).Add(
   286  			new(big.Int).Div(new(big.Int).Mul(x, x), big16),
   287  			new(big.Int).Sub(new(big.Int).Mul(big480, x), big199680),
   288  		)
   289  	}
   290  	return x
   291  }
   292  
   293  // RequiredGas returns the gas required to execute the pre-compiled contract.
   294  func (c *bigModExp) RequiredGas(input []byte) uint64 {
   295  	var (
   296  		baseLen = new(big.Int).SetBytes(getData(input, 0, 32))
   297  		expLen  = new(big.Int).SetBytes(getData(input, 32, 32))
   298  		modLen  = new(big.Int).SetBytes(getData(input, 64, 32))
   299  	)
   300  	if len(input) > 96 {
   301  		input = input[96:]
   302  	} else {
   303  		input = input[:0]
   304  	}
   305  	// Retrieve the head 32 bytes of exp for the adjusted exponent length
   306  	var expHead *big.Int
   307  	if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 {
   308  		expHead = new(big.Int)
   309  	} else {
   310  		if expLen.Cmp(big32) > 0 {
   311  			expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), 32))
   312  		} else {
   313  			expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), expLen.Uint64()))
   314  		}
   315  	}
   316  	// Calculate the adjusted exponent length
   317  	var msb int
   318  	if bitlen := expHead.BitLen(); bitlen > 0 {
   319  		msb = bitlen - 1
   320  	}
   321  	adjExpLen := new(big.Int)
   322  	if expLen.Cmp(big32) > 0 {
   323  		adjExpLen.Sub(expLen, big32)
   324  		adjExpLen.Mul(big8, adjExpLen)
   325  	}
   326  	adjExpLen.Add(adjExpLen, big.NewInt(int64(msb)))
   327  	// Calculate the gas cost of the operation
   328  	gas := new(big.Int).Set(math.BigMax(modLen, baseLen))
   329  	if c.eip2565 {
   330  		// EIP-2565 has three changes
   331  		// 1. Different multComplexity (inlined here)
   332  		// in EIP-2565 (https://eips.ethereum.org/EIPS/eip-2565):
   333  		//
   334  		// def mult_complexity(x):
   335  		//    ceiling(x/8)^2
   336  		//
   337  		//where is x is max(length_of_MODULUS, length_of_BASE)
   338  		gas = gas.Add(gas, big7)
   339  		gas = gas.Div(gas, big8)
   340  		gas.Mul(gas, gas)
   341  
   342  		gas.Mul(gas, math.BigMax(adjExpLen, big1))
   343  		// 2. Different divisor (`GQUADDIVISOR`) (3)
   344  		gas.Div(gas, big3)
   345  		if gas.BitLen() > 64 {
   346  			return math.MaxUint64
   347  		}
   348  		// 3. Minimum price of 200 gas
   349  		if gas.Uint64() < 200 {
   350  			return 200
   351  		}
   352  		return gas.Uint64()
   353  	}
   354  	gas = modexpMultComplexity(gas)
   355  	gas.Mul(gas, math.BigMax(adjExpLen, big1))
   356  	gas.Div(gas, big20)
   357  
   358  	if gas.BitLen() > 64 {
   359  		return math.MaxUint64
   360  	}
   361  	return gas.Uint64()
   362  }
   363  
   364  func (c *bigModExp) Run(input []byte) ([]byte, error) {
   365  	var (
   366  		baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64()
   367  		expLen  = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64()
   368  		modLen  = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64()
   369  	)
   370  	if len(input) > 96 {
   371  		input = input[96:]
   372  	} else {
   373  		input = input[:0]
   374  	}
   375  	// Handle a special case when both the base and mod length is zero
   376  	if baseLen == 0 && modLen == 0 {
   377  		return []byte{}, nil
   378  	}
   379  	// Retrieve the operands and execute the exponentiation
   380  	var (
   381  		base = new(big.Int).SetBytes(getData(input, 0, baseLen))
   382  		exp  = new(big.Int).SetBytes(getData(input, baseLen, expLen))
   383  		mod  = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen))
   384  	)
   385  	if mod.BitLen() == 0 {
   386  		// Modulo 0 is undefined, return zero
   387  		return common.LeftPadBytes([]byte{}, int(modLen)), nil
   388  	}
   389  	return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil
   390  }
   391  
   392  // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point,
   393  // returning it, or an error if the point is invalid.
   394  func newCurvePoint(blob []byte) (*bn256.G1, error) {
   395  	p := new(bn256.G1)
   396  	if _, err := p.Unmarshal(blob); err != nil {
   397  		return nil, err
   398  	}
   399  	return p, nil
   400  }
   401  
   402  // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point,
   403  // returning it, or an error if the point is invalid.
   404  func newTwistPoint(blob []byte) (*bn256.G2, error) {
   405  	p := new(bn256.G2)
   406  	if _, err := p.Unmarshal(blob); err != nil {
   407  		return nil, err
   408  	}
   409  	return p, nil
   410  }
   411  
   412  // runBn256Add implements the Bn256Add precompile, referenced by both
   413  // Byzantium and Istanbul operations.
   414  func runBn256Add(input []byte) ([]byte, error) {
   415  	x, err := newCurvePoint(getData(input, 0, 64))
   416  	if err != nil {
   417  		return nil, err
   418  	}
   419  	y, err := newCurvePoint(getData(input, 64, 64))
   420  	if err != nil {
   421  		return nil, err
   422  	}
   423  	res := new(bn256.G1)
   424  	res.Add(x, y)
   425  	return res.Marshal(), nil
   426  }
   427  
   428  // bn256Add implements a native elliptic curve point addition conforming to
   429  // Istanbul consensus rules.
   430  type bn256AddIstanbul struct{}
   431  
   432  // RequiredGas returns the gas required to execute the pre-compiled contract.
   433  func (c *bn256AddIstanbul) RequiredGas(input []byte) uint64 {
   434  	return params.Bn256AddGasIstanbul
   435  }
   436  
   437  func (c *bn256AddIstanbul) Run(input []byte) ([]byte, error) {
   438  	return runBn256Add(input)
   439  }
   440  
   441  // bn256AddByzantium implements a native elliptic curve point addition
   442  // conforming to Byzantium consensus rules.
   443  type bn256AddByzantium struct{}
   444  
   445  // RequiredGas returns the gas required to execute the pre-compiled contract.
   446  func (c *bn256AddByzantium) RequiredGas(input []byte) uint64 {
   447  	return params.Bn256AddGasByzantium
   448  }
   449  
   450  func (c *bn256AddByzantium) Run(input []byte) ([]byte, error) {
   451  	return runBn256Add(input)
   452  }
   453  
   454  // runBn256ScalarMul implements the Bn256ScalarMul precompile, referenced by
   455  // both Byzantium and Istanbul operations.
   456  func runBn256ScalarMul(input []byte) ([]byte, error) {
   457  	p, err := newCurvePoint(getData(input, 0, 64))
   458  	if err != nil {
   459  		return nil, err
   460  	}
   461  	res := new(bn256.G1)
   462  	res.ScalarMult(p, new(big.Int).SetBytes(getData(input, 64, 32)))
   463  	return res.Marshal(), nil
   464  }
   465  
   466  // bn256ScalarMulIstanbul implements a native elliptic curve scalar
   467  // multiplication conforming to Istanbul consensus rules.
   468  type bn256ScalarMulIstanbul struct{}
   469  
   470  // RequiredGas returns the gas required to execute the pre-compiled contract.
   471  func (c *bn256ScalarMulIstanbul) RequiredGas(input []byte) uint64 {
   472  	return params.Bn256ScalarMulGasIstanbul
   473  }
   474  
   475  func (c *bn256ScalarMulIstanbul) Run(input []byte) ([]byte, error) {
   476  	return runBn256ScalarMul(input)
   477  }
   478  
   479  // bn256ScalarMulByzantium implements a native elliptic curve scalar
   480  // multiplication conforming to Byzantium consensus rules.
   481  type bn256ScalarMulByzantium struct{}
   482  
   483  // RequiredGas returns the gas required to execute the pre-compiled contract.
   484  func (c *bn256ScalarMulByzantium) RequiredGas(input []byte) uint64 {
   485  	return params.Bn256ScalarMulGasByzantium
   486  }
   487  
   488  func (c *bn256ScalarMulByzantium) Run(input []byte) ([]byte, error) {
   489  	return runBn256ScalarMul(input)
   490  }
   491  
   492  var (
   493  	// true32Byte is returned if the bn256 pairing check succeeds.
   494  	true32Byte = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
   495  
   496  	// false32Byte is returned if the bn256 pairing check fails.
   497  	false32Byte = make([]byte, 32)
   498  
   499  	// errBadPairingInput is returned if the bn256 pairing input is invalid.
   500  	errBadPairingInput = errors.New("bad elliptic curve pairing size")
   501  )
   502  
   503  // runBn256Pairing implements the Bn256Pairing precompile, referenced by both
   504  // Byzantium and Istanbul operations.
   505  func runBn256Pairing(input []byte) ([]byte, error) {
   506  	// Handle some corner cases cheaply
   507  	if len(input)%192 > 0 {
   508  		return nil, errBadPairingInput
   509  	}
   510  	// Convert the input into a set of coordinates
   511  	var (
   512  		cs []*bn256.G1
   513  		ts []*bn256.G2
   514  	)
   515  	for i := 0; i < len(input); i += 192 {
   516  		c, err := newCurvePoint(input[i : i+64])
   517  		if err != nil {
   518  			return nil, err
   519  		}
   520  		t, err := newTwistPoint(input[i+64 : i+192])
   521  		if err != nil {
   522  			return nil, err
   523  		}
   524  		cs = append(cs, c)
   525  		ts = append(ts, t)
   526  	}
   527  	// Execute the pairing checks and return the results
   528  	if bn256.PairingCheck(cs, ts) {
   529  		return true32Byte, nil
   530  	}
   531  	return false32Byte, nil
   532  }
   533  
   534  // bn256PairingIstanbul implements a pairing pre-compile for the bn256 curve
   535  // conforming to Istanbul consensus rules.
   536  type bn256PairingIstanbul struct{}
   537  
   538  // RequiredGas returns the gas required to execute the pre-compiled contract.
   539  func (c *bn256PairingIstanbul) RequiredGas(input []byte) uint64 {
   540  	return params.Bn256PairingBaseGasIstanbul + uint64(len(input)/192)*params.Bn256PairingPerPointGasIstanbul
   541  }
   542  
   543  func (c *bn256PairingIstanbul) Run(input []byte) ([]byte, error) {
   544  	return runBn256Pairing(input)
   545  }
   546  
   547  // bn256PairingByzantium implements a pairing pre-compile for the bn256 curve
   548  // conforming to Byzantium consensus rules.
   549  type bn256PairingByzantium struct{}
   550  
   551  // RequiredGas returns the gas required to execute the pre-compiled contract.
   552  func (c *bn256PairingByzantium) RequiredGas(input []byte) uint64 {
   553  	return params.Bn256PairingBaseGasByzantium + uint64(len(input)/192)*params.Bn256PairingPerPointGasByzantium
   554  }
   555  
   556  func (c *bn256PairingByzantium) Run(input []byte) ([]byte, error) {
   557  	return runBn256Pairing(input)
   558  }
   559  
   560  type blake2F struct{}
   561  
   562  func (c *blake2F) RequiredGas(input []byte) uint64 {
   563  	// If the input is malformed, we can't calculate the gas, return 0 and let the
   564  	// actual call choke and fault.
   565  	if len(input) != blake2FInputLength {
   566  		return 0
   567  	}
   568  	return uint64(binary.BigEndian.Uint32(input[0:4]))
   569  }
   570  
   571  const (
   572  	blake2FInputLength        = 213
   573  	blake2FFinalBlockBytes    = byte(1)
   574  	blake2FNonFinalBlockBytes = byte(0)
   575  )
   576  
   577  var (
   578  	errBlake2FInvalidInputLength = errors.New("invalid input length")
   579  	errBlake2FInvalidFinalFlag   = errors.New("invalid final flag")
   580  )
   581  
   582  func (c *blake2F) Run(input []byte) ([]byte, error) {
   583  	// Make sure the input is valid (correct length and final flag)
   584  	if len(input) != blake2FInputLength {
   585  		return nil, errBlake2FInvalidInputLength
   586  	}
   587  	if input[212] != blake2FNonFinalBlockBytes && input[212] != blake2FFinalBlockBytes {
   588  		return nil, errBlake2FInvalidFinalFlag
   589  	}
   590  	// Parse the input into the Blake2b call parameters
   591  	var (
   592  		rounds = binary.BigEndian.Uint32(input[0:4])
   593  		final  = (input[212] == blake2FFinalBlockBytes)
   594  
   595  		h [8]uint64
   596  		m [16]uint64
   597  		t [2]uint64
   598  	)
   599  	for i := 0; i < 8; i++ {
   600  		offset := 4 + i*8
   601  		h[i] = binary.LittleEndian.Uint64(input[offset : offset+8])
   602  	}
   603  	for i := 0; i < 16; i++ {
   604  		offset := 68 + i*8
   605  		m[i] = binary.LittleEndian.Uint64(input[offset : offset+8])
   606  	}
   607  	t[0] = binary.LittleEndian.Uint64(input[196:204])
   608  	t[1] = binary.LittleEndian.Uint64(input[204:212])
   609  
   610  	// Execute the compression function, extract and return the result
   611  	blake2b.F(&h, m, t, final, rounds)
   612  
   613  	output := make([]byte, 64)
   614  	for i := 0; i < 8; i++ {
   615  		offset := i * 8
   616  		binary.LittleEndian.PutUint64(output[offset:offset+8], h[i])
   617  	}
   618  	return output, nil
   619  }
   620  
   621  var (
   622  	errBLS12381InvalidInputLength          = errors.New("invalid input length")
   623  	errBLS12381InvalidFieldElementTopBytes = errors.New("invalid field element top bytes")
   624  	errBLS12381G1PointSubgroup             = errors.New("g1 point is not on correct subgroup")
   625  	errBLS12381G2PointSubgroup             = errors.New("g2 point is not on correct subgroup")
   626  )
   627  
   628  // bls12381G1Add implements EIP-2537 G1Add precompile.
   629  type bls12381G1Add struct{}
   630  
   631  // RequiredGas returns the gas required to execute the pre-compiled contract.
   632  func (c *bls12381G1Add) RequiredGas(input []byte) uint64 {
   633  	return params.Bls12381G1AddGas
   634  }
   635  
   636  func (c *bls12381G1Add) Run(input []byte) ([]byte, error) {
   637  	// Implements EIP-2537 G1Add precompile.
   638  	// > G1 addition call expects `256` bytes as an input that is interpreted as byte concatenation of two G1 points (`128` bytes each).
   639  	// > Output is an encoding of addition operation result - single G1 point (`128` bytes).
   640  	if len(input) != 256 {
   641  		return nil, errBLS12381InvalidInputLength
   642  	}
   643  	var err error
   644  	var p0, p1 *bls12381.PointG1
   645  
   646  	// Initialize G1
   647  	g := bls12381.NewG1()
   648  
   649  	// Decode G1 point p_0
   650  	if p0, err = g.DecodePoint(input[:128]); err != nil {
   651  		return nil, err
   652  	}
   653  	// Decode G1 point p_1
   654  	if p1, err = g.DecodePoint(input[128:]); err != nil {
   655  		return nil, err
   656  	}
   657  
   658  	// Compute r = p_0 + p_1
   659  	r := g.New()
   660  	g.Add(r, p0, p1)
   661  
   662  	// Encode the G1 point result into 128 bytes
   663  	return g.EncodePoint(r), nil
   664  }
   665  
   666  // bls12381G1Mul implements EIP-2537 G1Mul precompile.
   667  type bls12381G1Mul struct{}
   668  
   669  // RequiredGas returns the gas required to execute the pre-compiled contract.
   670  func (c *bls12381G1Mul) RequiredGas(input []byte) uint64 {
   671  	return params.Bls12381G1MulGas
   672  }
   673  
   674  func (c *bls12381G1Mul) Run(input []byte) ([]byte, error) {
   675  	// Implements EIP-2537 G1Mul precompile.
   676  	// > 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).
   677  	// > Output is an encoding of multiplication operation result - single G1 point (`128` bytes).
   678  	if len(input) != 160 {
   679  		return nil, errBLS12381InvalidInputLength
   680  	}
   681  	var err error
   682  	var p0 *bls12381.PointG1
   683  
   684  	// Initialize G1
   685  	g := bls12381.NewG1()
   686  
   687  	// Decode G1 point
   688  	if p0, err = g.DecodePoint(input[:128]); err != nil {
   689  		return nil, err
   690  	}
   691  	// Decode scalar value
   692  	e := new(big.Int).SetBytes(input[128:])
   693  
   694  	// Compute r = e * p_0
   695  	r := g.New()
   696  	g.MulScalar(r, p0, e)
   697  
   698  	// Encode the G1 point into 128 bytes
   699  	return g.EncodePoint(r), nil
   700  }
   701  
   702  // bls12381G1MultiExp implements EIP-2537 G1MultiExp precompile.
   703  type bls12381G1MultiExp struct{}
   704  
   705  // RequiredGas returns the gas required to execute the pre-compiled contract.
   706  func (c *bls12381G1MultiExp) RequiredGas(input []byte) uint64 {
   707  	// Calculate G1 point, scalar value pair length
   708  	k := len(input) / 160
   709  	if k == 0 {
   710  		// Return 0 gas for small input length
   711  		return 0
   712  	}
   713  	// Lookup discount value for G1 point, scalar value pair length
   714  	var discount uint64
   715  	if dLen := len(params.Bls12381MultiExpDiscountTable); k < dLen {
   716  		discount = params.Bls12381MultiExpDiscountTable[k-1]
   717  	} else {
   718  		discount = params.Bls12381MultiExpDiscountTable[dLen-1]
   719  	}
   720  	// Calculate gas and return the result
   721  	return (uint64(k) * params.Bls12381G1MulGas * discount) / 1000
   722  }
   723  
   724  func (c *bls12381G1MultiExp) Run(input []byte) ([]byte, error) {
   725  	// Implements EIP-2537 G1MultiExp precompile.
   726  	// 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).
   727  	// Output is an encoding of multiexponentiation operation result - single G1 point (`128` bytes).
   728  	k := len(input) / 160
   729  	if len(input) == 0 || len(input)%160 != 0 {
   730  		return nil, errBLS12381InvalidInputLength
   731  	}
   732  	var err error
   733  	points := make([]*bls12381.PointG1, k)
   734  	scalars := make([]*big.Int, k)
   735  
   736  	// Initialize G1
   737  	g := bls12381.NewG1()
   738  
   739  	// Decode point scalar pairs
   740  	for i := 0; i < k; i++ {
   741  		off := 160 * i
   742  		t0, t1, t2 := off, off+128, off+160
   743  		// Decode G1 point
   744  		if points[i], err = g.DecodePoint(input[t0:t1]); err != nil {
   745  			return nil, err
   746  		}
   747  		// Decode scalar value
   748  		scalars[i] = new(big.Int).SetBytes(input[t1:t2])
   749  	}
   750  
   751  	// Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1)
   752  	r := g.New()
   753  	g.MultiExp(r, points, scalars)
   754  
   755  	// Encode the G1 point to 128 bytes
   756  	return g.EncodePoint(r), nil
   757  }
   758  
   759  // bls12381G2Add implements EIP-2537 G2Add precompile.
   760  type bls12381G2Add struct{}
   761  
   762  // RequiredGas returns the gas required to execute the pre-compiled contract.
   763  func (c *bls12381G2Add) RequiredGas(input []byte) uint64 {
   764  	return params.Bls12381G2AddGas
   765  }
   766  
   767  func (c *bls12381G2Add) Run(input []byte) ([]byte, error) {
   768  	// Implements EIP-2537 G2Add precompile.
   769  	// > G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each).
   770  	// > Output is an encoding of addition operation result - single G2 point (`256` bytes).
   771  	if len(input) != 512 {
   772  		return nil, errBLS12381InvalidInputLength
   773  	}
   774  	var err error
   775  	var p0, p1 *bls12381.PointG2
   776  
   777  	// Initialize G2
   778  	g := bls12381.NewG2()
   779  	r := g.New()
   780  
   781  	// Decode G2 point p_0
   782  	if p0, err = g.DecodePoint(input[:256]); err != nil {
   783  		return nil, err
   784  	}
   785  	// Decode G2 point p_1
   786  	if p1, err = g.DecodePoint(input[256:]); err != nil {
   787  		return nil, err
   788  	}
   789  
   790  	// Compute r = p_0 + p_1
   791  	g.Add(r, p0, p1)
   792  
   793  	// Encode the G2 point into 256 bytes
   794  	return g.EncodePoint(r), nil
   795  }
   796  
   797  // bls12381G2Mul implements EIP-2537 G2Mul precompile.
   798  type bls12381G2Mul struct{}
   799  
   800  // RequiredGas returns the gas required to execute the pre-compiled contract.
   801  func (c *bls12381G2Mul) RequiredGas(input []byte) uint64 {
   802  	return params.Bls12381G2MulGas
   803  }
   804  
   805  func (c *bls12381G2Mul) Run(input []byte) ([]byte, error) {
   806  	// Implements EIP-2537 G2MUL precompile logic.
   807  	// > 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).
   808  	// > Output is an encoding of multiplication operation result - single G2 point (`256` bytes).
   809  	if len(input) != 288 {
   810  		return nil, errBLS12381InvalidInputLength
   811  	}
   812  	var err error
   813  	var p0 *bls12381.PointG2
   814  
   815  	// Initialize G2
   816  	g := bls12381.NewG2()
   817  
   818  	// Decode G2 point
   819  	if p0, err = g.DecodePoint(input[:256]); err != nil {
   820  		return nil, err
   821  	}
   822  	// Decode scalar value
   823  	e := new(big.Int).SetBytes(input[256:])
   824  
   825  	// Compute r = e * p_0
   826  	r := g.New()
   827  	g.MulScalar(r, p0, e)
   828  
   829  	// Encode the G2 point into 256 bytes
   830  	return g.EncodePoint(r), nil
   831  }
   832  
   833  // bls12381G2MultiExp implements EIP-2537 G2MultiExp precompile.
   834  type bls12381G2MultiExp struct{}
   835  
   836  // RequiredGas returns the gas required to execute the pre-compiled contract.
   837  func (c *bls12381G2MultiExp) RequiredGas(input []byte) uint64 {
   838  	// Calculate G2 point, scalar value pair length
   839  	k := len(input) / 288
   840  	if k == 0 {
   841  		// Return 0 gas for small input length
   842  		return 0
   843  	}
   844  	// Lookup discount value for G2 point, scalar value pair length
   845  	var discount uint64
   846  	if dLen := len(params.Bls12381MultiExpDiscountTable); k < dLen {
   847  		discount = params.Bls12381MultiExpDiscountTable[k-1]
   848  	} else {
   849  		discount = params.Bls12381MultiExpDiscountTable[dLen-1]
   850  	}
   851  	// Calculate gas and return the result
   852  	return (uint64(k) * params.Bls12381G2MulGas * discount) / 1000
   853  }
   854  
   855  func (c *bls12381G2MultiExp) Run(input []byte) ([]byte, error) {
   856  	// Implements EIP-2537 G2MultiExp precompile logic
   857  	// > 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).
   858  	// > Output is an encoding of multiexponentiation operation result - single G2 point (`256` bytes).
   859  	k := len(input) / 288
   860  	if len(input) == 0 || len(input)%288 != 0 {
   861  		return nil, errBLS12381InvalidInputLength
   862  	}
   863  	var err error
   864  	points := make([]*bls12381.PointG2, k)
   865  	scalars := make([]*big.Int, k)
   866  
   867  	// Initialize G2
   868  	g := bls12381.NewG2()
   869  
   870  	// Decode point scalar pairs
   871  	for i := 0; i < k; i++ {
   872  		off := 288 * i
   873  		t0, t1, t2 := off, off+256, off+288
   874  		// Decode G1 point
   875  		if points[i], err = g.DecodePoint(input[t0:t1]); err != nil {
   876  			return nil, err
   877  		}
   878  		// Decode scalar value
   879  		scalars[i] = new(big.Int).SetBytes(input[t1:t2])
   880  	}
   881  
   882  	// Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1)
   883  	r := g.New()
   884  	g.MultiExp(r, points, scalars)
   885  
   886  	// Encode the G2 point to 256 bytes.
   887  	return g.EncodePoint(r), nil
   888  }
   889  
   890  // bls12381Pairing implements EIP-2537 Pairing precompile.
   891  type bls12381Pairing struct{}
   892  
   893  // RequiredGas returns the gas required to execute the pre-compiled contract.
   894  func (c *bls12381Pairing) RequiredGas(input []byte) uint64 {
   895  	return params.Bls12381PairingBaseGas + uint64(len(input)/384)*params.Bls12381PairingPerPairGas
   896  }
   897  
   898  func (c *bls12381Pairing) Run(input []byte) ([]byte, error) {
   899  	// Implements EIP-2537 Pairing precompile logic.
   900  	// > Pairing call expects `384*k` bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure:
   901  	// > - `128` bytes of G1 point encoding
   902  	// > - `256` bytes of G2 point encoding
   903  	// > 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
   904  	// > (which is equivalent of Big Endian encoding of Solidity values `uint256(1)` and `uin256(0)` respectively).
   905  	k := len(input) / 384
   906  	if len(input) == 0 || len(input)%384 != 0 {
   907  		return nil, errBLS12381InvalidInputLength
   908  	}
   909  
   910  	// Initialize BLS12-381 pairing engine
   911  	e := bls12381.NewPairingEngine()
   912  	g1, g2 := e.G1, e.G2
   913  
   914  	// Decode pairs
   915  	for i := 0; i < k; i++ {
   916  		off := 384 * i
   917  		t0, t1, t2 := off, off+128, off+384
   918  
   919  		// Decode G1 point
   920  		p1, err := g1.DecodePoint(input[t0:t1])
   921  		if err != nil {
   922  			return nil, err
   923  		}
   924  		// Decode G2 point
   925  		p2, err := g2.DecodePoint(input[t1:t2])
   926  		if err != nil {
   927  			return nil, err
   928  		}
   929  
   930  		// 'point is on curve' check already done,
   931  		// Here we need to apply subgroup checks.
   932  		if !g1.InCorrectSubgroup(p1) {
   933  			return nil, errBLS12381G1PointSubgroup
   934  		}
   935  		if !g2.InCorrectSubgroup(p2) {
   936  			return nil, errBLS12381G2PointSubgroup
   937  		}
   938  
   939  		// Update pairing engine with G1 and G2 ponits
   940  		e.AddPair(p1, p2)
   941  	}
   942  	// Prepare 32 byte output
   943  	out := make([]byte, 32)
   944  
   945  	// Compute pairing and set the result
   946  	if e.Check() {
   947  		out[31] = 1
   948  	}
   949  	return out, nil
   950  }
   951  
   952  // decodeBLS12381FieldElement decodes BLS12-381 elliptic curve field element.
   953  // Removes top 16 bytes of 64 byte input.
   954  func decodeBLS12381FieldElement(in []byte) ([]byte, error) {
   955  	if len(in) != 64 {
   956  		return nil, errors.New("invalid field element length")
   957  	}
   958  	// check top bytes
   959  	for i := 0; i < 16; i++ {
   960  		if in[i] != byte(0x00) {
   961  			return nil, errBLS12381InvalidFieldElementTopBytes
   962  		}
   963  	}
   964  	out := make([]byte, 48)
   965  	copy(out[:], in[16:])
   966  	return out, nil
   967  }
   968  
   969  // bls12381MapG1 implements EIP-2537 MapG1 precompile.
   970  type bls12381MapG1 struct{}
   971  
   972  // RequiredGas returns the gas required to execute the pre-compiled contract.
   973  func (c *bls12381MapG1) RequiredGas(input []byte) uint64 {
   974  	return params.Bls12381MapG1Gas
   975  }
   976  
   977  func (c *bls12381MapG1) Run(input []byte) ([]byte, error) {
   978  	// Implements EIP-2537 Map_To_G1 precompile.
   979  	// > Field-to-curve call expects `64` bytes an an input that is interpreted as a an element of the base field.
   980  	// > Output of this call is `128` bytes and is G1 point following respective encoding rules.
   981  	if len(input) != 64 {
   982  		return nil, errBLS12381InvalidInputLength
   983  	}
   984  
   985  	// Decode input field element
   986  	fe, err := decodeBLS12381FieldElement(input)
   987  	if err != nil {
   988  		return nil, err
   989  	}
   990  
   991  	// Initialize G1
   992  	g := bls12381.NewG1()
   993  
   994  	// Compute mapping
   995  	r, err := g.MapToCurve(fe)
   996  	if err != nil {
   997  		return nil, err
   998  	}
   999  
  1000  	// Encode the G1 point to 128 bytes
  1001  	return g.EncodePoint(r), nil
  1002  }
  1003  
  1004  // bls12381MapG2 implements EIP-2537 MapG2 precompile.
  1005  type bls12381MapG2 struct{}
  1006  
  1007  // RequiredGas returns the gas required to execute the pre-compiled contract.
  1008  func (c *bls12381MapG2) RequiredGas(input []byte) uint64 {
  1009  	return params.Bls12381MapG2Gas
  1010  }
  1011  
  1012  func (c *bls12381MapG2) Run(input []byte) ([]byte, error) {
  1013  	// Implements EIP-2537 Map_FP2_TO_G2 precompile logic.
  1014  	// > Field-to-curve call expects `128` bytes an an input that is interpreted as a an element of the quadratic extension field.
  1015  	// > Output of this call is `256` bytes and is G2 point following respective encoding rules.
  1016  	if len(input) != 128 {
  1017  		return nil, errBLS12381InvalidInputLength
  1018  	}
  1019  
  1020  	// Decode input field element
  1021  	fe := make([]byte, 96)
  1022  	c0, err := decodeBLS12381FieldElement(input[:64])
  1023  	if err != nil {
  1024  		return nil, err
  1025  	}
  1026  	copy(fe[48:], c0)
  1027  	c1, err := decodeBLS12381FieldElement(input[64:])
  1028  	if err != nil {
  1029  		return nil, err
  1030  	}
  1031  	copy(fe[:48], c1)
  1032  
  1033  	// Initialize G2
  1034  	g := bls12381.NewG2()
  1035  
  1036  	// Compute mapping
  1037  	r, err := g.MapToCurve(fe)
  1038  	if err != nil {
  1039  		return nil, err
  1040  	}
  1041  
  1042  	// Encode the G2 point to 256 bytes
  1043  	return g.EncodePoint(r), nil
  1044  }