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