bridge.go 15.3 KB
Newer Older
1
// Copyright 2016 The go-ethereum Authors
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package console

import (
	"encoding/json"
	"fmt"
	"io"
23
	"reflect"
24
	"strings"
25 26
	"time"

27
	"github.com/dop251/goja"
28
	"github.com/ethereum/go-ethereum/accounts/scwallet"
29
	"github.com/ethereum/go-ethereum/accounts/usbwallet"
30
	"github.com/ethereum/go-ethereum/common/hexutil"
31
	"github.com/ethereum/go-ethereum/console/prompt"
32
	"github.com/ethereum/go-ethereum/internal/jsre"
33 34 35 36 37 38
	"github.com/ethereum/go-ethereum/rpc"
)

// bridge is a collection of JavaScript utility methods to bride the .js runtime
// environment and the Go RPC connection backing the remote method calls.
type bridge struct {
39 40 41
	client   *rpc.Client         // RPC client to execute Ethereum requests through
	prompter prompt.UserPrompter // Input prompter to allow interactive user feedback
	printer  io.Writer           // Output writer to serialize any display strings to
42 43 44
}

// newBridge creates a new JavaScript wrapper around an RPC client.
45
func newBridge(client *rpc.Client, prompter prompt.UserPrompter, printer io.Writer) *bridge {
46 47 48 49 50 51 52
	return &bridge{
		client:   client,
		prompter: prompter,
		printer:  printer,
	}
}

53 54 55 56 57 58 59 60
func getJeth(vm *goja.Runtime) *goja.Object {
	jeth := vm.Get("jeth")
	if jeth == nil {
		panic(vm.ToValue("jeth object does not exist"))
	}
	return jeth.ToObject(vm)
}

61
// NewAccount is a wrapper around the personal.newAccount RPC method that uses a
62
// non-echoing password prompt to acquire the passphrase and executes the original
63
// RPC method (saved in jeth.newAccount) with it to actually execute the RPC call.
64
func (b *bridge) NewAccount(call jsre.Call) (goja.Value, error) {
65 66 67 68 69 70 71
	var (
		password string
		confirm  string
		err      error
	)
	switch {
	// No password was specified, prompt the user for it
72 73 74
	case len(call.Arguments) == 0:
		if password, err = b.prompter.PromptPassword("Passphrase: "); err != nil {
			return nil, err
75
		}
76 77
		if confirm, err = b.prompter.PromptPassword("Repeat passphrase: "); err != nil {
			return nil, err
78 79
		}
		if password != confirm {
80
			return nil, fmt.Errorf("passwords don't match!")
81 82
		}
	// A single string password was specified, use that
83 84
	case len(call.Arguments) == 1 && call.Argument(0).ToString() != nil:
		password = call.Argument(0).ToString().String()
85
	default:
86
		return nil, fmt.Errorf("expected 0 or 1 string argument")
87
	}
88
	// Password acquired, execute the call and return
89 90 91 92 93
	newAccount, callable := goja.AssertFunction(getJeth(call.VM).Get("newAccount"))
	if !callable {
		return nil, fmt.Errorf("jeth.newAccount is not callable")
	}
	ret, err := newAccount(goja.Null(), call.VM.ToValue(password))
94
	if err != nil {
95
		return nil, err
96
	}
97
	return ret, nil
98 99
}

