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