github.com/ethereum/go-ethereum@v1.16.1/core/state_processor_test.go (about) 1 // Copyright 2020 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 core 18 19 import ( 20 "crypto/ecdsa" 21 "math" 22 "math/big" 23 "testing" 24 25 "github.com/ethereum/go-ethereum/common" 26 "github.com/ethereum/go-ethereum/consensus" 27 "github.com/ethereum/go-ethereum/consensus/beacon" 28 "github.com/ethereum/go-ethereum/consensus/ethash" 29 "github.com/ethereum/go-ethereum/consensus/misc/eip1559" 30 "github.com/ethereum/go-ethereum/consensus/misc/eip4844" 31 "github.com/ethereum/go-ethereum/core/rawdb" 32 "github.com/ethereum/go-ethereum/core/types" 33 "github.com/ethereum/go-ethereum/crypto" 34 "github.com/ethereum/go-ethereum/params" 35 "github.com/ethereum/go-ethereum/trie" 36 "github.com/holiman/uint256" 37 "golang.org/x/crypto/sha3" 38 ) 39 40 func u64(val uint64) *uint64 { return &val } 41 42 // TestStateProcessorErrors tests the output from the 'core' errors 43 // as defined in core/error.go. These errors are generated when the 44 // blockchain imports bad blocks, meaning blocks which have valid headers but 45 // contain invalid transactions 46 func TestStateProcessorErrors(t *testing.T) { 47 var ( 48 config = params.MergedTestChainConfig 49 signer = types.LatestSigner(config) 50 key1, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") 51 key2, _ = crypto.HexToECDSA("0202020202020202020202020202020202020202020202020202002020202020") 52 ) 53 var makeTx = func(key *ecdsa.PrivateKey, nonce uint64, to common.Address, amount *big.Int, gasLimit uint64, gasPrice *big.Int, data []byte) *types.Transaction { 54 tx, _ := types.SignTx(types.NewTransaction(nonce, to, amount, gasLimit, gasPrice, data), signer, key) 55 return tx 56 } 57 var mkDynamicTx = func(nonce uint64, to common.Address, gasLimit uint64, gasTipCap, gasFeeCap *big.Int) *types.Transaction { 58 tx, _ := types.SignTx(types.NewTx(&types.DynamicFeeTx{ 59 Nonce: nonce, 60 GasTipCap: gasTipCap, 61 GasFeeCap: gasFeeCap, 62 Gas: gasLimit, 63 To: &to, 64 Value: big.NewInt(0), 65 }), signer, key1) 66 return tx 67 } 68 var mkDynamicCreationTx = func(nonce uint64, gasLimit uint64, gasTipCap, gasFeeCap *big.Int, data []byte) *types.Transaction { 69 tx, _ := types.SignTx(types.NewTx(&types.DynamicFeeTx{ 70 Nonce: nonce, 71 GasTipCap: gasTipCap, 72 GasFeeCap: gasFeeCap, 73 Gas: gasLimit, 74 Value: big.NewInt(0), 75 Data: data, 76 }), signer, key1) 77 return tx 78 } 79 var mkBlobTx = func(nonce uint64, to common.Address, gasLimit uint64, gasTipCap, gasFeeCap, blobGasFeeCap *big.Int, hashes []common.Hash) *types.Transaction { 80 tx, err := types.SignTx(types.NewTx(&types.BlobTx{ 81 Nonce: nonce, 82 GasTipCap: uint256.MustFromBig(gasTipCap), 83 GasFeeCap: uint256.MustFromBig(gasFeeCap), 84 Gas: gasLimit, 85 To: to, 86 BlobHashes: hashes, 87 BlobFeeCap: uint256.MustFromBig(blobGasFeeCap), 88 Value: new(uint256.Int), 89 }), signer, key1) 90 if err != nil { 91 t.Fatal(err) 92 } 93 return tx 94 } 95 var mkSetCodeTx = func(nonce uint64, to common.Address, gasLimit uint64, gasTipCap, gasFeeCap *big.Int, authlist []types.SetCodeAuthorization) *types.Transaction { 96 tx, err := types.SignTx(types.NewTx(&types.SetCodeTx{ 97 Nonce: nonce, 98 GasTipCap: uint256.MustFromBig(gasTipCap), 99 GasFeeCap: uint256.MustFromBig(gasFeeCap), 100 Gas: gasLimit, 101 To: to, 102 Value: new(uint256.Int), 103 AuthList: authlist, 104 }), signer, key1) 105 if err != nil { 106 t.Fatal(err) 107 } 108 return tx 109 } 110 111 { // Tests against a 'recent' chain definition 112 var ( 113 db = rawdb.NewMemoryDatabase() 114 gspec = &Genesis{ 115 Config: config, 116 Alloc: types.GenesisAlloc{ 117 common.HexToAddress("0x71562b71999873DB5b286dF957af199Ec94617F7"): types.Account{ 118 Balance: big.NewInt(1000000000000000000), // 1 ether 119 Nonce: 0, 120 }, 121 common.HexToAddress("0xfd0810DD14796680f72adf1a371963d0745BCc64"): types.Account{ 122 Balance: big.NewInt(1000000000000000000), // 1 ether 123 Nonce: math.MaxUint64, 124 }, 125 }, 126 } 127 blockchain, _ = NewBlockChain(db, gspec, beacon.New(ethash.NewFaker()), nil) 128 tooBigInitCode = [params.MaxInitCodeSize + 1]byte{} 129 ) 130 131 defer blockchain.Stop() 132 bigNumber := new(big.Int).SetBytes(common.MaxHash.Bytes()) 133 tooBigNumber := new(big.Int).Set(bigNumber) 134 tooBigNumber.Add(tooBigNumber, common.Big1) 135 for i, tt := range []struct { 136 txs []*types.Transaction 137 want string 138 }{ 139 { // ErrNonceTooLow 140 txs: []*types.Transaction{ 141 makeTx(key1, 0, common.Address{}, big.NewInt(0), params.TxGas, big.NewInt(875000000), nil), 142 makeTx(key1, 0, common.Address{}, big.NewInt(0), params.TxGas, big.NewInt(875000000), nil), 143 }, 144 want: "could not apply tx 1 [0x0026256b3939ed97e2c4a6f3fce8ecf83bdcfa6d507c47838c308a1fb0436f62]: nonce too low: address 0x71562b71999873DB5b286dF957af199Ec94617F7, tx: 0 state: 1", 145 }, 146 { // ErrNonceTooHigh 147 txs: []*types.Transaction{ 148 makeTx(key1, 100, common.Address{}, big.NewInt(0), params.TxGas, big.NewInt(875000000), nil), 149 }, 150 want: "could not apply tx 0 [0xdebad714ca7f363bd0d8121c4518ad48fa469ca81b0a081be3d10c17460f751b]: nonce too high: address 0x71562b71999873DB5b286dF957af199Ec94617F7, tx: 100 state: 0", 151 }, 152 { // ErrNonceMax 153 txs: []*types.Transaction{ 154 makeTx(key2, math.MaxUint64, common.Address{}, big.NewInt(0), params.TxGas, big.NewInt(875000000), nil), 155 }, 156 want: "could not apply tx 0 [0x84ea18d60eb2bb3b040e3add0eb72f757727122cc257dd858c67cb6591a85986]: nonce has max value: address 0xfd0810DD14796680f72adf1a371963d0745BCc64, nonce: 18446744073709551615", 157 }, 158 { // ErrGasLimitReached 159 txs: []*types.Transaction{ 160 makeTx(key1, 0, common.Address{}, big.NewInt(0), 21000000, big.NewInt(875000000), nil), 161 }, 162 want: "could not apply tx 0 [0xbd49d8dadfd47fb846986695f7d4da3f7b2c48c8da82dbc211a26eb124883de9]: gas limit reached", 163 }, 164 { // ErrInsufficientFundsForTransfer 165 txs: []*types.Transaction{ 166 makeTx(key1, 0, common.Address{}, big.NewInt(1000000000000000000), params.TxGas, big.NewInt(875000000), nil), 167 }, 168 want: "could not apply tx 0 [0x98c796b470f7fcab40aaef5c965a602b0238e1034cce6fb73823042dd0638d74]: insufficient funds for gas * price + value: address 0x71562b71999873DB5b286dF957af199Ec94617F7 have 1000000000000000000 want 1000018375000000000", 169 }, 170 { // ErrInsufficientFunds 171 txs: []*types.Transaction{ 172 makeTx(key1, 0, common.Address{}, big.NewInt(0), params.TxGas, big.NewInt(900000000000000000), nil), 173 }, 174 want: "could not apply tx 0 [0x4a69690c4b0cd85e64d0d9ea06302455b01e10a83db964d60281739752003440]: insufficient funds for gas * price + value: address 0x71562b71999873DB5b286dF957af199Ec94617F7 have 1000000000000000000 want 18900000000000000000000", 175 }, 176 // ErrGasUintOverflow 177 // One missing 'core' error is ErrGasUintOverflow: "gas uint64 overflow", 178 // In order to trigger that one, we'd have to allocate a _huge_ chunk of data, such that the 179 // multiplication len(data) +gas_per_byte overflows uint64. Not testable at the moment 180 { // ErrIntrinsicGas 181 txs: []*types.Transaction{ 182 makeTx(key1, 0, common.Address{}, big.NewInt(0), params.TxGas-1000, big.NewInt(875000000), nil), 183 }, 184 want: "could not apply tx 0 [0xcf3b049a0b516cb4f9274b3e2a264359e2ba53b2fb64b7bda2c634d5c9d01fca]: intrinsic gas too low: have 20000, want 21000", 185 }, 186 { // ErrGasLimitReached 187 txs: []*types.Transaction{ 188 makeTx(key1, 0, common.Address{}, big.NewInt(0), params.TxGas*1000, big.NewInt(875000000), nil), 189 }, 190 want: "could not apply tx 0 [0xbd49d8dadfd47fb846986695f7d4da3f7b2c48c8da82dbc211a26eb124883de9]: gas limit reached", 191 }, 192 { // ErrFeeCapTooLow 193 txs: []*types.Transaction{ 194 mkDynamicTx(0, common.Address{}, params.TxGas, big.NewInt(0), big.NewInt(0)), 195 }, 196 want: "could not apply tx 0 [0xc4ab868fef0c82ae0387b742aee87907f2d0fc528fc6ea0a021459fb0fc4a4a8]: max fee per gas less than block base fee: address 0x71562b71999873DB5b286dF957af199Ec94617F7, maxFeePerGas: 0, baseFee: 875000000", 197 }, 198 { // ErrTipVeryHigh 199 txs: []*types.Transaction{ 200 mkDynamicTx(0, common.Address{}, params.TxGas, tooBigNumber, big.NewInt(1)), 201 }, 202 want: "could not apply tx 0 [0x15b8391b9981f266b32f3ab7da564bbeb3d6c21628364ea9b32a21139f89f712]: max priority fee per gas higher than 2^256-1: address 0x71562b71999873DB5b286dF957af199Ec94617F7, maxPriorityFeePerGas bit length: 257", 203 }, 204 { // ErrFeeCapVeryHigh 205 txs: []*types.Transaction{ 206 mkDynamicTx(0, common.Address{}, params.TxGas, big.NewInt(1), tooBigNumber), 207 }, 208 want: "could not apply tx 0 [0x48bc299b83fdb345c57478f239e89814bb3063eb4e4b49f3b6057a69255c16bd]: max fee per gas higher than 2^256-1: address 0x71562b71999873DB5b286dF957af199Ec94617F7, maxFeePerGas bit length: 257", 209 }, 210 { // ErrTipAboveFeeCap 211 txs: []*types.Transaction{ 212 mkDynamicTx(0, common.Address{}, params.TxGas, big.NewInt(2), big.NewInt(1)), 213 }, 214 want: "could not apply tx 0 [0xf987a31ff0c71895780a7612f965a0c8b056deb54e020bb44fa478092f14c9b4]: max priority fee per gas higher than max fee per gas: address 0x71562b71999873DB5b286dF957af199Ec94617F7, maxPriorityFeePerGas: 2, maxFeePerGas: 1", 215 }, 216 { // ErrInsufficientFunds 217 // Available balance: 1000000000000000000 218 // Effective cost: 18375000021000 219 // FeeCap * gas: 1050000000000000000 220 // This test is designed to have the effective cost be covered by the balance, but 221 // the extended requirement on FeeCap*gas < balance to fail 222 txs: []*types.Transaction{ 223 mkDynamicTx(0, common.Address{}, params.TxGas, big.NewInt(1), big.NewInt(50000000000000)), 224 }, 225 want: "could not apply tx 0 [0x413603cd096a87f41b1660d3ed3e27d62e1da78eac138961c0a1314ed43bd129]: insufficient funds for gas * price + value: address 0x71562b71999873DB5b286dF957af199Ec94617F7 have 1000000000000000000 want 1050000000000000000", 226 }, 227 { // Another ErrInsufficientFunds, this one to ensure that feecap/tip of max u256 is allowed 228 txs: []*types.Transaction{ 229 mkDynamicTx(0, common.Address{}, params.TxGas, bigNumber, bigNumber), 230 }, 231 want: "could not apply tx 0 [0xd82a0c2519acfeac9a948258c47e784acd20651d9d80f9a1c67b4137651c3a24]: insufficient funds for gas * price + value: address 0x71562b71999873DB5b286dF957af199Ec94617F7 required balance exceeds 256 bits", 232 }, 233 { // ErrMaxInitCodeSizeExceeded 234 txs: []*types.Transaction{ 235 mkDynamicCreationTx(0, 520000, common.Big0, big.NewInt(params.InitialBaseFee), tooBigInitCode[:]), 236 }, 237 want: "could not apply tx 0 [0x3a30404d42d6ccc843d7c391fd0c87b9b9795a0c174261b46d2ac95ca17b81cd]: max initcode size exceeded: code size 49153 limit 49152", 238 }, 239 { // ErrIntrinsicGas: Not enough gas to cover init code 240 txs: []*types.Transaction{ 241 mkDynamicCreationTx(0, 54299, common.Big0, big.NewInt(params.InitialBaseFee), make([]byte, 320)), 242 }, 243 want: "could not apply tx 0 [0xfd49536a9b323769d8472fcb3ebb3689b707a349379baee3e2ee3fe7baae06a1]: intrinsic gas too low: have 54299, want 54300", 244 }, 245 { // ErrBlobFeeCapTooLow 246 txs: []*types.Transaction{ 247 mkBlobTx(0, common.Address{}, params.TxGas, big.NewInt(1), big.NewInt(1), big.NewInt(0), []common.Hash{(common.Hash{1})}), 248 }, 249 want: "could not apply tx 0 [0x6c11015985ce82db691d7b2d017acda296db88b811c3c60dc71449c76256c716]: max fee per gas less than block base fee: address 0x71562b71999873DB5b286dF957af199Ec94617F7, maxFeePerGas: 1, baseFee: 875000000", 250 }, 251 { // ErrEmptyAuthList 252 txs: []*types.Transaction{ 253 mkSetCodeTx(0, common.Address{}, params.TxGas, big.NewInt(params.InitialBaseFee), big.NewInt(params.InitialBaseFee), nil), 254 }, 255 want: "could not apply tx 0 [0xc18d10f4c809dbdfa1a074c3300de9bc4b7f16a20f0ec667f6f67312b71b956a]: EIP-7702 transaction with empty auth list (sender 0x71562b71999873DB5b286dF957af199Ec94617F7)", 256 }, 257 // ErrSetCodeTxCreate cannot be tested here: it is impossible to create a SetCode-tx with nil `to`. 258 // The EstimateGas API tests test this case. 259 } { 260 block := GenerateBadBlock(gspec.ToBlock(), beacon.New(ethash.NewFaker()), tt.txs, gspec.Config, false) 261 _, err := blockchain.InsertChain(types.Blocks{block}) 262 if err == nil { 263 t.Fatal("block imported without errors") 264 } 265 if have, want := err.Error(), tt.want; have != want { 266 t.Errorf("test %d:\nhave \"%v\"\nwant \"%v\"\n", i, have, want) 267 } 268 } 269 } 270 271 // ErrTxTypeNotSupported, For this, we need an older chain 272 { 273 var ( 274 db = rawdb.NewMemoryDatabase() 275 gspec = &Genesis{ 276 Config: ¶ms.ChainConfig{ 277 ChainID: big.NewInt(1), 278 HomesteadBlock: big.NewInt(0), 279 EIP150Block: big.NewInt(0), 280 EIP155Block: big.NewInt(0), 281 EIP158Block: big.NewInt(0), 282 ByzantiumBlock: big.NewInt(0), 283 ConstantinopleBlock: big.NewInt(0), 284 PetersburgBlock: big.NewInt(0), 285 IstanbulBlock: big.NewInt(0), 286 MuirGlacierBlock: big.NewInt(0), 287 }, 288 Alloc: types.GenesisAlloc{ 289 common.HexToAddress("0x71562b71999873DB5b286dF957af199Ec94617F7"): types.Account{ 290 Balance: big.NewInt(1000000000000000000), // 1 ether 291 Nonce: 0, 292 }, 293 }, 294 } 295 blockchain, _ = NewBlockChain(db, gspec, ethash.NewFaker(), nil) 296 ) 297 defer blockchain.Stop() 298 for i, tt := range []struct { 299 txs []*types.Transaction 300 want string 301 }{ 302 { // ErrTxTypeNotSupported 303 txs: []*types.Transaction{ 304 mkDynamicTx(0, common.Address{}, params.TxGas-1000, big.NewInt(0), big.NewInt(0)), 305 }, 306 want: "could not apply tx 0 [0x88626ac0d53cb65308f2416103c62bb1f18b805573d4f96a3640bbbfff13c14f]: transaction type not supported", 307 }, 308 } { 309 block := GenerateBadBlock(gspec.ToBlock(), ethash.NewFaker(), tt.txs, gspec.Config, true) 310 _, err := blockchain.InsertChain(types.Blocks{block}) 311 if err == nil { 312 t.Fatal("block imported without errors") 313 } 314 if have, want := err.Error(), tt.want; have != want { 315 t.Errorf("test %d:\nhave \"%v\"\nwant \"%v\"\n", i, have, want) 316 } 317 } 318 } 319 320 // ErrSenderNoEOA, for this we need the sender to have contract code 321 { 322 var ( 323 db = rawdb.NewMemoryDatabase() 324 gspec = &Genesis{ 325 Config: config, 326 Alloc: types.GenesisAlloc{ 327 common.HexToAddress("0x71562b71999873DB5b286dF957af199Ec94617F7"): types.Account{ 328 Balance: big.NewInt(1000000000000000000), // 1 ether 329 Nonce: 0, 330 Code: common.FromHex("0xB0B0FACE"), 331 }, 332 }, 333 } 334 blockchain, _ = NewBlockChain(db, gspec, beacon.New(ethash.NewFaker()), nil) 335 ) 336 defer blockchain.Stop() 337 for i, tt := range []struct { 338 txs []*types.Transaction 339 want string 340 }{ 341 { // ErrSenderNoEOA 342 txs: []*types.Transaction{ 343 mkDynamicTx(0, common.Address{}, params.TxGas-1000, big.NewInt(0), big.NewInt(0)), 344 }, 345 want: "could not apply tx 0 [0x88626ac0d53cb65308f2416103c62bb1f18b805573d4f96a3640bbbfff13c14f]: sender not an eoa: address 0x71562b71999873DB5b286dF957af199Ec94617F7, len(code): 4", 346 }, 347 } { 348 block := GenerateBadBlock(gspec.ToBlock(), beacon.New(ethash.NewFaker()), tt.txs, gspec.Config, false) 349 _, err := blockchain.InsertChain(types.Blocks{block}) 350 if err == nil { 351 t.Fatal("block imported without errors") 352 } 353 if have, want := err.Error(), tt.want; have != want { 354 t.Errorf("test %d:\nhave \"%v\"\nwant \"%v\"\n", i, have, want) 355 } 356 } 357 } 358 } 359 360 // GenerateBadBlock constructs a "block" which contains the transactions. The transactions are not expected to be 361 // valid, and no proper post-state can be made. But from the perspective of the blockchain, the block is sufficiently 362 // valid to be considered for import: 363 // - valid pow (fake), ancestry, difficulty, gaslimit etc 364 func GenerateBadBlock(parent *types.Block, engine consensus.Engine, txs types.Transactions, config *params.ChainConfig, isPOW bool) *types.Block { 365 difficulty := big.NewInt(0) 366 if isPOW { 367 fakeChainReader := newChainMaker(nil, config, engine) 368 difficulty = engine.CalcDifficulty(fakeChainReader, parent.Time()+10, &types.Header{ 369 Number: parent.Number(), 370 Time: parent.Time(), 371 Difficulty: parent.Difficulty(), 372 UncleHash: parent.UncleHash(), 373 }) 374 } 375 376 header := &types.Header{ 377 ParentHash: parent.Hash(), 378 Coinbase: parent.Coinbase(), 379 Difficulty: difficulty, 380 GasLimit: parent.GasLimit(), 381 Number: new(big.Int).Add(parent.Number(), common.Big1), 382 Time: parent.Time() + 10, 383 UncleHash: types.EmptyUncleHash, 384 } 385 if config.IsLondon(header.Number) { 386 header.BaseFee = eip1559.CalcBaseFee(config, parent.Header()) 387 } 388 if config.IsShanghai(header.Number, header.Time) { 389 header.WithdrawalsHash = &types.EmptyWithdrawalsHash 390 } 391 var receipts []*types.Receipt 392 // The post-state result doesn't need to be correct (this is a bad block), but we do need something there 393 // Preferably something unique. So let's use a combo of blocknum + txhash 394 hasher := sha3.NewLegacyKeccak256() 395 hasher.Write(header.Number.Bytes()) 396 var cumulativeGas uint64 397 var nBlobs int 398 for _, tx := range txs { 399 txh := tx.Hash() 400 hasher.Write(txh[:]) 401 receipt := types.NewReceipt(nil, false, cumulativeGas+tx.Gas()) 402 receipt.TxHash = tx.Hash() 403 receipt.GasUsed = tx.Gas() 404 receipts = append(receipts, receipt) 405 cumulativeGas += tx.Gas() 406 nBlobs += len(tx.BlobHashes()) 407 } 408 header.Root = common.BytesToHash(hasher.Sum(nil)) 409 if config.IsCancun(header.Number, header.Time) { 410 excess := eip4844.CalcExcessBlobGas(config, parent.Header(), header.Time) 411 used := uint64(nBlobs * params.BlobTxBlobGasPerBlob) 412 header.ExcessBlobGas = &excess 413 header.BlobGasUsed = &used 414 415 beaconRoot := common.HexToHash("0xbeac00") 416 header.ParentBeaconRoot = &beaconRoot 417 } 418 // Assemble and return the final block for sealing 419 body := &types.Body{Transactions: txs} 420 if config.IsShanghai(header.Number, header.Time) { 421 body.Withdrawals = []*types.Withdrawal{} 422 } 423 return types.NewBlock(header, body, receipts, trie.NewStackTrie(nil)) 424 }