chaincmd.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. "runtime"
  22. "strconv"
  23. "sync/atomic"
  24. "time"
  25. "github.com/ethereum/go-ethereum/cmd/utils"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/console"
  28. "github.com/ethereum/go-ethereum/core"
  29. "github.com/ethereum/go-ethereum/core/state"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/ethdb"
  32. "github.com/ethereum/go-ethereum/log"
  33. "github.com/ethereum/go-ethereum/trie"
  34. "github.com/syndtr/goleveldb/leveldb/util"
  35. "gopkg.in/urfave/cli.v1"
  36. )
  37. var (
  38. initCommand = cli.Command{
  39. Action: initGenesis,
  40. Name: "init",
  41. Usage: "Bootstrap and initialize a new genesis block",
  42. ArgsUsage: "<genesisPath>",
  43. Category: "BLOCKCHAIN COMMANDS",
  44. Description: `
  45. The init command initializes a new genesis block and definition for the network.
  46. This is a destructive action and changes the network in which you will be
  47. participating.
  48. `,
  49. }
  50. importCommand = cli.Command{
  51. Action: importChain,
  52. Name: "import",
  53. Usage: "Import a blockchain file",
  54. ArgsUsage: "<filename>",
  55. Category: "BLOCKCHAIN COMMANDS",
  56. Description: `
  57. TODO: Please write this
  58. `,
  59. }
  60. exportCommand = cli.Command{
  61. Action: exportChain,
  62. Name: "export",
  63. Usage: "Export blockchain into file",
  64. ArgsUsage: "<filename> [<blockNumFirst> <blockNumLast>]",
  65. Category: "BLOCKCHAIN COMMANDS",
  66. Description: `
  67. Requires a first argument of the file to write to.
  68. Optional second and third arguments control the first and
  69. last block to write. In this mode, the file will be appended
  70. if already existing.
  71. `,
  72. }
  73. upgradedbCommand = cli.Command{
  74. Action: upgradeDB,
  75. Name: "upgradedb",
  76. Usage: "Upgrade chainblock database",
  77. ArgsUsage: " ",
  78. Category: "BLOCKCHAIN COMMANDS",
  79. Description: `
  80. TODO: Please write this
  81. `,
  82. }
  83. removedbCommand = cli.Command{
  84. Action: removeDB,
  85. Name: "removedb",
  86. Usage: "Remove blockchain and state databases",
  87. ArgsUsage: " ",
  88. Category: "BLOCKCHAIN COMMANDS",
  89. Description: `
  90. TODO: Please write this
  91. `,
  92. }
  93. dumpCommand = cli.Command{
  94. Action: dump,
  95. Name: "dump",
  96. Usage: "Dump a specific block from storage",
  97. ArgsUsage: "[<blockHash> | <blockNum>]...",
  98. Category: "BLOCKCHAIN COMMANDS",
  99. Description: `
  100. The arguments are interpreted as block numbers or hashes.
  101. Use "ethereum dump 0" to dump the genesis block.
  102. `,
  103. }
  104. )
  105. // initGenesis will initialise the given JSON format genesis file and writes it as
  106. // the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
  107. func initGenesis(ctx *cli.Context) error {
  108. genesisPath := ctx.Args().First()
  109. if len(genesisPath) == 0 {
  110. log.Crit(fmt.Sprintf("must supply path to genesis JSON file"))
  111. }
  112. stack := makeFullNode(ctx)
  113. chaindb := utils.MakeChainDatabase(ctx, stack)
  114. genesisFile, err := os.Open(genesisPath)
  115. if err != nil {
  116. log.Crit(fmt.Sprintf("failed to read genesis file: %v", err))
  117. }
  118. defer genesisFile.Close()
  119. block, err := core.WriteGenesisBlock(chaindb, genesisFile)
  120. if err != nil {
  121. log.Crit(fmt.Sprintf("failed to write genesis block: %v", err))
  122. }
  123. log.Info(fmt.Sprintf("successfully wrote genesis block and/or chain rule set: %x", block.Hash()))
  124. return nil
  125. }
  126. func importChain(ctx *cli.Context) error {
  127. if len(ctx.Args()) != 1 {
  128. log.Crit(fmt.Sprintf("This command requires an argument."))
  129. }
  130. stack := makeFullNode(ctx)
  131. chain, chainDb := utils.MakeChain(ctx, stack)
  132. defer chainDb.Close()
  133. // Start periodically gathering memory profiles
  134. var peakMemAlloc, peakMemSys uint64
  135. go func() {
  136. stats := new(runtime.MemStats)
  137. for {
  138. runtime.ReadMemStats(stats)
  139. if atomic.LoadUint64(&peakMemAlloc) < stats.Alloc {
  140. atomic.StoreUint64(&peakMemAlloc, stats.Alloc)
  141. }
  142. if atomic.LoadUint64(&peakMemSys) < stats.Sys {
  143. atomic.StoreUint64(&peakMemSys, stats.Sys)
  144. }
  145. time.Sleep(5 * time.Second)
  146. }
  147. }()
  148. // Import the chain
  149. start := time.Now()
  150. if err := utils.ImportChain(chain, ctx.Args().First()); err != nil {
  151. log.Crit(fmt.Sprintf("Import error: %v", err))
  152. }
  153. fmt.Printf("Import done in %v.\n\n", time.Since(start))
  154. // Output pre-compaction stats mostly to see the import trashing
  155. db := chainDb.(*ethdb.LDBDatabase)
  156. stats, err := db.LDB().GetProperty("leveldb.stats")
  157. if err != nil {
  158. log.Crit(fmt.Sprintf("Failed to read database stats: %v", err))
  159. }
  160. fmt.Println(stats)
  161. fmt.Printf("Trie cache misses: %d\n", trie.CacheMisses())
  162. fmt.Printf("Trie cache unloads: %d\n\n", trie.CacheUnloads())
  163. // Print the memory statistics used by the importing
  164. mem := new(runtime.MemStats)
  165. runtime.ReadMemStats(mem)
  166. fmt.Printf("Object memory: %.3f MB current, %.3f MB peak\n", float64(mem.Alloc)/1024/1024, float64(atomic.LoadUint64(&peakMemAlloc))/1024/1024)
  167. fmt.Printf("System memory: %.3f MB current, %.3f MB peak\n", float64(mem.Sys)/1024/1024, float64(atomic.LoadUint64(&peakMemSys))/1024/1024)
  168. fmt.Printf("Allocations: %.3f million\n", float64(mem.Mallocs)/1000000)
  169. fmt.Printf("GC pause: %v\n\n", time.Duration(mem.PauseTotalNs))
  170. // Compact the entire database to more accurately measure disk io and print the stats
  171. start = time.Now()
  172. fmt.Println("Compacting entire database...")
  173. if err = db.LDB().CompactRange(util.Range{}); err != nil {
  174. log.Crit(fmt.Sprintf("Compaction failed: %v", err))
  175. }
  176. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  177. stats, err = db.LDB().GetProperty("leveldb.stats")
  178. if err != nil {
  179. log.Crit(fmt.Sprintf("Failed to read database stats: %v", err))
  180. }
  181. fmt.Println(stats)
  182. return nil
  183. }
  184. func exportChain(ctx *cli.Context) error {
  185. if len(ctx.Args()) < 1 {
  186. log.Crit(fmt.Sprintf("This command requires an argument."))
  187. }
  188. stack := makeFullNode(ctx)
  189. chain, _ := utils.MakeChain(ctx, stack)
  190. start := time.Now()
  191. var err error
  192. fp := ctx.Args().First()
  193. if len(ctx.Args()) < 3 {
  194. err = utils.ExportChain(chain, fp)
  195. } else {
  196. // This can be improved to allow for numbers larger than 9223372036854775807
  197. first, ferr := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
  198. last, lerr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
  199. if ferr != nil || lerr != nil {
  200. log.Crit(fmt.Sprintf("Export error in parsing parameters: block number not an integer\n"))
  201. }
  202. if first < 0 || last < 0 {
  203. log.Crit(fmt.Sprintf("Export error: block number must be greater than 0\n"))
  204. }
  205. err = utils.ExportAppendChain(chain, fp, uint64(first), uint64(last))
  206. }
  207. if err != nil {
  208. log.Crit(fmt.Sprintf("Export error: %v\n", err))
  209. }
  210. fmt.Printf("Export done in %v", time.Since(start))
  211. return nil
  212. }
  213. func removeDB(ctx *cli.Context) error {
  214. stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  215. dbdir := stack.ResolvePath(utils.ChainDbName(ctx))
  216. if !common.FileExist(dbdir) {
  217. fmt.Println(dbdir, "does not exist")
  218. return nil
  219. }
  220. fmt.Println(dbdir)
  221. confirm, err := console.Stdin.PromptConfirm("Remove this database?")
  222. switch {
  223. case err != nil:
  224. log.Crit(fmt.Sprintf("%v", err))
  225. case !confirm:
  226. fmt.Println("Operation aborted")
  227. default:
  228. fmt.Println("Removing...")
  229. start := time.Now()
  230. os.RemoveAll(dbdir)
  231. fmt.Printf("Removed in %v\n", time.Since(start))
  232. }
  233. return nil
  234. }
  235. func upgradeDB(ctx *cli.Context) error {
  236. log.Info(fmt.Sprint("Upgrading blockchain database"))
  237. stack := utils.MakeNode(ctx, clientIdentifier, gitCommit)
  238. chain, chainDb := utils.MakeChain(ctx, stack)
  239. bcVersion := core.GetBlockChainVersion(chainDb)
  240. if bcVersion == 0 {
  241. bcVersion = core.BlockChainVersion
  242. }
  243. // Export the current chain.
  244. filename := fmt.Sprintf("blockchain_%d_%s.chain", bcVersion, time.Now().Format("20060102_150405"))
  245. exportFile := filepath.Join(ctx.GlobalString(utils.DataDirFlag.Name), filename)
  246. if err := utils.ExportChain(chain, exportFile); err != nil {
  247. log.Crit(fmt.Sprintf("Unable to export chain for reimport %s", err))
  248. }
  249. chainDb.Close()
  250. if dir := dbDirectory(chainDb); dir != "" {
  251. os.RemoveAll(dir)
  252. }
  253. // Import the chain file.
  254. chain, chainDb = utils.MakeChain(ctx, stack)
  255. core.WriteBlockChainVersion(chainDb, core.BlockChainVersion)
  256. err := utils.ImportChain(chain, exportFile)
  257. chainDb.Close()
  258. if err != nil {
  259. log.Crit(fmt.Sprintf("Import error %v (a backup is made in %s, use the import command to import it)", err, exportFile))
  260. } else {
  261. os.Remove(exportFile)
  262. log.Info(fmt.Sprint("Import finished"))
  263. }
  264. return nil
  265. }
  266. func dbDirectory(db ethdb.Database) string {
  267. ldb, ok := db.(*ethdb.LDBDatabase)
  268. if !ok {
  269. return ""
  270. }
  271. return ldb.Path()
  272. }
  273. func dump(ctx *cli.Context) error {
  274. stack := makeFullNode(ctx)
  275. chain, chainDb := utils.MakeChain(ctx, stack)
  276. for _, arg := range ctx.Args() {
  277. var block *types.Block
  278. if hashish(arg) {
  279. block = chain.GetBlockByHash(common.HexToHash(arg))
  280. } else {
  281. num, _ := strconv.Atoi(arg)
  282. block = chain.GetBlockByNumber(uint64(num))
  283. }
  284. if block == nil {
  285. fmt.Println("{}")
  286. log.Crit(fmt.Sprintf("block not found"))
  287. } else {
  288. state, err := state.New(block.Root(), chainDb)
  289. if err != nil {
  290. log.Crit(fmt.Sprintf("could not create new state: %v", err))
  291. }
  292. fmt.Printf("%s\n", state.Dump())
  293. }
  294. }
  295. chainDb.Close()
  296. return nil
  297. }
  298. // hashish returns true for strings that look like hashes.
  299. func hashish(x string) bool {
  300. _, err := strconv.Atoi(x)
  301. return err != nil
  302. }
  303. func closeAll(dbs ...ethdb.Database) {
  304. for _, db := range dbs {
  305. db.Close()
  306. }
  307. }