main.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU 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. // go-ethereum 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 General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. // evm executes EVM code snippets.
  17. package main
  18. import (
  19. "fmt"
  20. "io/ioutil"
  21. "math/big"
  22. "os"
  23. "runtime"
  24. "time"
  25. "github.com/ethereum/go-ethereum/cmd/utils"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/core"
  28. "github.com/ethereum/go-ethereum/core/state"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/core/vm"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/ethdb"
  33. "github.com/ethereum/go-ethereum/logger/glog"
  34. "github.com/ethereum/go-ethereum/params"
  35. "gopkg.in/urfave/cli.v1"
  36. )
  37. var gitCommit = "" // Git SHA1 commit hash of the release (set via linker flags)
  38. var (
  39. app = utils.NewApp(gitCommit, "the evm command line interface")
  40. DebugFlag = cli.BoolFlag{
  41. Name: "debug",
  42. Usage: "output full trace logs",
  43. }
  44. ForceJitFlag = cli.BoolFlag{
  45. Name: "forcejit",
  46. Usage: "forces jit compilation",
  47. }
  48. DisableJitFlag = cli.BoolFlag{
  49. Name: "nojit",
  50. Usage: "disabled jit compilation",
  51. }
  52. CodeFlag = cli.StringFlag{
  53. Name: "code",
  54. Usage: "EVM code",
  55. }
  56. CodeFileFlag = cli.StringFlag{
  57. Name: "codefile",
  58. Usage: "file containing EVM code",
  59. }
  60. GasFlag = cli.StringFlag{
  61. Name: "gas",
  62. Usage: "gas limit for the evm",
  63. Value: "10000000000",
  64. }
  65. PriceFlag = cli.StringFlag{
  66. Name: "price",
  67. Usage: "price set for the evm",
  68. Value: "0",
  69. }
  70. ValueFlag = cli.StringFlag{
  71. Name: "value",
  72. Usage: "value set for the evm",
  73. Value: "0",
  74. }
  75. DumpFlag = cli.BoolFlag{
  76. Name: "dump",
  77. Usage: "dumps the state after the run",
  78. }
  79. InputFlag = cli.StringFlag{
  80. Name: "input",
  81. Usage: "input for the EVM",
  82. }
  83. SysStatFlag = cli.BoolFlag{
  84. Name: "sysstat",
  85. Usage: "display system stats",
  86. }
  87. VerbosityFlag = cli.IntFlag{
  88. Name: "verbosity",
  89. Usage: "sets the verbosity level",
  90. }
  91. CreateFlag = cli.BoolFlag{
  92. Name: "create",
  93. Usage: "indicates the action should be create rather than call",
  94. }
  95. )
  96. func init() {
  97. app.Flags = []cli.Flag{
  98. CreateFlag,
  99. DebugFlag,
  100. VerbosityFlag,
  101. ForceJitFlag,
  102. DisableJitFlag,
  103. SysStatFlag,
  104. CodeFlag,
  105. CodeFileFlag,
  106. GasFlag,
  107. PriceFlag,
  108. ValueFlag,
  109. DumpFlag,
  110. InputFlag,
  111. }
  112. app.Action = run
  113. }
  114. func run(ctx *cli.Context) error {
  115. glog.SetToStderr(true)
  116. glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))
  117. db, _ := ethdb.NewMemDatabase()
  118. statedb, _ := state.New(common.Hash{}, db)
  119. sender := statedb.CreateAccount(common.StringToAddress("sender"))
  120. logger := vm.NewStructLogger(nil)
  121. vmenv := NewEnv(statedb, common.StringToAddress("evmuser"), common.Big(ctx.GlobalString(ValueFlag.Name)), vm.Config{
  122. Debug: ctx.GlobalBool(DebugFlag.Name),
  123. ForceJit: ctx.GlobalBool(ForceJitFlag.Name),
  124. EnableJit: !ctx.GlobalBool(DisableJitFlag.Name),
  125. Tracer: logger,
  126. })
  127. tstart := time.Now()
  128. var (
  129. code []byte
  130. ret []byte
  131. err error
  132. )
  133. if ctx.GlobalString(CodeFlag.Name) != "" {
  134. code = common.Hex2Bytes(ctx.GlobalString(CodeFlag.Name))
  135. } else {
  136. var hexcode []byte
  137. if ctx.GlobalString(CodeFileFlag.Name) != "" {
  138. var err error
  139. hexcode, err = ioutil.ReadFile(ctx.GlobalString(CodeFileFlag.Name))
  140. if err != nil {
  141. fmt.Printf("Could not load code from file: %v\n", err)
  142. os.Exit(1)
  143. }
  144. } else {
  145. var err error
  146. hexcode, err = ioutil.ReadAll(os.Stdin)
  147. if err != nil {
  148. fmt.Printf("Could not load code from stdin: %v\n", err)
  149. os.Exit(1)
  150. }
  151. }
  152. code = common.Hex2Bytes(string(hexcode[:]))
  153. }
  154. if ctx.GlobalBool(CreateFlag.Name) {
  155. input := append(code, common.Hex2Bytes(ctx.GlobalString(InputFlag.Name))...)
  156. ret, _, err = vmenv.Create(
  157. sender,
  158. input,
  159. common.Big(ctx.GlobalString(GasFlag.Name)),
  160. common.Big(ctx.GlobalString(PriceFlag.Name)),
  161. common.Big(ctx.GlobalString(ValueFlag.Name)),
  162. )
  163. } else {
  164. receiver := statedb.CreateAccount(common.StringToAddress("receiver"))
  165. receiver.SetCode(crypto.Keccak256Hash(code), code)
  166. ret, err = vmenv.Call(
  167. sender,
  168. receiver.Address(),
  169. common.Hex2Bytes(ctx.GlobalString(InputFlag.Name)),
  170. common.Big(ctx.GlobalString(GasFlag.Name)),
  171. common.Big(ctx.GlobalString(PriceFlag.Name)),
  172. common.Big(ctx.GlobalString(ValueFlag.Name)),
  173. )
  174. }
  175. vmdone := time.Since(tstart)
  176. if ctx.GlobalBool(DumpFlag.Name) {
  177. statedb.Commit(true)
  178. fmt.Println(string(statedb.Dump()))
  179. }
  180. vm.StdErrFormat(logger.StructLogs())
  181. if ctx.GlobalBool(SysStatFlag.Name) {
  182. var mem runtime.MemStats
  183. runtime.ReadMemStats(&mem)
  184. fmt.Printf("vm took %v\n", vmdone)
  185. fmt.Printf(`alloc: %d
  186. tot alloc: %d
  187. no. malloc: %d
  188. heap alloc: %d
  189. heap objs: %d
  190. num gc: %d
  191. `, mem.Alloc, mem.TotalAlloc, mem.Mallocs, mem.HeapAlloc, mem.HeapObjects, mem.NumGC)
  192. }
  193. fmt.Printf("OUT: 0x%x", ret)
  194. if err != nil {
  195. fmt.Printf(" error: %v", err)
  196. }
  197. fmt.Println()
  198. return nil
  199. }
  200. func main() {
  201. if err := app.Run(os.Args); err != nil {
  202. fmt.Fprintln(os.Stderr, err)
  203. os.Exit(1)
  204. }
  205. }
  206. type VMEnv struct {
  207. state *state.StateDB
  208. block *types.Block
  209. transactor *common.Address
  210. value *big.Int
  211. depth int
  212. Gas *big.Int
  213. time *big.Int
  214. logs []vm.StructLog
  215. evm *vm.EVM
  216. }
  217. func NewEnv(state *state.StateDB, transactor common.Address, value *big.Int, cfg vm.Config) *VMEnv {
  218. env := &VMEnv{
  219. state: state,
  220. transactor: &transactor,
  221. value: value,
  222. time: big.NewInt(time.Now().Unix()),
  223. }
  224. env.evm = vm.New(env, cfg)
  225. return env
  226. }
  227. // ruleSet implements vm.ChainConfig and will always default to the homestead rule set.
  228. type ruleSet struct{}
  229. func (ruleSet) IsHomestead(*big.Int) bool { return true }
  230. func (ruleSet) GasTable(*big.Int) params.GasTable {
  231. return params.GasTableHomesteadGasRepriceFork
  232. }
  233. func (self *VMEnv) ChainConfig() *params.ChainConfig { return params.TestChainConfig }
  234. func (self *VMEnv) Vm() vm.Vm { return self.evm }
  235. func (self *VMEnv) Db() vm.Database { return self.state }
  236. func (self *VMEnv) SnapshotDatabase() int { return self.state.Snapshot() }
  237. func (self *VMEnv) RevertToSnapshot(snap int) { self.state.RevertToSnapshot(snap) }
  238. func (self *VMEnv) Origin() common.Address { return *self.transactor }
  239. func (self *VMEnv) BlockNumber() *big.Int { return common.Big0 }
  240. func (self *VMEnv) Coinbase() common.Address { return *self.transactor }
  241. func (self *VMEnv) Time() *big.Int { return self.time }
  242. func (self *VMEnv) Difficulty() *big.Int { return common.Big1 }
  243. func (self *VMEnv) BlockHash() []byte { return make([]byte, 32) }
  244. func (self *VMEnv) Value() *big.Int { return self.value }
  245. func (self *VMEnv) GasLimit() *big.Int { return big.NewInt(1000000000) }
  246. func (self *VMEnv) VmType() vm.Type { return vm.StdVmTy }
  247. func (self *VMEnv) Depth() int { return 0 }
  248. func (self *VMEnv) SetDepth(i int) { self.depth = i }
  249. func (self *VMEnv) GetHash(n uint64) common.Hash {
  250. if self.block.Number().Cmp(big.NewInt(int64(n))) == 0 {
  251. return self.block.Hash()
  252. }
  253. return common.Hash{}
  254. }
  255. func (self *VMEnv) AddLog(log *vm.Log) {
  256. self.state.AddLog(log)
  257. }
  258. func (self *VMEnv) CanTransfer(from common.Address, balance *big.Int) bool {
  259. return self.state.GetBalance(from).Cmp(balance) >= 0
  260. }
  261. func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) {
  262. core.Transfer(from, to, amount)
  263. }
  264. func (self *VMEnv) Call(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
  265. self.Gas = gas
  266. return core.Call(self, caller, addr, data, gas, price, value)
  267. }
  268. func (self *VMEnv) CallCode(caller vm.ContractRef, addr common.Address, data []byte, gas, price, value *big.Int) ([]byte, error) {
  269. return core.CallCode(self, caller, addr, data, gas, price, value)
  270. }
  271. func (self *VMEnv) DelegateCall(caller vm.ContractRef, addr common.Address, data []byte, gas, price *big.Int) ([]byte, error) {
  272. return core.DelegateCall(self, caller, addr, data, gas, price)
  273. }
  274. func (self *VMEnv) Create(caller vm.ContractRef, data []byte, gas, price, value *big.Int) ([]byte, common.Address, error) {
  275. return core.Create(self, caller, data, gas, price, value)
  276. }