100 101
// OpenWallet is a wrapper around personal.openWallet which can interpret and
// react to certain error messages, such as the Trezor PIN matrix request.
102
func (b *bridge) OpenWallet(call jsre.Call) (goja.Value, error) {
103
	// Make sure we have a wallet specified to open
104 105
	if call.Argument(0).ToObject(call.VM).ClassName() != "String" {
		return nil, fmt.Errorf("first argument must be the wallet URL to open")
106 107 108
	}
	wallet := call.Argument(0)

109 110 111
	var passwd goja.Value
	if goja.IsUndefined(call.Argument(1)) || goja.IsNull(call.Argument(1)) {
		passwd = call.VM.ToValue("")
112 113 114 115
	} else {
		passwd = call.Argument(1)
	}
	// Open the wallet and return if successful in itself
116 117 118 119 120
	openWallet, callable := goja.AssertFunction(getJeth(call.VM).Get("openWallet"))
	if !callable {
		return nil, fmt.Errorf("jeth.openWallet is not callable")
	}
	val, err := openWallet(goja.Null(), wallet, passwd)
121
	if err == nil {
122
		return val, nil
123
	}
124 125 126 127

	// Wallet open failed, report error unless it's a PIN or PUK entry
	switch {
	case strings.HasSuffix(err.Error(), usbwallet.ErrTrezorPINNeeded.Error()):
128 129
		val, err = b.readPinAndReopenWallet(call)
		if err == nil {
130
			return val, nil
131
		}
132 133
		val, err = b.readPassphraseAndReopenWallet(call)
		if err != nil {
134
			return nil, err
135 136
		}

137
	case strings.HasSuffix(err.Error(), scwallet.ErrPairingPasswordNeeded.Error()):
138
		// PUK input requested, fetch from the user and call open again
139 140 141
		input, err := b.prompter.PromptPassword("Please enter the pairing password: ")
		if err != nil {
			return nil, err
142
		}
143 144
		passwd = call.VM.ToValue(input)
		if val, err = openWallet(goja.Null(), wallet, passwd); err != nil {
145
			if !strings.HasSuffix(err.Error(), scwallet.ErrPINNeeded.Error()) {
146
				return nil, err
147 148 149 150 151 152 153 154
			}
			// PIN input requested, fetch from the user and call open again
			input, err := b.prompter.PromptPassword("Please enter current PIN: ")
			if err != nil {
				return nil, err
			}
			if val, err = openWallet(goja.Null(), wallet, call.VM.ToValue(input)); err != nil {
				return nil, err
155 156 157
			}
		}

158 159 160
	case strings.HasSuffix(err.Error(), scwallet.ErrPINUnblockNeeded.Error()):
		// PIN unblock requested, fetch PUK and new PIN from the user
		var pukpin string
161 162 163
		input, err := b.prompter.PromptPassword("Please enter current PUK: ")
		if err != nil {
			return nil, err
164
		}
165 166 167 168
		pukpin = input
		input, err = b.prompter.PromptPassword("Please enter new PIN: ")
		if err != nil {
			return nil, err
169
		}
170 171 172 173
		pukpin += input

		if val, err = openWallet(goja.Null(), wallet, call.VM.ToValue(pukpin)); err != nil {
			return nil, err
174 175
		}

176 177
	case strings.HasSuffix(err.Error(), scwallet.ErrPINNeeded.Error()):
		// PIN input requested, fetch from the user and call open again
178 179 180
		input, err := b.prompter.PromptPassword("Please enter current PIN: ")
		if err != nil {
			return nil, err
181
		}
182 183
		if val, err = openWallet(goja.Null(), wallet, call.VM.ToValue(input)); err != nil {
			return nil, err
184 185 186 187
		}

	default:
		// Unknown error occurred, drop to the user
188
		return nil, err
189
	}
190
	return val, nil
191 192
}

193
func (b *bridge) readPassphraseAndReopenWallet(call jsre.Call) (goja.Value, error) {
194
	wallet := call.Argument(0)
195 196 197 198 199 200 201
	input, err := b.prompter.PromptPassword("Please enter your passphrase: ")
	if err != nil {
		return nil, err
	}
	openWallet, callable := goja.AssertFunction(getJeth(call.VM).Get("openWallet"))
	if !callable {
		return nil, fmt.Errorf("jeth.openWallet is not callable")
202
	}
203
	return openWallet(goja.Null(), wallet, call.VM.ToValue(input))
204 205
}

