cmd.go 5.5 KB

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