console.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. // Copyright 2016 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser 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. // The go-ethereum library 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 Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package console
  17. import (
  18. "fmt"
  19. "io"
  20. "io/ioutil"
  21. "os"
  22. "os/signal"
  23. "path/filepath"
  24. "regexp"
  25. "sort"
  26. "strings"
  27. "syscall"
  28. "github.com/dop251/goja"
  29. "github.com/ethereum/go-ethereum/console/prompt"
  30. "github.com/ethereum/go-ethereum/internal/jsre"
  31. "github.com/ethereum/go-ethereum/internal/jsre/deps"
  32. "github.com/ethereum/go-ethereum/internal/web3ext"
  33. "github.com/ethereum/go-ethereum/rpc"
  34. "github.com/mattn/go-colorable"
  35. "github.com/peterh/liner"
  36. )
  37. var (
  38. // u: unlock, s: signXX, sendXX, n: newAccount, i: importXX
  39. passwordRegexp = regexp.MustCompile(`personal.[nusi]`)
  40. onlyWhitespace = regexp.MustCompile(`^\s*$`)
  41. exit = regexp.MustCompile(`^\s*exit\s*;*\s*$`)
  42. )
  43. // HistoryFile is the file within the data directory to store input scrollback.
  44. const HistoryFile = "history"
  45. // DefaultPrompt is the default prompt line prefix to use for user input querying.
  46. const DefaultPrompt = "> "
  47. // Config is the collection of configurations to fine tune the behavior of the
  48. // JavaScript console.
  49. type Config struct {
  50. DataDir string // Data directory to store the console history at
  51. DocRoot string // Filesystem path from where to load JavaScript files from
  52. Client *rpc.Client // RPC client to execute Ethereum requests through
  53. Prompt string // Input prompt prefix string (defaults to DefaultPrompt)
  54. Prompter prompt.UserPrompter // Input prompter to allow interactive user feedback (defaults to TerminalPrompter)
  55. Printer io.Writer // Output writer to serialize any display strings to (defaults to os.Stdout)
  56. Preload []string // Absolute paths to JavaScript files to preload
  57. }
  58. // Console is a JavaScript interpreted runtime environment. It is a fully fledged
  59. // JavaScript console attached to a running node via an external or in-process RPC
  60. // client.
  61. type Console struct {
  62. client *rpc.Client // RPC client to execute Ethereum requests through
  63. jsre *jsre.JSRE // JavaScript runtime environment running the interpreter
  64. prompt string // Input prompt prefix string
  65. prompter prompt.UserPrompter // Input prompter to allow interactive user feedback
  66. histPath string // Absolute path to the console scrollback history
  67. history []string // Scroll history maintained by the console
  68. printer io.Writer // Output writer to serialize any display strings to
  69. }
  70. // New initializes a JavaScript interpreted runtime environment and sets defaults
  71. // with the config struct.
  72. func New(config Config) (*Console, error) {
  73. // Handle unset config values gracefully
  74. if config.Prompter == nil {
  75. config.Prompter = prompt.Stdin
  76. }
  77. if config.Prompt == "" {
  78. config.Prompt = DefaultPrompt
  79. }
  80. if config.Printer == nil {
  81. config.Printer = colorable.NewColorableStdout()
  82. }
  83. // Initialize the console and return
  84. console := &Console{
  85. client: config.Client,
  86. jsre: jsre.New(config.DocRoot, config.Printer),
  87. prompt: config.Prompt,
  88. prompter: config.Prompter,
  89. printer: config.Printer,
  90. histPath: filepath.Join(config.DataDir, HistoryFile),
  91. }
  92. if err := os.MkdirAll(config.DataDir, 0700); err != nil {
  93. return nil, err
  94. }
  95. if err := console.init(config.Preload); err != nil {
  96. return nil, err
  97. }
  98. return console, nil
  99. }
  100. // init retrieves the available APIs from the remote RPC provider and initializes
  101. // the console's JavaScript namespaces based on the exposed modules.
  102. func (c *Console) init(preload []string) error {
  103. c.initConsoleObject()
  104. // Initialize the JavaScript <-> Go RPC bridge.
  105. bridge := newBridge(c.client, c.prompter, c.printer)
  106. if err := c.initWeb3(bridge); err != nil {
  107. return err
  108. }
  109. if err := c.initExtensions(); err != nil {
  110. return err
  111. }
  112. // Add bridge overrides for web3.js functionality.
  113. c.jsre.Do(func(vm *goja.Runtime) {
  114. c.initAdmin(vm, bridge)
  115. c.initPersonal(vm, bridge)
  116. })
  117. // Preload JavaScript files.
  118. for _, path := range preload {
  119. if err := c.jsre.Exec(path); err != nil {
  120. failure := err.Error()
  121. if gojaErr, ok := err.(*goja.Exception); ok {
  122. failure = gojaErr.String()
  123. }
  124. return fmt.Errorf("%s: %v", path, failure)
  125. }
  126. }
  127. // Configure the input prompter for history and tab completion.
  128. if c.prompter != nil {
  129. if content, err := ioutil.ReadFile(c.histPath); err != nil {
  130. c.prompter.SetHistory(nil)
  131. } else {
  132. c.history = strings.Split(string(content), "\n")
  133. c.prompter.SetHistory(c.history)
  134. }
  135. c.prompter.SetWordCompleter(c.AutoCompleteInput)
  136. }
  137. return nil
  138. }
  139. func (c *Console) initConsoleObject() {
  140. c.jsre.Do(func(vm *goja.Runtime) {
  141. console := vm.NewObject()
  142. console.Set("log", c.consoleOutput)
  143. console.Set("error", c.consoleOutput)
  144. vm.Set("console", console)
  145. })
  146. }
  147. func (c *Console) initWeb3(bridge *bridge) error {
  148. bnJS := string(deps.MustAsset("bignumber.js"))
  149. web3JS := string(deps.MustAsset("web3.js"))
  150. if err := c.jsre.Compile("bignumber.js", bnJS); err != nil {
  151. return fmt.Errorf("bignumber.js: %v", err)
  152. }
  153. if err := c.jsre.Compile("web3.js", web3JS); err != nil {
  154. return fmt.Errorf("web3.js: %v", err)
  155. }
  156. if _, err := c.jsre.Run("var Web3 = require('web3');"); err != nil {
  157. return fmt.Errorf("web3 require: %v", err)
  158. }
  159. var err error
  160. c.jsre.Do(func(vm *goja.Runtime) {
  161. transport := vm.NewObject()
  162. transport.Set("send", jsre.MakeCallback(vm, bridge.Send))
  163. transport.Set("sendAsync", jsre.MakeCallback(vm, bridge.Send))
  164. vm.Set("_consoleWeb3Transport", transport)
  165. _, err = vm.RunString("var web3 = new Web3(_consoleWeb3Transport)")
  166. })
  167. return err
  168. }
  169. // initExtensions loads and registers web3.js extensions.
  170. func (c *Console) initExtensions() error {
  171. // Compute aliases from server-provided modules.
  172. apis, err := c.client.SupportedModules()
  173. if err != nil {
  174. return fmt.Errorf("api modules: %v", err)
  175. }
  176. aliases := map[string]struct{}{"eth": {}, "personal": {}}
  177. for api := range apis {
  178. if api == "web3" {
  179. continue
  180. }
  181. aliases[api] = struct{}{}
  182. if file, ok := web3ext.Modules[api]; ok {
  183. if err = c.jsre.Compile(api+".js", file); err != nil {
  184. return fmt.Errorf("%s.js: %v", api, err)
  185. }
  186. }
  187. }
  188. // Apply aliases.
  189. c.jsre.Do(func(vm *goja.Runtime) {
  190. web3 := getObject(vm, "web3")
  191. for name := range aliases {
  192. if v := web3.Get(name); v != nil {
  193. vm.Set(name, v)
  194. }
  195. }
  196. })
  197. return nil
  198. }
  199. // initAdmin creates additional admin APIs implemented by the bridge.
  200. func (c *Console) initAdmin(vm *goja.Runtime, bridge *bridge) {
  201. if admin := getObject(vm, "admin"); admin != nil {
  202. admin.Set("sleepBlocks", jsre.MakeCallback(vm, bridge.SleepBlocks))
  203. admin.Set("sleep", jsre.MakeCallback(vm, bridge.Sleep))
  204. admin.Set("clearHistory", c.clearHistory)
  205. }
  206. }
  207. // initPersonal redirects account-related API methods through the bridge.
  208. //
  209. // If the console is in interactive mode and the 'personal' API is available, override
  210. // the openWallet, unlockAccount, newAccount and sign methods since these require user
  211. // interaction. The original web3 callbacks are stored in 'jeth'. These will be called
  212. // by the bridge after the prompt and send the original web3 request to the backend.
  213. func (c *Console) initPersonal(vm *goja.Runtime, bridge *bridge) {
  214. personal := getObject(vm, "personal")
  215. if personal == nil || c.prompter == nil {
  216. return
  217. }
  218. jeth := vm.NewObject()
  219. vm.Set("jeth", jeth)
  220. jeth.Set("openWallet", personal.Get("openWallet"))
  221. jeth.Set("unlockAccount", personal.Get("unlockAccount"))
  222. jeth.Set("newAccount", personal.Get("newAccount"))
  223. jeth.Set("sign", personal.Get("sign"))
  224. personal.Set("openWallet", jsre.MakeCallback(vm, bridge.OpenWallet))
  225. personal.Set("unlockAccount", jsre.MakeCallback(vm, bridge.UnlockAccount))
  226. personal.Set("newAccount", jsre.MakeCallback(vm, bridge.NewAccount))
  227. personal.Set("sign", jsre.MakeCallback(vm, bridge.Sign))
  228. }
  229. func (c *Console) clearHistory() {
  230. c.history = nil
  231. c.prompter.ClearHistory()
  232. if err := os.Remove(c.histPath); err != nil {
  233. fmt.Fprintln(c.printer, "can't delete history file:", err)
  234. } else {
  235. fmt.Fprintln(c.printer, "history file deleted")
  236. }
  237. }
  238. // consoleOutput is an override for the console.log and console.error methods to
  239. // stream the output into the configured output stream instead of stdout.
  240. func (c *Console) consoleOutput(call goja.FunctionCall) goja.Value {
  241. var output []string
  242. for _, argument := range call.Arguments {
  243. output = append(output, fmt.Sprintf("%v", argument))
  244. }
  245. fmt.Fprintln(c.printer, strings.Join(output, " "))
  246. return goja.Null()
  247. }
  248. // AutoCompleteInput is a pre-assembled word completer to be used by the user
  249. // input prompter to provide hints to the user about the methods available.
  250. func (c *Console) AutoCompleteInput(line string, pos int) (string, []string, string) {
  251. // No completions can be provided for empty inputs
  252. if len(line) == 0 || pos == 0 {
  253. return "", nil, ""
  254. }
  255. // Chunck data to relevant part for autocompletion
  256. // E.g. in case of nested lines eth.getBalance(eth.coinb<tab><tab>
  257. start := pos - 1
  258. for ; start > 0; start-- {
  259. // Skip all methods and namespaces (i.e. including the dot)
  260. if line[start] == '.' || (line[start] >= 'a' && line[start] <= 'z') || (line[start] >= 'A' && line[start] <= 'Z') {
  261. continue
  262. }
  263. // Handle web3 in a special way (i.e. other numbers aren't auto completed)
  264. if start >= 3 && line[start-3:start] == "web3" {
  265. start -= 3
  266. continue
  267. }
  268. // We've hit an unexpected character, autocomplete form here
  269. start++
  270. break
  271. }
  272. return line[:start], c.jsre.CompleteKeywords(line[start:pos]), line[pos:]
  273. }
  274. // Welcome show summary of current Geth instance and some metadata about the
  275. // console's available modules.
  276. func (c *Console) Welcome() {
  277. message := "Welcome to the Geth JavaScript console!\n\n"
  278. // Print some generic Geth metadata
  279. if res, err := c.jsre.Run(`
  280. var message = "instance: " + web3.version.node + "\n";
  281. try {
  282. message += "coinbase: " + eth.coinbase + "\n";
  283. } catch (err) {}
  284. message += "at block: " + eth.blockNumber + " (" + new Date(1000 * eth.getBlock(eth.blockNumber).timestamp) + ")\n";
  285. try {
  286. message += " datadir: " + admin.datadir + "\n";
  287. } catch (err) {}
  288. message
  289. `); err == nil {
  290. message += res.String()
  291. }
  292. // List all the supported modules for the user to call
  293. if apis, err := c.client.SupportedModules(); err == nil {
  294. modules := make([]string, 0, len(apis))
  295. for api, version := range apis {
  296. modules = append(modules, fmt.Sprintf("%s:%s", api, version))
  297. }
  298. sort.Strings(modules)
  299. message += " modules: " + strings.Join(modules, " ") + "\n"
  300. }
  301. message += "\nTo exit, press ctrl-d"
  302. fmt.Fprintln(c.printer, message)
  303. }
  304. // Evaluate executes code and pretty prints the result to the specified output
  305. // stream.
  306. func (c *Console) Evaluate(statement string) {
  307. defer func() {
  308. if r := recover(); r != nil {
  309. fmt.Fprintf(c.printer, "[native] error: %v\n", r)
  310. }
  311. }()
  312. c.jsre.Evaluate(statement, c.printer)
  313. }
  314. // Interactive starts an interactive user session, where input is propted from
  315. // the configured user prompter.
  316. func (c *Console) Interactive() {
  317. var (
  318. prompt = c.prompt // the current prompt line (used for multi-line inputs)
  319. indents = 0 // the current number of input indents (used for multi-line inputs)
  320. input = "" // the current user input
  321. inputLine = make(chan string, 1) // receives user input
  322. inputErr = make(chan error, 1) // receives liner errors
  323. requestLine = make(chan string) // requests a line of input
  324. interrupt = make(chan os.Signal, 1)
  325. )
  326. // Monitor Ctrl-C. While liner does turn on the relevant terminal mode bits to avoid
  327. // the signal, a signal can still be received for unsupported terminals. Unfortunately
  328. // there is no way to cancel the line reader when this happens. The readLines
  329. // goroutine will be leaked in this case.
  330. signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
  331. defer signal.Stop(interrupt)
  332. // The line reader runs in a separate goroutine.
  333. go c.readLines(inputLine, inputErr, requestLine)
  334. defer close(requestLine)
  335. for {
  336. // Send the next prompt, triggering an input read.
  337. requestLine <- prompt
  338. select {
  339. case <-interrupt:
  340. fmt.Fprintln(c.printer, "caught interrupt, exiting")
  341. return
  342. case err := <-inputErr:
  343. if err == liner.ErrPromptAborted {
  344. // When prompting for multi-line input, the first Ctrl-C resets
  345. // the multi-line state.
  346. prompt, indents, input = c.prompt, 0, ""
  347. continue
  348. }
  349. return
  350. case line := <-inputLine:
  351. // User input was returned by the prompter, handle special cases.
  352. if indents <= 0 && exit.MatchString(line) {
  353. return
  354. }
  355. if onlyWhitespace.MatchString(line) {
  356. continue
  357. }
  358. // Append the line to the input and check for multi-line interpretation.
  359. input += line + "\n"
  360. indents = countIndents(input)
  361. if indents <= 0 {
  362. prompt = c.prompt
  363. } else {
  364. prompt = strings.Repeat(".", indents*3) + " "
  365. }
  366. // If all the needed lines are present, save the command and run it.
  367. if indents <= 0 {
  368. if len(input) > 0 && input[0] != ' ' && !passwordRegexp.MatchString(input) {
  369. if command := strings.TrimSpace(input); len(c.history) == 0 || command != c.history[len(c.history)-1] {
  370. c.history = append(c.history, command)
  371. if c.prompter != nil {
  372. c.prompter.AppendHistory(command)
  373. }
  374. }
  375. }
  376. c.Evaluate(input)
  377. input = ""
  378. }
  379. }
  380. }
  381. }
  382. // readLines runs in its own goroutine, prompting for input.
  383. func (c *Console) readLines(input chan<- string, errc chan<- error, prompt <-chan string) {
  384. for p := range prompt {
  385. line, err := c.prompter.PromptInput(p)
  386. if err != nil {
  387. errc <- err
  388. } else {
  389. input <- line
  390. }
  391. }
  392. }
  393. // countIndents returns the number of identations for the given input.
  394. // In case of invalid input such as var a = } the result can be negative.
  395. func countIndents(input string) int {
  396. var (
  397. indents = 0
  398. inString = false
  399. strOpenChar = ' ' // keep track of the string open char to allow var str = "I'm ....";
  400. charEscaped = false // keep track if the previous char was the '\' char, allow var str = "abc\"def";
  401. )
  402. for _, c := range input {
  403. switch c {
  404. case '\\':
  405. // indicate next char as escaped when in string and previous char isn't escaping this backslash
  406. if !charEscaped && inString {
  407. charEscaped = true
  408. }
  409. case '\'', '"':
  410. if inString && !charEscaped && strOpenChar == c { // end string
  411. inString = false
  412. } else if !inString && !charEscaped { // begin string
  413. inString = true
  414. strOpenChar = c
  415. }
  416. charEscaped = false
  417. case '{', '(':
  418. if !inString { // ignore brackets when in string, allow var str = "a{"; without indenting
  419. indents++
  420. }
  421. charEscaped = false
  422. case '}', ')':
  423. if !inString {
  424. indents--
  425. }
  426. charEscaped = false
  427. default:
  428. charEscaped = false
  429. }
  430. }
  431. return indents
  432. }
  433. // Execute runs the JavaScript file specified as the argument.
  434. func (c *Console) Execute(path string) error {
  435. return c.jsre.Exec(path)
  436. }
  437. // Stop cleans up the console and terminates the runtime environment.
  438. func (c *Console) Stop(graceful bool) error {
  439. if err := ioutil.WriteFile(c.histPath, []byte(strings.Join(c.history, "\n")), 0600); err != nil {
  440. return err
  441. }
  442. if err := os.Chmod(c.histPath, 0600); err != nil { // Force 0600, even if it was different previously
  443. return err
  444. }
  445. c.jsre.Stop(graceful)
  446. return nil
  447. }