cmd.go 5.9 KB
Newer Older
O
obscuren 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
	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
	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 go-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @authors
 * 	Jeffrey Wilcke <i@jev.io>
 * 	Viktor Tron <viktor@ethdev.com>
 */
22 23 24
package utils

import (
Z
go fmt  
zelig 已提交
25
	"fmt"
26 27
	"os"
	"os/signal"
O
obscuren 已提交
28
	"regexp"
29

O
obscuren 已提交
30
	"github.com/ethereum/go-ethereum/core/types"
O
obscuren 已提交
31
	"github.com/ethereum/go-ethereum/crypto"
Z
zelig 已提交
32
	"github.com/ethereum/go-ethereum/eth"
33
	"github.com/ethereum/go-ethereum/ethutil"
O
obscuren 已提交
34
	"github.com/ethereum/go-ethereum/logger"
O
obscuren 已提交
35
	"github.com/ethereum/go-ethereum/rlp"
36
	rpchttp "github.com/ethereum/go-ethereum/rpc/http"
T
Taylor Gerring 已提交
37
	rpcws "github.com/ethereum/go-ethereum/rpc/ws"
O
obscuren 已提交
38
	"github.com/ethereum/go-ethereum/state"
O
obscuren 已提交
39
	"github.com/ethereum/go-ethereum/xeth"
40 41
)

O
obscuren 已提交
42
var clilogger = logger.NewLogger("CLI")
Z
zelig 已提交
43
var interruptCallbacks = []func(os.Signal){}
44

Z
zelig 已提交
45
// Register interrupt handlers callbacks
46
func RegisterInterrupt(cb func(os.Signal)) {
Z
go fmt  
zelig 已提交
47
	interruptCallbacks = append(interruptCallbacks, cb)
Z
zelig 已提交
48 49 50 51
}

// go routine that call interrupt handlers in order of registering
func HandleInterrupt() {
Z
go fmt  
zelig 已提交
52 53 54 55
	c := make(chan os.Signal, 1)
	go func() {
		signal.Notify(c, os.Interrupt)
		for sig := range c {
O
obscuren 已提交
56
			clilogger.Errorf("Shutting down (%v) ... \n", sig)
Z
go fmt  
zelig 已提交
57 58 59
			RunInterruptCallbacks(sig)
		}
	}()
60 61
}

Z
zelig 已提交
62
func RunInterruptCallbacks(sig os.Signal) {
Z
go fmt  
zelig 已提交
63 64 65
	for _, cb := range interruptCallbacks {
		cb(sig)
	}
Z
zelig 已提交
66 67
}

Z
go fmt  
zelig 已提交
68
func openLogFile(Datadir string, filename string) *os.File {
O
obscuren 已提交
69
	path := ethutil.AbsolutePath(Datadir, filename)
Z
go fmt  
zelig 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
	file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
	}
	return file
}

func confirm(message string) bool {
	fmt.Println(message, "Are you sure? (y/n)")
	var r string
	fmt.Scanln(&r)
	for ; ; fmt.Scanln(&r) {
		if r == "n" || r == "y" {
			break
		} else {
O
obscuren 已提交
85
			fmt.Printf("Yes or no? (%s)", r)
Z
go fmt  
zelig 已提交
86 87 88
		}
	}
	return r == "y"
89
}
O
obscuren 已提交
90

O
obscuren 已提交
91
func initDataDir(Datadir string) {
Z
go fmt  
zelig 已提交
92 93 94
	_, err := os.Stat(Datadir)
	if err != nil {
		if os.IsNotExist(err) {
95
			fmt.Printf("Data directory '%s' doesn't exist, creating it\n", Datadir)
Z
go fmt  
zelig 已提交
96 97 98 99 100
			os.Mkdir(Datadir, 0777)
		}
	}
}

O
New VM  
obscuren 已提交
101
func InitConfig(vmType int, ConfigFile string, Datadir string, EnvPrefix string) *ethutil.ConfigManager {
O
obscuren 已提交
102
	initDataDir(Datadir)
O
New VM  
obscuren 已提交
103 104 105 106
	cfg := ethutil.ReadConfig(ConfigFile, Datadir, EnvPrefix)
	cfg.VmType = vmType

	return cfg
107
}
108

109 110 111
func exit(err error) {
	status := 0
	if err != nil {
O
obscuren 已提交
112
		clilogger.Errorln("Fatal: ", err)
113 114
		status = 1
	}
O
obscuren 已提交
115
	logger.Flush()
Z
go fmt  
zelig 已提交
116
	os.Exit(status)
117
}
O
obscuren 已提交
118

119
func StartEthereum(ethereum *eth.Ethereum) {
120
	clilogger.Infoln("Starting ", ethereum.Name())
121
	if err := ethereum.Start(); err != nil {
O
obscuren 已提交
122 123
		exit(err)
	}
Z
go fmt  
zelig 已提交
124 125
	RegisterInterrupt(func(sig os.Signal) {
		ethereum.Stop()
O
obscuren 已提交
126
		logger.Flush()
Z
go fmt  
zelig 已提交
127
	})
128
}
O
obscuren 已提交
129

