js.go 11.8 KB
Newer Older
1 2
// Copyright 2014 The go-ethereum Authors
// This file is part of go-ethereum.
obscuren's avatar
obscuren committed
3
//
4 5 6 7
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
obscuren's avatar
obscuren committed
8
//
9
// go-ethereum is distributed in the hope that it will be useful,
obscuren's avatar
obscuren committed
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
// GNU General Public License for more details.
obscuren's avatar
obscuren committed
13 14
//
// You should have received a copy of the GNU General Public License
15
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
Felix Lange's avatar
Felix Lange committed
16

17 18 19
package main

import (
20
	"bufio"
21
	"fmt"
22
	"math/big"
23
	"os"
24
	"os/signal"
25
	"path/filepath"
26
	"regexp"
27
	"sort"
28
	"strings"
29

zelig's avatar
zelig committed
30
	"github.com/ethereum/go-ethereum/cmd/utils"
31
	"github.com/ethereum/go-ethereum/common"
32
	"github.com/ethereum/go-ethereum/common/registrar"
zelig's avatar
zelig committed
33
	"github.com/ethereum/go-ethereum/eth"
zelig's avatar
zelig committed
34
	re "github.com/ethereum/go-ethereum/jsre"
35
	"github.com/ethereum/go-ethereum/node"
zelig's avatar
zelig committed
36
	"github.com/ethereum/go-ethereum/rpc"
37
	"github.com/peterh/liner"
38
	"github.com/robertkrimen/otto"
39 40
)

zelig's avatar
zelig committed
41 42 43 44 45 46
var (
	passwordRegexp = regexp.MustCompile("personal.[nu]")
	leadingSpace   = regexp.MustCompile("^ ")
	onlyws         = regexp.MustCompile("^\\s*$")
	exit           = regexp.MustCompile("^\\s*exit\\s*;*\\s*$")
)
47

48 49 50 51 52 53
type prompter interface {
	AppendHistory(string)
	Prompt(p string) (string, error)
	PasswordPrompt(p string) (string, error)
}

54
type dumbterm struct{ r *bufio.Reader }
55

56
func (r dumbterm) Prompt(p string) (string, error) {
57
	fmt.Print(p)
58 59
	line, err := r.r.ReadString('\n')
	return strings.TrimSuffix(line, "\n"), err
60
}
61

62
func (r dumbterm) PasswordPrompt(p string) (string, error) {
63 64 65 66 67 68 69
	fmt.Println("!! Unsupported terminal, password will echo.")
	fmt.Print(p)
	input, err := bufio.NewReader(os.Stdin).ReadString('\n')
	fmt.Println()
	return input, err
}

70
func (r dumbterm) AppendHistory(string) {}
71 72

type jsre struct {
73
	re         *re.JSRE
74
	stack      *node.Node
75
	wait       chan *big.Int
76 77 78
	ps1        string
	atexit     func()
	corsDomain string
79
	client     rpc.Client
80
	prompter
81 82
}

83 84
func makeCompleter(re *jsre) liner.WordCompleter {
	return func(line string, pos int) (head string, completions []string, tail string) {
85 86
		if len(line) == 0 || pos == 0 {
			return "", nil, ""
87
		}
88 89 90 91 92 93
		// chuck data to relevant part for autocompletion, e.g. in case of nested lines eth.getBalance(eth.coinb<tab><tab>
		i := 0
		for i = pos - 1; i > 0; i-- {
			if line[i] == '.' || (line[i] >= 'a' && line[i] <= 'z') || (line[i] >= 'A' && line[i] <= 'Z') {
				continue
			}
94
			if i >= 3 && line[i] == '3' && line[i-3] == 'w' && line[i-2] == 'e' && line[i-1] == 'b' {
95 96 97 98
				continue
			}
			i += 1
			break
99
		}
100
		return line[:i], re.re.CompleteKeywords(line[i:pos]), line[pos:]
101
	}
102 103
}

