From d0dbf014f342651a0a62a5e86ba69e5dd5bdd8a9 Mon Sep 17 00:00:00 2001 From: Andrew Ashikhmin <34320705+yperbasis@users.noreply.github.com> Date: Tue, 7 Dec 2021 17:24:59 +0000 Subject: [PATCH] Update consensus tests to 10.2. EIP-2681 (#3103) * ArrowGlacier fork config * core/vm: implement EIP-2681: Limit account nonce to 2^64-1 (#23853) This retroactively implements requirements or EIP-2681 for the account nonce upper limit. * Update consesus tests to 10.2 * Handle TransactionWithHighNonce64Minus1 * Check intrinsic gas in transaction tests * Refactor overflow protection in IntrinsicGas * Remove remnants of vm tests * Update difficulty tests to the new format Co-authored-by: Andrei Maiboroda --- core/error.go | 4 + core/state_transition.go | 45 +++++++-- core/vm/errors.go | 1 + core/vm/evm.go | 3 + tests/difficulty_test.go | 84 +++++----------- tests/difficulty_test_util.go | 23 +++-- tests/gen_difficultytest.go | 11 +-- tests/gen_vmexec.go | 90 ------------------ tests/init.go | 32 ++++++- tests/init_test.go | 2 +- tests/state_test_util.go | 4 + tests/testdata | 2 +- tests/transaction_test.go | 4 - tests/transaction_test_util.go | 30 ++++-- tests/vm_test_util.go | 169 --------------------------------- 15 files changed, 146 insertions(+), 358 deletions(-) delete mode 100644 tests/gen_vmexec.go delete mode 100644 tests/vm_test_util.go diff --git a/core/error.go b/core/error.go index 317f1ea8d..9104c11d6 100644 --- a/core/error.go +++ b/core/error.go @@ -61,6 +61,10 @@ var ( // next one expected based on the local chain. ErrNonceTooHigh = errors.New("nonce too high") + // ErrNonceMax is returned if the nonce of a transaction sender account has + // maximum allowed value and would become invalid if incremented. + ErrNonceMax = errors.New("nonce has max value") + // ErrGasLimitReached is returned by the gas pool if the amount of gas required // by a transaction is higher than what's left in the block. ErrGasLimitReached = errors.New("gas limit reached") diff --git a/core/state_transition.go b/core/state_transition.go index f6b16e7f6..611af47b2 100644 --- a/core/state_transition.go +++ b/core/state_transition.go @@ -18,7 +18,7 @@ package core import ( "fmt" - "math" + "math/bits" "github.com/holiman/uint256" @@ -128,6 +128,10 @@ func IntrinsicGas(data []byte, accessList types.AccessList, isContractCreation b } else { gas = params.TxGas } + + // Auxiliary variables for overflow protection + var product, overflow uint64 + // Bump the required gas by the amount of transactional data if len(data) > 0 { // Zero and non-zero bytes are priced differently @@ -142,20 +146,44 @@ func IntrinsicGas(data []byte, accessList types.AccessList, isContractCreation b if isEIP2028 { nonZeroGas = params.TxDataNonZeroGasEIP2028 } - if (math.MaxUint64-gas)/nonZeroGas < nz { + + overflow, product = bits.Mul64(nz, nonZeroGas) + if overflow != 0 { + return 0, ErrGasUintOverflow + } + gas, overflow = bits.Add64(gas, product, 0) + if overflow != 0 { return 0, ErrGasUintOverflow } - gas += nz * nonZeroGas z := uint64(len(data)) - nz - if (math.MaxUint64-gas)/params.TxDataZeroGas < z { + overflow, product = bits.Mul64(z, params.TxDataZeroGas) + if overflow != 0 { + return 0, ErrGasUintOverflow + } + gas, overflow = bits.Add64(gas, product, 0) + if overflow != 0 { return 0, ErrGasUintOverflow } - gas += z * params.TxDataZeroGas } if accessList != nil { - gas += uint64(len(accessList)) * params.TxAccessListAddressGas - gas += uint64(accessList.StorageKeys()) * params.TxAccessListStorageKeyGas + overflow, product = bits.Mul64(uint64(len(accessList)), params.TxAccessListAddressGas) + if overflow != 0 { + return 0, ErrGasUintOverflow + } + gas, overflow = bits.Add64(gas, product, 0) + if overflow != 0 { + return 0, ErrGasUintOverflow + } + + overflow, product = bits.Mul64(uint64(accessList.StorageKeys()), params.TxAccessListStorageKeyGas) + if overflow != 0 { + return 0, ErrGasUintOverflow + } + gas, overflow = bits.Add64(gas, product, 0) + if overflow != 0 { + return 0, ErrGasUintOverflow + } } return gas, nil } @@ -248,6 +276,9 @@ func (st *StateTransition) preCheck(gasBailout bool) error { } else if stNonce > msgNonce { return fmt.Errorf("%w: address %v, tx: %d state: %d", ErrNonceTooLow, st.msg.From().Hex(), msgNonce, stNonce) + } else if stNonce+1 < stNonce { + return fmt.Errorf("%w: address %v, nonce: %d", ErrNonceMax, + st.msg.From().Hex(), stNonce) } } diff --git a/core/vm/errors.go b/core/vm/errors.go index d0606181a..a3ac70bd6 100644 --- a/core/vm/errors.go +++ b/core/vm/errors.go @@ -40,6 +40,7 @@ var ( ErrInvalidRetsub = errors.New("invalid retsub") ErrReturnStackExceeded = errors.New("return stack limit reached") ErrInvalidCode = errors.New("invalid code") + ErrNonceUintOverflow = errors.New("nonce uint64 overflow") ) // ErrStackUnderflow wraps an evm error when the items on the stack less diff --git a/core/vm/evm.go b/core/vm/evm.go index d44b1975d..42646861d 100644 --- a/core/vm/evm.go +++ b/core/vm/evm.go @@ -505,6 +505,9 @@ func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, }(gas, time.Now()) } nonce := evm.intraBlockState.GetNonce(caller.Address()) + if nonce+1 < nonce { + return nil, common.Address{}, gas, ErrNonceUintOverflow + } evm.intraBlockState.SetNonce(caller.Address(), nonce+1) // We add this to the access list _before_ taking a snapshot. Even if the creation fails, // the access-list change should not be rolled back diff --git a/tests/difficulty_test.go b/tests/difficulty_test.go index c3f8a1bfe..432ba3b41 100644 --- a/tests/difficulty_test.go +++ b/tests/difficulty_test.go @@ -17,75 +17,41 @@ package tests import ( - "math/big" + "encoding/json" + "fmt" "testing" - - "github.com/ledgerwatch/erigon/common" - "github.com/ledgerwatch/erigon/params" -) - -var ( - mainnetChainConfig = params.ChainConfig{ - ChainID: big.NewInt(1), - HomesteadBlock: big.NewInt(1150000), - DAOForkBlock: big.NewInt(1920000), - DAOForkSupport: true, - EIP150Block: big.NewInt(2463000), - EIP150Hash: common.HexToHash("0x2086799aeebeae135c246c65021c82b4e15a2c451340993aacfd2751886514f0"), - EIP155Block: big.NewInt(2675000), - EIP158Block: big.NewInt(2675000), - ByzantiumBlock: big.NewInt(4370000), - } ) func TestDifficulty(t *testing.T) { t.Parallel() dt := new(testMatcher) - // Not difficulty-tests - dt.skipLoad("hexencodetest.*") - dt.skipLoad("crypto.*") - dt.skipLoad("blockgenesistest\\.json") - dt.skipLoad("genesishashestest\\.json") - dt.skipLoad("keyaddrtest\\.json") - dt.skipLoad("txtest\\.json") - // files are 2 years old, contains strange values - dt.skipLoad("difficultyCustomHomestead\\.json") - dt.skipLoad("difficultyMorden\\.json") - dt.skipLoad("difficultyOlimpic\\.json") + dt.walk(t, difficultyTestDir, func(t *testing.T, name string, superTest map[string]json.RawMessage) { + for fork, rawTests := range superTest { + if fork == "_info" { + continue + } + var tests map[string]DifficultyTest + if err := json.Unmarshal(rawTests, &tests); err != nil { + t.Error(err) + continue + } - dt.config("Ropsten", *params.RopstenChainConfig) - dt.config("Morden", *params.RopstenChainConfig) - dt.config("Frontier", params.ChainConfig{}) + cfg, ok := Forks[fork] + if !ok { + t.Error(UnsupportedForkError{fork}) + continue + } - dt.config("Homestead", params.ChainConfig{ - HomesteadBlock: big.NewInt(0), - }) - - dt.config("Byzantium", params.ChainConfig{ - ByzantiumBlock: big.NewInt(0), - }) - - dt.config("Frontier", *params.RopstenChainConfig) - dt.config("MainNetwork", mainnetChainConfig) - dt.config("CustomMainNetwork", mainnetChainConfig) - dt.config("Constantinople", params.ChainConfig{ - ConstantinopleBlock: big.NewInt(0), - }) - dt.config("EIP2384", params.ChainConfig{ - MuirGlacierBlock: big.NewInt(0), - }) - dt.config("difficulty.json", mainnetChainConfig) - - dt.walk(t, difficultyTestDir, func(t *testing.T, name string, test *DifficultyTest) { - cfg := dt.findConfig(name) - if test.ParentDifficulty.Cmp(params.MinimumDifficulty) < 0 { - t.Skip("difficulty below minimum") - return - } - if err := dt.checkFailure(t, test.Run(cfg)); err != nil { - t.Error(err) + for subname, subtest := range tests { + key := fmt.Sprintf("%s/%s", fork, subname) + t.Run(key, func(t *testing.T) { + if err := dt.checkFailure(t, subtest.Run(cfg)); err != nil { + t.Error(err) + } + }) + } } }) } diff --git a/tests/difficulty_test_util.go b/tests/difficulty_test_util.go index 09e4fa985..0277c540d 100644 --- a/tests/difficulty_test_util.go +++ b/tests/difficulty_test_util.go @@ -30,12 +30,12 @@ import ( //go:generate gencodec -type DifficultyTest -field-override difficultyTestMarshaling -out gen_difficultytest.go type DifficultyTest struct { - ParentTimestamp uint64 `json:"parentTimestamp"` - ParentDifficulty *big.Int `json:"parentDifficulty"` - UncleHash common.Hash `json:"parentUncles"` - CurrentTimestamp uint64 `json:"currentTimestamp"` - CurrentBlockNumber uint64 `json:"currentBlockNumber"` - CurrentDifficulty *big.Int `json:"currentDifficulty"` + ParentTimestamp uint64 `json:"parentTimestamp"` + ParentDifficulty *big.Int `json:"parentDifficulty"` + ParentUncles uint64 `json:"parentUncles"` + CurrentTimestamp uint64 `json:"currentTimestamp"` + CurrentBlockNumber uint64 `json:"currentBlockNumber"` + CurrentDifficulty *big.Int `json:"currentDifficulty"` } type difficultyTestMarshaling struct { @@ -43,7 +43,7 @@ type difficultyTestMarshaling struct { ParentDifficulty *math.HexOrDecimal256 CurrentTimestamp math.HexOrDecimal64 CurrentDifficulty *math.HexOrDecimal256 - UncleHash common.Hash + ParentUncles uint64 CurrentBlockNumber math.HexOrDecimal64 } @@ -53,7 +53,12 @@ func (test *DifficultyTest) Run(config *params.ChainConfig) error { Difficulty: test.ParentDifficulty, Time: test.ParentTimestamp, Number: parentNumber, - UncleHash: test.UncleHash, + } + + if test.ParentUncles == 0 { + parent.UncleHash = types.EmptyUncleHash + } else { + parent.UncleHash = common.HexToHash("ab") // some dummy != EmptyUncleHash } actual := ethash.CalcDifficulty(config, test.CurrentTimestamp, parent.Time, parent.Difficulty, parent.Number.Uint64(), parent.UncleHash) @@ -61,7 +66,7 @@ func (test *DifficultyTest) Run(config *params.ChainConfig) error { if actual.Cmp(exp) != 0 { return fmt.Errorf("parent[time %v diff %v unclehash:%x] child[time %v number %v] diff %v != expected %v", - test.ParentTimestamp, test.ParentDifficulty, test.UncleHash, + test.ParentTimestamp, test.ParentDifficulty, test.ParentUncles, test.CurrentTimestamp, test.CurrentBlockNumber, actual, exp) } return nil diff --git a/tests/gen_difficultytest.go b/tests/gen_difficultytest.go index 9750e8fb2..33e3a41bb 100644 --- a/tests/gen_difficultytest.go +++ b/tests/gen_difficultytest.go @@ -6,7 +6,6 @@ import ( "encoding/json" "math/big" - "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/common/math" ) @@ -17,7 +16,7 @@ func (d DifficultyTest) MarshalJSON() ([]byte, error) { type DifficultyTest struct { ParentTimestamp math.HexOrDecimal64 `json:"parentTimestamp"` ParentDifficulty *math.HexOrDecimal256 `json:"parentDifficulty"` - UncleHash common.Hash `json:"parentUncles"` + ParentUncles math.HexOrDecimal64 `json:"parentUncles"` CurrentTimestamp math.HexOrDecimal64 `json:"currentTimestamp"` CurrentBlockNumber math.HexOrDecimal64 `json:"currentBlockNumber"` CurrentDifficulty *math.HexOrDecimal256 `json:"currentDifficulty"` @@ -25,7 +24,7 @@ func (d DifficultyTest) MarshalJSON() ([]byte, error) { var enc DifficultyTest enc.ParentTimestamp = math.HexOrDecimal64(d.ParentTimestamp) enc.ParentDifficulty = (*math.HexOrDecimal256)(d.ParentDifficulty) - enc.UncleHash = d.UncleHash + enc.ParentUncles = math.HexOrDecimal64(d.ParentUncles) enc.CurrentTimestamp = math.HexOrDecimal64(d.CurrentTimestamp) enc.CurrentBlockNumber = math.HexOrDecimal64(d.CurrentBlockNumber) enc.CurrentDifficulty = (*math.HexOrDecimal256)(d.CurrentDifficulty) @@ -37,7 +36,7 @@ func (d *DifficultyTest) UnmarshalJSON(input []byte) error { type DifficultyTest struct { ParentTimestamp *math.HexOrDecimal64 `json:"parentTimestamp"` ParentDifficulty *math.HexOrDecimal256 `json:"parentDifficulty"` - UncleHash *common.Hash `json:"parentUncles"` + ParentUncles *math.HexOrDecimal64 `json:"parentUncles"` CurrentTimestamp *math.HexOrDecimal64 `json:"currentTimestamp"` CurrentBlockNumber *math.HexOrDecimal64 `json:"currentBlockNumber"` CurrentDifficulty *math.HexOrDecimal256 `json:"currentDifficulty"` @@ -52,8 +51,8 @@ func (d *DifficultyTest) UnmarshalJSON(input []byte) error { if dec.ParentDifficulty != nil { d.ParentDifficulty = (*big.Int)(dec.ParentDifficulty) } - if dec.UncleHash != nil { - d.UncleHash = *dec.UncleHash + if dec.ParentUncles != nil { + d.ParentUncles = uint64(*dec.ParentUncles) } if dec.CurrentTimestamp != nil { d.CurrentTimestamp = uint64(*dec.CurrentTimestamp) diff --git a/tests/gen_vmexec.go b/tests/gen_vmexec.go deleted file mode 100644 index 80d73a9e9..000000000 --- a/tests/gen_vmexec.go +++ /dev/null @@ -1,90 +0,0 @@ -// Code generated by github.com/fjl/gencodec. DO NOT EDIT. - -package tests - -import ( - "encoding/json" - "errors" - "math/big" - - "github.com/ledgerwatch/erigon/common" - "github.com/ledgerwatch/erigon/common/hexutil" - "github.com/ledgerwatch/erigon/common/math" -) - -var _ = (*vmExecMarshaling)(nil) - -// MarshalJSON marshals as JSON. -func (v vmExec) MarshalJSON() ([]byte, error) { - type vmExec struct { - Address common.UnprefixedAddress `json:"address" gencodec:"required"` - Caller common.UnprefixedAddress `json:"caller" gencodec:"required"` - Origin common.UnprefixedAddress `json:"origin" gencodec:"required"` - Code hexutil.Bytes `json:"code" gencodec:"required"` - Data hexutil.Bytes `json:"data" gencodec:"required"` - Value *math.HexOrDecimal256 `json:"value" gencodec:"required"` - GasLimit math.HexOrDecimal64 `json:"gas" gencodec:"required"` - GasPrice *math.HexOrDecimal256 `json:"gasPrice" gencodec:"required"` - } - var enc vmExec - enc.Address = common.UnprefixedAddress(v.Address) - enc.Caller = common.UnprefixedAddress(v.Caller) - enc.Origin = common.UnprefixedAddress(v.Origin) - enc.Code = v.Code - enc.Data = v.Data - enc.Value = (*math.HexOrDecimal256)(v.Value) - enc.GasLimit = math.HexOrDecimal64(v.GasLimit) - enc.GasPrice = (*math.HexOrDecimal256)(v.GasPrice) - return json.Marshal(&enc) -} - -// UnmarshalJSON unmarshals from JSON. -func (v *vmExec) UnmarshalJSON(input []byte) error { - type vmExec struct { - Address *common.UnprefixedAddress `json:"address" gencodec:"required"` - Caller *common.UnprefixedAddress `json:"caller" gencodec:"required"` - Origin *common.UnprefixedAddress `json:"origin" gencodec:"required"` - Code *hexutil.Bytes `json:"code" gencodec:"required"` - Data *hexutil.Bytes `json:"data" gencodec:"required"` - Value *math.HexOrDecimal256 `json:"value" gencodec:"required"` - GasLimit *math.HexOrDecimal64 `json:"gas" gencodec:"required"` - GasPrice *math.HexOrDecimal256 `json:"gasPrice" gencodec:"required"` - } - var dec vmExec - if err := json.Unmarshal(input, &dec); err != nil { - return err - } - if dec.Address == nil { - return errors.New("missing required field 'address' for vmExec") - } - v.Address = common.Address(*dec.Address) - if dec.Caller == nil { - return errors.New("missing required field 'caller' for vmExec") - } - v.Caller = common.Address(*dec.Caller) - if dec.Origin == nil { - return errors.New("missing required field 'origin' for vmExec") - } - v.Origin = common.Address(*dec.Origin) - if dec.Code == nil { - return errors.New("missing required field 'code' for vmExec") - } - v.Code = *dec.Code - if dec.Data == nil { - return errors.New("missing required field 'data' for vmExec") - } - v.Data = *dec.Data - if dec.Value == nil { - return errors.New("missing required field 'value' for vmExec") - } - v.Value = (*big.Int)(dec.Value) - if dec.GasLimit == nil { - return errors.New("missing required field 'gas' for vmExec") - } - v.GasLimit = uint64(*dec.GasLimit) - if dec.GasPrice == nil { - return errors.New("missing required field 'gasPrice' for vmExec") - } - v.GasPrice = (*big.Int)(dec.GasPrice) - return nil -} diff --git a/tests/init.go b/tests/init.go index e15a1f05b..794b52b23 100644 --- a/tests/init.go +++ b/tests/init.go @@ -141,8 +141,18 @@ var Forks = map[string]*params.ChainConfig{ PetersburgBlock: big.NewInt(0), IstanbulBlock: big.NewInt(5), }, - // This specification is subject to change, but is for now identical to YOLOv3 - // for cross-client testing purposes + "EIP2384": { + ChainID: big.NewInt(1), + HomesteadBlock: big.NewInt(0), + EIP150Block: big.NewInt(0), + EIP155Block: big.NewInt(0), + EIP158Block: big.NewInt(0), + ByzantiumBlock: big.NewInt(0), + ConstantinopleBlock: big.NewInt(0), + PetersburgBlock: big.NewInt(0), + IstanbulBlock: big.NewInt(0), + MuirGlacierBlock: big.NewInt(0), + }, "Berlin": { ChainID: big.NewInt(1), HomesteadBlock: big.NewInt(0), @@ -153,6 +163,7 @@ var Forks = map[string]*params.ChainConfig{ ConstantinopleBlock: big.NewInt(0), PetersburgBlock: big.NewInt(0), IstanbulBlock: big.NewInt(0), + MuirGlacierBlock: big.NewInt(0), BerlinBlock: big.NewInt(0), }, "BerlinToLondonAt5": { @@ -165,6 +176,7 @@ var Forks = map[string]*params.ChainConfig{ ConstantinopleBlock: big.NewInt(0), PetersburgBlock: big.NewInt(0), IstanbulBlock: big.NewInt(0), + MuirGlacierBlock: big.NewInt(0), BerlinBlock: big.NewInt(0), LondonBlock: big.NewInt(5), }, @@ -178,9 +190,25 @@ var Forks = map[string]*params.ChainConfig{ ConstantinopleBlock: big.NewInt(0), PetersburgBlock: big.NewInt(0), IstanbulBlock: big.NewInt(0), + MuirGlacierBlock: big.NewInt(0), BerlinBlock: big.NewInt(0), LondonBlock: big.NewInt(0), }, + "ArrowGlacier": { + ChainID: big.NewInt(1), + HomesteadBlock: big.NewInt(0), + EIP150Block: big.NewInt(0), + EIP155Block: big.NewInt(0), + EIP158Block: big.NewInt(0), + ByzantiumBlock: big.NewInt(0), + ConstantinopleBlock: big.NewInt(0), + PetersburgBlock: big.NewInt(0), + IstanbulBlock: big.NewInt(0), + MuirGlacierBlock: big.NewInt(0), + BerlinBlock: big.NewInt(0), + LondonBlock: big.NewInt(0), + ArrowGlacierBlock: big.NewInt(0), + }, } // Returns the set of defined fork names diff --git a/tests/init_test.go b/tests/init_test.go index fdc478add..77e037517 100644 --- a/tests/init_test.go +++ b/tests/init_test.go @@ -39,7 +39,7 @@ var ( stateTestDir = filepath.Join(baseDir, "GeneralStateTests") transactionTestDir = filepath.Join(baseDir, "TransactionTests") rlpTestDir = filepath.Join(baseDir, "RLPTests") - difficultyTestDir = filepath.Join(baseDir, "BasicTests") + difficultyTestDir = filepath.Join(baseDir, "DifficultyTests") ) func readJSON(reader io.Reader, value interface{}) error { diff --git a/tests/state_test_util.go b/tests/state_test_util.go index 860e2f8d8..15087dd5a 100644 --- a/tests/state_test_util.go +++ b/tests/state_test_util.go @@ -420,3 +420,7 @@ func rlpHash(x interface{}) (h common.Hash) { hw.Sum(h[:0]) return h } + +func vmTestBlockHash(n uint64) common.Hash { + return common.BytesToHash(crypto.Keccak256([]byte(big.NewInt(int64(n)).String()))) +} diff --git a/tests/testdata b/tests/testdata index fbff6fee0..6401889de 160000 --- a/tests/testdata +++ b/tests/testdata @@ -1 +1 @@ -Subproject commit fbff6fee061ade2358280a8d6f98f67b4ae2b60e +Subproject commit 6401889dec4eee58e808fd178fb2c7f628a3e039 diff --git a/tests/transaction_test.go b/tests/transaction_test.go index 2d528b720..02e1dd415 100644 --- a/tests/transaction_test.go +++ b/tests/transaction_test.go @@ -32,10 +32,6 @@ func TestTransaction(t *testing.T) { // because of the gas limit txt.skipLoad("^ttGasLimit/TransactionWithGasLimitxPriceOverflow.json") - // The nonce is too large for uint64. Not a concern, it means geth won't - // accept transactions at a certain point in the distant future - txt.skipLoad("^ttNonce/TransactionWithHighNonce256.json") - txt.walk(t, transactionTestDir, func(t *testing.T, name string, test *TransactionTest) { cfg := params.MainnetChainConfig if err := txt.checkFailure(t, test.Run(cfg)); err != nil { diff --git a/tests/transaction_test_util.go b/tests/transaction_test_util.go index 60e79cc5a..373b56455 100644 --- a/tests/transaction_test_util.go +++ b/tests/transaction_test_util.go @@ -19,9 +19,11 @@ package tests import ( "bytes" "fmt" + "math/big" "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/common/hexutil" + "github.com/ledgerwatch/erigon/common/math" "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/types" "github.com/ledgerwatch/erigon/params" @@ -48,31 +50,36 @@ type ttForks struct { } type ttFork struct { - Exception string `json:"exception"` - Sender common.Address `json:"sender"` - Hash common.Hash `json:"hash"` + Exception string `json:"exception"` + Sender common.Address `json:"sender"` + Hash common.Hash `json:"hash"` + IntrinsicGas *math.HexOrDecimal256 `json:"intrinsicGas"` } func (tt *TransactionTest) Run(config *params.ChainConfig) error { - validateTx := func(rlpData hexutil.Bytes, signer types.Signer, isHomestead bool, isIstanbul bool) (*common.Address, *common.Hash, error) { + validateTx := func(rlpData hexutil.Bytes, signer types.Signer, isHomestead bool, isIstanbul bool) (*common.Address, *common.Hash, uint64, error) { tx, err := types.DecodeTransaction(rlp.NewStream(bytes.NewReader(rlpData), 0)) if err != nil { - return nil, nil, err + return nil, nil, 0, err } sender, err := tx.Sender(signer) if err != nil { - return nil, nil, err + return nil, nil, 0, err } // Intrinsic gas requiredGas, err := core.IntrinsicGas(tx.GetData(), tx.GetAccessList(), tx.GetTo() == nil, isHomestead, isIstanbul) if err != nil { - return nil, nil, err + return nil, nil, 0, err } if requiredGas > tx.GetGas() { - return nil, nil, fmt.Errorf("insufficient gas ( %d < %d )", tx.GetGas(), requiredGas) + return nil, nil, requiredGas, fmt.Errorf("insufficient gas ( %d < %d )", tx.GetGas(), requiredGas) + } + // EIP-2681: Limit account nonce to 2^64-1 + if tx.GetNonce()+1 < tx.GetNonce() { + return nil, nil, requiredGas, fmt.Errorf("%w: nonce: %d", core.ErrNonceMax, tx.GetNonce()) } h := tx.Hash() - return &sender, &h, nil + return &sender, &h, requiredGas, nil } for _, testcase := range []struct { @@ -93,7 +100,7 @@ func (tt *TransactionTest) Run(config *params.ChainConfig) error { {"Berlin", types.LatestSignerForChainID(config.ChainID), tt.Forks.Berlin, true, true}, {"London", types.LatestSignerForChainID(config.ChainID), tt.Forks.London, true, true}, } { - sender, txhash, err := validateTx(tt.RLP, *testcase.signer, testcase.isHomestead, testcase.isIstanbul) + sender, txhash, intrinsicGas, err := validateTx(tt.RLP, *testcase.signer, testcase.isHomestead, testcase.isIstanbul) if testcase.fork.Exception != "" { if err == nil { @@ -117,6 +124,9 @@ func (tt *TransactionTest) Run(config *params.ChainConfig) error { if *txhash != common.Hash(testcase.fork.Hash) { return fmt.Errorf("hash mismatch: got %x, want %x", *txhash, testcase.fork.Hash) } + if new(big.Int).SetUint64(intrinsicGas).Cmp((*big.Int)(testcase.fork.IntrinsicGas)) != 0 { + return fmt.Errorf("intrinsic gas mismatch: got %x, want %x", intrinsicGas, (*big.Int)(testcase.fork.IntrinsicGas)) + } } return nil } diff --git a/tests/vm_test_util.go b/tests/vm_test_util.go deleted file mode 100644 index a2fa37693..000000000 --- a/tests/vm_test_util.go +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2015 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -package tests - -import ( - "bytes" - "encoding/json" - "fmt" - "math/big" - - "github.com/holiman/uint256" - "github.com/ledgerwatch/erigon-lib/kv" - "github.com/ledgerwatch/erigon/turbo/trie" - - "github.com/ledgerwatch/erigon/common" - "github.com/ledgerwatch/erigon/common/hexutil" - "github.com/ledgerwatch/erigon/common/math" - "github.com/ledgerwatch/erigon/core" - "github.com/ledgerwatch/erigon/core/vm" - "github.com/ledgerwatch/erigon/crypto" - "github.com/ledgerwatch/erigon/params" -) - -// VMTest checks EVM execution without block or transaction context. -// See https://github.com/ethereum/tests/wiki/VM-Tests for the test format specification. -type VMTest struct { - json vmJSON -} - -func (t *VMTest) UnmarshalJSON(data []byte) error { - return json.Unmarshal(data, &t.json) -} - -type vmJSON struct { - Env stEnv `json:"env"` - Exec vmExec `json:"exec"` - Logs common.UnprefixedHash `json:"logs"` - GasRemaining *math.HexOrDecimal64 `json:"gas"` - Out hexutil.Bytes `json:"out"` - Pre core.GenesisAlloc `json:"pre"` - Post core.GenesisAlloc `json:"post"` - PostStateRoot common.Hash `json:"postStateRoot"` -} - -//go:generate gencodec -type vmExec -field-override vmExecMarshaling -out gen_vmexec.go - -type vmExec struct { - Address common.Address `json:"address" gencodec:"required"` - Caller common.Address `json:"caller" gencodec:"required"` - Origin common.Address `json:"origin" gencodec:"required"` - Code []byte `json:"code" gencodec:"required"` - Data []byte `json:"data" gencodec:"required"` - Value *big.Int `json:"value" gencodec:"required"` - GasLimit uint64 `json:"gas" gencodec:"required"` - GasPrice *big.Int `json:"gasPrice" gencodec:"required"` -} - -type vmExecMarshaling struct { - Address common.UnprefixedAddress - Caller common.UnprefixedAddress - Origin common.UnprefixedAddress - Code hexutil.Bytes - Data hexutil.Bytes - Value *math.HexOrDecimal256 - GasLimit math.HexOrDecimal64 - GasPrice *math.HexOrDecimal256 -} - -func (t *VMTest) Run(tx kv.RwTx, vmconfig vm.Config, blockNr uint64) error { - state, err := MakePreState(params.MainnetChainConfig.Rules(blockNr), tx, t.json.Pre, blockNr) - if err != nil { - return fmt.Errorf("error in MakePreState: %w", err) - } - ret, gasRemaining, err := t.exec(state, vmconfig) - // err is not supposed to be checked here, because in VM tests, the failure - // is indicated by the absence of the post-condition section. - // In other words, when such section is not present, we expect an error - if t.json.GasRemaining == nil { - if err == nil { - return fmt.Errorf("gas unspecified (indicating an error), but VM returned no error") - } - if gasRemaining > 0 { - return fmt.Errorf("gas unspecified (indicating an error), but VM returned gas remaining > 0") - } - return nil - } - // Test declares gas, expecting outputs to match. - if !bytes.Equal(ret, t.json.Out) { - return fmt.Errorf("return data mismatch: got %x, want %x", ret, t.json.Out) - } - if gasRemaining != uint64(*t.json.GasRemaining) { - return fmt.Errorf("remaining gas %v, want %v", gasRemaining, *t.json.GasRemaining) - } - var haveV uint256.Int - for addr, account := range t.json.Post { - for k, wantV := range account.Storage { - key := k - state.GetState(addr, &key, &haveV) - if haveV.Bytes32() != wantV { - return fmt.Errorf("wrong storage value at %x:\n got %x\n want %x", k, haveV, wantV) - } - } - } - root, err := trie.CalcRoot("test", tx) - if err != nil { - return fmt.Errorf("Error calculating state root: %w", err) - } - if t.json.PostStateRoot != (common.Hash{}) && root != t.json.PostStateRoot { - return fmt.Errorf("post state root mismatch, got %x, want %x", root, t.json.PostStateRoot) - } - if logs := rlpHash(state.Logs()); logs != common.Hash(t.json.Logs) { - return fmt.Errorf("post state logs hash mismatch: got %x, want %x", logs, t.json.Logs) - } - return nil -} - -func (t *VMTest) exec(state vm.IntraBlockState, vmconfig vm.Config) ([]byte, uint64, error) { - evm := t.newEVM(state, vmconfig) - e := t.json.Exec - value, _ := uint256.FromBig(e.Value) - return evm.Call(vm.AccountRef(e.Caller), e.Address, e.Data, e.GasLimit, value, false /* bailout */) -} - -func (t *VMTest) newEVM(state vm.IntraBlockState, vmconfig vm.Config) *vm.EVM { - initialCall := true - canTransfer := func(db vm.IntraBlockState, address common.Address, amount *uint256.Int) bool { - if initialCall { - initialCall = false - return true - } - return core.CanTransfer(db, address, amount) - } - txContext := vm.TxContext{ - Origin: t.json.Exec.Origin, - GasPrice: t.json.Exec.GasPrice, - } - transfer := func(db vm.IntraBlockState, sender, recipient common.Address, amount *uint256.Int, bailout bool) {} - context := vm.BlockContext{ - CanTransfer: canTransfer, - Transfer: transfer, - GetHash: vmTestBlockHash, - ContractHasTEVM: func(common.Hash) (bool, error) { return false, nil }, - Coinbase: t.json.Env.Coinbase, - BlockNumber: t.json.Env.Number, - Time: t.json.Env.Timestamp, - GasLimit: t.json.Env.GasLimit, - Difficulty: t.json.Env.Difficulty, - } - vmconfig.NoRecursion = true - return vm.NewEVM(context, txContext, state, params.MainnetChainConfig, vmconfig) -} - -func vmTestBlockHash(n uint64) common.Hash { - return common.BytesToHash(crypto.Keccak256([]byte(big.NewInt(int64(n)).String()))) -}