main.go 21.4 KB
Newer Older
F
Felix Lange 已提交
1 2 3 4 5 6 7 8 9 10
// Copyright 2014 The go-ethereum Authors
// This file is part of go-ethereum.
//
// 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.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
F
Felix Lange 已提交
12 13 14
// GNU General Public License for more details.
//
// 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/>.
F
Felix Lange 已提交
16

17
// geth is the official command-line client for Ethereum.
18 19 20
package main

import (
O
obscuren 已提交
21
	"fmt"
22
	"io/ioutil"
O
obscuren 已提交
23
	"os"
24
	"path/filepath"
O
obscuren 已提交
25
	"runtime"
26
	"strconv"
27
	"strings"
28
	"time"
O
obscuren 已提交
29

30
	"github.com/codegangsta/cli"
31
	"github.com/ethereum/ethash"
Z
zelig 已提交
32
	"github.com/ethereum/go-ethereum/accounts"
O
obscuren 已提交
33
	"github.com/ethereum/go-ethereum/cmd/utils"
Z
zelig 已提交
34
	"github.com/ethereum/go-ethereum/common"
35
	"github.com/ethereum/go-ethereum/core"
O
obscuren 已提交
36
	"github.com/ethereum/go-ethereum/eth"
37
	"github.com/ethereum/go-ethereum/ethdb"
38
	"github.com/ethereum/go-ethereum/internal/debug"
O
obscuren 已提交
39
	"github.com/ethereum/go-ethereum/logger"
40
	"github.com/ethereum/go-ethereum/logger/glog"
41
	"github.com/ethereum/go-ethereum/metrics"
42
	"github.com/ethereum/go-ethereum/node"
43 44
	"github.com/ethereum/go-ethereum/params"
	"github.com/ethereum/go-ethereum/rlp"
45 46
)

Z
zelig 已提交
47
const (
48
	ClientIdentifier = "Geth"
49
	Version          = "1.4.0-unstable"
50
	VersionMajor     = 1
51
	VersionMinor     = 4
J
Jeffrey Wilcke 已提交
52
	VersionPatch     = 0
Z
zelig 已提交
53 54
)

55
var (
J
Jeffrey Wilcke 已提交
56
	gitCommit       string // set via linker flagg
57 58 59
	nodeNameVersion string
	app             *cli.App
)
60

