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