js.go 11 KB

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