cmd.go 7.1 KB

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