206
func (b *bridge) readPinAndReopenWallet(call jsre.Call) (goja.Value, error) {
207
	wallet := call.Argument(0)
208 209
	// Trezor PIN matrix input requested, display the matrix to the user and fetch the data
	fmt.Fprintf(b.printer, "Look at the device for number positions\n\n")
210
	fmt.Fprintf(b.printer, "7 | 8 | 9\n")
211
	fmt.Fprintf(b.printer, "--+---+--\n")
212
	fmt.Fprintf(b.printer, "4 | 5 | 6\n")
213
	fmt.Fprintf(b.printer, "--+---+--\n")
214
	fmt.Fprintf(b.printer, "1 | 2 | 3\n\n")
215

216 217 218 219 220 221 222
	input, err := b.prompter.PromptPassword("Please enter current PIN: ")
	if err != nil {
		return nil, err
	}
	openWallet, callable := goja.AssertFunction(getJeth(call.VM).Get("openWallet"))
	if !callable {
		return nil, fmt.Errorf("jeth.openWallet is not callable")
223
	}
224
	return openWallet(goja.Null(), wallet, call.VM.ToValue(input))
225 226
}

227
// UnlockAccount is a wrapper around the personal.unlockAccount RPC method that
228
// uses a non-echoing password prompt to acquire the passphrase and executes the
229 230
// original RPC method (saved in jeth.unlockAccount) with it to actually execute
// the RPC call.
231
func (b *bridge) UnlockAccount(call jsre.Call) (goja.Value, error) {
232
	if len(call.Arguments) < 1 {
233 234
		return nil, fmt.Errorf("usage: unlockAccount(account, [ password, duration ])")
	}
235 236

	account := call.Argument(0)
237
	// Make sure we have an account specified to unlock.
238
	if goja.IsUndefined(account) || goja.IsNull(account) || account.ExportType().Kind() != reflect.String {
239
		return nil, fmt.Errorf("first argument must be the account to unlock")
240 241
	}

242 243 244
	// If password is not given or is the null value, prompt the user for it.
	var passwd goja.Value
	if goja.IsUndefined(call.Argument(1)) || goja.IsNull(call.Argument(1)) {
245
		fmt.Fprintf(b.printer, "Unlock account %s\n", account)
246 247 248
		input, err := b.prompter.PromptPassword("Passphrase: ")
		if err != nil {
			return nil, err
249
		}
250
		passwd = call.VM.ToValue(input)
251
	} else {
252 253
		if call.Argument(1).ExportType().Kind() != reflect.String {
			return nil, fmt.Errorf("password must be a string")
254 255 256
		}
		passwd = call.Argument(1)
	}
257 258 259 260 261 262

	// Third argument is the duration how long the account should be unlocked.
	duration := goja.Null()
	if !goja.IsUndefined(call.Argument(2)) && !goja.IsNull(call.Argument(2)) {
		if !isNumber(call.Argument(2)) {
			return nil, fmt.Errorf("unlock duration must be a number")
263 264 265
		}
		duration = call.Argument(2)
	}
266 267 268 269 270

	// Send the request to the backend and return.
	unlockAccount, callable := goja.AssertFunction(getJeth(call.VM).Get("unlockAccount"))
	if !callable {
		return nil, fmt.Errorf("jeth.unlockAccount is not callable")
271
	}
272
	return unlockAccount(goja.Null(), account, passwd, duration)
273 274
}

