cmd.go 6.1 KB

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