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