js.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "bufio"
  19. "fmt"
  20. "math/big"
  21. "os"
  22. "os/signal"
  23. "path/filepath"
  24. "regexp"
  25. "strings"
  26. "sort"
  27. "github.com/ethereum/go-ethereum/cmd/utils"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/common/natspec"
  30. "github.com/ethereum/go-ethereum/common/registrar"
  31. "github.com/ethereum/go-ethereum/eth"
  32. re "github.com/ethereum/go-ethereum/jsre"
  33. "github.com/ethereum/go-ethereum/rpc"
  34. "github.com/ethereum/go-ethereum/rpc/api"
  35. "github.com/ethereum/go-ethereum/rpc/codec"
  36. "github.com/ethereum/go-ethereum/rpc/comms"
  37. "github.com/ethereum/go-ethereum/rpc/shared"
  38. "github.com/ethereum/go-ethereum/xeth"
  39. "github.com/peterh/liner"
  40. "github.com/robertkrimen/otto"
  41. )
  42. var (
  43. passwordRegexp = regexp.MustCompile("personal.[nu]")
  44. leadingSpace = regexp.MustCompile("^ ")
  45. onlyws = regexp.MustCompile("^\\s*$")
  46. exit = regexp.MustCompile("^\\s*exit\\s*;*\\s*$")
  47. )
  48. type prompter interface {
  49. AppendHistory(string)
  50. Prompt(p string) (string, error)
  51. PasswordPrompt(p string) (string, error)
  52. }
  53. type dumbterm struct{ r *bufio.Reader }
  54. func (r dumbterm) Prompt(p string) (string, error) {
  55. fmt.Print(p)
  56. line, err := r.r.ReadString('\n')
  57. return strings.TrimSuffix(line, "\n"), err
  58. }
  59. func (r dumbterm) PasswordPrompt(p string) (string, error) {
  60. fmt.Println("!! Unsupported terminal, password will echo.")
  61. fmt.Print(p)
  62. input, err := bufio.NewReader(os.Stdin).ReadString('\n')
  63. fmt.Println()
  64. return input, err
  65. }
  66. func (r dumbterm) AppendHistory(string) {}
  67. type jsre struct {
  68. re *re.JSRE
  69. ethereum *eth.Ethereum
  70. xeth *xeth.XEth
  71. wait chan *big.Int
  72. ps1 string
  73. atexit func()
  74. corsDomain string
  75. client comms.EthereumClient
  76. prompter
  77. }
  78. var (
  79. loadedModulesMethods map[string][]string
  80. )
  81. func keywordCompleter(line string) []string {
  82. results := make([]string, 0)
  83. if strings.Contains(line, ".") {
  84. elements := strings.Split(line, ".")
  85. if len(elements) == 2 {
  86. module := elements[0]
  87. partialMethod := elements[1]
  88. if methods, found := loadedModulesMethods[module]; found {
  89. for _, method := range methods {
  90. if strings.HasPrefix(method, partialMethod) { // e.g. debug.se
  91. results = append(results, module+"."+method)
  92. }
  93. }
  94. }
  95. }
  96. } else {
  97. for module, methods := range loadedModulesMethods {
  98. if line == module { // user typed in full module name, show all methods
  99. for _, method := range methods {
  100. results = append(results, module+"."+method)
  101. }
  102. } else if strings.HasPrefix(module, line) { // partial method name, e.g. admi
  103. results = append(results, module)
  104. }
  105. }
  106. }
  107. return results
  108. }
  109. func apiWordCompleter(line string, pos int) (head string, completions []string, tail string) {
  110. if len(line) == 0 || pos == 0 {
  111. return "", nil, ""
  112. }
  113. i := 0
  114. for i = pos - 1; i > 0; i-- {
  115. if line[i] == '.' || (line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') {
  116. continue
  117. }
  118. if i >= 3 && line[i] == '3' && line[i-3] == 'w' && line[i-2] == 'e' && line[i-1] == 'b' {
  119. continue
  120. }
  121. i += 1
  122. break
  123. }
  124. begin := line[:i]
  125. keyword := line[i:pos]
  126. end := line[pos:]
  127. completionWords := keywordCompleter(keyword)
  128. return begin, completionWords, end
  129. }
  130. func newLightweightJSRE(docRoot string, client comms.EthereumClient, datadir string, interactive bool) *jsre {
  131. js := &jsre{ps1: "> "}
  132. js.wait = make(chan *big.Int)
  133. js.client = client
  134. // update state in separare forever blocks
  135. js.re = re.New(docRoot)
  136. if err := js.apiBindings(js); err != nil {
  137. utils.Fatalf("Unable to initialize console - %v", err)
  138. }
  139. if !liner.TerminalSupported() || !interactive {
  140. js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
  141. } else {
  142. lr := liner.NewLiner()
  143. js.withHistory(datadir, func(hist *os.File) { lr.ReadHistory(hist) })
  144. lr.SetCtrlCAborts(true)
  145. js.loadAutoCompletion()
  146. lr.SetWordCompleter(apiWordCompleter)
  147. lr.SetTabCompletionStyle(liner.TabPrints)
  148. js.prompter = lr
  149. js.atexit = func() {
  150. js.withHistory(datadir, func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
  151. lr.Close()
  152. close(js.wait)
  153. }
  154. }
  155. return js
  156. }
  157. func newJSRE(ethereum *eth.Ethereum, docRoot, corsDomain string, client comms.EthereumClient, interactive bool, f xeth.Frontend) *jsre {
  158. js := &jsre{ethereum: ethereum, ps1: "> "}
  159. // set default cors domain used by startRpc from CLI flag
  160. js.corsDomain = corsDomain
  161. if f == nil {
  162. f = js
  163. }
  164. js.xeth = xeth.New(ethereum, f)
  165. js.wait = js.xeth.UpdateState()
  166. js.client = client
  167. if clt, ok := js.client.(*comms.InProcClient); ok {
  168. if offeredApis, err := api.ParseApiString(shared.AllApis, codec.JSON, js.xeth, ethereum); err == nil {
  169. clt.Initialize(api.Merge(offeredApis...))
  170. }
  171. }
  172. // update state in separare forever blocks
  173. js.re = re.New(docRoot)
  174. if err := js.apiBindings(f); err != nil {
  175. utils.Fatalf("Unable to connect - %v", err)
  176. }
  177. if !liner.TerminalSupported() || !interactive {
  178. js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
  179. } else {
  180. lr := liner.NewLiner()
  181. js.withHistory(ethereum.DataDir, func(hist *os.File) { lr.ReadHistory(hist) })
  182. lr.SetCtrlCAborts(true)
  183. js.loadAutoCompletion()
  184. lr.SetWordCompleter(apiWordCompleter)
  185. lr.SetTabCompletionStyle(liner.TabPrints)
  186. js.prompter = lr
  187. js.atexit = func() {
  188. js.withHistory(ethereum.DataDir, func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
  189. lr.Close()
  190. close(js.wait)
  191. }
  192. }
  193. return js
  194. }
  195. func (self *jsre) loadAutoCompletion() {
  196. if modules, err := self.supportedApis(); err == nil {
  197. loadedModulesMethods = make(map[string][]string)
  198. for module, _ := range modules {
  199. loadedModulesMethods[module] = api.AutoCompletion[module]
  200. }
  201. }
  202. }
  203. func (self *jsre) batch(statement string) {
  204. err := self.re.EvalAndPrettyPrint(statement)
  205. if err != nil {
  206. fmt.Printf("error: %v", err)
  207. }
  208. if self.atexit != nil {
  209. self.atexit()
  210. }
  211. self.re.Stop(false)
  212. }
  213. // show summary of current geth instance
  214. func (self *jsre) welcome() {
  215. self.re.Run(`
  216. (function () {
  217. console.log('instance: ' + web3.version.client);
  218. console.log(' datadir: ' + admin.datadir);
  219. console.log("coinbase: " + eth.coinbase);
  220. var ts = 1000 * eth.getBlock(eth.blockNumber).timestamp;
  221. console.log("at block: " + eth.blockNumber + " (" + new Date(ts) + ")");
  222. })();
  223. `)
  224. if modules, err := self.supportedApis(); err == nil {
  225. loadedModules := make([]string, 0)
  226. for api, version := range modules {
  227. loadedModules = append(loadedModules, fmt.Sprintf("%s:%s", api, version))
  228. }
  229. sort.Strings(loadedModules)
  230. fmt.Println("modules:", strings.Join(loadedModules, " "))
  231. }
  232. }
  233. func (self *jsre) supportedApis() (map[string]string, error) {
  234. return self.client.SupportedModules()
  235. }
  236. func (js *jsre) apiBindings(f xeth.Frontend) error {
  237. apis, err := js.supportedApis()
  238. if err != nil {
  239. return err
  240. }
  241. apiNames := make([]string, 0, len(apis))
  242. for a, _ := range apis {
  243. apiNames = append(apiNames, a)
  244. }
  245. apiImpl, err := api.ParseApiString(strings.Join(apiNames, ","), codec.JSON, js.xeth, js.ethereum)
  246. if err != nil {
  247. utils.Fatalf("Unable to determine supported api's: %v", err)
  248. }
  249. jeth := rpc.NewJeth(api.Merge(apiImpl...), js.re, js.client, f)
  250. js.re.Set("jeth", struct{}{})
  251. t, _ := js.re.Get("jeth")
  252. jethObj := t.Object()
  253. jethObj.Set("send", jeth.Send)
  254. jethObj.Set("sendAsync", jeth.Send)
  255. err = js.re.Compile("bignumber.js", re.BigNumber_JS)
  256. if err != nil {
  257. utils.Fatalf("Error loading bignumber.js: %v", err)
  258. }
  259. err = js.re.Compile("ethereum.js", re.Web3_JS)
  260. if err != nil {
  261. utils.Fatalf("Error loading web3.js: %v", err)
  262. }
  263. _, err = js.re.Run("var web3 = require('web3');")
  264. if err != nil {
  265. utils.Fatalf("Error requiring web3: %v", err)
  266. }
  267. _, err = js.re.Run("web3.setProvider(jeth)")
  268. if err != nil {
  269. utils.Fatalf("Error setting web3 provider: %v", err)
  270. }
  271. // load only supported API's in javascript runtime
  272. shortcuts := "var eth = web3.eth; "
  273. for _, apiName := range apiNames {
  274. if apiName == shared.Web3ApiName {
  275. continue // manually mapped
  276. }
  277. if err = js.re.Compile(fmt.Sprintf("%s.js", apiName), api.Javascript(apiName)); err == nil {
  278. shortcuts += fmt.Sprintf("var %s = web3.%s; ", apiName, apiName)
  279. } else {
  280. utils.Fatalf("Error loading %s.js: %v", apiName, err)
  281. }
  282. }
  283. _, err = js.re.Run(shortcuts)
  284. if err != nil {
  285. utils.Fatalf("Error setting namespaces: %v", err)
  286. }
  287. js.re.Run(`var GlobalRegistrar = eth.contract(` + registrar.GlobalRegistrarAbi + `); registrar = GlobalRegistrar.at("` + registrar.GlobalRegistrarAddr + `");`)
  288. return nil
  289. }
  290. func (self *jsre) AskPassword() (string, bool) {
  291. pass, err := self.PasswordPrompt("Passphrase: ")
  292. if err != nil {
  293. return "", false
  294. }
  295. return pass, true
  296. }
  297. func (self *jsre) ConfirmTransaction(tx string) bool {
  298. if self.ethereum.NatSpec {
  299. notice := natspec.GetNotice(self.xeth, tx, self.ethereum.HTTPClient())
  300. fmt.Println(notice)
  301. answer, _ := self.Prompt("Confirm Transaction [y/n]")
  302. return strings.HasPrefix(strings.Trim(answer, " "), "y")
  303. } else {
  304. return true
  305. }
  306. }
  307. func (self *jsre) UnlockAccount(addr []byte) bool {
  308. fmt.Printf("Please unlock account %x.\n", addr)
  309. pass, err := self.PasswordPrompt("Passphrase: ")
  310. if err != nil {
  311. return false
  312. }
  313. // TODO: allow retry
  314. if err := self.ethereum.AccountManager().Unlock(common.BytesToAddress(addr), pass); err != nil {
  315. return false
  316. } else {
  317. fmt.Println("Account is now unlocked for this session.")
  318. return true
  319. }
  320. }
  321. func (self *jsre) exec(filename string) error {
  322. if err := self.re.Exec(filename); err != nil {
  323. self.re.Stop(false)
  324. return fmt.Errorf("Javascript Error: %v", err)
  325. }
  326. self.re.Stop(true)
  327. return nil
  328. }
  329. func (self *jsre) interactive() {
  330. // Read input lines.
  331. prompt := make(chan string)
  332. inputln := make(chan string)
  333. go func() {
  334. defer close(inputln)
  335. for {
  336. line, err := self.Prompt(<-prompt)
  337. if err != nil {
  338. if err == liner.ErrPromptAborted { // ctrl-C
  339. self.resetPrompt()
  340. inputln <- ""
  341. continue
  342. }
  343. return
  344. }
  345. inputln <- line
  346. }
  347. }()
  348. // Wait for Ctrl-C, too.
  349. sig := make(chan os.Signal, 1)
  350. signal.Notify(sig, os.Interrupt)
  351. defer func() {
  352. if self.atexit != nil {
  353. self.atexit()
  354. }
  355. self.re.Stop(false)
  356. }()
  357. for {
  358. prompt <- self.ps1
  359. select {
  360. case <-sig:
  361. fmt.Println("caught interrupt, exiting")
  362. return
  363. case input, ok := <-inputln:
  364. if !ok || indentCount <= 0 && exit.MatchString(input) {
  365. return
  366. }
  367. if onlyws.MatchString(input) {
  368. continue
  369. }
  370. str += input + "\n"
  371. self.setIndent()
  372. if indentCount <= 0 {
  373. if mustLogInHistory(str) {
  374. self.AppendHistory(str[:len(str)-1])
  375. }
  376. self.parseInput(str)
  377. str = ""
  378. }
  379. }
  380. }
  381. }
  382. func mustLogInHistory(input string) bool {
  383. return len(input) == 0 ||
  384. passwordRegexp.MatchString(input) ||
  385. !leadingSpace.MatchString(input)
  386. }
  387. func (self *jsre) withHistory(datadir string, op func(*os.File)) {
  388. hist, err := os.OpenFile(filepath.Join(datadir, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
  389. if err != nil {
  390. fmt.Printf("unable to open history file: %v\n", err)
  391. return
  392. }
  393. op(hist)
  394. hist.Close()
  395. }
  396. func (self *jsre) parseInput(code string) {
  397. defer func() {
  398. if r := recover(); r != nil {
  399. fmt.Println("[native] error", r)
  400. }
  401. }()
  402. if err := self.re.EvalAndPrettyPrint(code); err != nil {
  403. if ottoErr, ok := err.(*otto.Error); ok {
  404. fmt.Println(ottoErr.String())
  405. } else {
  406. fmt.Println(err)
  407. }
  408. return
  409. }
  410. }
  411. var indentCount = 0
  412. var str = ""
  413. func (self *jsre) resetPrompt() {
  414. indentCount = 0
  415. str = ""
  416. self.ps1 = "> "
  417. }
  418. func (self *jsre) setIndent() {
  419. open := strings.Count(str, "{")
  420. open += strings.Count(str, "(")
  421. closed := strings.Count(str, "}")
  422. closed += strings.Count(str, ")")
  423. indentCount = open - closed
  424. if indentCount <= 0 {
  425. self.ps1 = "> "
  426. } else {
  427. self.ps1 = strings.Join(make([]string, indentCount*2), "..")
  428. self.ps1 += " "
  429. }
  430. }