cmd.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. "regexp"
  25. "github.com/ethereum/go-ethereum/core/types"
  26. "github.com/ethereum/go-ethereum/crypto"
  27. "github.com/ethereum/go-ethereum/eth"
  28. "github.com/ethereum/go-ethereum/ethutil"
  29. "github.com/ethereum/go-ethereum/logger"
  30. "github.com/ethereum/go-ethereum/rlp"
  31. rpchttp "github.com/ethereum/go-ethereum/rpc/http"
  32. rpcws "github.com/ethereum/go-ethereum/rpc/ws"
  33. "github.com/ethereum/go-ethereum/state"
  34. "github.com/ethereum/go-ethereum/xeth"
  35. )
  36. var clilogger = logger.NewLogger("CLI")
  37. var interruptCallbacks = []func(os.Signal){}
  38. // Register interrupt handlers callbacks
  39. func RegisterInterrupt(cb func(os.Signal)) {
  40. interruptCallbacks = append(interruptCallbacks, cb)
  41. }
  42. // go routine that call interrupt handlers in order of registering
  43. func HandleInterrupt() {
  44. c := make(chan os.Signal, 1)
  45. go func() {
  46. signal.Notify(c, os.Interrupt)
  47. for sig := range c {
  48. clilogger.Errorf("Shutting down (%v) ... \n", sig)
  49. RunInterruptCallbacks(sig)
  50. }
  51. }()
  52. }
  53. func RunInterruptCallbacks(sig os.Signal) {
  54. for _, cb := range interruptCallbacks {
  55. cb(sig)
  56. }
  57. }
  58. func openLogFile(Datadir string, filename string) *os.File {
  59. path := ethutil.AbsolutePath(Datadir, filename)
  60. file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  61. if err != nil {
  62. panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
  63. }
  64. return file
  65. }
  66. func confirm(message string) bool {
  67. fmt.Println(message, "Are you sure? (y/n)")
  68. var r string
  69. fmt.Scanln(&r)
  70. for ; ; fmt.Scanln(&r) {
  71. if r == "n" || r == "y" {
  72. break
  73. } else {
  74. fmt.Printf("Yes or no? (%s)", r)
  75. }
  76. }
  77. return r == "y"
  78. }
  79. func initDataDir(Datadir string) {
  80. _, err := os.Stat(Datadir)
  81. if err != nil {
  82. if os.IsNotExist(err) {
  83. fmt.Printf("Data directory '%s' doesn't exist, creating it\n", Datadir)
  84. os.Mkdir(Datadir, 0777)
  85. }
  86. }
  87. }
  88. func InitConfig(vmType int, ConfigFile string, Datadir string, EnvPrefix string) *ethutil.ConfigManager {
  89. initDataDir(Datadir)
  90. cfg := ethutil.ReadConfig(ConfigFile, Datadir, EnvPrefix)
  91. cfg.VmType = vmType
  92. return cfg
  93. }
  94. func exit(err error) {
  95. status := 0
  96. if err != nil {
  97. clilogger.Errorln("Fatal: ", err)
  98. status = 1
  99. }
  100. logger.Flush()
  101. os.Exit(status)
  102. }
  103. func StartEthereum(ethereum *eth.Ethereum) {
  104. clilogger.Infoln("Starting ", ethereum.Name())
  105. if err := ethereum.Start(); err != nil {
  106. exit(err)
  107. }
  108. RegisterInterrupt(func(sig os.Signal) {
  109. ethereum.Stop()
  110. logger.Flush()
  111. })
  112. }
  113. func KeyTasks(keyManager *crypto.KeyManager, KeyRing string, GenAddr bool, SecretFile string, ExportDir string, NonInteractive bool) {
  114. var err error
  115. switch {
  116. case GenAddr:
  117. if NonInteractive || confirm("This action overwrites your old private key.") {
  118. err = keyManager.Init(KeyRing, 0, true)
  119. }
  120. exit(err)
  121. case len(SecretFile) > 0:
  122. SecretFile = ethutil.ExpandHomePath(SecretFile)
  123. if NonInteractive || confirm("This action overwrites your old private key.") {
  124. err = keyManager.InitFromSecretsFile(KeyRing, 0, SecretFile)
  125. }
  126. exit(err)
  127. case len(ExportDir) > 0:
  128. err = keyManager.Init(KeyRing, 0, false)
  129. if err == nil {
  130. err = keyManager.Export(ExportDir)
  131. }
  132. exit(err)
  133. default:
  134. // Creates a keypair if none exists
  135. err = keyManager.Init(KeyRing, 0, false)
  136. if err != nil {
  137. exit(err)
  138. }
  139. }
  140. clilogger.Infof("Main address %x\n", keyManager.Address())
  141. }
  142. func StartRpc(ethereum *eth.Ethereum, RpcPort int) {
  143. var err error
  144. ethereum.RpcServer, err = rpchttp.NewRpcHttpServer(xeth.New(ethereum), RpcPort)
  145. if err != nil {
  146. clilogger.Errorf("Could not start RPC interface (port %v): %v", RpcPort, err)
  147. } else {
  148. go ethereum.RpcServer.Start()
  149. }
  150. }
  151. func StartWebSockets(eth *eth.Ethereum, wsPort int) {
  152. clilogger.Infoln("Starting WebSockets")
  153. var err error
  154. eth.WsServer, err = rpcws.NewWebSocketServer(xeth.New(eth), wsPort)
  155. if err != nil {
  156. clilogger.Errorf("Could not start RPC interface (port %v): %v", wsPort, err)
  157. } else {
  158. go eth.WsServer.Start()
  159. }
  160. }
  161. func FormatTransactionData(data string) []byte {
  162. d := ethutil.StringToByteFunc(data, func(s string) (ret []byte) {
  163. slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
  164. for _, dataItem := range slice {
  165. d := ethutil.FormatData(dataItem)
  166. ret = append(ret, d...)
  167. }
  168. return
  169. })
  170. return d
  171. }
  172. // Replay block
  173. func BlockDo(ethereum *eth.Ethereum, hash []byte) error {
  174. block := ethereum.ChainManager().GetBlock(hash)
  175. if block == nil {
  176. return fmt.Errorf("unknown block %x", hash)
  177. }
  178. parent := ethereum.ChainManager().GetBlock(block.ParentHash())
  179. statedb := state.New(parent.Root(), ethereum.Db())
  180. _, err := ethereum.BlockProcessor().TransitionState(statedb, parent, block, true)
  181. if err != nil {
  182. return err
  183. }
  184. return nil
  185. }
  186. func ImportChain(ethereum *eth.Ethereum, fn string) error {
  187. clilogger.Infof("importing chain '%s'\n", fn)
  188. fh, err := os.OpenFile(fn, os.O_RDONLY, os.ModePerm)
  189. if err != nil {
  190. return err
  191. }
  192. defer fh.Close()
  193. var chain types.Blocks
  194. if err := rlp.Decode(fh, &chain); err != nil {
  195. return err
  196. }
  197. ethereum.ChainManager().Reset()
  198. if err := ethereum.ChainManager().InsertChain(chain); err != nil {
  199. return err
  200. }
  201. clilogger.Infof("imported %d blocks\n", len(chain))
  202. return nil
  203. }