js.go 6.3 KB

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