console.go 16 KB

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