chaincmd.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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. "net"
  21. "os"
  22. "path"
  23. "path/filepath"
  24. "runtime"
  25. "strconv"
  26. "strings"
  27. "sync/atomic"
  28. "time"
  29. "github.com/ethereum/go-ethereum/cmd/utils"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/console"
  32. "github.com/ethereum/go-ethereum/core"
  33. "github.com/ethereum/go-ethereum/core/rawdb"
  34. "github.com/ethereum/go-ethereum/core/state"
  35. "github.com/ethereum/go-ethereum/core/types"
  36. "github.com/ethereum/go-ethereum/eth/downloader"
  37. "github.com/ethereum/go-ethereum/event"
  38. "github.com/ethereum/go-ethereum/log"
  39. "github.com/ethereum/go-ethereum/metrics"
  40. "github.com/ethereum/go-ethereum/node"
  41. "github.com/ethereum/go-ethereum/p2p/enode"
  42. "github.com/ethereum/go-ethereum/trie"
  43. "gopkg.in/urfave/cli.v1"
  44. )
  45. var (
  46. initCommand = cli.Command{
  47. Action: utils.MigrateFlags(initGenesis),
  48. Name: "init",
  49. Usage: "Bootstrap and initialize a new genesis block",
  50. ArgsUsage: "<genesisPath>",
  51. Flags: []cli.Flag{
  52. utils.DataDirFlag,
  53. },
  54. Category: "BLOCKCHAIN COMMANDS",
  55. Description: `
  56. The init command initializes a new genesis block and definition for the network.
  57. This is a destructive action and changes the network in which you will be
  58. participating.
  59. It expects the genesis file as argument.`,
  60. }
  61. initNetworkCommand = cli.Command{
  62. Action: utils.MigrateFlags(initNetwork),
  63. Name: "init-network",
  64. Usage: "Bootstrap and initialize a new genesis block, and nodekey, config files for network nodes",
  65. ArgsUsage: "<genesisPath>",
  66. Flags: []cli.Flag{
  67. utils.InitNetworkDir,
  68. utils.InitNetworkPort,
  69. utils.InitNetworkSize,
  70. utils.InitNetworkIps,
  71. configFileFlag,
  72. },
  73. Category: "BLOCKCHAIN COMMANDS",
  74. Description: `
  75. The init-network command initializes a new genesis block, definition for the network, config files for network nodes.
  76. It expects the genesis file as argument.`,
  77. }
  78. dumpGenesisCommand = cli.Command{
  79. Action: utils.MigrateFlags(dumpGenesis),
  80. Name: "dumpgenesis",
  81. Usage: "Dumps genesis block JSON configuration to stdout",
  82. ArgsUsage: "",
  83. Flags: []cli.Flag{
  84. utils.DataDirFlag,
  85. },
  86. Category: "BLOCKCHAIN COMMANDS",
  87. Description: `
  88. The dumpgenesis command dumps the genesis block configuration in JSON format to stdout.`,
  89. }
  90. importCommand = cli.Command{
  91. Action: utils.MigrateFlags(importChain),
  92. Name: "import",
  93. Usage: "Import a blockchain file",
  94. ArgsUsage: "<filename> (<filename 2> ... <filename N>) ",
  95. Flags: []cli.Flag{
  96. utils.DataDirFlag,
  97. utils.CacheFlag,
  98. utils.SyncModeFlag,
  99. utils.GCModeFlag,
  100. utils.SnapshotFlag,
  101. utils.CacheDatabaseFlag,
  102. utils.CacheGCFlag,
  103. utils.MetricsEnabledFlag,
  104. utils.MetricsEnabledExpensiveFlag,
  105. utils.MetricsEnableInfluxDBFlag,
  106. utils.MetricsInfluxDBEndpointFlag,
  107. utils.MetricsInfluxDBDatabaseFlag,
  108. utils.MetricsInfluxDBUsernameFlag,
  109. utils.MetricsInfluxDBPasswordFlag,
  110. utils.MetricsInfluxDBTagsFlag,
  111. },
  112. Category: "BLOCKCHAIN COMMANDS",
  113. Description: `
  114. The import command imports blocks from an RLP-encoded form. The form can be one file
  115. with several RLP-encoded blocks, or several files can be used.
  116. If only one file is used, import error will result in failure. If several files are used,
  117. processing will proceed even if an individual RLP-file import failure occurs.`,
  118. }
  119. exportCommand = cli.Command{
  120. Action: utils.MigrateFlags(exportChain),
  121. Name: "export",
  122. Usage: "Export blockchain into file",
  123. ArgsUsage: "<filename> [<blockNumFirst> <blockNumLast>]",
  124. Flags: []cli.Flag{
  125. utils.DataDirFlag,
  126. utils.CacheFlag,
  127. utils.SyncModeFlag,
  128. },
  129. Category: "BLOCKCHAIN COMMANDS",
  130. Description: `
  131. Requires a first argument of the file to write to.
  132. Optional second and third arguments control the first and
  133. last block to write. In this mode, the file will be appended
  134. if already existing. If the file ends with .gz, the output will
  135. be gzipped.`,
  136. }
  137. importPreimagesCommand = cli.Command{
  138. Action: utils.MigrateFlags(importPreimages),
  139. Name: "import-preimages",
  140. Usage: "Import the preimage database from an RLP stream",
  141. ArgsUsage: "<datafile>",
  142. Flags: []cli.Flag{
  143. utils.DataDirFlag,
  144. utils.CacheFlag,
  145. utils.SyncModeFlag,
  146. },
  147. Category: "BLOCKCHAIN COMMANDS",
  148. Description: `
  149. The import-preimages command imports hash preimages from an RLP encoded stream.`,
  150. }
  151. exportPreimagesCommand = cli.Command{
  152. Action: utils.MigrateFlags(exportPreimages),
  153. Name: "export-preimages",
  154. Usage: "Export the preimage database into an RLP stream",
  155. ArgsUsage: "<dumpfile>",
  156. Flags: []cli.Flag{
  157. utils.DataDirFlag,
  158. utils.CacheFlag,
  159. utils.SyncModeFlag,
  160. },
  161. Category: "BLOCKCHAIN COMMANDS",
  162. Description: `
  163. The export-preimages command export hash preimages to an RLP encoded stream`,
  164. }
  165. copydbCommand = cli.Command{
  166. Action: utils.MigrateFlags(copyDb),
  167. Name: "copydb",
  168. Usage: "Create a local chain from a target chaindata folder",
  169. ArgsUsage: "<sourceChaindataDir>",
  170. Flags: []cli.Flag{
  171. utils.DataDirFlag,
  172. utils.CacheFlag,
  173. utils.SyncModeFlag,
  174. utils.FakePoWFlag,
  175. utils.RopstenFlag,
  176. utils.RinkebyFlag,
  177. utils.GoerliFlag,
  178. utils.LegacyTestnetFlag,
  179. },
  180. Category: "BLOCKCHAIN COMMANDS",
  181. Description: `
  182. The first argument must be the directory containing the blockchain to download from`,
  183. }
  184. removedbCommand = cli.Command{
  185. Action: utils.MigrateFlags(removeDB),
  186. Name: "removedb",
  187. Usage: "Remove blockchain and state databases",
  188. ArgsUsage: " ",
  189. Flags: []cli.Flag{
  190. utils.DataDirFlag,
  191. },
  192. Category: "BLOCKCHAIN COMMANDS",
  193. Description: `
  194. Remove blockchain and state databases`,
  195. }
  196. dumpCommand = cli.Command{
  197. Action: utils.MigrateFlags(dump),
  198. Name: "dump",
  199. Usage: "Dump a specific block from storage",
  200. ArgsUsage: "[<blockHash> | <blockNum>]...",
  201. Flags: []cli.Flag{
  202. utils.DataDirFlag,
  203. utils.CacheFlag,
  204. utils.SyncModeFlag,
  205. utils.IterativeOutputFlag,
  206. utils.ExcludeCodeFlag,
  207. utils.ExcludeStorageFlag,
  208. utils.IncludeIncompletesFlag,
  209. },
  210. Category: "BLOCKCHAIN COMMANDS",
  211. Description: `
  212. The arguments are interpreted as block numbers or hashes.
  213. Use "ethereum dump 0" to dump the genesis block.`,
  214. }
  215. inspectCommand = cli.Command{
  216. Action: utils.MigrateFlags(inspect),
  217. Name: "inspect",
  218. Usage: "Inspect the storage size for each type of data in the database",
  219. ArgsUsage: " ",
  220. Flags: []cli.Flag{
  221. utils.DataDirFlag,
  222. utils.AncientFlag,
  223. utils.CacheFlag,
  224. utils.RopstenFlag,
  225. utils.RinkebyFlag,
  226. utils.GoerliFlag,
  227. utils.LegacyTestnetFlag,
  228. utils.SyncModeFlag,
  229. },
  230. Category: "BLOCKCHAIN COMMANDS",
  231. }
  232. )
  233. // initGenesis will initialise the given JSON format genesis file and writes it as
  234. // the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
  235. func initGenesis(ctx *cli.Context) error {
  236. // Make sure we have a valid genesis JSON
  237. genesisPath := ctx.Args().First()
  238. if len(genesisPath) == 0 {
  239. utils.Fatalf("Must supply path to genesis JSON file")
  240. }
  241. file, err := os.Open(genesisPath)
  242. if err != nil {
  243. utils.Fatalf("Failed to read genesis file: %v", err)
  244. }
  245. defer file.Close()
  246. genesis := new(core.Genesis)
  247. if err := json.NewDecoder(file).Decode(genesis); err != nil {
  248. utils.Fatalf("invalid genesis file: %v", err)
  249. }
  250. // Open an initialise both full and light databases
  251. stack := makeFullNode(ctx)
  252. defer stack.Close()
  253. for _, name := range []string{"chaindata", "lightchaindata"} {
  254. chaindb, err := stack.OpenDatabase(name, 0, 0, "")
  255. if err != nil {
  256. utils.Fatalf("Failed to open database: %v", err)
  257. }
  258. _, hash, err := core.SetupGenesisBlock(chaindb, genesis)
  259. if err != nil {
  260. utils.Fatalf("Failed to write genesis block: %v", err)
  261. }
  262. chaindb.Close()
  263. log.Info("Successfully wrote genesis state", "database", name, "hash", hash)
  264. }
  265. return nil
  266. }
  267. // initNetwork will bootstrap and initialize a new genesis block, and nodekey, config files for network nodes
  268. func initNetwork(ctx *cli.Context) error {
  269. initDir := ctx.String(utils.InitNetworkDir.Name)
  270. if len(initDir) == 0 {
  271. utils.Fatalf("init.dir is required")
  272. }
  273. size := ctx.Int(utils.InitNetworkSize.Name)
  274. port := ctx.Int(utils.InitNetworkPort.Name)
  275. ipStr := ctx.String(utils.InitNetworkIps.Name)
  276. cfgFile := ctx.String(configFileFlag.Name)
  277. if len(cfgFile) == 0 {
  278. utils.Fatalf("config file is required")
  279. }
  280. var ips []string
  281. if len(ipStr) != 0 {
  282. ips = strings.Split(ipStr, ",")
  283. if len(ips) != size {
  284. utils.Fatalf("mismatch of size and length of ips")
  285. }
  286. for i := 0; i < size; i++ {
  287. _, err := net.ResolveIPAddr("", ips[i])
  288. if err != nil {
  289. utils.Fatalf("invalid format of ip")
  290. return err
  291. }
  292. }
  293. } else {
  294. ips = make([]string, size)
  295. for i := 0; i < size; i++ {
  296. ips[i] = "127.0.0.1"
  297. }
  298. }
  299. // Make sure we have a valid genesis JSON
  300. genesisPath := ctx.Args().First()
  301. if len(genesisPath) == 0 {
  302. utils.Fatalf("Must supply path to genesis JSON file")
  303. }
  304. file, err := os.Open(genesisPath)
  305. if err != nil {
  306. utils.Fatalf("Failed to read genesis file: %v", err)
  307. }
  308. defer file.Close()
  309. genesis := new(core.Genesis)
  310. if err := json.NewDecoder(file).Decode(genesis); err != nil {
  311. utils.Fatalf("invalid genesis file: %v", err)
  312. }
  313. enodes := make([]*enode.Node, size)
  314. // load config
  315. var config gethConfig
  316. err = loadConfig(cfgFile, &config)
  317. if err != nil {
  318. return err
  319. }
  320. config.Eth.Genesis = genesis
  321. for i := 0; i < size; i++ {
  322. stack, err := node.New(&config.Node)
  323. if err != nil {
  324. return err
  325. }
  326. stack.Config().DataDir = path.Join(initDir, fmt.Sprintf("node%d", i))
  327. pk := stack.Config().NodeKey()
  328. enodes[i] = enode.NewV4(&pk.PublicKey, net.ParseIP(ips[i]), port, port)
  329. }
  330. for i := 0; i < size; i++ {
  331. config.Node.HTTPHost = ips[i]
  332. config.Node.P2P.StaticNodes = make([]*enode.Node, size-1)
  333. for j := 0; j < i; j++ {
  334. config.Node.P2P.StaticNodes[j] = enodes[j]
  335. }
  336. for j := i + 1; j < size; j++ {
  337. config.Node.P2P.StaticNodes[j-1] = enodes[j]
  338. }
  339. out, err := tomlSettings.Marshal(config)
  340. if err != nil {
  341. return err
  342. }
  343. dump, err := os.OpenFile(path.Join(initDir, fmt.Sprintf("node%d", i), "config.toml"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
  344. if err != nil {
  345. return err
  346. }
  347. defer dump.Close()
  348. dump.Write(out)
  349. }
  350. return nil
  351. }
  352. func dumpGenesis(ctx *cli.Context) error {
  353. genesis := utils.MakeGenesis(ctx)
  354. if genesis == nil {
  355. genesis = core.DefaultGenesisBlock()
  356. }
  357. if err := json.NewEncoder(os.Stdout).Encode(genesis); err != nil {
  358. utils.Fatalf("could not encode genesis")
  359. }
  360. return nil
  361. }
  362. func importChain(ctx *cli.Context) error {
  363. if len(ctx.Args()) < 1 {
  364. utils.Fatalf("This command requires an argument.")
  365. }
  366. // Start metrics export if enabled
  367. utils.SetupMetrics(ctx)
  368. // Start system runtime metrics collection
  369. go metrics.CollectProcessMetrics(3 * time.Second)
  370. stack := makeFullNode(ctx)
  371. defer stack.Close()
  372. chain, db := utils.MakeChain(ctx, stack)
  373. defer db.Close()
  374. // Start periodically gathering memory profiles
  375. var peakMemAlloc, peakMemSys uint64
  376. go func() {
  377. stats := new(runtime.MemStats)
  378. for {
  379. runtime.ReadMemStats(stats)
  380. if atomic.LoadUint64(&peakMemAlloc) < stats.Alloc {
  381. atomic.StoreUint64(&peakMemAlloc, stats.Alloc)
  382. }
  383. if atomic.LoadUint64(&peakMemSys) < stats.Sys {
  384. atomic.StoreUint64(&peakMemSys, stats.Sys)
  385. }
  386. time.Sleep(5 * time.Second)
  387. }
  388. }()
  389. // Import the chain
  390. start := time.Now()
  391. if len(ctx.Args()) == 1 {
  392. if err := utils.ImportChain(chain, ctx.Args().First()); err != nil {
  393. log.Error("Import error", "err", err)
  394. }
  395. } else {
  396. for _, arg := range ctx.Args() {
  397. if err := utils.ImportChain(chain, arg); err != nil {
  398. log.Error("Import error", "file", arg, "err", err)
  399. }
  400. }
  401. }
  402. chain.Stop()
  403. fmt.Printf("Import done in %v.\n\n", time.Since(start))
  404. // Output pre-compaction stats mostly to see the import trashing
  405. stats, err := db.Stat("leveldb.stats")
  406. if err != nil {
  407. utils.Fatalf("Failed to read database stats: %v", err)
  408. }
  409. fmt.Println(stats)
  410. ioStats, err := db.Stat("leveldb.iostats")
  411. if err != nil {
  412. utils.Fatalf("Failed to read database iostats: %v", err)
  413. }
  414. fmt.Println(ioStats)
  415. // Print the memory statistics used by the importing
  416. mem := new(runtime.MemStats)
  417. runtime.ReadMemStats(mem)
  418. fmt.Printf("Object memory: %.3f MB current, %.3f MB peak\n", float64(mem.Alloc)/1024/1024, float64(atomic.LoadUint64(&peakMemAlloc))/1024/1024)
  419. fmt.Printf("System memory: %.3f MB current, %.3f MB peak\n", float64(mem.Sys)/1024/1024, float64(atomic.LoadUint64(&peakMemSys))/1024/1024)
  420. fmt.Printf("Allocations: %.3f million\n", float64(mem.Mallocs)/1000000)
  421. fmt.Printf("GC pause: %v\n\n", time.Duration(mem.PauseTotalNs))
  422. if ctx.GlobalBool(utils.NoCompactionFlag.Name) {
  423. return nil
  424. }
  425. // Compact the entire database to more accurately measure disk io and print the stats
  426. start = time.Now()
  427. fmt.Println("Compacting entire database...")
  428. if err = db.Compact(nil, nil); err != nil {
  429. utils.Fatalf("Compaction failed: %v", err)
  430. }
  431. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  432. stats, err = db.Stat("leveldb.stats")
  433. if err != nil {
  434. utils.Fatalf("Failed to read database stats: %v", err)
  435. }
  436. fmt.Println(stats)
  437. ioStats, err = db.Stat("leveldb.iostats")
  438. if err != nil {
  439. utils.Fatalf("Failed to read database iostats: %v", err)
  440. }
  441. fmt.Println(ioStats)
  442. return nil
  443. }
  444. func exportChain(ctx *cli.Context) error {
  445. if len(ctx.Args()) < 1 {
  446. utils.Fatalf("This command requires an argument.")
  447. }
  448. stack := makeFullNode(ctx)
  449. defer stack.Close()
  450. chain, _ := utils.MakeChain(ctx, stack)
  451. start := time.Now()
  452. var err error
  453. fp := ctx.Args().First()
  454. if len(ctx.Args()) < 3 {
  455. err = utils.ExportChain(chain, fp)
  456. } else {
  457. // This can be improved to allow for numbers larger than 9223372036854775807
  458. first, ferr := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
  459. last, lerr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
  460. if ferr != nil || lerr != nil {
  461. utils.Fatalf("Export error in parsing parameters: block number not an integer\n")
  462. }
  463. if first < 0 || last < 0 {
  464. utils.Fatalf("Export error: block number must be greater than 0\n")
  465. }
  466. err = utils.ExportAppendChain(chain, fp, uint64(first), uint64(last))
  467. }
  468. if err != nil {
  469. utils.Fatalf("Export error: %v\n", err)
  470. }
  471. fmt.Printf("Export done in %v\n", time.Since(start))
  472. return nil
  473. }
  474. // importPreimages imports preimage data from the specified file.
  475. func importPreimages(ctx *cli.Context) error {
  476. if len(ctx.Args()) < 1 {
  477. utils.Fatalf("This command requires an argument.")
  478. }
  479. stack := makeFullNode(ctx)
  480. defer stack.Close()
  481. db := utils.MakeChainDatabase(ctx, stack)
  482. start := time.Now()
  483. if err := utils.ImportPreimages(db, ctx.Args().First()); err != nil {
  484. utils.Fatalf("Import error: %v\n", err)
  485. }
  486. fmt.Printf("Import done in %v\n", time.Since(start))
  487. return nil
  488. }
  489. // exportPreimages dumps the preimage data to specified json file in streaming way.
  490. func exportPreimages(ctx *cli.Context) error {
  491. if len(ctx.Args()) < 1 {
  492. utils.Fatalf("This command requires an argument.")
  493. }
  494. stack := makeFullNode(ctx)
  495. defer stack.Close()
  496. db := utils.MakeChainDatabase(ctx, stack)
  497. start := time.Now()
  498. if err := utils.ExportPreimages(db, ctx.Args().First()); err != nil {
  499. utils.Fatalf("Export error: %v\n", err)
  500. }
  501. fmt.Printf("Export done in %v\n", time.Since(start))
  502. return nil
  503. }
  504. func copyDb(ctx *cli.Context) error {
  505. // Ensure we have a source chain directory to copy
  506. if len(ctx.Args()) < 1 {
  507. utils.Fatalf("Source chaindata directory path argument missing")
  508. }
  509. if len(ctx.Args()) < 2 {
  510. utils.Fatalf("Source ancient chain directory path argument missing")
  511. }
  512. // Initialize a new chain for the running node to sync into
  513. stack := makeFullNode(ctx)
  514. defer stack.Close()
  515. chain, chainDb := utils.MakeChain(ctx, stack)
  516. syncMode := *utils.GlobalTextMarshaler(ctx, utils.SyncModeFlag.Name).(*downloader.SyncMode)
  517. var syncBloom *trie.SyncBloom
  518. if syncMode == downloader.FastSync {
  519. syncBloom = trie.NewSyncBloom(uint64(ctx.GlobalInt(utils.CacheFlag.Name)/2), chainDb)
  520. }
  521. dl := downloader.New(0, chainDb, syncBloom, new(event.TypeMux), chain, nil, nil)
  522. // Create a source peer to satisfy downloader requests from
  523. db, err := rawdb.NewLevelDBDatabaseWithFreezer(ctx.Args().First(), ctx.GlobalInt(utils.CacheFlag.Name)/2, 256, ctx.Args().Get(1), "")
  524. if err != nil {
  525. return err
  526. }
  527. hc, err := core.NewHeaderChain(db, chain.Config(), chain.Engine(), func() bool { return false })
  528. if err != nil {
  529. return err
  530. }
  531. peer := downloader.NewFakePeer("local", db, hc, dl)
  532. if err = dl.RegisterPeer("local", 63, peer); err != nil {
  533. return err
  534. }
  535. // Synchronise with the simulated peer
  536. start := time.Now()
  537. currentHeader := hc.CurrentHeader()
  538. if err = dl.Synchronise("local", currentHeader.Hash(), hc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64()), syncMode); err != nil {
  539. return err
  540. }
  541. for dl.Synchronising() {
  542. time.Sleep(10 * time.Millisecond)
  543. }
  544. fmt.Printf("Database copy done in %v\n", time.Since(start))
  545. // Compact the entire database to remove any sync overhead
  546. start = time.Now()
  547. fmt.Println("Compacting entire database...")
  548. if err = db.Compact(nil, nil); err != nil {
  549. utils.Fatalf("Compaction failed: %v", err)
  550. }
  551. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  552. return nil
  553. }
  554. func removeDB(ctx *cli.Context) error {
  555. stack, config := makeConfigNode(ctx)
  556. // Remove the full node state database
  557. path := stack.ResolvePath("chaindata")
  558. if common.FileExist(path) {
  559. confirmAndRemoveDB(path, "full node state database")
  560. } else {
  561. log.Info("Full node state database missing", "path", path)
  562. }
  563. // Remove the full node ancient database
  564. path = config.Eth.DatabaseFreezer
  565. switch {
  566. case path == "":
  567. path = filepath.Join(stack.ResolvePath("chaindata"), "ancient")
  568. case !filepath.IsAbs(path):
  569. path = config.Node.ResolvePath(path)
  570. }
  571. if common.FileExist(path) {
  572. confirmAndRemoveDB(path, "full node ancient database")
  573. } else {
  574. log.Info("Full node ancient database missing", "path", path)
  575. }
  576. // Remove the light node database
  577. path = stack.ResolvePath("lightchaindata")
  578. if common.FileExist(path) {
  579. confirmAndRemoveDB(path, "light node database")
  580. } else {
  581. log.Info("Light node database missing", "path", path)
  582. }
  583. return nil
  584. }
  585. // confirmAndRemoveDB prompts the user for a last confirmation and removes the
  586. // folder if accepted.
  587. func confirmAndRemoveDB(database string, kind string) {
  588. confirm, err := console.Stdin.PromptConfirm(fmt.Sprintf("Remove %s (%s)?", kind, database))
  589. switch {
  590. case err != nil:
  591. utils.Fatalf("%v", err)
  592. case !confirm:
  593. log.Info("Database deletion skipped", "path", database)
  594. default:
  595. start := time.Now()
  596. filepath.Walk(database, func(path string, info os.FileInfo, err error) error {
  597. // If we're at the top level folder, recurse into
  598. if path == database {
  599. return nil
  600. }
  601. // Delete all the files, but not subfolders
  602. if !info.IsDir() {
  603. os.Remove(path)
  604. return nil
  605. }
  606. return filepath.SkipDir
  607. })
  608. log.Info("Database successfully deleted", "path", database, "elapsed", common.PrettyDuration(time.Since(start)))
  609. }
  610. }
  611. func dump(ctx *cli.Context) error {
  612. stack := makeFullNode(ctx)
  613. defer stack.Close()
  614. chain, chainDb := utils.MakeChain(ctx, stack)
  615. defer chainDb.Close()
  616. for _, arg := range ctx.Args() {
  617. var block *types.Block
  618. if hashish(arg) {
  619. block = chain.GetBlockByHash(common.HexToHash(arg))
  620. } else {
  621. num, _ := strconv.Atoi(arg)
  622. block = chain.GetBlockByNumber(uint64(num))
  623. }
  624. if block == nil {
  625. fmt.Println("{}")
  626. utils.Fatalf("block not found")
  627. } else {
  628. state, err := state.New(block.Root(), state.NewDatabase(chainDb), nil)
  629. if err != nil {
  630. utils.Fatalf("could not create new state: %v", err)
  631. }
  632. excludeCode := ctx.Bool(utils.ExcludeCodeFlag.Name)
  633. excludeStorage := ctx.Bool(utils.ExcludeStorageFlag.Name)
  634. includeMissing := ctx.Bool(utils.IncludeIncompletesFlag.Name)
  635. if ctx.Bool(utils.IterativeOutputFlag.Name) {
  636. state.IterativeDump(excludeCode, excludeStorage, !includeMissing, json.NewEncoder(os.Stdout))
  637. } else {
  638. if includeMissing {
  639. fmt.Printf("If you want to include accounts with missing preimages, you need iterative output, since" +
  640. " otherwise the accounts will overwrite each other in the resulting mapping.")
  641. }
  642. fmt.Printf("%v %s\n", includeMissing, state.Dump(excludeCode, excludeStorage, false))
  643. }
  644. }
  645. }
  646. return nil
  647. }
  648. func inspect(ctx *cli.Context) error {
  649. node, _ := makeConfigNode(ctx)
  650. defer node.Close()
  651. _, chainDb := utils.MakeChain(ctx, node)
  652. defer chainDb.Close()
  653. return rawdb.InspectDatabase(chainDb)
  654. }
  655. // hashish returns true for strings that look like hashes.
  656. func hashish(x string) bool {
  657. _, err := strconv.Atoi(x)
  658. return err != nil
  659. }