cmd.go 5.8 KB

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