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