chaincmd.go 14 KB

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