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