github.com/ccm-chain/ccmchain@v1.0.0/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/ccm-chain/ccmchain/accounts/abi" 28 "github.com/ccm-chain/ccmchain/common" 29 "github.com/ccm-chain/ccmchain/consensus" 30 "github.com/ccm-chain/ccmchain/core" 31 "github.com/ccm-chain/ccmchain/core/asm" 32 "github.com/ccm-chain/ccmchain/core/rawdb" 33 "github.com/ccm-chain/ccmchain/core/state" 34 "github.com/ccm-chain/ccmchain/core/types" 35 "github.com/ccm-chain/ccmchain/core/vm" 36 "github.com/ccm-chain/ccmchain/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 160 func benchmarkEVM_Create(bench *testing.B, code string) { 161 var ( 162 statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 163 sender = common.BytesToAddress([]byte("sender")) 164 receiver = common.BytesToAddress([]byte("receiver")) 165 ) 166 167 statedb.CreateAccount(sender) 168 statedb.SetCode(receiver, common.FromHex(code)) 169 runtimeConfig := Config{ 170 Origin: sender, 171 State: statedb, 172 GasLimit: 10000000, 173 Difficulty: big.NewInt(0x200000), 174 Time: new(big.Int).SetUint64(0), 175 Coinbase: common.Address{}, 176 BlockNumber: new(big.Int).SetUint64(1), 177 ChainConfig: ¶ms.ChainConfig{ 178 ChainID: big.NewInt(1), 179 HomesteadBlock: new(big.Int), 180 ByzantiumBlock: new(big.Int), 181 ConstantinopleBlock: new(big.Int), 182 EIP150Block: new(big.Int), 183 EIP155Block: new(big.Int), 184 EIP158Block: new(big.Int), 185 }, 186 EVMConfig: vm.Config{}, 187 } 188 // Warm up the intpools and stuff 189 bench.ResetTimer() 190 for i := 0; i < bench.N; i++ { 191 Call(receiver, []byte{}, &runtimeConfig) 192 } 193 bench.StopTimer() 194 } 195 196 func BenchmarkEVM_CREATE_500(bench *testing.B) { 197 // initcode size 500K, repeatedly calls CREATE and then modifies the mem contents 198 benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056") 199 } 200 func BenchmarkEVM_CREATE2_500(bench *testing.B) { 201 // initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents 202 benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056") 203 } 204 func BenchmarkEVM_CREATE_1200(bench *testing.B) { 205 // initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents 206 benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056") 207 } 208 func BenchmarkEVM_CREATE2_1200(bench *testing.B) { 209 // initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents 210 benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056") 211 } 212 213 func fakeHeader(n uint64, parentHash common.Hash) *types.Header { 214 header := types.Header{ 215 Coinbase: common.HexToAddress("0x00000000000000000000000000000000deadbeef"), 216 Number: big.NewInt(int64(n)), 217 ParentHash: parentHash, 218 Time: 1000, 219 Nonce: types.BlockNonce{0x1}, 220 Extra: []byte{}, 221 Difficulty: big.NewInt(0), 222 GasLimit: 100000, 223 } 224 return &header 225 } 226 227 type dummyChain struct { 228 counter int 229 } 230 231 // Engine retrieves the chain's consensus engine. 232 func (d *dummyChain) Engine() consensus.Engine { 233 return nil 234 } 235 236 // GetHeader returns the hash corresponding to their hash. 237 func (d *dummyChain) GetHeader(h common.Hash, n uint64) *types.Header { 238 d.counter++ 239 parentHash := common.Hash{} 240 s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32) 241 copy(parentHash[:], s) 242 243 //parentHash := common.Hash{byte(n - 1)} 244 //fmt.Printf("GetHeader(%x, %d) => header with parent %x\n", h, n, parentHash) 245 return fakeHeader(n, parentHash) 246 } 247 248 // TestBlockhash tests the blockhash operation. It's a bit special, since it internally 249 // requires access to a chain reader. 250 func TestBlockhash(t *testing.T) { 251 // Current head 252 n := uint64(1000) 253 parentHash := common.Hash{} 254 s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32) 255 copy(parentHash[:], s) 256 header := fakeHeader(n, parentHash) 257 258 // This is the contract we're using. It requests the blockhash for current num (should be all zeroes), 259 // then iteratively fetches all blockhashes back to n-260. 260 // It returns 261 // 1. the first (should be zero) 262 // 2. the second (should be the parent hash) 263 // 3. the last non-zero hash 264 // By making the chain reader return hashes which correlate to the number, we can 265 // verify that it obtained the right hashes where it should 266 267 /* 268 269 pragma solidity ^0.5.3; 270 contract Hasher{ 271 272 function test() public view returns (bytes32, bytes32, bytes32){ 273 uint256 x = block.number; 274 bytes32 first; 275 bytes32 last; 276 bytes32 zero; 277 zero = blockhash(x); // Should be zeroes 278 first = blockhash(x-1); 279 for(uint256 i = 2 ; i < 260; i++){ 280 bytes32 hash = blockhash(x - i); 281 if (uint256(hash) != 0){ 282 last = hash; 283 } 284 } 285 return (zero, first, last); 286 } 287 } 288 289 */ 290 // The contract above 291 data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029") 292 // The method call to 'test()' 293 input := common.Hex2Bytes("f8a8fd6d") 294 chain := &dummyChain{} 295 ret, _, err := Execute(data, input, &Config{ 296 GetHashFn: core.GetHashFn(header, chain), 297 BlockNumber: new(big.Int).Set(header.Number), 298 }) 299 if err != nil { 300 t.Fatalf("expected no error, got %v", err) 301 } 302 if len(ret) != 96 { 303 t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret)) 304 } 305 306 zero := new(big.Int).SetBytes(ret[0:32]) 307 first := new(big.Int).SetBytes(ret[32:64]) 308 last := new(big.Int).SetBytes(ret[64:96]) 309 if zero.BitLen() != 0 { 310 t.Fatalf("expected zeroes, got %x", ret[0:32]) 311 } 312 if first.Uint64() != 999 { 313 t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64]) 314 } 315 if last.Uint64() != 744 { 316 t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96]) 317 } 318 if exp, got := 255, chain.counter; exp != got { 319 t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got) 320 } 321 } 322 323 type stepCounter struct { 324 inner *vm.JSONLogger 325 steps int 326 } 327 328 func (s *stepCounter) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error { 329 return nil 330 } 331 332 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 { 333 s.steps++ 334 // Enable this for more output 335 //s.inner.CaptureState(env, pc, op, gas, cost, memory, stack, rStack, contract, depth, err) 336 return nil 337 } 338 339 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 { 340 return nil 341 } 342 343 func (s *stepCounter) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error { 344 return nil 345 } 346 347 func TestJumpSub1024Limit(t *testing.T) { 348 state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 349 address := common.HexToAddress("0x0a") 350 // Code is 351 // 0 beginsub 352 // 1 push 0 353 // 3 jumpsub 354 // 355 // The code recursively calls itself. It should error when the returns-stack 356 // grows above 1023 357 state.SetCode(address, []byte{ 358 byte(vm.PUSH1), 3, 359 byte(vm.JUMPSUB), 360 byte(vm.BEGINSUB), 361 byte(vm.PUSH1), 3, 362 byte(vm.JUMPSUB), 363 }) 364 tracer := stepCounter{inner: vm.NewJSONLogger(nil, os.Stdout)} 365 // Enable 2315 366 _, _, err := Call(address, nil, &Config{State: state, 367 GasLimit: 20000, 368 ChainConfig: params.AllEthashProtocolChanges, 369 EVMConfig: vm.Config{ 370 ExtraEips: []int{2315}, 371 Debug: true, 372 //Tracer: vm.NewJSONLogger(nil, os.Stdout), 373 Tracer: &tracer, 374 }}) 375 exp := "return stack limit reached" 376 if err.Error() != exp { 377 t.Fatalf("expected %v, got %v", exp, err) 378 } 379 if exp, got := 2048, tracer.steps; exp != got { 380 t.Fatalf("expected %d steps, got %d", exp, got) 381 } 382 } 383 384 func TestReturnSubShallow(t *testing.T) { 385 state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 386 address := common.HexToAddress("0x0a") 387 // The code does returnsub without having anything on the returnstack. 388 // It should not panic, but just fail after one step 389 state.SetCode(address, []byte{ 390 byte(vm.PUSH1), 5, 391 byte(vm.JUMPSUB), 392 byte(vm.RETURNSUB), 393 byte(vm.PC), 394 byte(vm.BEGINSUB), 395 byte(vm.RETURNSUB), 396 byte(vm.PC), 397 }) 398 tracer := stepCounter{} 399 400 // Enable 2315 401 _, _, err := Call(address, nil, &Config{State: state, 402 GasLimit: 10000, 403 ChainConfig: params.AllEthashProtocolChanges, 404 EVMConfig: vm.Config{ 405 ExtraEips: []int{2315}, 406 Debug: true, 407 Tracer: &tracer, 408 }}) 409 410 exp := "invalid retsub" 411 if err.Error() != exp { 412 t.Fatalf("expected %v, got %v", exp, err) 413 } 414 if exp, got := 4, tracer.steps; exp != got { 415 t.Fatalf("expected %d steps, got %d", exp, got) 416 } 417 } 418 419 // disabled -- only used for generating markdown 420 func DisabledTestReturnCases(t *testing.T) { 421 cfg := &Config{ 422 EVMConfig: vm.Config{ 423 Debug: true, 424 Tracer: vm.NewMarkdownLogger(nil, os.Stdout), 425 ExtraEips: []int{2315}, 426 }, 427 } 428 // This should fail at first opcode 429 Execute([]byte{ 430 byte(vm.RETURNSUB), 431 byte(vm.PC), 432 byte(vm.PC), 433 }, nil, cfg) 434 435 // Should also fail 436 Execute([]byte{ 437 byte(vm.PUSH1), 5, 438 byte(vm.JUMPSUB), 439 byte(vm.RETURNSUB), 440 byte(vm.PC), 441 byte(vm.BEGINSUB), 442 byte(vm.RETURNSUB), 443 byte(vm.PC), 444 }, nil, cfg) 445 446 // This should complete 447 Execute([]byte{ 448 byte(vm.PUSH1), 0x4, 449 byte(vm.JUMPSUB), 450 byte(vm.STOP), 451 byte(vm.BEGINSUB), 452 byte(vm.PUSH1), 0x9, 453 byte(vm.JUMPSUB), 454 byte(vm.RETURNSUB), 455 byte(vm.BEGINSUB), 456 byte(vm.RETURNSUB), 457 }, nil, cfg) 458 } 459 460 // DisabledTestEipExampleCases contains various testcases that are used for the 461 // EIP examples 462 // This test is disabled, as it's only used for generating markdown 463 func DisabledTestEipExampleCases(t *testing.T) { 464 cfg := &Config{ 465 EVMConfig: vm.Config{ 466 Debug: true, 467 Tracer: vm.NewMarkdownLogger(nil, os.Stdout), 468 ExtraEips: []int{2315}, 469 }, 470 } 471 prettyPrint := func(comment string, code []byte) { 472 instrs := make([]string, 0) 473 it := asm.NewInstructionIterator(code) 474 for it.Next() { 475 if it.Arg() != nil && 0 < len(it.Arg()) { 476 instrs = append(instrs, fmt.Sprintf("%v 0x%x", it.Op(), it.Arg())) 477 } else { 478 instrs = append(instrs, fmt.Sprintf("%v", it.Op())) 479 } 480 } 481 ops := strings.Join(instrs, ", ") 482 483 fmt.Printf("%v\nBytecode: `0x%x` (`%v`)\n", 484 comment, 485 code, ops) 486 Execute(code, nil, cfg) 487 } 488 489 { // First eip testcase 490 code := []byte{ 491 byte(vm.PUSH1), 4, 492 byte(vm.JUMPSUB), 493 byte(vm.STOP), 494 byte(vm.BEGINSUB), 495 byte(vm.RETURNSUB), 496 } 497 prettyPrint("This should jump into a subroutine, back out and stop.", code) 498 } 499 500 { 501 code := []byte{ 502 byte(vm.PUSH9), 0x00, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, (4 + 8), 503 byte(vm.JUMPSUB), 504 byte(vm.STOP), 505 byte(vm.BEGINSUB), 506 byte(vm.PUSH1), 8 + 9, 507 byte(vm.JUMPSUB), 508 byte(vm.RETURNSUB), 509 byte(vm.BEGINSUB), 510 byte(vm.RETURNSUB), 511 } 512 prettyPrint("This should execute fine, going into one two depths of subroutines", code) 513 } 514 // TODO(@holiman) move this test into an actual test, which not only prints 515 // out the trace. 516 { 517 code := []byte{ 518 byte(vm.PUSH9), 0x01, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, (4 + 8), 519 byte(vm.JUMPSUB), 520 byte(vm.STOP), 521 byte(vm.BEGINSUB), 522 byte(vm.PUSH1), 8 + 9, 523 byte(vm.JUMPSUB), 524 byte(vm.RETURNSUB), 525 byte(vm.BEGINSUB), 526 byte(vm.RETURNSUB), 527 } 528 prettyPrint("This should fail, since the given location is outside of the "+ 529 "code-range. The code is the same as previous example, except that the "+ 530 "pushed location is `0x01000000000000000c` instead of `0x0c`.", code) 531 } 532 { 533 // This should fail at first opcode 534 code := []byte{ 535 byte(vm.RETURNSUB), 536 byte(vm.PC), 537 byte(vm.PC), 538 } 539 prettyPrint("This should fail at first opcode, due to shallow `return_stack`", code) 540 541 } 542 { 543 code := []byte{ 544 byte(vm.PUSH1), 5, // Jump past the subroutine 545 byte(vm.JUMP), 546 byte(vm.BEGINSUB), 547 byte(vm.RETURNSUB), 548 byte(vm.JUMPDEST), 549 byte(vm.PUSH1), 3, // Now invoke the subroutine 550 byte(vm.JUMPSUB), 551 } 552 prettyPrint("In this example. the JUMPSUB is on the last byte of code. When the "+ 553 "subroutine returns, it should hit the 'virtual stop' _after_ the bytecode, "+ 554 "and not exit with error", code) 555 } 556 557 { 558 code := []byte{ 559 byte(vm.BEGINSUB), 560 byte(vm.RETURNSUB), 561 byte(vm.STOP), 562 } 563 prettyPrint("In this example, the code 'walks' into a subroutine, which is not "+ 564 "allowed, and causes an error", code) 565 } 566 } 567 568 // benchmarkNonModifyingCode benchmarks code, but if the code modifies the 569 // state, this should not be used, since it does not reset the state between runs. 570 func benchmarkNonModifyingCode(gas uint64, code []byte, name string, b *testing.B) { 571 cfg := new(Config) 572 setDefaults(cfg) 573 cfg.State, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 574 cfg.GasLimit = gas 575 var ( 576 destination = common.BytesToAddress([]byte("contract")) 577 vmenv = NewEnv(cfg) 578 sender = vm.AccountRef(cfg.Origin) 579 ) 580 cfg.State.CreateAccount(destination) 581 eoa := common.HexToAddress("E0") 582 { 583 cfg.State.CreateAccount(eoa) 584 cfg.State.SetNonce(eoa, 100) 585 } 586 reverting := common.HexToAddress("EE") 587 { 588 cfg.State.CreateAccount(reverting) 589 cfg.State.SetCode(reverting, []byte{ 590 byte(vm.PUSH1), 0x00, 591 byte(vm.PUSH1), 0x00, 592 byte(vm.REVERT), 593 }) 594 } 595 596 //cfg.State.CreateAccount(cfg.Origin) 597 // set the receiver's (the executing contract) code for execution. 598 cfg.State.SetCode(destination, code) 599 vmenv.Call(sender, destination, nil, gas, cfg.Value) 600 601 b.Run(name, func(b *testing.B) { 602 b.ReportAllocs() 603 for i := 0; i < b.N; i++ { 604 vmenv.Call(sender, destination, nil, gas, cfg.Value) 605 } 606 }) 607 } 608 609 // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG 610 // 55 ms 611 func BenchmarkSimpleLoop(b *testing.B) { 612 613 staticCallIdentity := []byte{ 614 byte(vm.JUMPDEST), // [ count ] 615 // push args for the call 616 byte(vm.PUSH1), 0, // out size 617 byte(vm.DUP1), // out offset 618 byte(vm.DUP1), // out insize 619 byte(vm.DUP1), // in offset 620 byte(vm.PUSH1), 0x4, // address of identity 621 byte(vm.GAS), // gas 622 byte(vm.STATICCALL), 623 byte(vm.POP), // pop return value 624 byte(vm.PUSH1), 0, // jumpdestination 625 byte(vm.JUMP), 626 } 627 628 callIdentity := []byte{ 629 byte(vm.JUMPDEST), // [ count ] 630 // push args for the call 631 byte(vm.PUSH1), 0, // out size 632 byte(vm.DUP1), // out offset 633 byte(vm.DUP1), // out insize 634 byte(vm.DUP1), // in offset 635 byte(vm.DUP1), // value 636 byte(vm.PUSH1), 0x4, // address of identity 637 byte(vm.GAS), // gas 638 byte(vm.CALL), 639 byte(vm.POP), // pop return value 640 byte(vm.PUSH1), 0, // jumpdestination 641 byte(vm.JUMP), 642 } 643 644 callInexistant := []byte{ 645 byte(vm.JUMPDEST), // [ count ] 646 // push args for the call 647 byte(vm.PUSH1), 0, // out size 648 byte(vm.DUP1), // out offset 649 byte(vm.DUP1), // out insize 650 byte(vm.DUP1), // in offset 651 byte(vm.DUP1), // value 652 byte(vm.PUSH1), 0xff, // address of existing contract 653 byte(vm.GAS), // gas 654 byte(vm.CALL), 655 byte(vm.POP), // pop return value 656 byte(vm.PUSH1), 0, // jumpdestination 657 byte(vm.JUMP), 658 } 659 660 callEOA := []byte{ 661 byte(vm.JUMPDEST), // [ count ] 662 // push args for the call 663 byte(vm.PUSH1), 0, // out size 664 byte(vm.DUP1), // out offset 665 byte(vm.DUP1), // out insize 666 byte(vm.DUP1), // in offset 667 byte(vm.DUP1), // value 668 byte(vm.PUSH1), 0xE0, // address of EOA 669 byte(vm.GAS), // gas 670 byte(vm.CALL), 671 byte(vm.POP), // pop return value 672 byte(vm.PUSH1), 0, // jumpdestination 673 byte(vm.JUMP), 674 } 675 676 loopingCode := []byte{ 677 byte(vm.JUMPDEST), // [ count ] 678 // push args for the call 679 byte(vm.PUSH1), 0, // out size 680 byte(vm.DUP1), // out offset 681 byte(vm.DUP1), // out insize 682 byte(vm.DUP1), // in offset 683 byte(vm.PUSH1), 0x4, // address of identity 684 byte(vm.GAS), // gas 685 686 byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), 687 byte(vm.PUSH1), 0, // jumpdestination 688 byte(vm.JUMP), 689 } 690 691 calllRevertingContractWithInput := []byte{ 692 byte(vm.JUMPDEST), // 693 // push args for the call 694 byte(vm.PUSH1), 0, // out size 695 byte(vm.DUP1), // out offset 696 byte(vm.PUSH1), 0x20, // in size 697 byte(vm.PUSH1), 0x00, // in offset 698 byte(vm.PUSH1), 0x00, // value 699 byte(vm.PUSH1), 0xEE, // address of reverting contract 700 byte(vm.GAS), // gas 701 byte(vm.CALL), 702 byte(vm.POP), // pop return value 703 byte(vm.PUSH1), 0, // jumpdestination 704 byte(vm.JUMP), 705 } 706 707 //tracer := vm.NewJSONLogger(nil, os.Stdout) 708 //Execute(loopingCode, nil, &Config{ 709 // EVMConfig: vm.Config{ 710 // Debug: true, 711 // Tracer: tracer, 712 // }}) 713 // 100M gas 714 benchmarkNonModifyingCode(100000000, staticCallIdentity, "staticcall-identity-100M", b) 715 benchmarkNonModifyingCode(100000000, callIdentity, "call-identity-100M", b) 716 benchmarkNonModifyingCode(100000000, loopingCode, "loop-100M", b) 717 benchmarkNonModifyingCode(100000000, callInexistant, "call-nonexist-100M", b) 718 benchmarkNonModifyingCode(100000000, callEOA, "call-EOA-100M", b) 719 benchmarkNonModifyingCode(100000000, calllRevertingContractWithInput, "call-reverting-100M", b) 720 721 //benchmarkNonModifyingCode(10000000, staticCallIdentity, "staticcall-identity-10M", b) 722 //benchmarkNonModifyingCode(10000000, loopingCode, "loop-10M", b) 723 }