js.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. "sort"
  26. "strings"
  27. "github.com/codegangsta/cli"
  28. "github.com/ethereum/go-ethereum/cmd/utils"
  29. "github.com/ethereum/go-ethereum/common"
  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/node"
  34. "github.com/ethereum/go-ethereum/rpc"
  35. "github.com/peterh/liner"
  36. "github.com/robertkrimen/otto"
  37. )
  38. var (
  39. passwordRegexp = regexp.MustCompile("personal.[nu]")
  40. leadingSpace = regexp.MustCompile("^ ")
  41. onlyws = regexp.MustCompile("^\\s*$")
  42. exit = regexp.MustCompile("^\\s*exit\\s*;*\\s*$")
  43. )
  44. type prompter interface {
  45. AppendHistory(string)
  46. Prompt(p string) (string, error)
  47. PasswordPrompt(p string) (string, error)
  48. }
  49. type dumbterm struct{ r *bufio.Reader }
  50. func (r dumbterm) Prompt(p string) (string, error) {
  51. fmt.Print(p)
  52. line, err := r.r.ReadString('\n')
  53. return strings.TrimSuffix(line, "\n"), err
  54. }
  55. func (r dumbterm) PasswordPrompt(p string) (string, error) {
  56. fmt.Println("!! Unsupported terminal, password will echo.")
  57. fmt.Print(p)
  58. input, err := bufio.NewReader(os.Stdin).ReadString('\n')
  59. fmt.Println()
  60. return input, err
  61. }
  62. func (r dumbterm) AppendHistory(string) {}
  63. type jsre struct {
  64. re *re.JSRE
  65. stack *node.Node
  66. wait chan *big.Int
  67. ps1 string
  68. atexit func()
  69. corsDomain string
  70. client rpc.Client
  71. prompter
  72. }
  73. func makeCompleter(re *jsre) liner.WordCompleter {
  74. return func(line string, pos int) (head string, completions []string, tail string) {
  75. if len(line) == 0 || pos == 0 {
  76. return "", nil, ""
  77. }
  78. // chuck data to relevant part for autocompletion, e.g. in case of nested lines eth.getBalance(eth.coinb<tab><tab>
  79. i := 0
  80. for i = pos - 1; i > 0; i-- {
  81. if line[i] == '.' || (line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') {
  82. continue
  83. }
  84. if i >= 3 && line[i] == '3' && line[i-3] == 'w' && line[i-2] == 'e' && line[i-1] == 'b' {
  85. continue
  86. }
  87. i += 1
  88. break
  89. }
  90. return line[:i], re.re.CompleteKeywords(line[i:pos]), line[pos:]
  91. }
  92. }
  93. func newLightweightJSRE(docRoot string, client rpc.Client, datadir string, interactive bool) *jsre {
  94. js := &jsre{ps1: "> "}
  95. js.wait = make(chan *big.Int)
  96. js.client = client
  97. js.re = re.New(docRoot)
  98. if err := js.apiBindings(); err != nil {
  99. utils.Fatalf("Unable to initialize console - %v", err)
  100. }
  101. if !liner.TerminalSupported() || !interactive {
  102. js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
  103. } else {
  104. lr := liner.NewLiner()
  105. js.withHistory(datadir, func(hist *os.File) { lr.ReadHistory(hist) })
  106. lr.SetCtrlCAborts(true)
  107. lr.SetWordCompleter(makeCompleter(js))
  108. lr.SetTabCompletionStyle(liner.TabPrints)
  109. js.prompter = lr
  110. js.atexit = func() {
  111. js.withHistory(datadir, func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
  112. lr.Close()
  113. close(js.wait)
  114. }
  115. }
  116. return js
  117. }
  118. func newJSRE(stack *node.Node, docRoot, corsDomain string, client rpc.Client, interactive bool) *jsre {
  119. js := &jsre{stack: stack, ps1: "> "}
  120. // set default cors domain used by startRpc from CLI flag
  121. js.corsDomain = corsDomain
  122. js.wait = make(chan *big.Int)
  123. js.client = client
  124. js.re = re.New(docRoot)
  125. if err := js.apiBindings(); err != nil {
  126. utils.Fatalf("Unable to connect - %v", err)
  127. }
  128. if !liner.TerminalSupported() || !interactive {
  129. js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
  130. } else {
  131. lr := liner.NewLiner()
  132. js.withHistory(stack.DataDir(), func(hist *os.File) { lr.ReadHistory(hist) })
  133. lr.SetCtrlCAborts(true)
  134. lr.SetWordCompleter(makeCompleter(js))
  135. lr.SetTabCompletionStyle(liner.TabPrints)
  136. js.prompter = lr
  137. js.atexit = func() {
  138. js.withHistory(stack.DataDir(), func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
  139. lr.Close()
  140. close(js.wait)
  141. }
  142. }
  143. return js
  144. }
  145. func (self *jsre) batch(statement string) {
  146. err := self.re.EvalAndPrettyPrint(statement)
  147. if err != nil {
  148. fmt.Printf("error: %v", err)
  149. }
  150. if self.atexit != nil {
  151. self.atexit()
  152. }
  153. self.re.Stop(false)
  154. }
  155. // show summary of current geth instance
  156. func (self *jsre) welcome() {
  157. self.re.Run(`
  158. (function () {
  159. console.log('instance: ' + web3.version.node);
  160. console.log("coinbase: " + eth.coinbase);
  161. var ts = 1000 * eth.getBlock(eth.blockNumber).timestamp;
  162. console.log("at block: " + eth.blockNumber + " (" + new Date(ts) + ")");
  163. console.log(' datadir: ' + admin.datadir);
  164. })();
  165. `)
  166. if modules, err := self.supportedApis(); err == nil {
  167. loadedModules := make([]string, 0)
  168. for api, version := range modules {
  169. loadedModules = append(loadedModules, fmt.Sprintf("%s:%s", api, version))
  170. }
  171. sort.Strings(loadedModules)
  172. }
  173. }
  174. func (self *jsre) supportedApis() (map[string]string, error) {
  175. return self.client.SupportedModules()
  176. }
  177. func (js *jsre) apiBindings() error {
  178. apis, err := js.supportedApis()
  179. if err != nil {
  180. return err
  181. }
  182. apiNames := make([]string, 0, len(apis))
  183. for a, _ := range apis {
  184. apiNames = append(apiNames, a)
  185. }
  186. jeth := utils.NewJeth(js.re, js.client)
  187. js.re.Set("jeth", struct{}{})
  188. t, _ := js.re.Get("jeth")
  189. jethObj := t.Object()
  190. jethObj.Set("send", jeth.Send)
  191. jethObj.Set("sendAsync", jeth.Send)
  192. err = js.re.Compile("bignumber.js", re.BigNumber_JS)
  193. if err != nil {
  194. utils.Fatalf("Error loading bignumber.js: %v", err)
  195. }
  196. err = js.re.Compile("web3.js", re.Web3_JS)
  197. if err != nil {
  198. utils.Fatalf("Error loading web3.js: %v", err)
  199. }
  200. _, err = js.re.Run("var Web3 = require('web3');")
  201. if err != nil {
  202. utils.Fatalf("Error requiring web3: %v", err)
  203. }
  204. _, err = js.re.Run("var web3 = new Web3(jeth);")
  205. if err != nil {
  206. utils.Fatalf("Error setting web3 provider: %v", err)
  207. }
  208. // load only supported API's in javascript runtime
  209. shortcuts := "var eth = web3.eth; "
  210. for _, apiName := range apiNames {
  211. if apiName == "web3" || apiName == "rpc" {
  212. continue // manually mapped or ignore
  213. }
  214. if jsFile, ok := rpc.WEB3Extensions[apiName]; ok {
  215. if err = js.re.Compile(fmt.Sprintf("%s.js", apiName), jsFile); err == nil {
  216. shortcuts += fmt.Sprintf("var %s = web3.%s; ", apiName, apiName)
  217. } else {
  218. utils.Fatalf("Error loading %s.js: %v", apiName, err)
  219. }
  220. }
  221. }
  222. _, err = js.re.Run(shortcuts)
  223. if err != nil {
  224. utils.Fatalf("Error setting namespaces: %v", err)
  225. }
  226. js.re.Run(`var GlobalRegistrar = eth.contract(` + registrar.GlobalRegistrarAbi + `); registrar = GlobalRegistrar.at("` + registrar.GlobalRegistrarAddr + `");`)
  227. // overrule some of the methods that require password as input and ask for it interactively
  228. p, err := js.re.Get("personal")
  229. if err != nil {
  230. fmt.Println("Unable to overrule sensitive methods in personal module")
  231. return nil
  232. }
  233. // Override the unlockAccount and newAccount methods on the personal object since these require user interaction.
  234. // Assign the jeth.unlockAccount and jeth.newAccount in the jsre the original web3 callbacks. These will be called
  235. // by the jeth.* methods after they got the password from the user and send the original web3 request to the backend.
  236. if persObj := p.Object(); persObj != nil { // make sure the personal api is enabled over the interface
  237. js.re.Run(`jeth.unlockAccount = personal.unlockAccount;`)
  238. persObj.Set("unlockAccount", jeth.UnlockAccount)
  239. js.re.Run(`jeth.newAccount = personal.newAccount;`)
  240. persObj.Set("newAccount", jeth.NewAccount)
  241. }
  242. // The admin.sleep and admin.sleepBlocks are offered by the console and not by the RPC layer.
  243. // Bind these if the admin module is available.
  244. if a, err := js.re.Get("admin"); err == nil {
  245. if adminObj := a.Object(); adminObj != nil {
  246. adminObj.Set("sleepBlocks", jeth.SleepBlocks)
  247. adminObj.Set("sleep", jeth.Sleep)
  248. }
  249. }
  250. return nil
  251. }
  252. func (self *jsre) AskPassword() (string, bool) {
  253. pass, err := self.PasswordPrompt("Passphrase: ")
  254. if err != nil {
  255. return "", false
  256. }
  257. return pass, true
  258. }
  259. func (self *jsre) ConfirmTransaction(tx string) bool {
  260. // Retrieve the Ethereum instance from the node
  261. var ethereum *eth.Ethereum
  262. if err := self.stack.Service(&ethereum); err != nil {
  263. return false
  264. }
  265. // If natspec is enabled, ask for permission
  266. if ethereum.NatSpec && false /* disabled for now */ {
  267. // notice := natspec.GetNotice(self.xeth, tx, ethereum.HTTPClient())
  268. // fmt.Println(notice)
  269. // answer, _ := self.Prompt("Confirm Transaction [y/n]")
  270. // return strings.HasPrefix(strings.Trim(answer, " "), "y")
  271. }
  272. return true
  273. }
  274. func (self *jsre) UnlockAccount(addr []byte) bool {
  275. fmt.Printf("Please unlock account %x.\n", addr)
  276. pass, err := self.PasswordPrompt("Passphrase: ")
  277. if err != nil {
  278. return false
  279. }
  280. // TODO: allow retry
  281. var ethereum *eth.Ethereum
  282. if err := self.stack.Service(&ethereum); err != nil {
  283. return false
  284. }
  285. if err := ethereum.AccountManager().Unlock(common.BytesToAddress(addr), pass); err != nil {
  286. return false
  287. } else {
  288. fmt.Println("Account is now unlocked for this session.")
  289. return true
  290. }
  291. }
  292. // preloadJSFiles loads JS files that the user has specified with ctx.PreLoadJSFlag into
  293. // the JSRE. If not all files could be loaded it will return an error describing the error.
  294. func (self *jsre) preloadJSFiles(ctx *cli.Context) error {
  295. if ctx.GlobalString(utils.PreLoadJSFlag.Name) != "" {
  296. assetPath := ctx.GlobalString(utils.JSpathFlag.Name)
  297. jsFiles := strings.Split(ctx.GlobalString(utils.PreLoadJSFlag.Name), ",")
  298. for _, file := range jsFiles {
  299. filename := common.AbsolutePath(assetPath, strings.TrimSpace(file))
  300. if err := self.re.Exec(filename); err != nil {
  301. return fmt.Errorf("%s: %v", file, err)
  302. }
  303. }
  304. }
  305. return nil
  306. }
  307. // exec executes the JS file with the given filename and stops the JSRE
  308. func (self *jsre) exec(filename string) error {
  309. if err := self.re.Exec(filename); err != nil {
  310. self.re.Stop(false)
  311. return fmt.Errorf("Javascript Error: %v", err)
  312. }
  313. self.re.Stop(true)
  314. return nil
  315. }
  316. func (self *jsre) interactive() {
  317. // Read input lines.
  318. prompt := make(chan string)
  319. inputln := make(chan string)
  320. go func() {
  321. defer close(inputln)
  322. for {
  323. line, err := self.Prompt(<-prompt)
  324. if err != nil {
  325. if err == liner.ErrPromptAborted { // ctrl-C
  326. self.resetPrompt()
  327. inputln <- ""
  328. continue
  329. }
  330. return
  331. }
  332. inputln <- line
  333. }
  334. }()
  335. // Wait for Ctrl-C, too.
  336. sig := make(chan os.Signal, 1)
  337. signal.Notify(sig, os.Interrupt)
  338. defer func() {
  339. if self.atexit != nil {
  340. self.atexit()
  341. }
  342. self.re.Stop(false)
  343. }()
  344. for {
  345. prompt <- self.ps1
  346. select {
  347. case <-sig:
  348. fmt.Println("caught interrupt, exiting")
  349. return
  350. case input, ok := <-inputln:
  351. if !ok || indentCount <= 0 && exit.MatchString(input) {
  352. return
  353. }
  354. if onlyws.MatchString(input) {
  355. continue
  356. }
  357. str += input + "\n"
  358. self.setIndent()
  359. if indentCount <= 0 {
  360. if mustLogInHistory(str) {
  361. self.AppendHistory(str[:len(str)-1])
  362. }
  363. self.parseInput(str)
  364. str = ""
  365. }
  366. }
  367. }
  368. }
  369. func mustLogInHistory(input string) bool {
  370. return len(input) == 0 ||
  371. passwordRegexp.MatchString(input) ||
  372. !leadingSpace.MatchString(input)
  373. }
  374. func (self *jsre) withHistory(datadir string, op func(*os.File)) {
  375. hist, err := os.OpenFile(filepath.Join(datadir, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
  376. if err != nil {
  377. fmt.Printf("unable to open history file: %v\n", err)
  378. return
  379. }
  380. op(hist)
  381. hist.Close()
  382. }
  383. func (self *jsre) parseInput(code string) {
  384. defer func() {
  385. if r := recover(); r != nil {
  386. fmt.Println("[native] error", r)
  387. }
  388. }()
  389. if err := self.re.EvalAndPrettyPrint(code); err != nil {
  390. if ottoErr, ok := err.(*otto.Error); ok {
  391. fmt.Println(ottoErr.String())
  392. } else {
  393. fmt.Println(err)
  394. }
  395. return
  396. }
  397. }
  398. var indentCount = 0
  399. var str = ""
  400. func (self *jsre) resetPrompt() {
  401. indentCount = 0
  402. str = ""
  403. self.ps1 = "> "
  404. }
  405. func (self *jsre) setIndent() {
  406. open := strings.Count(str, "{")
  407. open += strings.Count(str, "(")
  408. closed := strings.Count(str, "}")
  409. closed += strings.Count(str, ")")
  410. indentCount = open - closed
  411. if indentCount <= 0 {
  412. self.ps1 = "> "
  413. } else {
  414. self.ps1 = strings.Join(make([]string, indentCount*2), "..")
  415. self.ps1 += " "
  416. }
  417. }