github.com/cheng762/platon-go@v1.8.17-0.20190529111256-7deff2d7be26/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  	"errors"
    22  	"math/big"
    23  
    24  	"github.com/PlatONnetwork/PlatON-Go/common"
    25  	"github.com/PlatONnetwork/PlatON-Go/common/math"
    26  	"github.com/PlatONnetwork/PlatON-Go/crypto"
    27  	"github.com/PlatONnetwork/PlatON-Go/crypto/bn256"
    28  	"github.com/PlatONnetwork/PlatON-Go/params"
    29  	"golang.org/x/crypto/ripemd160"
    30  	"github.com/PlatONnetwork/PlatON-Go/log"
    31  )
    32  
    33  // PrecompiledContract is the basic interface for native Go contracts. The implementation
    34  // requires a deterministic gas count based on the input size of the Run method of the
    35  // contract.
    36  type PrecompiledContract interface {
    37  	RequiredGas(input []byte) uint64  // RequiredPrice calculates the contract gas use
    38  	Run(input []byte) ([]byte, error) // Run runs the precompiled contract
    39  }
    40  
    41  // PrecompiledContractsHomestead contains the default set of pre-compiled Ethereum
    42  // contracts used in the Frontier and Homestead releases.
    43  var PrecompiledContractsHomestead = map[common.Address]PrecompiledContract{
    44  	common.BytesToAddress([]byte{1}): &ecrecover{},
    45  	common.BytesToAddress([]byte{2}): &sha256hash{},
    46  	common.BytesToAddress([]byte{3}): &ripemd160hash{},
    47  	common.BytesToAddress([]byte{4}): &dataCopy{},
    48  }
    49  
    50  // PrecompiledContractsByzantium contains the default set of pre-compiled Ethereum
    51  // contracts used in the Byzantium release.
    52  var PrecompiledContractsByzantium = map[common.Address]PrecompiledContract{
    53  	common.BytesToAddress([]byte{1}): &ecrecover{},
    54  	common.BytesToAddress([]byte{2}): &sha256hash{},
    55  	common.BytesToAddress([]byte{3}): &ripemd160hash{},
    56  	common.BytesToAddress([]byte{4}): &dataCopy{},
    57  	common.BytesToAddress([]byte{5}): &bigModExp{},
    58  	common.BytesToAddress([]byte{6}): &bn256Add{},
    59  	common.BytesToAddress([]byte{7}): &bn256ScalarMul{},
    60  	common.BytesToAddress([]byte{8}): &bn256Pairing{},
    61  }
    62  
    63  // RunPrecompiledContract runs and evaluates the output of a precompiled contract.
    64  func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract) (ret []byte, err error) {
    65  	log.Info("IN PPOS PrecompiledContractsPpos RUN Previous ... ")
    66  	gas := p.RequiredGas(input)
    67  	if contract.UseGas(gas) {
    68  		return p.Run(input)
    69  	}
    70  	return nil, ErrOutOfGas
    71  }
    72  
    73  // ECRECOVER implemented as a native contract.
    74  type ecrecover struct{}
    75  
    76  func (c *ecrecover) RequiredGas(input []byte) uint64 {
    77  	return params.EcrecoverGas
    78  }
    79  
    80  func (c *ecrecover) Run(input []byte) ([]byte, error) {
    81  	const ecRecoverInputLength = 128
    82  
    83  	input = common.RightPadBytes(input, ecRecoverInputLength)
    84  	// "input" is (hash, v, r, s), each 32 bytes
    85  	// but for ecrecover we want (r, s, v)
    86  
    87  	r := new(big.Int).SetBytes(input[64:96])
    88  	s := new(big.Int).SetBytes(input[96:128])
    89  	v := input[63] - 27
    90  
    91  	// tighter sig s values input homestead only apply to tx sigs
    92  	if !allZero(input[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) {
    93  		return nil, nil
    94  	}
    95  	// v needs to be at the end for libsecp256k1
    96  	pubKey, err := crypto.Ecrecover(input[:32], append(input[64:128], v))
    97  	// make sure the public key is a valid one
    98  	if err != nil {
    99  		return nil, nil
   100  	}
   101  
   102  	// the first byte of pubkey is bitcoin heritage
   103  	return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32), nil
   104  }
   105  
   106  // SHA256 implemented as a native contract.
   107  type sha256hash struct{}
   108  
   109  // RequiredGas returns the gas required to execute the pre-compiled contract.
   110  //
   111  // This method does not require any overflow checking as the input size gas costs
   112  // required for anything significant is so high it's impossible to pay for.
   113  func (c *sha256hash) RequiredGas(input []byte) uint64 {
   114  	return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas
   115  }
   116  func (c *sha256hash) Run(input []byte) ([]byte, error) {
   117  	h := sha256.Sum256(input)
   118  	return h[:], nil
   119  }
   120  
   121  // RIPEMD160 implemented as a native contract.
   122  type ripemd160hash struct{}
   123  
   124  // RequiredGas returns the gas required to execute the pre-compiled contract.
   125  //
   126  // This method does not require any overflow checking as the input size gas costs
   127  // required for anything significant is so high it's impossible to pay for.
   128  func (c *ripemd160hash) RequiredGas(input []byte) uint64 {
   129  	return uint64(len(input)+31)/32*params.Ripemd160PerWordGas + params.Ripemd160BaseGas
   130  }
   131  func (c *ripemd160hash) Run(input []byte) ([]byte, error) {
   132  	ripemd := ripemd160.New()
   133  	ripemd.Write(input)
   134  	return common.LeftPadBytes(ripemd.Sum(nil), 32), nil
   135  }
   136  
   137  // data copy implemented as a native contract.
   138  type dataCopy struct{}
   139  
   140  // RequiredGas returns the gas required to execute the pre-compiled contract.
   141  //
   142  // This method does not require any overflow checking as the input size gas costs
   143  // required for anything significant is so high it's impossible to pay for.
   144  func (c *dataCopy) RequiredGas(input []byte) uint64 {
   145  	return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas
   146  }
   147  func (c *dataCopy) Run(in []byte) ([]byte, error) {
   148  	return in, nil
   149  }
   150  
   151  // bigModExp implements a native big integer exponential modular operation.
   152  type bigModExp struct{}
   153  
   154  var (
   155  	big1      = big.NewInt(1)
   156  	big4      = big.NewInt(4)
   157  	big8      = big.NewInt(8)
   158  	big16     = big.NewInt(16)
   159  	big32     = big.NewInt(32)
   160  	big64     = big.NewInt(64)
   161  	big96     = big.NewInt(96)
   162  	big480    = big.NewInt(480)
   163  	big1024   = big.NewInt(1024)
   164  	big3072   = big.NewInt(3072)
   165  	big199680 = big.NewInt(199680)
   166  )
   167  
   168  // RequiredGas returns the gas required to execute the pre-compiled contract.
   169  func (c *bigModExp) RequiredGas(input []byte) uint64 {
   170  	var (
   171  		baseLen = new(big.Int).SetBytes(getData(input, 0, 32))
   172  		expLen  = new(big.Int).SetBytes(getData(input, 32, 32))
   173  		modLen  = new(big.Int).SetBytes(getData(input, 64, 32))
   174  	)
   175  	if len(input) > 96 {
   176  		input = input[96:]
   177  	} else {
   178  		input = input[:0]
   179  	}
   180  	// Retrieve the head 32 bytes of exp for the adjusted exponent length
   181  	var expHead *big.Int
   182  	if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 {
   183  		expHead = new(big.Int)
   184  	} else {
   185  		if expLen.Cmp(big32) > 0 {
   186  			expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), 32))
   187  		} else {
   188  			expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), expLen.Uint64()))
   189  		}
   190  	}
   191  	// Calculate the adjusted exponent length
   192  	var msb int
   193  	if bitlen := expHead.BitLen(); bitlen > 0 {
   194  		msb = bitlen - 1
   195  	}
   196  	adjExpLen := new(big.Int)
   197  	if expLen.Cmp(big32) > 0 {
   198  		adjExpLen.Sub(expLen, big32)
   199  		adjExpLen.Mul(big8, adjExpLen)
   200  	}
   201  	adjExpLen.Add(adjExpLen, big.NewInt(int64(msb)))
   202  
   203  	// Calculate the gas cost of the operation
   204  	gas := new(big.Int).Set(math.BigMax(modLen, baseLen))
   205  	switch {
   206  	case gas.Cmp(big64) <= 0:
   207  		gas.Mul(gas, gas)
   208  	case gas.Cmp(big1024) <= 0:
   209  		gas = new(big.Int).Add(
   210  			new(big.Int).Div(new(big.Int).Mul(gas, gas), big4),
   211  			new(big.Int).Sub(new(big.Int).Mul(big96, gas), big3072),
   212  		)
   213  	default:
   214  		gas = new(big.Int).Add(
   215  			new(big.Int).Div(new(big.Int).Mul(gas, gas), big16),
   216  			new(big.Int).Sub(new(big.Int).Mul(big480, gas), big199680),
   217  		)
   218  	}
   219  	gas.Mul(gas, math.BigMax(adjExpLen, big1))
   220  	gas.Div(gas, new(big.Int).SetUint64(params.ModExpQuadCoeffDiv))
   221  
   222  	if gas.BitLen() > 64 {
   223  		return math.MaxUint64
   224  	}
   225  	return gas.Uint64()
   226  }
   227  
   228  func (c *bigModExp) Run(input []byte) ([]byte, error) {
   229  	var (
   230  		baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64()
   231  		expLen  = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64()
   232  		modLen  = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64()
   233  	)
   234  	if len(input) > 96 {
   235  		input = input[96:]
   236  	} else {
   237  		input = input[:0]
   238  	}
   239  	// Handle a special case when both the base and mod length is zero
   240  	if baseLen == 0 && modLen == 0 {
   241  		return []byte{}, nil
   242  	}
   243  	// Retrieve the operands and execute the exponentiation
   244  	var (
   245  		base = new(big.Int).SetBytes(getData(input, 0, baseLen))
   246  		exp  = new(big.Int).SetBytes(getData(input, baseLen, expLen))
   247  		mod  = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen))
   248  	)
   249  	if mod.BitLen() == 0 {
   250  		// Modulo 0 is undefined, return zero
   251  		return common.LeftPadBytes([]byte{}, int(modLen)), nil
   252  	}
   253  	return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), nil
   254  }
   255  
   256  // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point,
   257  // returning it, or an error if the point is invalid.
   258  func newCurvePoint(blob []byte) (*bn256.G1, error) {
   259  	p := new(bn256.G1)
   260  	if _, err := p.Unmarshal(blob); err != nil {
   261  		return nil, err
   262  	}
   263  	return p, nil
   264  }
   265  
   266  // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point,
   267  // returning it, or an error if the point is invalid.
   268  func newTwistPoint(blob []byte) (*bn256.G2, error) {
   269  	p := new(bn256.G2)
   270  	if _, err := p.Unmarshal(blob); err != nil {
   271  		return nil, err
   272  	}
   273  	return p, nil
   274  }
   275  
   276  // bn256Add implements a native elliptic curve point addition.
   277  type bn256Add struct{}
   278  
   279  // RequiredGas returns the gas required to execute the pre-compiled contract.
   280  func (c *bn256Add) RequiredGas(input []byte) uint64 {
   281  	return params.Bn256AddGas
   282  }
   283  
   284  func (c *bn256Add) Run(input []byte) ([]byte, error) {
   285  	x, err := newCurvePoint(getData(input, 0, 64))
   286  	if err != nil {
   287  		return nil, err
   288  	}
   289  	y, err := newCurvePoint(getData(input, 64, 64))
   290  	if err != nil {
   291  		return nil, err
   292  	}
   293  	res := new(bn256.G1)
   294  	res.Add(x, y)
   295  	return res.Marshal(), nil
   296  }
   297  
   298  // bn256ScalarMul implements a native elliptic curve scalar multiplication.
   299  type bn256ScalarMul struct{}
   300  
   301  // RequiredGas returns the gas required to execute the pre-compiled contract.
   302  func (c *bn256ScalarMul) RequiredGas(input []byte) uint64 {
   303  	return params.Bn256ScalarMulGas
   304  }
   305  
   306  func (c *bn256ScalarMul) Run(input []byte) ([]byte, error) {
   307  	p, err := newCurvePoint(getData(input, 0, 64))
   308  	if err != nil {
   309  		return nil, err
   310  	}
   311  	res := new(bn256.G1)
   312  	res.ScalarMult(p, new(big.Int).SetBytes(getData(input, 64, 32)))
   313  	return res.Marshal(), nil
   314  }
   315  
   316  var (
   317  	// true32Byte is returned if the bn256 pairing check succeeds.
   318  	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}
   319  
   320  	// false32Byte is returned if the bn256 pairing check fails.
   321  	false32Byte = make([]byte, 32)
   322  
   323  	// errBadPairingInput is returned if the bn256 pairing input is invalid.
   324  	errBadPairingInput = errors.New("bad elliptic curve pairing size")
   325  )
   326  
   327  // bn256Pairing implements a pairing pre-compile for the bn256 curve
   328  type bn256Pairing struct{}
   329  
   330  // RequiredGas returns the gas required to execute the pre-compiled contract.
   331  func (c *bn256Pairing) RequiredGas(input []byte) uint64 {
   332  	return params.Bn256PairingBaseGas + uint64(len(input)/192)*params.Bn256PairingPerPointGas
   333  }
   334  
   335  func (c *bn256Pairing) Run(input []byte) ([]byte, error) {
   336  	// Handle some corner cases cheaply
   337  	if len(input)%192 > 0 {
   338  		return nil, errBadPairingInput
   339  	}
   340  	// Convert the input into a set of coordinates
   341  	var (
   342  		cs []*bn256.G1
   343  		ts []*bn256.G2
   344  	)
   345  	for i := 0; i < len(input); i += 192 {
   346  		c, err := newCurvePoint(input[i : i+64])
   347  		if err != nil {
   348  			return nil, err
   349  		}
   350  		t, err := newTwistPoint(input[i+64 : i+192])
   351  		if err != nil {
   352  			return nil, err
   353  		}
   354  		cs = append(cs, c)
   355  		ts = append(ts, t)
   356  	}
   357  	// Execute the pairing checks and return the results
   358  	if bn256.PairingCheck(cs, ts) {
   359  		return true32Byte, nil
   360  	}
   361  	return false32Byte, nil
   362  }