chaincmd.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. fmt.Printf("Trie cache misses: %d\n", trie.CacheMisses())
  249. fmt.Printf("Trie cache unloads: %d\n\n", trie.CacheUnloads())
  250. // Print the memory statistics used by the importing
  251. mem := new(runtime.MemStats)
  252. runtime.ReadMemStats(mem)
  253. fmt.Printf("Object memory: %.3f MB current, %.3f MB peak\n", float64(mem.Alloc)/1024/1024, float64(atomic.LoadUint64(&peakMemAlloc))/1024/1024)
  254. fmt.Printf("System memory: %.3f MB current, %.3f MB peak\n", float64(mem.Sys)/1024/1024, float64(atomic.LoadUint64(&peakMemSys))/1024/1024)
  255. fmt.Printf("Allocations: %.3f million\n", float64(mem.Mallocs)/1000000)
  256. fmt.Printf("GC pause: %v\n\n", time.Duration(mem.PauseTotalNs))
  257. if ctx.GlobalIsSet(utils.NoCompactionFlag.Name) {
  258. return nil
  259. }
  260. // Compact the entire database to more accurately measure disk io and print the stats
  261. start = time.Now()
  262. fmt.Println("Compacting entire database...")
  263. if err = db.Compact(nil, nil); err != nil {
  264. utils.Fatalf("Compaction failed: %v", err)
  265. }
  266. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  267. stats, err = db.Stat("leveldb.stats")
  268. if err != nil {
  269. utils.Fatalf("Failed to read database stats: %v", err)
  270. }
  271. fmt.Println(stats)
  272. ioStats, err = db.Stat("leveldb.iostats")
  273. if err != nil {
  274. utils.Fatalf("Failed to read database iostats: %v", err)
  275. }
  276. fmt.Println(ioStats)
  277. return nil
  278. }
  279. func exportChain(ctx *cli.Context) error {
  280. if len(ctx.Args()) < 1 {
  281. utils.Fatalf("This command requires an argument.")
  282. }
  283. stack := makeFullNode(ctx)
  284. defer stack.Close()
  285. chain, _ := utils.MakeChain(ctx, stack)
  286. start := time.Now()
  287. var err error
  288. fp := ctx.Args().First()
  289. if len(ctx.Args()) < 3 {
  290. err = utils.ExportChain(chain, fp)
  291. } else {
  292. // This can be improved to allow for numbers larger than 9223372036854775807
  293. first, ferr := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
  294. last, lerr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
  295. if ferr != nil || lerr != nil {
  296. utils.Fatalf("Export error in parsing parameters: block number not an integer\n")
  297. }
  298. if first < 0 || last < 0 {
  299. utils.Fatalf("Export error: block number must be greater than 0\n")
  300. }
  301. err = utils.ExportAppendChain(chain, fp, uint64(first), uint64(last))
  302. }
  303. if err != nil {
  304. utils.Fatalf("Export error: %v\n", err)
  305. }
  306. fmt.Printf("Export done in %v\n", time.Since(start))
  307. return nil
  308. }
  309. // importPreimages imports preimage data from the specified file.
  310. func importPreimages(ctx *cli.Context) error {
  311. if len(ctx.Args()) < 1 {
  312. utils.Fatalf("This command requires an argument.")
  313. }
  314. stack := makeFullNode(ctx)
  315. defer stack.Close()
  316. db := utils.MakeChainDatabase(ctx, stack)
  317. start := time.Now()
  318. if err := utils.ImportPreimages(db, ctx.Args().First()); err != nil {
  319. utils.Fatalf("Import error: %v\n", err)
  320. }
  321. fmt.Printf("Import done in %v\n", time.Since(start))
  322. return nil
  323. }
  324. // exportPreimages dumps the preimage data to specified json file in streaming way.
  325. func exportPreimages(ctx *cli.Context) error {
  326. if len(ctx.Args()) < 1 {
  327. utils.Fatalf("This command requires an argument.")
  328. }
  329. stack := makeFullNode(ctx)
  330. defer stack.Close()
  331. db := utils.MakeChainDatabase(ctx, stack)
  332. start := time.Now()
  333. if err := utils.ExportPreimages(db, ctx.Args().First()); err != nil {
  334. utils.Fatalf("Export error: %v\n", err)
  335. }
  336. fmt.Printf("Export done in %v\n", time.Since(start))
  337. return nil
  338. }
  339. func copyDb(ctx *cli.Context) error {
  340. // Ensure we have a source chain directory to copy
  341. if len(ctx.Args()) != 1 {
  342. utils.Fatalf("Source chaindata directory path argument missing")
  343. }
  344. // Initialize a new chain for the running node to sync into
  345. stack := makeFullNode(ctx)
  346. defer stack.Close()
  347. chain, chainDb := utils.MakeChain(ctx, stack)
  348. syncmode := *utils.GlobalTextMarshaler(ctx, utils.SyncModeFlag.Name).(*downloader.SyncMode)
  349. dl := downloader.New(syncmode, chainDb, new(event.TypeMux), chain, nil, nil)
  350. // Create a source peer to satisfy downloader requests from
  351. db, err := rawdb.NewLevelDBDatabase(ctx.Args().First(), ctx.GlobalInt(utils.CacheFlag.Name), 256, "")
  352. if err != nil {
  353. return err
  354. }
  355. hc, err := core.NewHeaderChain(db, chain.Config(), chain.Engine(), func() bool { return false })
  356. if err != nil {
  357. return err
  358. }
  359. peer := downloader.NewFakePeer("local", db, hc, dl)
  360. if err = dl.RegisterPeer("local", 63, peer); err != nil {
  361. return err
  362. }
  363. // Synchronise with the simulated peer
  364. start := time.Now()
  365. currentHeader := hc.CurrentHeader()
  366. if err = dl.Synchronise("local", currentHeader.Hash(), hc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64()), syncmode); err != nil {
  367. return err
  368. }
  369. for dl.Synchronising() {
  370. time.Sleep(10 * time.Millisecond)
  371. }
  372. fmt.Printf("Database copy done in %v\n", time.Since(start))
  373. // Compact the entire database to remove any sync overhead
  374. start = time.Now()
  375. fmt.Println("Compacting entire database...")
  376. if err = db.Compact(nil, nil); err != nil {
  377. utils.Fatalf("Compaction failed: %v", err)
  378. }
  379. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  380. return nil
  381. }
  382. func removeDB(ctx *cli.Context) error {
  383. stack, _ := makeConfigNode(ctx)
  384. for _, name := range []string{"chaindata", "lightchaindata"} {
  385. // Ensure the database exists in the first place
  386. logger := log.New("database", name)
  387. dbdir := stack.ResolvePath(name)
  388. if !common.FileExist(dbdir) {
  389. logger.Info("Database doesn't exist, skipping", "path", dbdir)
  390. continue
  391. }
  392. // Confirm removal and execute
  393. fmt.Println(dbdir)
  394. confirm, err := console.Stdin.PromptConfirm("Remove this database?")
  395. switch {
  396. case err != nil:
  397. utils.Fatalf("%v", err)
  398. case !confirm:
  399. logger.Warn("Database deletion aborted")
  400. default:
  401. start := time.Now()
  402. os.RemoveAll(dbdir)
  403. logger.Info("Database successfully deleted", "elapsed", common.PrettyDuration(time.Since(start)))
  404. }
  405. }
  406. return nil
  407. }
  408. func dump(ctx *cli.Context) error {
  409. stack := makeFullNode(ctx)
  410. defer stack.Close()
  411. chain, chainDb := utils.MakeChain(ctx, stack)
  412. for _, arg := range ctx.Args() {
  413. var block *types.Block
  414. if hashish(arg) {
  415. block = chain.GetBlockByHash(common.HexToHash(arg))
  416. } else {
  417. num, _ := strconv.Atoi(arg)
  418. block = chain.GetBlockByNumber(uint64(num))
  419. }
  420. if block == nil {
  421. fmt.Println("{}")
  422. utils.Fatalf("block not found")
  423. } else {
  424. state, err := state.New(block.Root(), state.NewDatabase(chainDb))
  425. if err != nil {
  426. utils.Fatalf("could not create new state: %v", err)
  427. }
  428. fmt.Printf("%s\n", state.Dump())
  429. }
  430. }
  431. chainDb.Close()
  432. return nil
  433. }
  434. // hashish returns true for strings that look like hashes.
  435. func hashish(x string) bool {
  436. _, err := strconv.Atoi(x)
  437. return err != nil
  438. }