github.com/codysnider/go-ethereum@v1.10.18-0.20220420071915-14f4ae99222a/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/eth/tracers/logger" 38 "github.com/ethereum/go-ethereum/params" 39 40 // force-load js tracers to trigger registration 41 _ "github.com/ethereum/go-ethereum/eth/tracers/js" 42 ) 43 44 func TestDefaults(t *testing.T) { 45 cfg := new(Config) 46 setDefaults(cfg) 47 48 if cfg.Difficulty == nil { 49 t.Error("expected difficulty to be non nil") 50 } 51 52 if cfg.Time == nil { 53 t.Error("expected time to be non nil") 54 } 55 if cfg.GasLimit == 0 { 56 t.Error("didn't expect gaslimit to be zero") 57 } 58 if cfg.GasPrice == nil { 59 t.Error("expected time to be non nil") 60 } 61 if cfg.Value == nil { 62 t.Error("expected time to be non nil") 63 } 64 if cfg.GetHashFn == nil { 65 t.Error("expected time to be non nil") 66 } 67 if cfg.BlockNumber == nil { 68 t.Error("expected block number to be non nil") 69 } 70 } 71 72 func TestEVM(t *testing.T) { 73 defer func() { 74 if r := recover(); r != nil { 75 t.Fatalf("crashed with: %v", r) 76 } 77 }() 78 79 Execute([]byte{ 80 byte(vm.DIFFICULTY), 81 byte(vm.TIMESTAMP), 82 byte(vm.GASLIMIT), 83 byte(vm.PUSH1), 84 byte(vm.ORIGIN), 85 byte(vm.BLOCKHASH), 86 byte(vm.COINBASE), 87 }, nil, nil) 88 } 89 90 func TestExecute(t *testing.T) { 91 ret, _, err := Execute([]byte{ 92 byte(vm.PUSH1), 10, 93 byte(vm.PUSH1), 0, 94 byte(vm.MSTORE), 95 byte(vm.PUSH1), 32, 96 byte(vm.PUSH1), 0, 97 byte(vm.RETURN), 98 }, nil, nil) 99 if err != nil { 100 t.Fatal("didn't expect error", err) 101 } 102 103 num := new(big.Int).SetBytes(ret) 104 if num.Cmp(big.NewInt(10)) != 0 { 105 t.Error("Expected 10, got", num) 106 } 107 } 108 109 func TestCall(t *testing.T) { 110 state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 111 address := common.HexToAddress("0x0a") 112 state.SetCode(address, []byte{ 113 byte(vm.PUSH1), 10, 114 byte(vm.PUSH1), 0, 115 byte(vm.MSTORE), 116 byte(vm.PUSH1), 32, 117 byte(vm.PUSH1), 0, 118 byte(vm.RETURN), 119 }) 120 121 ret, _, err := Call(address, nil, &Config{State: state}) 122 if err != nil { 123 t.Fatal("didn't expect error", err) 124 } 125 126 num := new(big.Int).SetBytes(ret) 127 if num.Cmp(big.NewInt(10)) != 0 { 128 t.Error("Expected 10, got", num) 129 } 130 } 131 132 func BenchmarkCall(b *testing.B) { 133 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"}]` 134 135 var code = common.Hex2Bytes("6060604052361561006c5760e060020a600035046308551a53811461007457806335a063b4146100865780633fa4f245146100a6578063590e1ae3146100af5780637150d8ae146100cf57806373fac6f0146100e1578063c19d93fb146100fe578063d696069714610112575b610131610002565b610133600154600160a060020a031681565b610131600154600160a060020a0390811633919091161461015057610002565b61014660005481565b610131600154600160a060020a039081163391909116146102d557610002565b610133600254600160a060020a031681565b610131600254600160a060020a0333811691161461023757610002565b61014660025460ff60a060020a9091041681565b61013160025460009060ff60a060020a9091041681146101cc57610002565b005b600160a060020a03166060908152602090f35b6060908152602090f35b60025460009060a060020a900460ff16811461016b57610002565b600154600160a060020a03908116908290301631606082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f72c874aeff0b183a56e2b79c71b46e1aed4dee5e09862134b8821ba2fddbf8bf9250a150565b80546002023414806101dd57610002565b6002805460a060020a60ff021973ffffffffffffffffffffffffffffffffffffffff1990911633171660a060020a1790557fd5d55c8a68912e9a110618df8d5e2e83b8d83211c57a8ddd1203df92885dc881826060a15050565b60025460019060a060020a900460ff16811461025257610002565b60025460008054600160a060020a0390921691606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517fe89152acd703c9d8c7d28829d443260b411454d45394e7995815140c8cbcbcf79250a150565b60025460019060a060020a900460ff1681146102f057610002565b6002805460008054600160a060020a0390921692909102606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f8616bbbbad963e4e65b1366f1d75dfb63f9e9704bbbf91fb01bec70849906cf79250a15056") 136 137 abi, err := abi.JSON(strings.NewReader(definition)) 138 if err != nil { 139 b.Fatal(err) 140 } 141 142 cpurchase, err := abi.Pack("confirmPurchase") 143 if err != nil { 144 b.Fatal(err) 145 } 146 creceived, err := abi.Pack("confirmReceived") 147 if err != nil { 148 b.Fatal(err) 149 } 150 refund, err := abi.Pack("refund") 151 if err != nil { 152 b.Fatal(err) 153 } 154 155 b.ResetTimer() 156 for i := 0; i < b.N; i++ { 157 for j := 0; j < 400; j++ { 158 Execute(code, cpurchase, nil) 159 Execute(code, creceived, nil) 160 Execute(code, refund, nil) 161 } 162 } 163 } 164 func benchmarkEVM_Create(bench *testing.B, code string) { 165 var ( 166 statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 167 sender = common.BytesToAddress([]byte("sender")) 168 receiver = common.BytesToAddress([]byte("receiver")) 169 ) 170 171 statedb.CreateAccount(sender) 172 statedb.SetCode(receiver, common.FromHex(code)) 173 runtimeConfig := Config{ 174 Origin: sender, 175 State: statedb, 176 GasLimit: 10000000, 177 Difficulty: big.NewInt(0x200000), 178 Time: new(big.Int).SetUint64(0), 179 Coinbase: common.Address{}, 180 BlockNumber: new(big.Int).SetUint64(1), 181 ChainConfig: ¶ms.ChainConfig{ 182 ChainID: big.NewInt(1), 183 HomesteadBlock: new(big.Int), 184 ByzantiumBlock: new(big.Int), 185 ConstantinopleBlock: new(big.Int), 186 DAOForkBlock: new(big.Int), 187 DAOForkSupport: false, 188 EIP150Block: new(big.Int), 189 EIP155Block: new(big.Int), 190 EIP158Block: new(big.Int), 191 }, 192 EVMConfig: vm.Config{}, 193 } 194 // Warm up the intpools and stuff 195 bench.ResetTimer() 196 for i := 0; i < bench.N; i++ { 197 Call(receiver, []byte{}, &runtimeConfig) 198 } 199 bench.StopTimer() 200 } 201 202 func BenchmarkEVM_CREATE_500(bench *testing.B) { 203 // initcode size 500K, repeatedly calls CREATE and then modifies the mem contents 204 benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056") 205 } 206 func BenchmarkEVM_CREATE2_500(bench *testing.B) { 207 // initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents 208 benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056") 209 } 210 func BenchmarkEVM_CREATE_1200(bench *testing.B) { 211 // initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents 212 benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056") 213 } 214 func BenchmarkEVM_CREATE2_1200(bench *testing.B) { 215 // initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents 216 benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056") 217 } 218 219 func fakeHeader(n uint64, parentHash common.Hash) *types.Header { 220 header := types.Header{ 221 Coinbase: common.HexToAddress("0x00000000000000000000000000000000deadbeef"), 222 Number: big.NewInt(int64(n)), 223 ParentHash: parentHash, 224 Time: 1000, 225 Nonce: types.BlockNonce{0x1}, 226 Extra: []byte{}, 227 Difficulty: big.NewInt(0), 228 GasLimit: 100000, 229 } 230 return &header 231 } 232 233 type dummyChain struct { 234 counter int 235 } 236 237 // Engine retrieves the chain's consensus engine. 238 func (d *dummyChain) Engine() consensus.Engine { 239 return nil 240 } 241 242 // GetHeader returns the hash corresponding to their hash. 243 func (d *dummyChain) GetHeader(h common.Hash, n uint64) *types.Header { 244 d.counter++ 245 parentHash := common.Hash{} 246 s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32) 247 copy(parentHash[:], s) 248 249 //parentHash := common.Hash{byte(n - 1)} 250 //fmt.Printf("GetHeader(%x, %d) => header with parent %x\n", h, n, parentHash) 251 return fakeHeader(n, parentHash) 252 } 253 254 // TestBlockhash tests the blockhash operation. It's a bit special, since it internally 255 // requires access to a chain reader. 256 func TestBlockhash(t *testing.T) { 257 // Current head 258 n := uint64(1000) 259 parentHash := common.Hash{} 260 s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32) 261 copy(parentHash[:], s) 262 header := fakeHeader(n, parentHash) 263 264 // This is the contract we're using. It requests the blockhash for current num (should be all zeroes), 265 // then iteratively fetches all blockhashes back to n-260. 266 // It returns 267 // 1. the first (should be zero) 268 // 2. the second (should be the parent hash) 269 // 3. the last non-zero hash 270 // By making the chain reader return hashes which correlate to the number, we can 271 // verify that it obtained the right hashes where it should 272 273 /* 274 275 pragma solidity ^0.5.3; 276 contract Hasher{ 277 278 function test() public view returns (bytes32, bytes32, bytes32){ 279 uint256 x = block.number; 280 bytes32 first; 281 bytes32 last; 282 bytes32 zero; 283 zero = blockhash(x); // Should be zeroes 284 first = blockhash(x-1); 285 for(uint256 i = 2 ; i < 260; i++){ 286 bytes32 hash = blockhash(x - i); 287 if (uint256(hash) != 0){ 288 last = hash; 289 } 290 } 291 return (zero, first, last); 292 } 293 } 294 295 */ 296 // The contract above 297 data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029") 298 // The method call to 'test()' 299 input := common.Hex2Bytes("f8a8fd6d") 300 chain := &dummyChain{} 301 ret, _, err := Execute(data, input, &Config{ 302 GetHashFn: core.GetHashFn(header, chain), 303 BlockNumber: new(big.Int).Set(header.Number), 304 }) 305 if err != nil { 306 t.Fatalf("expected no error, got %v", err) 307 } 308 if len(ret) != 96 { 309 t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret)) 310 } 311 312 zero := new(big.Int).SetBytes(ret[0:32]) 313 first := new(big.Int).SetBytes(ret[32:64]) 314 last := new(big.Int).SetBytes(ret[64:96]) 315 if zero.BitLen() != 0 { 316 t.Fatalf("expected zeroes, got %x", ret[0:32]) 317 } 318 if first.Uint64() != 999 { 319 t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64]) 320 } 321 if last.Uint64() != 744 { 322 t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96]) 323 } 324 if exp, got := 255, chain.counter; exp != got { 325 t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got) 326 } 327 } 328 329 type stepCounter struct { 330 inner *logger.JSONLogger 331 steps int 332 } 333 334 func (s *stepCounter) CaptureStart(env *vm.EVM, from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) { 335 } 336 337 func (s *stepCounter) CaptureFault(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, depth int, err error) { 338 } 339 340 func (s *stepCounter) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) {} 341 342 func (s *stepCounter) CaptureState(pc uint64, op vm.OpCode, gas, cost uint64, scope *vm.ScopeContext, rData []byte, depth int, err error) { 343 s.steps++ 344 // Enable this for more output 345 //s.inner.CaptureState(env, pc, op, gas, cost, memory, stack, rStack, contract, depth, err) 346 } 347 348 // benchmarkNonModifyingCode benchmarks code, but if the code modifies the 349 // state, this should not be used, since it does not reset the state between runs. 350 func benchmarkNonModifyingCode(gas uint64, code []byte, name string, tracerCode string, b *testing.B) { 351 cfg := new(Config) 352 setDefaults(cfg) 353 cfg.State, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 354 cfg.GasLimit = gas 355 if len(tracerCode) > 0 { 356 tracer, err := tracers.New(tracerCode, new(tracers.Context)) 357 if err != nil { 358 b.Fatal(err) 359 } 360 cfg.EVMConfig = vm.Config{ 361 Debug: true, 362 Tracer: tracer, 363 } 364 } 365 var ( 366 destination = common.BytesToAddress([]byte("contract")) 367 vmenv = NewEnv(cfg) 368 sender = vm.AccountRef(cfg.Origin) 369 ) 370 cfg.State.CreateAccount(destination) 371 eoa := common.HexToAddress("E0") 372 { 373 cfg.State.CreateAccount(eoa) 374 cfg.State.SetNonce(eoa, 100) 375 } 376 reverting := common.HexToAddress("EE") 377 { 378 cfg.State.CreateAccount(reverting) 379 cfg.State.SetCode(reverting, []byte{ 380 byte(vm.PUSH1), 0x00, 381 byte(vm.PUSH1), 0x00, 382 byte(vm.REVERT), 383 }) 384 } 385 386 //cfg.State.CreateAccount(cfg.Origin) 387 // set the receiver's (the executing contract) code for execution. 388 cfg.State.SetCode(destination, code) 389 vmenv.Call(sender, destination, nil, gas, cfg.Value) 390 391 b.Run(name, func(b *testing.B) { 392 b.ReportAllocs() 393 for i := 0; i < b.N; i++ { 394 vmenv.Call(sender, destination, nil, gas, cfg.Value) 395 } 396 }) 397 } 398 399 // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG 400 // 55 ms 401 func BenchmarkSimpleLoop(b *testing.B) { 402 403 staticCallIdentity := []byte{ 404 byte(vm.JUMPDEST), // [ count ] 405 // push args for the call 406 byte(vm.PUSH1), 0, // out size 407 byte(vm.DUP1), // out offset 408 byte(vm.DUP1), // out insize 409 byte(vm.DUP1), // in offset 410 byte(vm.PUSH1), 0x4, // address of identity 411 byte(vm.GAS), // gas 412 byte(vm.STATICCALL), 413 byte(vm.POP), // pop return value 414 byte(vm.PUSH1), 0, // jumpdestination 415 byte(vm.JUMP), 416 } 417 418 callIdentity := []byte{ 419 byte(vm.JUMPDEST), // [ count ] 420 // push args for the call 421 byte(vm.PUSH1), 0, // out size 422 byte(vm.DUP1), // out offset 423 byte(vm.DUP1), // out insize 424 byte(vm.DUP1), // in offset 425 byte(vm.DUP1), // value 426 byte(vm.PUSH1), 0x4, // address of identity 427 byte(vm.GAS), // gas 428 byte(vm.CALL), 429 byte(vm.POP), // pop return value 430 byte(vm.PUSH1), 0, // jumpdestination 431 byte(vm.JUMP), 432 } 433 434 callInexistant := []byte{ 435 byte(vm.JUMPDEST), // [ count ] 436 // push args for the call 437 byte(vm.PUSH1), 0, // out size 438 byte(vm.DUP1), // out offset 439 byte(vm.DUP1), // out insize 440 byte(vm.DUP1), // in offset 441 byte(vm.DUP1), // value 442 byte(vm.PUSH1), 0xff, // address of existing contract 443 byte(vm.GAS), // gas 444 byte(vm.CALL), 445 byte(vm.POP), // pop return value 446 byte(vm.PUSH1), 0, // jumpdestination 447 byte(vm.JUMP), 448 } 449 450 callEOA := []byte{ 451 byte(vm.JUMPDEST), // [ count ] 452 // push args for the call 453 byte(vm.PUSH1), 0, // out size 454 byte(vm.DUP1), // out offset 455 byte(vm.DUP1), // out insize 456 byte(vm.DUP1), // in offset 457 byte(vm.DUP1), // value 458 byte(vm.PUSH1), 0xE0, // address of EOA 459 byte(vm.GAS), // gas 460 byte(vm.CALL), 461 byte(vm.POP), // pop return value 462 byte(vm.PUSH1), 0, // jumpdestination 463 byte(vm.JUMP), 464 } 465 466 loopingCode := []byte{ 467 byte(vm.JUMPDEST), // [ count ] 468 // push args for the call 469 byte(vm.PUSH1), 0, // out size 470 byte(vm.DUP1), // out offset 471 byte(vm.DUP1), // out insize 472 byte(vm.DUP1), // in offset 473 byte(vm.PUSH1), 0x4, // address of identity 474 byte(vm.GAS), // gas 475 476 byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), 477 byte(vm.PUSH1), 0, // jumpdestination 478 byte(vm.JUMP), 479 } 480 481 calllRevertingContractWithInput := []byte{ 482 byte(vm.JUMPDEST), // 483 // push args for the call 484 byte(vm.PUSH1), 0, // out size 485 byte(vm.DUP1), // out offset 486 byte(vm.PUSH1), 0x20, // in size 487 byte(vm.PUSH1), 0x00, // in offset 488 byte(vm.PUSH1), 0x00, // value 489 byte(vm.PUSH1), 0xEE, // address of reverting contract 490 byte(vm.GAS), // gas 491 byte(vm.CALL), 492 byte(vm.POP), // pop return value 493 byte(vm.PUSH1), 0, // jumpdestination 494 byte(vm.JUMP), 495 } 496 497 //tracer := logger.NewJSONLogger(nil, os.Stdout) 498 //Execute(loopingCode, nil, &Config{ 499 // EVMConfig: vm.Config{ 500 // Debug: true, 501 // Tracer: tracer, 502 // }}) 503 // 100M gas 504 benchmarkNonModifyingCode(100000000, staticCallIdentity, "staticcall-identity-100M", "", b) 505 benchmarkNonModifyingCode(100000000, callIdentity, "call-identity-100M", "", b) 506 benchmarkNonModifyingCode(100000000, loopingCode, "loop-100M", "", b) 507 benchmarkNonModifyingCode(100000000, callInexistant, "call-nonexist-100M", "", b) 508 benchmarkNonModifyingCode(100000000, callEOA, "call-EOA-100M", "", b) 509 benchmarkNonModifyingCode(100000000, calllRevertingContractWithInput, "call-reverting-100M", "", b) 510 511 //benchmarkNonModifyingCode(10000000, staticCallIdentity, "staticcall-identity-10M", b) 512 //benchmarkNonModifyingCode(10000000, loopingCode, "loop-10M", b) 513 } 514 515 // TestEip2929Cases contains various testcases that are used for 516 // EIP-2929 about gas repricings 517 func TestEip2929Cases(t *testing.T) { 518 t.Skip("Test only useful for generating documentation") 519 id := 1 520 prettyPrint := func(comment string, code []byte) { 521 522 instrs := make([]string, 0) 523 it := asm.NewInstructionIterator(code) 524 for it.Next() { 525 if it.Arg() != nil && 0 < len(it.Arg()) { 526 instrs = append(instrs, fmt.Sprintf("%v 0x%x", it.Op(), it.Arg())) 527 } else { 528 instrs = append(instrs, fmt.Sprintf("%v", it.Op())) 529 } 530 } 531 ops := strings.Join(instrs, ", ") 532 fmt.Printf("### Case %d\n\n", id) 533 id++ 534 fmt.Printf("%v\n\nBytecode: \n```\n0x%x\n```\nOperations: \n```\n%v\n```\n\n", 535 comment, 536 code, ops) 537 Execute(code, nil, &Config{ 538 EVMConfig: vm.Config{ 539 Debug: true, 540 Tracer: logger.NewMarkdownLogger(nil, os.Stdout), 541 ExtraEips: []int{2929}, 542 }, 543 }) 544 } 545 546 { // First eip testcase 547 code := []byte{ 548 // Three checks against a precompile 549 byte(vm.PUSH1), 1, byte(vm.EXTCODEHASH), byte(vm.POP), 550 byte(vm.PUSH1), 2, byte(vm.EXTCODESIZE), byte(vm.POP), 551 byte(vm.PUSH1), 3, byte(vm.BALANCE), byte(vm.POP), 552 // Three checks against a non-precompile 553 byte(vm.PUSH1), 0xf1, byte(vm.EXTCODEHASH), byte(vm.POP), 554 byte(vm.PUSH1), 0xf2, byte(vm.EXTCODESIZE), byte(vm.POP), 555 byte(vm.PUSH1), 0xf3, byte(vm.BALANCE), byte(vm.POP), 556 // Same three checks (should be cheaper) 557 byte(vm.PUSH1), 0xf2, byte(vm.EXTCODEHASH), byte(vm.POP), 558 byte(vm.PUSH1), 0xf3, byte(vm.EXTCODESIZE), byte(vm.POP), 559 byte(vm.PUSH1), 0xf1, byte(vm.BALANCE), byte(vm.POP), 560 // Check the origin, and the 'this' 561 byte(vm.ORIGIN), byte(vm.BALANCE), byte(vm.POP), 562 byte(vm.ADDRESS), byte(vm.BALANCE), byte(vm.POP), 563 564 byte(vm.STOP), 565 } 566 prettyPrint("This checks `EXT`(codehash,codesize,balance) of precompiles, which should be `100`, "+ 567 "and later checks the same operations twice against some non-precompiles. "+ 568 "Those are cheaper second time they are accessed. Lastly, it checks the `BALANCE` of `origin` and `this`.", code) 569 } 570 571 { // EXTCODECOPY 572 code := []byte{ 573 // extcodecopy( 0xff,0,0,0,0) 574 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 575 byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY), 576 // extcodecopy( 0xff,0,0,0,0) 577 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 578 byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY), 579 // extcodecopy( this,0,0,0,0) 580 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 581 byte(vm.ADDRESS), byte(vm.EXTCODECOPY), 582 583 byte(vm.STOP), 584 } 585 prettyPrint("This checks `extcodecopy( 0xff,0,0,0,0)` twice, (should be expensive first time), "+ 586 "and then does `extcodecopy( this,0,0,0,0)`.", code) 587 } 588 589 { // SLOAD + SSTORE 590 code := []byte{ 591 592 // Add slot `0x1` to access list 593 byte(vm.PUSH1), 0x01, byte(vm.SLOAD), byte(vm.POP), // SLOAD( 0x1) (add to access list) 594 // Write to `0x1` which is already in access list 595 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x01, byte(vm.SSTORE), // SSTORE( loc: 0x01, val: 0x11) 596 // Write to `0x2` which is not in access list 597 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11) 598 // Write again to `0x2` 599 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11) 600 // Read slot in access list (0x2) 601 byte(vm.PUSH1), 0x02, byte(vm.SLOAD), // SLOAD( 0x2) 602 // Read slot in access list (0x1) 603 byte(vm.PUSH1), 0x01, byte(vm.SLOAD), // SLOAD( 0x1) 604 } 605 prettyPrint("This checks `sload( 0x1)` followed by `sstore(loc: 0x01, val:0x11)`, then 'naked' sstore:"+ 606 "`sstore(loc: 0x02, val:0x11)` twice, and `sload(0x2)`, `sload(0x1)`. ", code) 607 } 608 { // Call variants 609 code := []byte{ 610 // identity precompile 611 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 612 byte(vm.PUSH1), 0x04, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP), 613 614 // random account - call 1 615 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 616 byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP), 617 618 // random account - call 2 619 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 620 byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.STATICCALL), byte(vm.POP), 621 } 622 prettyPrint("This calls the `identity`-precompile (cheap), then calls an account (expensive) and `staticcall`s the same"+ 623 "account (cheap)", code) 624 } 625 } 626 627 // TestColdAccountAccessCost test that the cold account access cost is reported 628 // correctly 629 // see: https://github.com/ethereum/go-ethereum/issues/22649 630 func TestColdAccountAccessCost(t *testing.T) { 631 for i, tc := range []struct { 632 code []byte 633 step int 634 want uint64 635 }{ 636 { // EXTCODEHASH(0xff) 637 code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.EXTCODEHASH), byte(vm.POP)}, 638 step: 1, 639 want: 2600, 640 }, 641 { // BALANCE(0xff) 642 code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.BALANCE), byte(vm.POP)}, 643 step: 1, 644 want: 2600, 645 }, 646 { // CALL(0xff) 647 code: []byte{ 648 byte(vm.PUSH1), 0x0, 649 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 650 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALL), byte(vm.POP), 651 }, 652 step: 7, 653 want: 2855, 654 }, 655 { // CALLCODE(0xff) 656 code: []byte{ 657 byte(vm.PUSH1), 0x0, 658 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 659 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALLCODE), byte(vm.POP), 660 }, 661 step: 7, 662 want: 2855, 663 }, 664 { // DELEGATECALL(0xff) 665 code: []byte{ 666 byte(vm.PUSH1), 0x0, 667 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 668 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.DELEGATECALL), byte(vm.POP), 669 }, 670 step: 6, 671 want: 2855, 672 }, 673 { // STATICCALL(0xff) 674 code: []byte{ 675 byte(vm.PUSH1), 0x0, 676 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 677 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.STATICCALL), byte(vm.POP), 678 }, 679 step: 6, 680 want: 2855, 681 }, 682 { // SELFDESTRUCT(0xff) 683 code: []byte{ 684 byte(vm.PUSH1), 0xff, byte(vm.SELFDESTRUCT), 685 }, 686 step: 1, 687 want: 7600, 688 }, 689 } { 690 tracer := logger.NewStructLogger(nil) 691 Execute(tc.code, nil, &Config{ 692 EVMConfig: vm.Config{ 693 Debug: true, 694 Tracer: tracer, 695 }, 696 }) 697 have := tracer.StructLogs()[tc.step].GasCost 698 if want := tc.want; have != want { 699 for ii, op := range tracer.StructLogs() { 700 t.Logf("%d: %v %d", ii, op.OpName(), op.GasCost) 701 } 702 t.Fatalf("tescase %d, gas report wrong, step %d, have %d want %d", i, tc.step, have, want) 703 } 704 } 705 } 706 707 func TestRuntimeJSTracer(t *testing.T) { 708 jsTracers := []string{ 709 `{enters: 0, exits: 0, enterGas: 0, gasUsed: 0, steps:0, 710 step: function() { this.steps++}, 711 fault: function() {}, 712 result: function() { 713 return [this.enters, this.exits,this.enterGas,this.gasUsed, this.steps].join(",") 714 }, 715 enter: function(frame) { 716 this.enters++; 717 this.enterGas = frame.getGas(); 718 }, 719 exit: function(res) { 720 this.exits++; 721 this.gasUsed = res.getGasUsed(); 722 }}`, 723 `{enters: 0, exits: 0, enterGas: 0, gasUsed: 0, steps:0, 724 fault: function() {}, 725 result: function() { 726 return [this.enters, this.exits,this.enterGas,this.gasUsed, this.steps].join(",") 727 }, 728 enter: function(frame) { 729 this.enters++; 730 this.enterGas = frame.getGas(); 731 }, 732 exit: function(res) { 733 this.exits++; 734 this.gasUsed = res.getGasUsed(); 735 }}`} 736 tests := []struct { 737 code []byte 738 // One result per tracer 739 results []string 740 }{ 741 { 742 // CREATE 743 code: []byte{ 744 // Store initcode in memory at 0x00 (5 bytes left-padded to 32 bytes) 745 byte(vm.PUSH5), 746 // Init code: PUSH1 0, PUSH1 0, RETURN (3 steps) 747 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN), 748 byte(vm.PUSH1), 0, 749 byte(vm.MSTORE), 750 // length, offset, value 751 byte(vm.PUSH1), 5, byte(vm.PUSH1), 27, byte(vm.PUSH1), 0, 752 byte(vm.CREATE), 753 byte(vm.POP), 754 }, 755 results: []string{`"1,1,4294935775,6,12"`, `"1,1,4294935775,6,0"`}, 756 }, 757 { 758 // CREATE2 759 code: []byte{ 760 // Store initcode in memory at 0x00 (5 bytes left-padded to 32 bytes) 761 byte(vm.PUSH5), 762 // Init code: PUSH1 0, PUSH1 0, RETURN (3 steps) 763 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN), 764 byte(vm.PUSH1), 0, 765 byte(vm.MSTORE), 766 // salt, length, offset, value 767 byte(vm.PUSH1), 1, byte(vm.PUSH1), 5, byte(vm.PUSH1), 27, byte(vm.PUSH1), 0, 768 byte(vm.CREATE2), 769 byte(vm.POP), 770 }, 771 results: []string{`"1,1,4294935766,6,13"`, `"1,1,4294935766,6,0"`}, 772 }, 773 { 774 // CALL 775 code: []byte{ 776 // outsize, outoffset, insize, inoffset 777 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 778 byte(vm.PUSH1), 0, // value 779 byte(vm.PUSH1), 0xbb, //address 780 byte(vm.GAS), // gas 781 byte(vm.CALL), 782 byte(vm.POP), 783 }, 784 results: []string{`"1,1,4294964716,6,13"`, `"1,1,4294964716,6,0"`}, 785 }, 786 { 787 // CALLCODE 788 code: []byte{ 789 // outsize, outoffset, insize, inoffset 790 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 791 byte(vm.PUSH1), 0, // value 792 byte(vm.PUSH1), 0xcc, //address 793 byte(vm.GAS), // gas 794 byte(vm.CALLCODE), 795 byte(vm.POP), 796 }, 797 results: []string{`"1,1,4294964716,6,13"`, `"1,1,4294964716,6,0"`}, 798 }, 799 { 800 // STATICCALL 801 code: []byte{ 802 // outsize, outoffset, insize, inoffset 803 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 804 byte(vm.PUSH1), 0xdd, //address 805 byte(vm.GAS), // gas 806 byte(vm.STATICCALL), 807 byte(vm.POP), 808 }, 809 results: []string{`"1,1,4294964719,6,12"`, `"1,1,4294964719,6,0"`}, 810 }, 811 { 812 // DELEGATECALL 813 code: []byte{ 814 // outsize, outoffset, insize, inoffset 815 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 816 byte(vm.PUSH1), 0xee, //address 817 byte(vm.GAS), // gas 818 byte(vm.DELEGATECALL), 819 byte(vm.POP), 820 }, 821 results: []string{`"1,1,4294964719,6,12"`, `"1,1,4294964719,6,0"`}, 822 }, 823 { 824 // CALL self-destructing contract 825 code: []byte{ 826 // outsize, outoffset, insize, inoffset 827 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 828 byte(vm.PUSH1), 0, // value 829 byte(vm.PUSH1), 0xff, //address 830 byte(vm.GAS), // gas 831 byte(vm.CALL), 832 byte(vm.POP), 833 }, 834 results: []string{`"2,2,0,5003,12"`, `"2,2,0,5003,0"`}, 835 }, 836 } 837 calleeCode := []byte{ 838 byte(vm.PUSH1), 0, 839 byte(vm.PUSH1), 0, 840 byte(vm.RETURN), 841 } 842 depressedCode := []byte{ 843 byte(vm.PUSH1), 0xaa, 844 byte(vm.SELFDESTRUCT), 845 } 846 main := common.HexToAddress("0xaa") 847 for i, jsTracer := range jsTracers { 848 for j, tc := range tests { 849 statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 850 statedb.SetCode(main, tc.code) 851 statedb.SetCode(common.HexToAddress("0xbb"), calleeCode) 852 statedb.SetCode(common.HexToAddress("0xcc"), calleeCode) 853 statedb.SetCode(common.HexToAddress("0xdd"), calleeCode) 854 statedb.SetCode(common.HexToAddress("0xee"), calleeCode) 855 statedb.SetCode(common.HexToAddress("0xff"), depressedCode) 856 857 tracer, err := tracers.New(jsTracer, new(tracers.Context)) 858 if err != nil { 859 t.Fatal(err) 860 } 861 _, _, err = Call(main, nil, &Config{ 862 State: statedb, 863 EVMConfig: vm.Config{ 864 Debug: true, 865 Tracer: tracer, 866 }}) 867 if err != nil { 868 t.Fatal("didn't expect error", err) 869 } 870 res, err := tracer.GetResult() 871 if err != nil { 872 t.Fatal(err) 873 } 874 if have, want := string(res), tc.results[i]; have != want { 875 t.Errorf("wrong result for tracer %d testcase %d, have \n%v\nwant\n%v\n", i, j, have, want) 876 } 877 } 878 } 879 } 880 881 func TestJSTracerCreateTx(t *testing.T) { 882 jsTracer := ` 883 {enters: 0, exits: 0, 884 step: function() {}, 885 fault: function() {}, 886 result: function() { return [this.enters, this.exits].join(",") }, 887 enter: function(frame) { this.enters++ }, 888 exit: function(res) { this.exits++ }}` 889 code := []byte{byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN)} 890 891 statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 892 tracer, err := tracers.New(jsTracer, new(tracers.Context)) 893 if err != nil { 894 t.Fatal(err) 895 } 896 _, _, _, err = Create(code, &Config{ 897 State: statedb, 898 EVMConfig: vm.Config{ 899 Debug: true, 900 Tracer: tracer, 901 }}) 902 if err != nil { 903 t.Fatal(err) 904 } 905 906 res, err := tracer.GetResult() 907 if err != nil { 908 t.Fatal(err) 909 } 910 if have, want := string(res), `"0,0"`; have != want { 911 t.Errorf("wrong result for tracer, have \n%v\nwant\n%v\n", have, want) 912 } 913 } 914 915 func BenchmarkTracerStepVsCallFrame(b *testing.B) { 916 // Simply pushes and pops some values in a loop 917 code := []byte{ 918 byte(vm.JUMPDEST), 919 byte(vm.PUSH1), 0, 920 byte(vm.PUSH1), 0, 921 byte(vm.POP), 922 byte(vm.POP), 923 byte(vm.PUSH1), 0, // jumpdestination 924 byte(vm.JUMP), 925 } 926 927 stepTracer := ` 928 { 929 step: function() {}, 930 fault: function() {}, 931 result: function() {}, 932 }` 933 callFrameTracer := ` 934 { 935 enter: function() {}, 936 exit: function() {}, 937 fault: function() {}, 938 result: function() {}, 939 }` 940 941 benchmarkNonModifyingCode(10000000, code, "tracer-step-10M", stepTracer, b) 942 benchmarkNonModifyingCode(10000000, code, "tracer-call-frame-10M", callFrameTracer, b) 943 }