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