js.go 6.8 KB

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