main.go 20.5 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"
23
	_ "net/http/pprof"
O
obscuren 已提交
24
	"os"
25
	"path/filepath"
O
obscuren 已提交
26
	"runtime"
27
	"strconv"
28
	"strings"
29
	"time"
O
obscuren 已提交
30

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

Z
zelig 已提交
49
const (
50
	ClientIdentifier = "Geth"
J
Jeffrey Wilcke 已提交
51
	Version          = "1.1.0"
52
	VersionMajor     = 1
J
Jeffrey Wilcke 已提交
53 54
	VersionMinor     = 1
	VersionPatch     = 0
Z
zelig 已提交
55 56
)

57
var (
J
Jeffrey Wilcke 已提交
58
	gitCommit       string // set via linker flagg
59 60
	nodeNameVersion string
	app             *cli.App
K
Kobi Gurkan 已提交
61 62 63 64 65

	ExtraDataFlag = cli.StringFlag{
		Name:  "extradata",
		Usage: "Extra data for the miner",
	}
66
)
67

68
func init() {
69 70 71 72 73 74 75
	if gitCommit == "" {
		nodeNameVersion = Version
	} else {
		nodeNameVersion = Version + "-" + gitCommit[:8]
	}

	app = utils.NewApp(Version, "the go-ethereum command line interface")
76 77 78
	app.Action = run
	app.HideVersion = true // we have a command to print the version
	app.Commands = []cli.Command{
79 80 81
		{
			Action: blockRecovery,
			Name:   "recover",
82
			Usage:  "attempts to recover a corrupted database by setting a new block by number or hash. See help recover.",
83 84 85
			Description: `
The recover commands will attempt to read out the last
block based on that.
86 87 88

recover #number recovers by number
recover <hex> recovers by hash
89 90
`,
		},
91 92 93 94 95 96
		blocktestCommand,
		importCommand,
		exportCommand,
		upgradedbCommand,
		removedbCommand,
		dumpCommand,
97
		monitorCommand,
98 99 100 101 102 103 104 105 106 107 108
		{
			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.
`,
		},
109 110 111 112 113 114 115 116
		{
			Action: version,
			Name:   "version",
			Usage:  "print ethereum version numbers",
			Description: `
The output of this command is supposed to be machine-readable.
`,
		},
117 118

		{
119 120
			Name:  "wallet",
			Usage: "ethereum presale wallet",
121 122 123 124 125 126 127
			Subcommands: []cli.Command{
				{
					Action: importWallet,
					Name:   "import",
					Usage:  "import ethereum presale wallet",
				},
			},
Z
zelig 已提交
128 129 130 131 132 133 134 135 136
			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 已提交
137 138 139 140
		{
			Action: accountList,
			Name:   "account",
			Usage:  "manage accounts",
141 142 143 144 145
			Description: `

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

146
'            help' shows a list of subcommands or help for one subcommand.
147

148 149 150 151 152 153 154 155 156 157 158 159
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
160
between ethereum nodes by simply copying.
161 162
Make sure you backup your keys regularly.

163 164 165
In order to use your account to send transactions, you need to unlock them using the
'--unlock' option. The argument is a comma

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

    ethereum account new

182 183 184 185 186 187
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 已提交
188 189 190 191
For non-interactive use the passphrase can be specified with the --password flag:

    ethereum --password <passwordfile> account new

192 193
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 已提交
194 195
					`,
				},
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
				{
					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:

    ethereum --password <passwordfile> account new

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 已提交
223 224 225 226 227 228 229 230
				{
					Action: accountImport,
					Name:   "import",
					Usage:  "import a private key into a new account",
					Description: `

    ethereum account import <keyfile>

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

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

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

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

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

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

Note:
Z
zelig 已提交
245
As you can directly copy your encrypted accounts to another ethereum instance,
246
this import mechanism is not needed when you transfer an account between
Z
zelig 已提交
247
nodes.
Z
zelig 已提交
248
					`,
F
Felix Lange 已提交
249 250 251
				},
			},
		},
252
		{
Z
CLI:  
zelig 已提交
253 254
			Action: console,
			Name:   "console",
O
obscuren 已提交
255
			Usage:  `Geth Console: interactive JavaScript environment`,
Z
CLI:  
zelig 已提交
256
			Description: `
O
obscuren 已提交
257
The Geth console is an interactive shell for the JavaScript runtime environment
258 259
which exposes a node admin interface as well as the Ðapp JavaScript API.
See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
B
Bas van Kervel 已提交
260 261 262 263
`},
		{
			Action: attach,
			Name:   "attach",
B
Bas van Kervel 已提交
264
			Usage:  `Geth Console: interactive JavaScript environment (connect to node)`,
B
Bas van Kervel 已提交
265 266 267 268 269
			Description: `
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 已提交
270 271 272 273
`,
		},
		{
			Action: execJSFiles,
274
			Name:   "js",
O
obscuren 已提交
275
			Usage:  `executes the given JavaScript files in the Geth JavaScript VM`,
276
			Description: `
277
The JavaScript VM exposes a node admin interface as well as the Ðapp
Z
zelig 已提交
278
JavaScript API. See https://github.com/ethereum/go-ethereum/wiki/Javascipt-Console
279 280 281 282
`,
		},
	}
	app.Flags = []cli.Flag{
283
		utils.IdentityFlag,
284
		utils.UnlockedAccountFlag,
Z
zelig 已提交
285
		utils.PasswordFileFlag,
286
		utils.GenesisFileFlag,
287 288
		utils.BootnodesFlag,
		utils.DataDirFlag,
289
		utils.BlockchainVersionFlag,
290
		utils.OlympicFlag,
291
		utils.EthVersionFlag,
292
		utils.CacheFlag,
Z
CLI:  
zelig 已提交
293
		utils.JSpathFlag,
294 295
		utils.ListenPortFlag,
		utils.MaxPeersFlag,
296
		utils.MaxPendingPeersFlag,
Z
zelig 已提交
297
		utils.EtherbaseFlag,
298
		utils.GasPriceFlag,
299 300
		utils.MinerThreadsFlag,
		utils.MiningEnabledFlag,
301
		utils.AutoDAGFlag,
302
		utils.NATFlag,
303
		utils.NatspecEnabledFlag,
304
		utils.NoDiscoverFlag,
305 306 307 308 309
		utils.NodeKeyFileFlag,
		utils.NodeKeyHexFlag,
		utils.RPCEnabledFlag,
		utils.RPCListenAddrFlag,
		utils.RPCPortFlag,
310
		utils.RpcApiFlag,
B
Bas van Kervel 已提交
311 312 313
		utils.IPCDisabledFlag,
		utils.IPCApiFlag,
		utils.IPCPathFlag,
314
		utils.ExecFlag,
315
		utils.WhisperEnabledFlag,
316
		utils.DevModeFlag,
317
		utils.VMDebugFlag,
318 319 320
		utils.VMForceJitFlag,
		utils.VMJitCacheFlag,
		utils.VMEnableJitFlag,
Z
zelig 已提交
321
		utils.NetworkIdFlag,
322
		utils.RPCCORSDomainFlag,
323
		utils.VerbosityFlag,
O
obscuren 已提交
324 325
		utils.BacktraceAtFlag,
		utils.LogToStdErrFlag,
O
obscuren 已提交
326 327 328
		utils.LogVModuleFlag,
		utils.LogFileFlag,
		utils.LogJSONFlag,
329
		utils.PProfEanbledFlag,
330
		utils.PProfPortFlag,
331
		utils.MetricsEnabledFlag,
332
		utils.SolcPathFlag,
Z
zsfelfoldi 已提交
333 334 335 336 337 338
		utils.GpoMinGasPriceFlag,
		utils.GpoMaxGasPriceFlag,
		utils.GpoFullBlockRatioFlag,
		utils.GpobaseStepDownFlag,
		utils.GpobaseStepUpFlag,
		utils.GpobaseCorrectionFactorFlag,
K
Kobi Gurkan 已提交
339
		ExtraDataFlag,
340
	}
341
	app.Before = func(ctx *cli.Context) error {
342
		utils.SetupLogger(ctx)
343
		utils.SetupVM(ctx)
344
		utils.SetupEth(ctx)
345
		if ctx.GlobalBool(utils.PProfEanbledFlag.Name) {
346 347 348
			utils.StartPProf(ctx)
		}
		return nil
349
	}
350
	// Start system runtime metrics collection
351
	go metrics.CollectProcessMetrics(3 * time.Second)
352
}
O
obscuren 已提交
353

354 355 356 357 358 359 360 361
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	defer logger.Flush()
	if err := app.Run(os.Args); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Z
zelig 已提交
362

K
Kobi Gurkan 已提交
363 364 365 366 367 368 369 370
// MakeExtra resolves extradata for the miner from a flag or returns a default.
func makeExtra(ctx *cli.Context) []byte {
	if ctx.GlobalIsSet(ExtraDataFlag.Name) {
		return []byte(ctx.GlobalString(ExtraDataFlag.Name))
	}
	return makeDefaultExtra()
}

371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
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
}

392
func run(ctx *cli.Context) {
T
Taylor Gerring 已提交
393
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))
394 395 396
	if ctx.GlobalBool(utils.OlympicFlag.Name) {
		utils.InitOlympic()
	}
T
Taylor Gerring 已提交
397

398
	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
K
Kobi Gurkan 已提交
399
	cfg.ExtraData = makeExtra(ctx)
400

401
	ethereum, err := eth.New(cfg)
402
	if err != nil {
403 404 405
		utils.Fatalf("%v", err)
	}

406
	startEth(ctx, ethereum)
407
	// this blocks the thread
408
	ethereum.WaitForShutdown()
409
}
410

B
Bas van Kervel 已提交
411
func attach(ctx *cli.Context) {
T
Taylor Gerring 已提交
412 413
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

B
Bas van Kervel 已提交
414 415 416 417 418 419
	var client comms.EthereumClient
	var err error
	if ctx.Args().Present() {
		client, err = comms.ClientFromEndpoint(ctx.Args().First(), codec.JSON)
	} else {
		cfg := comms.IpcConfig{
420
			Endpoint: utils.IpcSocketPath(ctx),
B
Bas van Kervel 已提交
421 422 423 424 425 426 427 428 429
		}
		client, err = comms.NewIpcClient(cfg, codec.JSON)
	}

	if err != nil {
		utils.Fatalf("Unable to attach to geth node - %v", err)
	}

	repl := newLightweightJSRE(
430
		ctx.GlobalString(utils.JSpathFlag.Name),
B
Bas van Kervel 已提交
431 432
		client,
		true,
B
Bas van Kervel 已提交
433
	)
B
Bas van Kervel 已提交
434

435 436 437 438 439 440
	if ctx.GlobalString(utils.ExecFlag.Name) != "" {
		repl.batch(ctx.GlobalString(utils.ExecFlag.Name))
	} else {
		repl.welcome()
		repl.interactive()
	}
B
Bas van Kervel 已提交
441 442
}

Z
CLI:  
zelig 已提交
443
func console(ctx *cli.Context) {
T
Taylor Gerring 已提交
444 445
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

446
	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
447
	ethereum, err := eth.New(cfg)
448
	if err != nil {
449 450 451
		utils.Fatalf("%v", err)
	}

452 453
	client := comms.NewInProcClient(codec.JSON)

454
	startEth(ctx, ethereum)
455 456
	repl := newJSRE(
		ethereum,
457
		ctx.GlobalString(utils.JSpathFlag.Name),
458
		ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
459
		client,
460 461 462
		true,
		nil,
	)
B
Bas van Kervel 已提交
463

464 465 466 467 468 469
	if ctx.GlobalString(utils.ExecFlag.Name) != "" {
		repl.batch(ctx.GlobalString(utils.ExecFlag.Name))
	} else {
		repl.welcome()
		repl.interactive()
	}
Z
CLI:  
zelig 已提交
470 471 472 473 474 475

	ethereum.Stop()
	ethereum.WaitForShutdown()
}

func execJSFiles(ctx *cli.Context) {
T
Taylor Gerring 已提交
476 477
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

478
	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
Z
CLI:  
zelig 已提交
479 480 481
	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
O
obscuren 已提交
482
	}
Z
CLI:  
zelig 已提交
483

484
	client := comms.NewInProcClient(codec.JSON)
Z
CLI:  
zelig 已提交
485
	startEth(ctx, ethereum)
486 487
	repl := newJSRE(
		ethereum,
488
		ctx.GlobalString(utils.JSpathFlag.Name),
489
		ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
490
		client,
491 492 493
		false,
		nil,
	)
Z
CLI:  
zelig 已提交
494 495 496 497
	for _, file := range ctx.Args() {
		repl.exec(file)
	}

498 499
	ethereum.Stop()
	ethereum.WaitForShutdown()
500
}
O
obscuren 已提交
501

502
func unlockAccount(ctx *cli.Context, am *accounts.Manager, addr string, i int) (addrHex, auth string) {
T
Taylor Gerring 已提交
503 504
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

505
	var err error
506 507 508 509 510 511 512 513 514 515 516
	addrHex, err = utils.ParamToAddress(addr, am)
	if err == nil {
		// Attempt to unlock the account 3 times
		attempts := 3
		for tries := 0; tries < attempts; tries++ {
			msg := fmt.Sprintf("Unlocking account %s | Attempt %d/%d", addr, tries+1, attempts)
			auth = getPassPhrase(ctx, msg, false, i)
			err = am.Unlock(common.HexToAddress(addrHex), auth)
			if err == nil {
				break
			}
517 518
		}
	}
519

520 521
	if err != nil {
		utils.Fatalf("Unlock account failed '%v'", err)
522
	}
523 524
	fmt.Printf("Account '%s' unlocked.\n", addr)
	return
Z
zelig 已提交
525 526
}

527
func blockRecovery(ctx *cli.Context) {
T
Taylor Gerring 已提交
528 529
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

530 531 532
	arg := ctx.Args().First()
	if len(ctx.Args()) < 1 && len(arg) > 0 {
		glog.Fatal("recover requires block number or hash")
533 534 535
	}

	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
536 537
	utils.CheckLegalese(cfg.DataDir)

538
	blockDb, err := ethdb.NewLDBDatabase(filepath.Join(cfg.DataDir, "blockchain"), cfg.DatabaseCache)
539
	if err != nil {
540 541 542 543 544
		glog.Fatalln("could not open db:", err)
	}

	var block *types.Block
	if arg[0] == '#' {
545
		block = core.GetBlock(blockDb, core.GetCanonicalHash(blockDb, common.String2Big(arg[1:]).Uint64()))
546
	} else {
547
		block = core.GetBlock(blockDb, common.HexToHash(arg))
548 549 550 551 552 553
	}

	if block == nil {
		glog.Fatalln("block not found. Recovery failed")
	}

554
	if err = core.WriteHeadBlockHash(blockDb, block.Hash()); err != nil {
555
		glog.Fatalln("block write err", err)
556
	}
557
	glog.Infof("Recovery succesful. New HEAD %x\n", block.Hash())
558 559
}

Z
zelig 已提交
560
func startEth(ctx *cli.Context, eth *eth.Ethereum) {
561
	// Start Ethereum itself
Z
zelig 已提交
562 563
	utils.StartEthereum(eth)

564
	am := eth.AccountManager()
Z
zelig 已提交
565
	account := ctx.GlobalString(utils.UnlockedAccountFlag.Name)
566
	accounts := strings.Split(account, " ")
567
	for i, account := range accounts {
568 569
		if len(account) > 0 {
			if account == "primary" {
Z
zelig 已提交
570
				utils.Fatalf("the 'primary' keyword is deprecated. You can use integer indexes, but the indexes are not permanent, they can change if you add external keys, export your keys or copy your keystore to another node.")
571
			}
572
			unlockAccount(ctx, am, account, i)
Z
zelig 已提交
573
		}
Z
zelig 已提交
574
	}
575
	// Start auxiliary services if enabled.
B
Bas van Kervel 已提交
576 577 578 579 580
	if !ctx.GlobalBool(utils.IPCDisabledFlag.Name) {
		if err := utils.StartIPC(eth, ctx); err != nil {
			utils.Fatalf("Error string IPC: %v", err)
		}
	}
581
	if ctx.GlobalBool(utils.RPCEnabledFlag.Name) {
582 583 584
		if err := utils.StartRPC(eth, ctx); err != nil {
			utils.Fatalf("Error starting RPC: %v", err)
		}
585 586
	}
	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
587
		if err := eth.StartMining(ctx.GlobalInt(utils.MinerThreadsFlag.Name)); err != nil {
588 589
			utils.Fatalf("%v", err)
		}
590 591
	}
}
O
Merge  
obscuren 已提交
592

F
Felix Lange 已提交
593
func accountList(ctx *cli.Context) {
T
Taylor Gerring 已提交
594 595
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

596
	am := utils.MakeAccountManager(ctx)
F
Felix Lange 已提交
597 598 599 600
	accts, err := am.Accounts()
	if err != nil {
		utils.Fatalf("Could not list accounts: %v", err)
	}
601
	for i, acct := range accts {
Z
zelig 已提交
602
		fmt.Printf("Account #%d: %x\n", i, acct)
F
Felix Lange 已提交
603 604 605
	}
}

606
func getPassPhrase(ctx *cli.Context, desc string, confirmation bool, i int) (passphrase string) {
607 608 609
	passfile := ctx.GlobalString(utils.PasswordFileFlag.Name)
	if len(passfile) == 0 {
		fmt.Println(desc)
610
		auth, err := utils.PromptPassword("Passphrase: ", true)
611 612 613 614
		if err != nil {
			utils.Fatalf("%v", err)
		}
		if confirmation {
615
			confirm, err := utils.PromptPassword("Repeat Passphrase: ", false)
Z
zelig 已提交
616 617 618
			if err != nil {
				utils.Fatalf("%v", err)
			}
619 620
			if auth != confirm {
				utils.Fatalf("Passphrases did not match.")
Z
zelig 已提交
621
			}
622 623
		}
		passphrase = auth
Z
zelig 已提交
624

625 626 627 628
	} else {
		passbytes, err := ioutil.ReadFile(passfile)
		if err != nil {
			utils.Fatalf("Unable to read password file '%s': %v", passfile, err)
629
		}
630 631 632 633 634 635 636 637 638
		// this is backwards compatible if the same password unlocks several accounts
		// it also has the consequence that trailing newlines will not count as part
		// of the password, so --password <(echo -n 'pass') will now work without -n
		passphrases := strings.Split(string(passbytes), "\n")
		if i >= len(passphrases) {
			passphrase = passphrases[len(passphrases)-1]
		} else {
			passphrase = passphrases[i]
		}
F
Felix Lange 已提交
639
	}
Z
zelig 已提交
640 641 642 643
	return
}

func accountCreate(ctx *cli.Context) {
T
Taylor Gerring 已提交
644 645
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

646
	am := utils.MakeAccountManager(ctx)
647
	passphrase := getPassPhrase(ctx, "Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0)
648
	acct, err := am.NewAccount(passphrase)
F
Felix Lange 已提交
649 650 651
	if err != nil {
		utils.Fatalf("Could not create the account: %v", err)
	}
Z
zelig 已提交
652 653 654
	fmt.Printf("Address: %x\n", acct)
}

655
func accountUpdate(ctx *cli.Context) {
T
Taylor Gerring 已提交
656 657
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

658 659 660 661 662 663 664 665 666 667 668 669 670 671
	am := utils.MakeAccountManager(ctx)
	arg := ctx.Args().First()
	if len(arg) == 0 {
		utils.Fatalf("account address or index must be given as argument")
	}

	addr, authFrom := unlockAccount(ctx, am, arg, 0)
	authTo := getPassPhrase(ctx, "Please give a new password. Do not forget this password.", true, 0)
	err := am.Update(common.HexToAddress(addr), authFrom, authTo)
	if err != nil {
		utils.Fatalf("Could not update the account: %v", err)
	}
}

672
func importWallet(ctx *cli.Context) {
T
Taylor Gerring 已提交
673 674
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

675 676 677 678 679 680 681 682 683
	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)
	}

684
	am := utils.MakeAccountManager(ctx)
685
	passphrase := getPassPhrase(ctx, "", false, 0)
686 687 688 689 690 691 692 693

	acct, err := am.ImportPreSaleKey(keyJson, passphrase)
	if err != nil {
		utils.Fatalf("Could not create the account: %v", err)
	}
	fmt.Printf("Address: %x\n", acct)
}

Z
zelig 已提交
694
func accountImport(ctx *cli.Context) {
T
Taylor Gerring 已提交
695 696
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

Z
zelig 已提交
697 698 699 700
	keyfile := ctx.Args().First()
	if len(keyfile) == 0 {
		utils.Fatalf("keyfile must be given as argument")
	}
701
	am := utils.MakeAccountManager(ctx)
702
	passphrase := getPassPhrase(ctx, "Your new account is locked with a password. Please give a password. Do not forget this password.", true, 0)
Z
zelig 已提交
703 704 705 706 707 708 709
	acct, err := am.Import(keyfile, passphrase)
	if err != nil {
		utils.Fatalf("Could not create the account: %v", err)
	}
	fmt.Printf("Address: %x\n", acct)
}

710
func makedag(ctx *cli.Context) {
T
Taylor Gerring 已提交
711 712
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
	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()
	}
739 740
}

741
func version(c *cli.Context) {
742 743 744 745 746
	fmt.Println(ClientIdentifier)
	fmt.Println("Version:", Version)
	if gitCommit != "" {
		fmt.Println("Git Commit:", gitCommit)
	}
747
	fmt.Println("Protocol Versions:", eth.ProtocolVersions)
748 749 750 751 752
	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 已提交
753
}