github.com/tenderly/bsc@v1.0.7/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/tenderly/bsc/common"
    26  	"github.com/tenderly/bsc/common/math"
    27  	"github.com/tenderly/bsc/crypto"
    28  	"github.com/tenderly/bsc/crypto/blake2b"
    29  	"github.com/tenderly/bsc/crypto/bn256"
    30  	"github.com/tenderly/bsc/params"
    31  
    32  	//lint:ignore SA1019 Needed for precompile
    33  	"golang.org/x/crypto/ripemd160"
    34  )
    35  
    36  // PrecompiledContract is the basic interface for native Go contracts. The implementation
    37  // requires a deterministic gas count based on the input size of the Run method of the
    38  // contract.
    39  type PrecompiledContract interface {
    40  	RequiredGas(input []byte) uint64  // RequiredPrice calculates the contract gas use
    41  	Run(input []byte) ([]byte, error) // Run runs the precompiled contract
    42  }
    43  
    44  // PrecompiledContractsHomestead contains the default set of pre-compiled Ethereum
    45  // contracts used in the Frontier and Homestead releases.
    46  var PrecompiledContractsHomestead = map[common.Address]PrecompiledContract{
    47  	common.BytesToAddress([]byte{1}): &ecrecover{},
    48  	common.BytesToAddress([]byte{2}): &sha256hash{},
    49  	common.BytesToAddress([]byte{3}): &ripemd160hash{},
    50  	common.BytesToAddress([]byte{4}): &dataCopy{},
    51  }
    52  
    53  // PrecompiledContractsByzantium contains the default set of pre-compiled Ethereum
    54  // contracts used in the Byzantium release.
    55  var PrecompiledContractsByzantium = map[common.Address]PrecompiledContract{
    56  	common.BytesToAddress([]byte{1}): &ecrecover{},
    57  	common.BytesToAddress([]byte{2}): &sha256hash{},
    58  	common.BytesToAddress([]byte{3}): &ripemd160hash{},
    59  	common.BytesToAddress([]byte{4}): &dataCopy{},
    60  	common.BytesToAddress([]byte{5}): &bigModExp{},
    61  	common.BytesToAddress([]byte{6}): &bn256AddByzantium{},
    62  	common.BytesToAddress([]byte{7}): &bn256ScalarMulByzantium{},
    63  	common.BytesToAddress([]byte{8}): &bn256PairingByzantium{},
    64  }
    65  
    66  // PrecompiledContractsIstanbul contains the default set of pre-compiled Ethereum
    67  // contracts used in the Istanbul release.
    68  var PrecompiledContractsIstanbul = map[common.Address]PrecompiledContract{
    69  	common.BytesToAddress([]byte{1}):  &ecrecover{},
    70  	common.BytesToAddress([]byte{2}):  &sha256hash{},
    71  	common.BytesToAddress([]byte{3}):  &ripemd160hash{},
    72  	common.BytesToAddress([]byte{4}):  &dataCopy{},
    73  	common.BytesToAddress([]byte{5}):  &bigModExp{},
    74  	common.BytesToAddress([]byte{6}):  &bn256AddIstanbul{},
    75  	common.BytesToAddress([]byte{7}):  &bn256ScalarMulIstanbul{},
    76  	common.BytesToAddress([]byte{8}):  &bn256PairingIstanbul{},
    77  	common.BytesToAddress([]byte{9}):  &blake2F{},
    78  
    79  	common.BytesToAddress([]byte{100}): &tmHeaderValidate{},
    80  	common.BytesToAddress([]byte{101}): &iavlMerkleProofValidate{},
    81  }
    82  
    83  // RunPrecompiledContract runs and evaluates the output of a precompiled contract.
    84  func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract) (ret []byte, err error) {
    85  	gas := p.RequiredGas(input)
    86  	if contract.UseGas(gas) {
    87  		return p.Run(input)
    88  	}
    89  	return nil, ErrOutOfGas
    90  }
    91  
    92  // ECRECOVER implemented as a native contract.
    93  type ecrecover struct{}
    94  
    95  func (c *ecrecover) RequiredGas(input []byte) uint64 {
    96  	return params.EcrecoverGas
    97  }
    98  
    99  func (c *ecrecover) Run(input []byte) ([]byte, error) {
   100  	const ecRecoverInputLength = 128
   101  
   102  	input = common.RightPadBytes(input, ecRecoverInputLength)
   103  	// "input" is (hash, v, r, s), each 32 bytes
   104  	// but for ecrecover we want (r, s, v)
   105  
   106  	r := new(big.Int).SetBytes(input[64:96])
   107  	s := new(big.Int).SetBytes(input[96:128])
   108  	v := input[63] - 27
   109  
   110  	// tighter sig s values input homestead only apply to tx sigs
   111  	if !allZero(input[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) {
   112  		return nil, nil
   113  	}
   114  	// We must make sure not to modify the 'input', so placing the 'v' along with
   115  	// the signature needs to be done on a new allocation
   116  	sig := make([]byte, 65)
   117  	copy(sig, input[64:128])
   118  	sig[64] = v
   119  	// v needs to be at the end for libsecp256k1
   120  	pubKey, err := crypto.Ecrecover(input[:32], sig)
   121  	// make sure the public key is a valid one
   122  	if err != nil {
   123  		return nil, nil
   124  	}
   125  
   126  	// the first byte of pubkey is bitcoin heritage
   127  	return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32), nil
   128  }
   129  
   130  // SHA256 implemented as a native contract.
   131  type sha256hash struct{}
   132  
   133  // RequiredGas returns the gas required to execute the pre-compiled contract.
   134  //
   135  // This method does not require any overflow checking as the input size gas costs
   136  // required for anything significant is so high it's impossible to pay for.
   137  func (c *sha256hash) RequiredGas(input []byte) uint64 {
   138  	return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas
   139  }
   140  func (c *sha256hash) Run(input []byte) ([]byte, error) {
   141  	h := sha256.Sum256(input)
   142  	return h[:], nil
   143  }
   144  
   145  // RIPEMD160 implemented as a native contract.
   146  type ripemd160hash struct{}
   147  
   148  // RequiredGas returns the gas required to execute the pre-compiled contract.
   149  //
   150  // This method does not require any overflow checking as the input size gas costs
   151  // required for anything significant is so high it's impossible to pay for.
   152  func (c *ripemd160hash) RequiredGas(input []byte) uint64 {
   153  	return uint64(len(input)+31)/32*params.Ripemd160PerWordGas + params.Ripemd160BaseGas
   154  }
   155  func (c *ripemd160hash) Run(input []byte) ([]byte, error) {
   156  	ripemd := ripemd160.New()
   157  	ripemd.Write(input)
   158  	return common.LeftPadBytes(ripemd.Sum(nil), 32), nil
   159  }
   160  
   161  // data copy implemented as a native contract.
   162  type dataCopy struct{}
   163  
   164  // RequiredGas returns the gas required to execute the pre-compiled contract.
   165  //
   166  // This method does not require any overflow checking as the input size gas costs
   167  // required for anything significant is so high it's impossible to pay for.
   168  func (c *dataCopy) RequiredGas(input []byte) uint64 {
   169  	return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas
   170  }
   171  func (c *dataCopy) Run(in []byte) ([]byte, error) {
   172  	return in, nil
   173  }
   174  
   175  // bigModExp implements a native big integer exponential modular operation.
   176  type bigModExp struct{}
   177  
   178  var (
   179  	big1      = big.NewInt(1)
   180  	big4      = big.NewInt(4)
   181  	big8      = big.NewInt(8)
   182  	big16     = big.NewInt(16)
   183  	big32     = big.NewInt(32)
   184  	big64     = big.NewInt(64)
   185  	big96     = big.NewInt(96)
   186  	big480    = big.NewInt(480)
   187  	big1024   = big.NewInt(1024)
   188  	big3072   = big.NewInt(3072)
   189  	big199680 = big.NewInt(199680)
   190  )
   191  
   192  // RequiredGas returns the gas required to execute the pre-compiled contract.
   193  func (c *bigModExp) RequiredGas(input []byte) uint64 {
   194  	var (
   195  		baseLen = new(big.Int).SetBytes(getData(input, 0, 32))
   196  		expLen  = new(big.Int).SetBytes(getData(input, 32, 32))
   197  		modLen  = new(big.Int).SetBytes(getData(input, 64, 32))
   198  	)
   199  	if len(input) > 96 {
   200  		input = input[96:]
   201  	} else {
   202  		input = input[:0]
   203  	}
   204  	// Retrieve the head 32 bytes of exp for the adjusted exponent length
   205  	var expHead *big.Int
   206  	if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 {
   207  		expHead = new(big.Int)
   208  	} else {
   209  		if expLen.Cmp(big32) > 0 {
   210  			expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), 32))
   211  		} else {
   212  			expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), expLen.Uint64()))
   213  		}
   214  	}
   215  	// Calculate the adjusted exponent length
   216  	var msb int
   217  	if bitlen := expHead.BitLen(); bitlen > 0 {
   218  		msb = bitlen - 1
   219  	}
   220  	adjExpLen := new(big.Int)
   221  	if expLen.Cmp(big32) > 0 {
   222  		adjExpLen.Sub(expLen, big32)
   223  		adjExpLen.Mul(big8, adjExpLen)
   224  	}
   225  	adjExpLen.Add(adjExpLen, big.NewInt(int64(msb)))
   226  
   227  	// Calculate the gas cost of the operation
   228  	gas := new(big.Int).Set(math.BigMax(modLen, baseLen))
   229  	switch {
   230  	case gas.Cmp(big64) <= 0:
   231  		gas.Mul(gas, gas)
   232  	case gas.Cmp(big1024) <= 0:
   233  		gas = new(big.Int).Add(
   234  			new(big.Int).Div(new(big.Int).Mul(gas, gas), big4),
   235  			new(big.Int).Sub(new(big.Int).Mul(big96, gas), big3072),
   236  		)
   237  	default:
   238  		gas = new(big.Int).Add(
   239  			new(big.Int).Div(new(big.Int).Mul(gas, gas), big16),
   240  			new(big.Int).Sub(new(big.Int).Mul(big480, gas), big199680),
   241  		)
   242  	}
   243  	gas.Mul(gas, math.BigMax(adjExpLen, big1))
   244  	gas.Div(gas, new(big.Int).SetUint64(params.ModExpQuadCoeffDiv))
   245  
   246  	if gas.BitLen() > 64 {
   247  		return math.MaxUint64
   248  	}
   249  	return gas.Uint64()
   250  }
   251  
   252  func (c *bigModExp) Run(input []byte) ([]byte, error) {
   253  	var (
   254  		baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64()
   255  		expLen  = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64()
   256  		modLen  = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64()
   257  	)
   258  	if len(input) > 96 {
   259  		input = input[96:]
   260  	} else {
   261  		input = input[:0]
   262  	}
   263  	// Handle a special case when both the base and mod length is zero
   264  	if baseLen == 0 && modLen == 0 {
   265  		return []byte{}, nil
   266  	}
   267  	// Retrieve the operands and execute the exponentiation
   268  	var (
   269  		base = new(big.Int).SetBytes(getData(input, 0, baseLen))
   270  		exp  = new(big.Int).SetBytes(getData(input, baseLen, expLen))
   271  		mod  = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen))
   272  	)
   273  	if mod.BitLen() == 0 {
   274  		// Modulo 0 is undefined, return zero
   275  		return common.LeftPadBytes([]byte{}, int(modLen)), nil
   276  	}
   277  	return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil
   278  }
   279  
   280  // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point,
   281  // returning it, or an error if the point is invalid.
   282  func newCurvePoint(blob []byte) (*bn256.G1, error) {
   283  	p := new(bn256.G1)
   284  	if _, err := p.Unmarshal(blob); err != nil {
   285  		return nil, err
   286  	}
   287  	return p, nil
   288  }
   289  
   290  // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point,
   291  // returning it, or an error if the point is invalid.
   292  func newTwistPoint(blob []byte) (*bn256.G2, error) {
   293  	p := new(bn256.G2)
   294  	if _, err := p.Unmarshal(blob); err != nil {
   295  		return nil, err
   296  	}
   297  	return p, nil
   298  }
   299  
   300  // runBn256Add implements the Bn256Add precompile, referenced by both
   301  // Byzantium and Istanbul operations.
   302  func runBn256Add(input []byte) ([]byte, error) {
   303  	x, err := newCurvePoint(getData(input, 0, 64))
   304  	if err != nil {
   305  		return nil, err
   306  	}
   307  	y, err := newCurvePoint(getData(input, 64, 64))
   308  	if err != nil {
   309  		return nil, err
   310  	}
   311  	res := new(bn256.G1)
   312  	res.Add(x, y)
   313  	return res.Marshal(), nil
   314  }
   315  
   316  // bn256Add implements a native elliptic curve point addition conforming to
   317  // Istanbul consensus rules.
   318  type bn256AddIstanbul struct{}
   319  
   320  // RequiredGas returns the gas required to execute the pre-compiled contract.
   321  func (c *bn256AddIstanbul) RequiredGas(input []byte) uint64 {
   322  	return params.Bn256AddGasIstanbul
   323  }
   324  
   325  func (c *bn256AddIstanbul) Run(input []byte) ([]byte, error) {
   326  	return runBn256Add(input)
   327  }
   328  
   329  // bn256AddByzantium implements a native elliptic curve point addition
   330  // conforming to Byzantium consensus rules.
   331  type bn256AddByzantium struct{}
   332  
   333  // RequiredGas returns the gas required to execute the pre-compiled contract.
   334  func (c *bn256AddByzantium) RequiredGas(input []byte) uint64 {
   335  	return params.Bn256AddGasByzantium
   336  }
   337  
   338  func (c *bn256AddByzantium) Run(input []byte) ([]byte, error) {
   339  	return runBn256Add(input)
   340  }
   341  
   342  // runBn256ScalarMul implements the Bn256ScalarMul precompile, referenced by
   343  // both Byzantium and Istanbul operations.
   344  func runBn256ScalarMul(input []byte) ([]byte, error) {
   345  	p, err := newCurvePoint(getData(input, 0, 64))
   346  	if err != nil {
   347  		return nil, err
   348  	}
   349  	res := new(bn256.G1)
   350  	res.ScalarMult(p, new(big.Int).SetBytes(getData(input, 64, 32)))
   351  	return res.Marshal(), nil
   352  }
   353  
   354  // bn256ScalarMulIstanbul implements a native elliptic curve scalar
   355  // multiplication conforming to Istanbul consensus rules.
   356  type bn256ScalarMulIstanbul struct{}
   357  
   358  // RequiredGas returns the gas required to execute the pre-compiled contract.
   359  func (c *bn256ScalarMulIstanbul) RequiredGas(input []byte) uint64 {
   360  	return params.Bn256ScalarMulGasIstanbul
   361  }
   362  
   363  func (c *bn256ScalarMulIstanbul) Run(input []byte) ([]byte, error) {
   364  	return runBn256ScalarMul(input)
   365  }
   366  
   367  // bn256ScalarMulByzantium implements a native elliptic curve scalar
   368  // multiplication conforming to Byzantium consensus rules.
   369  type bn256ScalarMulByzantium struct{}
   370  
   371  // RequiredGas returns the gas required to execute the pre-compiled contract.
   372  func (c *bn256ScalarMulByzantium) RequiredGas(input []byte) uint64 {
   373  	return params.Bn256ScalarMulGasByzantium
   374  }
   375  
   376  func (c *bn256ScalarMulByzantium) Run(input []byte) ([]byte, error) {
   377  	return runBn256ScalarMul(input)
   378  }
   379  
   380  var (
   381  	// true32Byte is returned if the bn256 pairing check succeeds.
   382  	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}
   383  
   384  	// false32Byte is returned if the bn256 pairing check fails.
   385  	false32Byte = make([]byte, 32)
   386  
   387  	// errBadPairingInput is returned if the bn256 pairing input is invalid.
   388  	errBadPairingInput = errors.New("bad elliptic curve pairing size")
   389  )
   390  
   391  // runBn256Pairing implements the Bn256Pairing precompile, referenced by both
   392  // Byzantium and Istanbul operations.
   393  func runBn256Pairing(input []byte) ([]byte, error) {
   394  	// Handle some corner cases cheaply
   395  	if len(input)%192 > 0 {
   396  		return nil, errBadPairingInput
   397  	}
   398  	// Convert the input into a set of coordinates
   399  	var (
   400  		cs []*bn256.G1
   401  		ts []*bn256.G2
   402  	)
   403  	for i := 0; i < len(input); i += 192 {
   404  		c, err := newCurvePoint(input[i : i+64])
   405  		if err != nil {
   406  			return nil, err
   407  		}
   408  		t, err := newTwistPoint(input[i+64 : i+192])
   409  		if err != nil {
   410  			return nil, err
   411  		}
   412  		cs = append(cs, c)
   413  		ts = append(ts, t)
   414  	}
   415  	// Execute the pairing checks and return the results
   416  	if bn256.PairingCheck(cs, ts) {
   417  		return true32Byte, nil
   418  	}
   419  	return false32Byte, nil
   420  }
   421  
   422  // bn256PairingIstanbul implements a pairing pre-compile for the bn256 curve
   423  // conforming to Istanbul consensus rules.
   424  type bn256PairingIstanbul struct{}
   425  
   426  // RequiredGas returns the gas required to execute the pre-compiled contract.
   427  func (c *bn256PairingIstanbul) RequiredGas(input []byte) uint64 {
   428  	return params.Bn256PairingBaseGasIstanbul + uint64(len(input)/192)*params.Bn256PairingPerPointGasIstanbul
   429  }
   430  
   431  func (c *bn256PairingIstanbul) Run(input []byte) ([]byte, error) {
   432  	return runBn256Pairing(input)
   433  }
   434  
   435  // bn256PairingByzantium implements a pairing pre-compile for the bn256 curve
   436  // conforming to Byzantium consensus rules.
   437  type bn256PairingByzantium struct{}
   438  
   439  // RequiredGas returns the gas required to execute the pre-compiled contract.
   440  func (c *bn256PairingByzantium) RequiredGas(input []byte) uint64 {
   441  	return params.Bn256PairingBaseGasByzantium + uint64(len(input)/192)*params.Bn256PairingPerPointGasByzantium
   442  }
   443  
   444  func (c *bn256PairingByzantium) Run(input []byte) ([]byte, error) {
   445  	return runBn256Pairing(input)
   446  }
   447  
   448  type blake2F struct{}
   449  
   450  func (c *blake2F) RequiredGas(input []byte) uint64 {
   451  	// If the input is malformed, we can't calculate the gas, return 0 and let the
   452  	// actual call choke and fault.
   453  	if len(input) != blake2FInputLength {
   454  		return 0
   455  	}
   456  	return uint64(binary.BigEndian.Uint32(input[0:4]))
   457  }
   458  
   459  const (
   460  	blake2FInputLength        = 213
   461  	blake2FFinalBlockBytes    = byte(1)
   462  	blake2FNonFinalBlockBytes = byte(0)
   463  )
   464  
   465  var (
   466  	errBlake2FInvalidInputLength = errors.New("invalid input length")
   467  	errBlake2FInvalidFinalFlag   = errors.New("invalid final flag")
   468  )
   469  
   470  func (c *blake2F) Run(input []byte) ([]byte, error) {
   471  	// Make sure the input is valid (correct lenth and final flag)
   472  	if len(input) != blake2FInputLength {
   473  		return nil, errBlake2FInvalidInputLength
   474  	}
   475  	if input[212] != blake2FNonFinalBlockBytes && input[212] != blake2FFinalBlockBytes {
   476  		return nil, errBlake2FInvalidFinalFlag
   477  	}
   478  	// Parse the input into the Blake2b call parameters
   479  	var (
   480  		rounds = binary.BigEndian.Uint32(input[0:4])
   481  		final  = (input[212] == blake2FFinalBlockBytes)
   482  
   483  		h [8]uint64
   484  		m [16]uint64
   485  		t [2]uint64
   486  	)
   487  	for i := 0; i < 8; i++ {
   488  		offset := 4 + i*8
   489  		h[i] = binary.LittleEndian.Uint64(input[offset : offset+8])
   490  	}
   491  	for i := 0; i < 16; i++ {
   492  		offset := 68 + i*8
   493  		m[i] = binary.LittleEndian.Uint64(input[offset : offset+8])
   494  	}
   495  	t[0] = binary.LittleEndian.Uint64(input[196:204])
   496  	t[1] = binary.LittleEndian.Uint64(input[204:212])
   497  
   498  	// Execute the compression function, extract and return the result
   499  	blake2b.F(&h, m, t, final, rounds)
   500  
   501  	output := make([]byte, 64)
   502  	for i := 0; i < 8; i++ {
   503  		offset := i * 8
   504  		binary.LittleEndian.PutUint64(output[offset:offset+8], h[i])
   505  	}
   506  	return output, nil
   507  }