cmd.go 6.1 KB

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