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