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

import (
zelig's avatar
zelig committed
4
	"fmt"
5 6 7 8
	"os"
	"os/signal"
	"path"
	"path/filepath"
obscuren's avatar
obscuren committed
9
	"regexp"
10 11 12
	"runtime"

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

obscuren's avatar
obscuren committed
24
var clilogger = logger.NewLogger("CLI")
zelig's avatar
zelig committed
25
var interruptCallbacks = []func(os.Signal){}
26

zelig's avatar
zelig committed
27
// Register interrupt handlers callbacks
28
func RegisterInterrupt(cb func(os.Signal)) {
zelig's avatar
zelig committed
29
	interruptCallbacks = append(interruptCallbacks, cb)
zelig's avatar
zelig committed
30 31 32 33
}

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

zelig's avatar
zelig committed
44
func RunInterruptCallbacks(sig os.Signal) {
zelig's avatar
zelig committed
45 46 47
	for _, cb := range interruptCallbacks {
		cb(sig)
	}
zelig's avatar
zelig committed
48 49
}

zelig's avatar
zelig committed
50
func openLogFile(Datadir string, filename string) *os.File {
obscuren's avatar
obscuren committed
51
	path := ethutil.AbsolutePath(Datadir, filename)
zelig's avatar
zelig committed
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 {
obscuren's avatar
obscuren committed
67
			fmt.Printf("Yes or no? (%s)", r)
zelig's avatar
zelig committed
68 69 70
		}
	}
	return r == "y"
71
}
obscuren's avatar
obscuren committed
72

obscuren's avatar
obscuren committed
73
func initDataDir(Datadir string) {
zelig's avatar
zelig committed
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)
zelig's avatar
zelig committed
78 79 80 81 82
			os.Mkdir(Datadir, 0777)
		}
	}
}

obscuren's avatar
obscuren committed
83
func InitConfig(vmType int, ConfigFile string, Datadir string, EnvPrefix string) *ethutil.ConfigManager {
obscuren's avatar
obscuren committed
84
	initDataDir(Datadir)
obscuren's avatar
obscuren committed
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 {
obscuren's avatar
obscuren committed
94
		clilogger.Errorln("Fatal: ", err)
95 96
		status = 1
	}
obscuren's avatar
obscuren committed
97
	logger.Flush()
zelig's avatar
zelig committed
98
	os.Exit(status)
99
}
obscuren's avatar
obscuren committed
100

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

zelig's avatar
zelig committed
108 109
	RegisterInterrupt(func(sig os.Signal) {
		ethereum.Stop()
obscuren's avatar
obscuren committed
110
		logger.Flush()
zelig's avatar
zelig committed
111
	})
112
}
obscuren's avatar
obscuren committed
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":
129
			assetPath = "/usr/share/mist"
130 131 132 133 134 135 136 137
		case "windows":
			assetPath = "./assets"
		default:
			assetPath = "."
		}
	}
	return assetPath
}
138

obscuren's avatar
obscuren committed
139
func KeyTasks(keyManager *crypto.KeyManager, KeyRing string, GenAddr bool, SecretFile string, ExportDir string, NonInteractive bool) {
140

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

zelig's avatar
zelig committed
151
		if NonInteractive || confirm("This action overwrites your old private key.") {
152
			err = keyManager.InitFromSecretsFile(KeyRing, 0, SecretFile)
zelig's avatar
zelig committed
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)
zelig's avatar
zelig committed
161 162
	default:
		// Creates a keypair if none exists
163 164 165 166
		err = keyManager.Init(KeyRing, 0, false)
		if err != nil {
			exit(err)
		}
zelig's avatar
zelig committed
167
	}
168
	clilogger.Infof("Main address %x\n", keyManager.Address())
169
}
obscuren's avatar
obscuren committed
170

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

obscuren's avatar
obscuren committed
181
var gminer *miner.Miner
obscuren's avatar
obscuren committed
182

obscuren's avatar
obscuren committed
183 184
func GetMiner() *miner.Miner {
	return gminer
Maran's avatar
Maran committed
185
}
obscuren's avatar
obscuren committed
186

187
func StartMining(ethereum *eth.Ethereum) bool {
zelig's avatar
zelig committed
188 189
	if !ethereum.Mining {
		ethereum.Mining = true
190
		addr := ethereum.KeyManager().Address()
zelig's avatar
zelig committed
191 192

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

obscuren's avatar
obscuren committed
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 {
obscuren's avatar
obscuren committed
221 222
	if ethereum.Mining && gminer != nil {
		gminer.Stop()
obscuren's avatar
obscuren committed
223
		clilogger.Infoln("Stopped mining")
zelig's avatar
zelig committed
224
		ethereum.Mining = false
225

zelig's avatar
zelig committed
226 227
		return true
	}
228

zelig's avatar
zelig committed
229
	return false
obscuren's avatar
obscuren committed
230
}
obscuren's avatar
obscuren committed
231 232 233

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

239
	parent := ethereum.ChainManager().GetBlock(block.ParentHash())
obscuren's avatar
obscuren committed
240

241
	_, err := ethereum.BlockProcessor().TransitionState(parent.State(), parent, block)
obscuren's avatar
obscuren committed
242 243 244 245 246 247 248
	if err != nil {
		return err
	}

	return nil

}
obscuren's avatar
obscuren committed
249 250

func ImportChain(ethereum *eth.Ethereum, fn string) error {
obscuren's avatar
obscuren committed
251
	clilogger.Infof("importing chain '%s'\n", fn)
obscuren's avatar
obscuren committed
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
}