main.go 7.7 KB

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