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