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