js.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. "path"
  24. "strings"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/eth"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/javascript"
  29. "github.com/ethereum/go-ethereum/state"
  30. "github.com/ethereum/go-ethereum/xeth"
  31. "github.com/obscuren/otto"
  32. "github.com/peterh/liner"
  33. )
  34. type prompter interface {
  35. AppendHistory(string)
  36. Prompt(p string) (string, error)
  37. PasswordPrompt(p string) (string, error)
  38. }
  39. type dumbterm struct{ r *bufio.Reader }
  40. func (r dumbterm) Prompt(p string) (string, error) {
  41. fmt.Print(p)
  42. return r.r.ReadString('\n')
  43. }
  44. func (r dumbterm) PasswordPrompt(p string) (string, error) {
  45. fmt.Println("!! Unsupported terminal, password will echo.")
  46. fmt.Print(p)
  47. input, err := bufio.NewReader(os.Stdin).ReadString('\n')
  48. fmt.Println()
  49. return input, err
  50. }
  51. func (r dumbterm) AppendHistory(string) {}
  52. type jsre struct {
  53. re *javascript.JSRE
  54. ethereum *eth.Ethereum
  55. xeth *xeth.XEth
  56. ps1 string
  57. atexit func()
  58. prompter
  59. }
  60. func newJSRE(ethereum *eth.Ethereum) *jsre {
  61. js := &jsre{ethereum: ethereum, ps1: "> "}
  62. js.xeth = xeth.New(ethereum, js)
  63. js.re = javascript.NewJSRE(js.xeth)
  64. js.initStdFuncs()
  65. if !liner.TerminalSupported() {
  66. js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
  67. } else {
  68. lr := liner.NewLiner()
  69. js.withHistory(func(hist *os.File) { lr.ReadHistory(hist) })
  70. lr.SetCtrlCAborts(true)
  71. js.prompter = lr
  72. js.atexit = func() {
  73. js.withHistory(func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
  74. lr.Close()
  75. }
  76. }
  77. return js
  78. }
  79. func (self *jsre) ConfirmTransaction(tx *types.Transaction) bool {
  80. p := fmt.Sprintf("Confirm Transaction %v\n[y/n] ", tx)
  81. answer, _ := self.Prompt(p)
  82. return strings.HasPrefix(strings.Trim(answer, " "), "y")
  83. }
  84. func (self *jsre) UnlockAccount(addr []byte) bool {
  85. fmt.Printf("Please unlock account %x.\n", addr)
  86. pass, err := self.PasswordPrompt("Passphrase: ")
  87. if err != nil {
  88. return false
  89. }
  90. // TODO: allow retry
  91. if err := self.ethereum.AccountManager().Unlock(addr, pass); err != nil {
  92. return false
  93. } else {
  94. fmt.Println("Account is now unlocked for this session.")
  95. return true
  96. }
  97. }
  98. func (self *jsre) exec(filename string) error {
  99. file, err := os.Open(filename)
  100. if err != nil {
  101. return err
  102. }
  103. content, err := ioutil.ReadAll(file)
  104. if err != nil {
  105. return err
  106. }
  107. if _, err := self.re.Run(string(content)); err != nil {
  108. return fmt.Errorf("Javascript Error: %v", err)
  109. }
  110. return nil
  111. }
  112. func (self *jsre) interactive() {
  113. for {
  114. input, err := self.Prompt(self.ps1)
  115. if err != nil {
  116. break
  117. }
  118. if input == "" {
  119. continue
  120. }
  121. str += input + "\n"
  122. self.setIndent()
  123. if indentCount <= 0 {
  124. if input == "exit" {
  125. break
  126. }
  127. hist := str[:len(str)-1]
  128. self.AppendHistory(hist)
  129. self.parseInput(str)
  130. str = ""
  131. }
  132. }
  133. if self.atexit != nil {
  134. self.atexit()
  135. }
  136. }
  137. func (self *jsre) withHistory(op func(*os.File)) {
  138. hist, err := os.OpenFile(path.Join(self.ethereum.DataDir, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
  139. if err != nil {
  140. fmt.Printf("unable to open history file: %v\n", err)
  141. return
  142. }
  143. op(hist)
  144. hist.Close()
  145. }
  146. func (self *jsre) parseInput(code string) {
  147. defer func() {
  148. if r := recover(); r != nil {
  149. fmt.Println("[native] error", r)
  150. }
  151. }()
  152. value, err := self.re.Run(code)
  153. if err != nil {
  154. fmt.Println(err)
  155. return
  156. }
  157. self.printValue(value)
  158. }
  159. var indentCount = 0
  160. var str = ""
  161. func (self *jsre) setIndent() {
  162. open := strings.Count(str, "{")
  163. open += strings.Count(str, "(")
  164. closed := strings.Count(str, "}")
  165. closed += strings.Count(str, ")")
  166. indentCount = open - closed
  167. if indentCount <= 0 {
  168. self.ps1 = "> "
  169. } else {
  170. self.ps1 = strings.Join(make([]string, indentCount*2), "..")
  171. self.ps1 += " "
  172. }
  173. }
  174. func (self *jsre) printValue(v interface{}) {
  175. method, _ := self.re.Vm.Get("prettyPrint")
  176. v, err := self.re.Vm.ToValue(v)
  177. if err == nil {
  178. val, err := method.Call(method, v)
  179. if err == nil {
  180. fmt.Printf("%v", val)
  181. }
  182. }
  183. }
  184. func (self *jsre) initStdFuncs() {
  185. t, _ := self.re.Vm.Get("eth")
  186. eth := t.Object()
  187. eth.Set("connect", self.connect)
  188. eth.Set("stopMining", self.stopMining)
  189. eth.Set("startMining", self.startMining)
  190. eth.Set("dump", self.dump)
  191. eth.Set("export", self.export)
  192. }
  193. /*
  194. * The following methods are natively implemented javascript functions.
  195. */
  196. func (self *jsre) dump(call otto.FunctionCall) otto.Value {
  197. var block *types.Block
  198. if len(call.ArgumentList) > 0 {
  199. if call.Argument(0).IsNumber() {
  200. num, _ := call.Argument(0).ToInteger()
  201. block = self.ethereum.ChainManager().GetBlockByNumber(uint64(num))
  202. } else if call.Argument(0).IsString() {
  203. hash, _ := call.Argument(0).ToString()
  204. block = self.ethereum.ChainManager().GetBlock(common.Hex2Bytes(hash))
  205. } else {
  206. fmt.Println("invalid argument for dump. Either hex string or number")
  207. }
  208. if block == nil {
  209. fmt.Println("block not found")
  210. return otto.UndefinedValue()
  211. }
  212. } else {
  213. block = self.ethereum.ChainManager().CurrentBlock()
  214. }
  215. statedb := state.New(block.Root(), self.ethereum.StateDb())
  216. v, _ := self.re.Vm.ToValue(statedb.RawDump())
  217. return v
  218. }
  219. func (self *jsre) stopMining(call otto.FunctionCall) otto.Value {
  220. self.ethereum.StopMining()
  221. return otto.TrueValue()
  222. }
  223. func (self *jsre) startMining(call otto.FunctionCall) otto.Value {
  224. if err := self.ethereum.StartMining(); err != nil {
  225. return otto.FalseValue()
  226. }
  227. return otto.TrueValue()
  228. }
  229. func (self *jsre) connect(call otto.FunctionCall) otto.Value {
  230. nodeURL, err := call.Argument(0).ToString()
  231. if err != nil {
  232. return otto.FalseValue()
  233. }
  234. if err := self.ethereum.SuggestPeer(nodeURL); err != nil {
  235. return otto.FalseValue()
  236. }
  237. return otto.TrueValue()
  238. }
  239. func (self *jsre) export(call otto.FunctionCall) otto.Value {
  240. if len(call.ArgumentList) == 0 {
  241. fmt.Println("err: require file name")
  242. return otto.FalseValue()
  243. }
  244. fn, err := call.Argument(0).ToString()
  245. if err != nil {
  246. fmt.Println(err)
  247. return otto.FalseValue()
  248. }
  249. data := self.ethereum.ChainManager().Export()
  250. if err := common.WriteFile(fn, data); err != nil {
  251. fmt.Println(err)
  252. return otto.FalseValue()
  253. }
  254. return otto.TrueValue()
  255. }