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