js.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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/docserver"
  30. "github.com/ethereum/go-ethereum/common/natspec"
  31. "github.com/ethereum/go-ethereum/common/registrar"
  32. "github.com/ethereum/go-ethereum/eth"
  33. re "github.com/ethereum/go-ethereum/jsre"
  34. "github.com/ethereum/go-ethereum/rpc"
  35. "github.com/ethereum/go-ethereum/rpc/api"
  36. "github.com/ethereum/go-ethereum/rpc/codec"
  37. "github.com/ethereum/go-ethereum/rpc/comms"
  38. "github.com/ethereum/go-ethereum/rpc/shared"
  39. "github.com/ethereum/go-ethereum/xeth"
  40. "github.com/peterh/liner"
  41. "github.com/robertkrimen/otto"
  42. )
  43. var passwordRegexp = regexp.MustCompile("personal.[nu]")
  44. const passwordRepl = ""
  45. type prompter interface {
  46. AppendHistory(string)
  47. Prompt(p string) (string, error)
  48. PasswordPrompt(p string) (string, error)
  49. }
  50. type dumbterm struct{ r *bufio.Reader }
  51. func (r dumbterm) Prompt(p string) (string, error) {
  52. fmt.Print(p)
  53. line, err := r.r.ReadString('\n')
  54. return strings.TrimSuffix(line, "\n"), err
  55. }
  56. func (r dumbterm) PasswordPrompt(p string) (string, error) {
  57. fmt.Println("!! Unsupported terminal, password will echo.")
  58. fmt.Print(p)
  59. input, err := bufio.NewReader(os.Stdin).ReadString('\n')
  60. fmt.Println()
  61. return input, err
  62. }
  63. func (r dumbterm) AppendHistory(string) {}
  64. type jsre struct {
  65. ds *docserver.DocServer
  66. re *re.JSRE
  67. ethereum *eth.Ethereum
  68. xeth *xeth.XEth
  69. wait chan *big.Int
  70. ps1 string
  71. atexit func()
  72. corsDomain string
  73. client comms.EthereumClient
  74. prompter
  75. }
  76. var (
  77. loadedModulesMethods map[string][]string
  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 || pos == 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 newLightweightJSRE(libPath string, client comms.EthereumClient, datadir string, interactive bool) *jsre {
  129. js := &jsre{ps1: "> "}
  130. js.wait = make(chan *big.Int)
  131. js.client = client
  132. js.ds = docserver.New("/")
  133. // update state in separare forever blocks
  134. js.re = re.New(libPath)
  135. if err := js.apiBindings(js); err != nil {
  136. utils.Fatalf("Unable to initialize console - %v", err)
  137. }
  138. if !liner.TerminalSupported() || !interactive {
  139. js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
  140. } else {
  141. lr := liner.NewLiner()
  142. js.withHistory(datadir, func(hist *os.File) { lr.ReadHistory(hist) })
  143. lr.SetCtrlCAborts(true)
  144. js.loadAutoCompletion()
  145. lr.SetWordCompleter(apiWordCompleter)
  146. lr.SetTabCompletionStyle(liner.TabPrints)
  147. js.prompter = lr
  148. js.atexit = func() {
  149. js.withHistory(datadir, func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
  150. lr.Close()
  151. close(js.wait)
  152. }
  153. }
  154. return js
  155. }
  156. func newJSRE(ethereum *eth.Ethereum, libPath, corsDomain string, client comms.EthereumClient, interactive bool, f xeth.Frontend) *jsre {
  157. js := &jsre{ethereum: ethereum, ps1: "> "}
  158. // set default cors domain used by startRpc from CLI flag
  159. js.corsDomain = corsDomain
  160. if f == nil {
  161. f = js
  162. }
  163. js.ds = docserver.New("/")
  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(libPath)
  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) ConfirmTransaction(tx string) bool {
  291. if self.ethereum.NatSpec {
  292. notice := natspec.GetNotice(self.xeth, tx, self.ds)
  293. fmt.Println(notice)
  294. answer, _ := self.Prompt("Confirm Transaction [y/n]")
  295. return strings.HasPrefix(strings.Trim(answer, " "), "y")
  296. } else {
  297. return true
  298. }
  299. }
  300. func (self *jsre) UnlockAccount(addr []byte) bool {
  301. fmt.Printf("Please unlock account %x.\n", addr)
  302. pass, err := self.PasswordPrompt("Passphrase: ")
  303. if err != nil {
  304. return false
  305. }
  306. // TODO: allow retry
  307. if err := self.ethereum.AccountManager().Unlock(common.BytesToAddress(addr), pass); err != nil {
  308. return false
  309. } else {
  310. fmt.Println("Account is now unlocked for this session.")
  311. return true
  312. }
  313. }
  314. func (self *jsre) exec(filename string) error {
  315. if err := self.re.Exec(filename); err != nil {
  316. self.re.Stop(false)
  317. return fmt.Errorf("Javascript Error: %v", err)
  318. }
  319. self.re.Stop(true)
  320. return nil
  321. }
  322. func (self *jsre) interactive() {
  323. // Read input lines.
  324. prompt := make(chan string)
  325. inputln := make(chan string)
  326. go func() {
  327. defer close(inputln)
  328. for {
  329. line, err := self.Prompt(<-prompt)
  330. if err != nil {
  331. if err == liner.ErrPromptAborted { // ctrl-C
  332. self.resetPrompt()
  333. inputln <- ""
  334. continue
  335. }
  336. return
  337. }
  338. inputln <- line
  339. }
  340. }()
  341. // Wait for Ctrl-C, too.
  342. sig := make(chan os.Signal, 1)
  343. signal.Notify(sig, os.Interrupt)
  344. defer func() {
  345. if self.atexit != nil {
  346. self.atexit()
  347. }
  348. self.re.Stop(false)
  349. }()
  350. for {
  351. prompt <- self.ps1
  352. select {
  353. case <-sig:
  354. fmt.Println("caught interrupt, exiting")
  355. return
  356. case input, ok := <-inputln:
  357. if !ok || indentCount <= 0 && input == "exit" {
  358. return
  359. }
  360. if input == "" {
  361. continue
  362. }
  363. str += input + "\n"
  364. self.setIndent()
  365. if indentCount <= 0 {
  366. hist := hidepassword(str[:len(str)-1])
  367. if len(hist) > 0 {
  368. self.AppendHistory(hist)
  369. }
  370. self.parseInput(str)
  371. str = ""
  372. }
  373. }
  374. }
  375. }
  376. func hidepassword(input string) string {
  377. if passwordRegexp.MatchString(input) {
  378. return passwordRepl
  379. } else {
  380. return input
  381. }
  382. }
  383. func (self *jsre) withHistory(datadir string, op func(*os.File)) {
  384. hist, err := os.OpenFile(filepath.Join(datadir, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
  385. if err != nil {
  386. fmt.Printf("unable to open history file: %v\n", err)
  387. return
  388. }
  389. op(hist)
  390. hist.Close()
  391. }
  392. func (self *jsre) parseInput(code string) {
  393. defer func() {
  394. if r := recover(); r != nil {
  395. fmt.Println("[native] error", r)
  396. }
  397. }()
  398. if err := self.re.EvalAndPrettyPrint(code); err != nil {
  399. if ottoErr, ok := err.(*otto.Error); ok {
  400. fmt.Println(ottoErr.String())
  401. } else {
  402. fmt.Println(err)
  403. }
  404. return
  405. }
  406. }
  407. var indentCount = 0
  408. var str = ""
  409. func (self *jsre) resetPrompt() {
  410. indentCount = 0
  411. str = ""
  412. self.ps1 = "> "
  413. }
  414. func (self *jsre) setIndent() {
  415. open := strings.Count(str, "{")
  416. open += strings.Count(str, "(")
  417. closed := strings.Count(str, "}")
  418. closed += strings.Count(str, ")")
  419. indentCount = open - closed
  420. if indentCount <= 0 {
  421. self.ps1 = "> "
  422. } else {
  423. self.ps1 = strings.Join(make([]string, indentCount*2), "..")
  424. self.ps1 += " "
  425. }
  426. }