61
func init() {
62 63 64 65 66 67 68
	if gitCommit == "" {
		nodeNameVersion = Version
	} else {
		nodeNameVersion = Version + "-" + gitCommit[:8]
	}

	app = utils.NewApp(Version, "the go-ethereum command line interface")
69
	app.Action = geth
70 71
	app.HideVersion = true // we have a command to print the version
	app.Commands = []cli.Command{
72 73 74 75 76
		importCommand,
		exportCommand,
		upgradedbCommand,
		removedbCommand,
		dumpCommand,
77
		monitorCommand,
78 79 80 81 82 83 84 85 86
		{
			Action: makedag,
			Name:   "makedag",
			Usage:  "generate ethash dag (for testing)",
			Description: `
The makedag command generates an ethash DAG in /tmp/dag.

This command exists to support the system testing project.
Regular users do not need to execute it.
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
`,
		},
		{
			Action: gpuinfo,
			Name:   "gpuinfo",
			Usage:  "gpuinfo",
			Description: `
Prints OpenCL device info for all found GPUs.
`,
		},
		{
			Action: gpubench,
			Name:   "gpubench",
			Usage:  "benchmark GPU",
			Description: `
Runs quick benchmark on first GPU found.
103 104
`,
		},
105 106 107 108 109 110 111 112
		{
			Action: version,
			Name:   "version",
			Usage:  "print ethereum version numbers",
			Description: `
The output of this command is supposed to be machine-readable.
`,
		},
113
		{
114 115
			Name:  "wallet",
			Usage: "ethereum presale wallet",
116 117 118 119 120 121 122
			Subcommands: []cli.Command{
				{
					Action: importWallet,
					Name:   "import",
					Usage:  "import ethereum presale wallet",
				},
			},
Z
zelig 已提交
123 124 125 126 127 128 129 130 131
			Description: `

    get wallet import /path/to/my/presale.wallet

will prompt for your password and imports your ether presale account.
It can be used non-interactively with the --password option taking a
passwordfile as argument containing the wallet password in plaintext.

`},
F
Felix Lange 已提交
132 133 134 135
		{
			Action: accountList,
			Name:   "account",
			Usage:  "manage accounts",
136 137 138 139 140
			Description: `

Manage accounts lets you create new accounts, list all existing accounts,
import a private key into a new account.

141
'            help' shows a list of subcommands or help for one subcommand.
142

143 144 145 146 147 148 149 150 151 152 153 154
It supports interactive mode, when you are prompted for password as well as
non-interactive mode where passwords are supplied via a given password file.
Non-interactive mode is only meant for scripted use on test networks or known
safe environments.

Make sure you remember the password you gave when creating a new account (with
either new or import). Without it you are not able to unlock your account.

Note that exporting your key in unencrypted format is NOT supported.

Keys are stored under <DATADIR>/keys.
It is safe to transfer the entire directory or the individual keys therein
155
between ethereum nodes by simply copying.
156 157
Make sure you backup your keys regularly.

Z
zelig 已提交
158 159 160 161 162 163
In order to use your account to send transactions, you need to unlock them using
the '--unlock' option. The argument is a space separated list of addresses or
indexes. If used non-interactively with a passwordfile, the file should contain
the respective passwords one per line. If you unlock n accounts and the password
file contains less than n entries, then the last password is meant to apply to
all remaining accounts.
164

165 166
And finally. DO NOT FORGET YOUR PASSWORD.
`,
F
Felix Lange 已提交
167 168 169 170 171 172 173 174 175 176
			Subcommands: []cli.Command{
				{
					Action: accountList,
					Name:   "list",
					Usage:  "print account addresses",
				},
				{
					Action: accountCreate,
					Name:   "new",
					Usage:  "create a new account",
Z
zelig 已提交
177 178 179 180
					Description: `

    ethereum account new

181 182 183 184 185 186
Creates a new account. Prints the address.

The account is saved in encrypted format, you are prompted for a passphrase.

You must remember this passphrase to unlock your account in the future.

Z
zelig 已提交
187 188 189 190
For non-interactive use the passphrase can be specified with the --password flag:

    ethereum --password <passwordfile> account new

191 192
Note, this is meant to be used for testing only, it is a bad idea to save your
password to file or expose in any other way.
Z
zelig 已提交
193 194
					`,
				},
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
				{
					Action: accountUpdate,
					Name:   "update",
					Usage:  "update an existing account",
					Description: `

    ethereum account update <address>

Update an existing account.

The account is saved in the newest version in encrypted format, you are prompted
for a passphrase to unlock the account and another to save the updated file.

This same command can therefore be used to migrate an account of a deprecated
format to the newest format or change the password for an account.

For non-interactive use the passphrase can be specified with the --password flag:

Z
zelig 已提交
213
    ethereum --password <passwordfile> account update <address>
214 215 216 217 218 219 220 221

Since only one password can be given, only format update can be performed,
changing your password is only possible interactively.

Note that account update has the a side effect that the order of your accounts
changes.
					`,
				},
Z
zelig 已提交
222 223 224 225 226 227 228 229
				{
					Action: accountImport,
					Name:   "import",
					Usage:  "import a private key into a new account",
					Description: `

    ethereum account import <keyfile>

230 231 232
Imports an unencrypted private key from <keyfile> and creates a new account.
Prints the address.

233
The keyfile is assumed to contain an unencrypted private key in hexadecimal format.
Z
zelig 已提交
234 235 236

The account is saved in encrypted format, you are prompted for a passphrase.

237
You must remember this passphrase to unlock your account in the future.
Z
zelig 已提交
238

239
For non-interactive use the passphrase can be specified with the -password flag:
Z
zelig 已提交
240

241
    ethereum --password <passwordfile> account import <keyfile>
Z
zelig 已提交
242 243

Note:
Z
zelig 已提交
244
As you can directly copy your encrypted accounts to another ethereum instance,
245
this import mechanism is not needed when you transfer an account between
Z
zelig 已提交
246
nodes.
Z
zelig 已提交
247
					`,
F
Felix Lange 已提交
248 249 250
				},
			},
		},
251 252 253 254 255 256 257 258 259 260
		{
			Action: initGenesis,
			Name:   "init",
			Usage:  "bootstraps and initialises a new genesis block (JSON)",
			Description: `
The init command initialises a new genesis block and definition for the network.
This is a destructive action and changes the network in which you will be
participating.
`,
		},
261
		{
Z
CLI:  
zelig 已提交
262 263
			Action: console,
			Name:   "console",
O
obscuren 已提交
264
			Usage:  `Geth Console: interactive JavaScript environment`,
Z
CLI:  
zelig 已提交
265
			Description: `
O
obscuren 已提交
266
The Geth console is an interactive shell for the JavaScript runtime environment
267 268
which exposes a node admin interface as well as the Ðapp JavaScript API.
See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
269 270
`,
		},
B
Bas van Kervel 已提交
271 272 273
		{
			Action: attach,
			Name:   "attach",
B
Bas van Kervel 已提交
274
			Usage:  `Geth Console: interactive JavaScript environment (connect to node)`,
B
Bas van Kervel 已提交
275
			Description: `
276 277 278 279 280
		The Geth console is an interactive shell for the JavaScript runtime environment
		which exposes a node admin interface as well as the Ðapp JavaScript API.
		See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console.
		This command allows to open a console on a running geth node.
		`,
Z
CLI:  
zelig 已提交
281 282
		},
		{
283
			Action: execScripts,
284
			Name:   "js",
O
obscuren 已提交
285
			Usage:  `executes the given JavaScript files in the Geth JavaScript VM`,
286
			Description: `
287
The JavaScript VM exposes a node admin interface as well as the Ðapp
Z
zelig 已提交
288
JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
289 290 291 292
`,
		},
	}
	app.Flags = []cli.Flag{
293
		utils.IdentityFlag,
294
		utils.UnlockedAccountFlag,
Z
zelig 已提交
295
		utils.PasswordFileFlag,
296
		utils.GenesisFileFlag,
297 298
		utils.BootnodesFlag,
		utils.DataDirFlag,
K
Kobi Gurkan 已提交
299
		utils.KeyStoreDirFlag,
300
		utils.BlockchainVersionFlag,
301
		utils.OlympicFlag,
302
		utils.FastSyncFlag,
303
		utils.CacheFlag,
304
		utils.LightKDFFlag,
Z
CLI:  
zelig 已提交
305
		utils.JSpathFlag,
306 307
		utils.ListenPortFlag,
		utils.MaxPeersFlag,
308
		utils.MaxPendingPeersFlag,
Z
zelig 已提交
309
		utils.EtherbaseFlag,
310
		utils.GasPriceFlag,
311 312
		utils.MinerThreadsFlag,
		utils.MiningEnabledFlag,
313
		utils.MiningGPUFlag,
314
		utils.AutoDAGFlag,
315
		utils.TargetGasLimitFlag,
316
		utils.NATFlag,
317
		utils.NatspecEnabledFlag,
318
		utils.NoDiscoverFlag,
319 320 321 322 323
		utils.NodeKeyFileFlag,
		utils.NodeKeyHexFlag,
		utils.RPCEnabledFlag,
		utils.RPCListenAddrFlag,
		utils.RPCPortFlag,
324 325 326 327 328
		utils.RPCApiFlag,
		utils.WSEnabledFlag,
		utils.WSListenAddrFlag,
		utils.WSPortFlag,
		utils.WSApiFlag,
329
		utils.WSAllowedDomainsFlag,
B
Bas van Kervel 已提交
330 331 332
		utils.IPCDisabledFlag,
		utils.IPCApiFlag,
		utils.IPCPathFlag,
333
		utils.ExecFlag,
334
		utils.PreLoadJSFlag,
335
		utils.WhisperEnabledFlag,
336
		utils.DevModeFlag,
337
		utils.TestNetFlag,
338 339 340
		utils.VMForceJitFlag,
		utils.VMJitCacheFlag,
		utils.VMEnableJitFlag,
Z
zelig 已提交
341
		utils.NetworkIdFlag,
342
		utils.RPCCORSDomainFlag,
343
		utils.MetricsEnabledFlag,
344
		utils.SolcPathFlag,
Z
zsfelfoldi 已提交
345 346 347 348 349 350
		utils.GpoMinGasPriceFlag,
		utils.GpoMaxGasPriceFlag,
		utils.GpoFullBlockRatioFlag,
		utils.GpobaseStepDownFlag,
		utils.GpobaseStepUpFlag,
		utils.GpobaseCorrectionFactorFlag,
Z
zelig 已提交
351
		utils.ExtraDataFlag,
352
	}
353 354
	app.Flags = append(app.Flags, debug.Flags...)

355
	app.Before = func(ctx *cli.Context) error {
356
		runtime.GOMAXPROCS(runtime.NumCPU())
357 358 359 360 361
		if err := debug.Setup(ctx); err != nil {
			return err
		}
		// Start system runtime metrics collection
		go metrics.CollectProcessMetrics(3 * time.Second)
362

363
		utils.SetupNetwork(ctx)
364 365 366 367 368 369

		// Deprecation warning.
		if ctx.GlobalIsSet(utils.GenesisFileFlag.Name) {
			common.PrintDepricationWarning("--genesis is deprecated. Switch to use 'geth init /path/to/file'")
		}

370
		return nil
371
	}
372 373 374 375 376 377

	app.After = func(ctx *cli.Context) error {
		logger.Flush()
		debug.Exit()
		return nil
	}
378
}
O
obscuren 已提交
379

