github.com/amazechain/amc@v0.1.3/internal/vm/contracts.go (about)

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