cmd.go 5.3 KB

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