js.go 10 KB

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