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