cmd.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. "github.com/ethereum/go-ethereum/rpc"
  37. "github.com/ethereum/go-ethereum/state"
  38. "github.com/ethereum/go-ethereum/xeth"
  39. )
  40. var clilogger = logger.NewLogger("CLI")
  41. var interruptCallbacks = []func(os.Signal){}
  42. // Register interrupt handlers callbacks
  43. func RegisterInterrupt(cb func(os.Signal)) {
  44. interruptCallbacks = append(interruptCallbacks, cb)
  45. }
  46. // go routine that call interrupt handlers in order of registering
  47. func HandleInterrupt() {
  48. c := make(chan os.Signal, 1)
  49. go func() {
  50. signal.Notify(c, os.Interrupt)
  51. for sig := range c {
  52. clilogger.Errorf("Shutting down (%v) ... \n", sig)
  53. RunInterruptCallbacks(sig)
  54. }
  55. }()
  56. }
  57. func RunInterruptCallbacks(sig os.Signal) {
  58. for _, cb := range interruptCallbacks {
  59. cb(sig)
  60. }
  61. }
  62. func openLogFile(Datadir string, filename string) *os.File {
  63. path := ethutil.AbsolutePath(Datadir, filename)
  64. file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  65. if err != nil {
  66. panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
  67. }
  68. return file
  69. }
  70. func confirm(message string) bool {
  71. fmt.Println(message, "Are you sure? (y/n)")
  72. var r string
  73. fmt.Scanln(&r)
  74. for ; ; fmt.Scanln(&r) {
  75. if r == "n" || r == "y" {
  76. break
  77. } else {
  78. fmt.Printf("Yes or no? (%s)", r)
  79. }
  80. }
  81. return r == "y"
  82. }
  83. func initDataDir(Datadir string) {
  84. _, err := os.Stat(Datadir)
  85. if err != nil {
  86. if os.IsNotExist(err) {
  87. fmt.Printf("Data directory '%s' doesn't exist, creating it\n", Datadir)
  88. os.Mkdir(Datadir, 0777)
  89. }
  90. }
  91. }
  92. func InitConfig(vmType int, ConfigFile string, Datadir string, EnvPrefix string) *ethutil.ConfigManager {
  93. initDataDir(Datadir)
  94. cfg := ethutil.ReadConfig(ConfigFile, Datadir, EnvPrefix)
  95. cfg.VmType = vmType
  96. return cfg
  97. }
  98. func exit(err error) {
  99. status := 0
  100. if err != nil {
  101. clilogger.Errorln("Fatal: ", err)
  102. status = 1
  103. }
  104. logger.Flush()
  105. os.Exit(status)
  106. }
  107. func StartEthereum(ethereum *eth.Ethereum, UseSeed bool) {
  108. clilogger.Infof("Starting %s", ethereum.ClientIdentity())
  109. err := ethereum.Start(UseSeed)
  110. if err != nil {
  111. exit(err)
  112. }
  113. RegisterInterrupt(func(sig os.Signal) {
  114. ethereum.Stop()
  115. logger.Flush()
  116. })
  117. }
  118. func DefaultAssetPath() string {
  119. var assetPath string
  120. // If the current working directory is the go-ethereum dir
  121. // assume a debug build and use the source directory as
  122. // asset directory.
  123. pwd, _ := os.Getwd()
  124. if pwd == path.Join(os.Getenv("GOPATH"), "src", "github.com", "ethereum", "go-ethereum", "cmd", "mist") {
  125. assetPath = path.Join(pwd, "assets")
  126. } else {
  127. switch runtime.GOOS {
  128. case "darwin":
  129. // Get Binary Directory
  130. exedir, _ := osext.ExecutableFolder()
  131. assetPath = filepath.Join(exedir, "../Resources")
  132. case "linux":
  133. assetPath = "/usr/share/mist"
  134. case "windows":
  135. assetPath = "./assets"
  136. default:
  137. assetPath = "."
  138. }
  139. }
  140. return assetPath
  141. }
  142. func KeyTasks(keyManager *crypto.KeyManager, KeyRing string, GenAddr bool, SecretFile string, ExportDir string, NonInteractive bool) {
  143. var err error
  144. switch {
  145. case GenAddr:
  146. if NonInteractive || confirm("This action overwrites your old private key.") {
  147. err = keyManager.Init(KeyRing, 0, true)
  148. }
  149. exit(err)
  150. case len(SecretFile) > 0:
  151. SecretFile = ethutil.ExpandHomePath(SecretFile)
  152. if NonInteractive || confirm("This action overwrites your old private key.") {
  153. err = keyManager.InitFromSecretsFile(KeyRing, 0, SecretFile)
  154. }
  155. exit(err)
  156. case len(ExportDir) > 0:
  157. err = keyManager.Init(KeyRing, 0, false)
  158. if err == nil {
  159. err = keyManager.Export(ExportDir)
  160. }
  161. exit(err)
  162. default:
  163. // Creates a keypair if none exists
  164. err = keyManager.Init(KeyRing, 0, false)
  165. if err != nil {
  166. exit(err)
  167. }
  168. }
  169. clilogger.Infof("Main address %x\n", keyManager.Address())
  170. }
  171. func StartRpc(ethereum *eth.Ethereum, RpcPort int) {
  172. var err error
  173. ethereum.RpcServer, err = rpc.NewJsonRpcServer(xeth.NewJSXEth(ethereum), RpcPort)
  174. if err != nil {
  175. clilogger.Errorf("Could not start RPC interface (port %v): %v", RpcPort, err)
  176. } else {
  177. go ethereum.RpcServer.Start()
  178. }
  179. }
  180. var gminer *miner.Miner
  181. func GetMiner() *miner.Miner {
  182. return gminer
  183. }
  184. func StartMining(ethereum *eth.Ethereum) bool {
  185. if !ethereum.Mining {
  186. ethereum.Mining = true
  187. addr := ethereum.KeyManager().Address()
  188. go func() {
  189. clilogger.Infoln("Start mining")
  190. if gminer == nil {
  191. gminer = miner.New(addr, ethereum)
  192. }
  193. gminer.Start()
  194. }()
  195. RegisterInterrupt(func(os.Signal) {
  196. StopMining(ethereum)
  197. })
  198. return true
  199. }
  200. return false
  201. }
  202. func FormatTransactionData(data string) []byte {
  203. d := ethutil.StringToByteFunc(data, func(s string) (ret []byte) {
  204. slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
  205. for _, dataItem := range slice {
  206. d := ethutil.FormatData(dataItem)
  207. ret = append(ret, d...)
  208. }
  209. return
  210. })
  211. return d
  212. }
  213. func StopMining(ethereum *eth.Ethereum) bool {
  214. if ethereum.Mining && gminer != nil {
  215. gminer.Stop()
  216. clilogger.Infoln("Stopped mining")
  217. ethereum.Mining = false
  218. return true
  219. }
  220. return false
  221. }
  222. // Replay block
  223. func BlockDo(ethereum *eth.Ethereum, hash []byte) error {
  224. block := ethereum.ChainManager().GetBlock(hash)
  225. if block == nil {
  226. return fmt.Errorf("unknown block %x", hash)
  227. }
  228. parent := ethereum.ChainManager().GetBlock(block.ParentHash())
  229. statedb := state.New(parent.Root(), ethereum.Db())
  230. _, err := ethereum.BlockProcessor().TransitionState(statedb, parent, block)
  231. if err != nil {
  232. return err
  233. }
  234. return nil
  235. }
  236. func ImportChain(ethereum *eth.Ethereum, fn string) error {
  237. clilogger.Infof("importing chain '%s'\n", fn)
  238. fh, err := os.OpenFile(fn, os.O_RDONLY, os.ModePerm)
  239. if err != nil {
  240. return err
  241. }
  242. defer fh.Close()
  243. var chain types.Blocks
  244. if err := rlp.Decode(fh, &chain); err != nil {
  245. return err
  246. }
  247. ethereum.ChainManager().Reset()
  248. if err := ethereum.ChainManager().InsertChain(chain); err != nil {
  249. return err
  250. }
  251. clilogger.Infof("imported %d blocks\n", len(chain))
  252. return nil
  253. }