cmd.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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/big"
  23. "os"
  24. "os/signal"
  25. "regexp"
  26. "strings"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/core"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/eth"
  31. "github.com/ethereum/go-ethereum/logger"
  32. "github.com/ethereum/go-ethereum/logger/glog"
  33. "github.com/ethereum/go-ethereum/params"
  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. // 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 InitOlympic() {
  134. params.DurationLimit = big.NewInt(8)
  135. params.GenesisGasLimit = big.NewInt(3141592)
  136. params.MinGasLimit = big.NewInt(125000)
  137. params.MaximumExtraDataSize = big.NewInt(1024)
  138. NetworkIdFlag.Value = 0
  139. core.BlockReward = big.NewInt(1.5e+18)
  140. }
  141. func FormatTransactionData(data string) []byte {
  142. d := common.StringToByteFunc(data, func(s string) (ret []byte) {
  143. slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
  144. for _, dataItem := range slice {
  145. d := common.FormatData(dataItem)
  146. ret = append(ret, d...)
  147. }
  148. return
  149. })
  150. return d
  151. }
  152. func ImportChain(chain *core.ChainManager, fn string) error {
  153. // Watch for Ctrl-C while the import is running.
  154. // If a signal is received, the import will stop at the next batch.
  155. interrupt := make(chan os.Signal, 1)
  156. stop := make(chan struct{})
  157. signal.Notify(interrupt, os.Interrupt)
  158. defer signal.Stop(interrupt)
  159. defer close(interrupt)
  160. go func() {
  161. if _, ok := <-interrupt; ok {
  162. glog.Info("caught interrupt during import, will stop at next batch")
  163. }
  164. close(stop)
  165. }()
  166. checkInterrupt := func() bool {
  167. select {
  168. case <-stop:
  169. return true
  170. default:
  171. return false
  172. }
  173. }
  174. glog.Infoln("Importing blockchain", fn)
  175. fh, err := os.Open(fn)
  176. if err != nil {
  177. return err
  178. }
  179. defer fh.Close()
  180. stream := rlp.NewStream(fh, 0)
  181. // Run actual the import.
  182. blocks := make(types.Blocks, importBatchSize)
  183. n := 0
  184. for batch := 0; ; batch++ {
  185. // Load a batch of RLP blocks.
  186. if checkInterrupt() {
  187. return fmt.Errorf("interrupted")
  188. }
  189. i := 0
  190. for ; i < importBatchSize; i++ {
  191. var b types.Block
  192. if err := stream.Decode(&b); err == io.EOF {
  193. break
  194. } else if err != nil {
  195. return fmt.Errorf("at block %d: %v", n, err)
  196. }
  197. // don't import first block
  198. if b.NumberU64() == 0 {
  199. i--
  200. continue
  201. }
  202. blocks[i] = &b
  203. n++
  204. }
  205. if i == 0 {
  206. break
  207. }
  208. // Import the batch.
  209. if checkInterrupt() {
  210. return fmt.Errorf("interrupted")
  211. }
  212. if hasAllBlocks(chain, blocks[:i]) {
  213. glog.Infof("skipping batch %d, all blocks present [%x / %x]",
  214. batch, blocks[0].Hash().Bytes()[:4], blocks[i-1].Hash().Bytes()[:4])
  215. continue
  216. }
  217. if _, err := chain.InsertChain(blocks[:i]); err != nil {
  218. return fmt.Errorf("invalid block %d: %v", n, err)
  219. }
  220. }
  221. return nil
  222. }
  223. func hasAllBlocks(chain *core.ChainManager, bs []*types.Block) bool {
  224. for _, b := range bs {
  225. if !chain.HasBlock(b.Hash()) {
  226. return false
  227. }
  228. }
  229. return true
  230. }
  231. func ExportChain(chainmgr *core.ChainManager, fn string) error {
  232. glog.Infoln("Exporting blockchain to", fn)
  233. fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  234. if err != nil {
  235. return err
  236. }
  237. defer fh.Close()
  238. if err := chainmgr.Export(fh); err != nil {
  239. return err
  240. }
  241. glog.Infoln("Exported blockchain to", fn)
  242. return nil
  243. }
  244. func ExportAppendChain(chainmgr *core.ChainManager, fn string, first uint64, last uint64) error {
  245. glog.Infoln("Exporting blockchain to", fn)
  246. // TODO verify mode perms
  247. fh, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm)
  248. if err != nil {
  249. return err
  250. }
  251. defer fh.Close()
  252. if err := chainmgr.ExportN(fh, first, last); err != nil {
  253. return err
  254. }
  255. glog.Infoln("Exported blockchain to", fn)
  256. return nil
  257. }