js.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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/rpc/api"
  34. "github.com/ethereum/go-ethereum/rpc/codec"
  35. "github.com/ethereum/go-ethereum/rpc/comms"
  36. "github.com/ethereum/go-ethereum/rpc/shared"
  37. "github.com/ethereum/go-ethereum/xeth"
  38. "github.com/peterh/liner"
  39. "github.com/robertkrimen/otto"
  40. )
  41. type prompter interface {
  42. AppendHistory(string)
  43. Prompt(p string) (string, error)
  44. PasswordPrompt(p string) (string, error)
  45. }
  46. type dumbterm struct{ r *bufio.Reader }
  47. func (r dumbterm) Prompt(p string) (string, error) {
  48. fmt.Print(p)
  49. line, err := r.r.ReadString('\n')
  50. return strings.TrimSuffix(line, "\n"), err
  51. }
  52. func (r dumbterm) PasswordPrompt(p string) (string, error) {
  53. fmt.Println("!! Unsupported terminal, password will echo.")
  54. fmt.Print(p)
  55. input, err := bufio.NewReader(os.Stdin).ReadString('\n')
  56. fmt.Println()
  57. return input, err
  58. }
  59. func (r dumbterm) AppendHistory(string) {}
  60. type jsre struct {
  61. re *re.JSRE
  62. ethereum *eth.Ethereum
  63. xeth *xeth.XEth
  64. wait chan *big.Int
  65. ps1 string
  66. atexit func()
  67. corsDomain string
  68. client comms.EthereumClient
  69. prompter
  70. }
  71. var (
  72. loadedModulesMethods map[string][]string
  73. )
  74. func keywordCompleter(line string) []string {
  75. results := make([]string, 0)
  76. if strings.Contains(line, ".") {
  77. elements := strings.Split(line, ".")
  78. if len(elements) == 2 {
  79. module := elements[0]
  80. partialMethod := elements[1]
  81. if methods, found := loadedModulesMethods[module]; found {
  82. for _, method := range methods {
  83. if strings.HasPrefix(method, partialMethod) { // e.g. debug.se
  84. results = append(results, module+"."+method)
  85. }
  86. }
  87. }
  88. }
  89. } else {
  90. for module, methods := range loadedModulesMethods {
  91. if line == module { // user typed in full module name, show all methods
  92. for _, method := range methods {
  93. results = append(results, module+"."+method)
  94. }
  95. } else if strings.HasPrefix(module, line) { // partial method name, e.g. admi
  96. results = append(results, module)
  97. }
  98. }
  99. }
  100. return results
  101. }
  102. func apiWordCompleter(line string, pos int) (head string, completions []string, tail string) {
  103. if len(line) == 0 {
  104. return "", nil, ""
  105. }
  106. i := 0
  107. for i = pos - 1; i > 0; i-- {
  108. if line[i] == '.' || (line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') {
  109. continue
  110. }
  111. if i >= 3 && line[i] == '3' && line[i-3] == 'w' && line[i-2] == 'e' && line[i-1] == 'b' {
  112. continue
  113. }
  114. i += 1
  115. break
  116. }
  117. begin := line[:i]
  118. keyword := line[i:pos]
  119. end := line[pos:]
  120. completionWords := keywordCompleter(keyword)
  121. return begin, completionWords, end
  122. }
  123. func newJSRE(ethereum *eth.Ethereum, libPath, corsDomain string, client comms.EthereumClient, interactive bool, f xeth.Frontend) *jsre {
  124. js := &jsre{ethereum: ethereum, ps1: "> "}
  125. // set default cors domain used by startRpc from CLI flag
  126. js.corsDomain = corsDomain
  127. if f == nil {
  128. f = js
  129. }
  130. js.xeth = xeth.New(ethereum, f)
  131. js.wait = js.xeth.UpdateState()
  132. js.client = client
  133. if clt, ok := js.client.(*comms.InProcClient); ok {
  134. clt.Initialize(js.xeth, ethereum)
  135. }
  136. // update state in separare forever blocks
  137. js.re = re.New(libPath)
  138. if err := js.apiBindings(f); err != nil {
  139. utils.Fatalf("Unable to connect - %v", err)
  140. }
  141. if !liner.TerminalSupported() || !interactive {
  142. js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
  143. } else {
  144. lr := liner.NewLiner()
  145. js.withHistory(func(hist *os.File) { lr.ReadHistory(hist) })
  146. lr.SetCtrlCAborts(true)
  147. js.loadAutoCompletion()
  148. lr.SetWordCompleter(apiWordCompleter)
  149. lr.SetTabCompletionStyle(liner.TabPrints)
  150. js.prompter = lr
  151. js.atexit = func() {
  152. js.withHistory(func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
  153. lr.Close()
  154. close(js.wait)
  155. }
  156. }
  157. return js
  158. }
  159. func (self *jsre) loadAutoCompletion() {
  160. if modules, err := self.suportedApis(); err == nil {
  161. loadedModulesMethods = make(map[string][]string)
  162. for module, _ := range modules {
  163. loadedModulesMethods[module] = api.AutoCompletion[module]
  164. }
  165. }
  166. }
  167. func (self *jsre) suportedApis() (map[string]string, error) {
  168. req := shared.Request{
  169. Id: 1,
  170. Jsonrpc: "2.0",
  171. Method: "modules",
  172. }
  173. err := self.client.Send(&req)
  174. if err != nil {
  175. return nil, err
  176. }
  177. res, err := self.client.Recv()
  178. if err != nil {
  179. return nil, err
  180. }
  181. if sucRes, ok := res.(map[string]string); ok {
  182. if err == nil {
  183. return sucRes, nil
  184. }
  185. }
  186. return nil, fmt.Errorf("Unable to determine supported API's")
  187. }
  188. func (js *jsre) apiBindings(f xeth.Frontend) error {
  189. apis, err := js.suportedApis()
  190. if err != nil {
  191. return err
  192. }
  193. apiNames := make([]string, 0, len(apis))
  194. for a, _ := range apis {
  195. apiNames = append(apiNames, a)
  196. }
  197. apiImpl, err := api.ParseApiString(strings.Join(apiNames, ","), codec.JSON, js.xeth, js.ethereum)
  198. if err != nil {
  199. utils.Fatalf("Unable to determine supported api's: %v", err)
  200. }
  201. jeth := rpc.NewJeth(api.Merge(apiImpl...), js.re, js.client)
  202. js.re.Set("jeth", struct{}{})
  203. t, _ := js.re.Get("jeth")
  204. jethObj := t.Object()
  205. jethObj.Set("send", jeth.Send)
  206. jethObj.Set("sendAsync", jeth.Send)
  207. err = js.re.Compile("bignumber.js", re.BigNumber_JS)
  208. if err != nil {
  209. utils.Fatalf("Error loading bignumber.js: %v", err)
  210. }
  211. err = js.re.Compile("ethereum.js", re.Web3_JS)
  212. if err != nil {
  213. utils.Fatalf("Error loading web3.js: %v", err)
  214. }
  215. _, err = js.re.Eval("var web3 = require('web3');")
  216. if err != nil {
  217. utils.Fatalf("Error requiring web3: %v", err)
  218. }
  219. _, err = js.re.Eval("web3.setProvider(jeth)")
  220. if err != nil {
  221. utils.Fatalf("Error setting web3 provider: %v", err)
  222. }
  223. // load only supported API's in javascript runtime
  224. shortcuts := "var eth = web3.eth; "
  225. for _, apiName := range apiNames {
  226. if apiName == api.Web3ApiName || apiName == api.EthApiName {
  227. continue // manually mapped
  228. }
  229. if err = js.re.Compile(fmt.Sprintf("%s.js", apiName), api.Javascript(apiName)); err == nil {
  230. shortcuts += fmt.Sprintf("var %s = web3.%s; ", apiName, apiName)
  231. } else {
  232. utils.Fatalf("Error loading %s.js: %v", apiName, err)
  233. }
  234. }
  235. _, err = js.re.Eval(shortcuts)
  236. if err != nil {
  237. utils.Fatalf("Error setting namespaces: %v", err)
  238. }
  239. js.re.Eval(globalRegistrar + "registrar = GlobalRegistrar.at(\"" + globalRegistrarAddr + "\");")
  240. return nil
  241. }
  242. /*
  243. func (js *jsre) apiBindings(ipcpath string, f xeth.Frontend) {
  244. xe := xeth.New(js.ethereum, f)
  245. apiNames, err := js.suportedApis(ipcpath)
  246. if err != nil {
  247. return
  248. }
  249. ethApi := rpc.NewEthereumApi(xe)
  250. jeth := rpc.NewJeth(ethApi, js.re, ipcpath)
  251. js.re.Set("jeth", struct{}{})
  252. t, _ := js.re.Get("jeth")
  253. jethObj := t.Object()
  254. jethObj.Set("send", jeth.Send)
  255. jethObj.Set("sendAsync", jeth.Send)
  256. err := js.re.Compile("bignumber.js", re.BigNumber_JS)
  257. if err != nil {
  258. utils.Fatalf("Error loading bignumber.js: %v", err)
  259. }
  260. err = js.re.Compile("ethereum.js", re.Web3_JS)
  261. if err != nil {
  262. utils.Fatalf("Error loading ethereum.js: %v", err)
  263. }
  264. _, err = js.re.Eval("var web3 = require('web3');")
  265. if err != nil {
  266. utils.Fatalf("Error requiring web3: %v", err)
  267. }
  268. _, err = js.re.Eval("web3.setProvider(jeth)")
  269. if err != nil {
  270. utils.Fatalf("Error setting web3 provider: %v", err)
  271. }
  272. _, err = js.re.Eval(`
  273. var eth = web3.eth;
  274. var shh = web3.shh;
  275. var db = web3.db;
  276. var net = web3.net;
  277. `)
  278. if err != nil {
  279. utils.Fatalf("Error setting namespaces: %v", err)
  280. }
  281. js.re.Eval(globalRegistrar + "registrar = GlobalRegistrar.at(\"" + globalRegistrarAddr + "\");")
  282. }
  283. */
  284. var ds, _ = docserver.New("/")
  285. func (self *jsre) ConfirmTransaction(tx string) bool {
  286. if self.ethereum.NatSpec {
  287. notice := natspec.GetNotice(self.xeth, tx, ds)
  288. fmt.Println(notice)
  289. answer, _ := self.Prompt("Confirm Transaction [y/n]")
  290. return strings.HasPrefix(strings.Trim(answer, " "), "y")
  291. } else {
  292. return true
  293. }
  294. }
  295. func (self *jsre) UnlockAccount(addr []byte) bool {
  296. fmt.Printf("Please unlock account %x.\n", addr)
  297. pass, err := self.PasswordPrompt("Passphrase: ")
  298. if err != nil {
  299. return false
  300. }
  301. // TODO: allow retry
  302. if err := self.ethereum.AccountManager().Unlock(common.BytesToAddress(addr), pass); err != nil {
  303. return false
  304. } else {
  305. fmt.Println("Account is now unlocked for this session.")
  306. return true
  307. }
  308. }
  309. func (self *jsre) exec(filename string) error {
  310. if err := self.re.Exec(filename); err != nil {
  311. self.re.Stop(false)
  312. return fmt.Errorf("Javascript Error: %v", err)
  313. }
  314. self.re.Stop(true)
  315. return nil
  316. }
  317. func (self *jsre) interactive() {
  318. // Read input lines.
  319. prompt := make(chan string)
  320. inputln := make(chan string)
  321. go func() {
  322. defer close(inputln)
  323. for {
  324. line, err := self.Prompt(<-prompt)
  325. if err != nil {
  326. return
  327. }
  328. inputln <- line
  329. }
  330. }()
  331. // Wait for Ctrl-C, too.
  332. sig := make(chan os.Signal, 1)
  333. signal.Notify(sig, os.Interrupt)
  334. defer func() {
  335. if self.atexit != nil {
  336. self.atexit()
  337. }
  338. self.re.Stop(false)
  339. }()
  340. for {
  341. prompt <- self.ps1
  342. select {
  343. case <-sig:
  344. fmt.Println("caught interrupt, exiting")
  345. return
  346. case input, ok := <-inputln:
  347. if !ok || indentCount <= 0 && input == "exit" {
  348. return
  349. }
  350. if input == "" {
  351. continue
  352. }
  353. str += input + "\n"
  354. self.setIndent()
  355. if indentCount <= 0 {
  356. hist := str[:len(str)-1]
  357. self.AppendHistory(hist)
  358. self.parseInput(str)
  359. str = ""
  360. }
  361. }
  362. }
  363. }
  364. func (self *jsre) withHistory(op func(*os.File)) {
  365. hist, err := os.OpenFile(filepath.Join(self.ethereum.DataDir, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
  366. if err != nil {
  367. fmt.Printf("unable to open history file: %v\n", err)
  368. return
  369. }
  370. op(hist)
  371. hist.Close()
  372. }
  373. func (self *jsre) parseInput(code string) {
  374. defer func() {
  375. if r := recover(); r != nil {
  376. fmt.Println("[native] error", r)
  377. }
  378. }()
  379. value, err := self.re.Run(code)
  380. if err != nil {
  381. if ottoErr, ok := err.(*otto.Error); ok {
  382. fmt.Println(ottoErr.String())
  383. } else {
  384. fmt.Println(err)
  385. }
  386. return
  387. }
  388. self.printValue(value)
  389. }
  390. var indentCount = 0
  391. var str = ""
  392. func (self *jsre) setIndent() {
  393. open := strings.Count(str, "{")
  394. open += strings.Count(str, "(")
  395. closed := strings.Count(str, "}")
  396. closed += strings.Count(str, ")")
  397. indentCount = open - closed
  398. if indentCount <= 0 {
  399. self.ps1 = "> "
  400. } else {
  401. self.ps1 = strings.Join(make([]string, indentCount*2), "..")
  402. self.ps1 += " "
  403. }
  404. }
  405. func (self *jsre) printValue(v interface{}) {
  406. val, err := self.re.PrettyPrint(v)
  407. if err == nil {
  408. fmt.Printf("%v", val)
  409. }
  410. }