cmd.go 6.5 KB

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