cmd.go 6.1 KB

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