275
// Sign is a wrapper around the personal.sign RPC method that uses a non-echoing password
276
// prompt to acquire the passphrase and executes the original RPC method (saved in
277
// jeth.sign) with it to actually execute the RPC call.
278
func (b *bridge) Sign(call jsre.Call) (goja.Value, error) {
279 280 281
	if nArgs := len(call.Arguments); nArgs < 2 {
		return nil, fmt.Errorf("usage: sign(message, account, [ password ])")
	}
282 283 284 285 286 287
	var (
		message = call.Argument(0)
		account = call.Argument(1)
		passwd  = call.Argument(2)
	)

288
	if goja.IsUndefined(message) || message.ExportType().Kind() != reflect.String {
289
		return nil, fmt.Errorf("first argument must be the message to sign")
290
	}
291
	if goja.IsUndefined(account) || account.ExportType().Kind() != reflect.String {
292
		return nil, fmt.Errorf("second argument must be the account to sign with")
293 294 295
	}

	// if the password is not given or null ask the user and ensure password is a string
296
	if goja.IsUndefined(passwd) || goja.IsNull(passwd) {
297
		fmt.Fprintf(b.printer, "Give password for account %s\n", account)
298 299 300
		input, err := b.prompter.PromptPassword("Password: ")
		if err != nil {
			return nil, err
301
		}
302 303 304
		passwd = call.VM.ToValue(input)
	} else if passwd.ExportType().Kind() != reflect.String {
		return nil, fmt.Errorf("third argument must be the password to unlock the account")
305 306 307
	}

	// Send the request to the backend and return
308
	sign, callable := goja.AssertFunction(getJeth(call.VM).Get("sign"))
309
	if !callable {
310
		return nil, fmt.Errorf("jeth.sign is not callable")
311
	}
312
	return sign(goja.Null(), message, account, passwd)
313 314
}

315
// Sleep will block the console for the specified number of seconds.
316
func (b *bridge) Sleep(call jsre.Call) (goja.Value, error) {
317 318 319
	if nArgs := len(call.Arguments); nArgs < 1 {
		return nil, fmt.Errorf("usage: sleep(<number of seconds>)")
	}
320 321
	sleepObj := call.Argument(0)
	if goja.IsUndefined(sleepObj) || goja.IsNull(sleepObj) || !isNumber(sleepObj) {
322
		return nil, fmt.Errorf("usage: sleep(<number of seconds>)")
323
	}
324
	sleep := sleepObj.ToFloat()
325 326
	time.Sleep(time.Duration(sleep * float64(time.Second)))
	return call.VM.ToValue(true), nil
327 328 329 330
}

// SleepBlocks will block the console for a specified number of new blocks optionally
// until the given timeout is reached.
331 332
func (b *bridge) SleepBlocks(call jsre.Call) (goja.Value, error) {
	// Parse the input parameters for the sleep.
333 334 335 336
	var (
		blocks = int64(0)
		sleep  = int64(9999999999999999) // indefinitely
	)
337
	nArgs := len(call.Arguments)
338
	if nArgs == 0 {
339
		return nil, fmt.Errorf("usage: sleepBlocks(<n blocks>[, max sleep in seconds])")
340 341
	}
	if nArgs >= 1 {
342
		if goja.IsNull(call.Argument(0)) || goja.IsUndefined(call.Argument(0)) || !isNumber(call.Argument(0)) {
343
			return nil, fmt.Errorf("expected number as first argument")
344
		}
345
		blocks = call.Argument(0).ToInteger()
346 347
	}
	if nArgs >= 2 {
348
		if goja.IsNull(call.Argument(1)) || goja.IsUndefined(call.Argument(1)) || !isNumber(call.Argument(1)) {
349
			return nil, fmt.Errorf("expected number as second argument")
350
		}
351
		sleep = call.Argument(1).ToInteger()
352
	}
353 354

	// Poll the current block number until either it or a timeout is reached.
355 356 357 358 359
	deadline := time.Now().Add(time.Duration(sleep) * time.Second)
	var lastNumber hexutil.Uint64
	if err := b.client.Call(&lastNumber, "eth_blockNumber"); err != nil {
		return nil, err
	}
360 361
	for time.Now().Before(deadline) {
		var number hexutil.Uint64
362
		if err := b.client.Call(&number, "eth_blockNumber"); err != nil {
363
			return nil, err
364
		}
365 366 367
		if number != lastNumber {
			lastNumber = number
			blocks--
368
		}
369 370
		if blocks <= 0 {
			break
371 372 373
		}
		time.Sleep(time.Second)
	}
374
	return call.VM.ToValue(true), nil
375 376
}

