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