chaincmd.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. "errors"
  20. "fmt"
  21. "os"
  22. "runtime"
  23. "strconv"
  24. "sync/atomic"
  25. "time"
  26. "github.com/ethereum/go-ethereum/cmd/utils"
  27. "github.com/ethereum/go-ethereum/common"
  28. "github.com/ethereum/go-ethereum/common/hexutil"
  29. "github.com/ethereum/go-ethereum/core"
  30. "github.com/ethereum/go-ethereum/core/rawdb"
  31. "github.com/ethereum/go-ethereum/core/state"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/crypto"
  34. "github.com/ethereum/go-ethereum/ethdb"
  35. "github.com/ethereum/go-ethereum/internal/flags"
  36. "github.com/ethereum/go-ethereum/log"
  37. "github.com/ethereum/go-ethereum/metrics"
  38. "github.com/ethereum/go-ethereum/node"
  39. "github.com/urfave/cli/v2"
  40. )
  41. var (
  42. initCommand = &cli.Command{
  43. Action: initGenesis,
  44. Name: "init",
  45. Usage: "Bootstrap and initialize a new genesis block",
  46. ArgsUsage: "<genesisPath>",
  47. Flags: utils.DatabasePathFlags,
  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: dumpGenesis,
  56. Name: "dumpgenesis",
  57. Usage: "Dumps genesis block JSON configuration to stdout",
  58. ArgsUsage: "",
  59. Flags: utils.NetworkFlags,
  60. Description: `
  61. The dumpgenesis command dumps the genesis block configuration in JSON format to stdout.`,
  62. }
  63. importCommand = &cli.Command{
  64. Action: importChain,
  65. Name: "import",
  66. Usage: "Import a blockchain file",
  67. ArgsUsage: "<filename> (<filename 2> ... <filename N>) ",
  68. Flags: flags.Merge([]cli.Flag{
  69. utils.CacheFlag,
  70. utils.SyncModeFlag,
  71. utils.GCModeFlag,
  72. utils.SnapshotFlag,
  73. utils.CacheDatabaseFlag,
  74. utils.CacheGCFlag,
  75. utils.MetricsEnabledFlag,
  76. utils.MetricsEnabledExpensiveFlag,
  77. utils.MetricsHTTPFlag,
  78. utils.MetricsPortFlag,
  79. utils.MetricsEnableInfluxDBFlag,
  80. utils.MetricsEnableInfluxDBV2Flag,
  81. utils.MetricsInfluxDBEndpointFlag,
  82. utils.MetricsInfluxDBDatabaseFlag,
  83. utils.MetricsInfluxDBUsernameFlag,
  84. utils.MetricsInfluxDBPasswordFlag,
  85. utils.MetricsInfluxDBTagsFlag,
  86. utils.MetricsInfluxDBTokenFlag,
  87. utils.MetricsInfluxDBBucketFlag,
  88. utils.MetricsInfluxDBOrganizationFlag,
  89. utils.TxLookupLimitFlag,
  90. }, utils.DatabasePathFlags),
  91. Description: `
  92. The import command imports blocks from an RLP-encoded form. The form can be one file
  93. with several RLP-encoded blocks, or several files can be used.
  94. If only one file is used, import error will result in failure. If several files are used,
  95. processing will proceed even if an individual RLP-file import failure occurs.`,
  96. }
  97. exportCommand = &cli.Command{
  98. Action: exportChain,
  99. Name: "export",
  100. Usage: "Export blockchain into file",
  101. ArgsUsage: "<filename> [<blockNumFirst> <blockNumLast>]",
  102. Flags: flags.Merge([]cli.Flag{
  103. utils.CacheFlag,
  104. utils.SyncModeFlag,
  105. }, utils.DatabasePathFlags),
  106. Description: `
  107. Requires a first argument of the file to write to.
  108. Optional second and third arguments control the first and
  109. last block to write. In this mode, the file will be appended
  110. if already existing. If the file ends with .gz, the output will
  111. be gzipped.`,
  112. }
  113. importPreimagesCommand = &cli.Command{
  114. Action: importPreimages,
  115. Name: "import-preimages",
  116. Usage: "Import the preimage database from an RLP stream",
  117. ArgsUsage: "<datafile>",
  118. Flags: flags.Merge([]cli.Flag{
  119. utils.CacheFlag,
  120. utils.SyncModeFlag,
  121. }, utils.DatabasePathFlags),
  122. Description: `
  123. The import-preimages command imports hash preimages from an RLP encoded stream.
  124. It's deprecated, please use "geth db import" instead.
  125. `,
  126. }
  127. exportPreimagesCommand = &cli.Command{
  128. Action: exportPreimages,
  129. Name: "export-preimages",
  130. Usage: "Export the preimage database into an RLP stream",
  131. ArgsUsage: "<dumpfile>",
  132. Flags: flags.Merge([]cli.Flag{
  133. utils.CacheFlag,
  134. utils.SyncModeFlag,
  135. }, utils.DatabasePathFlags),
  136. Description: `
  137. The export-preimages command exports hash preimages to an RLP encoded stream.
  138. It's deprecated, please use "geth db export" instead.
  139. `,
  140. }
  141. dumpCommand = &cli.Command{
  142. Action: dump,
  143. Name: "dump",
  144. Usage: "Dump a specific block from storage",
  145. ArgsUsage: "[? <blockHash> | <blockNum>]",
  146. Flags: flags.Merge([]cli.Flag{
  147. utils.CacheFlag,
  148. utils.IterativeOutputFlag,
  149. utils.ExcludeCodeFlag,
  150. utils.ExcludeStorageFlag,
  151. utils.IncludeIncompletesFlag,
  152. utils.StartKeyFlag,
  153. utils.DumpLimitFlag,
  154. }, utils.DatabasePathFlags),
  155. Description: `
  156. This command dumps out the state for a given block (or latest, if none provided).
  157. `,
  158. }
  159. )
  160. // initGenesis will initialise the given JSON format genesis file and writes it as
  161. // the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
  162. func initGenesis(ctx *cli.Context) error {
  163. if ctx.Args().Len() != 1 {
  164. utils.Fatalf("need genesis.json file as the only argument")
  165. }
  166. genesisPath := ctx.Args().First()
  167. if len(genesisPath) == 0 {
  168. utils.Fatalf("invalid path to genesis file")
  169. }
  170. file, err := os.Open(genesisPath)
  171. if err != nil {
  172. utils.Fatalf("Failed to read genesis file: %v", err)
  173. }
  174. defer file.Close()
  175. genesis := new(core.Genesis)
  176. if err := json.NewDecoder(file).Decode(genesis); err != nil {
  177. utils.Fatalf("invalid genesis file: %v", err)
  178. }
  179. // Open and initialise both full and light databases
  180. stack, _ := makeConfigNode(ctx)
  181. defer stack.Close()
  182. for _, name := range []string{"chaindata", "lightchaindata"} {
  183. chaindb, err := stack.OpenDatabaseWithFreezer(name, 0, 0, ctx.String(utils.AncientFlag.Name), "", false)
  184. if err != nil {
  185. utils.Fatalf("Failed to open database: %v", err)
  186. }
  187. _, hash, err := core.SetupGenesisBlock(chaindb, genesis)
  188. if err != nil {
  189. utils.Fatalf("Failed to write genesis block: %v", err)
  190. }
  191. chaindb.Close()
  192. log.Info("Successfully wrote genesis state", "database", name, "hash", hash)
  193. }
  194. return nil
  195. }
  196. func dumpGenesis(ctx *cli.Context) error {
  197. // TODO(rjl493456442) support loading from the custom datadir
  198. genesis := utils.MakeGenesis(ctx)
  199. if genesis == nil {
  200. genesis = core.DefaultGenesisBlock()
  201. }
  202. if err := json.NewEncoder(os.Stdout).Encode(genesis); err != nil {
  203. utils.Fatalf("could not encode genesis")
  204. }
  205. return nil
  206. }
  207. func importChain(ctx *cli.Context) error {
  208. if ctx.Args().Len() < 1 {
  209. utils.Fatalf("This command requires an argument.")
  210. }
  211. // Start metrics export if enabled
  212. utils.SetupMetrics(ctx)
  213. // Start system runtime metrics collection
  214. go metrics.CollectProcessMetrics(3 * time.Second)
  215. stack, _ := makeConfigNode(ctx)
  216. defer stack.Close()
  217. chain, db := utils.MakeChain(ctx, stack)
  218. defer db.Close()
  219. // Start periodically gathering memory profiles
  220. var peakMemAlloc, peakMemSys uint64
  221. go func() {
  222. stats := new(runtime.MemStats)
  223. for {
  224. runtime.ReadMemStats(stats)
  225. if atomic.LoadUint64(&peakMemAlloc) < stats.Alloc {
  226. atomic.StoreUint64(&peakMemAlloc, stats.Alloc)
  227. }
  228. if atomic.LoadUint64(&peakMemSys) < stats.Sys {
  229. atomic.StoreUint64(&peakMemSys, stats.Sys)
  230. }
  231. time.Sleep(5 * time.Second)
  232. }
  233. }()
  234. // Import the chain
  235. start := time.Now()
  236. var importErr error
  237. if ctx.Args().Len() == 1 {
  238. if err := utils.ImportChain(chain, ctx.Args().First()); err != nil {
  239. importErr = err
  240. log.Error("Import error", "err", err)
  241. }
  242. } else {
  243. for _, arg := range ctx.Args().Slice() {
  244. if err := utils.ImportChain(chain, arg); err != nil {
  245. importErr = err
  246. log.Error("Import error", "file", arg, "err", err)
  247. }
  248. }
  249. }
  250. chain.Stop()
  251. fmt.Printf("Import done in %v.\n\n", time.Since(start))
  252. // Output pre-compaction stats mostly to see the import trashing
  253. showLeveldbStats(db)
  254. // Print the memory statistics used by the importing
  255. mem := new(runtime.MemStats)
  256. runtime.ReadMemStats(mem)
  257. fmt.Printf("Object memory: %.3f MB current, %.3f MB peak\n", float64(mem.Alloc)/1024/1024, float64(atomic.LoadUint64(&peakMemAlloc))/1024/1024)
  258. fmt.Printf("System memory: %.3f MB current, %.3f MB peak\n", float64(mem.Sys)/1024/1024, float64(atomic.LoadUint64(&peakMemSys))/1024/1024)
  259. fmt.Printf("Allocations: %.3f million\n", float64(mem.Mallocs)/1000000)
  260. fmt.Printf("GC pause: %v\n\n", time.Duration(mem.PauseTotalNs))
  261. if ctx.Bool(utils.NoCompactionFlag.Name) {
  262. return nil
  263. }
  264. // Compact the entire database to more accurately measure disk io and print the stats
  265. start = time.Now()
  266. fmt.Println("Compacting entire database...")
  267. if err := db.Compact(nil, nil); err != nil {
  268. utils.Fatalf("Compaction failed: %v", err)
  269. }
  270. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  271. showLeveldbStats(db)
  272. return importErr
  273. }
  274. func exportChain(ctx *cli.Context) error {
  275. if ctx.Args().Len() < 1 {
  276. utils.Fatalf("This command requires an argument.")
  277. }
  278. stack, _ := makeConfigNode(ctx)
  279. defer stack.Close()
  280. chain, _ := utils.MakeChain(ctx, stack)
  281. start := time.Now()
  282. var err error
  283. fp := ctx.Args().First()
  284. if ctx.Args().Len() < 3 {
  285. err = utils.ExportChain(chain, fp)
  286. } else {
  287. // This can be improved to allow for numbers larger than 9223372036854775807
  288. first, ferr := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
  289. last, lerr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
  290. if ferr != nil || lerr != nil {
  291. utils.Fatalf("Export error in parsing parameters: block number not an integer\n")
  292. }
  293. if first < 0 || last < 0 {
  294. utils.Fatalf("Export error: block number must be greater than 0\n")
  295. }
  296. if head := chain.CurrentFastBlock(); uint64(last) > head.NumberU64() {
  297. utils.Fatalf("Export error: block number %d larger than head block %d\n", uint64(last), head.NumberU64())
  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 ctx.Args().Len() < 1 {
  310. utils.Fatalf("This command requires an argument.")
  311. }
  312. stack, _ := makeConfigNode(ctx)
  313. defer stack.Close()
  314. db := utils.MakeChainDatabase(ctx, stack, false)
  315. start := time.Now()
  316. if err := utils.ImportPreimages(db, ctx.Args().First()); err != nil {
  317. utils.Fatalf("Import error: %v\n", err)
  318. }
  319. fmt.Printf("Import 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 ctx.Args().Len() < 1 {
  325. utils.Fatalf("This command requires an argument.")
  326. }
  327. stack, _ := makeConfigNode(ctx)
  328. defer stack.Close()
  329. db := utils.MakeChainDatabase(ctx, stack, true)
  330. start := time.Now()
  331. if err := utils.ExportPreimages(db, ctx.Args().First()); err != nil {
  332. utils.Fatalf("Export error: %v\n", err)
  333. }
  334. fmt.Printf("Export done in %v\n", time.Since(start))
  335. return nil
  336. }
  337. func parseDumpConfig(ctx *cli.Context, stack *node.Node) (*state.DumpConfig, ethdb.Database, common.Hash, error) {
  338. db := utils.MakeChainDatabase(ctx, stack, true)
  339. var header *types.Header
  340. if ctx.NArg() > 1 {
  341. return nil, nil, common.Hash{}, fmt.Errorf("expected 1 argument (number or hash), got %d", ctx.NArg())
  342. }
  343. if ctx.NArg() == 1 {
  344. arg := ctx.Args().First()
  345. if hashish(arg) {
  346. hash := common.HexToHash(arg)
  347. if number := rawdb.ReadHeaderNumber(db, hash); number != nil {
  348. header = rawdb.ReadHeader(db, hash, *number)
  349. } else {
  350. return nil, nil, common.Hash{}, fmt.Errorf("block %x not found", hash)
  351. }
  352. } else {
  353. number, err := strconv.ParseUint(arg, 10, 64)
  354. if err != nil {
  355. return nil, nil, common.Hash{}, err
  356. }
  357. if hash := rawdb.ReadCanonicalHash(db, number); hash != (common.Hash{}) {
  358. header = rawdb.ReadHeader(db, hash, number)
  359. } else {
  360. return nil, nil, common.Hash{}, fmt.Errorf("header for block %d not found", number)
  361. }
  362. }
  363. } else {
  364. // Use latest
  365. header = rawdb.ReadHeadHeader(db)
  366. }
  367. if header == nil {
  368. return nil, nil, common.Hash{}, errors.New("no head block found")
  369. }
  370. startArg := common.FromHex(ctx.String(utils.StartKeyFlag.Name))
  371. var start common.Hash
  372. switch len(startArg) {
  373. case 0: // common.Hash
  374. case 32:
  375. start = common.BytesToHash(startArg)
  376. case 20:
  377. start = crypto.Keccak256Hash(startArg)
  378. log.Info("Converting start-address to hash", "address", common.BytesToAddress(startArg), "hash", start.Hex())
  379. default:
  380. return nil, nil, common.Hash{}, fmt.Errorf("invalid start argument: %x. 20 or 32 hex-encoded bytes required", startArg)
  381. }
  382. var conf = &state.DumpConfig{
  383. SkipCode: ctx.Bool(utils.ExcludeCodeFlag.Name),
  384. SkipStorage: ctx.Bool(utils.ExcludeStorageFlag.Name),
  385. OnlyWithAddresses: !ctx.Bool(utils.IncludeIncompletesFlag.Name),
  386. Start: start.Bytes(),
  387. Max: ctx.Uint64(utils.DumpLimitFlag.Name),
  388. }
  389. log.Info("State dump configured", "block", header.Number, "hash", header.Hash().Hex(),
  390. "skipcode", conf.SkipCode, "skipstorage", conf.SkipStorage,
  391. "start", hexutil.Encode(conf.Start), "limit", conf.Max)
  392. return conf, db, header.Root, nil
  393. }
  394. func dump(ctx *cli.Context) error {
  395. stack, _ := makeConfigNode(ctx)
  396. defer stack.Close()
  397. conf, db, root, err := parseDumpConfig(ctx, stack)
  398. if err != nil {
  399. return err
  400. }
  401. state, err := state.New(root, state.NewDatabase(db), nil)
  402. if err != nil {
  403. return err
  404. }
  405. if ctx.Bool(utils.IterativeOutputFlag.Name) {
  406. state.IterativeDump(conf, json.NewEncoder(os.Stdout))
  407. } else {
  408. if conf.OnlyWithAddresses {
  409. fmt.Fprintf(os.Stderr, "If you want to include accounts with missing preimages, you need iterative output, since"+
  410. " otherwise the accounts will overwrite each other in the resulting mapping.")
  411. return fmt.Errorf("incompatible options")
  412. }
  413. fmt.Println(string(state.Dump(conf)))
  414. }
  415. return nil
  416. }
  417. // hashish returns true for strings that look like hashes.
  418. func hashish(x string) bool {
  419. _, err := strconv.Atoi(x)
  420. return err != nil
  421. }