runtime_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. "math/big"
  19. "strings"
  20. "testing"
  21. "github.com/ethereum/go-ethereum/accounts/abi"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/consensus"
  24. "github.com/ethereum/go-ethereum/core"
  25. "github.com/ethereum/go-ethereum/core/rawdb"
  26. "github.com/ethereum/go-ethereum/core/state"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/core/vm"
  29. "github.com/ethereum/go-ethereum/params"
  30. )
  31. func TestDefaults(t *testing.T) {
  32. cfg := new(Config)
  33. setDefaults(cfg)
  34. if cfg.Difficulty == nil {
  35. t.Error("expected difficulty to be non nil")
  36. }
  37. if cfg.Time == nil {
  38. t.Error("expected time to be non nil")
  39. }
  40. if cfg.GasLimit == 0 {
  41. t.Error("didn't expect gaslimit to be zero")
  42. }
  43. if cfg.GasPrice == nil {
  44. t.Error("expected time to be non nil")
  45. }
  46. if cfg.Value == nil {
  47. t.Error("expected time to be non nil")
  48. }
  49. if cfg.GetHashFn == nil {
  50. t.Error("expected time to be non nil")
  51. }
  52. if cfg.BlockNumber == nil {
  53. t.Error("expected block number to be non nil")
  54. }
  55. }
  56. func TestEVM(t *testing.T) {
  57. defer func() {
  58. if r := recover(); r != nil {
  59. t.Fatalf("crashed with: %v", r)
  60. }
  61. }()
  62. Execute([]byte{
  63. byte(vm.DIFFICULTY),
  64. byte(vm.TIMESTAMP),
  65. byte(vm.GASLIMIT),
  66. byte(vm.PUSH1),
  67. byte(vm.ORIGIN),
  68. byte(vm.BLOCKHASH),
  69. byte(vm.COINBASE),
  70. }, nil, nil)
  71. }
  72. func TestExecute(t *testing.T) {
  73. ret, _, err := Execute([]byte{
  74. byte(vm.PUSH1), 10,
  75. byte(vm.PUSH1), 0,
  76. byte(vm.MSTORE),
  77. byte(vm.PUSH1), 32,
  78. byte(vm.PUSH1), 0,
  79. byte(vm.RETURN),
  80. }, nil, nil)
  81. if err != nil {
  82. t.Fatal("didn't expect error", err)
  83. }
  84. num := new(big.Int).SetBytes(ret)
  85. if num.Cmp(big.NewInt(10)) != 0 {
  86. t.Error("Expected 10, got", num)
  87. }
  88. }
  89. func TestCall(t *testing.T) {
  90. state, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  91. address := common.HexToAddress("0x0a")
  92. state.SetCode(address, []byte{
  93. byte(vm.PUSH1), 10,
  94. byte(vm.PUSH1), 0,
  95. byte(vm.MSTORE),
  96. byte(vm.PUSH1), 32,
  97. byte(vm.PUSH1), 0,
  98. byte(vm.RETURN),
  99. })
  100. ret, _, err := Call(address, nil, &Config{State: state})
  101. if err != nil {
  102. t.Fatal("didn't expect error", err)
  103. }
  104. num := new(big.Int).SetBytes(ret)
  105. if num.Cmp(big.NewInt(10)) != 0 {
  106. t.Error("Expected 10, got", num)
  107. }
  108. }
  109. func BenchmarkCall(b *testing.B) {
  110. 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"}]`
  111. var code = common.Hex2Bytes("6060604052361561006c5760e060020a600035046308551a53811461007457806335a063b4146100865780633fa4f245146100a6578063590e1ae3146100af5780637150d8ae146100cf57806373fac6f0146100e1578063c19d93fb146100fe578063d696069714610112575b610131610002565b610133600154600160a060020a031681565b610131600154600160a060020a0390811633919091161461015057610002565b61014660005481565b610131600154600160a060020a039081163391909116146102d557610002565b610133600254600160a060020a031681565b610131600254600160a060020a0333811691161461023757610002565b61014660025460ff60a060020a9091041681565b61013160025460009060ff60a060020a9091041681146101cc57610002565b005b600160a060020a03166060908152602090f35b6060908152602090f35b60025460009060a060020a900460ff16811461016b57610002565b600154600160a060020a03908116908290301631606082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f72c874aeff0b183a56e2b79c71b46e1aed4dee5e09862134b8821ba2fddbf8bf9250a150565b80546002023414806101dd57610002565b6002805460a060020a60ff021973ffffffffffffffffffffffffffffffffffffffff1990911633171660a060020a1790557fd5d55c8a68912e9a110618df8d5e2e83b8d83211c57a8ddd1203df92885dc881826060a15050565b60025460019060a060020a900460ff16811461025257610002565b60025460008054600160a060020a0390921691606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517fe89152acd703c9d8c7d28829d443260b411454d45394e7995815140c8cbcbcf79250a150565b60025460019060a060020a900460ff1681146102f057610002565b6002805460008054600160a060020a0390921692909102606082818181858883f150508354604051600160a060020a0391821694503090911631915082818181858883f150506002805460a060020a60ff02191660a160020a179055506040517f8616bbbbad963e4e65b1366f1d75dfb63f9e9704bbbf91fb01bec70849906cf79250a15056")
  112. abi, err := abi.JSON(strings.NewReader(definition))
  113. if err != nil {
  114. b.Fatal(err)
  115. }
  116. cpurchase, err := abi.Pack("confirmPurchase")
  117. if err != nil {
  118. b.Fatal(err)
  119. }
  120. creceived, err := abi.Pack("confirmReceived")
  121. if err != nil {
  122. b.Fatal(err)
  123. }
  124. refund, err := abi.Pack("refund")
  125. if err != nil {
  126. b.Fatal(err)
  127. }
  128. b.ResetTimer()
  129. for i := 0; i < b.N; i++ {
  130. for j := 0; j < 400; j++ {
  131. Execute(code, cpurchase, nil)
  132. Execute(code, creceived, nil)
  133. Execute(code, refund, nil)
  134. }
  135. }
  136. }
  137. func benchmarkEVM_Create(bench *testing.B, code string) {
  138. var (
  139. statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil)
  140. sender = common.BytesToAddress([]byte("sender"))
  141. receiver = common.BytesToAddress([]byte("receiver"))
  142. )
  143. statedb.CreateAccount(sender)
  144. statedb.SetCode(receiver, common.FromHex(code))
  145. runtimeConfig := Config{
  146. Origin: sender,
  147. State: statedb,
  148. GasLimit: 10000000,
  149. Difficulty: big.NewInt(0x200000),
  150. Time: new(big.Int).SetUint64(0),
  151. Coinbase: common.Address{},
  152. BlockNumber: new(big.Int).SetUint64(1),
  153. ChainConfig: &params.ChainConfig{
  154. ChainID: big.NewInt(1),
  155. HomesteadBlock: new(big.Int),
  156. ByzantiumBlock: new(big.Int),
  157. ConstantinopleBlock: new(big.Int),
  158. DAOForkBlock: new(big.Int),
  159. DAOForkSupport: false,
  160. EIP150Block: new(big.Int),
  161. EIP155Block: new(big.Int),
  162. EIP158Block: new(big.Int),
  163. },
  164. EVMConfig: vm.Config{},
  165. }
  166. // Warm up the intpools and stuff
  167. bench.ResetTimer()
  168. for i := 0; i < bench.N; i++ {
  169. Call(receiver, []byte{}, &runtimeConfig)
  170. }
  171. bench.StopTimer()
  172. }
  173. func BenchmarkEVM_CREATE_500(bench *testing.B) {
  174. // initcode size 500K, repeatedly calls CREATE and then modifies the mem contents
  175. benchmarkEVM_Create(bench, "5b6207a120600080f0600152600056")
  176. }
  177. func BenchmarkEVM_CREATE2_500(bench *testing.B) {
  178. // initcode size 500K, repeatedly calls CREATE2 and then modifies the mem contents
  179. benchmarkEVM_Create(bench, "5b586207a120600080f5600152600056")
  180. }
  181. func BenchmarkEVM_CREATE_1200(bench *testing.B) {
  182. // initcode size 1200K, repeatedly calls CREATE and then modifies the mem contents
  183. benchmarkEVM_Create(bench, "5b62124f80600080f0600152600056")
  184. }
  185. func BenchmarkEVM_CREATE2_1200(bench *testing.B) {
  186. // initcode size 1200K, repeatedly calls CREATE2 and then modifies the mem contents
  187. benchmarkEVM_Create(bench, "5b5862124f80600080f5600152600056")
  188. }
  189. func fakeHeader(n uint64, parentHash common.Hash) *types.Header {
  190. header := types.Header{
  191. Coinbase: common.HexToAddress("0x00000000000000000000000000000000deadbeef"),
  192. Number: big.NewInt(int64(n)),
  193. ParentHash: parentHash,
  194. Time: 1000,
  195. Nonce: types.BlockNonce{0x1},
  196. Extra: []byte{},
  197. Difficulty: big.NewInt(0),
  198. GasLimit: 100000,
  199. }
  200. return &header
  201. }
  202. type dummyChain struct {
  203. counter int
  204. }
  205. // Engine retrieves the chain's consensus engine.
  206. func (d *dummyChain) Engine() consensus.Engine {
  207. return nil
  208. }
  209. // GetHeader returns the hash corresponding to their hash.
  210. func (d *dummyChain) GetHeader(h common.Hash, n uint64) *types.Header {
  211. d.counter++
  212. parentHash := common.Hash{}
  213. s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
  214. copy(parentHash[:], s)
  215. //parentHash := common.Hash{byte(n - 1)}
  216. //fmt.Printf("GetHeader(%x, %d) => header with parent %x\n", h, n, parentHash)
  217. return fakeHeader(n, parentHash)
  218. }
  219. // TestBlockhash tests the blockhash operation. It's a bit special, since it internally
  220. // requires access to a chain reader.
  221. func TestBlockhash(t *testing.T) {
  222. // Current head
  223. n := uint64(1000)
  224. parentHash := common.Hash{}
  225. s := common.LeftPadBytes(big.NewInt(int64(n-1)).Bytes(), 32)
  226. copy(parentHash[:], s)
  227. header := fakeHeader(n, parentHash)
  228. // This is the contract we're using. It requests the blockhash for current num (should be all zeroes),
  229. // then iteratively fetches all blockhashes back to n-260.
  230. // It returns
  231. // 1. the first (should be zero)
  232. // 2. the second (should be the parent hash)
  233. // 3. the last non-zero hash
  234. // By making the chain reader return hashes which correlate to the number, we can
  235. // verify that it obtained the right hashes where it should
  236. /*
  237. pragma solidity ^0.5.3;
  238. contract Hasher{
  239. function test() public view returns (bytes32, bytes32, bytes32){
  240. uint256 x = block.number;
  241. bytes32 first;
  242. bytes32 last;
  243. bytes32 zero;
  244. zero = blockhash(x); // Should be zeroes
  245. first = blockhash(x-1);
  246. for(uint256 i = 2 ; i < 260; i++){
  247. bytes32 hash = blockhash(x - i);
  248. if (uint256(hash) != 0){
  249. last = hash;
  250. }
  251. }
  252. return (zero, first, last);
  253. }
  254. }
  255. */
  256. // The contract above
  257. data := common.Hex2Bytes("6080604052348015600f57600080fd5b50600436106045576000357c010000000000000000000000000000000000000000000000000000000090048063f8a8fd6d14604a575b600080fd5b60506074565b60405180848152602001838152602001828152602001935050505060405180910390f35b600080600080439050600080600083409050600184034092506000600290505b61010481101560c35760008186034090506000816001900414151560b6578093505b5080806001019150506094565b508083839650965096505050505090919256fea165627a7a72305820462d71b510c1725ff35946c20b415b0d50b468ea157c8c77dff9466c9cb85f560029")
  258. // The method call to 'test()'
  259. input := common.Hex2Bytes("f8a8fd6d")
  260. chain := &dummyChain{}
  261. ret, _, err := Execute(data, input, &Config{
  262. GetHashFn: core.GetHashFn(header, chain),
  263. BlockNumber: new(big.Int).Set(header.Number),
  264. })
  265. if err != nil {
  266. t.Fatalf("expected no error, got %v", err)
  267. }
  268. if len(ret) != 96 {
  269. t.Fatalf("expected returndata to be 96 bytes, got %d", len(ret))
  270. }
  271. zero := new(big.Int).SetBytes(ret[0:32])
  272. first := new(big.Int).SetBytes(ret[32:64])
  273. last := new(big.Int).SetBytes(ret[64:96])
  274. if zero.BitLen() != 0 {
  275. t.Fatalf("expected zeroes, got %x", ret[0:32])
  276. }
  277. if first.Uint64() != 999 {
  278. t.Fatalf("second block should be 999, got %d (%x)", first, ret[32:64])
  279. }
  280. if last.Uint64() != 744 {
  281. t.Fatalf("last block should be 744, got %d (%x)", last, ret[64:96])
  282. }
  283. if exp, got := 255, chain.counter; exp != got {
  284. t.Errorf("suboptimal; too much chain iteration, expected %d, got %d", exp, got)
  285. }
  286. }
  287. // BenchmarkSimpleLoop test a pretty simple loop which loops
  288. // 1M (1 048 575) times.
  289. // Takes about 200 ms
  290. func BenchmarkSimpleLoop(b *testing.B) {
  291. // 0xfffff = 1048575 loops
  292. code := []byte{
  293. byte(vm.PUSH3), 0x0f, 0xff, 0xff,
  294. byte(vm.JUMPDEST), // [ count ]
  295. byte(vm.PUSH1), 1, // [count, 1]
  296. byte(vm.SWAP1), // [1, count]
  297. byte(vm.SUB), // [ count -1 ]
  298. byte(vm.DUP1), // [ count -1 , count-1]
  299. byte(vm.PUSH1), 4, // [count-1, count -1, label]
  300. byte(vm.JUMPI), // [ 0 ]
  301. byte(vm.STOP),
  302. }
  303. //tracer := vm.NewJSONLogger(nil, os.Stdout)
  304. //Execute(code, nil, &Config{
  305. // EVMConfig: vm.Config{
  306. // Debug: true,
  307. // Tracer: tracer,
  308. // }})
  309. for i := 0; i < b.N; i++ {
  310. Execute(code, nil, nil)
  311. }
  312. }