104
func newLightweightJSRE(docRoot string, client rpc.Client, datadir string, interactive bool) *jsre {
105 106 107 108
	js := &jsre{ps1: "> "}
	js.wait = make(chan *big.Int)
	js.client = client

zelig's avatar
zelig committed
109
	js.re = re.New(docRoot)
110
	if err := js.apiBindings(); err != nil {
111 112 113 114 115 116 117
		utils.Fatalf("Unable to initialize console - %v", err)
	}

	if !liner.TerminalSupported() || !interactive {
		js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
	} else {
		lr := liner.NewLiner()
118
		js.withHistory(datadir, func(hist *os.File) { lr.ReadHistory(hist) })
119
		lr.SetCtrlCAborts(true)
120
		lr.SetWordCompleter(makeCompleter(js))
121 122 123
		lr.SetTabCompletionStyle(liner.TabPrints)
		js.prompter = lr
		js.atexit = func() {
124
			js.withHistory(datadir, func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
125 126 127 128 129 130 131
			lr.Close()
			close(js.wait)
		}
	}
	return js
}

132
func newJSRE(stack *node.Node, docRoot, corsDomain string, client rpc.Client, interactive bool) *jsre {
133
	js := &jsre{stack: stack, ps1: "> "}
134 135
	// set default cors domain used by startRpc from CLI flag
	js.corsDomain = corsDomain
136
	js.wait = make(chan *big.Int)
137 138
	js.client = client

zelig's avatar
zelig committed
139
	js.re = re.New(docRoot)
140
	if err := js.apiBindings(); err != nil {
141 142
		utils.Fatalf("Unable to connect - %v", err)
	}
143

144
	if !liner.TerminalSupported() || !interactive {
145
		js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
146 147
	} else {
		lr := liner.NewLiner()
148
		js.withHistory(stack.DataDir(), func(hist *os.File) { lr.ReadHistory(hist) })
149
		lr.SetCtrlCAborts(true)
150
		lr.SetWordCompleter(makeCompleter(js))
151
		lr.SetTabCompletionStyle(liner.TabPrints)
152
		js.prompter = lr
153
		js.atexit = func() {
154
			js.withHistory(stack.DataDir(), func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
155
			lr.Close()
156
			close(js.wait)
157
		}
158
	}
159
	return js
160 161
}

162
func (self *jsre) batch(statement string) {
163
	err := self.re.EvalAndPrettyPrint(statement)
164 165 166 167 168 169 170 171 172 173 174 175

	if err != nil {
		fmt.Printf("error: %v", err)
	}

	if self.atexit != nil {
		self.atexit()
	}

	self.re.Stop(false)
}

176 177
// show summary of current geth instance
func (self *jsre) welcome() {
178
	self.re.Run(`
zelig's avatar
zelig committed
179
    (function () {
180
      console.log('instance: ' + web3.version.node);
zelig's avatar
zelig committed
181 182 183
      console.log("coinbase: " + eth.coinbase);
      var ts = 1000 * eth.getBlock(eth.blockNumber).timestamp;
      console.log("at block: " + eth.blockNumber + " (" + new Date(ts) + ")");
184
      console.log(' datadir: ' + admin.datadir);
zelig's avatar
zelig committed
185 186
    })();
  `)
187 188 189 190
	if modules, err := self.supportedApis(); err == nil {
		loadedModules := make([]string, 0)
		for api, version := range modules {
			loadedModules = append(loadedModules, fmt.Sprintf("%s:%s", api, version))
191
		}
192
		sort.Strings(loadedModules)
193
	}
194
}
195

196 197
func (self *jsre) supportedApis() (map[string]string, error) {
	return self.client.SupportedModules()
198 199
}

200
func (js *jsre) apiBindings() error {
201
	apis, err := js.supportedApis()
202 203 204 205 206 207 208 209 210
	if err != nil {
		return err
	}

	apiNames := make([]string, 0, len(apis))
	for a, _ := range apis {
		apiNames = append(apiNames, a)
	}

211
	jeth := utils.NewJeth(js.re, js.client)
212 213 214 215 216 217 218 219 220 221 222 223
	js.re.Set("jeth", struct{}{})
	t, _ := js.re.Get("jeth")
	jethObj := t.Object()

	jethObj.Set("send", jeth.Send)
	jethObj.Set("sendAsync", jeth.Send)

	err = js.re.Compile("bignumber.js", re.BigNumber_JS)
	if err != nil {
		utils.Fatalf("Error loading bignumber.js: %v", err)
	}

224
	err = js.re.Compile("web3.js", re.Web3_JS)
225 226 227 228
	if err != nil {
		utils.Fatalf("Error loading web3.js: %v", err)
	}

229
	_, err = js.re.Run("var Web3 = require('web3');")
230 231 232 233
	if err != nil {
		utils.Fatalf("Error requiring web3: %v", err)
	}

234
	_, err = js.re.Run("var web3 = new Web3(jeth);")
235 236 237 238 239 240 241
	if err != nil {
		utils.Fatalf("Error setting web3 provider: %v", err)
	}

	// load only supported API's in javascript runtime
	shortcuts := "var eth = web3.eth; "
	for _, apiName := range apiNames {
242 243
		if apiName == "web3" || apiName == "rpc" {
			continue // manually mapped or ignore
244 245
		}

246 247 248 249 250 251
		if jsFile, ok := rpc.WEB3Extensions[apiName]; ok {
			if err = js.re.Compile(fmt.Sprintf("%s.js", apiName), jsFile); err == nil {
				shortcuts += fmt.Sprintf("var %s = web3.%s; ", apiName, apiName)
			} else {
				utils.Fatalf("Error loading %s.js: %v", apiName, err)
			}
252 253 254
		}
	}

255
	_, err = js.re.Run(shortcuts)
256 257 258 259
	if err != nil {
		utils.Fatalf("Error setting namespaces: %v", err)
	}

zelig's avatar
zelig committed
260
	js.re.Run(`var GlobalRegistrar = eth.contract(` + registrar.GlobalRegistrarAbi + `);   registrar = GlobalRegistrar.at("` + registrar.GlobalRegistrarAddr + `");`)
261 262 263 264 265 266 267 268 269 270 271

	// overrule some of the methods that require password as input and ask for it interactively
	p, err := js.re.Get("personal")
	if err != nil {
		fmt.Println("Unable to overrule sensitive methods in personal module")
		return nil
	}

	// Override the unlockAccount and newAccount methods on the personal object since these require user interaction.
	// Assign the jeth.unlockAccount and jeth.newAccount in the jsre the original web3 callbacks. These will be called
	// by the jeth.* methods after they got the password from the user and send the original web3 request to the backend.
272 273 274 275 276 277
	if persObj := p.Object(); persObj != nil { // make sure the personal api is enabled over the interface
		js.re.Run(`jeth.unlockAccount = personal.unlockAccount;`)
		persObj.Set("unlockAccount", jeth.UnlockAccount)
		js.re.Run(`jeth.newAccount = personal.newAccount;`)
		persObj.Set("newAccount", jeth.NewAccount)
	}
278

279 280 281 282 283 284 285 286 287
	// The admin.sleep and admin.sleepBlocks are offered by the console and not by the RPC layer.
	// Bind these if the admin module is available.
	if a, err := js.re.Get("admin"); err == nil {
		if adminObj := a.Object(); adminObj != nil {
			adminObj.Set("sleepBlocks", jeth.SleepBlocks)
			adminObj.Set("sleep", jeth.Sleep)
		}
	}

288 289 290
	return nil
}

zelig's avatar
zelig committed
291 292 293 294 295 296 297 298
func (self *jsre) AskPassword() (string, bool) {
	pass, err := self.PasswordPrompt("Passphrase: ")
	if err != nil {
		return "", false
	}
	return pass, true
}

299
func (self *jsre) ConfirmTransaction(tx string) bool {
300 301
	// Retrieve the Ethereum instance from the node
	var ethereum *eth.Ethereum
302
	if err := self.stack.Service(&ethereum); err != nil {
303 304 305
		return false
	}
	// If natspec is enabled, ask for permission
306 307 308 309 310
	if ethereum.NatSpec && false /* disabled for now */ {
		//		notice := natspec.GetNotice(self.xeth, tx, ethereum.HTTPClient())
		//		fmt.Println(notice)
		//		answer, _ := self.Prompt("Confirm Transaction [y/n]")
		//		return strings.HasPrefix(strings.Trim(answer, " "), "y")
311
	}
312
	return true
313 314
}

315 316
func (self *jsre) UnlockAccount(addr []byte) bool {
	fmt.Printf("Please unlock account %x.\n", addr)
317
	pass, err := self.PasswordPrompt("Passphrase: ")
318
	if err != nil {
319 320 321
		return false
	}
	// TODO: allow retry
322
	var ethereum *eth.Ethereum
323
	if err := self.stack.Service(&ethereum); err != nil {
324 325 326
		return false
	}
	if err := ethereum.AccountManager().Unlock(common.BytesToAddress(addr), pass); err != nil {
327 328 329 330
		return false
	} else {
		fmt.Println("Account is now unlocked for this session.")
		return true
331 332 333
	}
}

334
func (self *jsre) exec(filename string) error {
zelig's avatar
zelig committed
335
	if err := self.re.Exec(filename); err != nil {
336
		self.re.Stop(false)
337 338
		return fmt.Errorf("Javascript Error: %v", err)
	}
339
	self.re.Stop(true)
340
	return nil
341 342
}

343
func (self *jsre) interactive() {
344 345 346 347 348 349 350 351
	// Read input lines.
	prompt := make(chan string)
	inputln := make(chan string)
	go func() {
		defer close(inputln)
		for {
			line, err := self.Prompt(<-prompt)
			if err != nil {
352 353 354 355 356
				if err == liner.ErrPromptAborted { // ctrl-C
					self.resetPrompt()
					inputln <- ""
					continue
				}
357 358 359
				return
			}
			inputln <- line
360
		}
361 362 363 364 365 366 367 368
	}()
	// Wait for Ctrl-C, too.
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt)

	defer func() {
		if self.atexit != nil {
			self.atexit()
369
		}
370 371 372 373 374 375 376 377 378
		self.re.Stop(false)
	}()
	for {
		prompt <- self.ps1
		select {
		case <-sig:
			fmt.Println("caught interrupt, exiting")
			return
		case input, ok := <-inputln:
zelig's avatar
zelig committed
379
			if !ok || indentCount <= 0 && exit.MatchString(input) {
380 381
				return
			}
zelig's avatar
zelig committed
382
			if onlyws.MatchString(input) {
383 384 385 386 387
				continue
			}
			str += input + "\n"
			self.setIndent()
			if indentCount <= 0 {
zelig's avatar
zelig committed
388 389
				if mustLogInHistory(str) {
					self.AppendHistory(str[:len(str)-1])
390
				}
391 392
				self.parseInput(str)
				str = ""
393 394 395 396 397
			}
		}
	}
}

zelig's avatar
zelig committed
398 399 400
func mustLogInHistory(input string) bool {
	return len(input) == 0 ||
		passwordRegexp.MatchString(input) ||
401
		!leadingSpace.MatchString(input)
402 403
}

404
func (self *jsre) withHistory(datadir string, op func(*os.File)) {
405
	hist, err := os.OpenFile(filepath.Join(datadir, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
406 407 408 409 410 411 412 413 414 415 416 417
	if err != nil {
		fmt.Printf("unable to open history file: %v\n", err)
		return
	}
	op(hist)
	hist.Close()
}

func (self *jsre) parseInput(code string) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("[native] error", r)
418 419
		}
	}()
420
	if err := self.re.EvalAndPrettyPrint(code); err != nil {
421 422 423 424 425
		if ottoErr, ok := err.(*otto.Error); ok {
			fmt.Println(ottoErr.String())
		} else {
			fmt.Println(err)
		}
426 427 428
		return
	}
}
429

430 431
var indentCount = 0
var str = ""
432

433 434 435 436 437 438
func (self *jsre) resetPrompt() {
	indentCount = 0
	str = ""
	self.ps1 = "> "
}

439 440 441 442 443 444 445 446 447 448 449
func (self *jsre) setIndent() {
	open := strings.Count(str, "{")
	open += strings.Count(str, "(")
	closed := strings.Count(str, "}")
	closed += strings.Count(str, ")")
	indentCount = open - closed
	if indentCount <= 0 {
		self.ps1 = "> "
	} else {
		self.ps1 = strings.Join(make([]string, indentCount*2), "..")
		self.ps1 += " "
450 451
	}
}