cmd.go 6.1 KB
Newer Older
1 2 3
package utils

import (
Z
go fmt  
zelig 已提交
4
	"fmt"
5 6 7 8
	"os"
	"os/signal"
	"path"
	"path/filepath"
O
obscuren 已提交
9
	"regexp"
10 11 12
	"runtime"

	"bitbucket.org/kardianos/osext"
O
obscuren 已提交
13
	"github.com/ethereum/go-ethereum/core/types"
O
obscuren 已提交
14
	"github.com/ethereum/go-ethereum/crypto"
Z
zelig 已提交
15
	"github.com/ethereum/go-ethereum/eth"
16
	"github.com/ethereum/go-ethereum/ethutil"
O
obscuren 已提交
17
	"github.com/ethereum/go-ethereum/logger"
O
obscuren 已提交
18
	"github.com/ethereum/go-ethereum/miner"
O
obscuren 已提交
19
	"github.com/ethereum/go-ethereum/rlp"
20
	"github.com/ethereum/go-ethereum/rpc"
O
obscuren 已提交
21
	"github.com/ethereum/go-ethereum/xeth"
22 23
)

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

Z
zelig 已提交
27
// Register interrupt handlers callbacks
28
func RegisterInterrupt(cb func(os.Signal)) {
Z
go fmt  
zelig 已提交
29
	interruptCallbacks = append(interruptCallbacks, cb)
Z
zelig 已提交
30 31 32 33
}

// go routine that call interrupt handlers in order of registering
func HandleInterrupt() {
Z
go fmt  
zelig 已提交
34 35 36 37
	c := make(chan os.Signal, 1)
	go func() {
		signal.Notify(c, os.Interrupt)
		for sig := range c {
O
obscuren 已提交
38
			clilogger.Errorf("Shutting down (%v) ... \n", sig)
Z
go fmt  
zelig 已提交
39 40 41
			RunInterruptCallbacks(sig)
		}
	}()
42 43
}

Z
zelig 已提交
44
func RunInterruptCallbacks(sig os.Signal) {
Z
go fmt  
zelig 已提交
45 46 47
	for _, cb := range interruptCallbacks {
		cb(sig)
	}
Z
zelig 已提交
48 49
}

Z
go fmt  
zelig 已提交
50
func openLogFile(Datadir string, filename string) *os.File {
O
obscuren 已提交
51
	path := ethutil.AbsolutePath(Datadir, filename)
Z
go fmt  
zelig 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
	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 已提交
67
			fmt.Printf("Yes or no? (%s)", r)
Z
go fmt  
zelig 已提交
68 69 70
		}
	}
	return r == "y"
71
}
O
obscuren 已提交
72

O
obscuren 已提交
73
func initDataDir(Datadir string) {
Z
go fmt  
zelig 已提交
74 75 76
	_, err := os.Stat(Datadir)
	if err != nil {
		if os.IsNotExist(err) {
77
			fmt.Printf("Data directory '%s' doesn't exist, creating it\n", Datadir)
Z
go fmt  
zelig 已提交
78 79 80 81 82
			os.Mkdir(Datadir, 0777)
		}
	}
}

O
New VM  
obscuren 已提交
83
func InitConfig(vmType int, ConfigFile string, Datadir string, EnvPrefix string) *ethutil.ConfigManager {
O
obscuren 已提交
84
	initDataDir(Datadir)
O
New VM  
obscuren 已提交
85 86 87 88
	cfg := ethutil.ReadConfig(ConfigFile, Datadir, EnvPrefix)
	cfg.VmType = vmType

	return cfg
89
}
90

91 92 93
func exit(err error) {
	status := 0
	if err != nil {
O
obscuren 已提交
94
		clilogger.Errorln("Fatal: ", err)
95 96
		status = 1
	}
O
obscuren 已提交
97
	logger.Flush()
Z
go fmt  
zelig 已提交
98
	os.Exit(status)
99
}
O
obscuren 已提交
100

101
func StartEthereum(ethereum *eth.Ethereum, UseSeed bool) {
O
obscuren 已提交
102
	clilogger.Infof("Starting %s", ethereum.ClientIdentity())
O
obscuren 已提交
103 104 105 106 107
	err := ethereum.Start(UseSeed)
	if err != nil {
		exit(err)
	}

Z
go fmt  
zelig 已提交
108 109
	RegisterInterrupt(func(sig os.Signal) {
		ethereum.Stop()
O
obscuren 已提交
110
		logger.Flush()
Z
go fmt  
zelig 已提交
111
	})
112
}
O
obscuren 已提交
113

