runtime_test.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  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/params"
  34. )
  35. func TestDefaults(t *testing.T) {
  36. cfg := new(Config)
  37. setDefaults(cfg)
  38. if cfg.Difficulty == nil {
  39. t.Error("expected difficulty to be non nil")
  40. }
  41. if cfg.Time == nil {
  42. t.Error("expected time to be non nil")
  43. }
  44. if cfg.GasLimit == 0 {
  45. t.Error("didn't expect gaslimit to be zero")
  46. }
  47. if cfg.GasPrice == nil {
  48. t.Error("expected time to be non nil")
  49. }
  50. if cfg.Value == nil {
  51. t.Error("expected time to be non nil")
  52. }
  53. if cfg.GetHashFn == nil {
  54. t.Error("expected time to be non nil")
  55. }
  56. if cfg.BlockNumber == nil {
  57. t.Error("expected block number to be non nil")
  58. }
  59. }
  60. func TestEVM(t *testing.T) {
  61. defer func() {
  62. if r := recover(); r != nil {
  63. t.Fatalf("crashed with: %v", r)
  64. }
  65. }()
  66. Execute([]byte{
  67. byte(vm.DIFFICULTY),
  68. byte(vm.TIMESTAMP),
  69. byte(vm.GASLIMIT),
  70. byte(vm.PUSH1),
  71. byte(vm.ORIGIN),
  72. byte(vm.BLOCKHASH),
  73. byte(vm.COINBASE),
  74. }, nil, nil)
  75. }
  76. func TestExecute(t *testing.T) {
  77. ret, _, err := Execute([]byte{
  78. byte(vm.PUSH1), 10,
  79. byte(vm.PUSH1), 0,
  80. byte(vm.MSTORE),
  81. byte(vm.PUSH1), 32,
  82. byte(vm.PUSH1), 0,
  83. byte(vm.RETURN),
  84. }, nil, nil)
  85. if err != nil {
  86. t.Fatal("didn't expect error", err)
  87. }
  88. num := new(big.Int).SetBytes(ret)
  89. if num.Cmp(big.NewInt(10)) != 0 {
  90. t.Error("Expected 10, got", num)
  91. }
  92. }
  93. func TestCall(t *testing.T) {
  94. state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  95. address := common.HexToAddress("0x0a")
  96. state.SetCode(address, []byte{
  97. byte(vm.PUSH1), 10,
  98. byte(vm.PUSH1), 0,
  99. byte(vm.MSTORE),
  100. byte(vm.PUSH1), 32,
  101. byte(vm.PUSH1), 0,
  102. byte(vm.RETURN),
  103. })
  104. ret, _, err := Call(address, nil, &Config{State: state})
  105. if err != nil {
  106. t.Fatal("didn't expect error", err)
  107. }
  108. num := new(big.Int).SetBytes(ret)
  109. if num.Cmp(big.NewInt(10)) != 0 {
  110. t.Error("Expected 10, got", num)
  111. }
  112. }
  113. func BenchmarkCall(b *testing.B) {
  114. 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"}]`
  115. var code = common.Hex2Bytes("6060604052361561006c5760e060020a600035046308551a53811461007457806335a063b4146100865780633fa4f245146100a6578063590e1ae3146100af5780637150d8ae146100cf57806373fac6f0146100e1578063c19d93fb146100fe578063d696069714610112575b610131610002565b610133600154600160a060020a031681565b610131600154600160a060020a0390811633919091161461015057610002565b61014660005481565b610131600154600160a060020a039081163391909116146102d557610002565b610133600254600160a060020a031681565b610131600254600160a060020a0333811691161461023757610002565b61014660025460ff60a060020a9091041681565b61013160025460009060ff60a060020a9091041681146101cc57610002565b005b600160a060020a03166060908152602090f35b6060908152602090f35b60025460009060a060020a900460ff16811461016b57610002565b600154600160a060020a03908116908290301631606082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f72c874aeff0b183a56e2b79c71b46e1aed4dee5e09862134b8821ba2fddbf8bf9250a150565b80546002023414806101dd57610002565b6002805460a060020a60ff021973ffffffffffffffffffffffffffffffffffffffff1990911633171660a060020a1790557fd5d55c8a68912e9a110618df8d5e2e83b8d83211c57a8ddd1203df92885dc881826060a15050565b60025460019060a060020a900460ff16811461025257610002565b60025460008054600160a060020a0390921691606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517fe89152acd703c9d8c7d28829d443260b411454d45394e7995815140c8cbcbcf79250a150565b60025460019060a060020a900460ff1681146102f057610002565b6002805460008054600160a060020a0390921692909102606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f8616bbbbad963e4e65b1366f1d75dfb63f9e9704bbbf91fb01bec70849906cf79250a15056")
  116. abi, err := abi.JSON(strings.NewReader(definition))
  117. if err != nil {
  118. b.Fatal(err)
  119. }
  120. cpurchase, err := abi.Pack("confirmPurchase")
  121. if err != nil {
  122. b.Fatal(err)
  123. }
  124. creceived, err := abi.Pack("confirmReceived")
  125. if err != nil {
  126. b.Fatal(err)
  127. }
  128. refund, err := abi.Pack("refund")
  129. if err != nil {
  130. b.Fatal(err)
  131. }
  132. b.ResetTimer()
  133. for i := 0; i < b.N; i++ {
  134. for j := 0; j < 400; j++ {
  135. Execute(code, cpurchase, nil)
  136. Execute(code, creceived, nil)
  137. Execute(code, refund, nil)
  138. }
  139. }
  140. }
  141. func benchmarkEVM_Create(bench *testing.B, code string) {
  142. var (
  143. statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  144. sender = common.BytesToAddress([]byte("sender"))
  145. receiver = common.BytesToAddress([]byte("receiver"))
  146. )
  147. statedb.CreateAccount(sender)
  148. statedb.SetCode(receiver, common.FromHex(code))
  149. runtimeConfig := Config{
  150. Origin: sender,
  151. State: statedb,
  152. GasLimit: 10000000,
  153. Difficulty: big.NewInt(0x200000),
  154. Time: new(big.Int).SetUint64(0),
  155. Coinbase: common.Address{},
  156. BlockNumber: new(big.Int).SetUint64(1),
  157. ChainConfig: &params.ChainConfig{
  158. ChainID: big.NewInt(1),
  159. HomesteadBlock: new(big.Int),
  160. ByzantiumBlock: new(big.Int),
  161. ConstantinopleBlock: new(big.Int),
  162. DAOForkBlock: new(big.Int),
  163. DAOForkSupport: false,
  164. EIP150Block: new(big.Int),
  165. EIP155Block: new(big.Int),
  166. EIP158Block: new(big.Int),
  167. },
  168. EVMConfig: vm.Config{},
  169. }
  170. // Warm up the intpools and stuff
  171. bench.ResetTimer()
  172. for i := 0; i < bench.N; i++ {
  173. Call(receiver, []byte{}, &runtimeConfig)
  174. }
  175. bench.StopTimer()
  176. }
  177. func BenchmarkEVM_CREATE_500(bench *testing.B) {
  178. // initcode size 500K, repeatedly calls CREATE and then modifies the mem contents
  179. benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056")
  180. }
  181. func BenchmarkEVM_CREATE2_500(bench *testing.B) {
  182. // initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents
  183. benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056")
  184. }
  185. func BenchmarkEVM_CREATE_1200(bench *testing.B) {
  186. // initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents
  187. benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056")
  188. }
  189. func BenchmarkEVM_CREATE2_1200(bench *testing.B) {
  190. // initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents
  191. benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056")
  192. }
  193. func fakeHeader(n uint64, parentHash common.Hash) *types.Header {
  194. header := types.Header{
  195. Coinbase: common.HexToAddress("0x00000000000000000000000000000000deadbeef"),
  196. Number: big.NewInt(int64(n)),
  197. ParentHash: parentHash,
  198. Time: 1000,
  199. Nonce: types.BlockNonce{0x1},
  200. Extra: []byte{},
  201. Difficulty: big.NewInt(0),
  202. GasLimit: 100000,
  203. }
  204. return &header
  205. }
  206. type dummyChain struct {
  207. counter int
  208. }
  209. // Engine retrieves the chain's consensus engine.
  210. func (d *dummyChain) Engine() consensus.Engine {
  211. return nil
  212. }
  213. // GetHeader returns the hash corresponding to their hash.
  214. func (d *dummyChain) GetHeader(h common.Hash, n uint64) *types.Header {
  215. d.counter++
  216. parentHash := common.Hash{}
  217. s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
  218. copy(parentHash[:], s)
  219. //parentHash := common.Hash{byte(n - 1)}
  220. //fmt.Printf("GetHeader(%x, %d) => header with parent %x\n", h, n, parentHash)
  221. return fakeHeader(n, parentHash)
  222. }
  223. // TestBlockhash tests the blockhash operation. It's a bit special, since it internally
  224. // requires access to a chain reader.
  225. func TestBlockhash(t *testing.T) {
  226. // Current head
  227. n := uint64(1000)
  228. parentHash := common.Hash{}
  229. s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
  230. copy(parentHash[:], s)
  231. header := fakeHeader(n, parentHash)
  232. // This is the contract we're using. It requests the blockhash for current num (should be all zeroes),
  233. // then iteratively fetches all blockhashes back to n-260.
  234. // It returns
  235. // 1. the first (should be zero)
  236. // 2. the second (should be the parent hash)
  237. // 3. the last non-zero hash
  238. // By making the chain reader return hashes which correlate to the number, we can
  239. // verify that it obtained the right hashes where it should
  240. /*
  241. pragma solidity ^0.5.3;
  242. contract Hasher{
  243. function test() public view returns (bytes32, bytes32, bytes32){
  244. uint256 x = block.number;
  245. bytes32 first;
  246. bytes32 last;
  247. bytes32 zero;
  248. zero = blockhash(x); // Should be zeroes
  249. first = blockhash(x-1);
  250. for(uint256 i = 2 ; i < 260; i++){
  251. bytes32 hash = blockhash(x - i);
  252. if (uint256(hash) != 0){
  253. last = hash;
  254. }
  255. }
  256. return (zero, first, last);
  257. }
  258. }
  259. */
  260. // The contract above
  261. data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029")
  262. // The method call to 'test()'
  263. input := common.Hex2Bytes("f8a8fd6d")
  264. chain := &dummyChain{}
  265. ret, _, err := Execute(data, input, &Config{
  266. GetHashFn: core.GetHashFn(header, chain),
  267. BlockNumber: new(big.Int).Set(header.Number),
  268. })
  269. if err != nil {
  270. t.Fatalf("expected no error, got %v", err)
  271. }
  272. if len(ret) != 96 {
  273. t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret))
  274. }
  275. zero := new(big.Int).SetBytes(ret[0:32])
  276. first := new(big.Int).SetBytes(ret[32:64])
  277. last := new(big.Int).SetBytes(ret[64:96])
  278. if zero.BitLen() != 0 {
  279. t.Fatalf("expected zeroes, got %x", ret[0:32])
  280. }
  281. if first.Uint64() != 999 {
  282. t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64])
  283. }
  284. if last.Uint64() != 744 {
  285. t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96])
  286. }
  287. if exp, got := 255, chain.counter; exp != got {
  288. t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got)
  289. }
  290. }
  291. type stepCounter struct {
  292. inner *vm.JSONLogger
  293. steps int
  294. }
  295. func (s *stepCounter) CaptureStart(from common.Address, to common.Address, create bool, input []byte, gas uint64, value *big.Int) error {
  296. return nil
  297. }
  298. func (s *stepCounter) CaptureState(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, rStack *vm.ReturnStack, rData []byte, contract *vm.Contract, depth int, err error) error {
  299. s.steps++
  300. // Enable this for more output
  301. //s.inner.CaptureState(env, pc, op, gas, cost, memory, stack, rStack, contract, depth, err)
  302. return nil
  303. }
  304. func (s *stepCounter) CaptureFault(env *vm.EVM, pc uint64, op vm.OpCode, gas, cost uint64, memory *vm.Memory, stack *vm.Stack, rStack *vm.ReturnStack, contract *vm.Contract, depth int, err error) error {
  305. return nil
  306. }
  307. func (s *stepCounter) CaptureEnd(output []byte, gasUsed uint64, t time.Duration, err error) error {
  308. return nil
  309. }
  310. func TestJumpSub1024Limit(t *testing.T) {
  311. state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  312. address := common.HexToAddress("0x0a")
  313. // Code is
  314. // 0 beginsub
  315. // 1 push 0
  316. // 3 jumpsub
  317. //
  318. // The code recursively calls itself. It should error when the returns-stack
  319. // grows above 1023
  320. state.SetCode(address, []byte{
  321. byte(vm.PUSH1), 3,
  322. byte(vm.JUMPSUB),
  323. byte(vm.BEGINSUB),
  324. byte(vm.PUSH1), 3,
  325. byte(vm.JUMPSUB),
  326. })
  327. tracer := stepCounter{inner: vm.NewJSONLogger(nil, os.Stdout)}
  328. // Enable 2315
  329. _, _, err := Call(address, nil, &Config{State: state,
  330. GasLimit: 20000,
  331. ChainConfig: params.AllEthashProtocolChanges,
  332. EVMConfig: vm.Config{
  333. ExtraEips: []int{2315},
  334. Debug: true,
  335. //Tracer: vm.NewJSONLogger(nil, os.Stdout),
  336. Tracer: &tracer,
  337. }})
  338. exp := "return stack limit reached"
  339. if err.Error() != exp {
  340. t.Fatalf("expected %v, got %v", exp, err)
  341. }
  342. if exp, got := 2048, tracer.steps; exp != got {
  343. t.Fatalf("expected %d steps, got %d", exp, got)
  344. }
  345. }
  346. func TestReturnSubShallow(t *testing.T) {
  347. state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  348. address := common.HexToAddress("0x0a")
  349. // The code does returnsub without having anything on the returnstack.
  350. // It should not panic, but just fail after one step
  351. state.SetCode(address, []byte{
  352. byte(vm.PUSH1), 5,
  353. byte(vm.JUMPSUB),
  354. byte(vm.RETURNSUB),
  355. byte(vm.PC),
  356. byte(vm.BEGINSUB),
  357. byte(vm.RETURNSUB),
  358. byte(vm.PC),
  359. })
  360. tracer := stepCounter{}
  361. // Enable 2315
  362. _, _, err := Call(address, nil, &Config{State: state,
  363. GasLimit: 10000,
  364. ChainConfig: params.AllEthashProtocolChanges,
  365. EVMConfig: vm.Config{
  366. ExtraEips: []int{2315},
  367. Debug: true,
  368. Tracer: &tracer,
  369. }})
  370. exp := "invalid retsub"
  371. if err.Error() != exp {
  372. t.Fatalf("expected %v, got %v", exp, err)
  373. }
  374. if exp, got := 4, tracer.steps; exp != got {
  375. t.Fatalf("expected %d steps, got %d", exp, got)
  376. }
  377. }
  378. // disabled -- only used for generating markdown
  379. func DisabledTestReturnCases(t *testing.T) {
  380. cfg := &Config{
  381. EVMConfig: vm.Config{
  382. Debug: true,
  383. Tracer: vm.NewMarkdownLogger(nil, os.Stdout),
  384. ExtraEips: []int{2315},
  385. },
  386. }
  387. // This should fail at first opcode
  388. Execute([]byte{
  389. byte(vm.RETURNSUB),
  390. byte(vm.PC),
  391. byte(vm.PC),
  392. }, nil, cfg)
  393. // Should also fail
  394. Execute([]byte{
  395. byte(vm.PUSH1), 5,
  396. byte(vm.JUMPSUB),
  397. byte(vm.RETURNSUB),
  398. byte(vm.PC),
  399. byte(vm.BEGINSUB),
  400. byte(vm.RETURNSUB),
  401. byte(vm.PC),
  402. }, nil, cfg)
  403. // This should complete
  404. Execute([]byte{
  405. byte(vm.PUSH1), 0x4,
  406. byte(vm.JUMPSUB),
  407. byte(vm.STOP),
  408. byte(vm.BEGINSUB),
  409. byte(vm.PUSH1), 0x9,
  410. byte(vm.JUMPSUB),
  411. byte(vm.RETURNSUB),
  412. byte(vm.BEGINSUB),
  413. byte(vm.RETURNSUB),
  414. }, nil, cfg)
  415. }
  416. // DisabledTestEipExampleCases contains various testcases that are used for the
  417. // EIP examples
  418. // This test is disabled, as it's only used for generating markdown
  419. func DisabledTestEipExampleCases(t *testing.T) {
  420. cfg := &Config{
  421. EVMConfig: vm.Config{
  422. Debug: true,
  423. Tracer: vm.NewMarkdownLogger(nil, os.Stdout),
  424. ExtraEips: []int{2315},
  425. },
  426. }
  427. prettyPrint := func(comment string, code []byte) {
  428. instrs := make([]string, 0)
  429. it := asm.NewInstructionIterator(code)
  430. for it.Next() {
  431. if it.Arg() != nil && 0 < len(it.Arg()) {
  432. instrs = append(instrs, fmt.Sprintf("%v 0x%x", it.Op(), it.Arg()))
  433. } else {
  434. instrs = append(instrs, fmt.Sprintf("%v", it.Op()))
  435. }
  436. }
  437. ops := strings.Join(instrs, ", ")
  438. fmt.Printf("%v\nBytecode: `0x%x` (`%v`)\n",
  439. comment,
  440. code, ops)
  441. Execute(code, nil, cfg)
  442. }
  443. { // First eip testcase
  444. code := []byte{
  445. byte(vm.PUSH1), 4,
  446. byte(vm.JUMPSUB),
  447. byte(vm.STOP),
  448. byte(vm.BEGINSUB),
  449. byte(vm.RETURNSUB),
  450. }
  451. prettyPrint("This should jump into a subroutine, back out and stop.", code)
  452. }
  453. {
  454. code := []byte{
  455. byte(vm.PUSH9), 0x00, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, 4 + 8,
  456. byte(vm.JUMPSUB),
  457. byte(vm.STOP),
  458. byte(vm.BEGINSUB),
  459. byte(vm.PUSH1), 8 + 9,
  460. byte(vm.JUMPSUB),
  461. byte(vm.RETURNSUB),
  462. byte(vm.BEGINSUB),
  463. byte(vm.RETURNSUB),
  464. }
  465. prettyPrint("This should execute fine, going into one two depths of subroutines", code)
  466. }
  467. // TODO(@holiman) move this test into an actual test, which not only prints
  468. // out the trace.
  469. {
  470. code := []byte{
  471. byte(vm.PUSH9), 0x01, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00, 0x00, 4 + 8,
  472. byte(vm.JUMPSUB),
  473. byte(vm.STOP),
  474. byte(vm.BEGINSUB),
  475. byte(vm.PUSH1), 8 + 9,
  476. byte(vm.JUMPSUB),
  477. byte(vm.RETURNSUB),
  478. byte(vm.BEGINSUB),
  479. byte(vm.RETURNSUB),
  480. }
  481. prettyPrint("This should fail, since the given location is outside of the "+
  482. "code-range. The code is the same as previous example, except that the "+
  483. "pushed location is `0x01000000000000000c` instead of `0x0c`.", code)
  484. }
  485. {
  486. // This should fail at first opcode
  487. code := []byte{
  488. byte(vm.RETURNSUB),
  489. byte(vm.PC),
  490. byte(vm.PC),
  491. }
  492. prettyPrint("This should fail at first opcode, due to shallow `return_stack`", code)
  493. }
  494. {
  495. code := []byte{
  496. byte(vm.PUSH1), 5, // Jump past the subroutine
  497. byte(vm.JUMP),
  498. byte(vm.BEGINSUB),
  499. byte(vm.RETURNSUB),
  500. byte(vm.JUMPDEST),
  501. byte(vm.PUSH1), 3, // Now invoke the subroutine
  502. byte(vm.JUMPSUB),
  503. }
  504. prettyPrint("In this example. the JUMPSUB is on the last byte of code. When the "+
  505. "subroutine returns, it should hit the 'virtual stop' _after_ the bytecode, "+
  506. "and not exit with error", code)
  507. }
  508. {
  509. code := []byte{
  510. byte(vm.BEGINSUB),
  511. byte(vm.RETURNSUB),
  512. byte(vm.STOP),
  513. }
  514. prettyPrint("In this example, the code 'walks' into a subroutine, which is not "+
  515. "allowed, and causes an error", code)
  516. }
  517. }
  518. // benchmarkNonModifyingCode benchmarks code, but if the code modifies the
  519. // state, this should not be used, since it does not reset the state between runs.
  520. func benchmarkNonModifyingCode(gas uint64, code []byte, name string, b *testing.B) {
  521. cfg := new(Config)
  522. setDefaults(cfg)
  523. cfg.State, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  524. cfg.GasLimit = gas
  525. var (
  526. destination = common.BytesToAddress([]byte("contract"))
  527. vmenv = NewEnv(cfg)
  528. sender = vm.AccountRef(cfg.Origin)
  529. )
  530. cfg.State.CreateAccount(destination)
  531. eoa := common.HexToAddress("E0")
  532. {
  533. cfg.State.CreateAccount(eoa)
  534. cfg.State.SetNonce(eoa, 100)
  535. }
  536. reverting := common.HexToAddress("EE")
  537. {
  538. cfg.State.CreateAccount(reverting)
  539. cfg.State.SetCode(reverting, []byte{
  540. byte(vm.PUSH1), 0x00,
  541. byte(vm.PUSH1), 0x00,
  542. byte(vm.REVERT),
  543. })
  544. }
  545. //cfg.State.CreateAccount(cfg.Origin)
  546. // set the receiver's (the executing contract) code for execution.
  547. cfg.State.SetCode(destination, code)
  548. vmenv.Call(sender, destination, nil, gas, cfg.Value)
  549. b.Run(name, func(b *testing.B) {
  550. b.ReportAllocs()
  551. for i := 0; i < b.N; i++ {
  552. vmenv.Call(sender, destination, nil, gas, cfg.Value)
  553. }
  554. })
  555. }
  556. // BenchmarkSimpleLoop test a pretty simple loop which loops until OOG
  557. // 55 ms
  558. func BenchmarkSimpleLoop(b *testing.B) {
  559. staticCallIdentity := []byte{
  560. byte(vm.JUMPDEST), // [ count ]
  561. // push args for the call
  562. byte(vm.PUSH1), 0, // out size
  563. byte(vm.DUP1), // out offset
  564. byte(vm.DUP1), // out insize
  565. byte(vm.DUP1), // in offset
  566. byte(vm.PUSH1), 0x4, // address of identity
  567. byte(vm.GAS), // gas
  568. byte(vm.STATICCALL),
  569. byte(vm.POP), // pop return value
  570. byte(vm.PUSH1), 0, // jumpdestination
  571. byte(vm.JUMP),
  572. }
  573. callIdentity := []byte{
  574. byte(vm.JUMPDEST), // [ count ]
  575. // push args for the call
  576. byte(vm.PUSH1), 0, // out size
  577. byte(vm.DUP1), // out offset
  578. byte(vm.DUP1), // out insize
  579. byte(vm.DUP1), // in offset
  580. byte(vm.DUP1), // value
  581. byte(vm.PUSH1), 0x4, // address of identity
  582. byte(vm.GAS), // gas
  583. byte(vm.CALL),
  584. byte(vm.POP), // pop return value
  585. byte(vm.PUSH1), 0, // jumpdestination
  586. byte(vm.JUMP),
  587. }
  588. callInexistant := []byte{
  589. byte(vm.JUMPDEST), // [ count ]
  590. // push args for the call
  591. byte(vm.PUSH1), 0, // out size
  592. byte(vm.DUP1), // out offset
  593. byte(vm.DUP1), // out insize
  594. byte(vm.DUP1), // in offset
  595. byte(vm.DUP1), // value
  596. byte(vm.PUSH1), 0xff, // address of existing contract
  597. byte(vm.GAS), // gas
  598. byte(vm.CALL),
  599. byte(vm.POP), // pop return value
  600. byte(vm.PUSH1), 0, // jumpdestination
  601. byte(vm.JUMP),
  602. }
  603. callEOA := []byte{
  604. byte(vm.JUMPDEST), // [ count ]
  605. // push args for the call
  606. byte(vm.PUSH1), 0, // out size
  607. byte(vm.DUP1), // out offset
  608. byte(vm.DUP1), // out insize
  609. byte(vm.DUP1), // in offset
  610. byte(vm.DUP1), // value
  611. byte(vm.PUSH1), 0xE0, // address of EOA
  612. byte(vm.GAS), // gas
  613. byte(vm.CALL),
  614. byte(vm.POP), // pop return value
  615. byte(vm.PUSH1), 0, // jumpdestination
  616. byte(vm.JUMP),
  617. }
  618. loopingCode := []byte{
  619. byte(vm.JUMPDEST), // [ count ]
  620. // push args for the call
  621. byte(vm.PUSH1), 0, // out size
  622. byte(vm.DUP1), // out offset
  623. byte(vm.DUP1), // out insize
  624. byte(vm.DUP1), // in offset
  625. byte(vm.PUSH1), 0x4, // address of identity
  626. byte(vm.GAS), // gas
  627. byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP), byte(vm.POP),
  628. byte(vm.PUSH1), 0, // jumpdestination
  629. byte(vm.JUMP),
  630. }
  631. calllRevertingContractWithInput := []byte{
  632. byte(vm.JUMPDEST), //
  633. // push args for the call
  634. byte(vm.PUSH1), 0, // out size
  635. byte(vm.DUP1), // out offset
  636. byte(vm.PUSH1), 0x20, // in size
  637. byte(vm.PUSH1), 0x00, // in offset
  638. byte(vm.PUSH1), 0x00, // value
  639. byte(vm.PUSH1), 0xEE, // address of reverting contract
  640. byte(vm.GAS), // gas
  641. byte(vm.CALL),
  642. byte(vm.POP), // pop return value
  643. byte(vm.PUSH1), 0, // jumpdestination
  644. byte(vm.JUMP),
  645. }
  646. //tracer := vm.NewJSONLogger(nil, os.Stdout)
  647. //Execute(loopingCode, nil, &Config{
  648. // EVMConfig: vm.Config{
  649. // Debug: true,
  650. // Tracer: tracer,
  651. // }})
  652. // 100M gas
  653. benchmarkNonModifyingCode(100000000, staticCallIdentity, "staticcall-identity-100M", b)
  654. benchmarkNonModifyingCode(100000000, callIdentity, "call-identity-100M", b)
  655. benchmarkNonModifyingCode(100000000, loopingCode, "loop-100M", b)
  656. benchmarkNonModifyingCode(100000000, callInexistant, "call-nonexist-100M", b)
  657. benchmarkNonModifyingCode(100000000, callEOA, "call-EOA-100M", b)
  658. benchmarkNonModifyingCode(100000000, calllRevertingContractWithInput, "call-reverting-100M", b)
  659. //benchmarkNonModifyingCode(10000000, staticCallIdentity, "staticcall-identity-10M", b)
  660. //benchmarkNonModifyingCode(10000000, loopingCode, "loop-10M", b)
  661. }
  662. // TestEip2929Cases contains various testcases that are used for
  663. // EIP-2929 about gas repricings
  664. func TestEip2929Cases(t *testing.T) {
  665. id := 1
  666. prettyPrint := func(comment string, code []byte) {
  667. instrs := make([]string, 0)
  668. it := asm.NewInstructionIterator(code)
  669. for it.Next() {
  670. if it.Arg() != nil && 0 < len(it.Arg()) {
  671. instrs = append(instrs, fmt.Sprintf("%v 0x%x", it.Op(), it.Arg()))
  672. } else {
  673. instrs = append(instrs, fmt.Sprintf("%v", it.Op()))
  674. }
  675. }
  676. ops := strings.Join(instrs, ", ")
  677. fmt.Printf("### Case %d\n\n", id)
  678. id++
  679. fmt.Printf("%v\n\nBytecode: \n```\n0x%x\n```\nOperations: \n```\n%v\n```\n\n",
  680. comment,
  681. code, ops)
  682. Execute(code, nil, &Config{
  683. EVMConfig: vm.Config{
  684. Debug: true,
  685. Tracer: vm.NewMarkdownLogger(nil, os.Stdout),
  686. ExtraEips: []int{2929},
  687. },
  688. })
  689. }
  690. { // First eip testcase
  691. code := []byte{
  692. // Three checks against a precompile
  693. byte(vm.PUSH1), 1, byte(vm.EXTCODEHASH), byte(vm.POP),
  694. byte(vm.PUSH1), 2, byte(vm.EXTCODESIZE), byte(vm.POP),
  695. byte(vm.PUSH1), 3, byte(vm.BALANCE), byte(vm.POP),
  696. // Three checks against a non-precompile
  697. byte(vm.PUSH1), 0xf1, byte(vm.EXTCODEHASH), byte(vm.POP),
  698. byte(vm.PUSH1), 0xf2, byte(vm.EXTCODESIZE), byte(vm.POP),
  699. byte(vm.PUSH1), 0xf3, byte(vm.BALANCE), byte(vm.POP),
  700. // Same three checks (should be cheaper)
  701. byte(vm.PUSH1), 0xf2, byte(vm.EXTCODEHASH), byte(vm.POP),
  702. byte(vm.PUSH1), 0xf3, byte(vm.EXTCODESIZE), byte(vm.POP),
  703. byte(vm.PUSH1), 0xf1, byte(vm.BALANCE), byte(vm.POP),
  704. // Check the origin, and the 'this'
  705. byte(vm.ORIGIN), byte(vm.BALANCE), byte(vm.POP),
  706. byte(vm.ADDRESS), byte(vm.BALANCE), byte(vm.POP),
  707. byte(vm.STOP),
  708. }
  709. prettyPrint("This checks `EXT`(codehash,codesize,balance) of precompiles, which should be `100`, "+
  710. "and later checks the same operations twice against some non-precompiles. "+
  711. "Those are cheaper second time they are accessed. Lastly, it checks the `BALANCE` of `origin` and `this`.", code)
  712. }
  713. { // EXTCODECOPY
  714. code := []byte{
  715. // extcodecopy( 0xff,0,0,0,0)
  716. byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset
  717. byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY),
  718. // extcodecopy( 0xff,0,0,0,0)
  719. byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset
  720. byte(vm.PUSH1), 0xff, byte(vm.EXTCODECOPY),
  721. // extcodecopy( this,0,0,0,0)
  722. byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, byte(vm.PUSH1), 0x00, //length, codeoffset, memoffset
  723. byte(vm.ADDRESS), byte(vm.EXTCODECOPY),
  724. byte(vm.STOP),
  725. }
  726. prettyPrint("This checks `extcodecopy( 0xff,0,0,0,0)` twice, (should be expensive first time), "+
  727. "and then does `extcodecopy( this,0,0,0,0)`.", code)
  728. }
  729. { // SLOAD + SSTORE
  730. code := []byte{
  731. // Add slot `0x1` to access list
  732. byte(vm.PUSH1), 0x01, byte(vm.SLOAD), byte(vm.POP), // SLOAD( 0x1) (add to access list)
  733. // Write to `0x1` which is already in access list
  734. byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x01, byte(vm.SSTORE), // SSTORE( loc: 0x01, val: 0x11)
  735. // Write to `0x2` which is not in access list
  736. byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11)
  737. // Write again to `0x2`
  738. byte(vm.PUSH1), 0x11, byte(vm.PUSH1), 0x02, byte(vm.SSTORE), // SSTORE( loc: 0x02, val: 0x11)
  739. // Read slot in access list (0x2)
  740. byte(vm.PUSH1), 0x02, byte(vm.SLOAD), // SLOAD( 0x2)
  741. // Read slot in access list (0x1)
  742. byte(vm.PUSH1), 0x01, byte(vm.SLOAD), // SLOAD( 0x1)
  743. }
  744. prettyPrint("This checks `sload( 0x1)` followed by `sstore(loc: 0x01, val:0x11)`, then 'naked' sstore:"+
  745. "`sstore(loc: 0x02, val:0x11)` twice, and `sload(0x2)`, `sload(0x1)`. ", code)
  746. }
  747. { // Call variants
  748. code := []byte{
  749. // identity precompile
  750. byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
  751. byte(vm.PUSH1), 0x04, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP),
  752. // random account - call 1
  753. byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
  754. byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.CALL), byte(vm.POP),
  755. // random account - call 2
  756. byte(vm.PUSH1), 0x0, byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1), byte(vm.DUP1),
  757. byte(vm.PUSH1), 0xff, byte(vm.PUSH1), 0x0, byte(vm.STATICCALL), byte(vm.POP),
  758. }
  759. prettyPrint("This calls the `identity`-precompile (cheap), then calls an account (expensive) and `staticcall`s the same"+
  760. "account (cheap)", code)
  761. }
  762. }