377
type jsonrpcCall struct {
378
	ID     int64
379 380 381 382 383
	Method string
	Params []interface{}
}

// Send implements the web3 provider "send" method.
384
func (b *bridge) Send(call jsre.Call) (goja.Value, error) {
385
	// Remarshal the request into a Go value.
386
	reqVal, err := call.Argument(0).ToObject(call.VM).MarshalJSON()
387
	if err != nil {
388
		return nil, err
389
	}
390

391
	var (
392
		rawReq = string(reqVal)
393
		dec    = json.NewDecoder(strings.NewReader(rawReq))
394 395
		reqs   []jsonrpcCall
		batch  bool
396
	)
397
	dec.UseNumber() // avoid float64s
398 399
	if rawReq[0] == '[' {
		batch = true
400
		dec.Decode(&reqs)
401
	} else {
402
		batch = false
403
		reqs = make([]jsonrpcCall, 1)
404
		dec.Decode(&reqs[0])
405 406
	}

407
	// Execute the requests.
408
	var resps []*goja.Object
409
	for _, req := range reqs {
410 411
		resp := call.VM.NewObject()
		resp.Set("jsonrpc", "2.0")
412
		resp.Set("id", req.ID)
413

414
		var result json.RawMessage
415
		if err = b.client.Call(&result, req.Method, req.Params...); err == nil {
416 417 418
			if result == nil {
				// Special case null because it is decoded as an empty
				// raw message for some reason.
419
				resp.Set("result", goja.Null())
420
			} else {
421 422 423 424 425 426
				JSON := call.VM.Get("JSON").ToObject(call.VM)
				parse, callable := goja.AssertFunction(JSON.Get("parse"))
				if !callable {
					return nil, fmt.Errorf("JSON.parse is not a function")
				}
				resultVal, err := parse(goja.Null(), call.VM.ToValue(string(result)))
427
				if err != nil {
428
					setError(resp, -32603, err.Error(), nil)
429 430 431 432
				} else {
					resp.Set("result", resultVal)
				}
			}
433 434 435 436 437 438 439 440 441 442
		} else {
			code := -32603
			var data interface{}
			if err, ok := err.(rpc.Error); ok {
				code = err.ErrorCode()
			}
			if err, ok := err.(rpc.DataError); ok {
				data = err.ErrorData()
			}
			setError(resp, code, err.Error(), data)
443
		}
444
		resps = append(resps, resp)
445 446 447
	}
	// Return the responses either to the callback (if supplied)
	// or directly as the return value.
448
	var result goja.Value
449
	if batch {
450
		result = call.VM.ToValue(resps)
451
	} else {
452
		result = resps[0]
453
	}
454 455 456
	if fn, isFunc := goja.AssertFunction(call.Argument(1)); isFunc {
		fn(goja.Null(), goja.Null(), result)
		return goja.Undefined(), nil
457
	}
458
	return result, nil
459 460
}

461 462 463 464 465 466 467 468
func setError(resp *goja.Object, code int, msg string, data interface{}) {
	err := make(map[string]interface{})
	err["code"] = code
	err["message"] = msg
	if data != nil {
		err["data"] = data
	}
	resp.Set("error", err)
469 470
}

471 472 473 474 475 476 477 478 479 480
// isNumber returns true if input value is a JS number.
func isNumber(v goja.Value) bool {
	k := v.ExportType().Kind()
	return k >= reflect.Int && k <= reflect.Float64
}

func getObject(vm *goja.Runtime, name string) *goja.Object {
	v := vm.Get(name)
	if v == nil {
		return nil
481
	}
482
	return v.ToObject(vm)
483
}