chaincmd.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. "net"
  21. "os"
  22. "path"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "sync/atomic"
  27. "time"
  28. "github.com/ethereum/go-ethereum/cmd/utils"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/core"
  31. "github.com/ethereum/go-ethereum/core/rawdb"
  32. "github.com/ethereum/go-ethereum/core/state"
  33. "github.com/ethereum/go-ethereum/core/types"
  34. "github.com/ethereum/go-ethereum/log"
  35. "github.com/ethereum/go-ethereum/metrics"
  36. "github.com/ethereum/go-ethereum/node"
  37. "github.com/ethereum/go-ethereum/p2p/enode"
  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. initNetworkCommand = cli.Command{
  57. Action: utils.MigrateFlags(initNetwork),
  58. Name: "init-network",
  59. Usage: "Bootstrap and initialize a new genesis block, and nodekey, config files for network nodes",
  60. ArgsUsage: "<genesisPath>",
  61. Flags: []cli.Flag{
  62. utils.InitNetworkDir,
  63. utils.InitNetworkPort,
  64. utils.InitNetworkSize,
  65. utils.InitNetworkIps,
  66. configFileFlag,
  67. },
  68. Category: "BLOCKCHAIN COMMANDS",
  69. Description: `
  70. The init-network command initializes a new genesis block, definition for the network, config files for network nodes.
  71. It expects the genesis file as argument.`,
  72. }
  73. dumpGenesisCommand = cli.Command{
  74. Action: utils.MigrateFlags(dumpGenesis),
  75. Name: "dumpgenesis",
  76. Usage: "Dumps genesis block JSON configuration to stdout",
  77. ArgsUsage: "",
  78. Flags: []cli.Flag{
  79. utils.MainnetFlag,
  80. utils.RopstenFlag,
  81. utils.RinkebyFlag,
  82. utils.GoerliFlag,
  83. utils.YoloV3Flag,
  84. },
  85. Category: "BLOCKCHAIN COMMANDS",
  86. Description: `
  87. The dumpgenesis command dumps the genesis block configuration in JSON format to stdout.`,
  88. }
  89. importCommand = cli.Command{
  90. Action: utils.MigrateFlags(importChain),
  91. Name: "import",
  92. Usage: "Import a blockchain file",
  93. ArgsUsage: "<filename> (<filename 2> ... <filename N>) ",
  94. Flags: []cli.Flag{
  95. utils.DataDirFlag,
  96. utils.CacheFlag,
  97. utils.SyncModeFlag,
  98. utils.GCModeFlag,
  99. utils.SnapshotFlag,
  100. utils.CacheDatabaseFlag,
  101. utils.CacheGCFlag,
  102. utils.MetricsEnabledFlag,
  103. utils.MetricsEnabledExpensiveFlag,
  104. utils.MetricsHTTPFlag,
  105. utils.MetricsPortFlag,
  106. utils.MetricsEnableInfluxDBFlag,
  107. utils.MetricsInfluxDBEndpointFlag,
  108. utils.MetricsInfluxDBDatabaseFlag,
  109. utils.MetricsInfluxDBUsernameFlag,
  110. utils.MetricsInfluxDBPasswordFlag,
  111. utils.MetricsInfluxDBTagsFlag,
  112. utils.TxLookupLimitFlag,
  113. },
  114. Category: "BLOCKCHAIN COMMANDS",
  115. Description: `
  116. The import command imports blocks from an RLP-encoded form. The form can be one file
  117. with several RLP-encoded blocks, or several files can be used.
  118. If only one file is used, import error will result in failure. If several files are used,
  119. processing will proceed even if an individual RLP-file import failure occurs.`,
  120. }
  121. exportCommand = cli.Command{
  122. Action: utils.MigrateFlags(exportChain),
  123. Name: "export",
  124. Usage: "Export blockchain into file",
  125. ArgsUsage: "<filename> [<blockNumFirst> <blockNumLast>]",
  126. Flags: []cli.Flag{
  127. utils.DataDirFlag,
  128. utils.CacheFlag,
  129. utils.SyncModeFlag,
  130. },
  131. Category: "BLOCKCHAIN COMMANDS",
  132. Description: `
  133. Requires a first argument of the file to write to.
  134. Optional second and third arguments control the first and
  135. last block to write. In this mode, the file will be appended
  136. if already existing. If the file ends with .gz, the output will
  137. be gzipped.`,
  138. }
  139. importPreimagesCommand = cli.Command{
  140. Action: utils.MigrateFlags(importPreimages),
  141. Name: "import-preimages",
  142. Usage: "Import the preimage database from an RLP stream",
  143. ArgsUsage: "<datafile>",
  144. Flags: []cli.Flag{
  145. utils.DataDirFlag,
  146. utils.CacheFlag,
  147. utils.SyncModeFlag,
  148. },
  149. Category: "BLOCKCHAIN COMMANDS",
  150. Description: `
  151. The import-preimages command imports hash preimages from an RLP encoded stream.`,
  152. }
  153. exportPreimagesCommand = cli.Command{
  154. Action: utils.MigrateFlags(exportPreimages),
  155. Name: "export-preimages",
  156. Usage: "Export the preimage database into an RLP stream",
  157. ArgsUsage: "<dumpfile>",
  158. Flags: []cli.Flag{
  159. utils.DataDirFlag,
  160. utils.CacheFlag,
  161. utils.SyncModeFlag,
  162. },
  163. Category: "BLOCKCHAIN COMMANDS",
  164. Description: `
  165. The export-preimages command export hash preimages to an RLP encoded stream`,
  166. }
  167. dumpCommand = cli.Command{
  168. Action: utils.MigrateFlags(dump),
  169. Name: "dump",
  170. Usage: "Dump a specific block from storage",
  171. ArgsUsage: "[<blockHash> | <blockNum>]...",
  172. Flags: []cli.Flag{
  173. utils.DataDirFlag,
  174. utils.CacheFlag,
  175. utils.SyncModeFlag,
  176. utils.IterativeOutputFlag,
  177. utils.ExcludeCodeFlag,
  178. utils.ExcludeStorageFlag,
  179. utils.IncludeIncompletesFlag,
  180. },
  181. Category: "BLOCKCHAIN COMMANDS",
  182. Description: `
  183. The arguments are interpreted as block numbers or hashes.
  184. Use "ethereum dump 0" to dump the genesis block.`,
  185. }
  186. )
  187. // initGenesis will initialise the given JSON format genesis file and writes it as
  188. // the zero'd block (i.e. genesis) or will fail hard if it can't succeed.
  189. func initGenesis(ctx *cli.Context) error {
  190. // Make sure we have a valid genesis JSON
  191. genesisPath := ctx.Args().First()
  192. if len(genesisPath) == 0 {
  193. utils.Fatalf("Must supply path to genesis JSON file")
  194. }
  195. file, err := os.Open(genesisPath)
  196. if err != nil {
  197. utils.Fatalf("Failed to read genesis file: %v", err)
  198. }
  199. defer file.Close()
  200. genesis := new(core.Genesis)
  201. if err := json.NewDecoder(file).Decode(genesis); err != nil {
  202. utils.Fatalf("invalid genesis file: %v", err)
  203. }
  204. // Open and initialise both full and light databases
  205. stack, _ := makeConfigNode(ctx)
  206. defer stack.Close()
  207. for _, name := range []string{"chaindata", "lightchaindata"} {
  208. chaindb, err := stack.OpenDatabase(name, 0, 0, "", false)
  209. if err != nil {
  210. utils.Fatalf("Failed to open database: %v", err)
  211. }
  212. _, hash, err := core.SetupGenesisBlock(chaindb, genesis)
  213. if err != nil {
  214. utils.Fatalf("Failed to write genesis block: %v", err)
  215. }
  216. chaindb.Close()
  217. log.Info("Successfully wrote genesis state", "database", name, "hash", hash)
  218. }
  219. return nil
  220. }
  221. // initNetwork will bootstrap and initialize a new genesis block, and nodekey, config files for network nodes
  222. func initNetwork(ctx *cli.Context) error {
  223. initDir := ctx.String(utils.InitNetworkDir.Name)
  224. if len(initDir) == 0 {
  225. utils.Fatalf("init.dir is required")
  226. }
  227. size := ctx.Int(utils.InitNetworkSize.Name)
  228. port := ctx.Int(utils.InitNetworkPort.Name)
  229. ipStr := ctx.String(utils.InitNetworkIps.Name)
  230. cfgFile := ctx.String(configFileFlag.Name)
  231. if len(cfgFile) == 0 {
  232. utils.Fatalf("config file is required")
  233. }
  234. var ips []string
  235. if len(ipStr) != 0 {
  236. ips = strings.Split(ipStr, ",")
  237. if len(ips) != size {
  238. utils.Fatalf("mismatch of size and length of ips")
  239. }
  240. for i := 0; i < size; i++ {
  241. _, err := net.ResolveIPAddr("", ips[i])
  242. if err != nil {
  243. utils.Fatalf("invalid format of ip")
  244. return err
  245. }
  246. }
  247. } else {
  248. ips = make([]string, size)
  249. for i := 0; i < size; i++ {
  250. ips[i] = "127.0.0.1"
  251. }
  252. }
  253. // Make sure we have a valid genesis JSON
  254. genesisPath := ctx.Args().First()
  255. if len(genesisPath) == 0 {
  256. utils.Fatalf("Must supply path to genesis JSON file")
  257. }
  258. file, err := os.Open(genesisPath)
  259. if err != nil {
  260. utils.Fatalf("Failed to read genesis file: %v", err)
  261. }
  262. defer file.Close()
  263. genesis := new(core.Genesis)
  264. if err := json.NewDecoder(file).Decode(genesis); err != nil {
  265. utils.Fatalf("invalid genesis file: %v", err)
  266. }
  267. enodes := make([]*enode.Node, size)
  268. // load config
  269. var config gethConfig
  270. err = loadConfig(cfgFile, &config)
  271. if err != nil {
  272. return err
  273. }
  274. config.Eth.Genesis = genesis
  275. for i := 0; i < size; i++ {
  276. stack, err := node.New(&config.Node)
  277. if err != nil {
  278. return err
  279. }
  280. stack.Config().DataDir = path.Join(initDir, fmt.Sprintf("node%d", i))
  281. pk := stack.Config().NodeKey()
  282. enodes[i] = enode.NewV4(&pk.PublicKey, net.ParseIP(ips[i]), port, port)
  283. }
  284. for i := 0; i < size; i++ {
  285. config.Node.HTTPHost = ips[i]
  286. config.Node.P2P.StaticNodes = make([]*enode.Node, size-1)
  287. for j := 0; j < i; j++ {
  288. config.Node.P2P.StaticNodes[j] = enodes[j]
  289. }
  290. for j := i + 1; j < size; j++ {
  291. config.Node.P2P.StaticNodes[j-1] = enodes[j]
  292. }
  293. out, err := tomlSettings.Marshal(config)
  294. if err != nil {
  295. return err
  296. }
  297. dump, err := os.OpenFile(path.Join(initDir, fmt.Sprintf("node%d", i), "config.toml"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
  298. if err != nil {
  299. return err
  300. }
  301. defer dump.Close()
  302. dump.Write(out)
  303. }
  304. return nil
  305. }
  306. func dumpGenesis(ctx *cli.Context) error {
  307. // TODO(rjl493456442) support loading from the custom datadir
  308. genesis := utils.MakeGenesis(ctx)
  309. if genesis == nil {
  310. genesis = core.DefaultGenesisBlock()
  311. }
  312. if err := json.NewEncoder(os.Stdout).Encode(genesis); err != nil {
  313. utils.Fatalf("could not encode genesis")
  314. }
  315. return nil
  316. }
  317. func importChain(ctx *cli.Context) error {
  318. if len(ctx.Args()) < 1 {
  319. utils.Fatalf("This command requires an argument.")
  320. }
  321. // Start metrics export if enabled
  322. utils.SetupMetrics(ctx)
  323. // Start system runtime metrics collection
  324. go metrics.CollectProcessMetrics(3 * time.Second)
  325. stack, _ := makeConfigNode(ctx)
  326. defer stack.Close()
  327. chain, db := utils.MakeChain(ctx, stack)
  328. defer db.Close()
  329. // Start periodically gathering memory profiles
  330. var peakMemAlloc, peakMemSys uint64
  331. go func() {
  332. stats := new(runtime.MemStats)
  333. for {
  334. runtime.ReadMemStats(stats)
  335. if atomic.LoadUint64(&peakMemAlloc) < stats.Alloc {
  336. atomic.StoreUint64(&peakMemAlloc, stats.Alloc)
  337. }
  338. if atomic.LoadUint64(&peakMemSys) < stats.Sys {
  339. atomic.StoreUint64(&peakMemSys, stats.Sys)
  340. }
  341. time.Sleep(5 * time.Second)
  342. }
  343. }()
  344. // Import the chain
  345. start := time.Now()
  346. var importErr error
  347. if len(ctx.Args()) == 1 {
  348. if err := utils.ImportChain(chain, ctx.Args().First()); err != nil {
  349. importErr = err
  350. log.Error("Import error", "err", err)
  351. }
  352. } else {
  353. for _, arg := range ctx.Args() {
  354. if err := utils.ImportChain(chain, arg); err != nil {
  355. importErr = err
  356. log.Error("Import error", "file", arg, "err", err)
  357. }
  358. }
  359. }
  360. chain.Stop()
  361. fmt.Printf("Import done in %v.\n\n", time.Since(start))
  362. // Output pre-compaction stats mostly to see the import trashing
  363. showLeveldbStats(db)
  364. // Print the memory statistics used by the importing
  365. mem := new(runtime.MemStats)
  366. runtime.ReadMemStats(mem)
  367. fmt.Printf("Object memory: %.3f MB current, %.3f MB peak\n", float64(mem.Alloc)/1024/1024, float64(atomic.LoadUint64(&peakMemAlloc))/1024/1024)
  368. fmt.Printf("System memory: %.3f MB current, %.3f MB peak\n", float64(mem.Sys)/1024/1024, float64(atomic.LoadUint64(&peakMemSys))/1024/1024)
  369. fmt.Printf("Allocations: %.3f million\n", float64(mem.Mallocs)/1000000)
  370. fmt.Printf("GC pause: %v\n\n", time.Duration(mem.PauseTotalNs))
  371. if ctx.GlobalBool(utils.NoCompactionFlag.Name) {
  372. return nil
  373. }
  374. // Compact the entire database to more accurately measure disk io and print the stats
  375. start = time.Now()
  376. fmt.Println("Compacting entire database...")
  377. if err := db.Compact(nil, nil); err != nil {
  378. utils.Fatalf("Compaction failed: %v", err)
  379. }
  380. fmt.Printf("Compaction done in %v.\n\n", time.Since(start))
  381. showLeveldbStats(db)
  382. return importErr
  383. }
  384. func exportChain(ctx *cli.Context) error {
  385. if len(ctx.Args()) < 1 {
  386. utils.Fatalf("This command requires an argument.")
  387. }
  388. stack, _ := makeConfigNode(ctx)
  389. defer stack.Close()
  390. chain, _ := utils.MakeChain(ctx, stack)
  391. start := time.Now()
  392. var err error
  393. fp := ctx.Args().First()
  394. if len(ctx.Args()) < 3 {
  395. err = utils.ExportChain(chain, fp)
  396. } else {
  397. // This can be improved to allow for numbers larger than 9223372036854775807
  398. first, ferr := strconv.ParseInt(ctx.Args().Get(1), 10, 64)
  399. last, lerr := strconv.ParseInt(ctx.Args().Get(2), 10, 64)
  400. if ferr != nil || lerr != nil {
  401. utils.Fatalf("Export error in parsing parameters: block number not an integer\n")
  402. }
  403. if first < 0 || last < 0 {
  404. utils.Fatalf("Export error: block number must be greater than 0\n")
  405. }
  406. if head := chain.CurrentFastBlock(); uint64(last) > head.NumberU64() {
  407. utils.Fatalf("Export error: block number %d larger than head block %d\n", uint64(last), head.NumberU64())
  408. }
  409. err = utils.ExportAppendChain(chain, fp, uint64(first), uint64(last))
  410. }
  411. if 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. // importPreimages imports preimage data from the specified file.
  418. func importPreimages(ctx *cli.Context) error {
  419. if len(ctx.Args()) < 1 {
  420. utils.Fatalf("This command requires an argument.")
  421. }
  422. stack, _ := makeConfigNode(ctx)
  423. defer stack.Close()
  424. db := utils.MakeChainDatabase(ctx, stack, false, false)
  425. start := time.Now()
  426. if err := utils.ImportPreimages(db, ctx.Args().First()); err != nil {
  427. utils.Fatalf("Import error: %v\n", err)
  428. }
  429. fmt.Printf("Import done in %v\n", time.Since(start))
  430. return nil
  431. }
  432. // exportPreimages dumps the preimage data to specified json file in streaming way.
  433. func exportPreimages(ctx *cli.Context) error {
  434. if len(ctx.Args()) < 1 {
  435. utils.Fatalf("This command requires an argument.")
  436. }
  437. stack, _ := makeConfigNode(ctx)
  438. defer stack.Close()
  439. db := utils.MakeChainDatabase(ctx, stack, true, false)
  440. start := time.Now()
  441. if err := utils.ExportPreimages(db, ctx.Args().First()); err != nil {
  442. utils.Fatalf("Export error: %v\n", err)
  443. }
  444. fmt.Printf("Export done in %v\n", time.Since(start))
  445. return nil
  446. }
  447. func dump(ctx *cli.Context) error {
  448. stack, _ := makeConfigNode(ctx)
  449. defer stack.Close()
  450. db := utils.MakeChainDatabase(ctx, stack, true, false)
  451. for _, arg := range ctx.Args() {
  452. var header *types.Header
  453. if hashish(arg) {
  454. hash := common.HexToHash(arg)
  455. number := rawdb.ReadHeaderNumber(db, hash)
  456. if number != nil {
  457. header = rawdb.ReadHeader(db, hash, *number)
  458. }
  459. } else {
  460. number, _ := strconv.Atoi(arg)
  461. hash := rawdb.ReadCanonicalHash(db, uint64(number))
  462. if hash != (common.Hash{}) {
  463. header = rawdb.ReadHeader(db, hash, uint64(number))
  464. }
  465. }
  466. if header == nil {
  467. fmt.Println("{}")
  468. utils.Fatalf("block not found")
  469. } else {
  470. state, err := state.New(header.Root, state.NewDatabase(db), nil)
  471. if err != nil {
  472. utils.Fatalf("could not create new state: %v", err)
  473. }
  474. excludeCode := ctx.Bool(utils.ExcludeCodeFlag.Name)
  475. excludeStorage := ctx.Bool(utils.ExcludeStorageFlag.Name)
  476. includeMissing := ctx.Bool(utils.IncludeIncompletesFlag.Name)
  477. if ctx.Bool(utils.IterativeOutputFlag.Name) {
  478. state.IterativeDump(excludeCode, excludeStorage, !includeMissing, json.NewEncoder(os.Stdout))
  479. } else {
  480. if includeMissing {
  481. fmt.Printf("If you want to include accounts with missing preimages, you need iterative output, since" +
  482. " otherwise the accounts will overwrite each other in the resulting mapping.")
  483. }
  484. fmt.Printf("%v %s\n", includeMissing, state.Dump(excludeCode, excludeStorage, false))
  485. }
  486. }
  487. }
  488. return nil
  489. }
  490. // hashish returns true for strings that look like hashes.
  491. func hashish(x string) bool {
  492. _, err := strconv.Atoi(x)
  493. return err != nil
  494. }