github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/core/vm/contracts.go (about)

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