github.com/zhiqiangxu/go-ethereum@v1.9.16-0.20210824055606-be91cfdebc48/core/vm/contracts.go (about)

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