js.go 6.0 KB

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