chaincmd.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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/core"
  28. "github.com/ethereum/go-ethereum/core/rawdb"
  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/event"
  33. "github.com/ethereum/go-ethereum/log"
  34. "github.com/ethereum/go-ethereum/metrics"
  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. dumpGenesisCommand = cli.Command{
  55. Action: utils.MigrateFlags(dumpGenesis),
  56. Name: "dumpgenesis",
  57. Usage: "Dumps genesis block JSON configuration to stdout",
  58. ArgsUsage: "",
  59. Flags: []cli.Flag{
  60. utils.DataDirFlag,
  61. },
  62. Category: "BLOCKCHAIN COMMANDS",
  63. Description: `
  64. The dumpgenesis command dumps the genesis block configuration in JSON format to stdout.`,
  65. }
  66. importCommand = cli.Command{
  67. Action: utils.MigrateFlags(importChain),
  68. Name: "import",
  69. Usage: "Import a blockchain file",
  70. ArgsUsage: "<filename> (<filename 2> ... <filename N>) ",
  71. Flags: []cli.Flag{
  72. utils.DataDirFlag,
  73. utils.CacheFlag,
  74. utils.SyncModeFlag,
  75. utils.GCModeFlag,
  76. utils.SnapshotFlag,
  77. utils.CacheDatabaseFlag,
  78. utils.CacheGCFlag,
  79. utils.MetricsEnabledFlag,
  80. utils.MetricsEnabledExpensiveFlag,
  81. utils.MetricsHTTPFlag,
  82. utils.MetricsPortFlag,
  83. utils.MetricsEnableInfluxDBFlag,
  84. utils.MetricsInfluxDBEndpointFlag,
  85. utils.MetricsInfluxDBDatabaseFlag,
  86. utils.MetricsInfluxDBUsernameFlag,
  87. utils.MetricsInfluxDBPasswordFlag,
  88. utils.MetricsInfluxDBTagsFlag,
  89. utils.TxLookupLimitFlag,
  90. },
  91. Category: "BLOCKCHAIN COMMANDS",
  92. Description: `
  93. The import command imports blocks from an RLP-encoded form. The form can be one file
  94. with several RLP-encoded blocks, or several files can be used.
  95. If only one file is used, import error will result in failure. If several files are used,
  96. processing will proceed even if an individual RLP-file import failure occurs.`,
  97. }
  98. exportCommand = cli.Command{
  99. Action: utils.MigrateFlags(exportChain),
  100. Name: "export",
  101. Usage: "Export blockchain into file",
  102. ArgsUsage: "<filename> [<blockNumFirst> <blockNumLast>]",
  103. Flags: []cli.Flag{
  104. utils.DataDirFlag,
  105. utils.CacheFlag,
  106. utils.SyncModeFlag,
  107. },
  108. Category: "BLOCKCHAIN COMMANDS",
  109. Description: `
  110. Requires a first argument of the file to write to.
  111. Optional second and third arguments control the first and
  112. last block to write. In this mode, the file will be appended
  113. if already existing. If the file ends with .gz, the output will
  114. be gzipped.`,
  115. }
  116. importPreimagesCommand = cli.Command{
  117. Action: utils.MigrateFlags(importPreimages),
  118. Name: "import-preimages",
  119. Usage: "Import the preimage database from an RLP stream",
  120. ArgsUsage: "<datafile>",
  121. Flags: []cli.Flag{
  122. utils.DataDirFlag,
  123. utils.CacheFlag,
  124. utils.SyncModeFlag,
  125. },
  126. Category: "BLOCKCHAIN COMMANDS",
  127. Description: `
  128. The import-preimages command imports hash preimages from an RLP encoded stream.`,
  129. }
  130. exportPreimagesCommand = cli.Command{
  131. Action: utils.MigrateFlags(exportPreimages),
  132. Name: "export-preimages",
  133. Usage: "Export the preimage database into an RLP stream",
  134. ArgsUsage: "<dumpfile>",
  135. Flags: []cli.Flag{
  136. utils.DataDirFlag,
  137. utils.CacheFlag,
  138. utils.SyncModeFlag,
  139. },
  140. Category: "BLOCKCHAIN COMMANDS",
  141. Description: `
  142. The export-preimages command export hash preimages to an RLP encoded stream`,
  143. }
  144. copydbCommand = cli.Command{
  145. Action: utils.MigrateFlags(copyDb),
  146. Name: "copydb",
  147. Usage: "Create a local chain from a target chaindata folder",
  148. ArgsUsage: "<sourceChaindataDir>",
  149. Flags: []cli.Flag{
  150. utils.DataDirFlag,
  151. utils.CacheFlag,
  152. utils.SyncModeFlag,
  153. utils.FakePoWFlag,
  154. utils.MainnetFlag,
  155. utils.RopstenFlag,
  156. utils.RinkebyFlag,
  157. utils.TxLookupLimitFlag,
  158. utils.GoerliFlag,
  159. utils.YoloV3Flag,
  160. utils.LegacyTestnetFlag,
  161. },
  162. Category: "BLOCKCHAIN COMMANDS",
  163. Description: `
  164. The first argument must be the directory containing the blockchain to download from`,
  165. }
  166. dumpCommand = cli.Command{
  167. Action: utils.MigrateFlags(dump),
  168. Name: "dump",
  169. Usage: "Dump a specific block from storage",
  170. ArgsUsage: "[<blockHash> | <blockNum>]...",
  171. Flags: []cli.Flag{
  172. utils.DataDirFlag,
  173. utils.CacheFlag,
  174. utils.SyncModeFlag,
  175. utils.IterativeOutputFlag,
  176. utils.ExcludeCodeFlag,
  177. utils.ExcludeStorageFlag,
  178. utils.IncludeIncompletesFlag,
  179. },
  180. Category: "BLOCKCHAIN COMMANDS",
  181. Description: `
  182. The arguments are interpreted as block numbers or hashes.
  183. Use "ethereum dump 0" to dump the genesis block.`,
  184. }
  185. )
  186. // initGenesis will initialise the given JSON format genesis file and writes it as
  187. // the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
  188. func initGenesis(ctx *cli.Context) error {
  189. // Make sure we have a valid genesis JSON
  190. genesisPath := ctx.Args().First()
  191. if len(genesisPath) == 0 {
  192. utils.Fatalf("Must supply path to genesis JSON file")
  193. }
  194. file, err := os.Open(genesisPath)
  195. if err != nil {
  196. utils.Fatalf("Failed to read genesis file: %v", err)
  197. }
  198. defer file.Close()
  199. genesis := new(core.Genesis)
  200. if err := json.NewDecoder(file).Decode(genesis); err != nil {
  201. utils.Fatalf("invalid genesis file: %v", err)
  202. }
  203. // Open and initialise both full and light databases
  204. stack, _ := makeConfigNode(ctx)
  205. defer stack.Close()
  206. for _, name := range []string{"chaindata", "lightchaindata"} {
  207. chaindb, err := stack.OpenDatabase(name, 0, 0, "")
  208. if err != nil {
  209. utils.Fatalf("Failed to open database: %v", err)
  210. }
  211. _, hash, err := core.SetupGenesisBlock(chaindb, genesis)
  212. if err != nil {
  213. utils.Fatalf("Failed to write genesis block: %v", err)
  214. }
  215. chaindb.Close()
  216. log.Info("Successfully wrote genesis state", "database", name, "hash", hash)
  217. }
  218. return nil
  219. }
  220. func dumpGenesis(ctx *cli.Context) error {
  221. genesis := utils.MakeGenesis(ctx)
  222. if genesis == nil {
  223. genesis = core.DefaultGenesisBlock()
  224. }
  225. if err := json.NewEncoder(os.Stdout).Encode(genesis); err != nil {
  226. utils.Fatalf("could not encode genesis")
  227. }
  228. return nil
  229. }
  230. func importChain(ctx *cli.Context) error {
  231. if len(ctx.Args()) < 1 {
  232. utils.Fatalf("This command requires an argument.")
  233. }
  234. // Start metrics export if enabled
  235. utils.SetupMetrics(ctx)
  236. // Start system runtime metrics collection
  237. go metrics.CollectProcessMetrics(3 * time.Second)
  238. stack, _ := makeConfigNode(ctx)
  239. defer stack.Close()
  240. chain, db := utils.MakeChain(ctx, stack, false)
  241. defer db.Close()
  242. // Start periodically gathering memory profiles
  243. var peakMemAlloc, peakMemSys uint64
  244. go func() {
  245. stats := new(runtime.MemStats)
  246. for {
  247. runtime.ReadMemStats(stats)
  248. if atomic.LoadUint64(&peakMemAlloc) < stats.Alloc {
  249. atomic.StoreUint64(&peakMemAlloc, stats.Alloc)
  250. }
  251. if atomic.LoadUint64(&peakMemSys) < stats.Sys {
  252. atomic.StoreUint64(&peakMemSys, stats.Sys)
  253. }
  254. time.Sleep(5 * time.Second)
  255. }
  256. }()
  257. // Import the chain
  258. start := time.Now()
  259. var importErr error
  260. if len(ctx.Args()) == 1 {
  261. if err := utils.ImportChain(chain, ctx.Args().First()); err != nil {
  262. importErr = err
  263. log.Error("Import error", "err", err)
  264. }
  265. } else {
  266. for _, arg := range ctx.Args() {
  267. if err := utils.ImportChain(chain, arg); err != nil {
  268. importErr = err
  269. log.Error("Import error", "file", arg, "err", err)
  270. }
  271. }
  272. }
  273. chain.Stop()
  274. fmt.Printf("Import done in %v.\n\n", time.Since(start))
  275. // Output pre-compaction stats mostly to see the import trashing
  276. showLeveldbStats(db)
  277. // Print the memory statistics used by the importing
  278. mem := new(runtime.MemStats)
  279. runtime.ReadMemStats(mem)
  280. fmt.Printf("Object memory: %.3f MB current, %.3f MB peak\n", float64(mem.Alloc)/1024/1024, float64(atomic.LoadUint64(&peakMemAlloc))/1024/1024)
  281. fmt.Printf("System memory: %.3f MB current, %.3f MB peak\n", float64(mem.Sys)/1024/1024, float64(atomic.LoadUint64(&peakMemSys))/1024/1024)
  282. fmt.Printf("Allocations: %.3f million\n", float64(mem.Mallocs)/1000000)
  283. fmt.Printf("GC pause: %v\n\n", time.Duration(mem.PauseTotalNs))
  284. if ctx.GlobalBool(utils.NoCompactionFlag.Name) {
  285. return nil
  286. }
  287. // Compact the entire database to more accurately measure disk io and print the stats
  288. start = time.Now()
  289. fmt.Println("Compacting entire database...")
  290. if err := db.Compact(nil, nil); err != nil {
  291. utils.Fatalf("Compaction failed: %v", err)
  292. }
  293. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  294. showLeveldbStats(db)
  295. return importErr
  296. }
  297. func exportChain(ctx *cli.Context) error {
  298. if len(ctx.Args()) < 1 {
  299. utils.Fatalf("This command requires an argument.")
  300. }
  301. stack, _ := makeConfigNode(ctx)
  302. defer stack.Close()
  303. chain, _ := utils.MakeChain(ctx, stack, true)
  304. start := time.Now()
  305. var err error
  306. fp := ctx.Args().First()
  307. if len(ctx.Args()) < 3 {
  308. err = utils.ExportChain(chain, fp)
  309. } else {
  310. // This can be improved to allow for numbers larger than 9223372036854775807
  311. first, ferr := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
  312. last, lerr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
  313. if ferr != nil || lerr != nil {
  314. utils.Fatalf("Export error in parsing parameters: block number not an integer\n")
  315. }
  316. if first < 0 || last < 0 {
  317. utils.Fatalf("Export error: block number must be greater than 0\n")
  318. }
  319. err = utils.ExportAppendChain(chain, fp, uint64(first), uint64(last))
  320. }
  321. if err != nil {
  322. utils.Fatalf("Export error: %v\n", err)
  323. }
  324. fmt.Printf("Export done in %v\n", time.Since(start))
  325. return nil
  326. }
  327. // importPreimages imports preimage data from the specified file.
  328. func importPreimages(ctx *cli.Context) error {
  329. if len(ctx.Args()) < 1 {
  330. utils.Fatalf("This command requires an argument.")
  331. }
  332. stack, _ := makeConfigNode(ctx)
  333. defer stack.Close()
  334. db := utils.MakeChainDatabase(ctx, stack)
  335. start := time.Now()
  336. if err := utils.ImportPreimages(db, ctx.Args().First()); err != nil {
  337. utils.Fatalf("Import error: %v\n", err)
  338. }
  339. fmt.Printf("Import done in %v\n", time.Since(start))
  340. return nil
  341. }
  342. // exportPreimages dumps the preimage data to specified json file in streaming way.
  343. func exportPreimages(ctx *cli.Context) error {
  344. if len(ctx.Args()) < 1 {
  345. utils.Fatalf("This command requires an argument.")
  346. }
  347. stack, _ := makeConfigNode(ctx)
  348. defer stack.Close()
  349. db := utils.MakeChainDatabase(ctx, stack)
  350. start := time.Now()
  351. if err := utils.ExportPreimages(db, ctx.Args().First()); err != nil {
  352. utils.Fatalf("Export error: %v\n", err)
  353. }
  354. fmt.Printf("Export done in %v\n", time.Since(start))
  355. return nil
  356. }
  357. func copyDb(ctx *cli.Context) error {
  358. // Ensure we have a source chain directory to copy
  359. if len(ctx.Args()) < 1 {
  360. utils.Fatalf("Source chaindata directory path argument missing")
  361. }
  362. if len(ctx.Args()) < 2 {
  363. utils.Fatalf("Source ancient chain directory path argument missing")
  364. }
  365. // Initialize a new chain for the running node to sync into
  366. stack, _ := makeConfigNode(ctx)
  367. defer stack.Close()
  368. chain, chainDb := utils.MakeChain(ctx, stack, false)
  369. syncMode := *utils.GlobalTextMarshaler(ctx, utils.SyncModeFlag.Name).(*downloader.SyncMode)
  370. var syncBloom *trie.SyncBloom
  371. if syncMode == downloader.FastSync {
  372. syncBloom = trie.NewSyncBloom(uint64(ctx.GlobalInt(utils.CacheFlag.Name)/2), chainDb)
  373. }
  374. dl := downloader.New(0, chainDb, syncBloom, new(event.TypeMux), chain, nil, nil)
  375. // Create a source peer to satisfy downloader requests from
  376. db, err := rawdb.NewLevelDBDatabaseWithFreezer(ctx.Args().First(), ctx.GlobalInt(utils.CacheFlag.Name)/2, 256, ctx.Args().Get(1), "")
  377. if err != nil {
  378. return err
  379. }
  380. hc, err := core.NewHeaderChain(db, chain.Config(), chain.Engine(), func() bool { return false })
  381. if err != nil {
  382. return err
  383. }
  384. peer := downloader.NewFakePeer("local", db, hc, dl)
  385. if err = dl.RegisterPeer("local", 63, peer); err != nil {
  386. return err
  387. }
  388. // Synchronise with the simulated peer
  389. start := time.Now()
  390. currentHeader := hc.CurrentHeader()
  391. if err = dl.Synchronise("local", currentHeader.Hash(), hc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64()), syncMode); err != nil {
  392. return err
  393. }
  394. for dl.Synchronising() {
  395. time.Sleep(10 * time.Millisecond)
  396. }
  397. fmt.Printf("Database copy done in %v\n", time.Since(start))
  398. // Compact the entire database to remove any sync overhead
  399. start = time.Now()
  400. fmt.Println("Compacting entire database...")
  401. if err = db.Compact(nil, nil); err != nil {
  402. utils.Fatalf("Compaction failed: %v", err)
  403. }
  404. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  405. return nil
  406. }
  407. func dump(ctx *cli.Context) error {
  408. stack, _ := makeConfigNode(ctx)
  409. defer stack.Close()
  410. chain, chainDb := utils.MakeChain(ctx, stack, true)
  411. defer chainDb.Close()
  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), nil)
  425. if err != nil {
  426. utils.Fatalf("could not create new state: %v", err)
  427. }
  428. excludeCode := ctx.Bool(utils.ExcludeCodeFlag.Name)
  429. excludeStorage := ctx.Bool(utils.ExcludeStorageFlag.Name)
  430. includeMissing := ctx.Bool(utils.IncludeIncompletesFlag.Name)
  431. if ctx.Bool(utils.IterativeOutputFlag.Name) {
  432. state.IterativeDump(excludeCode, excludeStorage, !includeMissing, json.NewEncoder(os.Stdout))
  433. } else {
  434. if includeMissing {
  435. fmt.Printf("If you want to include accounts with missing preimages, you need iterative output, since" +
  436. " otherwise the accounts will overwrite each other in the resulting mapping.")
  437. }
  438. fmt.Printf("%v %s\n", includeMissing, state.Dump(excludeCode, excludeStorage, false))
  439. }
  440. }
  441. }
  442. return nil
  443. }
  444. // hashish returns true for strings that look like hashes.
  445. func hashish(x string) bool {
  446. _, err := strconv.Atoi(x)
  447. return err != nil
  448. }