js.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. // Copyright (c) 2013-2014, Jeffrey Wilcke. All rights reserved.
  2. //
  3. // This library is free software; you can redistribute it and/or
  4. // modify it under the terms of the GNU General Public
  5. // License as published by the Free Software Foundation; either
  6. // version 2.1 of the License, or (at your option) any later version.
  7. //
  8. // This library is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. // General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this library; if not, write to the Free Software
  15. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  16. // MA 02110-1301 USA
  17. package main
  18. import (
  19. "bufio"
  20. "fmt"
  21. "io/ioutil"
  22. "os"
  23. "os/signal"
  24. "path"
  25. "strings"
  26. "github.com/ethereum/go-ethereum/cmd/utils"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/eth"
  29. "github.com/ethereum/go-ethereum/ethutil"
  30. "github.com/ethereum/go-ethereum/javascript"
  31. "github.com/ethereum/go-ethereum/state"
  32. "github.com/ethereum/go-ethereum/xeth"
  33. "github.com/obscuren/otto"
  34. "github.com/peterh/liner"
  35. )
  36. func execJsFile(ethereum *eth.Ethereum, filename string) {
  37. file, err := os.Open(filename)
  38. if err != nil {
  39. utils.Fatalf("%v", err)
  40. }
  41. content, err := ioutil.ReadAll(file)
  42. if err != nil {
  43. utils.Fatalf("%v", err)
  44. }
  45. re := javascript.NewJSRE(xeth.New(ethereum, nil))
  46. if _, err := re.Run(string(content)); err != nil {
  47. utils.Fatalf("Javascript Error: %v", err)
  48. }
  49. }
  50. type repl struct {
  51. re *javascript.JSRE
  52. ethereum *eth.Ethereum
  53. xeth *xeth.XEth
  54. prompt string
  55. lr *liner.State
  56. }
  57. func runREPL(ethereum *eth.Ethereum) {
  58. xeth := xeth.New(ethereum, nil)
  59. repl := &repl{
  60. re: javascript.NewJSRE(xeth),
  61. xeth: xeth,
  62. ethereum: ethereum,
  63. prompt: "> ",
  64. }
  65. repl.initStdFuncs()
  66. if !liner.TerminalSupported() {
  67. repl.dumbRead()
  68. } else {
  69. lr := liner.NewLiner()
  70. defer lr.Close()
  71. lr.SetCtrlCAborts(true)
  72. repl.withHistory(func(hist *os.File) { lr.ReadHistory(hist) })
  73. repl.read(lr)
  74. repl.withHistory(func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
  75. }
  76. }
  77. func (self *repl) withHistory(op func(*os.File)) {
  78. hist, err := os.OpenFile(path.Join(self.ethereum.DataDir, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
  79. if err != nil {
  80. fmt.Printf("unable to open history file: %v\n", err)
  81. return
  82. }
  83. op(hist)
  84. hist.Close()
  85. }
  86. func (self *repl) parseInput(code string) {
  87. defer func() {
  88. if r := recover(); r != nil {
  89. fmt.Println("[native] error", r)
  90. }
  91. }()
  92. value, err := self.re.Run(code)
  93. if err != nil {
  94. fmt.Println(err)
  95. return
  96. }
  97. self.printValue(value)
  98. }
  99. var indentCount = 0
  100. var str = ""
  101. func (self *repl) setIndent() {
  102. open := strings.Count(str, "{")
  103. open += strings.Count(str, "(")
  104. closed := strings.Count(str, "}")
  105. closed += strings.Count(str, ")")
  106. indentCount = open - closed
  107. if indentCount <= 0 {
  108. self.prompt = "> "
  109. } else {
  110. self.prompt = strings.Join(make([]string, indentCount*2), "..")
  111. self.prompt += " "
  112. }
  113. }
  114. func (self *repl) read(lr *liner.State) {
  115. for {
  116. input, err := lr.Prompt(self.prompt)
  117. if err != nil {
  118. return
  119. }
  120. if input == "" {
  121. continue
  122. }
  123. str += input + "\n"
  124. self.setIndent()
  125. if indentCount <= 0 {
  126. if input == "exit" {
  127. return
  128. }
  129. hist := str[:len(str)-1]
  130. lr.AppendHistory(hist)
  131. self.parseInput(str)
  132. str = ""
  133. }
  134. }
  135. }
  136. func (self *repl) dumbRead() {
  137. fmt.Println("Unsupported terminal, line editing will not work.")
  138. // process lines
  139. readDone := make(chan struct{})
  140. go func() {
  141. r := bufio.NewReader(os.Stdin)
  142. loop:
  143. for {
  144. fmt.Print(self.prompt)
  145. line, err := r.ReadString('\n')
  146. switch {
  147. case err != nil || line == "exit":
  148. break loop
  149. case line == "":
  150. continue
  151. default:
  152. self.parseInput(line + "\n")
  153. }
  154. }
  155. close(readDone)
  156. }()
  157. // wait for Ctrl-C
  158. sigc := make(chan os.Signal, 1)
  159. signal.Notify(sigc, os.Interrupt, os.Kill)
  160. defer signal.Stop(sigc)
  161. select {
  162. case <-readDone:
  163. case <-sigc:
  164. os.Stdin.Close() // terminate read
  165. }
  166. }
  167. func (self *repl) printValue(v interface{}) {
  168. method, _ := self.re.Vm.Get("prettyPrint")
  169. v, err := self.re.Vm.ToValue(v)
  170. if err == nil {
  171. val, err := method.Call(method, v)
  172. if err == nil {
  173. fmt.Printf("%v", val)
  174. }
  175. }
  176. }
  177. func (self *repl) initStdFuncs() {
  178. t, _ := self.re.Vm.Get("eth")
  179. eth := t.Object()
  180. eth.Set("connect", self.connect)
  181. eth.Set("stopMining", self.stopMining)
  182. eth.Set("startMining", self.startMining)
  183. eth.Set("dump", self.dump)
  184. eth.Set("export", self.export)
  185. }
  186. /*
  187. * The following methods are natively implemented javascript functions.
  188. */
  189. func (self *repl) dump(call otto.FunctionCall) otto.Value {
  190. var block *types.Block
  191. if len(call.ArgumentList) > 0 {
  192. if call.Argument(0).IsNumber() {
  193. num, _ := call.Argument(0).ToInteger()
  194. block = self.ethereum.ChainManager().GetBlockByNumber(uint64(num))
  195. } else if call.Argument(0).IsString() {
  196. hash, _ := call.Argument(0).ToString()
  197. block = self.ethereum.ChainManager().GetBlock(ethutil.Hex2Bytes(hash))
  198. } else {
  199. fmt.Println("invalid argument for dump. Either hex string or number")
  200. }
  201. if block == nil {
  202. fmt.Println("block not found")
  203. return otto.UndefinedValue()
  204. }
  205. } else {
  206. block = self.ethereum.ChainManager().CurrentBlock()
  207. }
  208. statedb := state.New(block.Root(), self.ethereum.StateDb())
  209. v, _ := self.re.Vm.ToValue(statedb.RawDump())
  210. return v
  211. }
  212. func (self *repl) stopMining(call otto.FunctionCall) otto.Value {
  213. self.xeth.Miner().Stop()
  214. return otto.TrueValue()
  215. }
  216. func (self *repl) startMining(call otto.FunctionCall) otto.Value {
  217. self.xeth.Miner().Start()
  218. return otto.TrueValue()
  219. }
  220. func (self *repl) connect(call otto.FunctionCall) otto.Value {
  221. nodeURL, err := call.Argument(0).ToString()
  222. if err != nil {
  223. return otto.FalseValue()
  224. }
  225. if err := self.ethereum.SuggestPeer(nodeURL); err != nil {
  226. return otto.FalseValue()
  227. }
  228. return otto.TrueValue()
  229. }
  230. func (self *repl) export(call otto.FunctionCall) otto.Value {
  231. if len(call.ArgumentList) == 0 {
  232. fmt.Println("err: require file name")
  233. return otto.FalseValue()
  234. }
  235. fn, err := call.Argument(0).ToString()
  236. if err != nil {
  237. fmt.Println(err)
  238. return otto.FalseValue()
  239. }
  240. data := self.ethereum.ChainManager().Export()
  241. if err := ethutil.WriteFile(fn, data); err != nil {
  242. fmt.Println(err)
  243. return otto.FalseValue()
  244. }
  245. return otto.TrueValue()
  246. }