cmd.go 6.5 KB

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