github.com/phillinzzz/newBsc@v1.1.6/core/vm/contracts.go (about)

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