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