github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/core/vm/contracts.go (about)

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