console.go 15 KB

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