cmd.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /*
  2. This file is part of go-ethereum
  3. go-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. go-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /**
  15. * @authors
  16. * Jeffrey Wilcke <i@jev.io>
  17. * Viktor Tron <viktor@ethdev.com>
  18. */
  19. package utils
  20. import (
  21. "bufio"
  22. "fmt"
  23. "io"
  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/rlp"
  35. "github.com/peterh/liner"
  36. )
  37. const (
  38. importBatchSize = 2500
  39. )
  40. var interruptCallbacks = []func(os.Signal){}
  41. // Register interrupt handlers callbacks
  42. func RegisterInterrupt(cb func(os.Signal)) {
  43. interruptCallbacks = append(interruptCallbacks, cb)
  44. }
  45. // go routine that call interrupt handlers in order of registering
  46. func HandleInterrupt() {
  47. c := make(chan os.Signal, 1)
  48. go func() {
  49. signal.Notify(c, os.Interrupt)
  50. for sig := range c {
  51. glog.V(logger.Error).Infof("Shutting down (%v) ... \n", sig)
  52. RunInterruptCallbacks(sig)
  53. }
  54. }()
  55. }
  56. func RunInterruptCallbacks(sig os.Signal) {
  57. for _, cb := range interruptCallbacks {
  58. cb(sig)
  59. }
  60. }
  61. func openLogFile(Datadir string, filename string) *os.File {
  62. path := common.AbsolutePath(Datadir, filename)
  63. file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  64. if err != nil {
  65. panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
  66. }
  67. return file
  68. }
  69. func PromptConfirm(prompt string) (bool, error) {
  70. var (
  71. input string
  72. err error
  73. )
  74. prompt = prompt + " [y/N] "
  75. if liner.TerminalSupported() {
  76. lr := liner.NewLiner()
  77. defer lr.Close()
  78. input, err = lr.Prompt(prompt)
  79. } else {
  80. fmt.Print(prompt)
  81. input, err = bufio.NewReader(os.Stdin).ReadString('\n')
  82. fmt.Println()
  83. }
  84. if len(input) > 0 && strings.ToUpper(input[:1]) == "Y" {
  85. return true, nil
  86. } else {
  87. return false, nil
  88. }
  89. return false, err
  90. }
  91. func PromptPassword(prompt string, warnTerm bool) (string, error) {
  92. if liner.TerminalSupported() {
  93. lr := liner.NewLiner()
  94. defer lr.Close()
  95. return lr.PasswordPrompt(prompt)
  96. }
  97. if warnTerm {
  98. fmt.Println("!! Unsupported terminal, password will be echoed.")
  99. }
  100. fmt.Print(prompt)
  101. input, err := bufio.NewReader(os.Stdin).ReadString('\n')
  102. fmt.Println()
  103. return input, err
  104. }
  105. func initDataDir(Datadir string) {
  106. _, err := os.Stat(Datadir)
  107. if err != nil {
  108. if os.IsNotExist(err) {
  109. fmt.Printf("Data directory '%s' doesn't exist, creating it\n", Datadir)
  110. os.Mkdir(Datadir, 0777)
  111. }
  112. }
  113. }
  114. // Fatalf formats a message to standard error and exits the program.
  115. // The message is also printed to standard output if standard error
  116. // is redirected to a different file.
  117. func Fatalf(format string, args ...interface{}) {
  118. w := io.MultiWriter(os.Stdout, os.Stderr)
  119. outf, _ := os.Stdout.Stat()
  120. errf, _ := os.Stderr.Stat()
  121. if outf != nil && errf != nil && os.SameFile(outf, errf) {
  122. w = os.Stderr
  123. }
  124. fmt.Fprintf(w, "Fatal: "+format+"\n", args...)
  125. logger.Flush()
  126. os.Exit(1)
  127. }
  128. func StartEthereum(ethereum *eth.Ethereum) {
  129. glog.V(logger.Info).Infoln("Starting", ethereum.Name())
  130. if err := ethereum.Start(); err != nil {
  131. Fatalf("Error starting Ethereum: %v", err)
  132. }
  133. RegisterInterrupt(func(sig os.Signal) {
  134. ethereum.Stop()
  135. logger.Flush()
  136. })
  137. }
  138. func StartEthereumForTest(ethereum *eth.Ethereum) {
  139. glog.V(logger.Info).Infoln("Starting ", ethereum.Name())
  140. ethereum.StartForTest()
  141. RegisterInterrupt(func(sig os.Signal) {
  142. ethereum.Stop()
  143. logger.Flush()
  144. })
  145. }
  146. func FormatTransactionData(data string) []byte {
  147. d := common.StringToByteFunc(data, func(s string) (ret []byte) {
  148. slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
  149. for _, dataItem := range slice {
  150. d := common.FormatData(dataItem)
  151. ret = append(ret, d...)
  152. }
  153. return
  154. })
  155. return d
  156. }
  157. func ImportChain(chain *core.ChainManager, fn string) error {
  158. // Watch for Ctrl-C while the import is running.
  159. // If a signal is received, the import will stop at the next batch.
  160. interrupt := make(chan os.Signal, 1)
  161. stop := make(chan struct{})
  162. signal.Notify(interrupt, os.Interrupt)
  163. defer signal.Stop(interrupt)
  164. defer close(interrupt)
  165. go func() {
  166. if _, ok := <-interrupt; ok {
  167. glog.Info("caught interrupt during import, will stop at next batch")
  168. }
  169. close(stop)
  170. }()
  171. checkInterrupt := func() bool {
  172. select {
  173. case <-stop:
  174. return true
  175. default:
  176. return false
  177. }
  178. }
  179. glog.Infoln("Importing blockchain", fn)
  180. fh, err := os.Open(fn)
  181. if err != nil {
  182. return err
  183. }
  184. defer fh.Close()
  185. stream := rlp.NewStream(fh, 0)
  186. // Run actual the import.
  187. blocks := make(types.Blocks, importBatchSize)
  188. n := 0
  189. for batch := 0; ; batch++ {
  190. // Load a batch of RLP blocks.
  191. if checkInterrupt() {
  192. return fmt.Errorf("interrupted")
  193. }
  194. i := 0
  195. for ; i < importBatchSize; i++ {
  196. var b types.Block
  197. if err := stream.Decode(&b); err == io.EOF {
  198. break
  199. } else if err != nil {
  200. return fmt.Errorf("at block %d: %v", n, err)
  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. }