cmd.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. "fmt"
  20. "io"
  21. "os"
  22. "os/signal"
  23. "regexp"
  24. "runtime"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/internal/debug"
  29. "github.com/ethereum/go-ethereum/logger"
  30. "github.com/ethereum/go-ethereum/logger/glog"
  31. "github.com/ethereum/go-ethereum/node"
  32. "github.com/ethereum/go-ethereum/rlp"
  33. )
  34. const (
  35. importBatchSize = 2500
  36. )
  37. func openLogFile(Datadir string, filename string) *os.File {
  38. path := common.AbsolutePath(Datadir, filename)
  39. file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
  40. if err != nil {
  41. panic(fmt.Sprintf("error opening log file '%s': %v", filename, err))
  42. }
  43. return file
  44. }
  45. // Fatalf formats a message to standard error and exits the program.
  46. // The message is also printed to standard output if standard error
  47. // is redirected to a different file.
  48. func Fatalf(format string, args ...interface{}) {
  49. w := io.MultiWriter(os.Stdout, os.Stderr)
  50. if runtime.GOOS == "windows" {
  51. // The SameFile check below doesn't work on Windows.
  52. // stdout is unlikely to get redirected though, so just print there.
  53. w = os.Stdout
  54. } else {
  55. outf, _ := os.Stdout.Stat()
  56. errf, _ := os.Stderr.Stat()
  57. if outf != nil && errf != nil && os.SameFile(outf, errf) {
  58. w = os.Stderr
  59. }
  60. }
  61. fmt.Fprintf(w, "Fatal: "+format+"\n", args...)
  62. logger.Flush()
  63. os.Exit(1)
  64. }
  65. func StartNode(stack *node.Node) {
  66. if err := stack.Start(); err != nil {
  67. Fatalf("Error starting protocol stack: %v", err)
  68. }
  69. go func() {
  70. sigc := make(chan os.Signal, 1)
  71. signal.Notify(sigc, os.Interrupt)
  72. defer signal.Stop(sigc)
  73. <-sigc
  74. glog.V(logger.Info).Infoln("Got interrupt, shutting down...")
  75. go stack.Stop()
  76. for i := 10; i > 0; i-- {
  77. <-sigc
  78. if i > 1 {
  79. glog.V(logger.Info).Infof("Already shutting down, interrupt %d more times for panic.", i-1)
  80. }
  81. }
  82. debug.Exit() // ensure trace and CPU profile data is flushed.
  83. debug.LoudPanic("boom")
  84. }()
  85. }
  86. func FormatTransactionData(data string) []byte {
  87. d := common.StringToByteFunc(data, func(s string) (ret []byte) {
  88. slice := regexp.MustCompile("\\n|\\s").Split(s, 1000000000)
  89. for _, dataItem := range slice {
  90. d := common.FormatData(dataItem)
  91. ret = append(ret, d...)
  92. }
  93. return
  94. })
  95. return d
  96. }
  97. func ImportChain(chain *core.BlockChain, fn string) error {
  98. // Watch for Ctrl-C while the import is running.
  99. // If a signal is received, the import will stop at the next batch.
  100. interrupt := make(chan os.Signal, 1)
  101. stop := make(chan struct{})
  102. signal.Notify(interrupt, os.Interrupt)
  103. defer signal.Stop(interrupt)
  104. defer close(interrupt)
  105. go func() {
  106. if _, ok := <-interrupt; ok {
  107. glog.Info("caught interrupt during import, will stop at next batch")
  108. }
  109. close(stop)
  110. }()
  111. checkInterrupt := func() bool {
  112. select {
  113. case <-stop:
  114. return true
  115. default:
  116. return false
  117. }
  118. }
  119. glog.Infoln("Importing blockchain ", fn)
  120. fh, err := os.Open(fn)
  121. if err != nil {
  122. return err
  123. }
  124. defer fh.Close()
  125. stream := rlp.NewStream(fh, 0)
  126. // Run actual the import.
  127. blocks := make(types.Blocks, importBatchSize)
  128. n := 0
  129. for batch := 0; ; batch++ {
  130. // Load a batch of RLP blocks.
  131. if checkInterrupt() {
  132. return fmt.Errorf("interrupted")
  133. }
  134. i := 0
  135. for ; i < importBatchSize; i++ {
  136. var b types.Block
  137. if err := stream.Decode(&b); err == io.EOF {
  138. break
  139. } else if err != nil {
  140. return fmt.Errorf("at block %d: %v", n, err)
  141. }
  142. // don't import first block
  143. if b.NumberU64() == 0 {
  144. i--
  145. continue
  146. }
  147. blocks[i] = &b
  148. n++
  149. }
  150. if i == 0 {
  151. break
  152. }
  153. // Import the batch.
  154. if checkInterrupt() {
  155. return fmt.Errorf("interrupted")
  156. }
  157. if hasAllBlocks(chain, blocks[:i]) {
  158. glog.Infof("skipping batch %d, all blocks present [%x / %x]",
  159. batch, blocks[0].Hash().Bytes()[:4], blocks[i-1].Hash().Bytes()[:4])
  160. continue
  161. }
  162. if _, err := chain.InsertChain(blocks[:i]); err != nil {
  163. return fmt.Errorf("invalid block %d: %v", n, err)
  164. }
  165. }
  166. return nil
  167. }
  168. func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
  169. for _, b := range bs {
  170. if !chain.HasBlock(b.Hash()) {
  171. return false
  172. }
  173. }
  174. return true
  175. }
  176. func ExportChain(blockchain *core.BlockChain, fn string) error {
  177. glog.Infoln("Exporting blockchain to ", fn)
  178. fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  179. if err != nil {
  180. return err
  181. }
  182. defer fh.Close()
  183. if err := blockchain.Export(fh); err != nil {
  184. return err
  185. }
  186. glog.Infoln("Exported blockchain to ", fn)
  187. return nil
  188. }
  189. func ExportAppendChain(blockchain *core.BlockChain, fn string, first uint64, last uint64) error {
  190. glog.Infoln("Exporting blockchain to ", fn)
  191. // TODO verify mode perms
  192. fh, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm)
  193. if err != nil {
  194. return err
  195. }
  196. defer fh.Close()
  197. if err := blockchain.ExportN(fh, first, last); err != nil {
  198. return err
  199. }
  200. glog.Infoln("Exported blockchain to ", fn)
  201. return nil
  202. }