github.com/snowblossomcoin/go-ethereum@v1.9.25/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 "fmt" 21 "math/big" 22 "os" 23 "strings" 24 "testing" 25 "time" 26 27 "github.com/ethereum/go-ethereum/accounts/abi" 28 "github.com/ethereum/go-ethereum/common" 29 "github.com/ethereum/go-ethereum/consensus" 30 "github.com/ethereum/go-ethereum/core" 31 "github.com/ethereum/go-ethereum/core/asm" 32 "github.com/ethereum/go-ethereum/core/rawdb" 33 "github.com/ethereum/go-ethereum/core/state" 34 "github.com/ethereum/go-ethereum/core/types" 35 "github.com/ethereum/go-ethereum/core/vm" 36 "github.com/ethereum/go-ethereum/params" 37 ) 38 39 func TestDefaults(t *testing.T) { 40 cfg := new(Config) 41 setDefaults(cfg) 42 43 if cfg.Difficulty == nil { 44 t.Error("expected difficulty to be non nil") 45 } 46 47 if cfg.Time == nil { 48 t.Error("expected time to be non nil") 49 } 50 if cfg.GasLimit == 0 { 51 t.Error("didn't expect gaslimit to be zero") 52 } 53 if cfg.GasPrice == nil { 54 t.Error("expected time to be non nil") 55 } 56 if cfg.Value == nil { 57 t.Error("expected time to be non nil") 58 } 59 if cfg.GetHashFn == nil { 60 t.Error("expected time to be non nil") 61 } 62 if cfg.BlockNumber == nil { 63 t.Error("expected block number to be non nil") 64 } 65 } 66 67 func TestEVM(t *testing.T) { 68 defer func() { 69 if r := recover(); r != nil { 70 t.Fatalf("crashed with: %v", r) 71 } 72 }() 73 74 Execute([]byte{ 75 byte(vm.DIFFICULTY), 76 byte(vm.TIMESTAMP), 77 byte(vm.GASLIMIT), 78 byte(vm.PUSH1), 79 byte(vm.ORIGIN), 80 byte(vm.BLOCKHASH), 81 byte(vm.COINBASE), 82 }, nil, nil) 83 } 84 85 func TestExecute(t *testing.T) { 86 ret, _, err := Execute([]byte{ 87 byte(vm.PUSH1), 10, 88 byte(vm.PUSH1), 0, 89 byte(vm.MSTORE), 90 byte(vm.PUSH1), 32, 91 byte(vm.PUSH1), 0, 92 byte(vm.RETURN), 93 }, nil, nil) 94 if err != nil { 95 t.Fatal("didn't expect error", err) 96 } 97 98 num := new(big.Int).SetBytes(ret) 99 if num.Cmp(big.NewInt(10)) != 0 { 100 t.Error("Expected 10, got", num) 101 } 102 } 103 104 func TestCall(t *testing.T) { 105 state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 106 address := common.HexToAddress("0x0a") 107 state.SetCode(address, []byte{ 108 byte(vm.PUSH1), 10, 109 byte(vm.PUSH1), 0, 110 byte(vm.MSTORE), 111 byte(vm.PUSH1), 32, 112 byte(vm.PUSH1), 0, 113 byte(vm.RETURN), 114 }) 115 116 ret, _, err := Call(address, nil, &Config{State: state}) 117 if err != nil { 118 t.Fatal("didn't expect error", err) 119 } 120 121 num := new(big.Int).SetBytes(ret) 122 if num.Cmp(big.NewInt(10)) != 0 { 123 t.Error("Expected 10, got", num) 124 } 125 } 126 127 func BenchmarkCall(b *testing.B) { 128 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"}]` 129 130 var code = common.Hex2Bytes("6060604052361561006c5760e060020a600035046308551a53811461007457806335a063b4146100865780633fa4f245146100a6578063590e1ae3146100af5780637150d8ae146100cf57806373fac6f0146100e1578063c19d93fb146100fe578063d696069714610112575b610131610002565b610133600154600160a060020a031681565b610131600154600160a060020a0390811633919091161461015057610002565b61014660005481565b610131600154600160a060020a039081163391909116146102d557610002565b610133600254600160a060020a031681565b610131600254600160a060020a0333811691161461023757610002565b61014660025460ff60a060020a9091041681565b61013160025460009060ff60a060020a9091041681146101cc57610002565b005b600160a060020a03166060908152602090f35b6060908152602090f35b60025460009060a060020a900460ff16811461016b57610002565b600154600160a060020a03908116908290301631606082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f72c874aeff0b183a56e2b79c71b46e1aed4dee5e09862134b8821ba2fddbf8bf9250a150565b80546002023414806101dd57610002565b6002805460a060020a60ff021973ffffffffffffffffffffffffffffffffffffffff1990911633171660a060020a1790557fd5d55c8a68912e9a110618df8d5e2e83b8d83211c57a8ddd1203df92885dc881826060a15050565b60025460019060a060020a900460ff16811461025257610002565b60025460008054600160a060020a0390921691606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517fe89152acd703c9d8c7d28829d443260b411454d45394e7995815140c8cbcbcf79250a150565b60025460019060a060020a900460ff1681146102f057610002565b6002805460008054600160a060020a0390921692909102606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f8616bbbbad963e4e65b1366f1d75dfb63f9e9704bbbf91fb01bec70849906cf79250a15056") 131 132 abi, err := abi.JSON(strings.NewReader(definition)) 133 if err != nil { 134 b.Fatal(err) 135 } 136 137 cpurchase, err := abi.Pack("confirmPurchase") 138 if err != nil { 139 b.Fatal(err) 140 } 141 creceived, err := abi.Pack("confirmReceived") 142 if err != nil { 143 b.Fatal(err) 144 } 145 refund, err := abi.Pack("refund") 146 if err != nil { 147 b.Fatal(err) 148 } 149 150 b.ResetTimer() 151 for i := 0; i < b.N; i++ { 152 for j := 0; j < 400; j++ { 153 Execute(code, cpurchase, nil) 154 Execute(code, creceived, nil) 155 Execute(code, refund, nil) 156 } 157 } 158 } 159 func benchmarkEVM_Create(bench *testing.B, code string) { 160 var ( 161 statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 162 sender = common.BytesToAddress([]byte("sender")) 163 receiver = common.BytesToAddress([]byte("receiver")) 164 ) 165 166 statedb.CreateAccount(sender) 167 statedb.SetCode(receiver, common.FromHex(code)) 168 runtimeConfig := Config{ 169 Origin: sender, 170 State: statedb, 171 GasLimit: 10000000, 172 Difficulty: big.NewInt(0x200000), 173 Time: new(big.Int).SetUint64(0), 174 Coinbase: common.Address{}, 175 BlockNumber: new(big.Int).SetUint64(1), 176 ChainConfig: ¶ms.ChainConfig{ 177 ChainID: big.NewInt(1), 178 HomesteadBlock: new(big.Int), 179 ByzantiumBlock: new(big.Int), 180 ConstantinopleBlock: new(big.Int), 181 DAOForkBlock: new(big.Int), 182 DAOForkSupport: false, 183 EIP150Block: new(big.Int), 184 EIP155Block: new(big.Int), 185 EIP158Block: new(big.Int), 186 }, 187 EVMConfig: vm.Config{}, 188 } 189 // Warm up the intpools and stuff 190 bench.ResetTimer() 191 for i := 0; i < bench.N; i++ { 192 Call(receiver, []byte{}, &runtimeConfig) 193 } 194 bench.StopTimer() 195 } 196 197 func BenchmarkEVM_CREATE_500(bench *testing.B) { 198 // initcode size 500K, repeatedly calls CREATE and then modifies the mem contents 199 benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056") 200 } 201 func BenchmarkEVM_CREATE2_500(bench *testing.B) { 202 // initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents 203 benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056") 204 } 205 func BenchmarkEVM_CREATE_1200(bench *testing.B) { 206 // initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents 207 benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056") 208 } 209 func BenchmarkEVM_CREATE2_1200(bench *testing.B) { 210 // initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents 211 benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056") 212 } 213 214 func fakeHeader(n uint64, parentHash common.Hash) *types.Header { 215 header := types.Header{ 216 Coinbase: common.HexToAddress("0x00000000000000000000000000000000deadbeef"), 217 Number: big.NewInt(int64(n)), 218 ParentHash: parentHash, 219 Time: 1000, 220 Nonce: types.BlockNonce{0x1}, 221 Extra: []byte{}, 222 Difficulty: big.NewInt(0), 223 GasLimit: 100000, 224 } 225 return &header 226 } 227 228 type dummyChain struct { 229 counter int 230 } 231 232 // Engine retrieves the chain's consensus engine. 233 func (d *dummyChain) Engine() consensus.Engine { 234 return nil 235 } 236 237 // GetHeader returns the hash corresponding to their hash. 238 func (d *dummyChain) GetHeader(h common.Hash, n uint64) *types.Header { 239 d.counter++ 240 parentHash := common.Hash{} 241 s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32) 242 copy(parentHash[:], s) 243 244 //parentHash := common.Hash{byte(n - 1)} 245 //fmt.Printf("GetHeader(%x, %d) => header with parent %x\n", h, n, parentHash) 246 return fakeHeader(n, parentHash) 247 } 248 249 // TestBlockhash tests the blockhash operation. It's a bit special, since it internally 250 // requires access to a chain reader. 251 func TestBlockhash(t *testing.T) { 252 // Current head 253 n := uint64(1000) 254 parentHash := common.Hash{} 255 s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32) 256 copy(parentHash[:], s) 257 header := fakeHeader(n, parentHash) 258 259 // This is the contract we're using. It requests the blockhash for current num (should be all zeroes), 260 // then iteratively fetches all blockhashes back to n-260. 261 // It returns 262 // 1. the first (should be zero) 263 // 2. the second (should be the parent hash) 264 // 3. the last non-zero hash 265 // By making the chain reader return hashes which correlate to the number, we can 266 // verify that it obtained the right hashes where it should 267 268 /* 269 270 pragma solidity ^0.5.3; 271 contract Hasher{ 272 273 function test() public view returns (bytes32, bytes32, bytes32){ 274 uint256 x = block.number; 275 bytes32 first; 276 bytes32 last; 277 bytes32 zero; 278 zero = blockhash(x); // Should be zeroes 279 first = blockhash(x-1); 280 for(uint256 i = 2 ; i < 260; i++){ 281 bytes32 hash = blockhash(x - i); 282 if (uint256(hash) != 0){ 283 last = hash; 284 } 285 } 286 return (zero, first, last); 287 } 288 } 289 290 */ 291 // The contract above 292 data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029") 293 // The method call to 'test()' 294 input := common.Hex2Bytes("f8a8fd6d") 295 chain := &dummyChain{} 296 ret, _, err := Execute(data, input, &Config{ 297 GetHashFn: core.GetHashFn(header, chain), 298 BlockNumber: new(big.Int).Set(header.Number), 299 }) 300 if err != nil { 301 t.Fatalf("expected no error, got %v", err) 302 } 303 if len(ret) != 96 { 304 t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret)) 305 } 306 307 zero := new(big.Int).SetBytes(ret[0:32]) 308 first := new(big.Int).SetBytes(ret[32:64]) 309 last := new(big.Int).SetBytes(ret[64:96]) 310 if zero.BitLen() != 0 { 311 t.Fatalf("expected zeroes, got %x", ret[0:32]) 312 } 313 if first.Uint64() != 999 { 314 t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64]) 315 } 316 if last.Uint64() != 744 { 317 t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96]) 318 } 319 if exp, got := 255, chain.counter; exp != got { 320 t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got) 321 } 322 } 323 324 type stepCounter struct { 325 inner *vm.JSONLogger 326 steps int 327 } 328 329 func (s *stepCounter) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error { 330 return nil 331 } 332 333 func (s *stepCounter) CaptureState(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, rStack *vm.ReturnStack, rData []byte, contract *vm.Contract, depth int, err error) error { 334 s.steps++ 335 // Enable this for more output 336 //s.inner.CaptureState(env, pc, op, gas, cost, memory, stack, rStack, contract, depth, err) 337 return nil 338 } 339 340 func (s *stepCounter) CaptureFault(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, rStack *vm.ReturnStack, contract *vm.Contract, depth int, err error) error { 341 return nil 342 } 343 344 func (s *stepCounter) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error { 345 return nil 346 } 347 348 func TestJumpSub1024Limit(t *testing.T) { 349 state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 350 address := common.HexToAddress("0x0a") 351 // Code is 352 // 0 beginsub 353 // 1 push 0 354 // 3 jumpsub 355 // 356 // The code recursively calls itself. It should error when the returns-stack 357 // grows above 1023 358 state.SetCode(address, []byte{ 359 byte(vm.PUSH1), 3, 360 byte(vm.JUMPSUB), 361 byte(vm.BEGINSUB), 362 byte(vm.PUSH1), 3, 363 byte(vm.JUMPSUB), 364 }) 365 tracer := stepCounter{inner: vm.NewJSONLogger(nil, os.Stdout)} 366 // Enable 2315 367 _, _, err := Call(address, nil, &Config{State: state, 368 GasLimit: 20000, 369 ChainConfig: params.AllEthashProtocolChanges, 370 EVMConfig: vm.Config{ 371 ExtraEips: []int{2315}, 372 Debug: true, 373 //Tracer: vm.NewJSONLogger(nil, os.Stdout), 374 Tracer: &tracer, 375 }}) 376 exp := "return stack limit reached" 377 if err.Error() != exp { 378 t.Fatalf("expected %v, got %v", exp, err) 379 } 380 if exp, got := 2048, tracer.steps; exp != got { 381 t.Fatalf("expected %d steps, got %d", exp, got) 382 } 383 } 384 385 func TestReturnSubShallow(t *testing.T) { 386 state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 387 address := common.HexToAddress("0x0a") 388 // The code does returnsub without having anything on the returnstack. 389 // It should not panic, but just fail after one step 390 state.SetCode(address, []byte{ 391 byte(vm.PUSH1), 5, 392 byte(vm.JUMPSUB), 393 byte(vm.RETURNSUB), 394 byte(vm.PC), 395 byte(vm.BEGINSUB), 396 byte(vm.RETURNSUB), 397 byte(vm.PC), 398 }) 399 tracer := stepCounter{} 400 401 // Enable 2315 402 _, _, err := Call(address, nil, &Config{State: state, 403 GasLimit: 10000, 404 ChainConfig: params.AllEthashProtocolChanges, 405 EVMConfig: vm.Config{ 406 ExtraEips: []int{2315}, 407 Debug: true, 408 Tracer: &tracer, 409 }}) 410 411 exp := "invalid retsub" 412 if err.Error() != exp { 413 t.Fatalf("expected %v, got %v", exp, err) 414 } 415 if exp, got := 4, tracer.steps; exp != got { 416 t.Fatalf("expected %d steps, got %d", exp, got) 417 } 418 } 419 420 // disabled -- only used for generating markdown 421 func DisabledTestReturnCases(t *testing.T) { 422 cfg := &Config{ 423 EVMConfig: vm.Config{ 424 Debug: true, 425 Tracer: vm.NewMarkdownLogger(nil, os.Stdout), 426 ExtraEips: []int{2315}, 427 }, 428 } 429 // This should fail at first opcode 430 Execute([]byte{ 431 byte(vm.RETURNSUB), 432 byte(vm.PC), 433 byte(vm.PC), 434 }, nil, cfg) 435 436 // Should also fail 437 Execute([]byte{ 438 byte(vm.PUSH1), 5, 439 byte(vm.JUMPSUB), 440 byte(vm.RETURNSUB), 441 byte(vm.PC), 442 byte(vm.BEGINSUB), 443 byte(vm.RETURNSUB), 444 byte(vm.PC), 445 }, nil, cfg) 446 447 // This should complete 448 Execute([]byte{ 449 byte(vm.PUSH1), 0x4, 450 byte(vm.JUMPSUB), 451 byte(vm.STOP), 452 byte(vm.BEGINSUB), 453 byte(vm.PUSH1), 0x9, 454 byte(vm.JUMPSUB), 455 byte(vm.RETURNSUB), 456 byte(vm.BEGINSUB), 457 byte(vm.RETURNSUB), 458 }, nil, cfg) 459 } 460 461 // DisabledTestEipExampleCases contains various testcases that are used for the 462 // EIP examples 463 // This test is disabled, as it's only used for generating markdown 464 func DisabledTestEipExampleCases(t *testing.T) { 465 cfg := &Config{ 466 EVMConfig: vm.Config{ 467 Debug: true, 468 Tracer: vm.NewMarkdownLogger(nil, os.Stdout), 469 ExtraEips: []int{2315}, 470 }, 471 } 472 prettyPrint := func(comment string, code []byte) { 473 instrs := make([]string, 0) 474 it := asm.NewInstructionIterator(code) 475 for it.Next() { 476 if it.Arg() != nil && 0 < len(it.Arg()) { 477 instrs = append(instrs, fmt.Sprintf("%v 0x%x", it.Op(), it.Arg())) 478 } else { 479 instrs = append(instrs, fmt.Sprintf("%v", it.Op())) 480 } 481 } 482 ops := strings.Join(instrs, ", ") 483 484 fmt.Printf("%v\nBytecode: `0x%x` (`%v`)\n", 485 comment, 486 code, ops) 487 Execute(code, nil, cfg) 488 } 489 490 { // First eip testcase 491 code := []byte{ 492 byte(vm.PUSH1), 4, 493 byte(vm.JUMPSUB), 494 byte(vm.STOP), 495 byte(vm.BEGINSUB), 496 byte(vm.RETURNSUB), 497 } 498 prettyPrint("This should jump into a subroutine, back out and stop.", code) 499 } 500 501 { 502 code := []byte{ 503 byte(vm.PUSH9), 0x00, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, (4 + 8), 504 byte(vm.JUMPSUB), 505 byte(vm.STOP), 506 byte(vm.BEGINSUB), 507 byte(vm.PUSH1), 8 + 9, 508 byte(vm.JUMPSUB), 509 byte(vm.RETURNSUB), 510 byte(vm.BEGINSUB), 511 byte(vm.RETURNSUB), 512 } 513 prettyPrint("This should execute fine, going into one two depths of subroutines", code) 514 } 515 // TODO(@holiman) move this test into an actual test, which not only prints 516 // out the trace. 517 { 518 code := []byte{ 519 byte(vm.PUSH9), 0x01, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, (4 + 8), 520 byte(vm.JUMPSUB), 521 byte(vm.STOP), 522 byte(vm.BEGINSUB), 523 byte(vm.PUSH1), 8 + 9, 524 byte(vm.JUMPSUB), 525 byte(vm.RETURNSUB), 526 byte(vm.BEGINSUB), 527 byte(vm.RETURNSUB), 528 } 529 prettyPrint("This should fail, since the given location is outside of the "+ 530 "code-range. The code is the same as previous example, except that the "+ 531 "pushed location is `0x01000000000000000c` instead of `0x0c`.", code) 532 } 533 { 534 // This should fail at first opcode 535 code := []byte{ 536 byte(vm.RETURNSUB), 537 byte(vm.PC), 538 byte(vm.PC), 539 } 540 prettyPrint("This should fail at first opcode, due to shallow `return_stack`", code) 541 542 } 543 { 544 code := []byte{ 545 byte(vm.PUSH1), 5, // Jump past the subroutine 546 byte(vm.JUMP), 547 byte(vm.BEGINSUB), 548 byte(vm.RETURNSUB), 549 byte(vm.JUMPDEST), 550 byte(vm.PUSH1), 3, // Now invoke the subroutine 551 byte(vm.JUMPSUB), 552 } 553 prettyPrint("In this example. the JUMPSUB is on the last byte of code. When the "+ 554 "subroutine returns, it should hit the 'virtual stop' _after_ the bytecode, "+ 555 "and not exit with error", code) 556 } 557 558 { 559 code := []byte{ 560 byte(vm.BEGINSUB), 561 byte(vm.RETURNSUB), 562 byte(vm.STOP), 563 } 564 prettyPrint("In this example, the code 'walks' into a subroutine, which is not "+ 565 "allowed, and causes an error", code) 566 } 567 } 568 569 // benchmarkNonModifyingCode benchmarks code, but if the code modifies the 570 // state, this should not be used, since it does not reset the state between runs. 571 func benchmarkNonModifyingCode(gas uint64, code []byte, name string, b *testing.B) { 572 cfg := new(Config) 573 setDefaults(cfg) 574 cfg.State, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 575 cfg.GasLimit = gas 576 var ( 577 destination = common.BytesToAddress([]byte("contract")) 578 vmenv = NewEnv(cfg) 579 sender = vm.AccountRef(cfg.Origin) 580 ) 581 cfg.State.CreateAccount(destination) 582 eoa := common.HexToAddress("E0") 583 { 584 cfg.State.CreateAccount(eoa) 585 cfg.State.SetNonce(eoa, 100) 586 } 587 reverting := common.HexToAddress("EE") 588 { 589 cfg.State.CreateAccount(reverting) 590 cfg.State.SetCode(reverting, []byte{ 591 byte(vm.PUSH1), 0x00, 592 byte(vm.PUSH1), 0x00, 593 byte(vm.REVERT), 594 }) 595 } 596 597 //cfg.State.CreateAccount(cfg.Origin) 598 // set the receiver's (the executing contract) code for execution. 599 cfg.State.SetCode(destination, code) 600 vmenv.Call(sender, destination, nil, gas, cfg.Value) 601 602 b.Run(name, func(b *testing.B) { 603 b.ReportAllocs() 604 for i := 0; i < b.N; i++ { 605 vmenv.Call(sender, destination, nil, gas, cfg.Value) 606 } 607 }) 608 } 609 610 // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG 611 // 55 ms 612 func BenchmarkSimpleLoop(b *testing.B) { 613 614 staticCallIdentity := []byte{ 615 byte(vm.JUMPDEST), // [ count ] 616 // push args for the call 617 byte(vm.PUSH1), 0, // out size 618 byte(vm.DUP1), // out offset 619 byte(vm.DUP1), // out insize 620 byte(vm.DUP1), // in offset 621 byte(vm.PUSH1), 0x4, // address of identity 622 byte(vm.GAS), // gas 623 byte(vm.STATICCALL), 624 byte(vm.POP), // pop return value 625 byte(vm.PUSH1), 0, // jumpdestination 626 byte(vm.JUMP), 627 } 628 629 callIdentity := []byte{ 630 byte(vm.JUMPDEST), // [ count ] 631 // push args for the call 632 byte(vm.PUSH1), 0, // out size 633 byte(vm.DUP1), // out offset 634 byte(vm.DUP1), // out insize 635 byte(vm.DUP1), // in offset 636 byte(vm.DUP1), // value 637 byte(vm.PUSH1), 0x4, // address of identity 638 byte(vm.GAS), // gas 639 byte(vm.CALL), 640 byte(vm.POP), // pop return value 641 byte(vm.PUSH1), 0, // jumpdestination 642 byte(vm.JUMP), 643 } 644 645 callInexistant := []byte{ 646 byte(vm.JUMPDEST), // [ count ] 647 // push args for the call 648 byte(vm.PUSH1), 0, // out size 649 byte(vm.DUP1), // out offset 650 byte(vm.DUP1), // out insize 651 byte(vm.DUP1), // in offset 652 byte(vm.DUP1), // value 653 byte(vm.PUSH1), 0xff, // address of existing contract 654 byte(vm.GAS), // gas 655 byte(vm.CALL), 656 byte(vm.POP), // pop return value 657 byte(vm.PUSH1), 0, // jumpdestination 658 byte(vm.JUMP), 659 } 660 661 callEOA := []byte{ 662 byte(vm.JUMPDEST), // [ count ] 663 // push args for the call 664 byte(vm.PUSH1), 0, // out size 665 byte(vm.DUP1), // out offset 666 byte(vm.DUP1), // out insize 667 byte(vm.DUP1), // in offset 668 byte(vm.DUP1), // value 669 byte(vm.PUSH1), 0xE0, // address of EOA 670 byte(vm.GAS), // gas 671 byte(vm.CALL), 672 byte(vm.POP), // pop return value 673 byte(vm.PUSH1), 0, // jumpdestination 674 byte(vm.JUMP), 675 } 676 677 loopingCode := []byte{ 678 byte(vm.JUMPDEST), // [ count ] 679 // push args for the call 680 byte(vm.PUSH1), 0, // out size 681 byte(vm.DUP1), // out offset 682 byte(vm.DUP1), // out insize 683 byte(vm.DUP1), // in offset 684 byte(vm.PUSH1), 0x4, // address of identity 685 byte(vm.GAS), // gas 686 687 byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), 688 byte(vm.PUSH1), 0, // jumpdestination 689 byte(vm.JUMP), 690 } 691 692 calllRevertingContractWithInput := []byte{ 693 byte(vm.JUMPDEST), // 694 // push args for the call 695 byte(vm.PUSH1), 0, // out size 696 byte(vm.DUP1), // out offset 697 byte(vm.PUSH1), 0x20, // in size 698 byte(vm.PUSH1), 0x00, // in offset 699 byte(vm.PUSH1), 0x00, // value 700 byte(vm.PUSH1), 0xEE, // address of reverting contract 701 byte(vm.GAS), // gas 702 byte(vm.CALL), 703 byte(vm.POP), // pop return value 704 byte(vm.PUSH1), 0, // jumpdestination 705 byte(vm.JUMP), 706 } 707 708 //tracer := vm.NewJSONLogger(nil, os.Stdout) 709 //Execute(loopingCode, nil, &Config{ 710 // EVMConfig: vm.Config{ 711 // Debug: true, 712 // Tracer: tracer, 713 // }}) 714 // 100M gas 715 benchmarkNonModifyingCode(100000000, staticCallIdentity, "staticcall-identity-100M", b) 716 benchmarkNonModifyingCode(100000000, callIdentity, "call-identity-100M", b) 717 benchmarkNonModifyingCode(100000000, loopingCode, "loop-100M", b) 718 benchmarkNonModifyingCode(100000000, callInexistant, "call-nonexist-100M", b) 719 benchmarkNonModifyingCode(100000000, callEOA, "call-EOA-100M", b) 720 benchmarkNonModifyingCode(100000000, calllRevertingContractWithInput, "call-reverting-100M", b) 721 722 //benchmarkNonModifyingCode(10000000, staticCallIdentity, "staticcall-identity-10M", b) 723 //benchmarkNonModifyingCode(10000000, loopingCode, "loop-10M", b) 724 } 725 726 // TestEip2929Cases contains various testcases that are used for 727 // EIP-2929 about gas repricings 728 func TestEip2929Cases(t *testing.T) { 729 730 id := 1 731 prettyPrint := func(comment string, code []byte) { 732 733 instrs := make([]string, 0) 734 it := asm.NewInstructionIterator(code) 735 for it.Next() { 736 if it.Arg() != nil && 0 < len(it.Arg()) { 737 instrs = append(instrs, fmt.Sprintf("%v 0x%x", it.Op(), it.Arg())) 738 } else { 739 instrs = append(instrs, fmt.Sprintf("%v", it.Op())) 740 } 741 } 742 ops := strings.Join(instrs, ", ") 743 fmt.Printf("### Case %d\n\n", id) 744 id++ 745 fmt.Printf("%v\n\nBytecode: \n```\n0x%x\n```\nOperations: \n```\n%v\n```\n\n", 746 comment, 747 code, ops) 748 Execute(code, nil, &Config{ 749 EVMConfig: vm.Config{ 750 Debug: true, 751 Tracer: vm.NewMarkdownLogger(nil, os.Stdout), 752 ExtraEips: []int{2929}, 753 }, 754 }) 755 } 756 757 { // First eip testcase 758 code := []byte{ 759 // Three checks against a precompile 760 byte(vm.PUSH1), 1, byte(vm.EXTCODEHASH), byte(vm.POP), 761 byte(vm.PUSH1), 2, byte(vm.EXTCODESIZE), byte(vm.POP), 762 byte(vm.PUSH1), 3, byte(vm.BALANCE), byte(vm.POP), 763 // Three checks against a non-precompile 764 byte(vm.PUSH1), 0xf1, byte(vm.EXTCODEHASH), byte(vm.POP), 765 byte(vm.PUSH1), 0xf2, byte(vm.EXTCODESIZE), byte(vm.POP), 766 byte(vm.PUSH1), 0xf3, byte(vm.BALANCE), byte(vm.POP), 767 // Same three checks (should be cheaper) 768 byte(vm.PUSH1), 0xf2, byte(vm.EXTCODEHASH), byte(vm.POP), 769 byte(vm.PUSH1), 0xf3, byte(vm.EXTCODESIZE), byte(vm.POP), 770 byte(vm.PUSH1), 0xf1, byte(vm.BALANCE), byte(vm.POP), 771 // Check the origin, and the 'this' 772 byte(vm.ORIGIN), byte(vm.BALANCE), byte(vm.POP), 773 byte(vm.ADDRESS), byte(vm.BALANCE), byte(vm.POP), 774 775 byte(vm.STOP), 776 } 777 prettyPrint("This checks `EXT`(codehash,codesize,balance) of precompiles, which should be `100`, "+ 778 "and later checks the same operations twice against some non-precompiles. "+ 779 "Those are cheaper second time they are accessed. Lastly, it checks the `BALANCE` of `origin` and `this`.", code) 780 } 781 782 { // EXTCODECOPY 783 code := []byte{ 784 // extcodecopy( 0xff,0,0,0,0) 785 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 786 byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY), 787 // extcodecopy( 0xff,0,0,0,0) 788 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 789 byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY), 790 // extcodecopy( this,0,0,0,0) 791 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 792 byte(vm.ADDRESS), byte(vm.EXTCODECOPY), 793 794 byte(vm.STOP), 795 } 796 prettyPrint("This checks `extcodecopy( 0xff,0,0,0,0)` twice, (should be expensive first time), "+ 797 "and then does `extcodecopy( this,0,0,0,0)`.", code) 798 } 799 800 { // SLOAD + SSTORE 801 code := []byte{ 802 803 // Add slot `0x1` to access list 804 byte(vm.PUSH1), 0x01, byte(vm.SLOAD), byte(vm.POP), // SLOAD( 0x1) (add to access list) 805 // Write to `0x1` which is already in access list 806 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x01, byte(vm.SSTORE), // SSTORE( loc: 0x01, val: 0x11) 807 // Write to `0x2` which is not in access list 808 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11) 809 // Write again to `0x2` 810 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11) 811 // Read slot in access list (0x2) 812 byte(vm.PUSH1), 0x02, byte(vm.SLOAD), // SLOAD( 0x2) 813 // Read slot in access list (0x1) 814 byte(vm.PUSH1), 0x01, byte(vm.SLOAD), // SLOAD( 0x1) 815 } 816 prettyPrint("This checks `sload( 0x1)` followed by `sstore(loc: 0x01, val:0x11)`, then 'naked' sstore:"+ 817 "`sstore(loc: 0x02, val:0x11)` twice, and `sload(0x2)`, `sload(0x1)`. ", code) 818 } 819 { // Call variants 820 code := []byte{ 821 // identity precompile 822 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 823 byte(vm.PUSH1), 0x04, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP), 824 825 // random account - call 1 826 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 827 byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP), 828 829 // random account - call 2 830 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 831 byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.STATICCALL), byte(vm.POP), 832 } 833 prettyPrint("This calls the `identity`-precompile (cheap), then calls an account (expensive) and `staticcall`s the same"+ 834 "account (cheap)", code) 835 } 836 }