380 381 382 383 384 385
func main() {
	if err := app.Run(os.Args); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Z
zelig 已提交
386

387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
func makeDefaultExtra() []byte {
	var clientInfo = struct {
		Version   uint
		Name      string
		GoVersion string
		Os        string
	}{uint(VersionMajor<<16 | VersionMinor<<8 | VersionPatch), ClientIdentifier, runtime.Version(), runtime.GOOS}
	extra, err := rlp.EncodeToBytes(clientInfo)
	if err != nil {
		glog.V(logger.Warn).Infoln("error setting canonical miner information:", err)
	}

	if uint64(len(extra)) > params.MaximumExtraDataSize.Uint64() {
		glog.V(logger.Warn).Infoln("error setting canonical miner information: extra exceeds", params.MaximumExtraDataSize)
		glog.V(logger.Debug).Infof("extra: %x\n", extra)
		return nil
	}
	return extra
}

407 408 409 410 411 412 413
// geth is the main entry point into the system if no special subcommand is ran.
// It creates a default node based on the command line arguments and runs it in
// blocking mode, waiting for it to be shut down.
func geth(ctx *cli.Context) {
	node := utils.MakeSystemNode(ClientIdentifier, nodeNameVersion, makeDefaultExtra(), ctx)
	startNode(ctx, node)
	node.Wait()
414
}
415

416
// attach will connect to a running geth instance attaching a JavaScript console and to it.
B
Bas van Kervel 已提交
417
func attach(ctx *cli.Context) {
418 419
	// attach to a running geth instance
	client, err := utils.NewRemoteRPCClient(ctx)
B
Bas van Kervel 已提交
420
	if err != nil {
421
		utils.Fatalf("Unable to attach to geth: %v", err)
B
Bas van Kervel 已提交
422 423 424
	}

	repl := newLightweightJSRE(
425
		ctx.GlobalString(utils.JSpathFlag.Name),
B
Bas van Kervel 已提交
426
		client,
B
Bas van Kervel 已提交
427
		ctx.GlobalString(utils.DataDirFlag.Name),
B
Bas van Kervel 已提交
428
		true,
B
Bas van Kervel 已提交
429
	)
B
Bas van Kervel 已提交
430

431 432 433 434 435 436 437
	// preload user defined JS files into the console
	err = repl.preloadJSFiles(ctx)
	if err != nil {
		utils.Fatalf("unable to preload JS file %v", err)
	}

	// in case the exec flag holds a JS statement execute it and return
438 439 440 441 442 443
	if ctx.GlobalString(utils.ExecFlag.Name) != "" {
		repl.batch(ctx.GlobalString(utils.ExecFlag.Name))
	} else {
		repl.welcome()
		repl.interactive()
	}
B
Bas van Kervel 已提交
444 445
}

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
// initGenesis will initialise the given JSON format genesis file and writes it as
// the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
func initGenesis(ctx *cli.Context) {
	genesisPath := ctx.Args().First()
	if len(genesisPath) == 0 {
		utils.Fatalf("must supply path to genesis JSON file")
	}

	chainDb, err := ethdb.NewLDBDatabase(filepath.Join(utils.MustMakeDataDir(ctx), "chaindata"), 0, 0)
	if err != nil {
		utils.Fatalf("could not open database: %v", err)
	}

	genesisFile, err := os.Open(genesisPath)
	if err != nil {
		utils.Fatalf("failed to read genesis file: %v", err)
	}

	block, err := core.WriteGenesisBlock(chainDb, genesisFile)
	if err != nil {
		utils.Fatalf("failed to write genesis block: %v", err)
	}
	glog.V(logger.Info).Infof("successfully wrote genesis block and/or chain rule set: %x", block.Hash())
}

471 472
// console starts a new geth node, attaching a JavaScript console to it at the
// same time.
Z
CLI:  
zelig 已提交
473
func console(ctx *cli.Context) {
474 475 476
	// Create and start the node based on the CLI flags
	node := utils.MakeSystemNode(ClientIdentifier, nodeNameVersion, makeDefaultExtra(), ctx)
	startNode(ctx, node)
477

478
	// Attach to the newly started node, and either execute script or become interactive
479
	client, err := node.Attach()
480 481 482
	if err != nil {
		utils.Fatalf("Failed to attach to the inproc geth: %v", err)
	}
483
	repl := newJSRE(node,
484
		ctx.GlobalString(utils.JSpathFlag.Name),
485
		ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
486
		client, true)
B
Bas van Kervel 已提交
487

488 489 490 491 492 493 494
	// preload user defined JS files into the console
	err = repl.preloadJSFiles(ctx)
	if err != nil {
		utils.Fatalf("unable to preload JS file %v", err)
	}

	// in case the exec flag holds a JS statement execute it and return
495 496
	if script := ctx.GlobalString(utils.ExecFlag.Name); script != "" {
		repl.batch(script)
497 498 499 500
	} else {
		repl.welcome()
		repl.interactive()
	}
501
	node.Stop()
Z
CLI:  
zelig 已提交
502 503
}

504 505 506 507 508 509
// execScripts starts a new geth node based on the CLI flags, and executes each
// of the JavaScript files specified as command arguments.
func execScripts(ctx *cli.Context) {
	// Create and start the node based on the CLI flags
	node := utils.MakeSystemNode(ClientIdentifier, nodeNameVersion, makeDefaultExtra(), ctx)
	startNode(ctx, node)
Z
CLI:  
zelig 已提交
510

511
	// Attach to the newly started node and execute the given scripts
512
	client, err := node.Attach()
513 514 515
	if err != nil {
		utils.Fatalf("Failed to attach to the inproc geth: %v", err)
	}
516
	repl := newJSRE(node,
517
		ctx.GlobalString(utils.JSpathFlag.Name),
518
		ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
519
		client, false)
520

Z
CLI:  
zelig 已提交
521 522 523
	for _, file := range ctx.Args() {
		repl.exec(file)
	}
524
	node.Stop()
525
}
O
obscuren 已提交
526

527
// tries unlocking the specified account a few times.
528
func unlockAccount(ctx *cli.Context, accman *accounts.Manager, address string, i int, passwords []string) (common.Address, string) {
529 530 531 532
	account, err := utils.MakeAddress(accman, address)
	if err != nil {
		utils.Fatalf("Unlock error: %v", err)
	}
533

534 535 536 537 538 539
	for trials := 0; trials < 3; trials++ {
		prompt := fmt.Sprintf("Unlocking account %s | Attempt %d/%d", address, trials+1, 3)
		password := getPassPhrase(prompt, false, i, passwords)
		if err := accman.Unlock(account, password); err == nil {
			return account, password
		}
540
	}
541 542 543
	// All trials expended to unlock account, bail out
	utils.Fatalf("Failed to unlock account: %s", address)
	return common.Address{}, ""
Z
zelig 已提交
544 545
}

546 547 548 549 550 551
// startNode boots up the system node and all registered protocols, after which
// it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
// miner.
func startNode(ctx *cli.Context, stack *node.Node) {
	// Start up the node itself
	utils.StartNode(stack)
552

553 554
	// Unlock any account specifically requested
	var ethereum *eth.Ethereum
555
	if err := stack.Service(&ethereum); err != nil {
556
		utils.Fatalf("ethereum service not running: %v", err)
557
	}
558 559
	accman := ethereum.AccountManager()
	passwords := utils.MakePasswordList(ctx)
Z
zelig 已提交
560

561
	accounts := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
562
	for i, account := range accounts {
563 564
		if trimmed := strings.TrimSpace(account); trimmed != "" {
			unlockAccount(ctx, accman, trimmed, i, passwords)
Z
zelig 已提交
565
		}
Z
zelig 已提交
566
	}
567
	// Start auxiliary services if enabled
568
	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
569 570
		if err := ethereum.StartMining(ctx.GlobalInt(utils.MinerThreadsFlag.Name), ctx.GlobalString(utils.MiningGPUFlag.Name)); err != nil {
			utils.Fatalf("Failed to start mining: %v", err)
571
		}
572 573
	}
}
O
Merge  
obscuren 已提交
574

