github.com/kapoio/go-kapoio@v1.9.7/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/ethereum/go-ethereum/internal/jsre"
    32  	"github.com/ethereum/go-ethereum/internal/web3ext"
    33  	"github.com/ethereum/go-ethereum/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.BignumberJs); err != nil {
   124  		return fmt.Errorf("bignumber.js: %v", err)
   125  	}
   126  	if err := c.jsre.Compile("web3.js", jsre.Web3Js); 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  	var 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  	message := "Welcome to the Geth JavaScript console!\n\n"
   278  
   279  	// Print some generic Geth metadata
   280  	if res, err := c.jsre.Run(`
   281  		var message = "instance: " + web3.version.node + "\n";
   282  		try {
   283  			message += "coinbase: " + eth.coinbase + "\n";
   284  		} catch (err) {}
   285  		message += "at block: " + eth.blockNumber + " (" + new Date(1000 * eth.getBlock(eth.blockNumber).timestamp) + ")\n";
   286  		try {
   287  			message += " datadir: " + admin.datadir + "\n";
   288  		} catch (err) {}
   289  		message
   290  	`); err == nil {
   291  		message += res.String()
   292  	}
   293  	// List all the supported modules for the user to call
   294  	if apis, err := c.client.SupportedModules(); err == nil {
   295  		modules := make([]string, 0, len(apis))
   296  		for api, version := range apis {
   297  			modules = append(modules, fmt.Sprintf("%s:%s", api, version))
   298  		}
   299  		sort.Strings(modules)
   300  		message += " modules: " + strings.Join(modules, " ") + "\n"
   301  	}
   302  	fmt.Fprintln(c.printer, message)
   303  }
   304  
   305  // Evaluate executes code and pretty prints the result to the specified output
   306  // stream.
   307  func (c *Console) Evaluate(statement string) error {
   308  	defer func() {
   309  		if r := recover(); r != nil {
   310  			fmt.Fprintf(c.printer, "[native] error: %v\n", r)
   311  		}
   312  	}()
   313  	return c.jsre.Evaluate(statement, c.printer)
   314  }
   315  
   316  // Interactive starts an interactive user session, where input is propted from
   317  // the configured user prompter.
   318  func (c *Console) Interactive() {
   319  	var (
   320  		prompt    = c.prompt          // Current prompt line (used for multi-line inputs)
   321  		indents   = 0                 // Current number of input indents (used for multi-line inputs)
   322  		input     = ""                // Current user input
   323  		scheduler = make(chan string) // Channel to send the next prompt on and receive the input
   324  	)
   325  	// Start a goroutine to listen for prompt requests and send back inputs
   326  	go func() {
   327  		for {
   328  			// Read the next user input
   329  			line, err := c.prompter.PromptInput(<-scheduler)
   330  			if err != nil {
   331  				// In case of an error, either clear the prompt or fail
   332  				if err == liner.ErrPromptAborted { // ctrl-C
   333  					prompt, indents, input = c.prompt, 0, ""
   334  					scheduler <- ""
   335  					continue
   336  				}
   337  				close(scheduler)
   338  				return
   339  			}
   340  			// User input retrieved, send for interpretation and loop
   341  			scheduler <- line
   342  		}
   343  	}()
   344  	// Monitor Ctrl-C too in case the input is empty and we need to bail
   345  	abort := make(chan os.Signal, 1)
   346  	signal.Notify(abort, syscall.SIGINT, syscall.SIGTERM)
   347  
   348  	// Start sending prompts to the user and reading back inputs
   349  	for {
   350  		// Send the next prompt, triggering an input read and process the result
   351  		scheduler <- prompt
   352  		select {
   353  		case <-abort:
   354  			// User forcefully quite the console
   355  			fmt.Fprintln(c.printer, "caught interrupt, exiting")
   356  			return
   357  
   358  		case line, ok := <-scheduler:
   359  			// User input was returned by the prompter, handle special cases
   360  			if !ok || (indents <= 0 && exit.MatchString(line)) {
   361  				return
   362  			}
   363  			if onlyWhitespace.MatchString(line) {
   364  				continue
   365  			}
   366  			// Append the line to the input and check for multi-line interpretation
   367  			input += line + "\n"
   368  
   369  			indents = countIndents(input)
   370  			if indents <= 0 {
   371  				prompt = c.prompt
   372  			} else {
   373  				prompt = strings.Repeat(".", indents*3) + " "
   374  			}
   375  			// If all the needed lines are present, save the command and run
   376  			if indents <= 0 {
   377  				if len(input) > 0 && input[0] != ' ' && !passwordRegexp.MatchString(input) {
   378  					if command := strings.TrimSpace(input); len(c.history) == 0 || command != c.history[len(c.history)-1] {
   379  						c.history = append(c.history, command)
   380  						if c.prompter != nil {
   381  							c.prompter.AppendHistory(command)
   382  						}
   383  					}
   384  				}
   385  				c.Evaluate(input)
   386  				input = ""
   387  			}
   388  		}
   389  	}
   390  }
   391  
   392  // countIndents returns the number of identations for the given input.
   393  // In case of invalid input such as var a = } the result can be negative.
   394  func countIndents(input string) int {
   395  	var (
   396  		indents     = 0
   397  		inString    = false
   398  		strOpenChar = ' '   // keep track of the string open char to allow var str = "I'm ....";
   399  		charEscaped = false // keep track if the previous char was the '\' char, allow var str = "abc\"def";
   400  	)
   401  
   402  	for _, c := range input {
   403  		switch c {
   404  		case '\\':
   405  			// indicate next char as escaped when in string and previous char isn't escaping this backslash
   406  			if !charEscaped && inString {
   407  				charEscaped = true
   408  			}
   409  		case '\'', '"':
   410  			if inString && !charEscaped && strOpenChar == c { // end string
   411  				inString = false
   412  			} else if !inString && !charEscaped { // begin string
   413  				inString = true
   414  				strOpenChar = c
   415  			}
   416  			charEscaped = false
   417  		case '{', '(':
   418  			if !inString { // ignore brackets when in string, allow var str = "a{"; without indenting
   419  				indents++
   420  			}
   421  			charEscaped = false
   422  		case '}', ')':
   423  			if !inString {
   424  				indents--
   425  			}
   426  			charEscaped = false
   427  		default:
   428  			charEscaped = false
   429  		}
   430  	}
   431  
   432  	return indents
   433  }
   434  
   435  // Execute runs the JavaScript file specified as the argument.
   436  func (c *Console) Execute(path string) error {
   437  	return c.jsre.Exec(path)
   438  }
   439  
   440  // Stop cleans up the console and terminates the runtime environment.
   441  func (c *Console) Stop(graceful bool) error {
   442  	if err := ioutil.WriteFile(c.histPath, []byte(strings.Join(c.history, "\n")), 0600); err != nil {
   443  		return err
   444  	}
   445  	if err := os.Chmod(c.histPath, 0600); err != nil { // Force 0600, even if it was different previously
   446  		return err
   447  	}
   448  	c.jsre.Stop(graceful)
   449  	return nil
   450  }