github.com/core-coin/go-core@v1.1.7/core/vm/runtime/runtime_test.go (about) 1 // Copyright 2015 by the Authors 2 // This file is part of the go-core library. 3 // 4 // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>. 16 17 package runtime 18 19 import ( 20 "fmt" 21 "github.com/core-coin/go-core/core/asm" 22 "github.com/hpcloud/tail/util" 23 "math/big" 24 "os" 25 "strings" 26 "testing" 27 "time" 28 29 "github.com/core-coin/go-core/accounts/abi" 30 "github.com/core-coin/go-core/common" 31 "github.com/core-coin/go-core/consensus" 32 "github.com/core-coin/go-core/core" 33 "github.com/core-coin/go-core/core/rawdb" 34 "github.com/core-coin/go-core/core/state" 35 "github.com/core-coin/go-core/core/types" 36 "github.com/core-coin/go-core/core/vm" 37 "github.com/core-coin/go-core/params" 38 ) 39 40 func TestDefaults(t *testing.T) { 41 cfg := new(Config) 42 setDefaults(cfg) 43 44 if cfg.Difficulty == nil { 45 t.Error("expected difficulty to be non nil") 46 } 47 48 if cfg.Time == nil { 49 t.Error("expected time to be non nil") 50 } 51 if cfg.EnergyLimit == 0 { 52 t.Error("didn't expect energylimit to be zero") 53 } 54 if cfg.EnergyPrice == nil { 55 t.Error("expected time to be non nil") 56 } 57 if cfg.Value == nil { 58 t.Error("expected time to be non nil") 59 } 60 if cfg.GetHashFn == nil { 61 t.Error("expected time to be non nil") 62 } 63 if cfg.BlockNumber == nil { 64 t.Error("expected block number to be non nil") 65 } 66 } 67 68 func TestCVM(t *testing.T) { 69 defer func() { 70 if r := recover(); r != nil { 71 t.Fatalf("crashed with: %v", r) 72 } 73 }() 74 75 Execute([]byte{ 76 byte(vm.DIFFICULTY), 77 byte(vm.TIMESTAMP), 78 byte(vm.ENERGYLIMIT), 79 byte(vm.PUSH1), 80 byte(vm.ORIGIN), 81 byte(vm.BLOCKHASH), 82 byte(vm.COINBASE), 83 }, nil, nil) 84 } 85 86 func TestExecute(t *testing.T) { 87 ret, _, err := Execute([]byte{ 88 byte(vm.PUSH1), 10, 89 byte(vm.PUSH1), 0, 90 byte(vm.MSTORE), 91 byte(vm.PUSH1), 32, 92 byte(vm.PUSH1), 0, 93 byte(vm.RETURN), 94 }, nil, nil) 95 if err != nil { 96 t.Fatal("didn't expect error", err) 97 } 98 99 num := new(big.Int).SetBytes(ret) 100 if num.Cmp(big.NewInt(10)) != 0 { 101 t.Error("Expected 10, got", num) 102 } 103 } 104 105 func TestCall(t *testing.T) { 106 state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 107 address, err := common.HexToAddress("cb75000000000000000000000000000000000000000a") 108 if err != nil { 109 t.Error(err) 110 } 111 state.SetCode(address, []byte{ 112 byte(vm.PUSH1), 10, 113 byte(vm.PUSH1), 0, 114 byte(vm.MSTORE), 115 byte(vm.PUSH1), 32, 116 byte(vm.PUSH1), 0, 117 byte(vm.RETURN), 118 }) 119 120 ret, _, err := Call(address, nil, &Config{State: state}) 121 if err != nil { 122 t.Fatal("didn't expect error", err) 123 } 124 125 num := new(big.Int).SetBytes(ret) 126 if num.Cmp(big.NewInt(10)) != 0 { 127 t.Error("Expected 10, got", num) 128 } 129 } 130 131 func BenchmarkCall(b *testing.B) { 132 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"}]` 133 134 var code = common.Hex2Bytes("6060604052361561006c5760e060020a600035046308551a53811461007457806335a063b4146100865780633fa4f245146100a6578063590e1ae3146100af5780637150d8ae146100cf57806373fac6f0146100e1578063c19d93fb146100fe578063d696069714610112575b610131610002565b610133600154600160a060020a031681565b610131600154600160a060020a0390811633919091161461015057610002565b61014660005481565b610131600154600160a060020a039081163391909116146102d557610002565b610133600254600160a060020a031681565b610131600254600160a060020a0333811691161461023757610002565b61014660025460ff60a060020a9091041681565b61013160025460009060ff60a060020a9091041681146101cc57610002565b005b600160a060020a03166060908152602090f35b6060908152602090f35b60025460009060a060020a900460ff16811461016b57610002565b600154600160a060020a03908116908290301631606082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f72c874aeff0b183a56e2b79c71b46e1aed4dee5e09862134b8821ba2fddbf8bf9250a150565b80546002023414806101dd57610002565b6002805460a060020a60ff021973ffffffffffffffffffffffffffffffffffffffff1990911633171660a060020a1790557fd5d55c8a68912e9a110618df8d5e2e83b8d83211c57a8ddd1203df92885dc881826060a15050565b60025460019060a060020a900460ff16811461025257610002565b60025460008054600160a060020a0390921691606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517fe89152acd703c9d8c7d28829d443260b411454d45394e7995815140c8cbcbcf79250a150565b60025460019060a060020a900460ff1681146102f057610002565b6002805460008054600160a060020a0390921692909102606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f8616bbbbad963e4e65b1366f1d75dfb63f9e9704bbbf91fb01bec70849906cf79250a15056") 135 136 abi, err := abi.JSON(strings.NewReader(definition)) 137 if err != nil { 138 b.Fatal(err) 139 } 140 141 cpurchase, err := abi.Pack("confirmPurchase") 142 if err != nil { 143 b.Fatal(err) 144 } 145 creceived, err := abi.Pack("confirmReceived") 146 if err != nil { 147 b.Fatal(err) 148 } 149 refund, err := abi.Pack("refund") 150 if err != nil { 151 b.Fatal(err) 152 } 153 154 b.ResetTimer() 155 for i := 0; i < b.N; i++ { 156 for j := 0; j < 400; j++ { 157 Execute(code, cpurchase, nil) 158 Execute(code, creceived, nil) 159 Execute(code, refund, nil) 160 } 161 } 162 } 163 func benchmarkCVM_Create(bench *testing.B, code string) { 164 var ( 165 statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 166 sender = common.BytesToAddress([]byte("sender")) 167 receiver = common.BytesToAddress([]byte("receiver")) 168 ) 169 170 statedb.CreateAccount(sender) 171 statedb.SetCode(receiver, common.FromHex(code)) 172 runtimeConfig := Config{ 173 Origin: sender, 174 State: statedb, 175 EnergyLimit: 10000000, 176 Difficulty: big.NewInt(0x200000), 177 Time: new(big.Int).SetUint64(0), 178 Coinbase: common.Address{}, 179 BlockNumber: new(big.Int).SetUint64(1), 180 ChainConfig: ¶ms.ChainConfig{ 181 NetworkID: big.NewInt(1), 182 }, 183 CVMConfig: vm.Config{}, 184 } 185 // Warm up the intpools and stuff 186 bench.ResetTimer() 187 for i := 0; i < bench.N; i++ { 188 Call(receiver, []byte{}, &runtimeConfig) 189 } 190 bench.StopTimer() 191 } 192 193 func BenchmarkCVM_CREATE_500(bench *testing.B) { 194 // initcode size 500K, repeatedly calls CREATE and then modifies the mem contents 195 benchmarkCVM_Create(bench, "5b6207a120600080f0600152600056") 196 } 197 func BenchmarkCVM_CREATE2_500(bench *testing.B) { 198 // initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents 199 benchmarkCVM_Create(bench, "5b586207a120600080f5600152600056") 200 } 201 func BenchmarkCVM_CREATE_1200(bench *testing.B) { 202 // initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents 203 benchmarkCVM_Create(bench, "5b62124f80600080f0600152600056") 204 } 205 func BenchmarkCVM_CREATE2_1200(bench *testing.B) { 206 // initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents 207 benchmarkCVM_Create(bench, "5b5862124f80600080f5600152600056") 208 } 209 210 func fakeHeader(n uint64, parentHash common.Hash) *types.Header { 211 coinbase, err := common.HexToAddress("cb8000000000000000000000000000000000deadbeef") 212 if err != nil { 213 util.Fatal(err.Error()) 214 } 215 header := types.Header{ 216 Coinbase: coinbase, 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 EnergyLimit: 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, energy uint64, value *big.Int) error { 330 return nil 331 } 332 333 func (s *stepCounter) CaptureState(env *vm.CVM, pc uint64, op vm.OpCode, energy, 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, energy, cost, memory, stack, rStack, contract, depth, err) 337 return nil 338 } 339 340 func (s *stepCounter) CaptureFault(env *vm.CVM, pc uint64, op vm.OpCode, energy, 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, energyUsed 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("cb270000000000000000000000000000000000000001") 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 EnergyLimit: 20000, 369 ChainConfig: params.AllCryptoreProtocolChanges, 370 CVMConfig: vm.Config{ 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("cb270000000000000000000000000000000000000001") 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 EnergyLimit: 10000, 403 ChainConfig: params.AllCryptoreProtocolChanges, 404 CVMConfig: vm.Config{ 405 Debug: true, 406 Tracer: &tracer, 407 }}) 408 409 exp := "invalid retsub" 410 if err.Error() != exp { 411 t.Fatalf("expected %v, got %v", exp, err) 412 } 413 if exp, got := 4, tracer.steps; exp != got { 414 t.Fatalf("expected %d steps, got %d", exp, got) 415 } 416 } 417 418 // disabled -- only used for generating markdown 419 func DisabledTestReturnCases(t *testing.T) { 420 cfg := &Config{ 421 CVMConfig: vm.Config{ 422 Debug: true, 423 Tracer: vm.NewMarkdownLogger(nil, os.Stdout), 424 }, 425 } 426 // This should fail at first opcode 427 Execute([]byte{ 428 byte(vm.RETURNSUB), 429 byte(vm.PC), 430 byte(vm.PC), 431 }, nil, cfg) 432 433 // Should also fail 434 Execute([]byte{ 435 byte(vm.PUSH1), 5, 436 byte(vm.JUMPSUB), 437 byte(vm.RETURNSUB), 438 byte(vm.PC), 439 byte(vm.BEGINSUB), 440 byte(vm.RETURNSUB), 441 byte(vm.PC), 442 }, nil, cfg) 443 444 // This should complete 445 Execute([]byte{ 446 byte(vm.PUSH1), 0x4, 447 byte(vm.JUMPSUB), 448 byte(vm.STOP), 449 byte(vm.BEGINSUB), 450 byte(vm.PUSH1), 0x9, 451 byte(vm.JUMPSUB), 452 byte(vm.RETURNSUB), 453 byte(vm.BEGINSUB), 454 byte(vm.RETURNSUB), 455 }, nil, cfg) 456 } 457 458 // DisabledTestEipExampleCases contains various testcases that are used for the 459 // EIP examples 460 // This test is disabled, as it's only used for generating markdown 461 func DisabledTestEipExampleCases(t *testing.T) { 462 cfg := &Config{ 463 CVMConfig: vm.Config{ 464 Debug: true, 465 Tracer: vm.NewMarkdownLogger(nil, os.Stdout), 466 }, 467 } 468 prettyPrint := func(comment string, code []byte) { 469 instrs := make([]string, 0) 470 it := asm.NewInstructionIterator(code) 471 for it.Next() { 472 if it.Arg() != nil && 0 < len(it.Arg()) { 473 instrs = append(instrs, fmt.Sprintf("%v 0x%x", it.Op(), it.Arg())) 474 } else { 475 instrs = append(instrs, fmt.Sprintf("%v", it.Op())) 476 } 477 } 478 ops := strings.Join(instrs, ", ") 479 480 fmt.Printf("%v\nBytecode: `0x%x` (`%v`)\n", 481 comment, 482 code, ops) 483 Execute(code, nil, cfg) 484 } 485 486 { // First eip testcase 487 code := []byte{ 488 byte(vm.PUSH1), 4, 489 byte(vm.JUMPSUB), 490 byte(vm.STOP), 491 byte(vm.BEGINSUB), 492 byte(vm.RETURNSUB), 493 } 494 prettyPrint("This should jump into a subroutine, back out and stop.", code) 495 } 496 497 { 498 code := []byte{ 499 byte(vm.PUSH9), 0x00, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, (4 + 8), 500 byte(vm.JUMPSUB), 501 byte(vm.STOP), 502 byte(vm.BEGINSUB), 503 byte(vm.PUSH1), 8 + 9, 504 byte(vm.JUMPSUB), 505 byte(vm.RETURNSUB), 506 byte(vm.BEGINSUB), 507 byte(vm.RETURNSUB), 508 } 509 prettyPrint("This should execute fine, going into one two depths of subroutines", code) 510 } 511 // TODO(@holiman) move this test into an actual test, which not only prints 512 // out the trace. 513 { 514 code := []byte{ 515 byte(vm.PUSH9), 0x01, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, (4 + 8), 516 byte(vm.JUMPSUB), 517 byte(vm.STOP), 518 byte(vm.BEGINSUB), 519 byte(vm.PUSH1), 8 + 9, 520 byte(vm.JUMPSUB), 521 byte(vm.RETURNSUB), 522 byte(vm.BEGINSUB), 523 byte(vm.RETURNSUB), 524 } 525 prettyPrint("This should fail, since the given location is outside of the "+ 526 "code-range. The code is the same as previous example, except that the "+ 527 "pushed location is `0x01000000000000000c` instead of `0x0c`.", code) 528 } 529 { 530 // This should fail at first opcode 531 code := []byte{ 532 byte(vm.RETURNSUB), 533 byte(vm.PC), 534 byte(vm.PC), 535 } 536 prettyPrint("This should fail at first opcode, due to shallow `return_stack`", code) 537 538 } 539 { 540 code := []byte{ 541 byte(vm.PUSH1), 5, // Jump past the subroutine 542 byte(vm.JUMP), 543 byte(vm.BEGINSUB), 544 byte(vm.RETURNSUB), 545 byte(vm.JUMPDEST), 546 byte(vm.PUSH1), 3, // Now invoke the subroutine 547 byte(vm.JUMPSUB), 548 } 549 prettyPrint("In this example. the JUMPSUB is on the last byte of code. When the "+ 550 "subroutine returns, it should hit the 'virtual stop' _after_ the bytecode, "+ 551 "and not exit with error", code) 552 } 553 554 { 555 code := []byte{ 556 byte(vm.BEGINSUB), 557 byte(vm.RETURNSUB), 558 byte(vm.STOP), 559 } 560 prettyPrint("In this example, the code 'walks' into a subroutine, which is not "+ 561 "allowed, and causes an error", code) 562 } 563 } 564 565 // benchmarkNonModifyingCode benchmarks code, but if the code modifies the 566 // state, this should not be used, since it does not reset the state between runs. 567 func benchmarkNonModifyingCode(energy uint64, code []byte, name string, b *testing.B) { 568 cfg := new(Config) 569 setDefaults(cfg) 570 cfg.State, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 571 cfg.EnergyLimit = energy 572 var ( 573 destination = common.BytesToAddress([]byte("contract")) 574 vmenv = NewEnv(cfg) 575 sender = vm.AccountRef(cfg.Origin) 576 ) 577 cfg.State.CreateAccount(destination) 578 eoa, _ := common.HexToAddress("cb270000000000000000000000000000000000000001") 579 { 580 cfg.State.CreateAccount(eoa) 581 cfg.State.SetNonce(eoa, 100) 582 } 583 reverting, _ := common.HexToAddress("cb970000000000000000000000000000000000000002") 584 { 585 cfg.State.CreateAccount(reverting) 586 cfg.State.SetCode(reverting, []byte{ 587 byte(vm.PUSH1), 0x00, 588 byte(vm.PUSH1), 0x00, 589 byte(vm.REVERT), 590 }) 591 } 592 593 //cfg.State.CreateAccount(cfg.Origin) 594 // set the receiver's (the executing contract) code for execution. 595 cfg.State.SetCode(destination, code) 596 vmenv.Call(sender, destination, nil, energy, cfg.Value) 597 598 b.Run(name, func(b *testing.B) { 599 b.ReportAllocs() 600 for i := 0; i < b.N; i++ { 601 vmenv.Call(sender, destination, nil, energy, cfg.Value) 602 } 603 }) 604 } 605 606 // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG 607 // 55 ms 608 func BenchmarkSimpleLoop(b *testing.B) { 609 610 staticCallIdentity := []byte{ 611 byte(vm.JUMPDEST), // [ count ] 612 // push args for the call 613 byte(vm.PUSH1), 0, // out size 614 byte(vm.DUP1), // out offset 615 byte(vm.DUP1), // out insize 616 byte(vm.DUP1), // in offset 617 byte(vm.PUSH1), 0x4, // address of identity 618 byte(vm.ENERGY), // energy 619 byte(vm.STATICCALL), 620 byte(vm.POP), // pop return value 621 byte(vm.PUSH1), 0, // jumpdestination 622 byte(vm.JUMP), 623 } 624 625 callIdentity := []byte{ 626 byte(vm.JUMPDEST), // [ count ] 627 // push args for the call 628 byte(vm.PUSH1), 0, // out size 629 byte(vm.DUP1), // out offset 630 byte(vm.DUP1), // out insize 631 byte(vm.DUP1), // in offset 632 byte(vm.DUP1), // value 633 byte(vm.PUSH1), 0x4, // address of identity 634 byte(vm.ENERGY), // energy 635 byte(vm.CALL), 636 byte(vm.POP), // pop return value 637 byte(vm.PUSH1), 0, // jumpdestination 638 byte(vm.JUMP), 639 } 640 641 callInexistant := []byte{ 642 byte(vm.JUMPDEST), // [ count ] 643 // push args for the call 644 byte(vm.PUSH1), 0, // out size 645 byte(vm.DUP1), // out offset 646 byte(vm.DUP1), // out insize 647 byte(vm.DUP1), // in offset 648 byte(vm.DUP1), // value 649 byte(vm.PUSH1), 0xff, // address of existing contract 650 byte(vm.ENERGY), // energy 651 byte(vm.CALL), 652 byte(vm.POP), // pop return value 653 byte(vm.PUSH1), 0, // jumpdestination 654 byte(vm.JUMP), 655 } 656 657 callEOA := []byte{ 658 byte(vm.JUMPDEST), // [ count ] 659 // push args for the call 660 byte(vm.PUSH1), 0, // out size 661 byte(vm.DUP1), // out offset 662 byte(vm.DUP1), // out insize 663 byte(vm.DUP1), // in offset 664 byte(vm.DUP1), // value 665 byte(vm.PUSH1), 0xE0, // address of EOA 666 byte(vm.ENERGY), // energy 667 byte(vm.CALL), 668 byte(vm.POP), // pop return value 669 byte(vm.PUSH1), 0, // jumpdestination 670 byte(vm.JUMP), 671 } 672 673 loopingCode := []byte{ 674 byte(vm.JUMPDEST), // [ count ] 675 // push args for the call 676 byte(vm.PUSH1), 0, // out size 677 byte(vm.DUP1), // out offset 678 byte(vm.DUP1), // out insize 679 byte(vm.DUP1), // in offset 680 byte(vm.PUSH1), 0x4, // address of identity 681 byte(vm.ENERGY), // energy 682 683 byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), 684 byte(vm.PUSH1), 0, // jumpdestination 685 byte(vm.JUMP), 686 } 687 688 calllRevertingContractWithInput := []byte{ 689 byte(vm.JUMPDEST), // 690 // push args for the call 691 byte(vm.PUSH1), 0, // out size 692 byte(vm.DUP1), // out offset 693 byte(vm.PUSH1), 0x20, // in size 694 byte(vm.PUSH1), 0x00, // in offset 695 byte(vm.PUSH1), 0x00, // value 696 byte(vm.PUSH1), 0xEE, // address of reverting contract 697 byte(vm.ENERGY), // energy 698 byte(vm.CALL), 699 byte(vm.POP), // pop return value 700 byte(vm.PUSH1), 0, // jumpdestination 701 byte(vm.JUMP), 702 } 703 704 //tracer := vm.NewJSONLogger(nil, os.Stdout) 705 //Execute(loopingCode, nil, &Config{ 706 // EVMConfig: vm.Config{ 707 // Debug: true, 708 // Tracer: tracer, 709 // }}) 710 // 100M energy 711 benchmarkNonModifyingCode(100000000, staticCallIdentity, "staticcall-identity-100M", b) 712 benchmarkNonModifyingCode(100000000, callIdentity, "call-identity-100M", b) 713 benchmarkNonModifyingCode(100000000, loopingCode, "loop-100M", b) 714 benchmarkNonModifyingCode(100000000, callInexistant, "call-nonexist-100M", b) 715 benchmarkNonModifyingCode(100000000, callEOA, "call-EOA-100M", b) 716 benchmarkNonModifyingCode(100000000, calllRevertingContractWithInput, "call-reverting-100M", b) 717 718 //benchmarkNonModifyingCode(10000000, staticCallIdentity, "staticcall-identity-10M", b) 719 //benchmarkNonModifyingCode(10000000, loopingCode, "loop-10M", b) 720 }