cmd.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * @authors
  18. * Jeffrey Wilcke <i@jev.io>
  19. * Viktor Tron <viktor@ethdev.com>
  20. */
  21. package utils
  22. import (
  23. "bufio"
  24. "fmt"
  25. "io"
  26. "os"
  27. "os/signal"
  28. "regexp"
  29. "strings"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/core"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/eth"
  34. "github.com/ethereum/go-ethereum/logger"
  35. "github.com/ethereum/go-ethereum/logger/glog"
  36. "github.com/ethereum/go-ethereum/rlp"
  37. "github.com/peterh/liner"
  38. )
  39. const (
  40. importBatchSize = 2500
  41. )
  42. var interruptCallbacks = []func(os.Signal){}
  43. func openLogFile(Datadir string, filename string) *os.File {
  44. path := common.AbsolutePath(Datadir, filename)
  45. file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  46. if err != nil {
  47. panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
  48. }
  49. return file
  50. }
  51. func PromptConfirm(prompt string) (bool, error) {
  52. var (
  53. input string
  54. err error
  55. )
  56. prompt = prompt + " [y/N] "
  57. if liner.TerminalSupported() {
  58. lr := liner.NewLiner()
  59. defer lr.Close()
  60. input, err = lr.Prompt(prompt)
  61. } else {
  62. fmt.Print(prompt)
  63. input, err = bufio.NewReader(os.Stdin).ReadString('\n')
  64. fmt.Println()
  65. }
  66. if len(input) > 0 && strings.ToUpper(input[:1]) == "Y" {
  67. return true, nil
  68. } else {
  69. return false, nil
  70. }
  71. return false, err
  72. }
  73. func PromptPassword(prompt string, warnTerm bool) (string, error) {
  74. if liner.TerminalSupported() {
  75. lr := liner.NewLiner()
  76. defer lr.Close()
  77. return lr.PasswordPrompt(prompt)
  78. }
  79. if warnTerm {
  80. fmt.Println("!! Unsupported terminal, password will be echoed.")
  81. }
  82. fmt.Print(prompt)
  83. input, err := bufio.NewReader(os.Stdin).ReadString('\n')
  84. fmt.Println()
  85. return input, err
  86. }
  87. func initDataDir(Datadir string) {
  88. _, err := os.Stat(Datadir)
  89. if err != nil {
  90. if os.IsNotExist(err) {
  91. fmt.Printf("Data directory '%s' doesn't exist, creating it\n", Datadir)
  92. os.Mkdir(Datadir, 0777)
  93. }
  94. }
  95. }
  96. // Fatalf formats a message to standard error and exits the program.
  97. // The message is also printed to standard output if standard error
  98. // is redirected to a different file.
  99. func Fatalf(format string, args ...interface{}) {
  100. w := io.MultiWriter(os.Stdout, os.Stderr)
  101. outf, _ := os.Stdout.Stat()
  102. errf, _ := os.Stderr.Stat()
  103. if outf != nil && errf != nil && os.SameFile(outf, errf) {
  104. w = os.Stderr
  105. }
  106. fmt.Fprintf(w, "Fatal: "+format+"\n", args...)
  107. logger.Flush()
  108. os.Exit(1)
  109. }
  110. func StartEthereum(ethereum *eth.Ethereum) {
  111. glog.V(logger.Info).Infoln("Starting", ethereum.Name())
  112. if err := ethereum.Start(); err != nil {
  113. Fatalf("Error starting Ethereum: %v", err)
  114. }
  115. go func() {
  116. sigc := make(chan os.Signal, 1)
  117. signal.Notify(sigc, os.Interrupt)
  118. defer signal.Stop(sigc)
  119. <-sigc
  120. glog.V(logger.Info).Infoln("Got interrupt, shutting down...")
  121. go ethereum.Stop()
  122. logger.Flush()
  123. for i := 10; i > 0; i-- {
  124. <-sigc
  125. if i > 1 {
  126. glog.V(logger.Info).Infoln("Already shutting down, please be patient.")
  127. glog.V(logger.Info).Infoln("Interrupt", i-1, "more times to induce panic.")
  128. }
  129. }
  130. glog.V(logger.Error).Infof("Force quitting: this might not end so well.")
  131. panic("boom")
  132. }()
  133. }
  134. func FormatTransactionData(data string) []byte {
  135. d := common.StringToByteFunc(data, func(s string) (ret []byte) {
  136. slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
  137. for _, dataItem := range slice {
  138. d := common.FormatData(dataItem)
  139. ret = append(ret, d...)
  140. }
  141. return
  142. })
  143. return d
  144. }
  145. func ImportChain(chain *core.ChainManager, fn string) error {
  146. // Watch for Ctrl-C while the import is running.
  147. // If a signal is received, the import will stop at the next batch.
  148. interrupt := make(chan os.Signal, 1)
  149. stop := make(chan struct{})
  150. signal.Notify(interrupt, os.Interrupt)
  151. defer signal.Stop(interrupt)
  152. defer close(interrupt)
  153. go func() {
  154. if _, ok := <-interrupt; ok {
  155. glog.Info("caught interrupt during import, will stop at next batch")
  156. }
  157. close(stop)
  158. }()
  159. checkInterrupt := func() bool {
  160. select {
  161. case <-stop:
  162. return true
  163. default:
  164. return false
  165. }
  166. }
  167. glog.Infoln("Importing blockchain", fn)
  168. fh, err := os.Open(fn)
  169. if err != nil {
  170. return err
  171. }
  172. defer fh.Close()
  173. stream := rlp.NewStream(fh, 0)
  174. // Run actual the import.
  175. blocks := make(types.Blocks, importBatchSize)
  176. n := 0
  177. for batch := 0; ; batch++ {
  178. // Load a batch of RLP blocks.
  179. if checkInterrupt() {
  180. return fmt.Errorf("interrupted")
  181. }
  182. i := 0
  183. for ; i < importBatchSize; i++ {
  184. var b types.Block
  185. if err := stream.Decode(&b); err == io.EOF {
  186. break
  187. } else if err != nil {
  188. return fmt.Errorf("at block %d: %v", n, err)
  189. }
  190. blocks[i] = &b
  191. n++
  192. }
  193. if i == 0 {
  194. break
  195. }
  196. // Import the batch.
  197. if checkInterrupt() {
  198. return fmt.Errorf("interrupted")
  199. }
  200. if hasAllBlocks(chain, blocks[:i]) {
  201. glog.Infof("skipping batch %d, all blocks present [%x / %x]",
  202. batch, blocks[0].Hash().Bytes()[:4], blocks[i-1].Hash().Bytes()[:4])
  203. continue
  204. }
  205. if _, err := chain.InsertChain(blocks[:i]); err != nil {
  206. return fmt.Errorf("invalid block %d: %v", n, err)
  207. }
  208. }
  209. return nil
  210. }
  211. func hasAllBlocks(chain *core.ChainManager, bs []*types.Block) bool {
  212. for _, b := range bs {
  213. if !chain.HasBlock(b.Hash()) {
  214. return false
  215. }
  216. }
  217. return true
  218. }
  219. func ExportChain(chainmgr *core.ChainManager, fn string) error {
  220. glog.Infoln("Exporting blockchain to", fn)
  221. fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  222. if err != nil {
  223. return err
  224. }
  225. defer fh.Close()
  226. if err := chainmgr.Export(fh); err != nil {
  227. return err
  228. }
  229. glog.Infoln("Exported blockchain to", fn)
  230. return nil
  231. }
  232. func ExportAppendChain(chainmgr *core.ChainManager, fn string, first uint64, last uint64) error {
  233. glog.Infoln("Exporting blockchain to", fn)
  234. // TODO verify mode perms
  235. fh, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm)
  236. if err != nil {
  237. return err
  238. }
  239. defer fh.Close()
  240. if err := chainmgr.ExportN(fh, first, last); err != nil {
  241. return err
  242. }
  243. glog.Infoln("Exported blockchain to", fn)
  244. return nil
  245. }