github.com/Blockdaemon/celo-blockchain@v0.0.0-20200129231733-e667f6b08419/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  	"fmt"
    23  	"math/big"
    24  
    25  	"github.com/celo-org/bls-zexe/go"
    26  	"github.com/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/common/hexutil"
    28  	"github.com/ethereum/go-ethereum/common/math"
    29  	"github.com/ethereum/go-ethereum/core/types"
    30  	"github.com/ethereum/go-ethereum/crypto"
    31  	"github.com/ethereum/go-ethereum/crypto/bls"
    32  	"github.com/ethereum/go-ethereum/crypto/bn256"
    33  	"github.com/ethereum/go-ethereum/log"
    34  	"github.com/ethereum/go-ethereum/params"
    35  	"github.com/ethereum/go-ethereum/rlp"
    36  	"golang.org/x/crypto/ripemd160"
    37  )
    38  
    39  // PrecompiledContract is the basic interface for native Go contracts. The implementation
    40  // requires a deterministic gas count based on the input size of the Run method of the
    41  // contract.
    42  type PrecompiledContract interface {
    43  	RequiredGas(input []byte) uint64                                                       // RequiredGas calculates the contract gas use
    44  	Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) // Run runs the precompiled contract
    45  }
    46  
    47  // PrecompiledContractsHomestead contains the default set of pre-compiled Ethereum
    48  // contracts used in the Frontier and Homestead releases.
    49  var PrecompiledContractsHomestead = map[common.Address]PrecompiledContract{
    50  	common.BytesToAddress([]byte{1}): &ecrecover{},
    51  	common.BytesToAddress([]byte{2}): &sha256hash{},
    52  	common.BytesToAddress([]byte{3}): &ripemd160hash{},
    53  	common.BytesToAddress([]byte{4}): &dataCopy{},
    54  }
    55  
    56  func celoPrecompileAddress(index byte) common.Address {
    57  	return common.BytesToAddress(append([]byte{0}, (CeloPrecompiledContractsAddressOffset - index)))
    58  }
    59  
    60  var (
    61  	CeloPrecompiledContractsAddressOffset = byte(0xff)
    62  
    63  	transferAddress              = celoPrecompileAddress(2)
    64  	fractionMulExpAddress        = celoPrecompileAddress(3)
    65  	proofOfPossessionAddress     = celoPrecompileAddress(4)
    66  	getValidatorAddress          = celoPrecompileAddress(5)
    67  	numberValidatorsAddress      = celoPrecompileAddress(6)
    68  	epochSizeAddress             = celoPrecompileAddress(7)
    69  	blockNumberFromHeaderAddress = celoPrecompileAddress(8)
    70  	hashHeaderAddress            = celoPrecompileAddress(9)
    71  	getParentSealBitmapAddress   = celoPrecompileAddress(10)
    72  	getVerifiedSealBitmapAddress = celoPrecompileAddress(11)
    73  )
    74  
    75  // PrecompiledContractsByzantium contains the default set of pre-compiled Ethereum
    76  // contracts used in the Byzantium release.
    77  var PrecompiledContractsByzantium = map[common.Address]PrecompiledContract{
    78  	common.BytesToAddress([]byte{1}): &ecrecover{},
    79  	common.BytesToAddress([]byte{2}): &sha256hash{},
    80  	common.BytesToAddress([]byte{3}): &ripemd160hash{},
    81  	common.BytesToAddress([]byte{4}): &dataCopy{},
    82  	common.BytesToAddress([]byte{5}): &bigModExp{},
    83  	common.BytesToAddress([]byte{6}): &bn256Add{},
    84  	common.BytesToAddress([]byte{7}): &bn256ScalarMul{},
    85  	common.BytesToAddress([]byte{8}): &bn256Pairing{},
    86  
    87  	// Celo Precompiled Contracts
    88  	transferAddress:              &transfer{},
    89  	fractionMulExpAddress:        &fractionMulExp{},
    90  	proofOfPossessionAddress:     &proofOfPossession{},
    91  	getValidatorAddress:          &getValidator{},
    92  	numberValidatorsAddress:      &numberValidators{},
    93  	epochSizeAddress:             &epochSize{},
    94  	blockNumberFromHeaderAddress: &blockNumberFromHeader{},
    95  	hashHeaderAddress:            &hashHeader{},
    96  	getParentSealBitmapAddress:   &getParentSealBitmap{},
    97  	getVerifiedSealBitmapAddress: &getVerifiedSealBitmap{},
    98  }
    99  
   100  // RunPrecompiledContract runs and evaluates the output of a precompiled contract.
   101  func RunPrecompiledContract(p PrecompiledContract, input []byte, contract *Contract, evm *EVM) (ret []byte, err error) {
   102  	log.Trace("Running precompiled contract", "codeaddr", contract.CodeAddr, "input", input, "caller", contract.CallerAddress, "gas", contract.Gas)
   103  	ret, gas, err := p.Run(input, contract.CallerAddress, evm, contract.Gas)
   104  	contract.UseGas(contract.Gas - gas)
   105  	log.Trace("Finished running precompiled contract", "codeaddr", contract.CodeAddr, "input", input, "caller", contract.CallerAddress, "gas", contract.Gas, "gas_left", gas)
   106  	return ret, err
   107  }
   108  
   109  func debitRequiredGas(p PrecompiledContract, input []byte, gas uint64) (uint64, error) {
   110  	requiredGas := p.RequiredGas(input)
   111  	if requiredGas > gas {
   112  		return gas, ErrOutOfGas
   113  	}
   114  	return gas - requiredGas, nil
   115  }
   116  
   117  // ECRECOVER implemented as a native contract.
   118  type ecrecover struct{}
   119  
   120  func (c *ecrecover) RequiredGas(input []byte) uint64 {
   121  	return params.EcrecoverGas
   122  }
   123  
   124  func (c *ecrecover) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   125  	gas, err := debitRequiredGas(c, input, gas)
   126  	if err != nil {
   127  		return nil, gas, err
   128  	}
   129  
   130  	const ecRecoverInputLength = 128
   131  
   132  	input = common.RightPadBytes(input, ecRecoverInputLength)
   133  	// "input" is (hash, v, r, s), each 32 bytes
   134  	// but for ecrecover we want (r, s, v)
   135  
   136  	r := new(big.Int).SetBytes(input[64:96])
   137  	s := new(big.Int).SetBytes(input[96:128])
   138  	v := input[63] - 27
   139  
   140  	// tighter sig s values input homestead only apply to tx sigs
   141  	if !allZero(input[32:63]) || !crypto.ValidateSignatureValues(v, r, s, false) {
   142  		return nil, gas, nil
   143  	}
   144  	// v needs to be at the end for libsecp256k1
   145  	pubKey, err := crypto.Ecrecover(input[:32], append(input[64:128], v))
   146  	// make sure the public key is a valid one
   147  	if err != nil {
   148  		return nil, gas, nil
   149  	}
   150  
   151  	// the first byte of pubkey is bitcoin heritage
   152  	return common.LeftPadBytes(crypto.Keccak256(pubKey[1:])[12:], 32), gas, nil
   153  }
   154  
   155  // SHA256 implemented as a native contract.
   156  type sha256hash struct{}
   157  
   158  // RequiredGas returns the gas required to execute the pre-compiled contract.
   159  //
   160  // This method does not require any overflow checking as the input size gas costs
   161  // required for anything significant is so high it's impossible to pay for.
   162  func (c *sha256hash) RequiredGas(input []byte) uint64 {
   163  	return uint64(len(input)+31)/32*params.Sha256PerWordGas + params.Sha256BaseGas
   164  }
   165  func (c *sha256hash) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   166  	gas, err := debitRequiredGas(c, input, gas)
   167  	if err != nil {
   168  		return nil, gas, err
   169  	}
   170  
   171  	h := sha256.Sum256(input)
   172  	return h[:], gas, nil
   173  }
   174  
   175  // RIPEMD160 implemented as a native contract.
   176  type ripemd160hash struct{}
   177  
   178  // RequiredGas returns the gas required to execute the pre-compiled contract.
   179  //
   180  // This method does not require any overflow checking as the input size gas costs
   181  // required for anything significant is so high it's impossible to pay for.
   182  func (c *ripemd160hash) RequiredGas(input []byte) uint64 {
   183  	return uint64(len(input)+31)/32*params.Ripemd160PerWordGas + params.Ripemd160BaseGas
   184  }
   185  func (c *ripemd160hash) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   186  	gas, err := debitRequiredGas(c, input, gas)
   187  	if err != nil {
   188  		return nil, gas, err
   189  	}
   190  
   191  	ripemd := ripemd160.New()
   192  	ripemd.Write(input)
   193  	return common.LeftPadBytes(ripemd.Sum(nil), 32), gas, nil
   194  }
   195  
   196  // data copy implemented as a native contract.
   197  type dataCopy struct{}
   198  
   199  // RequiredGas returns the gas required to execute the pre-compiled contract.
   200  //
   201  // This method does not require any overflow checking as the input size gas costs
   202  // required for anything significant is so high it's impossible to pay for.
   203  func (c *dataCopy) RequiredGas(input []byte) uint64 {
   204  	return uint64(len(input)+31)/32*params.IdentityPerWordGas + params.IdentityBaseGas
   205  }
   206  func (c *dataCopy) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   207  	gas, err := debitRequiredGas(c, input, gas)
   208  	if err != nil {
   209  		return nil, gas, err
   210  	}
   211  
   212  	return input, gas, nil
   213  }
   214  
   215  // bigModExp implements a native big integer exponential modular operation.
   216  type bigModExp struct{}
   217  
   218  var (
   219  	big1      = big.NewInt(1)
   220  	big4      = big.NewInt(4)
   221  	big8      = big.NewInt(8)
   222  	big16     = big.NewInt(16)
   223  	big32     = big.NewInt(32)
   224  	big64     = big.NewInt(64)
   225  	big96     = big.NewInt(96)
   226  	big480    = big.NewInt(480)
   227  	big1024   = big.NewInt(1024)
   228  	big3072   = big.NewInt(3072)
   229  	big199680 = big.NewInt(199680)
   230  )
   231  
   232  // RequiredGas returns the gas required to execute the pre-compiled contract.
   233  func (c *bigModExp) RequiredGas(input []byte) uint64 {
   234  	var (
   235  		baseLen = new(big.Int).SetBytes(getData(input, 0, 32))
   236  		expLen  = new(big.Int).SetBytes(getData(input, 32, 32))
   237  		modLen  = new(big.Int).SetBytes(getData(input, 64, 32))
   238  	)
   239  	if len(input) > 96 {
   240  		input = input[96:]
   241  	} else {
   242  		input = input[:0]
   243  	}
   244  	// Retrieve the head 32 bytes of exp for the adjusted exponent length
   245  	var expHead *big.Int
   246  	if big.NewInt(int64(len(input))).Cmp(baseLen) <= 0 {
   247  		expHead = new(big.Int)
   248  	} else {
   249  		if expLen.Cmp(big32) > 0 {
   250  			expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), 32))
   251  		} else {
   252  			expHead = new(big.Int).SetBytes(getData(input, baseLen.Uint64(), expLen.Uint64()))
   253  		}
   254  	}
   255  	// Calculate the adjusted exponent length
   256  	var msb int
   257  	if bitlen := expHead.BitLen(); bitlen > 0 {
   258  		msb = bitlen - 1
   259  	}
   260  	adjExpLen := new(big.Int)
   261  	if expLen.Cmp(big32) > 0 {
   262  		adjExpLen.Sub(expLen, big32)
   263  		adjExpLen.Mul(big8, adjExpLen)
   264  	}
   265  	adjExpLen.Add(adjExpLen, big.NewInt(int64(msb)))
   266  
   267  	// Calculate the gas cost of the operation
   268  	gas := new(big.Int).Set(math.BigMax(modLen, baseLen))
   269  	switch {
   270  	case gas.Cmp(big64) <= 0:
   271  		gas.Mul(gas, gas)
   272  	case gas.Cmp(big1024) <= 0:
   273  		gas = new(big.Int).Add(
   274  			new(big.Int).Div(new(big.Int).Mul(gas, gas), big4),
   275  			new(big.Int).Sub(new(big.Int).Mul(big96, gas), big3072),
   276  		)
   277  	default:
   278  		gas = new(big.Int).Add(
   279  			new(big.Int).Div(new(big.Int).Mul(gas, gas), big16),
   280  			new(big.Int).Sub(new(big.Int).Mul(big480, gas), big199680),
   281  		)
   282  	}
   283  	gas.Mul(gas, math.BigMax(adjExpLen, big1))
   284  	gas.Div(gas, new(big.Int).SetUint64(params.ModExpQuadCoeffDiv))
   285  
   286  	if gas.BitLen() > 64 {
   287  		return math.MaxUint64
   288  	}
   289  	return gas.Uint64()
   290  }
   291  
   292  func (c *bigModExp) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   293  	gas, err := debitRequiredGas(c, input, gas)
   294  	if err != nil {
   295  		return nil, gas, err
   296  	}
   297  
   298  	var (
   299  		baseLen = new(big.Int).SetBytes(getData(input, 0, 32)).Uint64()
   300  		expLen  = new(big.Int).SetBytes(getData(input, 32, 32)).Uint64()
   301  		modLen  = new(big.Int).SetBytes(getData(input, 64, 32)).Uint64()
   302  	)
   303  	if len(input) > 96 {
   304  		input = input[96:]
   305  	} else {
   306  		input = input[:0]
   307  	}
   308  	// Handle a special case when both the base and mod length is zero
   309  	if baseLen == 0 && modLen == 0 {
   310  		return []byte{}, gas, nil
   311  	}
   312  	// Retrieve the operands and execute the exponentiation
   313  	var (
   314  		base = new(big.Int).SetBytes(getData(input, 0, baseLen))
   315  		exp  = new(big.Int).SetBytes(getData(input, baseLen, expLen))
   316  		mod  = new(big.Int).SetBytes(getData(input, baseLen+expLen, modLen))
   317  	)
   318  	if mod.BitLen() == 0 {
   319  		// Modulo 0 is undefined, return zero
   320  		return common.LeftPadBytes([]byte{}, int(modLen)), gas, nil
   321  	}
   322  	return common.LeftPadBytes(base.Exp(base, exp, mod).Bytes(), int(modLen)), gas, nil
   323  }
   324  
   325  // newCurvePoint unmarshals a binary blob into a bn256 elliptic curve point,
   326  // returning it, or an error if the point is invalid.
   327  func newCurvePoint(blob []byte) (*bn256.G1, error) {
   328  	p := new(bn256.G1)
   329  	if _, err := p.Unmarshal(blob); err != nil {
   330  		return nil, err
   331  	}
   332  	return p, nil
   333  }
   334  
   335  // newTwistPoint unmarshals a binary blob into a bn256 elliptic curve point,
   336  // returning it, or an error if the point is invalid.
   337  func newTwistPoint(blob []byte) (*bn256.G2, error) {
   338  	p := new(bn256.G2)
   339  	if _, err := p.Unmarshal(blob); err != nil {
   340  		return nil, err
   341  	}
   342  	return p, nil
   343  }
   344  
   345  // bn256Add implements a native elliptic curve point addition.
   346  type bn256Add struct{}
   347  
   348  // RequiredGas returns the gas required to execute the pre-compiled contract.
   349  func (c *bn256Add) RequiredGas(input []byte) uint64 {
   350  	return params.Bn256AddGas
   351  }
   352  
   353  func (c *bn256Add) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   354  	gas, err := debitRequiredGas(c, input, gas)
   355  	if err != nil {
   356  		return nil, gas, err
   357  	}
   358  
   359  	x, err := newCurvePoint(getData(input, 0, 64))
   360  	if err != nil {
   361  		return nil, gas, err
   362  	}
   363  	y, err := newCurvePoint(getData(input, 64, 64))
   364  	if err != nil {
   365  		return nil, gas, err
   366  	}
   367  	res := new(bn256.G1)
   368  	res.Add(x, y)
   369  	return res.Marshal(), gas, nil
   370  }
   371  
   372  // bn256ScalarMul implements a native elliptic curve scalar multiplication.
   373  type bn256ScalarMul struct{}
   374  
   375  // RequiredGas returns the gas required to execute the pre-compiled contract.
   376  func (c *bn256ScalarMul) RequiredGas(input []byte) uint64 {
   377  	return params.Bn256ScalarMulGas
   378  }
   379  
   380  func (c *bn256ScalarMul) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   381  	gas, err := debitRequiredGas(c, input, gas)
   382  	if err != nil {
   383  		return nil, gas, err
   384  	}
   385  
   386  	p, err := newCurvePoint(getData(input, 0, 64))
   387  	if err != nil {
   388  		return nil, gas, err
   389  	}
   390  	res := new(bn256.G1)
   391  	res.ScalarMult(p, new(big.Int).SetBytes(getData(input, 64, 32)))
   392  	return res.Marshal(), gas, nil
   393  }
   394  
   395  var (
   396  	// true32Byte is returned if the bn256 pairing check succeeds.
   397  	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}
   398  
   399  	// false32Byte is returned if the bn256 pairing check fails.
   400  	false32Byte = make([]byte, 32)
   401  
   402  	// errBadPairingInput is returned if the bn256 pairing input is invalid.
   403  	errBadPairingInput = errors.New("bad elliptic curve pairing size")
   404  )
   405  
   406  // bn256Pairing implements a pairing pre-compile for the bn256 curve
   407  type bn256Pairing struct{}
   408  
   409  // RequiredGas returns the gas required to execute the pre-compiled contract.
   410  func (c *bn256Pairing) RequiredGas(input []byte) uint64 {
   411  	return params.Bn256PairingBaseGas + uint64(len(input)/192)*params.Bn256PairingPerPointGas
   412  }
   413  
   414  func (c *bn256Pairing) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   415  	gas, err := debitRequiredGas(c, input, gas)
   416  	if err != nil {
   417  		return nil, gas, err
   418  	}
   419  
   420  	// Handle some corner cases cheaply
   421  	if len(input)%192 > 0 {
   422  		return nil, gas, errBadPairingInput
   423  	}
   424  	// Convert the input into a set of coordinates
   425  	var (
   426  		cs []*bn256.G1
   427  		ts []*bn256.G2
   428  	)
   429  	for i := 0; i < len(input); i += 192 {
   430  		c, err := newCurvePoint(input[i : i+64])
   431  		if err != nil {
   432  			return nil, gas, err
   433  		}
   434  		t, err := newTwistPoint(input[i+64 : i+192])
   435  		if err != nil {
   436  			return nil, gas, err
   437  		}
   438  		cs = append(cs, c)
   439  		ts = append(ts, t)
   440  	}
   441  	// Execute the pairing checks and return the results
   442  	if bn256.PairingCheck(cs, ts) {
   443  		return true32Byte, gas, nil
   444  	}
   445  	return false32Byte, gas, nil
   446  }
   447  
   448  // Native transfer contract to make Celo Gold ERC20 compatible.
   449  type transfer struct{}
   450  
   451  func (c *transfer) RequiredGas(input []byte) uint64 {
   452  	return params.TxGas
   453  }
   454  
   455  func (c *transfer) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   456  	celoGoldAddress, err := GetRegisteredAddressWithEvm(params.GoldTokenRegistryId, evm)
   457  	if err != nil {
   458  		return nil, gas, err
   459  	}
   460  
   461  	// input is comprised of 3 arguments:
   462  	//   from:  32 bytes representing the address of the sender
   463  	//   to:    32 bytes representing the address of the recipient
   464  	//   value: 32 bytes, a 256 bit integer representing the amount of Celo Gold to transfer
   465  	// 3 arguments x 32 bytes each = 96 bytes total input
   466  	if len(input) < 96 {
   467  		return nil, gas, ErrInputLength
   468  	}
   469  
   470  	if caller != *celoGoldAddress {
   471  		return nil, gas, fmt.Errorf("Unable to call transfer from unpermissioned address")
   472  	}
   473  	from := common.BytesToAddress(input[0:32])
   474  	to := common.BytesToAddress(input[32:64])
   475  	var parsed bool
   476  	value, parsed := math.ParseBig256(hexutil.Encode(input[64:96]))
   477  	if !parsed {
   478  		return nil, gas, fmt.Errorf("Error parsing transfer: unable to parse value from " + hexutil.Encode(input[64:96]))
   479  	}
   480  	// Fail if we're trying to transfer more than the available balance
   481  	if !evm.Context.CanTransfer(evm.StateDB, from, value) {
   482  		return nil, gas, ErrInsufficientBalance
   483  	}
   484  
   485  	gas, err = evm.TobinTransfer(evm.StateDB, from, to, gas, value)
   486  
   487  	return input, gas, err
   488  }
   489  
   490  // computes a * (b ^ exponent) to `decimals` places of precision, where a and b are fractions
   491  type fractionMulExp struct{}
   492  
   493  func (c *fractionMulExp) RequiredGas(input []byte) uint64 {
   494  	return params.FractionMulExpGas
   495  }
   496  
   497  func (c *fractionMulExp) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   498  	gas, err := debitRequiredGas(c, input, gas)
   499  	if err != nil {
   500  		return nil, gas, err
   501  	}
   502  
   503  	// input is comprised of 6 arguments:
   504  	//   aNumerator:   32 bytes, 256 bit integer, numerator for the first fraction (a)
   505  	//   aDenominator: 32 bytes, 256 bit integer, denominator for the first fraction (a)
   506  	//   bNumerator:   32 bytes, 256 bit integer, numerator for the second fraction (b)
   507  	//   bDenominator: 32 bytes, 256 bit integer, denominator for the second fraction (b)
   508  	//   exponent:     32 bytes, 256 bit integer, exponent to raise the second fraction (b) to
   509  	//   decimals:     32 bytes, 256 bit integer, places of precision
   510  	//
   511  	// 6 args x 32 bytes each = 192 bytes total input length
   512  	if len(input) < 192 {
   513  		return nil, gas, ErrInputLength
   514  	}
   515  
   516  	parseErrorStr := "Error parsing input: unable to parse %s value from %s"
   517  
   518  	aNumerator, parsed := math.ParseBig256(hexutil.Encode(input[0:32]))
   519  	if !parsed {
   520  		return nil, gas, fmt.Errorf(parseErrorStr, "aNumerator", hexutil.Encode(input[0:32]))
   521  	}
   522  
   523  	aDenominator, parsed := math.ParseBig256(hexutil.Encode(input[32:64]))
   524  	if !parsed {
   525  		return nil, gas, fmt.Errorf(parseErrorStr, "aDenominator", hexutil.Encode(input[32:64]))
   526  	}
   527  
   528  	bNumerator, parsed := math.ParseBig256(hexutil.Encode(input[64:96]))
   529  	if !parsed {
   530  		return nil, gas, fmt.Errorf(parseErrorStr, "bNumerator", hexutil.Encode(input[64:96]))
   531  	}
   532  
   533  	bDenominator, parsed := math.ParseBig256(hexutil.Encode(input[96:128]))
   534  	if !parsed {
   535  		return nil, gas, fmt.Errorf(parseErrorStr, "bDenominator", hexutil.Encode(input[96:128]))
   536  	}
   537  
   538  	exponent, parsed := math.ParseBig256(hexutil.Encode(input[128:160]))
   539  	if !parsed {
   540  		return nil, gas, fmt.Errorf(parseErrorStr, "exponent", hexutil.Encode(input[128:160]))
   541  	}
   542  
   543  	decimals, parsed := math.ParseBig256(hexutil.Encode(input[160:192]))
   544  	if !parsed {
   545  		return nil, gas, fmt.Errorf(parseErrorStr, "decimals", hexutil.Encode(input[160:192]))
   546  	}
   547  
   548  	// Handle passing of zero denominators
   549  	if aDenominator == big.NewInt(0) || bDenominator == big.NewInt(0) {
   550  		return nil, gas, fmt.Errorf("Input Error: Denominator of zero provided!")
   551  	}
   552  
   553  	numeratorExp := new(big.Int).Mul(aNumerator, new(big.Int).Exp(bNumerator, exponent, nil))
   554  	denominatorExp := new(big.Int).Mul(aDenominator, new(big.Int).Exp(bDenominator, exponent, nil))
   555  
   556  	decimalAdjustment := new(big.Int).Exp(big.NewInt(10), decimals, nil)
   557  
   558  	numeratorDecimalAdjusted := new(big.Int).Div(new(big.Int).Mul(numeratorExp, decimalAdjustment), denominatorExp).Bytes()
   559  	denominatorDecimalAdjusted := decimalAdjustment.Bytes()
   560  
   561  	numeratorPadded := common.LeftPadBytes(numeratorDecimalAdjusted, 32)
   562  	denominatorPadded := common.LeftPadBytes(denominatorDecimalAdjusted, 32)
   563  
   564  	return append(numeratorPadded, denominatorPadded...), gas, nil
   565  }
   566  
   567  type proofOfPossession struct{}
   568  
   569  func (c *proofOfPossession) RequiredGas(input []byte) uint64 {
   570  	return params.ProofOfPossessionGas
   571  }
   572  
   573  func (c *proofOfPossession) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   574  	gas, err := debitRequiredGas(c, input, gas)
   575  	if err != nil {
   576  		return nil, gas, err
   577  	}
   578  
   579  	// input is comprised of 3 arguments:
   580  	//   address:   20 bytes, an address used to generate the proof-of-possession
   581  	//   publicKey: 96 bytes, representing the public key (defined as a const in bls package)
   582  	//   signature: 48 bytes, representing the signature on `address` (defined as a const in bls package)
   583  	// the total length of input required is the sum of these constants
   584  	if len(input) != common.AddressLength+blscrypto.PUBLICKEYBYTES+blscrypto.SIGNATUREBYTES {
   585  		return nil, gas, ErrInputLength
   586  	}
   587  	addressBytes := input[:common.AddressLength]
   588  
   589  	publicKeyBytes := input[common.AddressLength : common.AddressLength+blscrypto.PUBLICKEYBYTES]
   590  	publicKey, err := bls.DeserializePublicKey(publicKeyBytes)
   591  	if err != nil {
   592  		return nil, gas, err
   593  	}
   594  	defer publicKey.Destroy()
   595  
   596  	signatureBytes := input[common.AddressLength+blscrypto.PUBLICKEYBYTES : common.AddressLength+blscrypto.PUBLICKEYBYTES+blscrypto.SIGNATUREBYTES]
   597  	signature, err := bls.DeserializeSignature(signatureBytes)
   598  	if err != nil {
   599  		return nil, gas, err
   600  	}
   601  	defer signature.Destroy()
   602  
   603  	err = publicKey.VerifyPoP(addressBytes, signature)
   604  	if err != nil {
   605  		return nil, gas, err
   606  	}
   607  
   608  	return true32Byte, gas, nil
   609  }
   610  
   611  type getValidator struct{}
   612  
   613  func (c *getValidator) RequiredGas(input []byte) uint64 {
   614  	return params.GetValidatorGas
   615  }
   616  
   617  // Return the validators that are required to sign the given, possibly unsealed, block number. If this block is
   618  // the last in an epoch, note that that may mean one or more of those validators may no longer be elected
   619  // for subsequent blocks.
   620  // WARNING: Validator set is always constructed from the canonical chain, therefore this precompile is undefined
   621  // if the engine is aware of a chain with higher total difficulty.
   622  func (c *getValidator) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   623  	gas, err := debitRequiredGas(c, input, gas)
   624  	if err != nil {
   625  		return nil, gas, err
   626  	}
   627  
   628  	// input is comprised of two arguments:
   629  	//   index: 32 byte integer representing the index of the validator to get
   630  	//   blockNumber: 32 byte integer representing the block number to access
   631  	if len(input) < 64 {
   632  		return nil, gas, ErrInputLength
   633  	}
   634  
   635  	index := new(big.Int).SetBytes(input[0:32])
   636  
   637  	blockNumber := new(big.Int).SetBytes(input[32:64])
   638  	if blockNumber.Cmp(common.Big0) == 0 {
   639  		// Validator set for the genesis block is empty, so any index is out of bounds.
   640  		return nil, gas, ErrValidatorsOutOfBounds
   641  	}
   642  	if blockNumber.Cmp(evm.Context.BlockNumber) > 0 {
   643  		return nil, gas, ErrBlockNumberOutOfBounds
   644  	}
   645  
   646  	// Note: Passing empty hash as here as it is an extra expense and the hash is not actually used.
   647  	validators := evm.Context.Engine.GetValidators(new(big.Int).Sub(blockNumber, common.Big1), common.Hash{})
   648  
   649  	// Ensure index, which is guaranteed to be non-negative, is valid.
   650  	if index.Cmp(big.NewInt(int64(len(validators)))) >= 0 {
   651  		return nil, gas, ErrValidatorsOutOfBounds
   652  	}
   653  
   654  	validatorAddress := validators[index.Uint64()].Address()
   655  	addressBytes := common.LeftPadBytes(validatorAddress[:], 32)
   656  
   657  	return addressBytes, gas, nil
   658  }
   659  
   660  type numberValidators struct{}
   661  
   662  func (c *numberValidators) RequiredGas(input []byte) uint64 {
   663  	return params.GetValidatorGas
   664  }
   665  
   666  // Return the number of validators that are required to sign this current, possibly unsealed, block. If this block is
   667  // the last in an epoch, note that that may mean one or more of those validators may no longer be elected
   668  // for subsequent blocks.
   669  // WARNING: Validator set is always constructed from the canonical chain, therefore this precompile is undefined
   670  // if the engine is aware of a chain with higher total difficulty.
   671  func (c *numberValidators) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   672  	gas, err := debitRequiredGas(c, input, gas)
   673  	if err != nil {
   674  		return nil, gas, err
   675  	}
   676  
   677  	// input is comprised of a single argument:
   678  	//   blockNumber: 32 byte integer representing the block number to access
   679  	if len(input) < 32 {
   680  		return nil, gas, ErrInputLength
   681  	}
   682  
   683  	blockNumber := new(big.Int).SetBytes(input[0:32])
   684  	if blockNumber.Cmp(common.Big0) == 0 {
   685  		// Genesis validator set is empty. Return 0.
   686  		return make([]byte, 32), gas, nil
   687  	}
   688  	if blockNumber.Cmp(evm.Context.BlockNumber) > 0 {
   689  		return nil, gas, ErrBlockNumberOutOfBounds
   690  	}
   691  
   692  	// Note: Passing empty hash as here as it is an extra expense and the hash is not actually used.
   693  	validators := evm.Context.Engine.GetValidators(new(big.Int).Sub(blockNumber, common.Big1), common.Hash{})
   694  
   695  	numberValidators := big.NewInt(int64(len(validators))).Bytes()
   696  	numberValidatorsBytes := common.LeftPadBytes(numberValidators[:], 32)
   697  	return numberValidatorsBytes, gas, nil
   698  }
   699  
   700  type epochSize struct{}
   701  
   702  func (c *epochSize) RequiredGas(input []byte) uint64 {
   703  	return params.GetEpochSizeGas
   704  }
   705  
   706  func (c *epochSize) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   707  	gas, err := debitRequiredGas(c, input, gas)
   708  	if err != nil || len(input) != 0 {
   709  		return nil, gas, err
   710  	}
   711  	epochSize := new(big.Int).SetUint64(evm.Context.Engine.EpochSize()).Bytes()
   712  	epochSizeBytes := common.LeftPadBytes(epochSize[:], 32)
   713  
   714  	return epochSizeBytes, gas, nil
   715  }
   716  
   717  type blockNumberFromHeader struct{}
   718  
   719  func (c *blockNumberFromHeader) RequiredGas(input []byte) uint64 {
   720  	return params.GetBlockNumberFromHeaderGas
   721  }
   722  
   723  func (c *blockNumberFromHeader) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   724  	gas, err := debitRequiredGas(c, input, gas)
   725  	if err != nil {
   726  		return nil, gas, err
   727  	}
   728  
   729  	var header types.Header
   730  	err = rlp.DecodeBytes(input, &header)
   731  	if err != nil {
   732  		return nil, gas, ErrInputDecode
   733  	}
   734  
   735  	blockNumber := header.Number.Bytes()
   736  	blockNumberBytes := common.LeftPadBytes(blockNumber[:], 32)
   737  
   738  	return blockNumberBytes, gas, nil
   739  }
   740  
   741  type hashHeader struct{}
   742  
   743  func (c *hashHeader) RequiredGas(input []byte) uint64 {
   744  	return params.HashHeaderGas
   745  }
   746  
   747  func (c *hashHeader) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   748  	gas, err := debitRequiredGas(c, input, gas)
   749  	if err != nil {
   750  		return nil, gas, err
   751  	}
   752  
   753  	var header types.Header
   754  	err = rlp.DecodeBytes(input, &header)
   755  	if err != nil {
   756  		return nil, gas, ErrInputDecode
   757  	}
   758  
   759  	hashBytes := header.Hash().Bytes()
   760  
   761  	return hashBytes, gas, nil
   762  }
   763  
   764  type getParentSealBitmap struct{}
   765  
   766  func (c *getParentSealBitmap) RequiredGas(input []byte) uint64 {
   767  	return params.GetParentSealBitmapGas
   768  }
   769  
   770  // Return the signer bitmap from the parent seal of a past block in the chain.
   771  // Requested parent seal must have occurred within 4 epochs of the current block number.
   772  func (c *getParentSealBitmap) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   773  	gas, err := debitRequiredGas(c, input, gas)
   774  	if err != nil {
   775  		return nil, gas, err
   776  	}
   777  
   778  	// input is comprised of a single argument:
   779  	//   blockNumber: 32 byte integer representing the block number to access
   780  	if len(input) < 32 {
   781  		return nil, gas, ErrInputLength
   782  	}
   783  
   784  	blockNumber := new(big.Int).SetBytes(input[0:32])
   785  
   786  	// Ensure the request is for information from a previously sealed block.
   787  	if blockNumber.Cmp(common.Big0) == 0 || blockNumber.Cmp(evm.Context.BlockNumber) > 0 {
   788  		return nil, gas, ErrBlockNumberOutOfBounds
   789  	}
   790  
   791  	// Ensure the request is for a sufficiently recent block to limit state expansion.
   792  	historyLimit := new(big.Int).SetUint64(evm.Context.Engine.EpochSize() * 4)
   793  	if blockNumber.Cmp(new(big.Int).Sub(evm.Context.BlockNumber, historyLimit)) <= 0 {
   794  		return nil, gas, ErrBlockNumberOutOfBounds
   795  	}
   796  
   797  	header := evm.Context.GetHeaderByNumber(blockNumber.Uint64())
   798  	if header == nil {
   799  		log.Error("Unexpected failure to retrieve block in getParentSealBitmap precompile", "blockNumber", blockNumber)
   800  		return nil, gas, ErrUnexpected
   801  	}
   802  
   803  	extra, err := types.ExtractIstanbulExtra(header)
   804  	if err != nil {
   805  		log.Error("Header without Istanbul extra data encountered in getParentSealBitmap precompile", "blockNumber", blockNumber, "err", err)
   806  		return nil, gas, ErrEngineIncompatible
   807  	}
   808  
   809  	return common.LeftPadBytes(extra.ParentAggregatedSeal.Bitmap.Bytes()[:], 32), gas, nil
   810  }
   811  
   812  // getVerifiedSealBitmap is a precompile to verify the seal on a given header and extract its bitmap.
   813  type getVerifiedSealBitmap struct{}
   814  
   815  func (c *getVerifiedSealBitmap) RequiredGas(input []byte) uint64 {
   816  	return params.GetVerifiedSealBitmapGas
   817  }
   818  
   819  func (c *getVerifiedSealBitmap) Run(input []byte, caller common.Address, evm *EVM, gas uint64) ([]byte, uint64, error) {
   820  	gas, err := debitRequiredGas(c, input, gas)
   821  	if err != nil {
   822  		return nil, gas, err
   823  	}
   824  
   825  	// input is comprised of a single argument:
   826  	//   header:  rlp encoded block header
   827  	var header types.Header
   828  	if err := rlp.DecodeBytes(input, &header); err != nil {
   829  		return nil, gas, ErrInputDecode
   830  	}
   831  
   832  	// Verify the seal against the engine rules.
   833  	if !evm.Context.VerifySeal(&header) {
   834  		return nil, gas, ErrInputVerification
   835  	}
   836  
   837  	// Extract the verified seal from the header.
   838  	extra, err := types.ExtractIstanbulExtra(&header)
   839  	if err != nil {
   840  		log.Error("Header without Istanbul extra data encountered in getVerifiedSealBitmap precompile", "extraData", header.Extra, "err", err)
   841  		// Seal verified by a non-Istanbul engine. Return an error.
   842  		return nil, gas, ErrEngineIncompatible
   843  	}
   844  
   845  	return common.LeftPadBytes(extra.AggregatedSeal.Bitmap.Bytes()[:], 32), gas, nil
   846  }