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