cmd.go 6.6 KB

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