chaincmd.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. // Copyright 2015 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 main
  17. import (
  18. "fmt"
  19. "os"
  20. "path/filepath"
  21. "strconv"
  22. "time"
  23. "github.com/ethereum/go-ethereum/cmd/utils"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/console"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/state"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/ethdb"
  30. "github.com/ethereum/go-ethereum/logger/glog"
  31. "github.com/ethereum/go-ethereum/trie"
  32. "github.com/syndtr/goleveldb/leveldb/util"
  33. "gopkg.in/urfave/cli.v1"
  34. )
  35. var (
  36. importCommand = cli.Command{
  37. Action: importChain,
  38. Name: "import",
  39. Usage: `import a blockchain file`,
  40. }
  41. exportCommand = cli.Command{
  42. Action: exportChain,
  43. Name: "export",
  44. Usage: `export blockchain into file`,
  45. Description: `
  46. Requires a first argument of the file to write to.
  47. Optional second and third arguments control the first and
  48. last block to write. In this mode, the file will be appended
  49. if already existing.
  50. `,
  51. }
  52. upgradedbCommand = cli.Command{
  53. Action: upgradeDB,
  54. Name: "upgradedb",
  55. Usage: "upgrade chainblock database",
  56. }
  57. removedbCommand = cli.Command{
  58. Action: removeDB,
  59. Name: "removedb",
  60. Usage: "Remove blockchain and state databases",
  61. }
  62. dumpCommand = cli.Command{
  63. Action: dump,
  64. Name: "dump",
  65. Usage: `dump a specific block from storage`,
  66. Description: `
  67. The arguments are interpreted as block numbers or hashes.
  68. Use "ethereum dump 0" to dump the genesis block.
  69. `,
  70. }
  71. )
  72. func importChain(ctx *cli.Context) error {
  73. if len(ctx.Args()) != 1 {
  74. utils.Fatalf("This command requires an argument.")
  75. }
  76. if ctx.GlobalBool(utils.TestNetFlag.Name) {
  77. state.StartingNonce = 1048576 // (2**20)
  78. }
  79. stack := makeFullNode(ctx)
  80. chain, chainDb := utils.MakeChain(ctx, stack)
  81. defer chainDb.Close()
  82. // Import the chain
  83. start := time.Now()
  84. if err := utils.ImportChain(chain, ctx.Args().First()); err != nil {
  85. utils.Fatalf("Import error: %v", err)
  86. }
  87. fmt.Printf("Import done in %v.\n", time.Since(start))
  88. if db, ok := chainDb.(*ethdb.LDBDatabase); ok {
  89. // Output pre-compaction stats mostly to see the import trashing
  90. stats, err := db.LDB().GetProperty("leveldb.stats")
  91. if err != nil {
  92. utils.Fatalf("Failed to read database stats: %v", err)
  93. }
  94. fmt.Println(stats)
  95. // Compact the entire database to more accurately measure disk io and print the stats
  96. start = time.Now()
  97. fmt.Println("Compacting entire database...")
  98. if err = db.LDB().CompactRange(util.Range{}); err != nil {
  99. utils.Fatalf("Compaction failed: %v", err)
  100. }
  101. fmt.Printf("Compaction done in %v.\n", time.Since(start))
  102. stats, err = db.LDB().GetProperty("leveldb.stats")
  103. if err != nil {
  104. utils.Fatalf("Failed to read database stats: %v", err)
  105. }
  106. fmt.Println(stats)
  107. fmt.Println("Trie cache misses:", trie.CacheMisses())
  108. }
  109. return nil
  110. }
  111. func exportChain(ctx *cli.Context) error {
  112. if len(ctx.Args()) < 1 {
  113. utils.Fatalf("This command requires an argument.")
  114. }
  115. stack := makeFullNode(ctx)
  116. chain, _ := utils.MakeChain(ctx, stack)
  117. start := time.Now()
  118. var err error
  119. fp := ctx.Args().First()
  120. if len(ctx.Args()) < 3 {
  121. err = utils.ExportChain(chain, fp)
  122. } else {
  123. // This can be improved to allow for numbers larger than 9223372036854775807
  124. first, ferr := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
  125. last, lerr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
  126. if ferr != nil || lerr != nil {
  127. utils.Fatalf("Export error in parsing parameters: block number not an integer\n")
  128. }
  129. if first < 0 || last < 0 {
  130. utils.Fatalf("Export error: block number must be greater than 0\n")
  131. }
  132. err = utils.ExportAppendChain(chain, fp, uint64(first), uint64(last))
  133. }
  134. if err != nil {
  135. utils.Fatalf("Export error: %v\n", err)
  136. }
  137. fmt.Printf("Export done in %v", time.Since(start))
  138. return nil
  139. }
  140. func removeDB(ctx *cli.Context) error {
  141. stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  142. dbdir := stack.ResolvePath("chaindata")
  143. if !common.FileExist(dbdir) {
  144. fmt.Println(dbdir, "does not exist")
  145. return nil
  146. }
  147. fmt.Println(dbdir)
  148. confirm, err := console.Stdin.PromptConfirm("Remove this database?")
  149. switch {
  150. case err != nil:
  151. utils.Fatalf("%v", err)
  152. case !confirm:
  153. fmt.Println("Operation aborted")
  154. default:
  155. fmt.Println("Removing...")
  156. start := time.Now()
  157. os.RemoveAll(dbdir)
  158. fmt.Printf("Removed in %v\n", time.Since(start))
  159. }
  160. return nil
  161. }
  162. func upgradeDB(ctx *cli.Context) error {
  163. glog.Infoln("Upgrading blockchain database")
  164. stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  165. chain, chainDb := utils.MakeChain(ctx, stack)
  166. bcVersion := core.GetBlockChainVersion(chainDb)
  167. if bcVersion == 0 {
  168. bcVersion = core.BlockChainVersion
  169. }
  170. // Export the current chain.
  171. filename := fmt.Sprintf("blockchain_%d_%s.chain", bcVersion, time.Now().Format("20060102_150405"))
  172. exportFile := filepath.Join(ctx.GlobalString(utils.DataDirFlag.Name), filename)
  173. if err := utils.ExportChain(chain, exportFile); err != nil {
  174. utils.Fatalf("Unable to export chain for reimport %s", err)
  175. }
  176. chainDb.Close()
  177. if dir := dbDirectory(chainDb); dir != "" {
  178. os.RemoveAll(dir)
  179. }
  180. // Import the chain file.
  181. chain, chainDb = utils.MakeChain(ctx, stack)
  182. core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
  183. err := utils.ImportChain(chain, exportFile)
  184. chainDb.Close()
  185. if err != nil {
  186. utils.Fatalf("Import error %v (a backup is made in %s, use the import command to import it)", err, exportFile)
  187. } else {
  188. os.Remove(exportFile)
  189. glog.Infoln("Import finished")
  190. }
  191. return nil
  192. }
  193. func dbDirectory(db ethdb.Database) string {
  194. ldb, ok := db.(*ethdb.LDBDatabase)
  195. if !ok {
  196. return ""
  197. }
  198. return ldb.Path()
  199. }
  200. func dump(ctx *cli.Context) error {
  201. stack := makeFullNode(ctx)
  202. chain, chainDb := utils.MakeChain(ctx, stack)
  203. for _, arg := range ctx.Args() {
  204. var block *types.Block
  205. if hashish(arg) {
  206. block = chain.GetBlockByHash(common.HexToHash(arg))
  207. } else {
  208. num, _ := strconv.Atoi(arg)
  209. block = chain.GetBlockByNumber(uint64(num))
  210. }
  211. if block == nil {
  212. fmt.Println("{}")
  213. utils.Fatalf("block not found")
  214. } else {
  215. state, err := state.New(block.Root(), chainDb)
  216. if err != nil {
  217. utils.Fatalf("could not create new state: %v", err)
  218. }
  219. fmt.Printf("%s\n", state.Dump())
  220. }
  221. }
  222. chainDb.Close()
  223. return nil
  224. }
  225. // hashish returns true for strings that look like hashes.
  226. func hashish(x string) bool {
  227. _, err := strconv.Atoi(x)
  228. return err != nil
  229. }
  230. func closeAll(dbs ...ethdb.Database) {
  231. for _, db := range dbs {
  232. db.Close()
  233. }
  234. }