F
Felix Lange 已提交
575
func accountList(ctx *cli.Context) {
576 577
	accman := utils.MakeAccountManager(ctx)
	accts, err := accman.Accounts()
F
Felix Lange 已提交
578 579 580
	if err != nil {
		utils.Fatalf("Could not list accounts: %v", err)
	}
581
	for i, acct := range accts {
Z
zelig 已提交
582
		fmt.Printf("Account #%d: %x\n", i, acct)
F
Felix Lange 已提交
583 584 585
	}
}

586 587 588 589 590 591 592
// getPassPhrase retrieves the passwor associated with an account, either fetched
// from a list of preloaded passphrases, or requested interactively from the user.
func getPassPhrase(prompt string, confirmation bool, i int, passwords []string) string {
	// If a list of passwords was supplied, retrieve from them
	if len(passwords) > 0 {
		if i < len(passwords) {
			return passwords[i]
593
		}
594 595 596 597 598 599 600 601 602 603 604 605
		return passwords[len(passwords)-1]
	}
	// Otherwise prompt the user for the password
	fmt.Println(prompt)
	password, err := utils.PromptPassword("Passphrase: ", true)
	if err != nil {
		utils.Fatalf("Failed to read passphrase: %v", err)
	}
	if confirmation {
		confirm, err := utils.PromptPassword("Repeat passphrase: ", false)
		if err != nil {
			utils.Fatalf("Failed to read passphrase confirmation: %v", err)
606
		}
607 608
		if password != confirm {
			utils.Fatalf("Passphrases do not match")
609
		}
F
Felix Lange 已提交
610
	}
611
	return password
Z
zelig 已提交
612 613
}

