chaincmd.go 8.1 KB

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