cmd.go 5.8 KB

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