cmd.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /*
  2. This file is part of go-ethereum
  3. go-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. go-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /**
  15. * @authors
  16. * Jeffrey Wilcke <i@jev.io>
  17. * Viktor Tron <viktor@ethdev.com>
  18. */
  19. package utils
  20. import (
  21. "fmt"
  22. "os"
  23. "os/signal"
  24. "path"
  25. "path/filepath"
  26. "regexp"
  27. "runtime"
  28. "bitbucket.org/kardianos/osext"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/crypto"
  31. "github.com/ethereum/go-ethereum/eth"
  32. "github.com/ethereum/go-ethereum/ethutil"
  33. "github.com/ethereum/go-ethereum/logger"
  34. "github.com/ethereum/go-ethereum/miner"
  35. "github.com/ethereum/go-ethereum/rlp"
  36. rpchttp "github.com/ethereum/go-ethereum/rpc/http"
  37. "github.com/ethereum/go-ethereum/state"
  38. "github.com/ethereum/go-ethereum/websocket"
  39. "github.com/ethereum/go-ethereum/xeth"
  40. )
  41. var clilogger = logger.NewLogger("CLI")
  42. var interruptCallbacks = []func(os.Signal){}
  43. // Register interrupt handlers callbacks
  44. func RegisterInterrupt(cb func(os.Signal)) {
  45. interruptCallbacks = append(interruptCallbacks, cb)
  46. }
  47. // go routine that call interrupt handlers in order of registering
  48. func HandleInterrupt() {
  49. c := make(chan os.Signal, 1)
  50. go func() {
  51. signal.Notify(c, os.Interrupt)
  52. for sig := range c {
  53. clilogger.Errorf("Shutting down (%v) ... \n", sig)
  54. RunInterruptCallbacks(sig)
  55. }
  56. }()
  57. }
  58. func RunInterruptCallbacks(sig os.Signal) {
  59. for _, cb := range interruptCallbacks {
  60. cb(sig)
  61. }
  62. }
  63. func openLogFile(Datadir string, filename string) *os.File {
  64. path := ethutil.AbsolutePath(Datadir, filename)
  65. file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  66. if err != nil {
  67. panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
  68. }
  69. return file
  70. }
  71. func confirm(message string) bool {
  72. fmt.Println(message, "Are you sure? (y/n)")
  73. var r string
  74. fmt.Scanln(&r)
  75. for ; ; fmt.Scanln(&r) {
  76. if r == "n" || r == "y" {
  77. break
  78. } else {
  79. fmt.Printf("Yes or no? (%s)", r)
  80. }
  81. }
  82. return r == "y"
  83. }
  84. func initDataDir(Datadir string) {
  85. _, err := os.Stat(Datadir)
  86. if err != nil {
  87. if os.IsNotExist(err) {
  88. fmt.Printf("Data directory '%s' doesn't exist, creating it\n", Datadir)
  89. os.Mkdir(Datadir, 0777)
  90. }
  91. }
  92. }
  93. func InitConfig(vmType int, ConfigFile string, Datadir string, EnvPrefix string) *ethutil.ConfigManager {
  94. initDataDir(Datadir)
  95. cfg := ethutil.ReadConfig(ConfigFile, Datadir, EnvPrefix)
  96. cfg.VmType = vmType
  97. return cfg
  98. }
  99. func exit(err error) {
  100. status := 0
  101. if err != nil {
  102. clilogger.Errorln("Fatal: ", err)
  103. status = 1
  104. }
  105. logger.Flush()
  106. os.Exit(status)
  107. }
  108. func StartEthereum(ethereum *eth.Ethereum, UseSeed bool) {
  109. clilogger.Infof("Starting %s", ethereum.ClientIdentity())
  110. err := ethereum.Start(UseSeed)
  111. if err != nil {
  112. exit(err)
  113. }
  114. RegisterInterrupt(func(sig os.Signal) {
  115. ethereum.Stop()
  116. logger.Flush()
  117. })
  118. }
  119. func DefaultAssetPath() string {
  120. var assetPath string
  121. // If the current working directory is the go-ethereum dir
  122. // assume a debug build and use the source directory as
  123. // asset directory.
  124. pwd, _ := os.Getwd()
  125. if pwd == path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist") {
  126. assetPath = path.Join(pwd, "assets")
  127. } else {
  128. switch runtime.GOOS {
  129. case "darwin":
  130. // Get Binary Directory
  131. exedir, _ := osext.ExecutableFolder()
  132. assetPath = filepath.Join(exedir, "../Resources")
  133. case "linux":
  134. assetPath = "/usr/share/mist"
  135. case "windows":
  136. assetPath = "./assets"
  137. default:
  138. assetPath = "."
  139. }
  140. }
  141. return assetPath
  142. }
  143. func KeyTasks(keyManager *crypto.KeyManager, KeyRing string, GenAddr bool, SecretFile string, ExportDir string, NonInteractive bool) {
  144. var err error
  145. switch {
  146. case GenAddr:
  147. if NonInteractive || confirm("This action overwrites your old private key.") {
  148. err = keyManager.Init(KeyRing, 0, true)
  149. }
  150. exit(err)
  151. case len(SecretFile) > 0:
  152. SecretFile = ethutil.ExpandHomePath(SecretFile)
  153. if NonInteractive || confirm("This action overwrites your old private key.") {
  154. err = keyManager.InitFromSecretsFile(KeyRing, 0, SecretFile)
  155. }
  156. exit(err)
  157. case len(ExportDir) > 0:
  158. err = keyManager.Init(KeyRing, 0, false)
  159. if err == nil {
  160. err = keyManager.Export(ExportDir)
  161. }
  162. exit(err)
  163. default:
  164. // Creates a keypair if none exists
  165. err = keyManager.Init(KeyRing, 0, false)
  166. if err != nil {
  167. exit(err)
  168. }
  169. }
  170. clilogger.Infof("Main address %x\n", keyManager.Address())
  171. }
  172. func StartRpc(ethereum *eth.Ethereum, RpcPort int) {
  173. var err error
  174. ethereum.RpcServer, err = rpchttp.NewRpcHttpServer(xeth.NewJSXEth(ethereum), RpcPort)
  175. if err != nil {
  176. clilogger.Errorf("Could not start RPC interface (port %v): %v", RpcPort, err)
  177. } else {
  178. go ethereum.RpcServer.Start()
  179. }
  180. }
  181. func StartWebSockets(eth *eth.Ethereum) {
  182. clilogger.Infoln("Starting WebSockets")
  183. sock := websocket.NewWebSocketServer(eth)
  184. go sock.Serv()
  185. }
  186. var gminer *miner.Miner
  187. func GetMiner() *miner.Miner {
  188. return gminer
  189. }
  190. func StartMining(ethereum *eth.Ethereum) bool {
  191. if !ethereum.Mining {
  192. ethereum.Mining = true
  193. addr := ethereum.KeyManager().Address()
  194. go func() {
  195. clilogger.Infoln("Start mining")
  196. if gminer == nil {
  197. gminer = miner.New(addr, ethereum)
  198. }
  199. gminer.Start()
  200. }()
  201. RegisterInterrupt(func(os.Signal) {
  202. StopMining(ethereum)
  203. })
  204. return true
  205. }
  206. return false
  207. }
  208. func FormatTransactionData(data string) []byte {
  209. d := ethutil.StringToByteFunc(data, func(s string) (ret []byte) {
  210. slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
  211. for _, dataItem := range slice {
  212. d := ethutil.FormatData(dataItem)
  213. ret = append(ret, d...)
  214. }
  215. return
  216. })
  217. return d
  218. }
  219. func StopMining(ethereum *eth.Ethereum) bool {
  220. if ethereum.Mining && gminer != nil {
  221. gminer.Stop()
  222. clilogger.Infoln("Stopped mining")
  223. ethereum.Mining = false
  224. return true
  225. }
  226. return false
  227. }
  228. // Replay block
  229. func BlockDo(ethereum *eth.Ethereum, hash []byte) error {
  230. block := ethereum.ChainManager().GetBlock(hash)
  231. if block == nil {
  232. return fmt.Errorf("unknown block %x", hash)
  233. }
  234. parent := ethereum.ChainManager().GetBlock(block.ParentHash())
  235. statedb := state.New(parent.Root(), ethereum.Db())
  236. _, err := ethereum.BlockProcessor().TransitionState(statedb, parent, block)
  237. if err != nil {
  238. return err
  239. }
  240. return nil
  241. }
  242. func ImportChain(ethereum *eth.Ethereum, fn string) error {
  243. clilogger.Infof("importing chain '%s'\n", fn)
  244. fh, err := os.OpenFile(fn, os.O_RDONLY, os.ModePerm)
  245. if err != nil {
  246. return err
  247. }
  248. defer fh.Close()
  249. var chain types.Blocks
  250. if err := rlp.Decode(fh, &chain); err != nil {
  251. return err
  252. }
  253. ethereum.ChainManager().Reset()
  254. if err := ethereum.ChainManager().InsertChain(chain); err != nil {
  255. return err
  256. }
  257. clilogger.Infof("imported %d blocks\n", len(chain))
  258. return nil
  259. }