114 115 116 117 118 119
func DefaultAssetPath() string {
	var assetPath string
	// If the current working directory is the go-ethereum dir
	// assume a debug build and use the source directory as
	// asset directory.
	pwd, _ := os.Getwd()
120
	if pwd == path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist") {
121 122 123 124 125 126 127 128
		assetPath = path.Join(pwd, "assets")
	} else {
		switch runtime.GOOS {
		case "darwin":
			// Get Binary Directory
			exedir, _ := osext.ExecutableFolder()
			assetPath = filepath.Join(exedir, "../Resources")
		case "linux":
O
obscuren 已提交
129
			assetPath = "/usr/share/mist"
130 131 132 133 134 135 136 137
		case "windows":
			assetPath = "./assets"
		default:
			assetPath = "."
		}
	}
	return assetPath
}
138

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

141
	var err error
Z
go fmt  
zelig 已提交
142 143 144
	switch {
	case GenAddr:
		if NonInteractive || confirm("This action overwrites your old private key.") {
145
			err = keyManager.Init(KeyRing, 0, true)
Z
go fmt  
zelig 已提交
146
		}
147 148
		exit(err)
	case len(SecretFile) > 0:
O
obscuren 已提交
149 150
		SecretFile = ethutil.ExpandHomePath(SecretFile)

Z
go fmt  
zelig 已提交
151
		if NonInteractive || confirm("This action overwrites your old private key.") {
152
			err = keyManager.InitFromSecretsFile(KeyRing, 0, SecretFile)
Z
go fmt  
zelig 已提交
153
		}
154 155 156 157 158 159 160
		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 已提交
161 162
	default:
		// Creates a keypair if none exists
163 164 165 166
		err = keyManager.Init(KeyRing, 0, false)
		if err != nil {
			exit(err)
		}
Z
go fmt  
zelig 已提交
167
	}
168
	clilogger.Infof("Main address %x\n", keyManager.Address())
169
}
O
obscuren 已提交
170

171
func StartRpc(ethereum *eth.Ethereum, RpcPort int) {
Z
go fmt  
zelig 已提交
172
	var err error
O
obscuren 已提交
173
	ethereum.RpcServer, err = rpc.NewJsonRpcServer(xeth.NewJSXEth(ethereum), RpcPort)
Z
go fmt  
zelig 已提交
174
	if err != nil {
O
obscuren 已提交
175
		clilogger.Errorf("Could not start RPC interface (port %v): %v", RpcPort, err)
Z
go fmt  
zelig 已提交
176 177 178
	} else {
		go ethereum.RpcServer.Start()
	}
O
obscuren 已提交
179 180
}

O
obscuren 已提交
181
var gminer *miner.Miner
O
obscuren 已提交
182

O
obscuren 已提交
183 184
func GetMiner() *miner.Miner {
	return gminer
M
Maran 已提交
185
}
O
obscuren 已提交
186

187
func StartMining(ethereum *eth.Ethereum) bool {
Z
go fmt  
zelig 已提交
188 189
	if !ethereum.Mining {
		ethereum.Mining = true
190
		addr := ethereum.KeyManager().Address()
Z
go fmt  
zelig 已提交
191 192

		go func() {
O
obscuren 已提交
193
			clilogger.Infoln("Start mining")
O
obscuren 已提交
194
			if gminer == nil {
195
				gminer = miner.New(addr, ethereum)
196
			}
O
obscuren 已提交
197
			gminer.Start()
Z
go fmt  
zelig 已提交
198 199 200 201 202 203 204
		}()
		RegisterInterrupt(func(os.Signal) {
			StopMining(ethereum)
		})
		return true
	}
	return false
205
}
O
obscuren 已提交
206

O
obscuren 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219
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
}

220
func StopMining(ethereum *eth.Ethereum) bool {
O
obscuren 已提交
221 222
	if ethereum.Mining && gminer != nil {
		gminer.Stop()
O
obscuren 已提交
223
		clilogger.Infoln("Stopped mining")
Z
go fmt  
zelig 已提交
224
		ethereum.Mining = false
O
obscuren 已提交
225

Z
go fmt  
zelig 已提交
226 227
		return true
	}
O
obscuren 已提交
228

Z
go fmt  
zelig 已提交
229
	return false
O
obscuren 已提交
230
}
O
obscuren 已提交
231 232 233

// Replay block
func BlockDo(ethereum *eth.Ethereum, hash []byte) error {
O
obscuren 已提交
234
	block := ethereum.ChainManager().GetBlock(hash)
O
obscuren 已提交
235 236 237 238
	if block == nil {
		return fmt.Errorf("unknown block %x", hash)
	}

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

O
obscuren 已提交
241
	_, err := ethereum.BlockProcessor().TransitionState(parent.State(), parent, block)
O
obscuren 已提交
242 243 244 245 246 247 248
	if err != nil {
		return err
	}

	return nil

}
O
obscuren 已提交
249 250

func ImportChain(ethereum *eth.Ethereum, fn string) error {
O
obscuren 已提交
251
	clilogger.Infof("importing chain '%s'\n", fn)
O
obscuren 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
	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
}