github.com/luckypickle/go-ethereum-vet@v1.14.2/console/console.go (about)

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