js.go 6.8 KB
Newer Older
obscuren's avatar
obscuren committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Copyright (c) 2013-2014, Jeffrey Wilcke. All rights reserved.
//
// This library 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 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301  USA
Felix Lange's avatar
Felix Lange committed
17

18 19 20
package main

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

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

41 42 43 44 45 46
type prompter interface {
	AppendHistory(string)
	Prompt(p string) (string, error)
	PasswordPrompt(p string) (string, error)
}

47
type dumbterm struct{ r *bufio.Reader }
48

49
func (r dumbterm) Prompt(p string) (string, error) {
50
	fmt.Print(p)
51 52
	line, err := r.r.ReadString('\n')
	return strings.TrimSuffix(line, "\n"), err
53
}
54

55
func (r dumbterm) PasswordPrompt(p string) (string, error) {
56 57 58 59 60 61 62
	fmt.Println("!! Unsupported terminal, password will echo.")
	fmt.Print(p)
	input, err := bufio.NewReader(os.Stdin).ReadString('\n')
	fmt.Println()
	return input, err
}

63
func (r dumbterm) AppendHistory(string) {}
64 65

type jsre struct {
66 67 68
	re         *re.JSRE
	ethereum   *eth.Ethereum
	xeth       *xeth.XEth
69
	wait       chan *big.Int
70 71 72
	ps1        string
	atexit     func()
	corsDomain string
73
	prompter
74 75
}

Bas van Kervel's avatar
Bas van Kervel committed
76
func newJSRE(ethereum *eth.Ethereum, libPath, corsDomain, ipcpath string, interactive bool, f xeth.Frontend) *jsre {
77
	js := &jsre{ethereum: ethereum, ps1: "> "}
78 79
	// set default cors domain used by startRpc from CLI flag
	js.corsDomain = corsDomain
80 81 82 83 84 85
	if f == nil {
		f = js
	}
	js.xeth = xeth.New(ethereum, f)
	js.wait = js.xeth.UpdateState()
	// update state in separare forever blocks
zelig's avatar
zelig committed
86
	js.re = re.New(libPath)
Bas van Kervel's avatar
Bas van Kervel committed
87
	js.apiBindings(ipcpath, f)
88
	js.adminBindings()
89

90
	if !liner.TerminalSupported() || !interactive {
91
		js.prompter = dumbterm{bufio.NewReader(os.Stdin)}
92 93
	} else {
		lr := liner.NewLiner()
94
		js.withHistory(func(hist *os.File) { lr.ReadHistory(hist) })
95
		lr.SetCtrlCAborts(true)
96
		js.prompter = lr
97 98 99
		js.atexit = func() {
			js.withHistory(func(hist *os.File) { hist.Truncate(0); lr.WriteHistory(hist) })
			lr.Close()
100
			close(js.wait)
101
		}
102
	}
103
	return js
104 105
}

Bas van Kervel's avatar
Bas van Kervel committed
106
func (js *jsre) apiBindings(ipcpath string, f xeth.Frontend) {
107 108
	xe := xeth.New(js.ethereum, f)
	ethApi := rpc.NewEthereumApi(xe)
Bas van Kervel's avatar
Bas van Kervel committed
109
	jeth := rpc.NewJeth(ethApi, js.re, ipcpath)
110

111 112 113
	js.re.Set("jeth", struct{}{})
	t, _ := js.re.Get("jeth")
	jethObj := t.Object()
114

115
	jethObj.Set("send", jeth.Send)
116
	jethObj.Set("sendAsync", jeth.Send)
zelig's avatar
zelig committed
117

118
	err := js.re.Compile("bignumber.js", re.BigNumber_JS)
zelig's avatar
zelig committed
119 120 121 122
	if err != nil {
		utils.Fatalf("Error loading bignumber.js: %v", err)
	}

Bas van Kervel's avatar
Bas van Kervel committed
123
	err = js.re.Compile("ethereum.js", re.Web3_JS)
zelig's avatar
zelig committed
124 125 126 127
	if err != nil {
		utils.Fatalf("Error loading ethereum.js: %v", err)
	}

128
	_, err = js.re.Eval("var web3 = require('web3');")
zelig's avatar
zelig committed
129 130 131 132 133 134 135 136 137
	if err != nil {
		utils.Fatalf("Error requiring web3: %v", err)
	}

	_, err = js.re.Eval("web3.setProvider(jeth)")
	if err != nil {
		utils.Fatalf("Error setting web3 provider: %v", err)
	}
	_, err = js.re.Eval(`
138 139 140 141
var eth = web3.eth;
var shh = web3.shh;
var db  = web3.db;
var net = web3.net;
zelig's avatar
zelig committed
142 143 144 145 146
  `)
	if err != nil {
		utils.Fatalf("Error setting namespaces: %v", err)
	}

147
	js.re.Eval(globalRegistrar + "registrar = GlobalRegistrar.at(\"" + globalRegistrarAddr + "\");")
zelig's avatar
zelig committed
148 149
}

