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