cmd.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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("Got interrupt, shutting down...")
  65. go stack.Stop()
  66. for i := 10; i > 0; i-- {
  67. <-sigc
  68. if i > 1 {
  69. log.Warn("Already shutting down, interrupt more to panic.", "times", 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("Interrupted during import, stopping 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("Importing blockchain", "file", 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("Skipping batch as all blocks present", "batch", batch, "first", blocks[0].Hash(), "last", blocks[i-1].Hash())
  144. continue
  145. }
  146. if _, err := chain.InsertChain(blocks[:i]); err != nil {
  147. return fmt.Errorf("invalid block %d: %v", n, err)
  148. }
  149. }
  150. return nil
  151. }
  152. func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
  153. for _, b := range bs {
  154. if !chain.HasBlock(b.Hash(), b.NumberU64()) {
  155. return false
  156. }
  157. }
  158. return true
  159. }
  160. func ExportChain(blockchain *core.BlockChain, fn string) error {
  161. log.Info("Exporting blockchain", "file", fn)
  162. fh, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  163. if err != nil {
  164. return err
  165. }
  166. defer fh.Close()
  167. var writer io.Writer = fh
  168. if strings.HasSuffix(fn, ".gz") {
  169. writer = gzip.NewWriter(writer)
  170. defer writer.(*gzip.Writer).Close()
  171. }
  172. if err := blockchain.Export(writer); err != nil {
  173. return err
  174. }
  175. log.Info("Exported blockchain", "file", fn)
  176. return nil
  177. }
  178. func ExportAppendChain(blockchain *core.BlockChain, fn string, first uint64, last uint64) error {
  179. log.Info("Exporting blockchain", "file", fn)
  180. // TODO verify mode perms
  181. fh, err := os.OpenFile(fn, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm)
  182. if err != nil {
  183. return err
  184. }
  185. defer fh.Close()
  186. var writer io.Writer = fh
  187. if strings.HasSuffix(fn, ".gz") {
  188. writer = gzip.NewWriter(writer)
  189. defer writer.(*gzip.Writer).Close()
  190. }
  191. if err := blockchain.ExportN(writer, first, last); err != nil {
  192. return err
  193. }
  194. log.Info("Exported blockchain to", "file", fn)
  195. return nil
  196. }