614
// accountCreate creates a new account into the keystore defined by the CLI flags.
Z
zelig 已提交
615
func accountCreate(ctx *cli.Context) {
616 617 618 619
	accman := utils.MakeAccountManager(ctx)
	password := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))

	account, err := accman.NewAccount(password)
F
Felix Lange 已提交
620
	if err != nil {
621
		utils.Fatalf("Failed to create account: %v", err)
F
Felix Lange 已提交
622
	}
623
	fmt.Printf("Address: %x\n", account)
Z
zelig 已提交
624 625
}

626 627
// accountUpdate transitions an account from a previous format to the current
// one, also providing the possibility to change the pass-phrase.
628
func accountUpdate(ctx *cli.Context) {
629 630
	if len(ctx.Args()) == 0 {
		utils.Fatalf("No accounts specified to update")
631
	}
632
	accman := utils.MakeAccountManager(ctx)
633

634 635 636
	account, oldPassword := unlockAccount(ctx, accman, ctx.Args().First(), 0, nil)
	newPassword := getPassPhrase("Please give a new password. Do not forget this password.", true, 0, nil)
	if err := accman.Update(account, oldPassword, newPassword); err != nil {
637 638 639 640
		utils.Fatalf("Could not update the account: %v", err)
	}
}

641 642 643 644 645 646 647 648 649 650
func importWallet(ctx *cli.Context) {
	keyfile := ctx.Args().First()
	if len(keyfile) == 0 {
		utils.Fatalf("keyfile must be given as argument")
	}
	keyJson, err := ioutil.ReadFile(keyfile)
	if err != nil {
		utils.Fatalf("Could not read wallet file: %v", err)
	}

651 652
	accman := utils.MakeAccountManager(ctx)
	passphrase := getPassPhrase("", false, 0, utils.MakePasswordList(ctx))
653

654
	acct, err := accman.ImportPreSaleKey(keyJson, passphrase)
655 656 657 658 659 660
	if err != nil {
		utils.Fatalf("Could not create the account: %v", err)
	}
	fmt.Printf("Address: %x\n", acct)
}

