github.com/ethereum/go-ethereum@v1.16.1/core/vm/runtime/runtime_test.go (about) 1 // Copyright 2015 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 runtime 18 19 import ( 20 "encoding/binary" 21 "fmt" 22 "math/big" 23 "os" 24 "strconv" 25 "strings" 26 "testing" 27 28 "github.com/ethereum/go-ethereum/accounts/abi" 29 "github.com/ethereum/go-ethereum/common" 30 "github.com/ethereum/go-ethereum/consensus" 31 "github.com/ethereum/go-ethereum/core" 32 "github.com/ethereum/go-ethereum/core/state" 33 "github.com/ethereum/go-ethereum/core/tracing" 34 "github.com/ethereum/go-ethereum/core/types" 35 "github.com/ethereum/go-ethereum/core/vm" 36 "github.com/ethereum/go-ethereum/core/vm/program" 37 "github.com/ethereum/go-ethereum/eth/tracers" 38 "github.com/ethereum/go-ethereum/eth/tracers/logger" 39 "github.com/ethereum/go-ethereum/params" 40 41 // force-load js tracers to trigger registration 42 _ "github.com/ethereum/go-ethereum/eth/tracers/js" 43 ) 44 45 func TestDefaults(t *testing.T) { 46 cfg := new(Config) 47 setDefaults(cfg) 48 49 if cfg.Difficulty == nil { 50 t.Error("expected difficulty to be non nil") 51 } 52 53 if cfg.GasLimit == 0 { 54 t.Error("didn't expect gaslimit to be zero") 55 } 56 if cfg.GasPrice == nil { 57 t.Error("expected time to be non nil") 58 } 59 if cfg.Value == nil { 60 t.Error("expected time to be non nil") 61 } 62 if cfg.GetHashFn == nil { 63 t.Error("expected time to be non nil") 64 } 65 if cfg.BlockNumber == nil { 66 t.Error("expected block number to be non nil") 67 } 68 } 69 70 func TestEVM(t *testing.T) { 71 defer func() { 72 if r := recover(); r != nil { 73 t.Fatalf("crashed with: %v", r) 74 } 75 }() 76 77 Execute([]byte{ 78 byte(vm.DIFFICULTY), 79 byte(vm.TIMESTAMP), 80 byte(vm.GASLIMIT), 81 byte(vm.PUSH1), 82 byte(vm.ORIGIN), 83 byte(vm.BLOCKHASH), 84 byte(vm.COINBASE), 85 }, nil, nil) 86 } 87 88 func TestExecute(t *testing.T) { 89 ret, _, err := Execute([]byte{ 90 byte(vm.PUSH1), 10, 91 byte(vm.PUSH1), 0, 92 byte(vm.MSTORE), 93 byte(vm.PUSH1), 32, 94 byte(vm.PUSH1), 0, 95 byte(vm.RETURN), 96 }, nil, nil) 97 if err != nil { 98 t.Fatal("didn't expect error", err) 99 } 100 101 num := new(big.Int).SetBytes(ret) 102 if num.Cmp(big.NewInt(10)) != 0 { 103 t.Error("Expected 10, got", num) 104 } 105 } 106 107 func TestCall(t *testing.T) { 108 state, _ := state.New(types.EmptyRootHash, state.NewDatabaseForTesting()) 109 address := common.HexToAddress("0xaa") 110 state.SetCode(address, []byte{ 111 byte(vm.PUSH1), 10, 112 byte(vm.PUSH1), 0, 113 byte(vm.MSTORE), 114 byte(vm.PUSH1), 32, 115 byte(vm.PUSH1), 0, 116 byte(vm.RETURN), 117 }) 118 119 ret, _, err := Call(address, nil, &Config{State: state}) 120 if err != nil { 121 t.Fatal("didn't expect error", err) 122 } 123 124 num := new(big.Int).SetBytes(ret) 125 if num.Cmp(big.NewInt(10)) != 0 { 126 t.Error("Expected 10, got", num) 127 } 128 } 129 130 func BenchmarkCall(b *testing.B) { 131 var definition = `[{"constant":true,"inputs":[],"name":"seller","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":false,"inputs":[],"name":"abort","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"value","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[],"name":"refund","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"buyer","outputs":[{"name":"","type":"address"}],"type":"function"},{"constant":false,"inputs":[],"name":"confirmReceived","outputs":[],"type":"function"},{"constant":true,"inputs":[],"name":"state","outputs":[{"name":"","type":"uint8"}],"type":"function"},{"constant":false,"inputs":[],"name":"confirmPurchase","outputs":[],"type":"function"},{"inputs":[],"type":"constructor"},{"anonymous":false,"inputs":[],"name":"Aborted","type":"event"},{"anonymous":false,"inputs":[],"name":"PurchaseConfirmed","type":"event"},{"anonymous":false,"inputs":[],"name":"ItemReceived","type":"event"},{"anonymous":false,"inputs":[],"name":"Refunded","type":"event"}]` 132 133 var code = common.Hex2Bytes("6060604052361561006c5760e060020a600035046308551a53811461007457806335a063b4146100865780633fa4f245146100a6578063590e1ae3146100af5780637150d8ae146100cf57806373fac6f0146100e1578063c19d93fb146100fe578063d696069714610112575b610131610002565b610133600154600160a060020a031681565b610131600154600160a060020a0390811633919091161461015057610002565b61014660005481565b610131600154600160a060020a039081163391909116146102d557610002565b610133600254600160a060020a031681565b610131600254600160a060020a0333811691161461023757610002565b61014660025460ff60a060020a9091041681565b61013160025460009060ff60a060020a9091041681146101cc57610002565b005b600160a060020a03166060908152602090f35b6060908152602090f35b60025460009060a060020a900460ff16811461016b57610002565b600154600160a060020a03908116908290301631606082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f72c874aeff0b183a56e2b79c71b46e1aed4dee5e09862134b8821ba2fddbf8bf9250a150565b80546002023414806101dd57610002565b6002805460a060020a60ff021973ffffffffffffffffffffffffffffffffffffffff1990911633171660a060020a1790557fd5d55c8a68912e9a110618df8d5e2e83b8d83211c57a8ddd1203df92885dc881826060a15050565b60025460019060a060020a900460ff16811461025257610002565b60025460008054600160a060020a0390921691606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517fe89152acd703c9d8c7d28829d443260b411454d45394e7995815140c8cbcbcf79250a150565b60025460019060a060020a900460ff1681146102f057610002565b6002805460008054600160a060020a0390921692909102606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f8616bbbbad963e4e65b1366f1d75dfb63f9e9704bbbf91fb01bec70849906cf79250a15056") 134 135 abi, err := abi.JSON(strings.NewReader(definition)) 136 if err != nil { 137 b.Fatal(err) 138 } 139 140 cpurchase, err := abi.Pack("confirmPurchase") 141 if err != nil { 142 b.Fatal(err) 143 } 144 creceived, err := abi.Pack("confirmReceived") 145 if err != nil { 146 b.Fatal(err) 147 } 148 refund, err := abi.Pack("refund") 149 if err != nil { 150 b.Fatal(err) 151 } 152 153 b.ResetTimer() 154 for i := 0; i < b.N; i++ { 155 for j := 0; j < 400; j++ { 156 Execute(code, cpurchase, nil) 157 Execute(code, creceived, nil) 158 Execute(code, refund, nil) 159 } 160 } 161 } 162 func benchmarkEVM_Create(bench *testing.B, code string) { 163 var ( 164 statedb, _ = state.New(types.EmptyRootHash, state.NewDatabaseForTesting()) 165 sender = common.BytesToAddress([]byte("sender")) 166 receiver = common.BytesToAddress([]byte("receiver")) 167 ) 168 169 statedb.CreateAccount(sender) 170 statedb.SetCode(receiver, common.FromHex(code)) 171 runtimeConfig := Config{ 172 Origin: sender, 173 State: statedb, 174 GasLimit: 10000000, 175 Difficulty: big.NewInt(0x200000), 176 Time: 0, 177 Coinbase: common.Address{}, 178 BlockNumber: new(big.Int).SetUint64(1), 179 ChainConfig: ¶ms.ChainConfig{ 180 ChainID: big.NewInt(1), 181 HomesteadBlock: new(big.Int), 182 ByzantiumBlock: new(big.Int), 183 ConstantinopleBlock: new(big.Int), 184 DAOForkBlock: new(big.Int), 185 DAOForkSupport: false, 186 EIP150Block: new(big.Int), 187 EIP155Block: new(big.Int), 188 EIP158Block: new(big.Int), 189 }, 190 EVMConfig: vm.Config{}, 191 } 192 // Warm up the intpools and stuff 193 bench.ResetTimer() 194 for i := 0; i < bench.N; i++ { 195 Call(receiver, []byte{}, &runtimeConfig) 196 } 197 bench.StopTimer() 198 } 199 200 func BenchmarkEVM_CREATE_500(bench *testing.B) { 201 // initcode size 500K, repeatedly calls CREATE and then modifies the mem contents 202 benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056") 203 } 204 func BenchmarkEVM_CREATE2_500(bench *testing.B) { 205 // initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents 206 benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056") 207 } 208 func BenchmarkEVM_CREATE_1200(bench *testing.B) { 209 // initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents 210 benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056") 211 } 212 func BenchmarkEVM_CREATE2_1200(bench *testing.B) { 213 // initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents 214 benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056") 215 } 216 217 func BenchmarkEVM_SWAP1(b *testing.B) { 218 // returns a contract that does n swaps (SWAP1) 219 swapContract := func(n uint64) []byte { 220 contract := []byte{ 221 byte(vm.PUSH0), // PUSH0 222 byte(vm.PUSH0), // PUSH0 223 } 224 for i := uint64(0); i < n; i++ { 225 contract = append(contract, byte(vm.SWAP1)) 226 } 227 return contract 228 } 229 230 state, _ := state.New(types.EmptyRootHash, state.NewDatabaseForTesting()) 231 contractAddr := common.BytesToAddress([]byte("contract")) 232 233 b.Run("10k", func(b *testing.B) { 234 contractCode := swapContract(10_000) 235 state.SetCode(contractAddr, contractCode) 236 237 for i := 0; i < b.N; i++ { 238 _, _, err := Call(contractAddr, []byte{}, &Config{State: state}) 239 if err != nil { 240 b.Fatal(err) 241 } 242 } 243 }) 244 } 245 246 func BenchmarkEVM_RETURN(b *testing.B) { 247 // returns a contract that returns a zero-byte slice of len size 248 returnContract := func(size uint64) []byte { 249 contract := []byte{ 250 byte(vm.PUSH8), 0, 0, 0, 0, 0, 0, 0, 0, // PUSH8 0xXXXXXXXXXXXXXXXX 251 byte(vm.PUSH0), // PUSH0 252 byte(vm.RETURN), // RETURN 253 } 254 binary.BigEndian.PutUint64(contract[1:], size) 255 return contract 256 } 257 258 state, _ := state.New(types.EmptyRootHash, state.NewDatabaseForTesting()) 259 contractAddr := common.BytesToAddress([]byte("contract")) 260 261 for _, n := range []uint64{1_000, 10_000, 100_000, 1_000_000} { 262 b.Run(strconv.FormatUint(n, 10), func(b *testing.B) { 263 b.ReportAllocs() 264 265 contractCode := returnContract(n) 266 state.SetCode(contractAddr, contractCode) 267 268 for i := 0; i < b.N; i++ { 269 ret, _, err := Call(contractAddr, []byte{}, &Config{State: state}) 270 if err != nil { 271 b.Fatal(err) 272 } 273 if uint64(len(ret)) != n { 274 b.Fatalf("expected return size %d, got %d", n, len(ret)) 275 } 276 } 277 }) 278 } 279 } 280 281 func fakeHeader(n uint64, parentHash common.Hash) *types.Header { 282 header := types.Header{ 283 Coinbase: common.HexToAddress("0x00000000000000000000000000000000deadbeef"), 284 Number: big.NewInt(int64(n)), 285 ParentHash: parentHash, 286 Time: 1000, 287 Nonce: types.BlockNonce{0x1}, 288 Extra: []byte{}, 289 Difficulty: big.NewInt(0), 290 GasLimit: 100000, 291 } 292 return &header 293 } 294 295 type dummyChain struct { 296 counter int 297 } 298 299 // Engine retrieves the chain's consensus engine. 300 func (d *dummyChain) Engine() consensus.Engine { 301 return nil 302 } 303 304 // GetHeader returns the hash corresponding to their hash. 305 func (d *dummyChain) GetHeader(h common.Hash, n uint64) *types.Header { 306 d.counter++ 307 parentHash := common.Hash{} 308 s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32) 309 copy(parentHash[:], s) 310 311 //parentHash := common.Hash{byte(n - 1)} 312 //fmt.Printf("GetHeader(%x, %d) => header with parent %x\n", h, n, parentHash) 313 return fakeHeader(n, parentHash) 314 } 315 316 func (d *dummyChain) Config() *params.ChainConfig { 317 return nil 318 } 319 320 // TestBlockhash tests the blockhash operation. It's a bit special, since it internally 321 // requires access to a chain reader. 322 func TestBlockhash(t *testing.T) { 323 // Current head 324 n := uint64(1000) 325 parentHash := common.Hash{} 326 s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32) 327 copy(parentHash[:], s) 328 header := fakeHeader(n, parentHash) 329 330 // This is the contract we're using. It requests the blockhash for current num (should be all zeroes), 331 // then iteratively fetches all blockhashes back to n-260. 332 // It returns 333 // 1. the first (should be zero) 334 // 2. the second (should be the parent hash) 335 // 3. the last non-zero hash 336 // By making the chain reader return hashes which correlate to the number, we can 337 // verify that it obtained the right hashes where it should 338 339 /* 340 341 pragma solidity ^0.5.3; 342 contract Hasher{ 343 344 function test() public view returns (bytes32, bytes32, bytes32){ 345 uint256 x = block.number; 346 bytes32 first; 347 bytes32 last; 348 bytes32 zero; 349 zero = blockhash(x); // Should be zeroes 350 first = blockhash(x-1); 351 for(uint256 i = 2 ; i < 260; i++){ 352 bytes32 hash = blockhash(x - i); 353 if (uint256(hash) != 0){ 354 last = hash; 355 } 356 } 357 return (zero, first, last); 358 } 359 } 360 361 */ 362 // The contract above 363 data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029") 364 // The method call to 'test()' 365 input := common.Hex2Bytes("f8a8fd6d") 366 chain := &dummyChain{} 367 ret, _, err := Execute(data, input, &Config{ 368 GetHashFn: core.GetHashFn(header, chain), 369 BlockNumber: new(big.Int).Set(header.Number), 370 }) 371 if err != nil { 372 t.Fatalf("expected no error, got %v", err) 373 } 374 if len(ret) != 96 { 375 t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret)) 376 } 377 378 zero := new(big.Int).SetBytes(ret[0:32]) 379 first := new(big.Int).SetBytes(ret[32:64]) 380 last := new(big.Int).SetBytes(ret[64:96]) 381 if zero.BitLen() != 0 { 382 t.Fatalf("expected zeroes, got %x", ret[0:32]) 383 } 384 if first.Uint64() != 999 { 385 t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64]) 386 } 387 if last.Uint64() != 744 { 388 t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96]) 389 } 390 if exp, got := 255, chain.counter; exp != got { 391 t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got) 392 } 393 } 394 395 // benchmarkNonModifyingCode benchmarks code, but if the code modifies the 396 // state, this should not be used, since it does not reset the state between runs. 397 func benchmarkNonModifyingCode(gas uint64, code []byte, name string, tracerCode string, b *testing.B) { 398 cfg := new(Config) 399 setDefaults(cfg) 400 cfg.State, _ = state.New(types.EmptyRootHash, state.NewDatabaseForTesting()) 401 cfg.GasLimit = gas 402 if len(tracerCode) > 0 { 403 tracer, err := tracers.DefaultDirectory.New(tracerCode, new(tracers.Context), nil, cfg.ChainConfig) 404 if err != nil { 405 b.Fatal(err) 406 } 407 cfg.EVMConfig = vm.Config{ 408 Tracer: tracer.Hooks, 409 } 410 } 411 destination := common.BytesToAddress([]byte("contract")) 412 cfg.State.CreateAccount(destination) 413 eoa := common.HexToAddress("E0") 414 { 415 cfg.State.CreateAccount(eoa) 416 cfg.State.SetNonce(eoa, 100, tracing.NonceChangeUnspecified) 417 } 418 reverting := common.HexToAddress("EE") 419 { 420 cfg.State.CreateAccount(reverting) 421 cfg.State.SetCode(reverting, []byte{ 422 byte(vm.PUSH1), 0x00, 423 byte(vm.PUSH1), 0x00, 424 byte(vm.REVERT), 425 }) 426 } 427 428 //cfg.State.CreateAccount(cfg.Origin) 429 // set the receiver's (the executing contract) code for execution. 430 cfg.State.SetCode(destination, code) 431 Call(destination, nil, cfg) 432 433 b.Run(name, func(b *testing.B) { 434 b.ReportAllocs() 435 for i := 0; i < b.N; i++ { 436 Call(destination, nil, cfg) 437 } 438 }) 439 } 440 441 // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG 442 // 55 ms 443 func BenchmarkSimpleLoop(b *testing.B) { 444 p, lbl := program.New().Jumpdest() 445 // Call identity, and pop return value 446 staticCallIdentity := p. 447 StaticCall(nil, 0x4, 0, 0, 0, 0). 448 Op(vm.POP).Jump(lbl).Bytes() // pop return value and jump to label 449 450 p, lbl = program.New().Jumpdest() 451 callIdentity := p. 452 Call(nil, 0x4, 0, 0, 0, 0, 0). 453 Op(vm.POP).Jump(lbl).Bytes() // pop return value and jump to label 454 455 p, lbl = program.New().Jumpdest() 456 callInexistant := p. 457 Call(nil, 0xff, 0, 0, 0, 0, 0). 458 Op(vm.POP).Jump(lbl).Bytes() // pop return value and jump to label 459 460 p, lbl = program.New().Jumpdest() 461 callEOA := p. 462 Call(nil, 0xE0, 0, 0, 0, 0, 0). // call addr of EOA 463 Op(vm.POP).Jump(lbl).Bytes() // pop return value and jump to label 464 465 p, lbl = program.New().Jumpdest() 466 // Push as if we were making call, then pop it off again, and loop 467 loopingCode := p.Push(0). 468 Op(vm.DUP1, vm.DUP1, vm.DUP1). 469 Push(0x4). 470 Op(vm.GAS, vm.POP, vm.POP, vm.POP, vm.POP, vm.POP, vm.POP). 471 Jump(lbl).Bytes() 472 473 p, lbl = program.New().Jumpdest() 474 loopingCode2 := p. 475 Push(0x01020304).Push(uint64(0x0102030405)). 476 Op(vm.POP, vm.POP). 477 Op(vm.PUSH6).Append(make([]byte, 6)).Op(vm.JUMP). // Jumpdest zero expressed in 6 bytes 478 Jump(lbl).Bytes() 479 480 p, lbl = program.New().Jumpdest() 481 callRevertingContractWithInput := p. 482 Call(nil, 0xee, 0, 0, 0x20, 0x0, 0x0). 483 Op(vm.POP).Jump(lbl).Bytes() // pop return value and jump to label 484 485 //tracer := logger.NewJSONLogger(nil, os.Stdout) 486 //Execute(loopingCode, nil, &Config{ 487 // EVMConfig: vm.Config{ 488 // Debug: true, 489 // Tracer: tracer, 490 // }}) 491 // 100M gas 492 benchmarkNonModifyingCode(100000000, staticCallIdentity, "staticcall-identity-100M", "", b) 493 benchmarkNonModifyingCode(100000000, callIdentity, "call-identity-100M", "", b) 494 benchmarkNonModifyingCode(100000000, loopingCode, "loop-100M", "", b) 495 benchmarkNonModifyingCode(100000000, loopingCode2, "loop2-100M", "", b) 496 benchmarkNonModifyingCode(100000000, callInexistant, "call-nonexist-100M", "", b) 497 benchmarkNonModifyingCode(100000000, callEOA, "call-EOA-100M", "", b) 498 benchmarkNonModifyingCode(100000000, callRevertingContractWithInput, "call-reverting-100M", "", b) 499 500 //benchmarkNonModifyingCode(10000000, staticCallIdentity, "staticcall-identity-10M", b) 501 //benchmarkNonModifyingCode(10000000, loopingCode, "loop-10M", b) 502 } 503 504 // TestEip2929Cases contains various testcases that are used for 505 // EIP-2929 about gas repricings 506 func TestEip2929Cases(t *testing.T) { 507 t.Skip("Test only useful for generating documentation") 508 id := 1 509 prettyPrint := func(comment string, code []byte) { 510 fmt.Printf("### Case %d\n\n", id) 511 id++ 512 fmt.Printf("%v\n\nBytecode: \n```\n%#x\n```\n", comment, code) 513 Execute(code, nil, &Config{ 514 EVMConfig: vm.Config{ 515 Tracer: logger.NewMarkdownLogger(nil, os.Stdout).Hooks(), 516 ExtraEips: []int{2929}, 517 }, 518 }) 519 } 520 521 { // First eip testcase 522 code := []byte{ 523 // Three checks against a precompile 524 byte(vm.PUSH1), 1, byte(vm.EXTCODEHASH), byte(vm.POP), 525 byte(vm.PUSH1), 2, byte(vm.EXTCODESIZE), byte(vm.POP), 526 byte(vm.PUSH1), 3, byte(vm.BALANCE), byte(vm.POP), 527 // Three checks against a non-precompile 528 byte(vm.PUSH1), 0xf1, byte(vm.EXTCODEHASH), byte(vm.POP), 529 byte(vm.PUSH1), 0xf2, byte(vm.EXTCODESIZE), byte(vm.POP), 530 byte(vm.PUSH1), 0xf3, byte(vm.BALANCE), byte(vm.POP), 531 // Same three checks (should be cheaper) 532 byte(vm.PUSH1), 0xf2, byte(vm.EXTCODEHASH), byte(vm.POP), 533 byte(vm.PUSH1), 0xf3, byte(vm.EXTCODESIZE), byte(vm.POP), 534 byte(vm.PUSH1), 0xf1, byte(vm.BALANCE), byte(vm.POP), 535 // Check the origin, and the 'this' 536 byte(vm.ORIGIN), byte(vm.BALANCE), byte(vm.POP), 537 byte(vm.ADDRESS), byte(vm.BALANCE), byte(vm.POP), 538 539 byte(vm.STOP), 540 } 541 prettyPrint("This checks `EXT`(codehash,codesize,balance) of precompiles, which should be `100`, "+ 542 "and later checks the same operations twice against some non-precompiles. "+ 543 "Those are cheaper second time they are accessed. Lastly, it checks the `BALANCE` of `origin` and `this`.", code) 544 } 545 546 { // EXTCODECOPY 547 code := []byte{ 548 // extcodecopy( 0xff,0,0,0,0) 549 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 550 byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY), 551 // extcodecopy( 0xff,0,0,0,0) 552 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 553 byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY), 554 // extcodecopy( this,0,0,0,0) 555 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 556 byte(vm.ADDRESS), byte(vm.EXTCODECOPY), 557 558 byte(vm.STOP), 559 } 560 prettyPrint("This checks `extcodecopy( 0xff,0,0,0,0)` twice, (should be expensive first time), "+ 561 "and then does `extcodecopy( this,0,0,0,0)`.", code) 562 } 563 564 { // SLOAD + SSTORE 565 code := []byte{ 566 567 // Add slot `0x1` to access list 568 byte(vm.PUSH1), 0x01, byte(vm.SLOAD), byte(vm.POP), // SLOAD( 0x1) (add to access list) 569 // Write to `0x1` which is already in access list 570 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x01, byte(vm.SSTORE), // SSTORE( loc: 0x01, val: 0x11) 571 // Write to `0x2` which is not in access list 572 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11) 573 // Write again to `0x2` 574 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11) 575 // Read slot in access list (0x2) 576 byte(vm.PUSH1), 0x02, byte(vm.SLOAD), // SLOAD( 0x2) 577 // Read slot in access list (0x1) 578 byte(vm.PUSH1), 0x01, byte(vm.SLOAD), // SLOAD( 0x1) 579 } 580 prettyPrint("This checks `sload( 0x1)` followed by `sstore(loc: 0x01, val:0x11)`, then 'naked' sstore:"+ 581 "`sstore(loc: 0x02, val:0x11)` twice, and `sload(0x2)`, `sload(0x1)`. ", code) 582 } 583 { // Call variants 584 code := []byte{ 585 // identity precompile 586 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 587 byte(vm.PUSH1), 0x04, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP), 588 589 // random account - call 1 590 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 591 byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP), 592 593 // random account - call 2 594 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 595 byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.STATICCALL), byte(vm.POP), 596 } 597 prettyPrint("This calls the `identity`-precompile (cheap), then calls an account (expensive) and `staticcall`s the same"+ 598 "account (cheap)", code) 599 } 600 } 601 602 // TestColdAccountAccessCost test that the cold account access cost is reported 603 // correctly 604 // see: https://github.com/ethereum/go-ethereum/issues/22649 605 func TestColdAccountAccessCost(t *testing.T) { 606 for i, tc := range []struct { 607 code []byte 608 step int 609 want uint64 610 }{ 611 { // EXTCODEHASH(0xff) 612 code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.EXTCODEHASH), byte(vm.POP)}, 613 step: 1, 614 want: 2600, 615 }, 616 { // BALANCE(0xff) 617 code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.BALANCE), byte(vm.POP)}, 618 step: 1, 619 want: 2600, 620 }, 621 { // CALL(0xff) 622 code: []byte{ 623 byte(vm.PUSH1), 0x0, 624 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 625 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALL), byte(vm.POP), 626 }, 627 step: 7, 628 want: 2855, 629 }, 630 { // CALLCODE(0xff) 631 code: []byte{ 632 byte(vm.PUSH1), 0x0, 633 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 634 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALLCODE), byte(vm.POP), 635 }, 636 step: 7, 637 want: 2855, 638 }, 639 { // DELEGATECALL(0xff) 640 code: []byte{ 641 byte(vm.PUSH1), 0x0, 642 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 643 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.DELEGATECALL), byte(vm.POP), 644 }, 645 step: 6, 646 want: 2855, 647 }, 648 { // STATICCALL(0xff) 649 code: []byte{ 650 byte(vm.PUSH1), 0x0, 651 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 652 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.STATICCALL), byte(vm.POP), 653 }, 654 step: 6, 655 want: 2855, 656 }, 657 { // SELFDESTRUCT(0xff) 658 code: []byte{ 659 byte(vm.PUSH1), 0xff, byte(vm.SELFDESTRUCT), 660 }, 661 step: 1, 662 want: 7600, 663 }, 664 } { 665 var step = 0 666 var have = uint64(0) 667 Execute(tc.code, nil, &Config{ 668 EVMConfig: vm.Config{ 669 Tracer: &tracing.Hooks{ 670 OnOpcode: func(pc uint64, op byte, gas, cost uint64, scope tracing.OpContext, rData []byte, depth int, err error) { 671 // Uncomment to investigate failures: 672 //t.Logf("%d: %v %d", step, vm.OpCode(op).String(), cost) 673 if step == tc.step { 674 have = cost 675 } 676 step++ 677 }, 678 }, 679 }, 680 }) 681 if want := tc.want; have != want { 682 t.Fatalf("testcase %d, gas report wrong, step %d, have %d want %d", i, tc.step, have, want) 683 } 684 } 685 } 686 687 func TestRuntimeJSTracer(t *testing.T) { 688 jsTracers := []string{ 689 `{enters: 0, exits: 0, enterGas: 0, gasUsed: 0, steps:0, 690 step: function() { this.steps++}, 691 fault: function() {}, 692 result: function() { 693 return [this.enters, this.exits,this.enterGas,this.gasUsed, this.steps].join(",") 694 }, 695 enter: function(frame) { 696 this.enters++; 697 this.enterGas = frame.getGas(); 698 }, 699 exit: function(res) { 700 this.exits++; 701 this.gasUsed = res.getGasUsed(); 702 }}`, 703 `{enters: 0, exits: 0, enterGas: 0, gasUsed: 0, steps:0, 704 fault: function() {}, 705 result: function() { 706 return [this.enters, this.exits,this.enterGas,this.gasUsed, this.steps].join(",") 707 }, 708 enter: function(frame) { 709 this.enters++; 710 this.enterGas = frame.getGas(); 711 }, 712 exit: function(res) { 713 this.exits++; 714 this.gasUsed = res.getGasUsed(); 715 }}`} 716 initcode := program.New().Return(0, 0).Bytes() 717 tests := []struct { 718 code []byte 719 // One result per tracer 720 results []string 721 }{ 722 { // CREATE 723 code: program.New().MstoreSmall(initcode, 0). 724 Push(len(initcode)). // length 725 Push(32 - len(initcode)). // offset 726 Push(0). // value 727 Op(vm.CREATE). 728 Op(vm.POP).Bytes(), 729 results: []string{`"1,1,952853,6,12"`, `"1,1,952853,6,0"`}, 730 }, 731 { // CREATE2 732 code: program.New().MstoreSmall(initcode, 0). 733 Push(1). // salt 734 Push(len(initcode)). // length 735 Push(32 - len(initcode)). // offset 736 Push(0). // value 737 Op(vm.CREATE2). 738 Op(vm.POP).Bytes(), 739 results: []string{`"1,1,952844,6,13"`, `"1,1,952844,6,0"`}, 740 }, 741 { // CALL 742 code: program.New().Call(nil, 0xbb, 0, 0, 0, 0, 0).Op(vm.POP).Bytes(), 743 results: []string{`"1,1,981796,6,13"`, `"1,1,981796,6,0"`}, 744 }, 745 { // CALLCODE 746 code: program.New().CallCode(nil, 0xcc, 0, 0, 0, 0, 0).Op(vm.POP).Bytes(), 747 results: []string{`"1,1,981796,6,13"`, `"1,1,981796,6,0"`}, 748 }, 749 { // STATICCALL 750 code: program.New().StaticCall(nil, 0xdd, 0, 0, 0, 0).Op(vm.POP).Bytes(), 751 results: []string{`"1,1,981799,6,12"`, `"1,1,981799,6,0"`}, 752 }, 753 { // DELEGATECALL 754 code: program.New().DelegateCall(nil, 0xee, 0, 0, 0, 0).Op(vm.POP).Bytes(), 755 results: []string{`"1,1,981799,6,12"`, `"1,1,981799,6,0"`}, 756 }, 757 { // CALL self-destructing contract 758 code: program.New().Call(nil, 0xff, 0, 0, 0, 0, 0).Op(vm.POP).Bytes(), 759 results: []string{`"2,2,0,5003,12"`, `"2,2,0,5003,0"`}, 760 }, 761 } 762 calleeCode := []byte{ 763 byte(vm.PUSH1), 0, 764 byte(vm.PUSH1), 0, 765 byte(vm.RETURN), 766 } 767 suicideCode := []byte{ 768 byte(vm.PUSH1), 0xaa, 769 byte(vm.SELFDESTRUCT), 770 } 771 main := common.HexToAddress("0xaa") 772 for i, jsTracer := range jsTracers { 773 for j, tc := range tests { 774 statedb, _ := state.New(types.EmptyRootHash, state.NewDatabaseForTesting()) 775 statedb.SetCode(main, tc.code) 776 statedb.SetCode(common.HexToAddress("0xbb"), calleeCode) 777 statedb.SetCode(common.HexToAddress("0xcc"), calleeCode) 778 statedb.SetCode(common.HexToAddress("0xdd"), calleeCode) 779 statedb.SetCode(common.HexToAddress("0xee"), calleeCode) 780 statedb.SetCode(common.HexToAddress("0xff"), suicideCode) 781 782 tracer, err := tracers.DefaultDirectory.New(jsTracer, new(tracers.Context), nil, params.MergedTestChainConfig) 783 if err != nil { 784 t.Fatal(err) 785 } 786 _, _, err = Call(main, nil, &Config{ 787 GasLimit: 1000000, 788 State: statedb, 789 EVMConfig: vm.Config{ 790 Tracer: tracer.Hooks, 791 }}) 792 if err != nil { 793 t.Fatal("didn't expect error", err) 794 } 795 res, err := tracer.GetResult() 796 if err != nil { 797 t.Fatal(err) 798 } 799 if have, want := string(res), tc.results[i]; have != want { 800 t.Errorf("wrong result for tracer %d testcase %d, have \n%v\nwant\n%v\n", i, j, have, want) 801 } 802 } 803 } 804 } 805 806 func TestJSTracerCreateTx(t *testing.T) { 807 jsTracer := ` 808 {enters: 0, exits: 0, 809 step: function() {}, 810 fault: function() {}, 811 result: function() { return [this.enters, this.exits].join(",") }, 812 enter: function(frame) { this.enters++ }, 813 exit: function(res) { this.exits++ }}` 814 code := []byte{byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN)} 815 816 statedb, _ := state.New(types.EmptyRootHash, state.NewDatabaseForTesting()) 817 tracer, err := tracers.DefaultDirectory.New(jsTracer, new(tracers.Context), nil, params.MergedTestChainConfig) 818 if err != nil { 819 t.Fatal(err) 820 } 821 _, _, _, err = Create(code, &Config{ 822 State: statedb, 823 EVMConfig: vm.Config{ 824 Tracer: tracer.Hooks, 825 }}) 826 if err != nil { 827 t.Fatal(err) 828 } 829 830 res, err := tracer.GetResult() 831 if err != nil { 832 t.Fatal(err) 833 } 834 if have, want := string(res), `"0,0"`; have != want { 835 t.Errorf("wrong result for tracer, have \n%v\nwant\n%v\n", have, want) 836 } 837 } 838 839 func BenchmarkTracerStepVsCallFrame(b *testing.B) { 840 // Simply pushes and pops some values in a loop 841 p, lbl := program.New().Jumpdest() 842 code := p.Push(0).Push(0).Op(vm.POP, vm.POP).Jump(lbl).Bytes() 843 stepTracer := ` 844 { 845 step: function() {}, 846 fault: function() {}, 847 result: function() {}, 848 }` 849 callFrameTracer := ` 850 { 851 enter: function() {}, 852 exit: function() {}, 853 fault: function() {}, 854 result: function() {}, 855 }` 856 857 benchmarkNonModifyingCode(10000000, code, "tracer-step-10M", stepTracer, b) 858 benchmarkNonModifyingCode(10000000, code, "tracer-call-frame-10M", callFrameTracer, b) 859 } 860 861 // TestDelegatedAccountAccessCost tests that calling an account with an EIP-7702 862 // delegation designator incurs the correct amount of gas based on the tracer. 863 func TestDelegatedAccountAccessCost(t *testing.T) { 864 statedb, _ := state.New(types.EmptyRootHash, state.NewDatabaseForTesting()) 865 statedb.SetCode(common.HexToAddress("0xff"), types.AddressToDelegation(common.HexToAddress("0xaa"))) 866 statedb.SetCode(common.HexToAddress("0xaa"), program.New().Return(0, 0).Bytes()) 867 868 for i, tc := range []struct { 869 code []byte 870 step int 871 want uint64 872 }{ 873 { // CALL(0xff) 874 code: []byte{ 875 byte(vm.PUSH1), 0x0, 876 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 877 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALL), byte(vm.POP), 878 }, 879 step: 7, 880 want: 5455, 881 }, 882 { // CALLCODE(0xff) 883 code: []byte{ 884 byte(vm.PUSH1), 0x0, 885 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 886 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALLCODE), byte(vm.POP), 887 }, 888 step: 7, 889 want: 5455, 890 }, 891 { // DELEGATECALL(0xff) 892 code: []byte{ 893 byte(vm.PUSH1), 0x0, 894 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 895 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.DELEGATECALL), byte(vm.POP), 896 }, 897 step: 6, 898 want: 5455, 899 }, 900 { // STATICCALL(0xff) 901 code: []byte{ 902 byte(vm.PUSH1), 0x0, 903 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 904 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.STATICCALL), byte(vm.POP), 905 }, 906 step: 6, 907 want: 5455, 908 }, 909 { // SELFDESTRUCT(0xff): should not be affected by resolution 910 code: []byte{ 911 byte(vm.PUSH1), 0xff, byte(vm.SELFDESTRUCT), 912 }, 913 step: 1, 914 want: 7600, 915 }, 916 } { 917 var step = 0 918 var have = uint64(0) 919 Execute(tc.code, nil, &Config{ 920 ChainConfig: params.MergedTestChainConfig, 921 State: statedb, 922 EVMConfig: vm.Config{ 923 Tracer: &tracing.Hooks{ 924 OnOpcode: func(pc uint64, op byte, gas, cost uint64, scope tracing.OpContext, rData []byte, depth int, err error) { 925 // Uncomment to investigate failures: 926 t.Logf("%d: %v %d", step, vm.OpCode(op).String(), cost) 927 if step == tc.step { 928 have = cost 929 } 930 step++ 931 }, 932 }, 933 }, 934 }) 935 if want := tc.want; have != want { 936 t.Fatalf("testcase %d, gas report wrong, step %d, have %d want %d", i, tc.step, have, want) 937 } 938 } 939 }