js.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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/ethereum/go-ethereum/cmd/utils"
  29. "github.com/ethereum/go-ethereum/common/docserver"
  30. re "github.com/ethereum/go-ethereum/jsre"
  31. "github.com/ethereum/go-ethereum/rpc"
  32. "github.com/ethereum/go-ethereum/rpc/api"
  33. "github.com/ethereum/go-ethereum/rpc/codec"
  34. "github.com/ethereum/go-ethereum/rpc/comms"
  35. "github.com/ethereum/go-ethereum/rpc/shared"
  36. "github.com/peterh/liner"
  37. "github.com/robertkrimen/otto"
  38. )
  39. type prompter interface {
  40. AppendHistory(string)
  41. Prompt(p string) (string, error)
  42. PasswordPrompt(p string) (string, error)
  43. }
  44. type dumbterm struct{ r *bufio.Reader }
  45. func (r dumbterm) Prompt(p string) (string, error) {
  46. fmt.Print(p)
  47. line, err := r.r.ReadString('\n')
  48. return strings.TrimSuffix(line, "\n"), err
  49. }
  50. func (r dumbterm) PasswordPrompt(p string) (string, error) {
  51. fmt.Println("!! Unsupported terminal, password will echo.")
  52. fmt.Print(p)
  53. input, err := bufio.NewReader(os.Stdin).ReadString('\n')
  54. fmt.Println()
  55. return input, err
  56. }
  57. func (r dumbterm) AppendHistory(string) {}
  58. type jsre struct {
  59. re *re.JSRE
  60. wait chan *big.Int
  61. ps1 string
  62. atexit func()
  63. datadir string
  64. prompter
  65. }
  66. var (
  67. loadedModulesMethods map[string][]string
  68. )
  69. func loadAutoCompletion(js *jsre, ipcpath string) {
  70. modules, err := js.suportedApis(ipcpath)
  71. if err != nil {
  72. utils.Fatalf("Unable to determine supported modules - %v", err)
  73. }
  74. fmt.Printf("load autocompletion %v", modules)
  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) interactive() {
  284. // Read input lines.
  285. prompt := make(chan string)
  286. inputln := make(chan string)
  287. go func() {
  288. defer close(inputln)
  289. for {
  290. line, err := self.Prompt(<-prompt)
  291. if err != nil {
  292. return
  293. }
  294. inputln <- line
  295. }
  296. }()
  297. // Wait for Ctrl-C, too.
  298. sig := make(chan os.Signal, 1)
  299. signal.Notify(sig, os.Interrupt)
  300. defer func() {
  301. if self.atexit != nil {
  302. self.atexit()
  303. }
  304. self.re.Stop(false)
  305. }()
  306. for {
  307. prompt <- self.ps1
  308. select {
  309. case <-sig:
  310. fmt.Println("caught interrupt, exiting")
  311. return
  312. case input, ok := <-inputln:
  313. if !ok || indentCount <= 0 && input == "exit" {
  314. return
  315. }
  316. if input == "" {
  317. continue
  318. }
  319. str += input + "\n"
  320. self.setIndent()
  321. if indentCount <= 0 {
  322. hist := str[:len(str)-1]
  323. self.AppendHistory(hist)
  324. self.parseInput(str)
  325. str = ""
  326. }
  327. }
  328. }
  329. }
  330. func (self *jsre) withHistory(op func(*os.File)) {
  331. hist, err := os.OpenFile(filepath.Join(self.datadir, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
  332. if err != nil {
  333. fmt.Printf("unable to open history file: %v\n", err)
  334. return
  335. }
  336. op(hist)
  337. hist.Close()
  338. }
  339. func (self *jsre) parseInput(code string) {
  340. defer func() {
  341. if r := recover(); r != nil {
  342. fmt.Println("[native] error", r)
  343. }
  344. }()
  345. value, err := self.re.Run(code)
  346. if err != nil {
  347. if ottoErr, ok := err.(*otto.Error); ok {
  348. fmt.Println(ottoErr.String())
  349. } else {
  350. fmt.Println(err)
  351. }
  352. return
  353. }
  354. self.printValue(value)
  355. }
  356. var indentCount = 0
  357. var str = ""
  358. func (self *jsre) setIndent() {
  359. open := strings.Count(str, "{")
  360. open += strings.Count(str, "(")
  361. closed := strings.Count(str, "}")
  362. closed += strings.Count(str, ")")
  363. indentCount = open - closed
  364. if indentCount <= 0 {
  365. self.ps1 = "> "
  366. } else {
  367. self.ps1 = strings.Join(make([]string, indentCount*2), "..")
  368. self.ps1 += " "
  369. }
  370. }
  371. func (self *jsre) printValue(v interface{}) {
  372. val, err := self.re.PrettyPrint(v)
  373. if err == nil {
  374. fmt.Printf("%v", val)
  375. }
  376. }