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