cmd.go 6.6 KB

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