console.go 15 KB

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