150
var ds, _ = docserver.New("/")
zelig's avatar
zelig committed
151

152
func (self *jsre) ConfirmTransaction(tx string) bool {
153 154 155
	if self.ethereum.NatSpec {
		notice := natspec.GetNotice(self.xeth, tx, ds)
		fmt.Println(notice)
156
		answer, _ := self.Prompt("Confirm Transaction [y/n]")
157 158 159 160
		return strings.HasPrefix(strings.Trim(answer, " "), "y")
	} else {
		return true
	}
161 162
}

163 164
func (self *jsre) UnlockAccount(addr []byte) bool {
	fmt.Printf("Please unlock account %x.\n", addr)
165
	pass, err := self.PasswordPrompt("Passphrase: ")
166
	if err != nil {
167 168 169
		return false
	}
	// TODO: allow retry
170
	if err := self.ethereum.AccountManager().Unlock(common.BytesToAddress(addr), pass); err != nil {
171 172 173 174
		return false
	} else {
		fmt.Println("Account is now unlocked for this session.")
		return true
175 176 177
	}
}

178
func (self *jsre) exec(filename string) error {
zelig's avatar
zelig committed
179
	if err := self.re.Exec(filename); err != nil {
180
		self.re.Stop(false)
181 182
		return fmt.Errorf("Javascript Error: %v", err)
	}
183
	self.re.Stop(true)
184
	return nil
185 186
}

187
func (self *jsre) interactive() {
188 189 190 191 192 193 194 195 196 197 198
	// 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 {
				return
			}
			inputln <- line
199
		}
200 201 202 203 204 205 206 207
	}()
	// Wait for Ctrl-C, too.
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt)

	defer func() {
		if self.atexit != nil {
			self.atexit()
208
		}
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
		self.re.Stop(false)
	}()
	for {
		prompt <- self.ps1
		select {
		case <-sig:
			fmt.Println("caught interrupt, exiting")
			return
		case input, ok := <-inputln:
			if !ok || indentCount <= 0 && input == "exit" {
				return
			}
			if input == "" {
				continue
			}
			str += input + "\n"
			self.setIndent()
			if indentCount <= 0 {
				hist := str[:len(str)-1]
				self.AppendHistory(hist)
				self.parseInput(str)
				str = ""
231 232 233 234 235
			}
		}
	}
}

236
func (self *jsre) withHistory(op func(*os.File)) {
237
	hist, err := os.OpenFile(filepath.Join(self.ethereum.DataDir, "history"), os.O_RDWR|os.O_CREATE, os.ModePerm)
238 239 240 241 242 243 244 245 246 247 248 249
	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)
250 251
		}
	}()
252 253
	value, err := self.re.Run(code)
	if err != nil {
254 255 256 257 258
		if ottoErr, ok := err.(*otto.Error); ok {
			fmt.Println(ottoErr.String())
		} else {
			fmt.Println(err)
		}
259 260 261 262
		return
	}
	self.printValue(value)
}
263

264 265
var indentCount = 0
var str = ""
266

267 268 269 270 271 272 273 274 275 276 277
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 += " "
278 279 280
	}
}

281
func (self *jsre) printValue(v interface{}) {
zelig's avatar
zelig committed
282
	val, err := self.re.PrettyPrint(v)
283
	if err == nil {
zelig's avatar
zelig committed
284
		fmt.Printf("%v", val)
285 286
	}
}