util.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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 tests
  17. import (
  18. "bytes"
  19. "encoding/hex"
  20. "fmt"
  21. "math/big"
  22. "os"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/common/math"
  25. "github.com/ethereum/go-ethereum/core"
  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/crypto"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/log"
  32. "github.com/ethereum/go-ethereum/params"
  33. )
  34. var (
  35. ForceJit bool
  36. EnableJit bool
  37. )
  38. func init() {
  39. log.Root().SetHandler(log.LvlFilterHandler(log.LvlCrit, log.StreamHandler(os.Stderr, log.TerminalFormat(false))))
  40. if os.Getenv("JITVM") == "true" {
  41. ForceJit = true
  42. EnableJit = true
  43. }
  44. }
  45. func checkLogs(tlog []Log, logs []*types.Log) error {
  46. if len(tlog) != len(logs) {
  47. return fmt.Errorf("log length mismatch. Expected %d, got %d", len(tlog), len(logs))
  48. } else {
  49. for i, log := range tlog {
  50. if common.HexToAddress(log.AddressF) != logs[i].Address {
  51. return fmt.Errorf("log address expected %v got %x", log.AddressF, logs[i].Address)
  52. }
  53. if !bytes.Equal(logs[i].Data, common.FromHex(log.DataF)) {
  54. return fmt.Errorf("log data expected %v got %x", log.DataF, logs[i].Data)
  55. }
  56. if len(log.TopicsF) != len(logs[i].Topics) {
  57. return fmt.Errorf("log topics length expected %d got %d", len(log.TopicsF), logs[i].Topics)
  58. } else {
  59. for j, topic := range log.TopicsF {
  60. if common.HexToHash(topic) != logs[i].Topics[j] {
  61. return fmt.Errorf("log topic[%d] expected %v got %x", j, topic, logs[i].Topics[j])
  62. }
  63. }
  64. }
  65. genBloom := common.LeftPadBytes(types.LogsBloom([]*types.Log{logs[i]}).Bytes(), 256)
  66. if !bytes.Equal(genBloom, common.Hex2Bytes(log.BloomF)) {
  67. return fmt.Errorf("bloom mismatch")
  68. }
  69. }
  70. }
  71. return nil
  72. }
  73. type Account struct {
  74. Balance string
  75. Code string
  76. Nonce string
  77. Storage map[string]string
  78. }
  79. type Log struct {
  80. AddressF string `json:"address"`
  81. DataF string `json:"data"`
  82. TopicsF []string `json:"topics"`
  83. BloomF string `json:"bloom"`
  84. }
  85. func (self Log) Address() []byte { return common.Hex2Bytes(self.AddressF) }
  86. func (self Log) Data() []byte { return common.Hex2Bytes(self.DataF) }
  87. func (self Log) RlpData() interface{} { return nil }
  88. func (self Log) Topics() [][]byte {
  89. t := make([][]byte, len(self.TopicsF))
  90. for i, topic := range self.TopicsF {
  91. t[i] = common.Hex2Bytes(topic)
  92. }
  93. return t
  94. }
  95. func makePreState(db ethdb.Database, accounts map[string]Account) *state.StateDB {
  96. statedb, _ := state.New(common.Hash{}, db)
  97. for addr, account := range accounts {
  98. insertAccount(statedb, addr, account)
  99. }
  100. return statedb
  101. }
  102. func insertAccount(state *state.StateDB, saddr string, account Account) {
  103. if common.IsHex(account.Code) {
  104. account.Code = account.Code[2:]
  105. }
  106. addr := common.HexToAddress(saddr)
  107. state.SetCode(addr, common.Hex2Bytes(account.Code))
  108. state.SetNonce(addr, math.MustParseUint64(account.Nonce))
  109. state.SetBalance(addr, math.MustParseBig256(account.Balance))
  110. for a, v := range account.Storage {
  111. state.SetState(addr, common.HexToHash(a), common.HexToHash(v))
  112. }
  113. }
  114. type VmEnv struct {
  115. CurrentCoinbase string
  116. CurrentDifficulty string
  117. CurrentGasLimit string
  118. CurrentNumber string
  119. CurrentTimestamp interface{}
  120. PreviousHash string
  121. }
  122. type VmTest struct {
  123. Callcreates interface{}
  124. //Env map[string]string
  125. Env VmEnv
  126. Exec map[string]string
  127. Transaction map[string]string
  128. Logs []Log
  129. Gas string
  130. Out string
  131. Post map[string]Account
  132. Pre map[string]Account
  133. PostStateRoot string
  134. }
  135. func NewEVMEnvironment(vmTest bool, chainConfig *params.ChainConfig, statedb *state.StateDB, envValues map[string]string, tx map[string]string) (*vm.EVM, core.Message) {
  136. var (
  137. data = common.FromHex(tx["data"])
  138. gas = math.MustParseBig256(tx["gasLimit"])
  139. price = math.MustParseBig256(tx["gasPrice"])
  140. value = math.MustParseBig256(tx["value"])
  141. nonce = math.MustParseUint64(tx["nonce"])
  142. )
  143. origin := common.HexToAddress(tx["caller"])
  144. if len(tx["secretKey"]) > 0 {
  145. key, _ := hex.DecodeString(tx["secretKey"])
  146. origin = crypto.PubkeyToAddress(crypto.ToECDSA(key).PublicKey)
  147. }
  148. var to *common.Address
  149. if len(tx["to"]) > 2 {
  150. t := common.HexToAddress(tx["to"])
  151. to = &t
  152. }
  153. msg := types.NewMessage(origin, to, nonce, value, gas, price, data, true)
  154. initialCall := true
  155. canTransfer := func(db vm.StateDB, address common.Address, amount *big.Int) bool {
  156. if vmTest {
  157. if initialCall {
  158. initialCall = false
  159. return true
  160. }
  161. }
  162. return core.CanTransfer(db, address, amount)
  163. }
  164. transfer := func(db vm.StateDB, sender, recipient common.Address, amount *big.Int) {
  165. if vmTest {
  166. return
  167. }
  168. core.Transfer(db, sender, recipient, amount)
  169. }
  170. context := vm.Context{
  171. CanTransfer: canTransfer,
  172. Transfer: transfer,
  173. GetHash: func(n uint64) common.Hash {
  174. return common.BytesToHash(crypto.Keccak256([]byte(big.NewInt(int64(n)).String())))
  175. },
  176. Origin: origin,
  177. Coinbase: common.HexToAddress(envValues["currentCoinbase"]),
  178. BlockNumber: math.MustParseBig256(envValues["currentNumber"]),
  179. Time: math.MustParseBig256(envValues["currentTimestamp"]),
  180. GasLimit: math.MustParseBig256(envValues["currentGasLimit"]),
  181. Difficulty: math.MustParseBig256(envValues["currentDifficulty"]),
  182. GasPrice: price,
  183. }
  184. if context.GasPrice == nil {
  185. context.GasPrice = new(big.Int)
  186. }
  187. return vm.NewEVM(context, statedb, chainConfig, vm.Config{NoRecursion: vmTest}), msg
  188. }