console.go 15 KB

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