chaincmd.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. utils.LightModeFlag,
  48. },
  49. Category: "BLOCKCHAIN COMMANDS",
  50. Description: `
  51. The init command initializes a new genesis block and definition for the network.
  52. This is a destructive action and changes the network in which you will be
  53. participating.
  54. It expects the genesis file as argument.`,
  55. }
  56. importCommand = cli.Command{
  57. Action: utils.MigrateFlags(importChain),
  58. Name: "import",
  59. Usage: "Import a blockchain file",
  60. ArgsUsage: "<filename> (<filename 2> ... <filename N>) ",
  61. Flags: []cli.Flag{
  62. utils.DataDirFlag,
  63. utils.CacheFlag,
  64. utils.LightModeFlag,
  65. utils.GCModeFlag,
  66. utils.CacheDatabaseFlag,
  67. utils.CacheGCFlag,
  68. },
  69. Category: "BLOCKCHAIN COMMANDS",
  70. Description: `
  71. The import command imports blocks from an RLP-encoded form. The form can be one file
  72. with several RLP-encoded blocks, or several files can be used.
  73. If only one file is used, import error will result in failure. If several files are used,
  74. processing will proceed even if an individual RLP-file import failure occurs.`,
  75. }
  76. exportCommand = cli.Command{
  77. Action: utils.MigrateFlags(exportChain),
  78. Name: "export",
  79. Usage: "Export blockchain into file",
  80. ArgsUsage: "<filename> [<blockNumFirst> <blockNumLast>]",
  81. Flags: []cli.Flag{
  82. utils.DataDirFlag,
  83. utils.CacheFlag,
  84. utils.LightModeFlag,
  85. },
  86. Category: "BLOCKCHAIN COMMANDS",
  87. Description: `
  88. Requires a first argument of the file to write to.
  89. Optional second and third arguments control the first and
  90. last block to write. In this mode, the file will be appended
  91. if already existing.`,
  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.LightModeFlag,
  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.LightModeFlag,
  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. utils.LightModeFlag,
  146. },
  147. Category: "BLOCKCHAIN COMMANDS",
  148. Description: `
  149. Remove blockchain and state databases`,
  150. }
  151. dumpCommand = cli.Command{
  152. Action: utils.MigrateFlags(dump),
  153. Name: "dump",
  154. Usage: "Dump a specific block from storage",
  155. ArgsUsage: "[<blockHash> | <blockNum>]...",
  156. Flags: []cli.Flag{
  157. utils.DataDirFlag,
  158. utils.CacheFlag,
  159. utils.LightModeFlag,
  160. },
  161. Category: "BLOCKCHAIN COMMANDS",
  162. Description: `
  163. The arguments are interpreted as block numbers or hashes.
  164. Use "ethereum dump 0" to dump the genesis block.`,
  165. }
  166. )
  167. // initGenesis will initialise the given JSON format genesis file and writes it as
  168. // the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
  169. func initGenesis(ctx *cli.Context) error {
  170. // Make sure we have a valid genesis JSON
  171. genesisPath := ctx.Args().First()
  172. if len(genesisPath) == 0 {
  173. utils.Fatalf("Must supply path to genesis JSON file")
  174. }
  175. file, err := os.Open(genesisPath)
  176. if err != nil {
  177. utils.Fatalf("Failed to read genesis file: %v", err)
  178. }
  179. defer file.Close()
  180. genesis := new(core.Genesis)
  181. if err := json.NewDecoder(file).Decode(genesis); err != nil {
  182. utils.Fatalf("invalid genesis file: %v", err)
  183. }
  184. // Open an initialise both full and light databases
  185. stack := makeFullNode(ctx)
  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. chain, chainDb := utils.MakeChain(ctx, stack)
  205. defer chainDb.Close()
  206. // Start periodically gathering memory profiles
  207. var peakMemAlloc, peakMemSys uint64
  208. go func() {
  209. stats := new(runtime.MemStats)
  210. for {
  211. runtime.ReadMemStats(stats)
  212. if atomic.LoadUint64(&peakMemAlloc) < stats.Alloc {
  213. atomic.StoreUint64(&peakMemAlloc, stats.Alloc)
  214. }
  215. if atomic.LoadUint64(&peakMemSys) < stats.Sys {
  216. atomic.StoreUint64(&peakMemSys, stats.Sys)
  217. }
  218. time.Sleep(5 * time.Second)
  219. }
  220. }()
  221. // Import the chain
  222. start := time.Now()
  223. if len(ctx.Args()) == 1 {
  224. if err := utils.ImportChain(chain, ctx.Args().First()); err != nil {
  225. log.Error("Import error", "err", err)
  226. }
  227. } else {
  228. for _, arg := range ctx.Args() {
  229. if err := utils.ImportChain(chain, arg); err != nil {
  230. log.Error("Import error", "file", arg, "err", err)
  231. }
  232. }
  233. }
  234. chain.Stop()
  235. fmt.Printf("Import done in %v.\n\n", time.Since(start))
  236. // Output pre-compaction stats mostly to see the import trashing
  237. db := chainDb.(*ethdb.LDBDatabase)
  238. stats, err := db.LDB().GetProperty("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.LDB().GetProperty("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.LDB().CompactRange(util.Range{}); 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.LDB().GetProperty("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.LDB().GetProperty("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. chain, _ := utils.MakeChain(ctx, stack)
  285. start := time.Now()
  286. var err error
  287. fp := ctx.Args().First()
  288. if len(ctx.Args()) < 3 {
  289. err = utils.ExportChain(chain, fp)
  290. } else {
  291. // This can be improved to allow for numbers larger than 9223372036854775807
  292. first, ferr := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
  293. last, lerr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
  294. if ferr != nil || lerr != nil {
  295. utils.Fatalf("Export error in parsing parameters: block number not an integer\n")
  296. }
  297. if first < 0 || last < 0 {
  298. utils.Fatalf("Export error: block number must be greater than 0\n")
  299. }
  300. err = utils.ExportAppendChain(chain, fp, uint64(first), uint64(last))
  301. }
  302. if err != nil {
  303. utils.Fatalf("Export error: %v\n", err)
  304. }
  305. fmt.Printf("Export done in %v\n", time.Since(start))
  306. return nil
  307. }
  308. // importPreimages imports preimage data from the specified file.
  309. func importPreimages(ctx *cli.Context) error {
  310. if len(ctx.Args()) < 1 {
  311. utils.Fatalf("This command requires an argument.")
  312. }
  313. stack := makeFullNode(ctx)
  314. diskdb := utils.MakeChainDatabase(ctx, stack).(*ethdb.LDBDatabase)
  315. start := time.Now()
  316. if err := utils.ImportPreimages(diskdb, ctx.Args().First()); err != nil {
  317. utils.Fatalf("Export error: %v\n", err)
  318. }
  319. fmt.Printf("Export 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. diskdb := utils.MakeChainDatabase(ctx, stack).(*ethdb.LDBDatabase)
  329. start := time.Now()
  330. if err := utils.ExportPreimages(diskdb, ctx.Args().First()); err != nil {
  331. utils.Fatalf("Export error: %v\n", err)
  332. }
  333. fmt.Printf("Export done in %v\n", time.Since(start))
  334. return nil
  335. }
  336. func copyDb(ctx *cli.Context) error {
  337. // Ensure we have a source chain directory to copy
  338. if len(ctx.Args()) != 1 {
  339. utils.Fatalf("Source chaindata directory path argument missing")
  340. }
  341. // Initialize a new chain for the running node to sync into
  342. stack := makeFullNode(ctx)
  343. chain, chainDb := utils.MakeChain(ctx, stack)
  344. syncmode := *utils.GlobalTextMarshaler(ctx, utils.SyncModeFlag.Name).(*downloader.SyncMode)
  345. dl := downloader.New(syncmode, chainDb, new(event.TypeMux), chain, nil, nil)
  346. // Create a source peer to satisfy downloader requests from
  347. db, err := ethdb.NewLDBDatabase(ctx.Args().First(), ctx.GlobalInt(utils.CacheFlag.Name), 256)
  348. if err != nil {
  349. return err
  350. }
  351. hc, err := core.NewHeaderChain(db, chain.Config(), chain.Engine(), func() bool { return false })
  352. if err != nil {
  353. return err
  354. }
  355. peer := downloader.NewFakePeer("local", db, hc, dl)
  356. if err = dl.RegisterPeer("local", 63, peer); err != nil {
  357. return err
  358. }
  359. // Synchronise with the simulated peer
  360. start := time.Now()
  361. currentHeader := hc.CurrentHeader()
  362. if err = dl.Synchronise("local", currentHeader.Hash(), hc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64()), syncmode); err != nil {
  363. return err
  364. }
  365. for dl.Synchronising() {
  366. time.Sleep(10 * time.Millisecond)
  367. }
  368. fmt.Printf("Database copy done in %v\n", time.Since(start))
  369. // Compact the entire database to remove any sync overhead
  370. start = time.Now()
  371. fmt.Println("Compacting entire database...")
  372. if err = chainDb.(*ethdb.LDBDatabase).LDB().CompactRange(util.Range{}); err != nil {
  373. utils.Fatalf("Compaction failed: %v", err)
  374. }
  375. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  376. return nil
  377. }
  378. func removeDB(ctx *cli.Context) error {
  379. stack, _ := makeConfigNode(ctx)
  380. for _, name := range []string{"chaindata", "lightchaindata"} {
  381. // Ensure the database exists in the first place
  382. logger := log.New("database", name)
  383. dbdir := stack.ResolvePath(name)
  384. if !common.FileExist(dbdir) {
  385. logger.Info("Database doesn't exist, skipping", "path", dbdir)
  386. continue
  387. }
  388. // Confirm removal and execute
  389. fmt.Println(dbdir)
  390. confirm, err := console.Stdin.PromptConfirm("Remove this database?")
  391. switch {
  392. case err != nil:
  393. utils.Fatalf("%v", err)
  394. case !confirm:
  395. logger.Warn("Database deletion aborted")
  396. default:
  397. start := time.Now()
  398. os.RemoveAll(dbdir)
  399. logger.Info("Database successfully deleted", "elapsed", common.PrettyDuration(time.Since(start)))
  400. }
  401. }
  402. return nil
  403. }
  404. func dump(ctx *cli.Context) error {
  405. stack := makeFullNode(ctx)
  406. chain, chainDb := utils.MakeChain(ctx, stack)
  407. for _, arg := range ctx.Args() {
  408. var block *types.Block
  409. if hashish(arg) {
  410. block = chain.GetBlockByHash(common.HexToHash(arg))
  411. } else {
  412. num, _ := strconv.Atoi(arg)
  413. block = chain.GetBlockByNumber(uint64(num))
  414. }
  415. if block == nil {
  416. fmt.Println("{}")
  417. utils.Fatalf("block not found")
  418. } else {
  419. state, err := state.New(block.Root(), state.NewDatabase(chainDb))
  420. if err != nil {
  421. utils.Fatalf("could not create new state: %v", err)
  422. }
  423. fmt.Printf("%s\n", state.Dump())
  424. }
  425. }
  426. chainDb.Close()
  427. return nil
  428. }
  429. // hashish returns true for strings that look like hashes.
  430. func hashish(x string) bool {
  431. _, err := strconv.Atoi(x)
  432. return err != nil
  433. }