console.go 17 KB

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