github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/console/console.go (about)

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