cmd.go 6.7 KB

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