chaincmd.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. "encoding/json"
  19. "fmt"
  20. "os"
  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/rawdb"
  30. "github.com/ethereum/go-ethereum/core/state"
  31. "github.com/ethereum/go-ethereum/core/types"
  32. "github.com/ethereum/go-ethereum/eth/downloader"
  33. "github.com/ethereum/go-ethereum/event"
  34. "github.com/ethereum/go-ethereum/log"
  35. "github.com/ethereum/go-ethereum/trie"
  36. "gopkg.in/urfave/cli.v1"
  37. )
  38. var (
  39. initCommand = cli.Command{
  40. Action: utils.MigrateFlags(initGenesis),
  41. Name: "init",
  42. Usage: "Bootstrap and initialize a new genesis block",
  43. ArgsUsage: "<genesisPath>",
  44. Flags: []cli.Flag{
  45. utils.DataDirFlag,
  46. },
  47. Category: "BLOCKCHAIN COMMANDS",
  48. Description: `
  49. The init command initializes a new genesis block and definition for the network.
  50. This is a destructive action and changes the network in which you will be
  51. participating.
  52. It expects the genesis file as argument.`,
  53. }
  54. importCommand = cli.Command{
  55. Action: utils.MigrateFlags(importChain),
  56. Name: "import",
  57. Usage: "Import a blockchain file",
  58. ArgsUsage: "<filename> (<filename 2> ... <filename N>) ",
  59. Flags: []cli.Flag{
  60. utils.DataDirFlag,
  61. utils.CacheFlag,
  62. utils.SyncModeFlag,
  63. utils.GCModeFlag,
  64. utils.CacheDatabaseFlag,
  65. utils.CacheGCFlag,
  66. },
  67. Category: "BLOCKCHAIN COMMANDS",
  68. Description: `
  69. The import command imports blocks from an RLP-encoded form. The form can be one file
  70. with several RLP-encoded blocks, or several files can be used.
  71. If only one file is used, import error will result in failure. If several files are used,
  72. processing will proceed even if an individual RLP-file import failure occurs.`,
  73. }
  74. exportCommand = cli.Command{
  75. Action: utils.MigrateFlags(exportChain),
  76. Name: "export",
  77. Usage: "Export blockchain into file",
  78. ArgsUsage: "<filename> [<blockNumFirst> <blockNumLast>]",
  79. Flags: []cli.Flag{
  80. utils.DataDirFlag,
  81. utils.CacheFlag,
  82. utils.SyncModeFlag,
  83. },
  84. Category: "BLOCKCHAIN COMMANDS",
  85. Description: `
  86. Requires a first argument of the file to write to.
  87. Optional second and third arguments control the first and
  88. last block to write. In this mode, the file will be appended
  89. if already existing. If the file ends with .gz, the output will
  90. be gzipped.`,
  91. }
  92. importPreimagesCommand = cli.Command{
  93. Action: utils.MigrateFlags(importPreimages),
  94. Name: "import-preimages",
  95. Usage: "Import the preimage database from an RLP stream",
  96. ArgsUsage: "<datafile>",
  97. Flags: []cli.Flag{
  98. utils.DataDirFlag,
  99. utils.CacheFlag,
  100. utils.SyncModeFlag,
  101. },
  102. Category: "BLOCKCHAIN COMMANDS",
  103. Description: `
  104. The import-preimages command imports hash preimages from an RLP encoded stream.`,
  105. }
  106. exportPreimagesCommand = cli.Command{
  107. Action: utils.MigrateFlags(exportPreimages),
  108. Name: "export-preimages",
  109. Usage: "Export the preimage database into an RLP stream",
  110. ArgsUsage: "<dumpfile>",
  111. Flags: []cli.Flag{
  112. utils.DataDirFlag,
  113. utils.CacheFlag,
  114. utils.SyncModeFlag,
  115. },
  116. Category: "BLOCKCHAIN COMMANDS",
  117. Description: `
  118. The export-preimages command export hash preimages to an RLP encoded stream`,
  119. }
  120. copydbCommand = cli.Command{
  121. Action: utils.MigrateFlags(copyDb),
  122. Name: "copydb",
  123. Usage: "Create a local chain from a target chaindata folder",
  124. ArgsUsage: "<sourceChaindataDir>",
  125. Flags: []cli.Flag{
  126. utils.DataDirFlag,
  127. utils.CacheFlag,
  128. utils.SyncModeFlag,
  129. utils.FakePoWFlag,
  130. utils.TestnetFlag,
  131. utils.RinkebyFlag,
  132. },
  133. Category: "BLOCKCHAIN COMMANDS",
  134. Description: `
  135. The first argument must be the directory containing the blockchain to download from`,
  136. }
  137. removedbCommand = cli.Command{
  138. Action: utils.MigrateFlags(removeDB),
  139. Name: "removedb",
  140. Usage: "Remove blockchain and state databases",
  141. ArgsUsage: " ",
  142. Flags: []cli.Flag{
  143. utils.DataDirFlag,
  144. },
  145. Category: "BLOCKCHAIN COMMANDS",
  146. Description: `
  147. Remove blockchain and state databases`,
  148. }
  149. dumpCommand = cli.Command{
  150. Action: utils.MigrateFlags(dump),
  151. Name: "dump",
  152. Usage: "Dump a specific block from storage",
  153. ArgsUsage: "[<blockHash> | <blockNum>]...",
  154. Flags: []cli.Flag{
  155. utils.DataDirFlag,
  156. utils.CacheFlag,
  157. utils.SyncModeFlag,
  158. },
  159. Category: "BLOCKCHAIN COMMANDS",
  160. Description: `
  161. The arguments are interpreted as block numbers or hashes.
  162. Use "ethereum dump 0" to dump the genesis block.`,
  163. }
  164. )
  165. // initGenesis will initialise the given JSON format genesis file and writes it as
  166. // the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
  167. func initGenesis(ctx *cli.Context) error {
  168. // Make sure we have a valid genesis JSON
  169. genesisPath := ctx.Args().First()
  170. if len(genesisPath) == 0 {
  171. utils.Fatalf("Must supply path to genesis JSON file")
  172. }
  173. file, err := os.Open(genesisPath)
  174. if err != nil {
  175. utils.Fatalf("Failed to read genesis file: %v", err)
  176. }
  177. defer file.Close()
  178. genesis := new(core.Genesis)
  179. if err := json.NewDecoder(file).Decode(genesis); err != nil {
  180. utils.Fatalf("invalid genesis file: %v", err)
  181. }
  182. // Open an initialise both full and light databases
  183. stack := makeFullNode(ctx)
  184. defer stack.Close()
  185. for _, name := range []string{"chaindata", "lightchaindata"} {
  186. chaindb, err := stack.OpenDatabase(name, 0, 0, "")
  187. if err != nil {
  188. utils.Fatalf("Failed to open database: %v", err)
  189. }
  190. _, hash, err := core.SetupGenesisBlock(chaindb, genesis)
  191. if err != nil {
  192. utils.Fatalf("Failed to write genesis block: %v", err)
  193. }
  194. chaindb.Close()
  195. log.Info("Successfully wrote genesis state", "database", name, "hash", hash)
  196. }
  197. return nil
  198. }
  199. func importChain(ctx *cli.Context) error {
  200. if len(ctx.Args()) < 1 {
  201. utils.Fatalf("This command requires an argument.")
  202. }
  203. stack := makeFullNode(ctx)
  204. defer stack.Close()
  205. chain, db := utils.MakeChain(ctx, stack)
  206. defer db.Close()
  207. // Start periodically gathering memory profiles
  208. var peakMemAlloc, peakMemSys uint64
  209. go func() {
  210. stats := new(runtime.MemStats)
  211. for {
  212. runtime.ReadMemStats(stats)
  213. if atomic.LoadUint64(&peakMemAlloc) < stats.Alloc {
  214. atomic.StoreUint64(&peakMemAlloc, stats.Alloc)
  215. }
  216. if atomic.LoadUint64(&peakMemSys) < stats.Sys {
  217. atomic.StoreUint64(&peakMemSys, stats.Sys)
  218. }
  219. time.Sleep(5 * time.Second)
  220. }
  221. }()
  222. // Import the chain
  223. start := time.Now()
  224. if len(ctx.Args()) == 1 {
  225. if err := utils.ImportChain(chain, ctx.Args().First()); err != nil {
  226. log.Error("Import error", "err", err)
  227. }
  228. } else {
  229. for _, arg := range ctx.Args() {
  230. if err := utils.ImportChain(chain, arg); err != nil {
  231. log.Error("Import error", "file", arg, "err", err)
  232. }
  233. }
  234. }
  235. chain.Stop()
  236. fmt.Printf("Import done in %v.\n\n", time.Since(start))
  237. // Output pre-compaction stats mostly to see the import trashing
  238. stats, err := db.Stat("leveldb.stats")
  239. if err != nil {
  240. utils.Fatalf("Failed to read database stats: %v", err)
  241. }
  242. fmt.Println(stats)
  243. ioStats, err := db.Stat("leveldb.iostats")
  244. if err != nil {
  245. utils.Fatalf("Failed to read database iostats: %v", err)
  246. }
  247. fmt.Println(ioStats)
  248. // Print the memory statistics used by the importing
  249. mem := new(runtime.MemStats)
  250. runtime.ReadMemStats(mem)
  251. fmt.Printf("Object memory: %.3f MB current, %.3f MB peak\n", float64(mem.Alloc)/1024/1024, float64(atomic.LoadUint64(&peakMemAlloc))/1024/1024)
  252. fmt.Printf("System memory: %.3f MB current, %.3f MB peak\n", float64(mem.Sys)/1024/1024, float64(atomic.LoadUint64(&peakMemSys))/1024/1024)
  253. fmt.Printf("Allocations: %.3f million\n", float64(mem.Mallocs)/1000000)
  254. fmt.Printf("GC pause: %v\n\n", time.Duration(mem.PauseTotalNs))
  255. if ctx.GlobalIsSet(utils.NoCompactionFlag.Name) {
  256. return nil
  257. }
  258. // Compact the entire database to more accurately measure disk io and print the stats
  259. start = time.Now()
  260. fmt.Println("Compacting entire database...")
  261. if err = db.Compact(nil, nil); err != nil {
  262. utils.Fatalf("Compaction failed: %v", err)
  263. }
  264. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  265. stats, err = db.Stat("leveldb.stats")
  266. if err != nil {
  267. utils.Fatalf("Failed to read database stats: %v", err)
  268. }
  269. fmt.Println(stats)
  270. ioStats, err = db.Stat("leveldb.iostats")
  271. if err != nil {
  272. utils.Fatalf("Failed to read database iostats: %v", err)
  273. }
  274. fmt.Println(ioStats)
  275. return nil
  276. }
  277. func exportChain(ctx *cli.Context) error {
  278. if len(ctx.Args()) < 1 {
  279. utils.Fatalf("This command requires an argument.")
  280. }
  281. stack := makeFullNode(ctx)
  282. defer stack.Close()
  283. chain, _ := utils.MakeChain(ctx, stack)
  284. start := time.Now()
  285. var err error
  286. fp := ctx.Args().First()
  287. if len(ctx.Args()) < 3 {
  288. err = utils.ExportChain(chain, fp)
  289. } else {
  290. // This can be improved to allow for numbers larger than 9223372036854775807
  291. first, ferr := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
  292. last, lerr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
  293. if ferr != nil || lerr != nil {
  294. utils.Fatalf("Export error in parsing parameters: block number not an integer\n")
  295. }
  296. if first < 0 || last < 0 {
  297. utils.Fatalf("Export error: block number must be greater than 0\n")
  298. }
  299. err = utils.ExportAppendChain(chain, fp, uint64(first), uint64(last))
  300. }
  301. if err != nil {
  302. utils.Fatalf("Export error: %v\n", err)
  303. }
  304. fmt.Printf("Export done in %v\n", time.Since(start))
  305. return nil
  306. }
  307. // importPreimages imports preimage data from the specified file.
  308. func importPreimages(ctx *cli.Context) error {
  309. if len(ctx.Args()) < 1 {
  310. utils.Fatalf("This command requires an argument.")
  311. }
  312. stack := makeFullNode(ctx)
  313. defer stack.Close()
  314. db := utils.MakeChainDatabase(ctx, stack)
  315. start := time.Now()
  316. if err := utils.ImportPreimages(db, ctx.Args().First()); err != nil {
  317. utils.Fatalf("Import error: %v\n", err)
  318. }
  319. fmt.Printf("Import done in %v\n", time.Since(start))
  320. return nil
  321. }
  322. // exportPreimages dumps the preimage data to specified json file in streaming way.
  323. func exportPreimages(ctx *cli.Context) error {
  324. if len(ctx.Args()) < 1 {
  325. utils.Fatalf("This command requires an argument.")
  326. }
  327. stack := makeFullNode(ctx)
  328. defer stack.Close()
  329. db := utils.MakeChainDatabase(ctx, stack)
  330. start := time.Now()
  331. if err := utils.ExportPreimages(db, ctx.Args().First()); err != nil {
  332. utils.Fatalf("Export error: %v\n", err)
  333. }
  334. fmt.Printf("Export done in %v\n", time.Since(start))
  335. return nil
  336. }
  337. func copyDb(ctx *cli.Context) error {
  338. // Ensure we have a source chain directory to copy
  339. if len(ctx.Args()) != 1 {
  340. utils.Fatalf("Source chaindata directory path argument missing")
  341. }
  342. // Initialize a new chain for the running node to sync into
  343. stack := makeFullNode(ctx)
  344. defer stack.Close()
  345. chain, chainDb := utils.MakeChain(ctx, stack)
  346. syncMode := *utils.GlobalTextMarshaler(ctx, utils.SyncModeFlag.Name).(*downloader.SyncMode)
  347. var syncBloom *trie.SyncBloom
  348. if syncMode == downloader.FastSync {
  349. syncBloom = trie.NewSyncBloom(uint64(ctx.GlobalInt(utils.CacheFlag.Name)/2), chainDb)
  350. }
  351. dl := downloader.New(0, chainDb, syncBloom, new(event.TypeMux), chain, nil, nil)
  352. // Create a source peer to satisfy downloader requests from
  353. db, err := rawdb.NewLevelDBDatabase(ctx.Args().First(), ctx.GlobalInt(utils.CacheFlag.Name)/2, 256, "")
  354. if err != nil {
  355. return err
  356. }
  357. hc, err := core.NewHeaderChain(db, chain.Config(), chain.Engine(), func() bool { return false })
  358. if err != nil {
  359. return err
  360. }
  361. peer := downloader.NewFakePeer("local", db, hc, dl)
  362. if err = dl.RegisterPeer("local", 63, peer); err != nil {
  363. return err
  364. }
  365. // Synchronise with the simulated peer
  366. start := time.Now()
  367. currentHeader := hc.CurrentHeader()
  368. if err = dl.Synchronise("local", currentHeader.Hash(), hc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64()), syncMode); err != nil {
  369. return err
  370. }
  371. for dl.Synchronising() {
  372. time.Sleep(10 * time.Millisecond)
  373. }
  374. fmt.Printf("Database copy done in %v\n", time.Since(start))
  375. // Compact the entire database to remove any sync overhead
  376. start = time.Now()
  377. fmt.Println("Compacting entire database...")
  378. if err = db.Compact(nil, nil); err != nil {
  379. utils.Fatalf("Compaction failed: %v", err)
  380. }
  381. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  382. return nil
  383. }
  384. func removeDB(ctx *cli.Context) error {
  385. stack, _ := makeConfigNode(ctx)
  386. for _, name := range []string{"chaindata", "lightchaindata"} {
  387. // Ensure the database exists in the first place
  388. logger := log.New("database", name)
  389. dbdir := stack.ResolvePath(name)
  390. if !common.FileExist(dbdir) {
  391. logger.Info("Database doesn't exist, skipping", "path", dbdir)
  392. continue
  393. }
  394. // Confirm removal and execute
  395. fmt.Println(dbdir)
  396. confirm, err := console.Stdin.PromptConfirm("Remove this database?")
  397. switch {
  398. case err != nil:
  399. utils.Fatalf("%v", err)
  400. case !confirm:
  401. logger.Warn("Database deletion aborted")
  402. default:
  403. start := time.Now()
  404. os.RemoveAll(dbdir)
  405. logger.Info("Database successfully deleted", "elapsed", common.PrettyDuration(time.Since(start)))
  406. }
  407. }
  408. return nil
  409. }
  410. func dump(ctx *cli.Context) error {
  411. stack := makeFullNode(ctx)
  412. defer stack.Close()
  413. chain, chainDb := utils.MakeChain(ctx, stack)
  414. for _, arg := range ctx.Args() {
  415. var block *types.Block
  416. if hashish(arg) {
  417. block = chain.GetBlockByHash(common.HexToHash(arg))
  418. } else {
  419. num, _ := strconv.Atoi(arg)
  420. block = chain.GetBlockByNumber(uint64(num))
  421. }
  422. if block == nil {
  423. fmt.Println("{}")
  424. utils.Fatalf("block not found")
  425. } else {
  426. state, err := state.New(block.Root(), state.NewDatabase(chainDb))
  427. if err != nil {
  428. utils.Fatalf("could not create new state: %v", err)
  429. }
  430. fmt.Printf("%s\n", state.Dump())
  431. }
  432. }
  433. chainDb.Close()
  434. return nil
  435. }
  436. // hashish returns true for strings that look like hashes.
  437. func hashish(x string) bool {
  438. _, err := strconv.Atoi(x)
  439. return err != nil
  440. }