runtime_test.go 31 KB

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