js.go 6.3 KB

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