github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/console/console.go (about)

     1  // Copyright 2016 The go-simplechain Authors
     2  // This file is part of the go-simplechain library.
     3  //
     4  // The go-simplechain 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-simplechain 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-simplechain 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/bigzoro/my_simplechain/internal/jsre"
    32  	"github.com/bigzoro/my_simplechain/internal/web3ext"
    33  	"github.com/bigzoro/my_simplechain/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.newAccountByCA = personal.newAccountByCA;`); err != nil {
   185  				return fmt.Errorf("personal.newAccountByCA: %v", err)
   186  			}
   187  			if _, err = c.jsre.Run(`jeth.sign = personal.sign;`); err != nil {
   188  				return fmt.Errorf("personal.sign: %v", err)
   189  			}
   190  			obj.Set("openWallet", bridge.OpenWallet)
   191  			obj.Set("unlockAccount", bridge.UnlockAccount)
   192  			obj.Set("newAccount", bridge.NewAccount)
   193  			obj.Set("newAccountByCA", bridge.NewAccountByCA)
   194  			obj.Set("sign", bridge.Sign)
   195  		}
   196  	}
   197  	// The admin.sleep and admin.sleepBlocks are offered by the console and not by the RPC layer.
   198  	admin, err := c.jsre.Get("admin")
   199  	if err != nil {
   200  		return err
   201  	}
   202  	if obj := admin.Object(); obj != nil { // make sure the admin api is enabled over the interface
   203  		obj.Set("sleepBlocks", bridge.SleepBlocks)
   204  		obj.Set("sleep", bridge.Sleep)
   205  		obj.Set("clearHistory", c.clearHistory)
   206  	}
   207  	// Preload any JavaScript files before starting the console
   208  	for _, path := range preload {
   209  		if err := c.jsre.Exec(path); err != nil {
   210  			failure := err.Error()
   211  			if ottoErr, ok := err.(*otto.Error); ok {
   212  				failure = ottoErr.String()
   213  			}
   214  			return fmt.Errorf("%s: %v", path, failure)
   215  		}
   216  	}
   217  	// Configure the console's input prompter for scrollback and tab completion
   218  	if c.prompter != nil {
   219  		if content, err := ioutil.ReadFile(c.histPath); err != nil {
   220  			c.prompter.SetHistory(nil)
   221  		} else {
   222  			c.history = strings.Split(string(content), "\n")
   223  			c.prompter.SetHistory(c.history)
   224  		}
   225  		c.prompter.SetWordCompleter(c.AutoCompleteInput)
   226  	}
   227  	return nil
   228  }
   229  
   230  func (c *Console) clearHistory() {
   231  	c.history = nil
   232  	c.prompter.ClearHistory()
   233  	if err := os.Remove(c.histPath); err != nil {
   234  		fmt.Fprintln(c.printer, "can't delete history file:", err)
   235  	} else {
   236  		fmt.Fprintln(c.printer, "history file deleted")
   237  	}
   238  }
   239  
   240  // consoleOutput is an override for the console.log and console.error methods to
   241  // stream the output into the configured output stream instead of stdout.
   242  func (c *Console) consoleOutput(call otto.FunctionCall) otto.Value {
   243  	var output []string
   244  	for _, argument := range call.ArgumentList {
   245  		output = append(output, fmt.Sprintf("%v", argument))
   246  	}
   247  	fmt.Fprintln(c.printer, strings.Join(output, " "))
   248  	return otto.Value{}
   249  }
   250  
   251  // AutoCompleteInput is a pre-assembled word completer to be used by the user
   252  // input prompter to provide hints to the user about the methods available.
   253  func (c *Console) AutoCompleteInput(line string, pos int) (string, []string, string) {
   254  	// No completions can be provided for empty inputs
   255  	if len(line) == 0 || pos == 0 {
   256  		return "", nil, ""
   257  	}
   258  	// Chunck data to relevant part for autocompletion
   259  	// E.g. in case of nested lines eth.getBalance(eth.coinb<tab><tab>
   260  	start := pos - 1
   261  	for ; start > 0; start-- {
   262  		// Skip all methods and namespaces (i.e. including the dot)
   263  		if line[start] == '.' || (line[start] >= 'a' && line[start] <= 'z') || (line[start] >= 'A' && line[start] <= 'Z') {
   264  			continue
   265  		}
   266  		// Handle web3 in a special way (i.e. other numbers aren't auto completed)
   267  		if start >= 3 && line[start-3:start] == "web3" {
   268  			start -= 3
   269  			continue
   270  		}
   271  		// We've hit an unexpected character, autocomplete form here
   272  		start++
   273  		break
   274  	}
   275  	return line[:start], c.jsre.CompleteKeywords(line[start:pos]), line[pos:]
   276  }
   277  
   278  // Welcome show summary of current Geth instance and some metadata about the
   279  // console's available modules.
   280  func (c *Console) Welcome() {
   281  	message := "Welcome to the Sipe JavaScript console!\n\n"
   282  
   283  	// Print some generic Geth metadata
   284  	if res, err := c.jsre.Run(`
   285  		var message = "instance: " + web3.version.node + "\n";
   286  		try {
   287  			message += "coinbase: " + eth.coinbase + "\n";
   288  		} catch (err) {}
   289  		message += "at block: " + eth.blockNumber + " (" + new Date(1000 * eth.getBlock(eth.blockNumber).timestamp) + ")\n";
   290  		try {
   291  			message += " datadir: " + admin.datadir + "\n";
   292  		} catch (err) {}
   293  		message
   294  	`); err == nil {
   295  		message += res.String()
   296  	}
   297  	// List all the supported modules for the user to call
   298  	if apis, err := c.client.SupportedModules(); err == nil {
   299  		modules := make([]string, 0, len(apis))
   300  		for api, version := range apis {
   301  			modules = append(modules, fmt.Sprintf("%s:%s", api, version))
   302  		}
   303  		sort.Strings(modules)
   304  		message += " modules: " + strings.Join(modules, " ") + "\n"
   305  	}
   306  	fmt.Fprintln(c.printer, message)
   307  }
   308  
   309  // Evaluate executes code and pretty prints the result to the specified output
   310  // stream.
   311  func (c *Console) Evaluate(statement string) error {
   312  	defer func() {
   313  		if r := recover(); r != nil {
   314  			fmt.Fprintf(c.printer, "[native] error: %v\n", r)
   315  		}
   316  	}()
   317  	return c.jsre.Evaluate(statement, c.printer)
   318  }
   319  
   320  // Interactive starts an interactive user session, where input is propted from
   321  // the configured user prompter.
   322  func (c *Console) Interactive() {
   323  	var (
   324  		prompt    = c.prompt          // Current prompt line (used for multi-line inputs)
   325  		indents   = 0                 // Current number of input indents (used for multi-line inputs)
   326  		input     = ""                // Current user input
   327  		scheduler = make(chan string) // Channel to send the next prompt on and receive the input
   328  	)
   329  	// Start a goroutine to listen for prompt requests and send back inputs
   330  	go func() {
   331  		for {
   332  			// Read the next user input
   333  			line, err := c.prompter.PromptInput(<-scheduler)
   334  			if err != nil {
   335  				// In case of an error, either clear the prompt or fail
   336  				if err == liner.ErrPromptAborted { // ctrl-C
   337  					prompt, indents, input = c.prompt, 0, ""
   338  					scheduler <- ""
   339  					continue
   340  				}
   341  				close(scheduler)
   342  				return
   343  			}
   344  			// User input retrieved, send for interpretation and loop
   345  			scheduler <- line
   346  		}
   347  	}()
   348  	// Monitor Ctrl-C too in case the input is empty and we need to bail
   349  	abort := make(chan os.Signal, 1)
   350  	signal.Notify(abort, syscall.SIGINT, syscall.SIGTERM)
   351  
   352  	// Start sending prompts to the user and reading back inputs
   353  	for {
   354  		// Send the next prompt, triggering an input read and process the result
   355  		scheduler <- prompt
   356  		select {
   357  		case <-abort:
   358  			// User forcefully quite the console
   359  			fmt.Fprintln(c.printer, "caught interrupt, exiting")
   360  			return
   361  
   362  		case line, ok := <-scheduler:
   363  			// User input was returned by the prompter, handle special cases
   364  			if !ok || (indents <= 0 && exit.MatchString(line)) {
   365  				return
   366  			}
   367  			if onlyWhitespace.MatchString(line) {
   368  				continue
   369  			}
   370  			// Append the line to the input and check for multi-line interpretation
   371  			input += line + "\n"
   372  
   373  			indents = countIndents(input)
   374  			if indents <= 0 {
   375  				prompt = c.prompt
   376  			} else {
   377  				prompt = strings.Repeat(".", indents*3) + " "
   378  			}
   379  			// If all the needed lines are present, save the command and run
   380  			if indents <= 0 {
   381  				if len(input) > 0 && input[0] != ' ' && !passwordRegexp.MatchString(input) {
   382  					if command := strings.TrimSpace(input); len(c.history) == 0 || command != c.history[len(c.history)-1] {
   383  						c.history = append(c.history, command)
   384  						if c.prompter != nil {
   385  							c.prompter.AppendHistory(command)
   386  						}
   387  					}
   388  				}
   389  				c.Evaluate(input)
   390  				input = ""
   391  			}
   392  		}
   393  	}
   394  }
   395  
   396  // countIndents returns the number of identations for the given input.
   397  // In case of invalid input such as var a = } the result can be negative.
   398  func countIndents(input string) int {
   399  	var (
   400  		indents     = 0
   401  		inString    = false
   402  		strOpenChar = ' '   // keep track of the string open char to allow var str = "I'm ....";
   403  		charEscaped = false // keep track if the previous char was the '\' char, allow var str = "abc\"def";
   404  	)
   405  
   406  	for _, c := range input {
   407  		switch c {
   408  		case '\\':
   409  			// indicate next char as escaped when in string and previous char isn't escaping this backslash
   410  			if !charEscaped && inString {
   411  				charEscaped = true
   412  			}
   413  		case '\'', '"':
   414  			if inString && !charEscaped && strOpenChar == c { // end string
   415  				inString = false
   416  			} else if !inString && !charEscaped { // begin string
   417  				inString = true
   418  				strOpenChar = c
   419  			}
   420  			charEscaped = false
   421  		case '{', '(':
   422  			if !inString { // ignore brackets when in string, allow var str = "a{"; without indenting
   423  				indents++
   424  			}
   425  			charEscaped = false
   426  		case '}', ')':
   427  			if !inString {
   428  				indents--
   429  			}
   430  			charEscaped = false
   431  		default:
   432  			charEscaped = false
   433  		}
   434  	}
   435  
   436  	return indents
   437  }
   438  
   439  // Execute runs the JavaScript file specified as the argument.
   440  func (c *Console) Execute(path string) error {
   441  	return c.jsre.Exec(path)
   442  }
   443  
   444  // Stop cleans up the console and terminates the runtime environment.
   445  func (c *Console) Stop(graceful bool) error {
   446  	if err := ioutil.WriteFile(c.histPath, []byte(strings.Join(c.history, "\n")), 0600); err != nil {
   447  		return err
   448  	}
   449  	if err := os.Chmod(c.histPath, 0600); err != nil { // Force 0600, even if it was different previously
   450  		return err
   451  	}
   452  	c.jsre.Stop(graceful)
   453  	return nil
   454  }