Z
zelig 已提交
661 662 663 664 665
func accountImport(ctx *cli.Context) {
	keyfile := ctx.Args().First()
	if len(keyfile) == 0 {
		utils.Fatalf("keyfile must be given as argument")
	}
666 667 668
	accman := utils.MakeAccountManager(ctx)
	passphrase := getPassPhrase("Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0, utils.MakePasswordList(ctx))
	acct, err := accman.Import(keyfile, passphrase)
Z
zelig 已提交
669 670 671 672 673 674
	if err != nil {
		utils.Fatalf("Could not create the account: %v", err)
	}
	fmt.Printf("Address: %x\n", acct)
}

675
func makedag(ctx *cli.Context) {
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
	args := ctx.Args()
	wrongArgs := func() {
		utils.Fatalf(`Usage: geth makedag <block number> <outputdir>`)
	}
	switch {
	case len(args) == 2:
		blockNum, err := strconv.ParseUint(args[0], 0, 64)
		dir := args[1]
		if err != nil {
			wrongArgs()
		} else {
			dir = filepath.Clean(dir)
			// seems to require a trailing slash
			if !strings.HasSuffix(dir, "/") {
				dir = dir + "/"
			}
			_, err = ioutil.ReadDir(dir)
			if err != nil {
				utils.Fatalf("Can't find dir")
			}
			fmt.Println("making DAG, this could take awhile...")
			ethash.MakeDAG(blockNum, dir)
		}
	default:
		wrongArgs()
	}
702 703
}

704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
func gpuinfo(ctx *cli.Context) {
	eth.PrintOpenCLDevices()
}

func gpubench(ctx *cli.Context) {
	args := ctx.Args()
	wrongArgs := func() {
		utils.Fatalf(`Usage: geth gpubench <gpu number>`)
	}
	switch {
	case len(args) == 1:
		n, err := strconv.ParseUint(args[0], 0, 64)
		if err != nil {
			wrongArgs()
		}
		eth.GPUBench(n)
	case len(args) == 0:
		eth.GPUBench(0)
	default:
		wrongArgs()
	}
}

727
func version(c *cli.Context) {
728 729 730 731 732
	fmt.Println(ClientIdentifier)
	fmt.Println("Version:", Version)
	if gitCommit != "" {
		fmt.Println("Git Commit:", gitCommit)
	}
733
	fmt.Println("Protocol Versions:", eth.ProtocolVersions)
734 735 736 737 738
	fmt.Println("Network Id:", c.GlobalInt(utils.NetworkIdFlag.Name))
	fmt.Println("Go Version:", runtime.Version())
	fmt.Println("OS:", runtime.GOOS)
	fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
	fmt.Printf("GOROOT=%s\n", runtime.GOROOT())
O
obscuren 已提交
739
}