chaincmd.go 13 KB

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