O
obscuren 已提交
130
func KeyTasks(keyManager *crypto.KeyManager, KeyRing string, GenAddr bool, SecretFile string, ExportDir string, NonInteractive bool) {
131

132
	var err error
Z
go fmt  
zelig 已提交
133 134 135
	switch {
	case GenAddr:
		if NonInteractive || confirm("This action overwrites your old private key.") {
136
			err = keyManager.Init(KeyRing, 0, true)
Z
go fmt  
zelig 已提交
137
		}
138 139
		exit(err)
	case len(SecretFile) > 0:
O
obscuren 已提交
140 141
		SecretFile = ethutil.ExpandHomePath(SecretFile)

Z
go fmt  
zelig 已提交
142
		if NonInteractive || confirm("This action overwrites your old private key.") {
143
			err = keyManager.InitFromSecretsFile(KeyRing, 0, SecretFile)
Z
go fmt  
zelig 已提交
144
		}
145 146 147 148 149 150 151
		exit(err)
	case len(ExportDir) > 0:
		err = keyManager.Init(KeyRing, 0, false)
		if err == nil {
			err = keyManager.Export(ExportDir)
		}
		exit(err)
Z
go fmt  
zelig 已提交
152 153
	default:
		// Creates a keypair if none exists
154 155 156 157
		err = keyManager.Init(KeyRing, 0, false)
		if err != nil {
			exit(err)
		}
Z
go fmt  
zelig 已提交
158
	}
159
	clilogger.Infof("Main address %x\n", keyManager.Address())
160
}
O
obscuren 已提交
161

T
Taylor Gerring 已提交
162
func StartRpc(ethereum *eth.Ethereum, RpcListenAddress string, RpcPort int) {
Z
go fmt  
zelig 已提交
163
	var err error
T
Taylor Gerring 已提交
164
	ethereum.RpcServer, err = rpchttp.NewRpcHttpServer(xeth.New(ethereum), RpcListenAddress, RpcPort)
Z
go fmt  
zelig 已提交
165
	if err != nil {
O
obscuren 已提交
166
		clilogger.Errorf("Could not start RPC interface (port %v): %v", RpcPort, err)
Z
go fmt  
zelig 已提交
167 168 169
	} else {
		go ethereum.RpcServer.Start()
	}
O
obscuren 已提交
170 171
}

172
func StartWebSockets(eth *eth.Ethereum, wsPort int) {
T
Taylor Gerring 已提交
173 174
	clilogger.Infoln("Starting WebSockets")

175
	var err error
176
	eth.WsServer, err = rpcws.NewWebSocketServer(xeth.New(eth), wsPort)
177 178 179 180 181
	if err != nil {
		clilogger.Errorf("Could not start RPC interface (port %v): %v", wsPort, err)
	} else {
		go eth.WsServer.Start()
	}
T
Taylor Gerring 已提交
182 183
}

O
obscuren 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196
func FormatTransactionData(data string) []byte {
	d := ethutil.StringToByteFunc(data, func(s string) (ret []byte) {
		slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
		for _, dataItem := range slice {
			d := ethutil.FormatData(dataItem)
			ret = append(ret, d...)
		}
		return
	})

	return d
}

O
obscuren 已提交
197 198
// Replay block
func BlockDo(ethereum *eth.Ethereum, hash []byte) error {
O
obscuren 已提交
199
	block := ethereum.ChainManager().GetBlock(hash)
O
obscuren 已提交
200 201 202 203
	if block == nil {
		return fmt.Errorf("unknown block %x", hash)
	}

O
obscuren 已提交
204
	parent := ethereum.ChainManager().GetBlock(block.ParentHash())
O
obscuren 已提交
205

O
obscuren 已提交
206
	statedb := state.New(parent.Root(), ethereum.Db())
207
	_, err := ethereum.BlockProcessor().TransitionState(statedb, parent, block, true)
O
obscuren 已提交
208 209 210 211 212 213 214
	if err != nil {
		return err
	}

	return nil

}
O
obscuren 已提交
215 216

func ImportChain(ethereum *eth.Ethereum, fn string) error {
O
obscuren 已提交
217
	clilogger.Infof("importing chain '%s'\n", fn)
O
obscuren 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
	fh, err := os.OpenFile(fn, os.O_RDONLY, os.ModePerm)
	if err != nil {
		return err
	}
	defer fh.Close()

	var chain types.Blocks
	if err := rlp.Decode(fh, &chain); err != nil {
		return err
	}

	ethereum.ChainManager().Reset()
	if err := ethereum.ChainManager().InsertChain(chain); err != nil {
		return err
	}
	clilogger.Infof("imported %d blocks\n", len(chain))

	return nil
}