github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/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 26 "github.com/ethereum/go-ethereum/accounts/abi" 27 "github.com/ethereum/go-ethereum/common" 28 "github.com/ethereum/go-ethereum/consensus" 29 "github.com/ethereum/go-ethereum/core" 30 "github.com/ethereum/go-ethereum/core/asm" 31 "github.com/ethereum/go-ethereum/core/rawdb" 32 "github.com/ethereum/go-ethereum/core/state" 33 "github.com/ethereum/go-ethereum/core/types" 34 "github.com/ethereum/go-ethereum/core/vm" 35 "github.com/ethereum/go-ethereum/eth/tracers" 36 "github.com/ethereum/go-ethereum/eth/tracers/logger" 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 // benchmarkNonModifyingCode benchmarks code, but if the code modifies the 329 // state, this should not be used, since it does not reset the state between runs. 330 func benchmarkNonModifyingCode(gas uint64, code []byte, name string, tracerCode string, b *testing.B) { 331 cfg := new(Config) 332 setDefaults(cfg) 333 cfg.State, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 334 cfg.GasLimit = gas 335 if len(tracerCode) > 0 { 336 tracer, err := tracers.New(tracerCode, new(tracers.Context), nil) 337 if err != nil { 338 b.Fatal(err) 339 } 340 cfg.EVMConfig = vm.Config{ 341 Debug: true, 342 Tracer: tracer, 343 } 344 } 345 var ( 346 destination = common.BytesToAddress([]byte("contract")) 347 vmenv = NewEnv(cfg) 348 sender = vm.AccountRef(cfg.Origin) 349 ) 350 cfg.State.CreateAccount(destination) 351 eoa := common.HexToAddress("E0") 352 { 353 cfg.State.CreateAccount(eoa) 354 cfg.State.SetNonce(eoa, 100) 355 } 356 reverting := common.HexToAddress("EE") 357 { 358 cfg.State.CreateAccount(reverting) 359 cfg.State.SetCode(reverting, []byte{ 360 byte(vm.PUSH1), 0x00, 361 byte(vm.PUSH1), 0x00, 362 byte(vm.REVERT), 363 }) 364 } 365 366 //cfg.State.CreateAccount(cfg.Origin) 367 // set the receiver's (the executing contract) code for execution. 368 cfg.State.SetCode(destination, code) 369 vmenv.Call(sender, destination, nil, gas, cfg.Value) 370 371 b.Run(name, func(b *testing.B) { 372 b.ReportAllocs() 373 for i := 0; i < b.N; i++ { 374 vmenv.Call(sender, destination, nil, gas, cfg.Value) 375 } 376 }) 377 } 378 379 // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG 380 // 55 ms 381 func BenchmarkSimpleLoop(b *testing.B) { 382 staticCallIdentity := []byte{ 383 byte(vm.JUMPDEST), // [ count ] 384 // push args for the call 385 byte(vm.PUSH1), 0, // out size 386 byte(vm.DUP1), // out offset 387 byte(vm.DUP1), // out insize 388 byte(vm.DUP1), // in offset 389 byte(vm.PUSH1), 0x4, // address of identity 390 byte(vm.GAS), // gas 391 byte(vm.STATICCALL), 392 byte(vm.POP), // pop return value 393 byte(vm.PUSH1), 0, // jumpdestination 394 byte(vm.JUMP), 395 } 396 397 callIdentity := []byte{ 398 byte(vm.JUMPDEST), // [ count ] 399 // push args for the call 400 byte(vm.PUSH1), 0, // out size 401 byte(vm.DUP1), // out offset 402 byte(vm.DUP1), // out insize 403 byte(vm.DUP1), // in offset 404 byte(vm.DUP1), // value 405 byte(vm.PUSH1), 0x4, // address of identity 406 byte(vm.GAS), // gas 407 byte(vm.CALL), 408 byte(vm.POP), // pop return value 409 byte(vm.PUSH1), 0, // jumpdestination 410 byte(vm.JUMP), 411 } 412 413 callInexistant := []byte{ 414 byte(vm.JUMPDEST), // [ count ] 415 // push args for the call 416 byte(vm.PUSH1), 0, // out size 417 byte(vm.DUP1), // out offset 418 byte(vm.DUP1), // out insize 419 byte(vm.DUP1), // in offset 420 byte(vm.DUP1), // value 421 byte(vm.PUSH1), 0xff, // address of existing contract 422 byte(vm.GAS), // gas 423 byte(vm.CALL), 424 byte(vm.POP), // pop return value 425 byte(vm.PUSH1), 0, // jumpdestination 426 byte(vm.JUMP), 427 } 428 429 callEOA := []byte{ 430 byte(vm.JUMPDEST), // [ count ] 431 // push args for the call 432 byte(vm.PUSH1), 0, // out size 433 byte(vm.DUP1), // out offset 434 byte(vm.DUP1), // out insize 435 byte(vm.DUP1), // in offset 436 byte(vm.DUP1), // value 437 byte(vm.PUSH1), 0xE0, // address of EOA 438 byte(vm.GAS), // gas 439 byte(vm.CALL), 440 byte(vm.POP), // pop return value 441 byte(vm.PUSH1), 0, // jumpdestination 442 byte(vm.JUMP), 443 } 444 445 loopingCode := []byte{ 446 byte(vm.JUMPDEST), // [ count ] 447 // push args for the call 448 byte(vm.PUSH1), 0, // out size 449 byte(vm.DUP1), // out offset 450 byte(vm.DUP1), // out insize 451 byte(vm.DUP1), // in offset 452 byte(vm.PUSH1), 0x4, // address of identity 453 byte(vm.GAS), // gas 454 455 byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), 456 byte(vm.PUSH1), 0, // jumpdestination 457 byte(vm.JUMP), 458 } 459 460 callRevertingContractWithInput := []byte{ 461 byte(vm.JUMPDEST), // 462 // push args for the call 463 byte(vm.PUSH1), 0, // out size 464 byte(vm.DUP1), // out offset 465 byte(vm.PUSH1), 0x20, // in size 466 byte(vm.PUSH1), 0x00, // in offset 467 byte(vm.PUSH1), 0x00, // value 468 byte(vm.PUSH1), 0xEE, // address of reverting contract 469 byte(vm.GAS), // gas 470 byte(vm.CALL), 471 byte(vm.POP), // pop return value 472 byte(vm.PUSH1), 0, // jumpdestination 473 byte(vm.JUMP), 474 } 475 476 //tracer := logger.NewJSONLogger(nil, os.Stdout) 477 //Execute(loopingCode, nil, &Config{ 478 // EVMConfig: vm.Config{ 479 // Debug: true, 480 // Tracer: tracer, 481 // }}) 482 // 100M gas 483 benchmarkNonModifyingCode(100000000, staticCallIdentity, "staticcall-identity-100M", "", b) 484 benchmarkNonModifyingCode(100000000, callIdentity, "call-identity-100M", "", b) 485 benchmarkNonModifyingCode(100000000, loopingCode, "loop-100M", "", b) 486 benchmarkNonModifyingCode(100000000, callInexistant, "call-nonexist-100M", "", b) 487 benchmarkNonModifyingCode(100000000, callEOA, "call-EOA-100M", "", b) 488 benchmarkNonModifyingCode(100000000, callRevertingContractWithInput, "call-reverting-100M", "", b) 489 490 //benchmarkNonModifyingCode(10000000, staticCallIdentity, "staticcall-identity-10M", b) 491 //benchmarkNonModifyingCode(10000000, loopingCode, "loop-10M", b) 492 } 493 494 // TestEip2929Cases contains various testcases that are used for 495 // EIP-2929 about gas repricings 496 func TestEip2929Cases(t *testing.T) { 497 t.Skip("Test only useful for generating documentation") 498 id := 1 499 prettyPrint := func(comment string, code []byte) { 500 instrs := make([]string, 0) 501 it := asm.NewInstructionIterator(code) 502 for it.Next() { 503 if it.Arg() != nil && 0 < len(it.Arg()) { 504 instrs = append(instrs, fmt.Sprintf("%v %#x", it.Op(), it.Arg())) 505 } else { 506 instrs = append(instrs, fmt.Sprintf("%v", it.Op())) 507 } 508 } 509 ops := strings.Join(instrs, ", ") 510 fmt.Printf("### Case %d\n\n", id) 511 id++ 512 fmt.Printf("%v\n\nBytecode: \n```\n%#x\n```\nOperations: \n```\n%v\n```\n\n", 513 comment, 514 code, ops) 515 Execute(code, nil, &Config{ 516 EVMConfig: vm.Config{ 517 Debug: true, 518 Tracer: logger.NewMarkdownLogger(nil, os.Stdout), 519 ExtraEips: []int{2929}, 520 }, 521 }) 522 } 523 524 { // First eip testcase 525 code := []byte{ 526 // Three checks against a precompile 527 byte(vm.PUSH1), 1, byte(vm.EXTCODEHASH), byte(vm.POP), 528 byte(vm.PUSH1), 2, byte(vm.EXTCODESIZE), byte(vm.POP), 529 byte(vm.PUSH1), 3, byte(vm.BALANCE), byte(vm.POP), 530 // Three checks against a non-precompile 531 byte(vm.PUSH1), 0xf1, byte(vm.EXTCODEHASH), byte(vm.POP), 532 byte(vm.PUSH1), 0xf2, byte(vm.EXTCODESIZE), byte(vm.POP), 533 byte(vm.PUSH1), 0xf3, byte(vm.BALANCE), byte(vm.POP), 534 // Same three checks (should be cheaper) 535 byte(vm.PUSH1), 0xf2, byte(vm.EXTCODEHASH), byte(vm.POP), 536 byte(vm.PUSH1), 0xf3, byte(vm.EXTCODESIZE), byte(vm.POP), 537 byte(vm.PUSH1), 0xf1, byte(vm.BALANCE), byte(vm.POP), 538 // Check the origin, and the 'this' 539 byte(vm.ORIGIN), byte(vm.BALANCE), byte(vm.POP), 540 byte(vm.ADDRESS), byte(vm.BALANCE), byte(vm.POP), 541 542 byte(vm.STOP), 543 } 544 prettyPrint("This checks `EXT`(codehash,codesize,balance) of precompiles, which should be `100`, "+ 545 "and later checks the same operations twice against some non-precompiles. "+ 546 "Those are cheaper second time they are accessed. Lastly, it checks the `BALANCE` of `origin` and `this`.", code) 547 } 548 549 { // EXTCODECOPY 550 code := []byte{ 551 // extcodecopy( 0xff,0,0,0,0) 552 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 553 byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY), 554 // extcodecopy( 0xff,0,0,0,0) 555 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 556 byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY), 557 // extcodecopy( this,0,0,0,0) 558 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 559 byte(vm.ADDRESS), byte(vm.EXTCODECOPY), 560 561 byte(vm.STOP), 562 } 563 prettyPrint("This checks `extcodecopy( 0xff,0,0,0,0)` twice, (should be expensive first time), "+ 564 "and then does `extcodecopy( this,0,0,0,0)`.", code) 565 } 566 567 { // SLOAD + SSTORE 568 code := []byte{ 569 570 // Add slot `0x1` to access list 571 byte(vm.PUSH1), 0x01, byte(vm.SLOAD), byte(vm.POP), // SLOAD( 0x1) (add to access list) 572 // Write to `0x1` which is already in access list 573 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x01, byte(vm.SSTORE), // SSTORE( loc: 0x01, val: 0x11) 574 // Write to `0x2` which is not in access list 575 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11) 576 // Write again to `0x2` 577 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11) 578 // Read slot in access list (0x2) 579 byte(vm.PUSH1), 0x02, byte(vm.SLOAD), // SLOAD( 0x2) 580 // Read slot in access list (0x1) 581 byte(vm.PUSH1), 0x01, byte(vm.SLOAD), // SLOAD( 0x1) 582 } 583 prettyPrint("This checks `sload( 0x1)` followed by `sstore(loc: 0x01, val:0x11)`, then 'naked' sstore:"+ 584 "`sstore(loc: 0x02, val:0x11)` twice, and `sload(0x2)`, `sload(0x1)`. ", code) 585 } 586 { // Call variants 587 code := []byte{ 588 // identity precompile 589 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 590 byte(vm.PUSH1), 0x04, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP), 591 592 // random account - call 1 593 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 594 byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP), 595 596 // random account - call 2 597 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 598 byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.STATICCALL), byte(vm.POP), 599 } 600 prettyPrint("This calls the `identity`-precompile (cheap), then calls an account (expensive) and `staticcall`s the same"+ 601 "account (cheap)", code) 602 } 603 } 604 605 // TestColdAccountAccessCost test that the cold account access cost is reported 606 // correctly 607 // see: https://github.com/ethereum/go-ethereum/issues/22649 608 func TestColdAccountAccessCost(t *testing.T) { 609 for i, tc := range []struct { 610 code []byte 611 step int 612 want uint64 613 }{ 614 { // EXTCODEHASH(0xff) 615 code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.EXTCODEHASH), byte(vm.POP)}, 616 step: 1, 617 want: 2600, 618 }, 619 { // BALANCE(0xff) 620 code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.BALANCE), byte(vm.POP)}, 621 step: 1, 622 want: 2600, 623 }, 624 { // CALL(0xff) 625 code: []byte{ 626 byte(vm.PUSH1), 0x0, 627 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 628 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALL), byte(vm.POP), 629 }, 630 step: 7, 631 want: 2855, 632 }, 633 { // CALLCODE(0xff) 634 code: []byte{ 635 byte(vm.PUSH1), 0x0, 636 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 637 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALLCODE), byte(vm.POP), 638 }, 639 step: 7, 640 want: 2855, 641 }, 642 { // DELEGATECALL(0xff) 643 code: []byte{ 644 byte(vm.PUSH1), 0x0, 645 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 646 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.DELEGATECALL), byte(vm.POP), 647 }, 648 step: 6, 649 want: 2855, 650 }, 651 { // STATICCALL(0xff) 652 code: []byte{ 653 byte(vm.PUSH1), 0x0, 654 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 655 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.STATICCALL), byte(vm.POP), 656 }, 657 step: 6, 658 want: 2855, 659 }, 660 { // SELFDESTRUCT(0xff) 661 code: []byte{ 662 byte(vm.PUSH1), 0xff, byte(vm.SELFDESTRUCT), 663 }, 664 step: 1, 665 want: 7600, 666 }, 667 } { 668 tracer := logger.NewStructLogger(nil) 669 Execute(tc.code, nil, &Config{ 670 EVMConfig: vm.Config{ 671 Debug: true, 672 Tracer: tracer, 673 }, 674 }) 675 have := tracer.StructLogs()[tc.step].GasCost 676 if want := tc.want; have != want { 677 for ii, op := range tracer.StructLogs() { 678 t.Logf("%d: %v %d", ii, op.OpName(), op.GasCost) 679 } 680 t.Fatalf("tescase %d, gas report wrong, step %d, have %d want %d", i, tc.step, have, want) 681 } 682 } 683 } 684 685 func TestRuntimeJSTracer(t *testing.T) { 686 jsTracers := []string{ 687 `{enters: 0, exits: 0, enterGas: 0, gasUsed: 0, steps:0, 688 step: function() { this.steps++}, 689 fault: function() {}, 690 result: function() { 691 return [this.enters, this.exits,this.enterGas,this.gasUsed, this.steps].join(",") 692 }, 693 enter: function(frame) { 694 this.enters++; 695 this.enterGas = frame.getGas(); 696 }, 697 exit: function(res) { 698 this.exits++; 699 this.gasUsed = res.getGasUsed(); 700 }}`, 701 `{enters: 0, exits: 0, enterGas: 0, gasUsed: 0, steps:0, 702 fault: function() {}, 703 result: function() { 704 return [this.enters, this.exits,this.enterGas,this.gasUsed, this.steps].join(",") 705 }, 706 enter: function(frame) { 707 this.enters++; 708 this.enterGas = frame.getGas(); 709 }, 710 exit: function(res) { 711 this.exits++; 712 this.gasUsed = res.getGasUsed(); 713 }}`} 714 tests := []struct { 715 code []byte 716 // One result per tracer 717 results []string 718 }{ 719 { 720 // CREATE 721 code: []byte{ 722 // Store initcode in memory at 0x00 (5 bytes left-padded to 32 bytes) 723 byte(vm.PUSH5), 724 // Init code: PUSH1 0, PUSH1 0, RETURN (3 steps) 725 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN), 726 byte(vm.PUSH1), 0, 727 byte(vm.MSTORE), 728 // length, offset, value 729 byte(vm.PUSH1), 5, byte(vm.PUSH1), 27, byte(vm.PUSH1), 0, 730 byte(vm.CREATE), 731 byte(vm.POP), 732 }, 733 results: []string{`"1,1,952855,6,12"`, `"1,1,952855,6,0"`}, 734 }, 735 { 736 // CREATE2 737 code: []byte{ 738 // Store initcode in memory at 0x00 (5 bytes left-padded to 32 bytes) 739 byte(vm.PUSH5), 740 // Init code: PUSH1 0, PUSH1 0, RETURN (3 steps) 741 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN), 742 byte(vm.PUSH1), 0, 743 byte(vm.MSTORE), 744 // salt, length, offset, value 745 byte(vm.PUSH1), 1, byte(vm.PUSH1), 5, byte(vm.PUSH1), 27, byte(vm.PUSH1), 0, 746 byte(vm.CREATE2), 747 byte(vm.POP), 748 }, 749 results: []string{`"1,1,952846,6,13"`, `"1,1,952846,6,0"`}, 750 }, 751 { 752 // CALL 753 code: []byte{ 754 // outsize, outoffset, insize, inoffset 755 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 756 byte(vm.PUSH1), 0, // value 757 byte(vm.PUSH1), 0xbb, //address 758 byte(vm.GAS), // gas 759 byte(vm.CALL), 760 byte(vm.POP), 761 }, 762 results: []string{`"1,1,981796,6,13"`, `"1,1,981796,6,0"`}, 763 }, 764 { 765 // CALLCODE 766 code: []byte{ 767 // outsize, outoffset, insize, inoffset 768 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 769 byte(vm.PUSH1), 0, // value 770 byte(vm.PUSH1), 0xcc, //address 771 byte(vm.GAS), // gas 772 byte(vm.CALLCODE), 773 byte(vm.POP), 774 }, 775 results: []string{`"1,1,981796,6,13"`, `"1,1,981796,6,0"`}, 776 }, 777 { 778 // STATICCALL 779 code: []byte{ 780 // outsize, outoffset, insize, inoffset 781 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 782 byte(vm.PUSH1), 0xdd, //address 783 byte(vm.GAS), // gas 784 byte(vm.STATICCALL), 785 byte(vm.POP), 786 }, 787 results: []string{`"1,1,981799,6,12"`, `"1,1,981799,6,0"`}, 788 }, 789 { 790 // DELEGATECALL 791 code: []byte{ 792 // outsize, outoffset, insize, inoffset 793 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 794 byte(vm.PUSH1), 0xee, //address 795 byte(vm.GAS), // gas 796 byte(vm.DELEGATECALL), 797 byte(vm.POP), 798 }, 799 results: []string{`"1,1,981799,6,12"`, `"1,1,981799,6,0"`}, 800 }, 801 { 802 // CALL self-destructing contract 803 code: []byte{ 804 // outsize, outoffset, insize, inoffset 805 byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, 806 byte(vm.PUSH1), 0, // value 807 byte(vm.PUSH1), 0xff, //address 808 byte(vm.GAS), // gas 809 byte(vm.CALL), 810 byte(vm.POP), 811 }, 812 results: []string{`"2,2,0,5003,12"`, `"2,2,0,5003,0"`}, 813 }, 814 } 815 calleeCode := []byte{ 816 byte(vm.PUSH1), 0, 817 byte(vm.PUSH1), 0, 818 byte(vm.RETURN), 819 } 820 depressedCode := []byte{ 821 byte(vm.PUSH1), 0xaa, 822 byte(vm.SELFDESTRUCT), 823 } 824 main := common.HexToAddress("0xaa") 825 for i, jsTracer := range jsTracers { 826 for j, tc := range tests { 827 statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 828 statedb.SetCode(main, tc.code) 829 statedb.SetCode(common.HexToAddress("0xbb"), calleeCode) 830 statedb.SetCode(common.HexToAddress("0xcc"), calleeCode) 831 statedb.SetCode(common.HexToAddress("0xdd"), calleeCode) 832 statedb.SetCode(common.HexToAddress("0xee"), calleeCode) 833 statedb.SetCode(common.HexToAddress("0xff"), depressedCode) 834 835 tracer, err := tracers.New(jsTracer, new(tracers.Context), nil) 836 if err != nil { 837 t.Fatal(err) 838 } 839 _, _, err = Call(main, nil, &Config{ 840 GasLimit: 1000000, 841 State: statedb, 842 EVMConfig: vm.Config{ 843 Debug: true, 844 Tracer: tracer, 845 }}) 846 if err != nil { 847 t.Fatal("didn't expect error", err) 848 } 849 res, err := tracer.GetResult() 850 if err != nil { 851 t.Fatal(err) 852 } 853 if have, want := string(res), tc.results[i]; have != want { 854 t.Errorf("wrong result for tracer %d testcase %d, have \n%v\nwant\n%v\n", i, j, have, want) 855 } 856 } 857 } 858 } 859 860 func TestJSTracerCreateTx(t *testing.T) { 861 jsTracer := ` 862 {enters: 0, exits: 0, 863 step: function() {}, 864 fault: function() {}, 865 result: function() { return [this.enters, this.exits].join(",") }, 866 enter: function(frame) { this.enters++ }, 867 exit: function(res) { this.exits++ }}` 868 code := []byte{byte(vm.PUSH1), 0, byte(vm.PUSH1), 0, byte(vm.RETURN)} 869 870 statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 871 tracer, err := tracers.New(jsTracer, new(tracers.Context), nil) 872 if err != nil { 873 t.Fatal(err) 874 } 875 _, _, _, err = Create(code, &Config{ 876 State: statedb, 877 EVMConfig: vm.Config{ 878 Debug: true, 879 Tracer: tracer, 880 }}) 881 if err != nil { 882 t.Fatal(err) 883 } 884 885 res, err := tracer.GetResult() 886 if err != nil { 887 t.Fatal(err) 888 } 889 if have, want := string(res), `"0,0"`; have != want { 890 t.Errorf("wrong result for tracer, have \n%v\nwant\n%v\n", have, want) 891 } 892 } 893 894 func BenchmarkTracerStepVsCallFrame(b *testing.B) { 895 // Simply pushes and pops some values in a loop 896 code := []byte{ 897 byte(vm.JUMPDEST), 898 byte(vm.PUSH1), 0, 899 byte(vm.PUSH1), 0, 900 byte(vm.POP), 901 byte(vm.POP), 902 byte(vm.PUSH1), 0, // jumpdestination 903 byte(vm.JUMP), 904 } 905 906 stepTracer := ` 907 { 908 step: function() {}, 909 fault: function() {}, 910 result: function() {}, 911 }` 912 callFrameTracer := ` 913 { 914 enter: function() {}, 915 exit: function() {}, 916 fault: function() {}, 917 result: function() {}, 918 }` 919 920 benchmarkNonModifyingCode(10000000, code, "tracer-step-10M", stepTracer, b) 921 benchmarkNonModifyingCode(10000000, code, "tracer-call-frame-10M", callFrameTracer, b) 922 }