github.com/MetalBlockchain/subnet-evm@v0.4.9/core/vm/runtime/runtime_test.go (about) 1 // (c) 2019-2021, Ava Labs, Inc. 2 // 3 // This file is a derived work, based on the go-ethereum library whose original 4 // notices appear below. 5 // 6 // It is distributed under a license compatible with the licensing terms of the 7 // original code from which it is derived. 8 // 9 // Much love to the original authors for their work. 10 // ********** 11 // Copyright 2015 The go-ethereum Authors 12 // This file is part of the go-ethereum library. 13 // 14 // The go-ethereum library is free software: you can redistribute it and/or modify 15 // it under the terms of the GNU Lesser General Public License as published by 16 // the Free Software Foundation, either version 3 of the License, or 17 // (at your option) any later version. 18 // 19 // The go-ethereum library is distributed in the hope that it will be useful, 20 // but WITHOUT ANY WARRANTY; without even the implied warranty of 21 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 // GNU Lesser General Public License for more details. 23 // 24 // You should have received a copy of the GNU Lesser General Public License 25 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 26 27 package runtime 28 29 import ( 30 "fmt" 31 "math/big" 32 "os" 33 "strings" 34 "testing" 35 36 "github.com/MetalBlockchain/subnet-evm/accounts/abi" 37 "github.com/MetalBlockchain/subnet-evm/consensus" 38 "github.com/MetalBlockchain/subnet-evm/core" 39 "github.com/MetalBlockchain/subnet-evm/core/rawdb" 40 "github.com/MetalBlockchain/subnet-evm/core/state" 41 "github.com/MetalBlockchain/subnet-evm/core/types" 42 "github.com/MetalBlockchain/subnet-evm/core/vm" 43 "github.com/MetalBlockchain/subnet-evm/eth/tracers" 44 "github.com/MetalBlockchain/subnet-evm/eth/tracers/logger" 45 "github.com/MetalBlockchain/subnet-evm/params" 46 "github.com/ethereum/go-ethereum/common" 47 "github.com/ethereum/go-ethereum/core/asm" 48 49 // force-load native tracers to trigger registration 50 _ "github.com/MetalBlockchain/subnet-evm/eth/tracers/native" 51 ) 52 53 func TestDefaults(t *testing.T) { 54 cfg := new(Config) 55 setDefaults(cfg) 56 57 if cfg.Difficulty == nil { 58 t.Error("expected difficulty to be non nil") 59 } 60 61 if cfg.Time == nil { 62 t.Error("expected time to be non nil") 63 } 64 if cfg.GasLimit == 0 { 65 t.Error("didn't expect gaslimit to be zero") 66 } 67 if cfg.GasPrice == nil { 68 t.Error("expected time to be non nil") 69 } 70 if cfg.Value == nil { 71 t.Error("expected time to be non nil") 72 } 73 if cfg.GetHashFn == nil { 74 t.Error("expected time to be non nil") 75 } 76 if cfg.BlockNumber == nil { 77 t.Error("expected block number to be non nil") 78 } 79 } 80 81 func TestEVM(t *testing.T) { 82 defer func() { 83 if r := recover(); r != nil { 84 t.Fatalf("crashed with: %v", r) 85 } 86 }() 87 88 Execute([]byte{ 89 byte(vm.DIFFICULTY), 90 byte(vm.TIMESTAMP), 91 byte(vm.GASLIMIT), 92 byte(vm.PUSH1), 93 byte(vm.ORIGIN), 94 byte(vm.BLOCKHASH), 95 byte(vm.COINBASE), 96 }, nil, nil) 97 } 98 99 func TestExecute(t *testing.T) { 100 ret, _, err := Execute([]byte{ 101 byte(vm.PUSH1), 10, 102 byte(vm.PUSH1), 0, 103 byte(vm.MSTORE), 104 byte(vm.PUSH1), 32, 105 byte(vm.PUSH1), 0, 106 byte(vm.RETURN), 107 }, nil, nil) 108 if err != nil { 109 t.Fatal("didn't expect error", err) 110 } 111 112 num := new(big.Int).SetBytes(ret) 113 if num.Cmp(big.NewInt(10)) != 0 { 114 t.Error("Expected 10, got", num) 115 } 116 } 117 118 func TestCall(t *testing.T) { 119 state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 120 address := common.HexToAddress("0x0a") 121 state.SetCode(address, []byte{ 122 byte(vm.PUSH1), 10, 123 byte(vm.PUSH1), 0, 124 byte(vm.MSTORE), 125 byte(vm.PUSH1), 32, 126 byte(vm.PUSH1), 0, 127 byte(vm.RETURN), 128 }) 129 130 ret, _, err := Call(address, nil, &Config{State: state}) 131 if err != nil { 132 t.Fatal("didn't expect error", err) 133 } 134 135 num := new(big.Int).SetBytes(ret) 136 if num.Cmp(big.NewInt(10)) != 0 { 137 t.Error("Expected 10, got", num) 138 } 139 } 140 141 func BenchmarkCall(b *testing.B) { 142 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"}]` 143 144 var code = common.Hex2Bytes("6060604052361561006c5760e060020a600035046308551a53811461007457806335a063b4146100865780633fa4f245146100a6578063590e1ae3146100af5780637150d8ae146100cf57806373fac6f0146100e1578063c19d93fb146100fe578063d696069714610112575b610131610002565b610133600154600160a060020a031681565b610131600154600160a060020a0390811633919091161461015057610002565b61014660005481565b610131600154600160a060020a039081163391909116146102d557610002565b610133600254600160a060020a031681565b610131600254600160a060020a0333811691161461023757610002565b61014660025460ff60a060020a9091041681565b61013160025460009060ff60a060020a9091041681146101cc57610002565b005b600160a060020a03166060908152602090f35b6060908152602090f35b60025460009060a060020a900460ff16811461016b57610002565b600154600160a060020a03908116908290301631606082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f72c874aeff0b183a56e2b79c71b46e1aed4dee5e09862134b8821ba2fddbf8bf9250a150565b80546002023414806101dd57610002565b6002805460a060020a60ff021973ffffffffffffffffffffffffffffffffffffffff1990911633171660a060020a1790557fd5d55c8a68912e9a110618df8d5e2e83b8d83211c57a8ddd1203df92885dc881826060a15050565b60025460019060a060020a900460ff16811461025257610002565b60025460008054600160a060020a0390921691606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517fe89152acd703c9d8c7d28829d443260b411454d45394e7995815140c8cbcbcf79250a150565b60025460019060a060020a900460ff1681146102f057610002565b6002805460008054600160a060020a0390921692909102606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f8616bbbbad963e4e65b1366f1d75dfb63f9e9704bbbf91fb01bec70849906cf79250a15056") 145 146 abi, err := abi.JSON(strings.NewReader(definition)) 147 if err != nil { 148 b.Fatal(err) 149 } 150 151 cpurchase, err := abi.Pack("confirmPurchase") 152 if err != nil { 153 b.Fatal(err) 154 } 155 creceived, err := abi.Pack("confirmReceived") 156 if err != nil { 157 b.Fatal(err) 158 } 159 refund, err := abi.Pack("refund") 160 if err != nil { 161 b.Fatal(err) 162 } 163 164 b.ResetTimer() 165 for i := 0; i < b.N; i++ { 166 for j := 0; j < 400; j++ { 167 Execute(code, cpurchase, nil) 168 Execute(code, creceived, nil) 169 Execute(code, refund, nil) 170 } 171 } 172 } 173 func benchmarkEVM_Create(bench *testing.B, code string) { 174 var ( 175 statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 176 sender = common.BytesToAddress([]byte("sender")) 177 receiver = common.BytesToAddress([]byte("receiver")) 178 ) 179 180 statedb.CreateAccount(sender) 181 statedb.SetCode(receiver, common.FromHex(code)) 182 runtimeConfig := Config{ 183 Origin: sender, 184 State: statedb, 185 GasLimit: 10000000, 186 Difficulty: big.NewInt(0x200000), 187 Time: new(big.Int).SetUint64(0), 188 Coinbase: common.Address{}, 189 BlockNumber: new(big.Int).SetUint64(1), 190 ChainConfig: ¶ms.ChainConfig{ 191 ChainID: big.NewInt(1), 192 HomesteadBlock: new(big.Int), 193 ByzantiumBlock: new(big.Int), 194 ConstantinopleBlock: new(big.Int), 195 EIP150Block: new(big.Int), 196 EIP155Block: new(big.Int), 197 EIP158Block: new(big.Int), 198 }, 199 EVMConfig: vm.Config{}, 200 } 201 // Warm up the intpools and stuff 202 bench.ResetTimer() 203 for i := 0; i < bench.N; i++ { 204 Call(receiver, []byte{}, &runtimeConfig) 205 } 206 bench.StopTimer() 207 } 208 209 func BenchmarkEVM_CREATE_500(bench *testing.B) { 210 // initcode size 500K, repeatedly calls CREATE and then modifies the mem contents 211 benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056") 212 } 213 func BenchmarkEVM_CREATE2_500(bench *testing.B) { 214 // initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents 215 benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056") 216 } 217 func BenchmarkEVM_CREATE_1200(bench *testing.B) { 218 // initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents 219 benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056") 220 } 221 func BenchmarkEVM_CREATE2_1200(bench *testing.B) { 222 // initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents 223 benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056") 224 } 225 226 func fakeHeader(n uint64, parentHash common.Hash) *types.Header { 227 header := types.Header{ 228 Coinbase: common.HexToAddress("0x00000000000000000000000000000000deadbeef"), 229 Number: big.NewInt(int64(n)), 230 ParentHash: parentHash, 231 Time: 1000, 232 Nonce: types.BlockNonce{0x1}, 233 Extra: []byte{}, 234 Difficulty: big.NewInt(0), 235 GasLimit: 100000, 236 } 237 return &header 238 } 239 240 type dummyChain struct { 241 counter int 242 } 243 244 // Engine retrieves the chain's consensus engine. 245 func (d *dummyChain) Engine() consensus.Engine { 246 return nil 247 } 248 249 // GetHeader returns the hash corresponding to their hash. 250 func (d *dummyChain) GetHeader(h common.Hash, n uint64) *types.Header { 251 d.counter++ 252 parentHash := common.Hash{} 253 s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32) 254 copy(parentHash[:], s) 255 256 //parentHash := common.Hash{byte(n - 1)} 257 //fmt.Printf("GetHeader(%x, %d) => header with parent %x\n", h, n, parentHash) 258 return fakeHeader(n, parentHash) 259 } 260 261 // TestBlockhash tests the blockhash operation. It's a bit special, since it internally 262 // requires access to a chain reader. 263 func TestBlockhash(t *testing.T) { 264 // Current head 265 n := uint64(1000) 266 parentHash := common.Hash{} 267 s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32) 268 copy(parentHash[:], s) 269 header := fakeHeader(n, parentHash) 270 271 // This is the contract we're using. It requests the blockhash for current num (should be all zeroes), 272 // then iteratively fetches all blockhashes back to n-260. 273 // It returns 274 // 1. the first (should be zero) 275 // 2. the second (should be the parent hash) 276 // 3. the last non-zero hash 277 // By making the chain reader return hashes which correlate to the number, we can 278 // verify that it obtained the right hashes where it should 279 280 /* 281 282 pragma solidity ^0.5.3; 283 contract Hasher{ 284 285 function test() public view returns (bytes32, bytes32, bytes32){ 286 uint256 x = block.number; 287 bytes32 first; 288 bytes32 last; 289 bytes32 zero; 290 zero = blockhash(x); // Should be zeroes 291 first = blockhash(x-1); 292 for(uint256 i = 2 ; i < 260; i++){ 293 bytes32 hash = blockhash(x - i); 294 if (uint256(hash) != 0){ 295 last = hash; 296 } 297 } 298 return (zero, first, last); 299 } 300 } 301 302 */ 303 // The contract above 304 data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029") 305 // The method call to 'test()' 306 input := common.Hex2Bytes("f8a8fd6d") 307 chain := &dummyChain{} 308 ret, _, err := Execute(data, input, &Config{ 309 GetHashFn: core.GetHashFn(header, chain), 310 BlockNumber: new(big.Int).Set(header.Number), 311 }) 312 if err != nil { 313 t.Fatalf("expected no error, got %v", err) 314 } 315 if len(ret) != 96 { 316 t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret)) 317 } 318 319 zero := new(big.Int).SetBytes(ret[0:32]) 320 first := new(big.Int).SetBytes(ret[32:64]) 321 last := new(big.Int).SetBytes(ret[64:96]) 322 if zero.BitLen() != 0 { 323 t.Fatalf("expected zeroes, got %x", ret[0:32]) 324 } 325 if first.Uint64() != 999 { 326 t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64]) 327 } 328 if last.Uint64() != 744 { 329 t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96]) 330 } 331 if exp, got := 255, chain.counter; exp != got { 332 t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got) 333 } 334 } 335 336 // benchmarkNonModifyingCode benchmarks code, but if the code modifies the 337 // state, this should not be used, since it does not reset the state between runs. 338 func benchmarkNonModifyingCode(gas uint64, code []byte, name string, tracerCode string, b *testing.B) { 339 cfg := new(Config) 340 setDefaults(cfg) 341 cfg.State, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) 342 cfg.GasLimit = gas 343 if len(tracerCode) > 0 { 344 tracer, err := tracers.New(tracerCode, new(tracers.Context), nil) 345 if err != nil { 346 b.Fatal(err) 347 } 348 cfg.EVMConfig = vm.Config{ 349 Debug: true, 350 Tracer: tracer, 351 } 352 } 353 var ( 354 destination = common.BytesToAddress([]byte("contract")) 355 vmenv = NewEnv(cfg) 356 sender = vm.AccountRef(cfg.Origin) 357 ) 358 cfg.State.CreateAccount(destination) 359 eoa := common.HexToAddress("E0") 360 { 361 cfg.State.CreateAccount(eoa) 362 cfg.State.SetNonce(eoa, 100) 363 } 364 reverting := common.HexToAddress("EE") 365 { 366 cfg.State.CreateAccount(reverting) 367 cfg.State.SetCode(reverting, []byte{ 368 byte(vm.PUSH1), 0x00, 369 byte(vm.PUSH1), 0x00, 370 byte(vm.REVERT), 371 }) 372 } 373 374 //cfg.State.CreateAccount(cfg.Origin) 375 // set the receiver's (the executing contract) code for execution. 376 cfg.State.SetCode(destination, code) 377 vmenv.Call(sender, destination, nil, gas, cfg.Value) 378 379 b.Run(name, func(b *testing.B) { 380 b.ReportAllocs() 381 for i := 0; i < b.N; i++ { 382 vmenv.Call(sender, destination, nil, gas, cfg.Value) 383 } 384 }) 385 } 386 387 // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG 388 // 55 ms 389 func BenchmarkSimpleLoop(b *testing.B) { 390 staticCallIdentity := []byte{ 391 byte(vm.JUMPDEST), // [ count ] 392 // push args for the call 393 byte(vm.PUSH1), 0, // out size 394 byte(vm.DUP1), // out offset 395 byte(vm.DUP1), // out insize 396 byte(vm.DUP1), // in offset 397 byte(vm.PUSH1), 0x4, // address of identity 398 byte(vm.GAS), // gas 399 byte(vm.STATICCALL), 400 byte(vm.POP), // pop return value 401 byte(vm.PUSH1), 0, // jumpdestination 402 byte(vm.JUMP), 403 } 404 405 callIdentity := []byte{ 406 byte(vm.JUMPDEST), // [ count ] 407 // push args for the call 408 byte(vm.PUSH1), 0, // out size 409 byte(vm.DUP1), // out offset 410 byte(vm.DUP1), // out insize 411 byte(vm.DUP1), // in offset 412 byte(vm.DUP1), // value 413 byte(vm.PUSH1), 0x4, // address of identity 414 byte(vm.GAS), // gas 415 byte(vm.CALL), 416 byte(vm.POP), // pop return value 417 byte(vm.PUSH1), 0, // jumpdestination 418 byte(vm.JUMP), 419 } 420 421 callInexistant := []byte{ 422 byte(vm.JUMPDEST), // [ count ] 423 // push args for the call 424 byte(vm.PUSH1), 0, // out size 425 byte(vm.DUP1), // out offset 426 byte(vm.DUP1), // out insize 427 byte(vm.DUP1), // in offset 428 byte(vm.DUP1), // value 429 byte(vm.PUSH1), 0xff, // address of existing contract 430 byte(vm.GAS), // gas 431 byte(vm.CALL), 432 byte(vm.POP), // pop return value 433 byte(vm.PUSH1), 0, // jumpdestination 434 byte(vm.JUMP), 435 } 436 437 callEOA := []byte{ 438 byte(vm.JUMPDEST), // [ count ] 439 // push args for the call 440 byte(vm.PUSH1), 0, // out size 441 byte(vm.DUP1), // out offset 442 byte(vm.DUP1), // out insize 443 byte(vm.DUP1), // in offset 444 byte(vm.DUP1), // value 445 byte(vm.PUSH1), 0xE0, // address of EOA 446 byte(vm.GAS), // gas 447 byte(vm.CALL), 448 byte(vm.POP), // pop return value 449 byte(vm.PUSH1), 0, // jumpdestination 450 byte(vm.JUMP), 451 } 452 453 loopingCode := []byte{ 454 byte(vm.JUMPDEST), // [ count ] 455 // push args for the call 456 byte(vm.PUSH1), 0, // out size 457 byte(vm.DUP1), // out offset 458 byte(vm.DUP1), // out insize 459 byte(vm.DUP1), // in offset 460 byte(vm.PUSH1), 0x4, // address of identity 461 byte(vm.GAS), // gas 462 463 byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), 464 byte(vm.PUSH1), 0, // jumpdestination 465 byte(vm.JUMP), 466 } 467 468 callRevertingContractWithInput := []byte{ 469 byte(vm.JUMPDEST), // 470 // push args for the call 471 byte(vm.PUSH1), 0, // out size 472 byte(vm.DUP1), // out offset 473 byte(vm.PUSH1), 0x20, // in size 474 byte(vm.PUSH1), 0x00, // in offset 475 byte(vm.PUSH1), 0x00, // value 476 byte(vm.PUSH1), 0xEE, // address of reverting contract 477 byte(vm.GAS), // gas 478 byte(vm.CALL), 479 byte(vm.POP), // pop return value 480 byte(vm.PUSH1), 0, // jumpdestination 481 byte(vm.JUMP), 482 } 483 484 //tracer := logger.NewJSONLogger(nil, os.Stdout) 485 //Execute(loopingCode, nil, &Config{ 486 // EVMConfig: vm.Config{ 487 // Debug: true, 488 // Tracer: tracer, 489 // }}) 490 // 100M gas 491 benchmarkNonModifyingCode(100000000, staticCallIdentity, "staticcall-identity-100M", "", b) 492 benchmarkNonModifyingCode(100000000, callIdentity, "call-identity-100M", "", b) 493 benchmarkNonModifyingCode(100000000, loopingCode, "loop-100M", "", b) 494 benchmarkNonModifyingCode(100000000, callInexistant, "call-nonexist-100M", "", b) 495 benchmarkNonModifyingCode(100000000, callEOA, "call-EOA-100M", "", b) 496 benchmarkNonModifyingCode(100000000, callRevertingContractWithInput, "call-reverting-100M", "", b) 497 498 //benchmarkNonModifyingCode(10000000, staticCallIdentity, "staticcall-identity-10M", b) 499 //benchmarkNonModifyingCode(10000000, loopingCode, "loop-10M", b) 500 } 501 502 // TestEip2929Cases contains various testcases that are used for 503 // EIP-2929 about gas repricings 504 func TestEip2929Cases(t *testing.T) { 505 t.Skip("Test only useful for generating documentation") 506 id := 1 507 prettyPrint := func(comment string, code []byte) { 508 instrs := make([]string, 0) 509 it := asm.NewInstructionIterator(code) 510 for it.Next() { 511 if it.Arg() != nil && 0 < len(it.Arg()) { 512 instrs = append(instrs, fmt.Sprintf("%v %#x", it.Op(), it.Arg())) 513 } else { 514 instrs = append(instrs, fmt.Sprintf("%v", it.Op())) 515 } 516 } 517 ops := strings.Join(instrs, ", ") 518 fmt.Printf("### Case %d\n\n", id) 519 id++ 520 fmt.Printf("%v\n\nBytecode: \n```\n%#x\n```\nOperations: \n```\n%v\n```\n\n", 521 comment, 522 code, ops) 523 Execute(code, nil, &Config{ 524 EVMConfig: vm.Config{ 525 Debug: true, 526 Tracer: logger.NewMarkdownLogger(nil, os.Stdout), 527 ExtraEips: []int{2929}, 528 }, 529 }) 530 } 531 532 { // First eip testcase 533 code := []byte{ 534 // Three checks against a precompile 535 byte(vm.PUSH1), 1, byte(vm.EXTCODEHASH), byte(vm.POP), 536 byte(vm.PUSH1), 2, byte(vm.EXTCODESIZE), byte(vm.POP), 537 byte(vm.PUSH1), 3, byte(vm.BALANCE), byte(vm.POP), 538 // Three checks against a non-precompile 539 byte(vm.PUSH1), 0xf1, byte(vm.EXTCODEHASH), byte(vm.POP), 540 byte(vm.PUSH1), 0xf2, byte(vm.EXTCODESIZE), byte(vm.POP), 541 byte(vm.PUSH1), 0xf3, byte(vm.BALANCE), byte(vm.POP), 542 // Same three checks (should be cheaper) 543 byte(vm.PUSH1), 0xf2, byte(vm.EXTCODEHASH), byte(vm.POP), 544 byte(vm.PUSH1), 0xf3, byte(vm.EXTCODESIZE), byte(vm.POP), 545 byte(vm.PUSH1), 0xf1, byte(vm.BALANCE), byte(vm.POP), 546 // Check the origin, and the 'this' 547 byte(vm.ORIGIN), byte(vm.BALANCE), byte(vm.POP), 548 byte(vm.ADDRESS), byte(vm.BALANCE), byte(vm.POP), 549 550 byte(vm.STOP), 551 } 552 prettyPrint("This checks `EXT`(codehash,codesize,balance) of precompiles, which should be `100`, "+ 553 "and later checks the same operations twice against some non-precompiles. "+ 554 "Those are cheaper second time they are accessed. Lastly, it checks the `BALANCE` of `origin` and `this`.", code) 555 } 556 557 { // EXTCODECOPY 558 code := []byte{ 559 // extcodecopy( 0xff,0,0,0,0) 560 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 561 byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY), 562 // extcodecopy( 0xff,0,0,0,0) 563 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 564 byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY), 565 // extcodecopy( this,0,0,0,0) 566 byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset 567 byte(vm.ADDRESS), byte(vm.EXTCODECOPY), 568 569 byte(vm.STOP), 570 } 571 prettyPrint("This checks `extcodecopy( 0xff,0,0,0,0)` twice, (should be expensive first time), "+ 572 "and then does `extcodecopy( this,0,0,0,0)`.", code) 573 } 574 575 { // SLOAD + SSTORE 576 code := []byte{ 577 578 // Add slot `0x1` to access list 579 byte(vm.PUSH1), 0x01, byte(vm.SLOAD), byte(vm.POP), // SLOAD( 0x1) (add to access list) 580 // Write to `0x1` which is already in access list 581 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x01, byte(vm.SSTORE), // SSTORE( loc: 0x01, val: 0x11) 582 // Write to `0x2` which is not in access list 583 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11) 584 // Write again to `0x2` 585 byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11) 586 // Read slot in access list (0x2) 587 byte(vm.PUSH1), 0x02, byte(vm.SLOAD), // SLOAD( 0x2) 588 // Read slot in access list (0x1) 589 byte(vm.PUSH1), 0x01, byte(vm.SLOAD), // SLOAD( 0x1) 590 } 591 prettyPrint("This checks `sload( 0x1)` followed by `sstore(loc: 0x01, val:0x11)`, then 'naked' sstore:"+ 592 "`sstore(loc: 0x02, val:0x11)` twice, and `sload(0x2)`, `sload(0x1)`. ", code) 593 } 594 { // Call variants 595 code := []byte{ 596 // identity precompile 597 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 598 byte(vm.PUSH1), 0x04, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP), 599 600 // random account - call 1 601 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 602 byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP), 603 604 // random account - call 2 605 byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 606 byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.STATICCALL), byte(vm.POP), 607 } 608 prettyPrint("This calls the `identity`-precompile (cheap), then calls an account (expensive) and `staticcall`s the same"+ 609 "account (cheap)", code) 610 } 611 } 612 613 // TestColdAccountAccessCost test that the cold account access cost is reported 614 // correctly 615 // see: https://github.com/ethereum/go-ethereum/issues/22649 616 func TestColdAccountAccessCost(t *testing.T) { 617 for i, tc := range []struct { 618 code []byte 619 step int 620 want uint64 621 }{ 622 { // EXTCODEHASH(0xff) 623 code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.EXTCODEHASH), byte(vm.POP)}, 624 step: 1, 625 want: 2600, 626 }, 627 { // BALANCE(0xff) 628 code: []byte{byte(vm.PUSH1), 0xFF, byte(vm.BALANCE), byte(vm.POP)}, 629 step: 1, 630 want: 2600, 631 }, 632 { // CALL(0xff) 633 code: []byte{ 634 byte(vm.PUSH1), 0x0, 635 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 636 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALL), byte(vm.POP), 637 }, 638 step: 7, 639 want: 2855, 640 }, 641 { // CALLCODE(0xff) 642 code: []byte{ 643 byte(vm.PUSH1), 0x0, 644 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 645 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.CALLCODE), byte(vm.POP), 646 }, 647 step: 7, 648 want: 2855, 649 }, 650 { // DELEGATECALL(0xff) 651 code: []byte{ 652 byte(vm.PUSH1), 0x0, 653 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 654 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.DELEGATECALL), byte(vm.POP), 655 }, 656 step: 6, 657 want: 2855, 658 }, 659 { // STATICCALL(0xff) 660 code: []byte{ 661 byte(vm.PUSH1), 0x0, 662 byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), 663 byte(vm.PUSH1), 0xff, byte(vm.DUP1), byte(vm.STATICCALL), byte(vm.POP), 664 }, 665 step: 6, 666 want: 2855, 667 }, 668 { // SELFDESTRUCT(0xff) 669 code: []byte{ 670 byte(vm.PUSH1), 0xff, byte(vm.SELFDESTRUCT), 671 }, 672 step: 1, 673 want: 7600, 674 }, 675 } { 676 tracer := logger.NewStructLogger(nil) 677 Execute(tc.code, nil, &Config{ 678 EVMConfig: vm.Config{ 679 Debug: true, 680 Tracer: tracer, 681 }, 682 }) 683 have := tracer.StructLogs()[tc.step].GasCost 684 if want := tc.want; have != want { 685 for ii, op := range tracer.StructLogs() { 686 t.Logf("%d: %v %d", ii, op.OpName(), op.GasCost) 687 } 688 t.Fatalf("tescase %d, gas report wrong, step %d, have %d want %d", i, tc.step, have, want) 689 } 690 } 691 }