chaincmd.go 14 KB

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