chaincmd.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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. "io"
  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/core"
  29. "github.com/ethereum/go-ethereum/core/mps"
  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/log"
  34. "github.com/ethereum/go-ethereum/metrics"
  35. "github.com/ethereum/go-ethereum/private"
  36. "github.com/ethereum/go-ethereum/private/engine/notinuse"
  37. "github.com/ethereum/go-ethereum/rlp"
  38. "gopkg.in/urfave/cli.v1"
  39. )
  40. var (
  41. initCommand = cli.Command{
  42. Action: utils.MigrateFlags(initGenesis),
  43. Name: "init",
  44. Usage: "Bootstrap and initialize a new genesis block",
  45. ArgsUsage: "<genesisPath>",
  46. Flags: []cli.Flag{
  47. utils.DataDirFlag,
  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. dumpGenesisCommand = cli.Command{
  57. Action: utils.MigrateFlags(dumpGenesis),
  58. Name: "dumpgenesis",
  59. Usage: "Dumps genesis block JSON configuration to stdout",
  60. ArgsUsage: "",
  61. Flags: []cli.Flag{
  62. utils.MainnetFlag,
  63. utils.RopstenFlag,
  64. utils.RinkebyFlag,
  65. utils.GoerliFlag,
  66. utils.YoloV3Flag,
  67. },
  68. Category: "BLOCKCHAIN COMMANDS",
  69. Description: `
  70. The dumpgenesis command dumps the genesis block configuration in JSON format to stdout.`,
  71. }
  72. importCommand = cli.Command{
  73. Action: utils.MigrateFlags(importChain),
  74. Name: "import",
  75. Usage: "Import a blockchain file",
  76. ArgsUsage: "<filename> (<filename 2> ... <filename N>) ",
  77. Flags: []cli.Flag{
  78. utils.DataDirFlag,
  79. utils.CacheFlag,
  80. utils.SyncModeFlag,
  81. utils.GCModeFlag,
  82. utils.SnapshotFlag,
  83. utils.CacheDatabaseFlag,
  84. utils.CacheGCFlag,
  85. utils.MetricsEnabledFlag,
  86. utils.MetricsEnabledExpensiveFlag,
  87. utils.MetricsHTTPFlag,
  88. utils.MetricsPortFlag,
  89. utils.MetricsEnableInfluxDBFlag,
  90. utils.MetricsInfluxDBEndpointFlag,
  91. utils.MetricsInfluxDBDatabaseFlag,
  92. utils.MetricsInfluxDBUsernameFlag,
  93. utils.MetricsInfluxDBPasswordFlag,
  94. utils.MetricsInfluxDBTagsFlag,
  95. utils.TxLookupLimitFlag,
  96. },
  97. Category: "BLOCKCHAIN COMMANDS",
  98. Description: `
  99. The import command imports blocks from an RLP-encoded form. The form can be one file
  100. with several RLP-encoded blocks, or several files can be used.
  101. If only one file is used, import error will result in failure. If several files are used,
  102. processing will proceed even if an individual RLP-file import failure occurs.`,
  103. }
  104. mpsdbUpgradeCommand = cli.Command{
  105. Action: utils.MigrateFlags(mpsdbUpgrade),
  106. Name: "mpsdbupgrade",
  107. Usage: "Upgrade a standalone DB to an MPS DB",
  108. ArgsUsage: "",
  109. Flags: []cli.Flag{
  110. utils.DataDirFlag,
  111. },
  112. Description: `
  113. Checks if the chain config isMPS parameter value.
  114. If false, it upgrades the DB to be MPS enabled (builds the trie of private states) and if successful sets isMPS to true.
  115. If true, exits displaying an error message that the DB is already MPS.`,
  116. Category: "BLOCKCHAIN COMMANDS",
  117. }
  118. exportCommand = cli.Command{
  119. Action: utils.MigrateFlags(exportChain),
  120. Name: "export",
  121. Usage: "Export blockchain into file",
  122. ArgsUsage: "<filename> [<blockNumFirst> <blockNumLast>]",
  123. Flags: []cli.Flag{
  124. utils.DataDirFlag,
  125. utils.CacheFlag,
  126. utils.SyncModeFlag,
  127. },
  128. Category: "BLOCKCHAIN COMMANDS",
  129. Description: `
  130. Requires a first argument of the file to write to.
  131. Optional second and third arguments control the first and
  132. last block to write. In this mode, the file will be appended
  133. if already existing. If the file ends with .gz, the output will
  134. be gzipped.`,
  135. }
  136. importPreimagesCommand = cli.Command{
  137. Action: utils.MigrateFlags(importPreimages),
  138. Name: "import-preimages",
  139. Usage: "Import the preimage database from an RLP stream",
  140. ArgsUsage: "<datafile>",
  141. Flags: []cli.Flag{
  142. utils.DataDirFlag,
  143. utils.CacheFlag,
  144. utils.SyncModeFlag,
  145. },
  146. Category: "BLOCKCHAIN COMMANDS",
  147. Description: `
  148. The import-preimages command imports hash preimages from an RLP encoded stream.`,
  149. }
  150. exportPreimagesCommand = cli.Command{
  151. Action: utils.MigrateFlags(exportPreimages),
  152. Name: "export-preimages",
  153. Usage: "Export the preimage database into an RLP stream",
  154. ArgsUsage: "<dumpfile>",
  155. Flags: []cli.Flag{
  156. utils.DataDirFlag,
  157. utils.CacheFlag,
  158. utils.SyncModeFlag,
  159. },
  160. Category: "BLOCKCHAIN COMMANDS",
  161. Description: `
  162. The export-preimages command export hash preimages to an RLP encoded stream`,
  163. }
  164. dumpCommand = cli.Command{
  165. Action: utils.MigrateFlags(dump),
  166. Name: "dump",
  167. Usage: "Dump a specific block from storage",
  168. ArgsUsage: "[<blockHash> | <blockNum>]...",
  169. Flags: []cli.Flag{
  170. utils.DataDirFlag,
  171. utils.CacheFlag,
  172. utils.SyncModeFlag,
  173. utils.IterativeOutputFlag,
  174. utils.ExcludeCodeFlag,
  175. utils.ExcludeStorageFlag,
  176. utils.IncludeIncompletesFlag,
  177. },
  178. Category: "BLOCKCHAIN COMMANDS",
  179. Description: `
  180. The arguments are interpreted as block numbers or hashes.
  181. Use "ethereum dump 0" to dump the genesis block.`,
  182. }
  183. )
  184. // In the regular Genesis / ChainConfig struct, due to the way go deserializes
  185. // json, IsQuorum defaults to false (when not specified). Here we specify it as
  186. // a pointer so we can make the distinction and default unspecified to true.
  187. func getIsQuorum(file io.Reader) bool {
  188. altGenesis := new(struct {
  189. Config *struct {
  190. IsQuorum *bool `json:"isQuorum"`
  191. } `json:"config"`
  192. })
  193. if err := json.NewDecoder(file).Decode(altGenesis); err != nil {
  194. utils.Fatalf("invalid genesis file: %v", err)
  195. }
  196. // unspecified defaults to true
  197. return altGenesis.Config.IsQuorum == nil || *altGenesis.Config.IsQuorum
  198. }
  199. // initGenesis will initialise the given JSON format genesis file and writes it as
  200. // the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
  201. func initGenesis(ctx *cli.Context) error {
  202. // Make sure we have a valid genesis JSON
  203. genesisPath := ctx.Args().First()
  204. if len(genesisPath) == 0 {
  205. utils.Fatalf("Must supply path to genesis JSON file")
  206. }
  207. file, err := os.Open(genesisPath)
  208. if err != nil {
  209. utils.Fatalf("Failed to read genesis file: %v", err)
  210. }
  211. defer file.Close()
  212. genesis := new(core.Genesis)
  213. if err := json.NewDecoder(file).Decode(genesis); err != nil {
  214. utils.Fatalf("invalid genesis file: %v", err)
  215. }
  216. // Quorum
  217. file.Seek(0, 0)
  218. genesis.Config.IsQuorum = getIsQuorum(file)
  219. // check the data given as a part of newMaxConfigData to ensure that
  220. // its in expected order
  221. err = genesis.Config.CheckMaxCodeConfigData()
  222. if err != nil {
  223. utils.Fatalf("maxCodeSize data invalid: %v", err)
  224. }
  225. if genesis.Config.IsQuorum {
  226. err = genesis.Config.CheckTransitionsData()
  227. if err != nil {
  228. utils.Fatalf("transitions data invalid: %v", err)
  229. }
  230. if genesis.Config.QBFT != nil && genesis.Config.QBFT.ValidatorContractAddress != (common.Address{}) {
  231. qbftExtra := new(types.QBFTExtra)
  232. err := rlp.DecodeBytes(genesis.ExtraData[:], qbftExtra)
  233. if err != nil || len(qbftExtra.Validators) > 0 {
  234. utils.Fatalf("invalid genesis file: cant combine extraData validators and config.qbft.validatorcontractaddress at the same time")
  235. }
  236. }
  237. if genesis.Config.IBFT != nil && genesis.Config.IBFT.ValidatorContractAddress != (common.Address{}) {
  238. istanbulExtra := new(types.IstanbulExtra)
  239. err := rlp.DecodeBytes(genesis.ExtraData[:], istanbulExtra)
  240. if err != nil || len(istanbulExtra.Validators) > 0 {
  241. utils.Fatalf("invalid genesis file: cant combine extraData validators and config.ibft.validatorcontractaddress at the same time")
  242. }
  243. }
  244. }
  245. // End Quorum
  246. // Open and initialise both full and light databases
  247. stack, _ := makeConfigNode(ctx)
  248. defer stack.Close()
  249. for _, name := range []string{"chaindata", "lightchaindata"} {
  250. chaindb, err := stack.OpenDatabase(name, 0, 0, "", false)
  251. if err != nil {
  252. utils.Fatalf("Failed to open database: %v", err)
  253. }
  254. _, hash, err := core.SetupGenesisBlock(chaindb, genesis)
  255. if err != nil {
  256. utils.Fatalf("Failed to write genesis block: %v", err)
  257. }
  258. chaindb.Close()
  259. log.Info("Successfully wrote genesis state", "database", name, "hash", hash)
  260. }
  261. return nil
  262. }
  263. func dumpGenesis(ctx *cli.Context) error {
  264. // TODO(rjl493456442) support loading from the custom datadir
  265. genesis := utils.MakeGenesis(ctx)
  266. if genesis == nil {
  267. genesis = core.DefaultGenesisBlock()
  268. }
  269. if err := json.NewEncoder(os.Stdout).Encode(genesis); err != nil {
  270. utils.Fatalf("could not encode genesis")
  271. }
  272. return nil
  273. }
  274. func importChain(ctx *cli.Context) error {
  275. if len(ctx.Args()) < 1 {
  276. utils.Fatalf("This command requires an argument.")
  277. }
  278. // Start metrics export if enabled
  279. utils.SetupMetrics(ctx)
  280. // Start system runtime metrics collection
  281. go metrics.CollectProcessMetrics(3 * time.Second)
  282. stack, _ := makeConfigNode(ctx)
  283. defer stack.Close()
  284. chain, db := utils.MakeChain(ctx, stack, true)
  285. defer db.Close()
  286. // Start periodically gathering memory profiles
  287. var peakMemAlloc, peakMemSys uint64
  288. go func() {
  289. stats := new(runtime.MemStats)
  290. for {
  291. runtime.ReadMemStats(stats)
  292. if atomic.LoadUint64(&peakMemAlloc) < stats.Alloc {
  293. atomic.StoreUint64(&peakMemAlloc, stats.Alloc)
  294. }
  295. if atomic.LoadUint64(&peakMemSys) < stats.Sys {
  296. atomic.StoreUint64(&peakMemSys, stats.Sys)
  297. }
  298. time.Sleep(5 * time.Second)
  299. }
  300. }()
  301. // Import the chain
  302. start := time.Now()
  303. var importErr error
  304. if len(ctx.Args()) == 1 {
  305. if err := utils.ImportChain(chain, ctx.Args().First()); err != nil {
  306. importErr = err
  307. log.Error("Import error", "err", err)
  308. }
  309. } else {
  310. for _, arg := range ctx.Args() {
  311. if err := utils.ImportChain(chain, arg); err != nil {
  312. importErr = err
  313. log.Error("Import error", "file", arg, "err", err)
  314. }
  315. }
  316. }
  317. chain.Stop()
  318. fmt.Printf("Import done in %v.\n\n", time.Since(start))
  319. // Output pre-compaction stats mostly to see the import trashing
  320. showLeveldbStats(db)
  321. // Print the memory statistics used by the importing
  322. mem := new(runtime.MemStats)
  323. runtime.ReadMemStats(mem)
  324. fmt.Printf("Object memory: %.3f MB current, %.3f MB peak\n", float64(mem.Alloc)/1024/1024, float64(atomic.LoadUint64(&peakMemAlloc))/1024/1024)
  325. fmt.Printf("System memory: %.3f MB current, %.3f MB peak\n", float64(mem.Sys)/1024/1024, float64(atomic.LoadUint64(&peakMemSys))/1024/1024)
  326. fmt.Printf("Allocations: %.3f million\n", float64(mem.Mallocs)/1000000)
  327. fmt.Printf("GC pause: %v\n\n", time.Duration(mem.PauseTotalNs))
  328. if ctx.GlobalBool(utils.NoCompactionFlag.Name) {
  329. return nil
  330. }
  331. // Compact the entire database to more accurately measure disk io and print the stats
  332. start = time.Now()
  333. fmt.Println("Compacting entire database...")
  334. if err := db.Compact(nil, nil); err != nil {
  335. utils.Fatalf("Compaction failed: %v", err)
  336. }
  337. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  338. showLeveldbStats(db)
  339. return importErr
  340. }
  341. func mpsdbUpgrade(ctx *cli.Context) error {
  342. stack, _ := makeConfigNode(ctx)
  343. defer stack.Close()
  344. // initialise the tx manager with the dummy tx mgr
  345. private.P = &notinuse.DBUpgradePrivateTransactionManager{}
  346. chain, db := utils.MakeChain(ctx, stack, true)
  347. if chain.Config().IsMPS {
  348. utils.Fatalf("The database is already upgraded to support multiple private states.")
  349. }
  350. currentBlockNumber := chain.CurrentBlock().Number().Int64()
  351. fmt.Printf("Current block number %v\n", currentBlockNumber)
  352. return mps.UpgradeDB(db, chain)
  353. }
  354. func exportChain(ctx *cli.Context) error {
  355. if len(ctx.Args()) < 1 {
  356. utils.Fatalf("This command requires an argument.")
  357. }
  358. stack, _ := makeConfigNode(ctx)
  359. defer stack.Close()
  360. chain, _ := utils.MakeChain(ctx, stack, true)
  361. start := time.Now()
  362. var err error
  363. fp := ctx.Args().First()
  364. if len(ctx.Args()) < 3 {
  365. err = utils.ExportChain(chain, fp)
  366. } else {
  367. // This can be improved to allow for numbers larger than 9223372036854775807
  368. first, ferr := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
  369. last, lerr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
  370. if ferr != nil || lerr != nil {
  371. utils.Fatalf("Export error in parsing parameters: block number not an integer\n")
  372. }
  373. if first < 0 || last < 0 {
  374. utils.Fatalf("Export error: block number must be greater than 0\n")
  375. }
  376. if head := chain.CurrentFastBlock(); uint64(last) > head.NumberU64() {
  377. utils.Fatalf("Export error: block number %d larger than head block %d\n", uint64(last), head.NumberU64())
  378. }
  379. err = utils.ExportAppendChain(chain, fp, uint64(first), uint64(last))
  380. }
  381. if err != nil {
  382. utils.Fatalf("Export error: %v\n", err)
  383. }
  384. fmt.Printf("Export done in %v\n", time.Since(start))
  385. return nil
  386. }
  387. // importPreimages imports preimage data from the specified file.
  388. func importPreimages(ctx *cli.Context) error {
  389. if len(ctx.Args()) < 1 {
  390. utils.Fatalf("This command requires an argument.")
  391. }
  392. stack, _ := makeConfigNode(ctx)
  393. defer stack.Close()
  394. db := utils.MakeChainDatabase(ctx, stack, false)
  395. start := time.Now()
  396. if err := utils.ImportPreimages(db, ctx.Args().First()); err != nil {
  397. utils.Fatalf("Import error: %v\n", err)
  398. }
  399. fmt.Printf("Import done in %v\n", time.Since(start))
  400. return nil
  401. }
  402. // exportPreimages dumps the preimage data to specified json file in streaming way.
  403. func exportPreimages(ctx *cli.Context) error {
  404. if len(ctx.Args()) < 1 {
  405. utils.Fatalf("This command requires an argument.")
  406. }
  407. stack, _ := makeConfigNode(ctx)
  408. defer stack.Close()
  409. db := utils.MakeChainDatabase(ctx, stack, true)
  410. start := time.Now()
  411. if err := utils.ExportPreimages(db, ctx.Args().First()); err != nil {
  412. utils.Fatalf("Export error: %v\n", err)
  413. }
  414. fmt.Printf("Export done in %v\n", time.Since(start))
  415. return nil
  416. }
  417. func dump(ctx *cli.Context) error {
  418. stack, _ := makeConfigNode(ctx)
  419. defer stack.Close()
  420. db := utils.MakeChainDatabase(ctx, stack, false)
  421. for _, arg := range ctx.Args() {
  422. var header *types.Header
  423. if hashish(arg) {
  424. hash := common.HexToHash(arg)
  425. number := rawdb.ReadHeaderNumber(db, hash)
  426. if number != nil {
  427. header = rawdb.ReadHeader(db, hash, *number)
  428. }
  429. } else {
  430. number, _ := strconv.Atoi(arg)
  431. hash := rawdb.ReadCanonicalHash(db, uint64(number))
  432. if hash != (common.Hash{}) {
  433. header = rawdb.ReadHeader(db, hash, uint64(number))
  434. }
  435. }
  436. if header == nil {
  437. fmt.Println("{}")
  438. utils.Fatalf("block not found")
  439. } else {
  440. state, err := state.New(header.Root, state.NewDatabase(db), nil)
  441. if err != nil {
  442. utils.Fatalf("could not create new state: %v", err)
  443. }
  444. excludeCode := ctx.Bool(utils.ExcludeCodeFlag.Name)
  445. excludeStorage := ctx.Bool(utils.ExcludeStorageFlag.Name)
  446. includeMissing := ctx.Bool(utils.IncludeIncompletesFlag.Name)
  447. if ctx.Bool(utils.IterativeOutputFlag.Name) {
  448. state.IterativeDump(excludeCode, excludeStorage, !includeMissing, json.NewEncoder(os.Stdout))
  449. } else {
  450. if includeMissing {
  451. fmt.Printf("If you want to include accounts with missing preimages, you need iterative output, since" +
  452. " otherwise the accounts will overwrite each other in the resulting mapping.")
  453. }
  454. fmt.Printf("%v %s\n", includeMissing, state.Dump(excludeCode, excludeStorage, false))
  455. }
  456. }
  457. }
  458. return nil
  459. }
  460. // hashish returns true for strings that look like hashes.
  461. func hashish(x string) bool {
  462. _, err := strconv.Atoi(x)
  463. return err != nil
  464. }