github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/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/ethereum/go-ethereum/common"
    26  	"github.com/ethereum/go-ethereum/common/math"
    27  	"github.com/ethereum/go-ethereum/crypto"
    28  	"github.com/ethereum/go-ethereum/crypto/blake2b"
    29  	"github.com/ethereum/go-ethereum/crypto/bls12381"
    30  	"github.com/ethereum/go-ethereum/crypto/bn256"
    31  	"github.com/ethereum/go-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  	)
   384  	if mod.BitLen() == 0 {
   385  		// Modulo 0 is undefined, return zero
   386  		return common.LeftPadBytes([]byte{}, int(modLen)), nil
   387  	}
   388  	return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil
   389  }
   390  
   391  // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point,
   392  // returning it, or an error if the point is invalid.
   393  func newCurvePoint(blob []byte) (*bn256.G1, error) {
   394  	p := new(bn256.G1)
   395  	if _, err := p.Unmarshal(blob); err != nil {
   396  		return nil, err
   397  	}
   398  	return p, nil
   399  }
   400  
   401  // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point,
   402  // returning it, or an error if the point is invalid.
   403  func newTwistPoint(blob []byte) (*bn256.G2, error) {
   404  	p := new(bn256.G2)
   405  	if _, err := p.Unmarshal(blob); err != nil {
   406  		return nil, err
   407  	}
   408  	return p, nil
   409  }
   410  
   411  // runBn256Add implements the Bn256Add precompile, referenced by both
   412  // Byzantium and Istanbul operations.
   413  func runBn256Add(input []byte) ([]byte, error) {
   414  	x, err := newCurvePoint(getData(input, 0, 64))
   415  	if err != nil {
   416  		return nil, err
   417  	}
   418  	y, err := newCurvePoint(getData(input, 64, 64))
   419  	if err != nil {
   420  		return nil, err
   421  	}
   422  	res := new(bn256.G1)
   423  	res.Add(x, y)
   424  	return res.Marshal(), nil
   425  }
   426  
   427  // bn256Add implements a native elliptic curve point addition conforming to
   428  // Istanbul consensus rules.
   429  type bn256AddIstanbul struct{}
   430  
   431  // RequiredGas returns the gas required to execute the pre-compiled contract.
   432  func (c *bn256AddIstanbul) RequiredGas(input []byte) uint64 {
   433  	return params.Bn256AddGasIstanbul
   434  }
   435  
   436  func (c *bn256AddIstanbul) Run(input []byte) ([]byte, error) {
   437  	return runBn256Add(input)
   438  }
   439  
   440  // bn256AddByzantium implements a native elliptic curve point addition
   441  // conforming to Byzantium consensus rules.
   442  type bn256AddByzantium struct{}
   443  
   444  // RequiredGas returns the gas required to execute the pre-compiled contract.
   445  func (c *bn256AddByzantium) RequiredGas(input []byte) uint64 {
   446  	return params.Bn256AddGasByzantium
   447  }
   448  
   449  func (c *bn256AddByzantium) Run(input []byte) ([]byte, error) {
   450  	return runBn256Add(input)
   451  }
   452  
   453  // runBn256ScalarMul implements the Bn256ScalarMul precompile, referenced by
   454  // both Byzantium and Istanbul operations.
   455  func runBn256ScalarMul(input []byte) ([]byte, error) {
   456  	p, err := newCurvePoint(getData(input, 0, 64))
   457  	if err != nil {
   458  		return nil, err
   459  	}
   460  	res := new(bn256.G1)
   461  	res.ScalarMult(p, new(big.Int).SetBytes(getData(input, 64, 32)))
   462  	return res.Marshal(), nil
   463  }
   464  
   465  // bn256ScalarMulIstanbul implements a native elliptic curve scalar
   466  // multiplication conforming to Istanbul consensus rules.
   467  type bn256ScalarMulIstanbul struct{}
   468  
   469  // RequiredGas returns the gas required to execute the pre-compiled contract.
   470  func (c *bn256ScalarMulIstanbul) RequiredGas(input []byte) uint64 {
   471  	return params.Bn256ScalarMulGasIstanbul
   472  }
   473  
   474  func (c *bn256ScalarMulIstanbul) Run(input []byte) ([]byte, error) {
   475  	return runBn256ScalarMul(input)
   476  }
   477  
   478  // bn256ScalarMulByzantium implements a native elliptic curve scalar
   479  // multiplication conforming to Byzantium consensus rules.
   480  type bn256ScalarMulByzantium struct{}
   481  
   482  // RequiredGas returns the gas required to execute the pre-compiled contract.
   483  func (c *bn256ScalarMulByzantium) RequiredGas(input []byte) uint64 {
   484  	return params.Bn256ScalarMulGasByzantium
   485  }
   486  
   487  func (c *bn256ScalarMulByzantium) Run(input []byte) ([]byte, error) {
   488  	return runBn256ScalarMul(input)
   489  }
   490  
   491  var (
   492  	// true32Byte is returned if the bn256 pairing check succeeds.
   493  	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}
   494  
   495  	// false32Byte is returned if the bn256 pairing check fails.
   496  	false32Byte = make([]byte, 32)
   497  
   498  	// errBadPairingInput is returned if the bn256 pairing input is invalid.
   499  	errBadPairingInput = errors.New("bad elliptic curve pairing size")
   500  )
   501  
   502  // runBn256Pairing implements the Bn256Pairing precompile, referenced by both
   503  // Byzantium and Istanbul operations.
   504  func runBn256Pairing(input []byte) ([]byte, error) {
   505  	// Handle some corner cases cheaply
   506  	if len(input)%192 > 0 {
   507  		return nil, errBadPairingInput
   508  	}
   509  	// Convert the input into a set of coordinates
   510  	var (
   511  		cs []*bn256.G1
   512  		ts []*bn256.G2
   513  	)
   514  	for i := 0; i < len(input); i += 192 {
   515  		c, err := newCurvePoint(input[i : i+64])
   516  		if err != nil {
   517  			return nil, err
   518  		}
   519  		t, err := newTwistPoint(input[i+64 : i+192])
   520  		if err != nil {
   521  			return nil, err
   522  		}
   523  		cs = append(cs, c)
   524  		ts = append(ts, t)
   525  	}
   526  	// Execute the pairing checks and return the results
   527  	if bn256.PairingCheck(cs, ts) {
   528  		return true32Byte, nil
   529  	}
   530  	return false32Byte, nil
   531  }
   532  
   533  // bn256PairingIstanbul implements a pairing pre-compile for the bn256 curve
   534  // conforming to Istanbul consensus rules.
   535  type bn256PairingIstanbul struct{}
   536  
   537  // RequiredGas returns the gas required to execute the pre-compiled contract.
   538  func (c *bn256PairingIstanbul) RequiredGas(input []byte) uint64 {
   539  	return params.Bn256PairingBaseGasIstanbul + uint64(len(input)/192)*params.Bn256PairingPerPointGasIstanbul
   540  }
   541  
   542  func (c *bn256PairingIstanbul) Run(input []byte) ([]byte, error) {
   543  	return runBn256Pairing(input)
   544  }
   545  
   546  // bn256PairingByzantium implements a pairing pre-compile for the bn256 curve
   547  // conforming to Byzantium consensus rules.
   548  type bn256PairingByzantium struct{}
   549  
   550  // RequiredGas returns the gas required to execute the pre-compiled contract.
   551  func (c *bn256PairingByzantium) RequiredGas(input []byte) uint64 {
   552  	return params.Bn256PairingBaseGasByzantium + uint64(len(input)/192)*params.Bn256PairingPerPointGasByzantium
   553  }
   554  
   555  func (c *bn256PairingByzantium) Run(input []byte) ([]byte, error) {
   556  	return runBn256Pairing(input)
   557  }
   558  
   559  type blake2F struct{}
   560  
   561  func (c *blake2F) RequiredGas(input []byte) uint64 {
   562  	// If the input is malformed, we can't calculate the gas, return 0 and let the
   563  	// actual call choke and fault.
   564  	if len(input) != blake2FInputLength {
   565  		return 0
   566  	}
   567  	return uint64(binary.BigEndian.Uint32(input[0:4]))
   568  }
   569  
   570  const (
   571  	blake2FInputLength        = 213
   572  	blake2FFinalBlockBytes    = byte(1)
   573  	blake2FNonFinalBlockBytes = byte(0)
   574  )
   575  
   576  var (
   577  	errBlake2FInvalidInputLength = errors.New("invalid input length")
   578  	errBlake2FInvalidFinalFlag   = errors.New("invalid final flag")
   579  )
   580  
   581  func (c *blake2F) Run(input []byte) ([]byte, error) {
   582  	// Make sure the input is valid (correct length and final flag)
   583  	if len(input) != blake2FInputLength {
   584  		return nil, errBlake2FInvalidInputLength
   585  	}
   586  	if input[212] != blake2FNonFinalBlockBytes && input[212] != blake2FFinalBlockBytes {
   587  		return nil, errBlake2FInvalidFinalFlag
   588  	}
   589  	// Parse the input into the Blake2b call parameters
   590  	var (
   591  		rounds = binary.BigEndian.Uint32(input[0:4])
   592  		final  = input[212] == blake2FFinalBlockBytes
   593  
   594  		h [8]uint64
   595  		m [16]uint64
   596  		t [2]uint64
   597  	)
   598  	for i := 0; i < 8; i++ {
   599  		offset := 4 + i*8
   600  		h[i] = binary.LittleEndian.Uint64(input[offset : offset+8])
   601  	}
   602  	for i := 0; i < 16; i++ {
   603  		offset := 68 + i*8
   604  		m[i] = binary.LittleEndian.Uint64(input[offset : offset+8])
   605  	}
   606  	t[0] = binary.LittleEndian.Uint64(input[196:204])
   607  	t[1] = binary.LittleEndian.Uint64(input[204:212])
   608  
   609  	// Execute the compression function, extract and return the result
   610  	blake2b.F(&h, m, t, final, rounds)
   611  
   612  	output := make([]byte, 64)
   613  	for i := 0; i < 8; i++ {
   614  		offset := i * 8
   615  		binary.LittleEndian.PutUint64(output[offset:offset+8], h[i])
   616  	}
   617  	return output, nil
   618  }
   619  
   620  var (
   621  	errBLS12381InvalidInputLength          = errors.New("invalid input length")
   622  	errBLS12381InvalidFieldElementTopBytes = errors.New("invalid field element top bytes")
   623  	errBLS12381G1PointSubgroup             = errors.New("g1 point is not on correct subgroup")
   624  	errBLS12381G2PointSubgroup             = errors.New("g2 point is not on correct subgroup")
   625  )
   626  
   627  // bls12381G1Add implements EIP-2537 G1Add precompile.
   628  type bls12381G1Add struct{}
   629  
   630  // RequiredGas returns the gas required to execute the pre-compiled contract.
   631  func (c *bls12381G1Add) RequiredGas(input []byte) uint64 {
   632  	return params.Bls12381G1AddGas
   633  }
   634  
   635  func (c *bls12381G1Add) Run(input []byte) ([]byte, error) {
   636  	// Implements EIP-2537 G1Add precompile.
   637  	// > G1 addition call expects `256` bytes as an input that is interpreted as byte concatenation of two G1 points (`128` bytes each).
   638  	// > Output is an encoding of addition operation result - single G1 point (`128` bytes).
   639  	if len(input) != 256 {
   640  		return nil, errBLS12381InvalidInputLength
   641  	}
   642  	var err error
   643  	var p0, p1 *bls12381.PointG1
   644  
   645  	// Initialize G1
   646  	g := bls12381.NewG1()
   647  
   648  	// Decode G1 point p_0
   649  	if p0, err = g.DecodePoint(input[:128]); err != nil {
   650  		return nil, err
   651  	}
   652  	// Decode G1 point p_1
   653  	if p1, err = g.DecodePoint(input[128:]); err != nil {
   654  		return nil, err
   655  	}
   656  
   657  	// Compute r = p_0 + p_1
   658  	r := g.New()
   659  	g.Add(r, p0, p1)
   660  
   661  	// Encode the G1 point result into 128 bytes
   662  	return g.EncodePoint(r), nil
   663  }
   664  
   665  // bls12381G1Mul implements EIP-2537 G1Mul precompile.
   666  type bls12381G1Mul struct{}
   667  
   668  // RequiredGas returns the gas required to execute the pre-compiled contract.
   669  func (c *bls12381G1Mul) RequiredGas(input []byte) uint64 {
   670  	return params.Bls12381G1MulGas
   671  }
   672  
   673  func (c *bls12381G1Mul) Run(input []byte) ([]byte, error) {
   674  	// Implements EIP-2537 G1Mul precompile.
   675  	// > 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).
   676  	// > Output is an encoding of multiplication operation result - single G1 point (`128` bytes).
   677  	if len(input) != 160 {
   678  		return nil, errBLS12381InvalidInputLength
   679  	}
   680  	var err error
   681  	var p0 *bls12381.PointG1
   682  
   683  	// Initialize G1
   684  	g := bls12381.NewG1()
   685  
   686  	// Decode G1 point
   687  	if p0, err = g.DecodePoint(input[:128]); err != nil {
   688  		return nil, err
   689  	}
   690  	// Decode scalar value
   691  	e := new(big.Int).SetBytes(input[128:])
   692  
   693  	// Compute r = e * p_0
   694  	r := g.New()
   695  	g.MulScalar(r, p0, e)
   696  
   697  	// Encode the G1 point into 128 bytes
   698  	return g.EncodePoint(r), nil
   699  }
   700  
   701  // bls12381G1MultiExp implements EIP-2537 G1MultiExp precompile.
   702  type bls12381G1MultiExp struct{}
   703  
   704  // RequiredGas returns the gas required to execute the pre-compiled contract.
   705  func (c *bls12381G1MultiExp) RequiredGas(input []byte) uint64 {
   706  	// Calculate G1 point, scalar value pair length
   707  	k := len(input) / 160
   708  	if k == 0 {
   709  		// Return 0 gas for small input length
   710  		return 0
   711  	}
   712  	// Lookup discount value for G1 point, scalar value pair length
   713  	var discount uint64
   714  	if dLen := len(params.Bls12381MultiExpDiscountTable); k < dLen {
   715  		discount = params.Bls12381MultiExpDiscountTable[k-1]
   716  	} else {
   717  		discount = params.Bls12381MultiExpDiscountTable[dLen-1]
   718  	}
   719  	// Calculate gas and return the result
   720  	return (uint64(k) * params.Bls12381G1MulGas * discount) / 1000
   721  }
   722  
   723  func (c *bls12381G1MultiExp) Run(input []byte) ([]byte, error) {
   724  	// Implements EIP-2537 G1MultiExp precompile.
   725  	// 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).
   726  	// Output is an encoding of multiexponentiation operation result - single G1 point (`128` bytes).
   727  	k := len(input) / 160
   728  	if len(input) == 0 || len(input)%160 != 0 {
   729  		return nil, errBLS12381InvalidInputLength
   730  	}
   731  	var err error
   732  	points := make([]*bls12381.PointG1, k)
   733  	scalars := make([]*big.Int, k)
   734  
   735  	// Initialize G1
   736  	g := bls12381.NewG1()
   737  
   738  	// Decode point scalar pairs
   739  	for i := 0; i < k; i++ {
   740  		off := 160 * i
   741  		t0, t1, t2 := off, off+128, off+160
   742  		// Decode G1 point
   743  		if points[i], err = g.DecodePoint(input[t0:t1]); err != nil {
   744  			return nil, err
   745  		}
   746  		// Decode scalar value
   747  		scalars[i] = new(big.Int).SetBytes(input[t1:t2])
   748  	}
   749  
   750  	// Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1)
   751  	r := g.New()
   752  	g.MultiExp(r, points, scalars)
   753  
   754  	// Encode the G1 point to 128 bytes
   755  	return g.EncodePoint(r), nil
   756  }
   757  
   758  // bls12381G2Add implements EIP-2537 G2Add precompile.
   759  type bls12381G2Add struct{}
   760  
   761  // RequiredGas returns the gas required to execute the pre-compiled contract.
   762  func (c *bls12381G2Add) RequiredGas(input []byte) uint64 {
   763  	return params.Bls12381G2AddGas
   764  }
   765  
   766  func (c *bls12381G2Add) Run(input []byte) ([]byte, error) {
   767  	// Implements EIP-2537 G2Add precompile.
   768  	// > G2 addition call expects `512` bytes as an input that is interpreted as byte concatenation of two G2 points (`256` bytes each).
   769  	// > Output is an encoding of addition operation result - single G2 point (`256` bytes).
   770  	if len(input) != 512 {
   771  		return nil, errBLS12381InvalidInputLength
   772  	}
   773  	var err error
   774  	var p0, p1 *bls12381.PointG2
   775  
   776  	// Initialize G2
   777  	g := bls12381.NewG2()
   778  	r := g.New()
   779  
   780  	// Decode G2 point p_0
   781  	if p0, err = g.DecodePoint(input[:256]); err != nil {
   782  		return nil, err
   783  	}
   784  	// Decode G2 point p_1
   785  	if p1, err = g.DecodePoint(input[256:]); err != nil {
   786  		return nil, err
   787  	}
   788  
   789  	// Compute r = p_0 + p_1
   790  	g.Add(r, p0, p1)
   791  
   792  	// Encode the G2 point into 256 bytes
   793  	return g.EncodePoint(r), nil
   794  }
   795  
   796  // bls12381G2Mul implements EIP-2537 G2Mul precompile.
   797  type bls12381G2Mul struct{}
   798  
   799  // RequiredGas returns the gas required to execute the pre-compiled contract.
   800  func (c *bls12381G2Mul) RequiredGas(input []byte) uint64 {
   801  	return params.Bls12381G2MulGas
   802  }
   803  
   804  func (c *bls12381G2Mul) Run(input []byte) ([]byte, error) {
   805  	// Implements EIP-2537 G2MUL precompile logic.
   806  	// > 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).
   807  	// > Output is an encoding of multiplication operation result - single G2 point (`256` bytes).
   808  	if len(input) != 288 {
   809  		return nil, errBLS12381InvalidInputLength
   810  	}
   811  	var err error
   812  	var p0 *bls12381.PointG2
   813  
   814  	// Initialize G2
   815  	g := bls12381.NewG2()
   816  
   817  	// Decode G2 point
   818  	if p0, err = g.DecodePoint(input[:256]); err != nil {
   819  		return nil, err
   820  	}
   821  	// Decode scalar value
   822  	e := new(big.Int).SetBytes(input[256:])
   823  
   824  	// Compute r = e * p_0
   825  	r := g.New()
   826  	g.MulScalar(r, p0, e)
   827  
   828  	// Encode the G2 point into 256 bytes
   829  	return g.EncodePoint(r), nil
   830  }
   831  
   832  // bls12381G2MultiExp implements EIP-2537 G2MultiExp precompile.
   833  type bls12381G2MultiExp struct{}
   834  
   835  // RequiredGas returns the gas required to execute the pre-compiled contract.
   836  func (c *bls12381G2MultiExp) RequiredGas(input []byte) uint64 {
   837  	// Calculate G2 point, scalar value pair length
   838  	k := len(input) / 288
   839  	if k == 0 {
   840  		// Return 0 gas for small input length
   841  		return 0
   842  	}
   843  	// Lookup discount value for G2 point, scalar value pair length
   844  	var discount uint64
   845  	if dLen := len(params.Bls12381MultiExpDiscountTable); k < dLen {
   846  		discount = params.Bls12381MultiExpDiscountTable[k-1]
   847  	} else {
   848  		discount = params.Bls12381MultiExpDiscountTable[dLen-1]
   849  	}
   850  	// Calculate gas and return the result
   851  	return (uint64(k) * params.Bls12381G2MulGas * discount) / 1000
   852  }
   853  
   854  func (c *bls12381G2MultiExp) Run(input []byte) ([]byte, error) {
   855  	// Implements EIP-2537 G2MultiExp precompile logic
   856  	// > 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).
   857  	// > Output is an encoding of multiexponentiation operation result - single G2 point (`256` bytes).
   858  	k := len(input) / 288
   859  	if len(input) == 0 || len(input)%288 != 0 {
   860  		return nil, errBLS12381InvalidInputLength
   861  	}
   862  	var err error
   863  	points := make([]*bls12381.PointG2, k)
   864  	scalars := make([]*big.Int, k)
   865  
   866  	// Initialize G2
   867  	g := bls12381.NewG2()
   868  
   869  	// Decode point scalar pairs
   870  	for i := 0; i < k; i++ {
   871  		off := 288 * i
   872  		t0, t1, t2 := off, off+256, off+288
   873  		// Decode G1 point
   874  		if points[i], err = g.DecodePoint(input[t0:t1]); err != nil {
   875  			return nil, err
   876  		}
   877  		// Decode scalar value
   878  		scalars[i] = new(big.Int).SetBytes(input[t1:t2])
   879  	}
   880  
   881  	// Compute r = e_0 * p_0 + e_1 * p_1 + ... + e_(k-1) * p_(k-1)
   882  	r := g.New()
   883  	g.MultiExp(r, points, scalars)
   884  
   885  	// Encode the G2 point to 256 bytes.
   886  	return g.EncodePoint(r), nil
   887  }
   888  
   889  // bls12381Pairing implements EIP-2537 Pairing precompile.
   890  type bls12381Pairing struct{}
   891  
   892  // RequiredGas returns the gas required to execute the pre-compiled contract.
   893  func (c *bls12381Pairing) RequiredGas(input []byte) uint64 {
   894  	return params.Bls12381PairingBaseGas + uint64(len(input)/384)*params.Bls12381PairingPerPairGas
   895  }
   896  
   897  func (c *bls12381Pairing) Run(input []byte) ([]byte, error) {
   898  	// Implements EIP-2537 Pairing precompile logic.
   899  	// > Pairing call expects `384*k` bytes as an inputs that is interpreted as byte concatenation of `k` slices. Each slice has the following structure:
   900  	// > - `128` bytes of G1 point encoding
   901  	// > - `256` bytes of G2 point encoding
   902  	// > 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
   903  	// > (which is equivalent of Big Endian encoding of Solidity values `uint256(1)` and `uin256(0)` respectively).
   904  	k := len(input) / 384
   905  	if len(input) == 0 || len(input)%384 != 0 {
   906  		return nil, errBLS12381InvalidInputLength
   907  	}
   908  
   909  	// Initialize BLS12-381 pairing engine
   910  	e := bls12381.NewPairingEngine()
   911  	g1, g2 := e.G1, e.G2
   912  
   913  	// Decode pairs
   914  	for i := 0; i < k; i++ {
   915  		off := 384 * i
   916  		t0, t1, t2 := off, off+128, off+384
   917  
   918  		// Decode G1 point
   919  		p1, err := g1.DecodePoint(input[t0:t1])
   920  		if err != nil {
   921  			return nil, err
   922  		}
   923  		// Decode G2 point
   924  		p2, err := g2.DecodePoint(input[t1:t2])
   925  		if err != nil {
   926  			return nil, err
   927  		}
   928  
   929  		// 'point is on curve' check already done,
   930  		// Here we need to apply subgroup checks.
   931  		if !g1.InCorrectSubgroup(p1) {
   932  			return nil, errBLS12381G1PointSubgroup
   933  		}
   934  		if !g2.InCorrectSubgroup(p2) {
   935  			return nil, errBLS12381G2PointSubgroup
   936  		}
   937  
   938  		// Update pairing engine with G1 and G2 ponits
   939  		e.AddPair(p1, p2)
   940  	}
   941  	// Prepare 32 byte output
   942  	out := make([]byte, 32)
   943  
   944  	// Compute pairing and set the result
   945  	if e.Check() {
   946  		out[31] = 1
   947  	}
   948  	return out, nil
   949  }
   950  
   951  // decodeBLS12381FieldElement decodes BLS12-381 elliptic curve field element.
   952  // Removes top 16 bytes of 64 byte input.
   953  func decodeBLS12381FieldElement(in []byte) ([]byte, error) {
   954  	if len(in) != 64 {
   955  		return nil, errors.New("invalid field element length")
   956  	}
   957  	// check top bytes
   958  	for i := 0; i < 16; i++ {
   959  		if in[i] != byte(0x00) {
   960  			return nil, errBLS12381InvalidFieldElementTopBytes
   961  		}
   962  	}
   963  	out := make([]byte, 48)
   964  	copy(out[:], in[16:])
   965  	return out, nil
   966  }
   967  
   968  // bls12381MapG1 implements EIP-2537 MapG1 precompile.
   969  type bls12381MapG1 struct{}
   970  
   971  // RequiredGas returns the gas required to execute the pre-compiled contract.
   972  func (c *bls12381MapG1) RequiredGas(input []byte) uint64 {
   973  	return params.Bls12381MapG1Gas
   974  }
   975  
   976  func (c *bls12381MapG1) Run(input []byte) ([]byte, error) {
   977  	// Implements EIP-2537 Map_To_G1 precompile.
   978  	// > Field-to-curve call expects `64` bytes an an input that is interpreted as a an element of the base field.
   979  	// > Output of this call is `128` bytes and is G1 point following respective encoding rules.
   980  	if len(input) != 64 {
   981  		return nil, errBLS12381InvalidInputLength
   982  	}
   983  
   984  	// Decode input field element
   985  	fe, err := decodeBLS12381FieldElement(input)
   986  	if err != nil {
   987  		return nil, err
   988  	}
   989  
   990  	// Initialize G1
   991  	g := bls12381.NewG1()
   992  
   993  	// Compute mapping
   994  	r, err := g.MapToCurve(fe)
   995  	if err != nil {
   996  		return nil, err
   997  	}
   998  
   999  	// Encode the G1 point to 128 bytes
  1000  	return g.EncodePoint(r), nil
  1001  }
  1002  
  1003  // bls12381MapG2 implements EIP-2537 MapG2 precompile.
  1004  type bls12381MapG2 struct{}
  1005  
  1006  // RequiredGas returns the gas required to execute the pre-compiled contract.
  1007  func (c *bls12381MapG2) RequiredGas(input []byte) uint64 {
  1008  	return params.Bls12381MapG2Gas
  1009  }
  1010  
  1011  func (c *bls12381MapG2) Run(input []byte) ([]byte, error) {
  1012  	// Implements EIP-2537 Map_FP2_TO_G2 precompile logic.
  1013  	// > Field-to-curve call expects `128` bytes an an input that is interpreted as a an element of the quadratic extension field.
  1014  	// > Output of this call is `256` bytes and is G2 point following respective encoding rules.
  1015  	if len(input) != 128 {
  1016  		return nil, errBLS12381InvalidInputLength
  1017  	}
  1018  
  1019  	// Decode input field element
  1020  	fe := make([]byte, 96)
  1021  	c0, err := decodeBLS12381FieldElement(input[:64])
  1022  	if err != nil {
  1023  		return nil, err
  1024  	}
  1025  	copy(fe[48:], c0)
  1026  	c1, err := decodeBLS12381FieldElement(input[64:])
  1027  	if err != nil {
  1028  		return nil, err
  1029  	}
  1030  	copy(fe[:48], c1)
  1031  
  1032  	// Initialize G2
  1033  	g := bls12381.NewG2()
  1034  
  1035  	// Compute mapping
  1036  	r, err := g.MapToCurve(fe)
  1037  	if err != nil {
  1038  		return nil, err
  1039  	}
  1040  
  1041  	// Encode the G2 point to 256 bytes
  1042  	return g.EncodePoint(r), nil
  1043  }