cmd.go 5.5 KB

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