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