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