js.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. "os"
  22. "path"
  23. "strings"
  24. "github.com/ethereum/go-ethereum/cmd/utils"
  25. "github.com/ethereum/go-ethereum/common/docserver"
  26. "github.com/ethereum/go-ethereum/common/natspec"
  27. "github.com/ethereum/go-ethereum/eth"
  28. re "github.com/ethereum/go-ethereum/jsre"
  29. "github.com/ethereum/go-ethereum/rpc"
  30. "github.com/ethereum/go-ethereum/xeth"
  31. "github.com/peterh/liner"
  32. "github.com/robertkrimen/otto"
  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 *re.JSRE
  54. ethereum *eth.Ethereum
  55. xeth *xeth.XEth
  56. ps1 string
  57. atexit func()
  58. corsDomain string
  59. prompter
  60. }
  61. func newJSRE(ethereum *eth.Ethereum, libPath string, interactive bool, corsDomain string) *jsre {
  62. js := &jsre{ethereum: ethereum, ps1: "> "}
  63. // set default cors domain used by startRpc from CLI flag
  64. js.corsDomain = corsDomain
  65. js.xeth = xeth.New(ethereum, js)
  66. js.re = re.New(libPath)
  67. js.apiBindings()
  68. js.adminBindings()
  69. if !liner.TerminalSupported() || !interactive {
  70. js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
  71. } else {
  72. lr := liner.NewLiner()
  73. js.withHistory(func(hist *os.File) { lr.ReadHistory(hist) })
  74. lr.SetCtrlCAborts(true)
  75. js.prompter = lr
  76. js.atexit = func() {
  77. js.withHistory(func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
  78. lr.Close()
  79. }
  80. }
  81. return js
  82. }
  83. func (js *jsre) apiBindings() {
  84. ethApi := rpc.NewEthereumApi(js.xeth)
  85. //js.re.Bind("jeth", rpc.NewJeth(ethApi, js.re.ToVal))
  86. jeth := rpc.NewJeth(ethApi, js.re.ToVal, js.re)
  87. //js.re.Bind("jeth", jeth)
  88. js.re.Set("jeth", struct{}{})
  89. t, _ := js.re.Get("jeth")
  90. jethObj := t.Object()
  91. jethObj.Set("send", jeth.Send)
  92. jethObj.Set("sendAsync", jeth.Send)
  93. err := js.re.Compile("bignumber.js", re.BigNumber_JS)
  94. if err != nil {
  95. utils.Fatalf("Error loading bignumber.js: %v", err)
  96. }
  97. // we need to declare a dummy setTimeout. Otto does not support it
  98. _, err = js.re.Eval("setTimeout = function(cb, delay) {};")
  99. if err != nil {
  100. utils.Fatalf("Error defining setTimeout: %v", err)
  101. }
  102. err = js.re.Compile("ethereum.js", re.Ethereum_JS)
  103. if err != nil {
  104. utils.Fatalf("Error loading ethereum.js: %v", err)
  105. }
  106. _, err = js.re.Eval("var web3 = require('web3');")
  107. if err != nil {
  108. utils.Fatalf("Error requiring web3: %v", err)
  109. }
  110. _, err = js.re.Eval("web3.setProvider(jeth)")
  111. if err != nil {
  112. utils.Fatalf("Error setting web3 provider: %v", err)
  113. }
  114. _, err = js.re.Eval(`
  115. var eth = web3.eth;
  116. var shh = web3.shh;
  117. var db = web3.db;
  118. var net = web3.net;
  119. `)
  120. if err != nil {
  121. utils.Fatalf("Error setting namespaces: %v", err)
  122. }
  123. js.re.Eval(globalRegistrar + "registrar = new GlobalRegistrar(\"" + globalRegistrarAddr + "\");")
  124. }
  125. var ds, _ = docserver.New(utils.JSpathFlag.String())
  126. func (self *jsre) ConfirmTransaction(tx string) bool {
  127. if self.ethereum.NatSpec {
  128. notice := natspec.GetNotice(self.xeth, tx, ds)
  129. fmt.Println(notice)
  130. answer, _ := self.Prompt("Confirm Transaction\n[y/n] ")
  131. return strings.HasPrefix(strings.Trim(answer, " "), "y")
  132. } else {
  133. return true
  134. }
  135. }
  136. func (self *jsre) UnlockAccount(addr []byte) bool {
  137. fmt.Printf("Please unlock account %x.\n", addr)
  138. pass, err := self.PasswordPrompt("Passphrase: ")
  139. if err != nil {
  140. return false
  141. }
  142. // TODO: allow retry
  143. if err := self.ethereum.AccountManager().Unlock(addr, pass); err != nil {
  144. return false
  145. } else {
  146. fmt.Println("Account is now unlocked for this session.")
  147. return true
  148. }
  149. }
  150. func (self *jsre) exec(filename string) error {
  151. if err := self.re.Exec(filename); err != nil {
  152. self.re.Stop(false)
  153. return fmt.Errorf("Javascript Error: %v", err)
  154. }
  155. self.re.Stop(true)
  156. return nil
  157. }
  158. func (self *jsre) interactive() {
  159. for {
  160. input, err := self.Prompt(self.ps1)
  161. if err != nil {
  162. break
  163. }
  164. if input == "" {
  165. continue
  166. }
  167. str += input + "\n"
  168. self.setIndent()
  169. if indentCount <= 0 {
  170. if input == "exit" {
  171. break
  172. }
  173. hist := str[:len(str)-1]
  174. self.AppendHistory(hist)
  175. self.parseInput(str)
  176. str = ""
  177. }
  178. }
  179. if self.atexit != nil {
  180. self.atexit()
  181. }
  182. self.re.Stop(false)
  183. }
  184. func (self *jsre) withHistory(op func(*os.File)) {
  185. hist, err := os.OpenFile(path.Join(self.ethereum.DataDir, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
  186. if err != nil {
  187. fmt.Printf("unable to open history file: %v\n", err)
  188. return
  189. }
  190. op(hist)
  191. hist.Close()
  192. }
  193. func (self *jsre) parseInput(code string) {
  194. defer func() {
  195. if r := recover(); r != nil {
  196. fmt.Println("[native] error", r)
  197. }
  198. }()
  199. value, err := self.re.Run(code)
  200. if err != nil {
  201. if ottoErr, ok := err.(*otto.Error); ok {
  202. fmt.Println(ottoErr.String())
  203. } else {
  204. fmt.Println(err)
  205. }
  206. return
  207. }
  208. self.printValue(value)
  209. }
  210. var indentCount = 0
  211. var str = ""
  212. func (self *jsre) setIndent() {
  213. open := strings.Count(str, "{")
  214. open += strings.Count(str, "(")
  215. closed := strings.Count(str, "}")
  216. closed += strings.Count(str, ")")
  217. indentCount = open - closed
  218. if indentCount <= 0 {
  219. self.ps1 = "> "
  220. } else {
  221. self.ps1 = strings.Join(make([]string, indentCount*2), "..")
  222. self.ps1 += " "
  223. }
  224. }
  225. func (self *jsre) printValue(v interface{}) {
  226. val, err := self.re.PrettyPrint(v)
  227. if err == nil {
  228. fmt.Printf("%v", val)
  229. }
  230. }