github.com/dim4egster/coreth@v0.10.2/core/vm/contracts.go (about)

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