github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/console/console.go (about)

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