cmd.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/crypto"
  28. "github.com/ethereum/go-ethereum/eth"
  29. "github.com/ethereum/go-ethereum/ethutil"
  30. "github.com/ethereum/go-ethereum/logger"
  31. "github.com/ethereum/go-ethereum/rlp"
  32. rpchttp "github.com/ethereum/go-ethereum/rpc/http"
  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. fmt.Fprintln(os.Stderr, "Fatal: ", err)
  98. status = 1
  99. }
  100. logger.Flush()
  101. os.Exit(status)
  102. }
  103. // Fatalf formats a message to standard output and exits the program.
  104. func Fatalf(format string, args ...interface{}) {
  105. fmt.Fprintf(os.Stderr, "Fatal: "+format+"\n", args...)
  106. logger.Flush()
  107. os.Exit(1)
  108. }
  109. func StartEthereum(ethereum *eth.Ethereum) {
  110. clilogger.Infoln("Starting ", ethereum.Name())
  111. if err := ethereum.Start(); err != nil {
  112. exit(err)
  113. }
  114. RegisterInterrupt(func(sig os.Signal) {
  115. ethereum.Stop()
  116. logger.Flush()
  117. })
  118. }
  119. func StartEthereumForTest(ethereum *eth.Ethereum) {
  120. clilogger.Infoln("Starting ", ethereum.Name())
  121. ethereum.StartForTest()
  122. RegisterInterrupt(func(sig os.Signal) {
  123. ethereum.Stop()
  124. logger.Flush()
  125. })
  126. }
  127. func KeyTasks(keyManager *crypto.KeyManager, KeyRing string, GenAddr bool, SecretFile string, ExportDir string, NonInteractive bool) {
  128. var err error
  129. switch {
  130. case GenAddr:
  131. if NonInteractive || confirm("This action overwrites your old private key.") {
  132. err = keyManager.Init(KeyRing, 0, true)
  133. }
  134. exit(err)
  135. case len(SecretFile) > 0:
  136. SecretFile = ethutil.ExpandHomePath(SecretFile)
  137. if NonInteractive || confirm("This action overwrites your old private key.") {
  138. err = keyManager.InitFromSecretsFile(KeyRing, 0, SecretFile)
  139. }
  140. exit(err)
  141. case len(ExportDir) > 0:
  142. err = keyManager.Init(KeyRing, 0, false)
  143. if err == nil {
  144. err = keyManager.Export(ExportDir)
  145. }
  146. exit(err)
  147. default:
  148. // Creates a keypair if none exists
  149. err = keyManager.Init(KeyRing, 0, false)
  150. if err != nil {
  151. exit(err)
  152. }
  153. }
  154. clilogger.Infof("Main address %x\n", keyManager.Address())
  155. }
  156. func StartRpc(ethereum *eth.Ethereum, RpcListenAddress string, RpcPort int) {
  157. var err error
  158. ethereum.RpcServer, err = rpchttp.NewRpcHttpServer(xeth.New(ethereum, nil), RpcListenAddress, RpcPort)
  159. if err != nil {
  160. clilogger.Errorf("Could not start RPC interface (port %v): %v", RpcPort, err)
  161. } else {
  162. go ethereum.RpcServer.Start()
  163. }
  164. }
  165. func FormatTransactionData(data string) []byte {
  166. d := ethutil.StringToByteFunc(data, func(s string) (ret []byte) {
  167. slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
  168. for _, dataItem := range slice {
  169. d := ethutil.FormatData(dataItem)
  170. ret = append(ret, d...)
  171. }
  172. return
  173. })
  174. return d
  175. }
  176. // Replay block
  177. func BlockDo(ethereum *eth.Ethereum, hash []byte) error {
  178. block := ethereum.ChainManager().GetBlock(hash)
  179. if block == nil {
  180. return fmt.Errorf("unknown block %x", hash)
  181. }
  182. parent := ethereum.ChainManager().GetBlock(block.ParentHash())
  183. statedb := state.New(parent.Root(), ethereum.StateDb())
  184. _, err := ethereum.BlockProcessor().TransitionState(statedb, parent, block, true)
  185. if err != nil {
  186. return err
  187. }
  188. return nil
  189. }
  190. func ImportChain(chain *core.ChainManager, fn string) error {
  191. fmt.Printf("importing chain '%s'\n", fn)
  192. fh, err := os.OpenFile(fn, os.O_RDONLY, os.ModePerm)
  193. if err != nil {
  194. return err
  195. }
  196. defer fh.Close()
  197. var blocks types.Blocks
  198. if err := rlp.Decode(fh, &blocks); err != nil {
  199. return err
  200. }
  201. chain.Reset()
  202. if err := chain.InsertChain(blocks); err != nil {
  203. return err
  204. }
  205. fmt.Printf("imported %d blocks\n", len(blocks))
  206. return nil
  207. }