github.com/n1ghtfa1l/go-vnt@v0.6.4-alpha.6/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 colorable "github.com/mattn/go-colorable" 32 "github.com/peterh/liner" 33 "github.com/robertkrimen/otto" 34 "github.com/vntchain/go-vnt/internal/jsre" 35 "github.com/vntchain/go-vnt/internal/vntjsext" 36 "github.com/vntchain/go-vnt/rpc" 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 VNT 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 fleged 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 VNT 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("jvnt", struct{}{}) 113 114 jvntObj, _ := c.jsre.Get("jvnt") 115 jvntObj.Object().Set("send", bridge.Send) 116 jvntObj.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.BigNumber_JS); err != nil { 124 return fmt.Errorf("bignumber.js: %v", err) 125 } 126 if err := c.jsre.Compile("vnt.js", jsre.VNT_JS); err != nil { 127 return fmt.Errorf("vnt.js: %v", err) 128 } 129 if _, err := c.jsre.Run("var Vnt = require('vnt');"); err != nil { 130 return fmt.Errorf("vnt require: %v", err) 131 } 132 if _, err := c.jsre.Run("var vnt = new Vnt(jvnt);"); err != nil { 133 return fmt.Errorf("vnt 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 core = vnt.core; var personal = vnt.personal; " 141 for api := range apis { 142 if api == "vnt" { 143 continue // manually mapped or ignore 144 } 145 if file, ok := vntjsext.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 = vnt.%s; ", api, api) 151 } else if obj, err := c.jsre.Run("vnt." + api); err == nil && obj.IsObject() { 152 // Enable vnt.js built-in extension if available. 153 flatten += fmt.Sprintf("var %s = vnt.%s; ", api, api) 154 } 155 } 156 if _, err = c.jsre.Run(flatten); err != nil { 157 return fmt.Errorf("namespace flattening: %v", err) 158 } 159 160 // Initialize the global name register (disabled for now) 161 //c.jsre.Run(`var GlobalRegistrar = vnt.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 unlockAccount, newAccount and sign methods since 171 // these require user interaction. Assign these method in the Console the 172 // original vnt callbacks. These will be called by the jvnt.* methods after 173 // they got the password from the user and send the original vnt 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(`jvnt.unlockAccount = personal.unlockAccount;`); err != nil { 177 return fmt.Errorf("personal.unlockAccount: %v", err) 178 } 179 if _, err = c.jsre.Run(`jvnt.newAccount = personal.newAccount;`); err != nil { 180 return fmt.Errorf("personal.newAccount: %v", err) 181 } 182 if _, err = c.jsre.Run(`jvnt.sign = personal.sign;`); err != nil { 183 return fmt.Errorf("personal.sign: %v", err) 184 } 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 core.getBalance(core.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 vnt in a special way (i.e. other numbers aren't auto completed) 260 if start >= 3 && line[start-3:start] == "vnt" { 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 Gvnt instance and some metadata about the 272 // console's available modules. 273 func (c *Console) Welcome() { 274 // Print some generic Gvnt metadata 275 fmt.Fprintf(c.printer, "Welcome to the Gvnt JavaScript console!\n\n") 276 c.jsre.Run(` 277 console.log("instance: " + vnt.version.node); 278 console.log("coinbase: " + core.coinbase); 279 console.log("at block: " + core.blockNumber + " (" + new Date(1000 * core.getBlock(core.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 285 modules := make([]string, 0, len(apis)) 286 for api, version := range apis { 287 modules = append(modules, fmt.Sprintf("%s:%s", api, version)) 288 } 289 sort.Strings(modules) 290 fmt.Fprintln(c.printer, " modules:", strings.Join(modules, " ")) 291 } 292 fmt.Fprintln(c.printer) 293 } 294 295 // Evaluate executes code and pretty prints the result to the specified output 296 // stream. 297 func (c *Console) Evaluate(statement string) error { 298 defer func() { 299 if r := recover(); r != nil { 300 fmt.Fprintf(c.printer, "[native] error: %v\n", r) 301 } 302 }() 303 return c.jsre.Evaluate(statement, c.printer) 304 } 305 306 // Interactive starts an interactive user session, where input is propted from 307 // the configured user prompter. 308 func (c *Console) Interactive() { 309 var ( 310 prompt = c.prompt // Current prompt line (used for multi-line inputs) 311 indents = 0 // Current number of input indents (used for multi-line inputs) 312 input = "" // Current user input 313 scheduler = make(chan string) // Channel to send the next prompt on and receive the input 314 ) 315 // Start a goroutine to listen for promt requests and send back inputs 316 go func() { 317 for { 318 // Read the next user input 319 line, err := c.prompter.PromptInput(<-scheduler) 320 if err != nil { 321 // In case of an error, either clear the prompt or fail 322 if err == liner.ErrPromptAborted { // ctrl-C 323 prompt, indents, input = c.prompt, 0, "" 324 scheduler <- "" 325 continue 326 } 327 close(scheduler) 328 return 329 } 330 // User input retrieved, send for interpretation and loop 331 scheduler <- line 332 } 333 }() 334 // Monitor Ctrl-C too in case the input is empty and we need to bail 335 abort := make(chan os.Signal, 1) 336 signal.Notify(abort, syscall.SIGINT, syscall.SIGTERM) 337 338 // Start sending prompts to the user and reading back inputs 339 for { 340 // Send the next prompt, triggering an input read and process the result 341 scheduler <- prompt 342 select { 343 case <-abort: 344 // User forcefully quite the console 345 fmt.Fprintln(c.printer, "caught interrupt, exiting") 346 return 347 348 case line, ok := <-scheduler: 349 // User input was returned by the prompter, handle special cases 350 if !ok || (indents <= 0 && exit.MatchString(line)) { 351 return 352 } 353 if onlyWhitespace.MatchString(line) { 354 continue 355 } 356 // Append the line to the input and check for multi-line interpretation 357 input += line + "\n" 358 359 indents = countIndents(input) 360 if indents <= 0 { 361 prompt = c.prompt 362 } else { 363 prompt = strings.Repeat(".", indents*3) + " " 364 } 365 // If all the needed lines are present, save the command and run 366 if indents <= 0 { 367 if len(input) > 0 && input[0] != ' ' && !passwordRegexp.MatchString(input) { 368 if command := strings.TrimSpace(input); len(c.history) == 0 || command != c.history[len(c.history)-1] { 369 c.history = append(c.history, command) 370 if c.prompter != nil { 371 c.prompter.AppendHistory(command) 372 } 373 } 374 } 375 c.Evaluate(input) 376 input = "" 377 } 378 } 379 } 380 } 381 382 // countIndents returns the number of identations for the given input. 383 // In case of invalid input such as var a = } the result can be negative. 384 func countIndents(input string) int { 385 var ( 386 indents = 0 387 inString = false 388 strOpenChar = ' ' // keep track of the string open char to allow var str = "I'm ...."; 389 charEscaped = false // keep track if the previous char was the '\' char, allow var str = "abc\"def"; 390 ) 391 392 for _, c := range input { 393 switch c { 394 case '\\': 395 // indicate next char as escaped when in string and previous char isn't escaping this backslash 396 if !charEscaped && inString { 397 charEscaped = true 398 } 399 case '\'', '"': 400 if inString && !charEscaped && strOpenChar == c { // end string 401 inString = false 402 } else if !inString && !charEscaped { // begin string 403 inString = true 404 strOpenChar = c 405 } 406 charEscaped = false 407 case '{', '(': 408 if !inString { // ignore brackets when in string, allow var str = "a{"; without indenting 409 indents++ 410 } 411 charEscaped = false 412 case '}', ')': 413 if !inString { 414 indents-- 415 } 416 charEscaped = false 417 default: 418 charEscaped = false 419 } 420 } 421 422 return indents 423 } 424 425 // Execute runs the JavaScript file specified as the argument. 426 func (c *Console) Execute(path string) error { 427 return c.jsre.Exec(path) 428 } 429 430 // Stop cleans up the console and terminates the runtime environment. 431 func (c *Console) Stop(graceful bool) error { 432 if err := ioutil.WriteFile(c.histPath, []byte(strings.Join(c.history, "\n")), 0600); err != nil { 433 return err 434 } 435 if err := os.Chmod(c.histPath, 0600); err != nil { // Force 0600, even if it was different previously 436 return err 437 } 438 c.jsre.Stop(graceful) 439 return nil 440 }