github.com/core-coin/go-core/v2@v2.1.9/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 "math/big" 22 "os" 23 "strings" 24 "testing" 25 "time" 26 27 "github.com/core-coin/go-core/v2/accounts/abi" 28 "github.com/core-coin/go-core/v2/common" 29 "github.com/core-coin/go-core/v2/consensus" 30 "github.com/core-coin/go-core/v2/core" 31 "github.com/core-coin/go-core/v2/core/asm" 32 "github.com/core-coin/go-core/v2/core/rawdb" 33 "github.com/core-coin/go-core/v2/core/state" 34 "github.com/core-coin/go-core/v2/core/types" 35 "github.com/core-coin/go-core/v2/core/vm" 36 "github.com/core-coin/go-core/v2/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.EnergyLimit == 0 { 51 t.Error("didn't expect energylimit to be zero") 52 } 53 if cfg.EnergyPrice == 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 TestCVM(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.ENERGYLIMIT), 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, err := common.HexToAddress("cb75000000000000000000000000000000000000000a") 107 if err != nil { 108 t.Error(err) 109 } 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 benchmarkCVM_Create(bench *testing.B, code string) { 163 var ( 164 statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 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 EnergyLimit: 10000000, 175 Difficulty: big.NewInt(0x200000), 176 Time: new(big.Int).SetUint64(0), 177 Coinbase: common.Address{}, 178 BlockNumber: new(big.Int).SetUint64(1), 179 ChainConfig: ¶ms.ChainConfig{ 180 NetworkID: big.NewInt(1), 181 }, 182 CVMConfig: vm.Config{}, 183 } 184 // Warm up the intpools and stuff 185 bench.ResetTimer() 186 for i := 0; i < bench.N; i++ { 187 Call(receiver, []byte{}, &runtimeConfig) 188 } 189 bench.StopTimer() 190 } 191 192 func BenchmarkCVM_CREATE_500(bench *testing.B) { 193 // initcode size 500K, repeatedly calls CREATE and then modifies the mem contents 194 benchmarkCVM_Create(bench, "5b6207a120600080f0600152600056") 195 } 196 func BenchmarkCVM_CREATE2_500(bench *testing.B) { 197 // initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents 198 benchmarkCVM_Create(bench, "5b586207a120600080f5600152600056") 199 } 200 func BenchmarkCVM_CREATE_1200(bench *testing.B) { 201 // initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents 202 benchmarkCVM_Create(bench, "5b62124f80600080f0600152600056") 203 } 204 func BenchmarkCVM_CREATE2_1200(bench *testing.B) { 205 // initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents 206 benchmarkCVM_Create(bench, "5b5862124f80600080f5600152600056") 207 } 208 209 func fakeHeader(n uint64, parentHash common.Hash) *types.Header { 210 coinbase, err := common.HexToAddress("cb8000000000000000000000000000000000deadbeef") 211 if err != nil { 212 panic(err) 213 } 214 header := types.Header{ 215 Coinbase: coinbase, 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 EnergyLimit: 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, energy uint64, value *big.Int) error { 329 return nil 330 } 331 332 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 { 333 s.steps++ 334 // Enable this for more output 335 //s.inner.CaptureState(env, pc, op, energy, cost, memory, stack, rStack, contract, depth, err) 336 return nil 337 } 338 339 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 { 340 return nil 341 } 342 343 func (s *stepCounter) CaptureEnd(output []byte, energyUsed 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, err := common.HexToAddress("cb75000000000000000000000000000000000000000a") 350 if err != nil { 351 t.Error(err) 352 } 353 // Code is 354 // 0 beginsub 355 // 1 push 0 356 // 3 jumpsub 357 // 358 // The code recursively calls itself. It should error when the returns-stack 359 // grows above 1023 360 state.SetCode(address, []byte{ 361 byte(vm.PUSH1), 3, 362 byte(vm.JUMPSUB), 363 byte(vm.BEGINSUB), 364 byte(vm.PUSH1), 3, 365 byte(vm.JUMPSUB), 366 }) 367 tracer := stepCounter{inner: vm.NewJSONLogger(nil, os.Stdout)} 368 // Enable 2315 369 _, _, err = Call(address, nil, &Config{State: state, 370 EnergyLimit: 20000, 371 ChainConfig: params.MainnetChainConfig, 372 CVMConfig: vm.Config{ 373 Debug: true, 374 //Tracer: vm.NewJSONLogger(nil, os.Stdout), 375 Tracer: &tracer, 376 }}) 377 exp := "return stack limit reached" 378 if err.Error() != exp { 379 t.Fatalf("expected %v, got %v", exp, err) 380 } 381 if exp, got := 2048, tracer.steps; exp != got { 382 t.Fatalf("expected %d steps, got %d", exp, got) 383 } 384 } 385 386 func TestReturnSubShallow(t *testing.T) { 387 state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 388 address, err := common.HexToAddress("cb75000000000000000000000000000000000000000a") 389 if err != nil { 390 t.Error(err) 391 } 392 // The code does returnsub without having anything on the returnstack. 393 // It should not panic, but just fail after one step 394 state.SetCode(address, []byte{ 395 byte(vm.PUSH1), 5, 396 byte(vm.JUMPSUB), 397 byte(vm.RETURNSUB), 398 byte(vm.PC), 399 byte(vm.BEGINSUB), 400 byte(vm.RETURNSUB), 401 byte(vm.PC), 402 }) 403 tracer := stepCounter{} 404 405 _, _, err = Call(address, nil, &Config{State: state, 406 EnergyLimit: 10000, 407 ChainConfig: params.MainnetChainConfig, 408 CVMConfig: vm.Config{ 409 Debug: true, 410 Tracer: &tracer, 411 }}) 412 413 exp := "invalid retsub" 414 if err.Error() != exp { 415 t.Fatalf("expected %v, got %v", exp, err) 416 } 417 if exp, got := 4, tracer.steps; exp != got { 418 t.Fatalf("expected %d steps, got %d", exp, got) 419 } 420 } 421 422 // disabled -- only used for generating markdown 423 func DisabledTestReturnCases(t *testing.T) { 424 cfg := &Config{ 425 CVMConfig: vm.Config{ 426 Debug: true, 427 Tracer: vm.NewMarkdownLogger(nil, os.Stdout), 428 }, 429 } 430 // This should fail at first opcode 431 Execute([]byte{ 432 byte(vm.RETURNSUB), 433 byte(vm.PC), 434 byte(vm.PC), 435 }, nil, cfg) 436 437 // Should also fail 438 Execute([]byte{ 439 byte(vm.PUSH1), 5, 440 byte(vm.JUMPSUB), 441 byte(vm.RETURNSUB), 442 byte(vm.PC), 443 byte(vm.BEGINSUB), 444 byte(vm.RETURNSUB), 445 byte(vm.PC), 446 }, nil, cfg) 447 448 // This should complete 449 Execute([]byte{ 450 byte(vm.PUSH1), 0x4, 451 byte(vm.JUMPSUB), 452 byte(vm.STOP), 453 byte(vm.BEGINSUB), 454 byte(vm.PUSH1), 0x9, 455 byte(vm.JUMPSUB), 456 byte(vm.RETURNSUB), 457 byte(vm.BEGINSUB), 458 byte(vm.RETURNSUB), 459 }, nil, cfg) 460 } 461 462 // DisabledTestEipExampleCases contains various testcases that are used for the 463 // CIP examples 464 // This test is disabled, as it's only used for generating markdown 465 func DisabledTestEipExampleCases(t *testing.T) { 466 cfg := &Config{ 467 CVMConfig: vm.Config{ 468 Debug: true, 469 Tracer: vm.NewMarkdownLogger(nil, os.Stdout), 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 cip 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(@raisty) 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(energy 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.EnergyLimit = energy 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("cb270000000000000000000000000000000000000001") 583 { 584 cfg.State.CreateAccount(eoa) 585 cfg.State.SetNonce(eoa, 100) 586 } 587 reverting, _ := common.HexToAddress("cb970000000000000000000000000000000000000002") 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, energy, 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, energy, 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.ENERGY), // energy 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.ENERGY), // energy 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.ENERGY), // energy 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.ENERGY), // energy 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.ENERGY), // energy 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.ENERGY), // energy 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 // CVMConfig: vm.Config{ 711 // Debug: true, 712 // Tracer: tracer, 713 // }}) 714 // 100M energy 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 }