cmd.go 6.5 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/internal/debug"
  30. "github.com/ethereum/go-ethereum/logger"
  31. "github.com/ethereum/go-ethereum/logger/glog"
  32. "github.com/ethereum/go-ethereum/node"
  33. "github.com/ethereum/go-ethereum/rlp"
  34. "github.com/peterh/liner"
  35. )
  36. const (
  37. importBatchSize = 2500
  38. )
  39. var (
  40. interruptCallbacks = []func(os.Signal){}
  41. )
  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. input = strings.TrimRight(input, "\r\n")
  85. fmt.Println()
  86. return input, err
  87. }
  88. // Fatalf formats a message to standard error and exits the program.
  89. // The message is also printed to standard output if standard error
  90. // is redirected to a different file.
  91. func Fatalf(format string, args ...interface{}) {
  92. w := io.MultiWriter(os.Stdout, os.Stderr)
  93. outf, _ := os.Stdout.Stat()
  94. errf, _ := os.Stderr.Stat()
  95. if outf != nil && errf != nil && os.SameFile(outf, errf) {
  96. w = os.Stderr
  97. }
  98. fmt.Fprintf(w, "Fatal: "+format+"\n", args...)
  99. logger.Flush()
  100. os.Exit(1)
  101. }
  102. func StartNode(stack *node.Node) {
  103. if err := stack.Start(); err != nil {
  104. Fatalf("Error starting protocol stack: %v", err)
  105. }
  106. go func() {
  107. sigc := make(chan os.Signal, 1)
  108. signal.Notify(sigc, os.Interrupt)
  109. defer signal.Stop(sigc)
  110. <-sigc
  111. glog.V(logger.Info).Infoln("Got interrupt, shutting down...")
  112. go stack.Stop()
  113. logger.Flush()
  114. for i := 10; i > 0; i-- {
  115. <-sigc
  116. if i > 1 {
  117. glog.V(logger.Info).Infoln("Already shutting down, please be patient.")
  118. glog.V(logger.Info).Infoln("Interrupt", i-1, "more times to induce panic.")
  119. }
  120. }
  121. glog.V(logger.Error).Infof("Force quitting: this might not end so well.")
  122. debug.LoudPanic("boom")
  123. }()
  124. }
  125. func FormatTransactionData(data string) []byte {
  126. d := common.StringToByteFunc(data, func(s string) (ret []byte) {
  127. slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
  128. for _, dataItem := range slice {
  129. d := common.FormatData(dataItem)
  130. ret = append(ret, d...)
  131. }
  132. return
  133. })
  134. return d
  135. }
  136. func ImportChain(chain *core.BlockChain, fn string) error {
  137. // Watch for Ctrl-C while the import is running.
  138. // If a signal is received, the import will stop at the next batch.
  139. interrupt := make(chan os.Signal, 1)
  140. stop := make(chan struct{})
  141. signal.Notify(interrupt, os.Interrupt)
  142. defer signal.Stop(interrupt)
  143. defer close(interrupt)
  144. go func() {
  145. if _, ok := <-interrupt; ok {
  146. glog.Info("caught interrupt during import, will stop at next batch")
  147. }
  148. close(stop)
  149. }()
  150. checkInterrupt := func() bool {
  151. select {
  152. case <-stop:
  153. return true
  154. default:
  155. return false
  156. }
  157. }
  158. glog.Infoln("Importing blockchain", fn)
  159. fh, err := os.Open(fn)
  160. if err != nil {
  161. return err
  162. }
  163. defer fh.Close()
  164. stream := rlp.NewStream(fh, 0)
  165. // Run actual the import.
  166. blocks := make(types.Blocks, importBatchSize)
  167. n := 0
  168. for batch := 0; ; batch++ {
  169. // Load a batch of RLP blocks.
  170. if checkInterrupt() {
  171. return fmt.Errorf("interrupted")
  172. }
  173. i := 0
  174. for ; i < importBatchSize; i++ {
  175. var b types.Block
  176. if err := stream.Decode(&b); err == io.EOF {
  177. break
  178. } else if err != nil {
  179. return fmt.Errorf("at block %d: %v", n, err)
  180. }
  181. // don't import first block
  182. if b.NumberU64() == 0 {
  183. i--
  184. continue
  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.BlockChain, 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(blockchain *core.BlockChain, 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 := blockchain.Export(fh); err != nil {
  223. return err
  224. }
  225. glog.Infoln("Exported blockchain to", fn)
  226. return nil
  227. }
  228. func ExportAppendChain(blockchain *core.BlockChain, 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 := blockchain.ExportN(fh, first, last); err != nil {
  237. return err
  238. }
  239. glog.Infoln("Exported blockchain to", fn)
  240. return nil
  241. }