cmd.go 5.4 KB

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