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