console.go 13 KB

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