chaincmd.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. fmt.Printf("Trie cache misses: %d\n", trie.CacheMisses())
  96. fmt.Printf("Trie cache unloads: %d\n\n", trie.CacheUnloads())
  97. // Compact the entire database to more accurately measure disk io and print the stats
  98. start = time.Now()
  99. fmt.Println("Compacting entire database...")
  100. if err = db.LDB().CompactRange(util.Range{}); err != nil {
  101. utils.Fatalf("Compaction failed: %v", err)
  102. }
  103. fmt.Printf("Compaction done in %v.\n", time.Since(start))
  104. stats, err = db.LDB().GetProperty("leveldb.stats")
  105. if err != nil {
  106. utils.Fatalf("Failed to read database stats: %v", err)
  107. }
  108. fmt.Println(stats)
  109. }
  110. return nil
  111. }
  112. func exportChain(ctx *cli.Context) error {
  113. if len(ctx.Args()) < 1 {
  114. utils.Fatalf("This command requires an argument.")
  115. }
  116. stack := makeFullNode(ctx)
  117. chain, _ := utils.MakeChain(ctx, stack)
  118. start := time.Now()
  119. var err error
  120. fp := ctx.Args().First()
  121. if len(ctx.Args()) < 3 {
  122. err = utils.ExportChain(chain, fp)
  123. } else {
  124. // This can be improved to allow for numbers larger than 9223372036854775807
  125. first, ferr := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
  126. last, lerr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
  127. if ferr != nil || lerr != nil {
  128. utils.Fatalf("Export error in parsing parameters: block number not an integer\n")
  129. }
  130. if first < 0 || last < 0 {
  131. utils.Fatalf("Export error: block number must be greater than 0\n")
  132. }
  133. err = utils.ExportAppendChain(chain, fp, uint64(first), uint64(last))
  134. }
  135. if err != nil {
  136. utils.Fatalf("Export error: %v\n", err)
  137. }
  138. fmt.Printf("Export done in %v", time.Since(start))
  139. return nil
  140. }
  141. func removeDB(ctx *cli.Context) error {
  142. stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  143. dbdir := stack.ResolvePath("chaindata")
  144. if !common.FileExist(dbdir) {
  145. fmt.Println(dbdir, "does not exist")
  146. return nil
  147. }
  148. fmt.Println(dbdir)
  149. confirm, err := console.Stdin.PromptConfirm("Remove this database?")
  150. switch {
  151. case err != nil:
  152. utils.Fatalf("%v", err)
  153. case !confirm:
  154. fmt.Println("Operation aborted")
  155. default:
  156. fmt.Println("Removing...")
  157. start := time.Now()
  158. os.RemoveAll(dbdir)
  159. fmt.Printf("Removed in %v\n", time.Since(start))
  160. }
  161. return nil
  162. }
  163. func upgradeDB(ctx *cli.Context) error {
  164. glog.Infoln("Upgrading blockchain database")
  165. stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  166. chain, chainDb := utils.MakeChain(ctx, stack)
  167. bcVersion := core.GetBlockChainVersion(chainDb)
  168. if bcVersion == 0 {
  169. bcVersion = core.BlockChainVersion
  170. }
  171. // Export the current chain.
  172. filename := fmt.Sprintf("blockchain_%d_%s.chain", bcVersion, time.Now().Format("20060102_150405"))
  173. exportFile := filepath.Join(ctx.GlobalString(utils.DataDirFlag.Name), filename)
  174. if err := utils.ExportChain(chain, exportFile); err != nil {
  175. utils.Fatalf("Unable to export chain for reimport %s", err)
  176. }
  177. chainDb.Close()
  178. if dir := dbDirectory(chainDb); dir != "" {
  179. os.RemoveAll(dir)
  180. }
  181. // Import the chain file.
  182. chain, chainDb = utils.MakeChain(ctx, stack)
  183. core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
  184. err := utils.ImportChain(chain, exportFile)
  185. chainDb.Close()
  186. if err != nil {
  187. utils.Fatalf("Import error %v (a backup is made in %s, use the import command to import it)", err, exportFile)
  188. } else {
  189. os.Remove(exportFile)
  190. glog.Infoln("Import finished")
  191. }
  192. return nil
  193. }
  194. func dbDirectory(db ethdb.Database) string {
  195. ldb, ok := db.(*ethdb.LDBDatabase)
  196. if !ok {
  197. return ""
  198. }
  199. return ldb.Path()
  200. }
  201. func dump(ctx *cli.Context) error {
  202. stack := makeFullNode(ctx)
  203. chain, chainDb := utils.MakeChain(ctx, stack)
  204. for _, arg := range ctx.Args() {
  205. var block *types.Block
  206. if hashish(arg) {
  207. block = chain.GetBlockByHash(common.HexToHash(arg))
  208. } else {
  209. num, _ := strconv.Atoi(arg)
  210. block = chain.GetBlockByNumber(uint64(num))
  211. }
  212. if block == nil {
  213. fmt.Println("{}")
  214. utils.Fatalf("block not found")
  215. } else {
  216. state, err := state.New(block.Root(), chainDb)
  217. if err != nil {
  218. utils.Fatalf("could not create new state: %v", err)
  219. }
  220. fmt.Printf("%s\n", state.Dump())
  221. }
  222. }
  223. chainDb.Close()
  224. return nil
  225. }
  226. // hashish returns true for strings that look like hashes.
  227. func hashish(x string) bool {
  228. _, err := strconv.Atoi(x)
  229. return err != nil
  230. }
  231. func closeAll(dbs ...ethdb.Database) {
  232. for _, db := range dbs {
  233. db.Close()
  234. }
  235. }