github.com/haliliceylan/bsc@v1.1.10-0.20220501224556-eb78d644ebcb/core/vm/runtime/runtime_test.go (about) 1 // Copyright 2015 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package runtime 18 19 import ( 20 "fmt" 21 "math/big" 22 "os" 23 "strings" 24 "testing" 25 "time" 26 27 "github.com/ethereum/go-ethereum/accounts/abi" 28 "github.com/ethereum/go-ethereum/common" 29 "github.com/ethereum/go-ethereum/consensus" 30 "github.com/ethereum/go-ethereum/core" 31 "github.com/ethereum/go-ethereum/core/asm" 32 "github.com/ethereum/go-ethereum/core/rawdb" 33 "github.com/ethereum/go-ethereum/core/state" 34 "github.com/ethereum/go-ethereum/core/types" 35 "github.com/ethereum/go-ethereum/core/vm" 36 "github.com/ethereum/go-ethereum/eth/tracers" 37 "github.com/ethereum/go-ethereum/params" 38 39 // force-load js tracers to trigger registration 40 _ "github.com/ethereum/go-ethereum/eth/tracers/js" 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 // TestBlockhash tests the blockhash operation. It's a bit special, since it internally 254 // requires access to a chain reader. 255 func TestBlockhash(t *testing.T) { 256 // Current head 257 n := uint64(1000) 258 parentHash := common.Hash{} 259 s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32) 260 copy(parentHash[:], s) 261 header := fakeHeader(n, parentHash) 262 263 // This is the contract we're using. It requests the blockhash for current num (should be all zeroes), 264 // then iteratively fetches all blockhashes back to n-260. 265 // It returns 266 // 1. the first (should be zero) 267 // 2. the second (should be the parent hash) 268 // 3. the last non-zero hash 269 // By making the chain reader return hashes which correlate to the number, we can 270 // verify that it obtained the right hashes where it should 271 272 /* 273 274 pragma solidity ^0.5.3; 275 contract Hasher{ 276 277 function test() public view returns (bytes32, bytes32, bytes32){ 278 uint256 x = block.number; 279 bytes32 first; 280 bytes32 last; 281 bytes32 zero; 282 zero = blockhash(x); // Should be zeroes 283 first = blockhash(x-1); 284 for(uint256 i = 2 ; i < 260; i++){ 285 bytes32 hash = blockhash(x - i); 286 if (uint256(hash) != 0){ 287 last = hash; 288 } 289 } 290 return (zero, first, last); 291 } 292 } 293 294 */ 295 // The contract above 296 data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029") 297 // The method call to 'test()' 298 input := common.Hex2Bytes("f8a8fd6d") 299 chain := &dummyChain{} 300 ret, _, err := Execute(data, input, &Config{ 301 GetHashFn: core.GetHashFn(header, chain), 302 BlockNumber: new(big.Int).Set(header.Number), 303 }) 304 if err != nil { 305 t.Fatalf("expected no error, got %v", err) 306 } 307 if len(ret) != 96 { 308 t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret)) 309 } 310 311 zero := new(big.Int).SetBytes(ret[0:32]) 312 first := new(big.Int).SetBytes(ret[32:64]) 313 last := new(big.Int).SetBytes(ret[64:96]) 314 if zero.BitLen() != 0 { 315 t.Fatalf("expected zeroes, got %x", ret[0:32]) 316 } 317 if first.Uint64() != 999 { 318 t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64]) 319 } 320 if last.Uint64() != 744 { 321 t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96]) 322 } 323 if exp, got := 255, chain.counter; exp != got { 324 t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got) 325 } 326 } 327 328 type stepCounter struct { 329 inner *vm.JSONLogger 330 steps int 331 } 332 333 func (s *stepCounter) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { 334 } 335 336 func (s *stepCounter) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) { 337 } 338 339 func (s *stepCounter) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) {} 340 341 func (s *stepCounter) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) { 342 s.steps++ 343 // Enable this for more output 344 //s.inner.CaptureState(env, pc, op, gas, cost, memory, stack, rStack, contract, depth, err) 345 } 346 347 // benchmarkNonModifyingCode benchmarks code, but if the code modifies the 348 // state, this should not be used, since it does not reset the state between runs. 349 func benchmarkNonModifyingCode(gas uint64, code []byte, name string, tracerCode string, b *testing.B) { 350 cfg := new(Config) 351 setDefaults(cfg) 352 cfg.State, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 353 cfg.GasLimit = gas 354 if len(tracerCode) > 0 { 355 tracer, err := tracers.New(tracerCode, new(tracers.Context)) 356 if err != nil { 357 b.Fatal(err) 358 } 359 cfg.EVMConfig = vm.Config{ 360 Debug: true, 361 Tracer: tracer, 362 } 363 } 364 var ( 365 destination = common.BytesToAddress([]byte("contract")) 366 vmenv = NewEnv(cfg) 367 sender = vm.AccountRef(cfg.Origin) 368 ) 369 cfg.State.CreateAccount(destination) 370 eoa := common.HexToAddress("E0") 371 { 372 cfg.State.CreateAccount(eoa) 373 cfg.State.SetNonce(eoa, 100) 374 } 375 reverting := common.HexToAddress("EE") 376 { 377 cfg.State.CreateAccount(reverting) 378 cfg.State.SetCode(reverting, []byte{ 379 byte(vm.PUSH1), 0x00, 380 byte(vm.PUSH1), 0x00, 381 byte(vm.REVERT), 382 }) 383 } 384 385 //cfg.State.CreateAccount(cfg.Origin) 386 // set the receiver's (the executing contract) code for execution. 387 cfg.State.SetCode(destination, code) 388 vmenv.Call(sender, destination, nil, gas, cfg.Value) 389 390 b.Run(name, func(b *testing.B) { 391 b.ReportAllocs() 392 for i := 0; i < b.N; i++ { 393 vmenv.Call(sender, destination, nil, gas, cfg.Value) 394 } 395 }) 396 } 397 398 // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG 399 // 55 ms 400 func BenchmarkSimpleLoop(b *testing.B) { 401 402 staticCallIdentity := []byte{ 403 byte(vm.JUMPDEST), // [ count ] 404 // push args for the call 405 byte(vm.PUSH1), 0, // out size 406 byte(vm.DUP1), // out offset 407 byte(vm.DUP1), // out insize 408 byte(vm.DUP1), // in offset 409 byte(vm.PUSH1), 0x4, // address of identity 410 byte(vm.GAS), // gas 411 byte(vm.STATICCALL), 412 byte(vm.POP), // pop return value 413 byte(vm.PUSH1), 0, // jumpdestination 414 byte(vm.JUMP), 415 } 416 417 callIdentity := []byte{ 418 byte(vm.JUMPDEST), // [ count ] 419 // push args for the call 420 byte(vm.PUSH1), 0, // out size 421 byte(vm.DUP1), // out offset 422 byte(vm.DUP1), // out insize 423 byte(vm.DUP1), // in offset 424 byte(vm.DUP1), // value 425 byte(vm.PUSH1), 0x4, // address of identity 426 byte(vm.GAS), // gas 427 byte(vm.CALL), 428 byte(vm.POP), // pop return value 429 byte(vm.PUSH1), 0, // jumpdestination 430 byte(vm.JUMP), 431 } 432 433 callInexistant := []byte{ 434 byte(vm.JUMPDEST), // [ count ] 435 // push args for the call 436 byte(vm.PUSH1), 0, // out size 437 byte(vm.DUP1), // out offset 438 byte(vm.DUP1), // out insize 439 byte(vm.DUP1), // in offset 440 byte(vm.DUP1), // value 441 byte(vm.PUSH1), 0xff, // address of existing contract 442 byte(vm.GAS), // gas 443 byte(vm.CALL), 444 byte(vm.POP), // pop return value 445 byte(vm.PUSH1), 0, // jumpdestination 446 byte(vm.JUMP), 447 } 448 449 callEOA := []byte{ 450 byte(vm.JUMPDEST), // [ count ] 451 // push args for the call 452 byte(vm.PUSH1), 0, // out size 453 byte(vm.DUP1), // out offset 454 byte(vm.DUP1), // out insize 455 byte(vm.DUP1), // in offset 456 byte(vm.DUP1), // value 457 byte(vm.PUSH1), 0xE0, // address of EOA 458 byte(vm.GAS), // gas 459 byte(vm.CALL), 460 byte(vm.POP), // pop return value 461 byte(vm.PUSH1), 0, // jumpdestination 462 byte(vm.JUMP), 463 } 464 465 loopingCode := []byte{ 466 byte(vm.JUMPDEST), // [ count ] 467 // push args for the call 468 byte(vm.PUSH1), 0, // out size 469 byte(vm.DUP1), // out offset 470 byte(vm.DUP1), // out insize 471 byte(vm.DUP1), // in offset 472 byte(vm.PUSH1), 0x4, // address of identity 473 byte(vm.GAS), // gas 474 475 byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), 476 byte(vm.PUSH1), 0, // jumpdestination 477 byte(vm.JUMP), 478 } 479 480 calllRevertingContractWithInput := []byte{ 481 byte(vm.JUMPDEST), // 482 // push args for the call 483 byte(vm.PUSH1), 0, // out size 484 byte(vm.DUP1), // out offset 485 byte(vm.PUSH1), 0x20, // in size 486 byte(vm.PUSH1), 0x00, // in offset 487 byte(vm.PUSH1), 0x00, // value 488 byte(vm.PUSH1), 0xEE, // address of reverting contract 489 byte(vm.GAS), // gas 490 byte(vm.CALL), 491 byte(vm.POP), // pop return value 492 byte(vm.PUSH1), 0, // jumpdestination 493 byte(vm.JUMP), 494 } 495 496 //tracer := vm.NewJSONLogger(nil, os.Stdout) 497 //Execute(loopingCode, nil, &Config{ 498 // EVMConfig: vm.Config{ 499 // Debug: true, 500 // Tracer: tracer, 501 // }}) 502 // 100M gas 503 benchmarkNonModifyingCode(100000000, staticCallIdentity, "staticcall-identity-100M", "", b) 504 benchmarkNonModifyingCode(100000000, callIdentity, "call-identity-100M", "", b) 505 benchmarkNonModifyingCode(100000000, loopingCode, "loop-100M", "", b) 506 benchmarkNonModifyingCode(100000000, callInexistant, "call-nonexist-100M", "", b) 507 benchmarkNonModifyingCode(100000000, callEOA, "call-EOA-100M", "", b) 508 benchmarkNonModifyingCode(100000000, calllRevertingContractWithInput, "call-reverting-100M", "", b) 509 510 //benchmarkNonModifyingCode(10000000, staticCallIdentity, "staticcall-identity-10M", b) 511 //benchmarkNonModifyingCode(10000000, loopingCode, "loop-10M", b) 512 } 513 514 // TestEip2929Cases contains various testcases that are used for 515 // EIP-2929 about gas repricings 516 func TestEip2929Cases(t *testing.T) { 517 t.Skip("Test only useful for generating documentation") 518 id := 1 519 prettyPrint := func(comment string, code []byte) { 520 521 instrs := make([]string, 0) 522 it := asm.NewInstructionIterator(code) 523 for it.Next() { 524 if it.Arg() != nil && 0 < len(it.Arg()) { 525 instrs = append(instrs, fmt.Sprintf("%v 0x%x", it.Op(), it.Arg())) 526 } else { 527 instrs = append(instrs, fmt.Sprintf("%v", it.Op())) 528 } 529 } 530 ops := strings.Join(instrs, ", ") 531 fmt.Printf("### Case %d\n\n", id) 532 id++ 533 fmt.Printf("%v\n\nBytecode: \n```\n0x%x\n```\nOperations: \n```\n%v\n```\n\n", 534 comment, 535 code, ops) 536 Execute(code, nil, &Config{ 537 EVMConfig: vm.Config{ 538 Debug: true, 539 Tracer: vm.NewMarkdownLogger(nil, os.Stdout), 540 ExtraEips: []int{2929}, 541 }, 542 }) 543 } 544 545 { // First eip testcase 546 code := []byte{ 547 // Three checks against a precompile 548 byte(vm.PUSH1), 1, byte(vm.EXTCODEHASH), byte(vm.POP), 549 byte(vm.PUSH1), 2, byte(vm.EXTCODESIZE), byte(vm.POP), 550 byte(vm.PUSH1), 3, byte(vm.BALANCE), byte(vm.POP), 551 // Three checks against a non-precompile 552 byte(vm.PUSH1), 0xf1, byte(vm.EXTCODEHASH), byte(vm.POP), 553 byte(vm.PUSH1), 0xf2, byte(vm.EXTCODESIZE), byte(vm.POP), 554 byte(vm.PUSH1), 0xf3, byte(vm.BALANCE), byte(vm.POP), 555 // Same three checks (should be cheaper) 556 byte(vm.PUSH1), 0xf2, byte(vm.EXTCODEHASH), byte(vm.POP), 557 byte(vm.PUSH1), 0xf3, byte(vm.EXTCODESIZE), byte(vm.POP), 558 byte(vm.PUSH1), 0xf1, byte(vm.BALANCE), byte(vm.POP), 559 // Check the origin, and the 'this' 560 byte(vm.ORIGIN), byte(vm.BALANCE), byte(vm.POP), 561 byte(vm.ADDRESS), byte(vm.BALANCE), byte(vm.POP), 562 563 byte(vm.STOP), 564 } 565 prettyPrint("This checks `EXT`(codehash,codesize,balance) of precompiles, which should be `100`, "+ 566 "and later checks the same operations twice against some non-precompiles. "+ 567 "Those are cheaper second time they are accessed. Lastly, it checks the `BALANCE` of `origin` and `this`.", code) 568 } 569 570 { // EXTCODECOPY 571 code := []byte{ 572 // extcodecopy( 0xff,0,0,0,0) 573 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 574 byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY), 575 // extcodecopy( 0xff,0,0,0,0) 576 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 577 byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY), 578 // extcodecopy( this,0,0,0,0) 579 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 580 byte(vm.ADDRESS), byte(vm.EXTCODECOPY), 581 582 byte(vm.STOP), 583 } 584 prettyPrint("This checks `extcodecopy( 0xff,0,0,0,0)` twice, (should be expensive first time), "+ 585 "and then does `extcodecopy( this,0,0,0,0)`.", code) 586 } 587 588 { // SLOAD + SSTORE 589 code := []byte{ 590 591 // Add slot `0x1` to access list 592 byte(vm.PUSH1), 0x01, byte(vm.SLOAD), byte(vm.POP), // SLOAD( 0x1) (add to access list) 593 // Write to `0x1` which is already in access list 594 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x01, byte(vm.SSTORE), // SSTORE( loc: 0x01, val: 0x11) 595 // Write to `0x2` which is not in access list 596 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11) 597 // Write again to `0x2` 598 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11) 599 // Read slot in access list (0x2) 600 byte(vm.PUSH1), 0x02, byte(vm.SLOAD), // SLOAD( 0x2) 601 // Read slot in access list (0x1) 602 byte(vm.PUSH1), 0x01, byte(vm.SLOAD), // SLOAD( 0x1) 603 } 604 prettyPrint("This checks `sload( 0x1)` followed by `sstore(loc: 0x01, val:0x11)`, then 'naked' sstore:"+ 605 "`sstore(loc: 0x02, val:0x11)` twice, and `sload(0x2)`, `sload(0x1)`. ", code) 606 } 607 { // Call variants 608 code := []byte{ 609 // identity precompile 610 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 611 byte(vm.PUSH1), 0x04, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP), 612 613 // random account - call 1 614 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 615 byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP), 616 617 // random account - call 2 618 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 619 byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.STATICCALL), byte(vm.POP), 620 } 621 prettyPrint("This calls the `identity`-precompile (cheap), then calls an account (expensive) and `staticcall`s the same"+ 622 "account (cheap)", code) 623 } 624 } 625 626 // TestColdAccountAccessCost test that the cold account access cost is reported 627 // correctly 628 // see: https://github.com/ethereum/go-ethereum/issues/22649 629 func TestColdAccountAccessCost(t *testing.T) { 630 for i, tc := range []struct { 631 code []byte 632 step int 633 want uint64 634 }{ 635 { // EXTCODEHASH(0xff) 636 code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.EXTCODEHASH), byte(vm.POP)}, 637 step: 1, 638 want: 2600, 639 }, 640 { // BALANCE(0xff) 641 code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.BALANCE), byte(vm.POP)}, 642 step: 1, 643 want: 2600, 644 }, 645 { // CALL(0xff) 646 code: []byte{ 647 byte(vm.PUSH1), 0x0, 648 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 649 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALL), byte(vm.POP), 650 }, 651 step: 7, 652 want: 2855, 653 }, 654 { // CALLCODE(0xff) 655 code: []byte{ 656 byte(vm.PUSH1), 0x0, 657 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 658 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALLCODE), byte(vm.POP), 659 }, 660 step: 7, 661 want: 2855, 662 }, 663 { // DELEGATECALL(0xff) 664 code: []byte{ 665 byte(vm.PUSH1), 0x0, 666 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 667 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.DELEGATECALL), byte(vm.POP), 668 }, 669 step: 6, 670 want: 2855, 671 }, 672 { // STATICCALL(0xff) 673 code: []byte{ 674 byte(vm.PUSH1), 0x0, 675 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 676 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.STATICCALL), byte(vm.POP), 677 }, 678 step: 6, 679 want: 2855, 680 }, 681 { // SELFDESTRUCT(0xff) 682 code: []byte{ 683 byte(vm.PUSH1), 0xff, byte(vm.SELFDESTRUCT), 684 }, 685 step: 1, 686 want: 7600, 687 }, 688 } { 689 tracer := vm.NewStructLogger(nil) 690 Execute(tc.code, nil, &Config{ 691 EVMConfig: vm.Config{ 692 Debug: true, 693 Tracer: tracer, 694 }, 695 }) 696 have := tracer.StructLogs()[tc.step].GasCost 697 if want := tc.want; have != want { 698 for ii, op := range tracer.StructLogs() { 699 t.Logf("%d: %v %d", ii, op.OpName(), op.GasCost) 700 } 701 t.Fatalf("tescase %d, gas report wrong, step %d, have %d want %d", i, tc.step, have, want) 702 } 703 } 704 } 705 706 func TestRuntimeJSTracer(t *testing.T) { 707 jsTracers := []string{ 708 `{enters: 0, exits: 0, enterGas: 0, gasUsed: 0, steps:0, 709 step: function() { this.steps++}, 710 fault: function() {}, 711 result: function() { 712 return [this.enters, this.exits,this.enterGas,this.gasUsed, this.steps].join(",") 713 }, 714 enter: function(frame) { 715 this.enters++; 716 this.enterGas = frame.getGas(); 717 }, 718 exit: function(res) { 719 this.exits++; 720 this.gasUsed = res.getGasUsed(); 721 }}`, 722 `{enters: 0, exits: 0, enterGas: 0, gasUsed: 0, steps:0, 723 fault: function() {}, 724 result: function() { 725 return [this.enters, this.exits,this.enterGas,this.gasUsed, this.steps].join(",") 726 }, 727 enter: function(frame) { 728 this.enters++; 729 this.enterGas = frame.getGas(); 730 }, 731 exit: function(res) { 732 this.exits++; 733 this.gasUsed = res.getGasUsed(); 734 }}`} 735 tests := []struct { 736 code []byte 737 // One result per tracer 738 results []string 739 }{ 740 { 741 // CREATE 742 code: []byte{ 743 // Store initcode in memory at 0x00 (5 bytes left-padded to 32 bytes) 744 byte(vm.PUSH5), 745 // Init code: PUSH1 0, PUSH1 0, RETURN (3 steps) 746 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN), 747 byte(vm.PUSH1), 0, 748 byte(vm.MSTORE), 749 // length, offset, value 750 byte(vm.PUSH1), 5, byte(vm.PUSH1), 27, byte(vm.PUSH1), 0, 751 byte(vm.CREATE), 752 byte(vm.POP), 753 }, 754 results: []string{`"1,1,4294935775,6,12"`, `"1,1,4294935775,6,0"`}, 755 }, 756 { 757 // CREATE2 758 code: []byte{ 759 // Store initcode in memory at 0x00 (5 bytes left-padded to 32 bytes) 760 byte(vm.PUSH5), 761 // Init code: PUSH1 0, PUSH1 0, RETURN (3 steps) 762 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN), 763 byte(vm.PUSH1), 0, 764 byte(vm.MSTORE), 765 // salt, length, offset, value 766 byte(vm.PUSH1), 1, byte(vm.PUSH1), 5, byte(vm.PUSH1), 27, byte(vm.PUSH1), 0, 767 byte(vm.CREATE2), 768 byte(vm.POP), 769 }, 770 results: []string{`"1,1,4294935766,6,13"`, `"1,1,4294935766,6,0"`}, 771 }, 772 { 773 // CALL 774 code: []byte{ 775 // outsize, outoffset, insize, inoffset 776 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 777 byte(vm.PUSH1), 0, // value 778 byte(vm.PUSH1), 0xbb, //address 779 byte(vm.GAS), // gas 780 byte(vm.CALL), 781 byte(vm.POP), 782 }, 783 results: []string{`"1,1,4294964716,6,13"`, `"1,1,4294964716,6,0"`}, 784 }, 785 { 786 // CALLCODE 787 code: []byte{ 788 // outsize, outoffset, insize, inoffset 789 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 790 byte(vm.PUSH1), 0, // value 791 byte(vm.PUSH1), 0xcc, //address 792 byte(vm.GAS), // gas 793 byte(vm.CALLCODE), 794 byte(vm.POP), 795 }, 796 results: []string{`"1,1,4294964716,6,13"`, `"1,1,4294964716,6,0"`}, 797 }, 798 { 799 // STATICCALL 800 code: []byte{ 801 // outsize, outoffset, insize, inoffset 802 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 803 byte(vm.PUSH1), 0xdd, //address 804 byte(vm.GAS), // gas 805 byte(vm.STATICCALL), 806 byte(vm.POP), 807 }, 808 results: []string{`"1,1,4294964719,6,12"`, `"1,1,4294964719,6,0"`}, 809 }, 810 { 811 // DELEGATECALL 812 code: []byte{ 813 // outsize, outoffset, insize, inoffset 814 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 815 byte(vm.PUSH1), 0xee, //address 816 byte(vm.GAS), // gas 817 byte(vm.DELEGATECALL), 818 byte(vm.POP), 819 }, 820 results: []string{`"1,1,4294964719,6,12"`, `"1,1,4294964719,6,0"`}, 821 }, 822 { 823 // CALL self-destructing contract 824 code: []byte{ 825 // outsize, outoffset, insize, inoffset 826 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 827 byte(vm.PUSH1), 0, // value 828 byte(vm.PUSH1), 0xff, //address 829 byte(vm.GAS), // gas 830 byte(vm.CALL), 831 byte(vm.POP), 832 }, 833 results: []string{`"2,2,0,5003,12"`, `"2,2,0,5003,0"`}, 834 }, 835 } 836 calleeCode := []byte{ 837 byte(vm.PUSH1), 0, 838 byte(vm.PUSH1), 0, 839 byte(vm.RETURN), 840 } 841 depressedCode := []byte{ 842 byte(vm.PUSH1), 0xaa, 843 byte(vm.SELFDESTRUCT), 844 } 845 main := common.HexToAddress("0xaa") 846 for i, jsTracer := range jsTracers { 847 for j, tc := range tests { 848 statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 849 statedb.SetCode(main, tc.code) 850 statedb.SetCode(common.HexToAddress("0xbb"), calleeCode) 851 statedb.SetCode(common.HexToAddress("0xcc"), calleeCode) 852 statedb.SetCode(common.HexToAddress("0xdd"), calleeCode) 853 statedb.SetCode(common.HexToAddress("0xee"), calleeCode) 854 statedb.SetCode(common.HexToAddress("0xff"), depressedCode) 855 856 tracer, err := tracers.New(jsTracer, new(tracers.Context)) 857 if err != nil { 858 t.Fatal(err) 859 } 860 _, _, err = Call(main, nil, &Config{ 861 State: statedb, 862 EVMConfig: vm.Config{ 863 Debug: true, 864 Tracer: tracer, 865 }}) 866 if err != nil { 867 t.Fatal("didn't expect error", err) 868 } 869 res, err := tracer.GetResult() 870 if err != nil { 871 t.Fatal(err) 872 } 873 if have, want := string(res), tc.results[i]; have != want { 874 t.Errorf("wrong result for tracer %d testcase %d, have \n%v\nwant\n%v\n", i, j, have, want) 875 } 876 } 877 } 878 } 879 880 func TestJSTracerCreateTx(t *testing.T) { 881 jsTracer := ` 882 {enters: 0, exits: 0, 883 step: function() {}, 884 fault: function() {}, 885 result: function() { return [this.enters, this.exits].join(",") }, 886 enter: function(frame) { this.enters++ }, 887 exit: function(res) { this.exits++ }}` 888 code := []byte{byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN)} 889 890 statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 891 tracer, err := tracers.New(jsTracer, new(tracers.Context)) 892 if err != nil { 893 t.Fatal(err) 894 } 895 _, _, _, err = Create(code, &Config{ 896 State: statedb, 897 EVMConfig: vm.Config{ 898 Debug: true, 899 Tracer: tracer, 900 }}) 901 if err != nil { 902 t.Fatal(err) 903 } 904 905 res, err := tracer.GetResult() 906 if err != nil { 907 t.Fatal(err) 908 } 909 if have, want := string(res), `"0,0"`; have != want { 910 t.Errorf("wrong result for tracer, have \n%v\nwant\n%v\n", have, want) 911 } 912 } 913 914 func BenchmarkTracerStepVsCallFrame(b *testing.B) { 915 // Simply pushes and pops some values in a loop 916 code := []byte{ 917 byte(vm.JUMPDEST), 918 byte(vm.PUSH1), 0, 919 byte(vm.PUSH1), 0, 920 byte(vm.POP), 921 byte(vm.POP), 922 byte(vm.PUSH1), 0, // jumpdestination 923 byte(vm.JUMP), 924 } 925 926 stepTracer := ` 927 { 928 step: function() {}, 929 fault: function() {}, 930 result: function() {}, 931 }` 932 callFrameTracer := ` 933 { 934 enter: function() {}, 935 exit: function() {}, 936 fault: function() {}, 937 result: function() {}, 938 }` 939 940 benchmarkNonModifyingCode(10000000, code, "tracer-step-10M", stepTracer, b) 941 benchmarkNonModifyingCode(10000000, code, "tracer-call-frame-10M", callFrameTracer, b) 942 }