dbcmd.go 24.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Copyright 2020 The go-ethereum Authors
// This file is part of go-ethereum.
//
// go-ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// go-ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.

package main

import (
20
	"bytes"
21 22
	"fmt"
	"os"
23
	"os/signal"
24
	"path/filepath"
25
	"sort"
26
	"strconv"
27 28
	"strings"
	"syscall"
29 30 31 32 33 34 35
	"time"

	"github.com/ethereum/go-ethereum/cmd/utils"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/ethereum/go-ethereum/console/prompt"
	"github.com/ethereum/go-ethereum/core/rawdb"
36
	"github.com/ethereum/go-ethereum/core/state/snapshot"
37
	"github.com/ethereum/go-ethereum/core/types"
38
	"github.com/ethereum/go-ethereum/crypto"
39 40
	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/log"
41
	"github.com/ethereum/go-ethereum/trie"
42
	"github.com/olekukonko/tablewriter"
43 44 45 46 47 48 49 50 51
	"gopkg.in/urfave/cli.v1"
)

var (
	removedbCommand = cli.Command{
		Action:    utils.MigrateFlags(removeDB),
		Name:      "removedb",
		Usage:     "Remove blockchain and state databases",
		ArgsUsage: "",
52 53
		Flags:     utils.DatabasePathFlags,
		Category:  "DATABASE COMMANDS",
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
		Description: `
Remove blockchain and state databases`,
	}
	dbCommand = cli.Command{
		Name:      "db",
		Usage:     "Low level database operations",
		ArgsUsage: "",
		Category:  "DATABASE COMMANDS",
		Subcommands: []cli.Command{
			dbInspectCmd,
			dbStatCmd,
			dbCompactCmd,
			dbGetCmd,
			dbDeleteCmd,
			dbPutCmd,
69
			dbGetSlotsCmd,
70
			dbDumpFreezerIndex,
71 72
			dbImportCmd,
			dbExportCmd,
73
			dbMetadataCmd,
74
			dbMigrateFreezerCmd,
75
			dbCheckStateContentCmd,
76 77 78 79 80 81
		},
	}
	dbInspectCmd = cli.Command{
		Action:    utils.MigrateFlags(inspect),
		Name:      "inspect",
		ArgsUsage: "<prefix> <start>",
82
		Flags: utils.GroupFlags([]cli.Flag{
83
			utils.SyncModeFlag,
84
		}, utils.NetworkFlags, utils.DatabasePathFlags),
85 86 87
		Usage:       "Inspect the storage size for each type of data in the database",
		Description: `This commands iterates the entire database. If the optional 'prefix' and 'start' arguments are provided, then the iteration is limited to the given subset of data.`,
	}
88 89 90 91 92 93 94 95 96 97
	dbCheckStateContentCmd = cli.Command{
		Action:    utils.MigrateFlags(checkStateContent),
		Name:      "check-state-content",
		ArgsUsage: "<start (optional)>",
		Flags:     utils.GroupFlags(utils.NetworkFlags, utils.DatabasePathFlags),
		Usage:     "Verify that state data is cryptographically correct",
		Description: `This command iterates the entire database for 32-byte keys, looking for rlp-encoded trie nodes.
For each trie node encountered, it checks that the key corresponds to the keccak256(value). If this is not true, this indicates
a data corruption.`,
	}
98
	dbStatCmd = cli.Command{
99
		Action: utils.MigrateFlags(dbStats),
100 101
		Name:   "stats",
		Usage:  "Print leveldb statistics",
102
		Flags: utils.GroupFlags([]cli.Flag{
103
			utils.SyncModeFlag,
104
		}, utils.NetworkFlags, utils.DatabasePathFlags),
105 106
	}
	dbCompactCmd = cli.Command{
107
		Action: utils.MigrateFlags(dbCompact),
108 109
		Name:   "compact",
		Usage:  "Compact leveldb database. WARNING: May take a very long time",
110
		Flags: utils.GroupFlags([]cli.Flag{
111 112 113
			utils.SyncModeFlag,
			utils.CacheFlag,
			utils.CacheDatabaseFlag,
114
		}, utils.NetworkFlags, utils.DatabasePathFlags),
115 116 117 118 119
		Description: `This command performs a database compaction. 
WARNING: This operation may take a very long time to finish, and may cause database
corruption if it is aborted during execution'!`,
	}
	dbGetCmd = cli.Command{
120 121 122 123
		Action:    utils.MigrateFlags(dbGet),
		Name:      "get",
		Usage:     "Show the value of a database key",
		ArgsUsage: "<hex-encoded key>",
124
		Flags: utils.GroupFlags([]cli.Flag{
125
			utils.SyncModeFlag,
126
		}, utils.NetworkFlags, utils.DatabasePathFlags),
127 128 129
		Description: "This command looks up the specified database key from the database.",
	}
	dbDeleteCmd = cli.Command{
130
		Action:    utils.MigrateFlags(dbDelete),
131 132 133
		Name:      "delete",
		Usage:     "Delete a database key (WARNING: may corrupt your database)",
		ArgsUsage: "<hex-encoded key>",
134
		Flags: utils.GroupFlags([]cli.Flag{
135
			utils.SyncModeFlag,
136
		}, utils.NetworkFlags, utils.DatabasePathFlags),
137 138 139 140
		Description: `This command deletes the specified database key from the database. 
WARNING: This is a low-level operation which may cause database corruption!`,
	}
	dbPutCmd = cli.Command{
141
		Action:    utils.MigrateFlags(dbPut),
142 143 144
		Name:      "put",
		Usage:     "Set the value of a database key (WARNING: may corrupt your database)",
		ArgsUsage: "<hex-encoded key> <hex-encoded value>",
145
		Flags: utils.GroupFlags([]cli.Flag{
146
			utils.SyncModeFlag,
147
		}, utils.NetworkFlags, utils.DatabasePathFlags),
148 149 150
		Description: `This command sets a given database key to the given value. 
WARNING: This is a low-level operation which may cause database corruption!`,
	}
151 152 153 154 155
	dbGetSlotsCmd = cli.Command{
		Action:    utils.MigrateFlags(dbDumpTrie),
		Name:      "dumptrie",
		Usage:     "Show the storage key/values of a given storage trie",
		ArgsUsage: "<hex-encoded storage trie root> <hex-encoded start (optional)> <int max elements (optional)>",
156
		Flags: utils.GroupFlags([]cli.Flag{
157
			utils.SyncModeFlag,
158
		}, utils.NetworkFlags, utils.DatabasePathFlags),
159 160
		Description: "This command looks up the specified database key from the database.",
	}
161 162 163 164 165
	dbDumpFreezerIndex = cli.Command{
		Action:    utils.MigrateFlags(freezerInspect),
		Name:      "freezer-index",
		Usage:     "Dump out the index of a given freezer type",
		ArgsUsage: "<type> <start (int)> <end (int)>",
166
		Flags: utils.GroupFlags([]cli.Flag{
167
			utils.SyncModeFlag,
168
		}, utils.NetworkFlags, utils.DatabasePathFlags),
169 170
		Description: "This command displays information about the freezer index.",
	}
171 172 173 174 175
	dbImportCmd = cli.Command{
		Action:    utils.MigrateFlags(importLDBdata),
		Name:      "import",
		Usage:     "Imports leveldb-data from an exported RLP dump.",
		ArgsUsage: "<dumpfile> <start (optional)",
176
		Flags: utils.GroupFlags([]cli.Flag{
177
			utils.SyncModeFlag,
178
		}, utils.NetworkFlags, utils.DatabasePathFlags),
179 180 181 182 183 184 185
		Description: "The import command imports the specific chain data from an RLP encoded stream.",
	}
	dbExportCmd = cli.Command{
		Action:    utils.MigrateFlags(exportChaindata),
		Name:      "export",
		Usage:     "Exports the chain data into an RLP dump. If the <dumpfile> has .gz suffix, gzip compression will be used.",
		ArgsUsage: "<type> <dumpfile>",
186
		Flags: utils.GroupFlags([]cli.Flag{
187
			utils.SyncModeFlag,
188
		}, utils.NetworkFlags, utils.DatabasePathFlags),
189 190
		Description: "Exports the specified chain data to an RLP encoded stream, optionally gzip-compressed.",
	}
191 192 193 194
	dbMetadataCmd = cli.Command{
		Action: utils.MigrateFlags(showMetaData),
		Name:   "metadata",
		Usage:  "Shows metadata about the chain status.",
195
		Flags: utils.GroupFlags([]cli.Flag{
196
			utils.SyncModeFlag,
197
		}, utils.NetworkFlags, utils.DatabasePathFlags),
198 199
		Description: "Shows metadata about the chain status.",
	}
200 201 202 203 204
	dbMigrateFreezerCmd = cli.Command{
		Action:    utils.MigrateFlags(freezerMigrate),
		Name:      "freezer-migrate",
		Usage:     "Migrate legacy parts of the freezer. (WARNING: may take a long time)",
		ArgsUsage: "",
205
		Flags: utils.GroupFlags([]cli.Flag{
206
			utils.SyncModeFlag,
207
		}, utils.NetworkFlags, utils.DatabasePathFlags),
208 209 210
		Description: `The freezer-migrate command checks your database for receipts in a legacy format and updates those.
WARNING: please back-up the receipt files in your ancients before running this command.`,
	}
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
)

func removeDB(ctx *cli.Context) error {
	stack, config := makeConfigNode(ctx)

	// Remove the full node state database
	path := stack.ResolvePath("chaindata")
	if common.FileExist(path) {
		confirmAndRemoveDB(path, "full node state database")
	} else {
		log.Info("Full node state database missing", "path", path)
	}
	// Remove the full node ancient database
	path = config.Eth.DatabaseFreezer
	switch {
	case path == "":
		path = filepath.Join(stack.ResolvePath("chaindata"), "ancient")
	case !filepath.IsAbs(path):
		path = config.Node.ResolvePath(path)
	}
	if common.FileExist(path) {
		confirmAndRemoveDB(path, "full node ancient database")
	} else {
		log.Info("Full node ancient database missing", "path", path)
	}
	// Remove the light node database
	path = stack.ResolvePath("lightchaindata")
	if common.FileExist(path) {
		confirmAndRemoveDB(path, "light node database")
	} else {
		log.Info("Light node database missing", "path", path)
	}
	return nil
}

// confirmAndRemoveDB prompts the user for a last confirmation and removes the
// folder if accepted.
func confirmAndRemoveDB(database string, kind string) {
	confirm, err := prompt.Stdin.PromptConfirm(fmt.Sprintf("Remove %s (%s)?", kind, database))
	switch {
	case err != nil:
		utils.Fatalf("%v", err)
	case !confirm:
		log.Info("Database deletion skipped", "path", database)
	default:
		start := time.Now()
		filepath.Walk(database, func(path string, info os.FileInfo, err error) error {
			// If we're at the top level folder, recurse into
			if path == database {
				return nil
			}
			// Delete all the files, but not subfolders
			if !info.IsDir() {
				os.Remove(path)
				return nil
			}
			return filepath.SkipDir
		})
		log.Info("Database successfully deleted", "path", database, "elapsed", common.PrettyDuration(time.Since(start)))
	}
}

func inspect(ctx *cli.Context) error {
	var (
		prefix []byte
		start  []byte
	)
	if ctx.NArg() > 2 {
		return fmt.Errorf("Max 2 arguments: %v", ctx.Command.ArgsUsage)
	}
	if ctx.NArg() >= 1 {
		if d, err := hexutil.Decode(ctx.Args().Get(0)); err != nil {
			return fmt.Errorf("failed to hex-decode 'prefix': %v", err)
		} else {
			prefix = d
		}
	}
	if ctx.NArg() >= 2 {
		if d, err := hexutil.Decode(ctx.Args().Get(1)); err != nil {
			return fmt.Errorf("failed to hex-decode 'start': %v", err)
		} else {
			start = d
		}
	}
	stack, _ := makeConfigNode(ctx)
	defer stack.Close()

298 299
	db := utils.MakeChainDatabase(ctx, stack, true)
	defer db.Close()
300

301
	return rawdb.InspectDatabase(db, prefix, start)
302 303
}

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
func checkStateContent(ctx *cli.Context) error {
	var (
		prefix []byte
		start  []byte
	)
	if ctx.NArg() > 1 {
		return fmt.Errorf("Max 1 argument: %v", ctx.Command.ArgsUsage)
	}
	if ctx.NArg() > 0 {
		if d, err := hexutil.Decode(ctx.Args().First()); err != nil {
			return fmt.Errorf("failed to hex-decode 'start': %v", err)
		} else {
			start = d
		}
	}
	stack, _ := makeConfigNode(ctx)
	defer stack.Close()

	db := utils.MakeChainDatabase(ctx, stack, true)
	defer db.Close()
	var (
		it        = rawdb.NewKeyLengthIterator(db.NewIterator(prefix, start), 32)
		hasher    = crypto.NewKeccakState()
		got       = make([]byte, 32)
		errs      int
		count     int
		startTime = time.Now()
		lastLog   = time.Now()
	)
	for it.Next() {
		count++
		v := it.Value()
		k := it.Key()
		hasher.Reset()
		hasher.Write(v)
		hasher.Read(got)
		if !bytes.Equal(k, got) {
			errs++
			fmt.Printf("Error at 0x%x\n", k)
			fmt.Printf("  Hash:  0x%x\n", got)
			fmt.Printf("  Data:  0x%x\n", v)
		}
		if time.Since(lastLog) > 8*time.Second {
			log.Info("Iterating the database", "at", fmt.Sprintf("%#x", k), "elapsed", common.PrettyDuration(time.Since(startTime)))
			lastLog = time.Now()
		}
	}
	if err := it.Error(); err != nil {
		return err
	}
	log.Info("Iterated the state content", "errors", errs, "items", count)
	return nil
}

358
func showLeveldbStats(db ethdb.KeyValueStater) {
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
	if stats, err := db.Stat("leveldb.stats"); err != nil {
		log.Warn("Failed to read database stats", "error", err)
	} else {
		fmt.Println(stats)
	}
	if ioStats, err := db.Stat("leveldb.iostats"); err != nil {
		log.Warn("Failed to read database iostats", "error", err)
	} else {
		fmt.Println(ioStats)
	}
}

func dbStats(ctx *cli.Context) error {
	stack, _ := makeConfigNode(ctx)
	defer stack.Close()
374 375 376 377

	db := utils.MakeChainDatabase(ctx, stack, true)
	defer db.Close()

378 379 380 381 382 383 384
	showLeveldbStats(db)
	return nil
}

func dbCompact(ctx *cli.Context) error {
	stack, _ := makeConfigNode(ctx)
	defer stack.Close()
385 386 387 388 389

	db := utils.MakeChainDatabase(ctx, stack, false)
	defer db.Close()

	log.Info("Stats before compaction")
390
	showLeveldbStats(db)
391

392
	log.Info("Triggering compaction")
393
	if err := db.Compact(nil, nil); err != nil {
394
		log.Info("Compact err", "error", err)
395
		return err
396
	}
397
	log.Info("Stats after compaction")
398
	showLeveldbStats(db)
399
	return nil
400 401 402 403 404 405 406 407 408
}

// dbGet shows the value of a given database key
func dbGet(ctx *cli.Context) error {
	if ctx.NArg() != 1 {
		return fmt.Errorf("required arguments: %v", ctx.Command.ArgsUsage)
	}
	stack, _ := makeConfigNode(ctx)
	defer stack.Close()
409 410

	db := utils.MakeChainDatabase(ctx, stack, true)
411
	defer db.Close()
412

413
	key, err := common.ParseHexOrString(ctx.Args().Get(0))
414 415 416 417
	if err != nil {
		log.Info("Could not decode the key", "error", err)
		return err
	}
418

419 420
	data, err := db.Get(key)
	if err != nil {
421
		log.Info("Get operation failed", "key", fmt.Sprintf("0x%#x", key), "error", err)
422 423
		return err
	}
424
	fmt.Printf("key %#x: %#x\n", key, data)
425 426 427 428 429 430 431 432 433 434
	return nil
}

// dbDelete deletes a key from the database
func dbDelete(ctx *cli.Context) error {
	if ctx.NArg() != 1 {
		return fmt.Errorf("required arguments: %v", ctx.Command.ArgsUsage)
	}
	stack, _ := makeConfigNode(ctx)
	defer stack.Close()
435 436

	db := utils.MakeChainDatabase(ctx, stack, false)
437
	defer db.Close()
438

439
	key, err := common.ParseHexOrString(ctx.Args().Get(0))
440 441 442 443
	if err != nil {
		log.Info("Could not decode the key", "error", err)
		return err
	}
444 445 446 447
	data, err := db.Get(key)
	if err == nil {
		fmt.Printf("Previous value: %#x\n", data)
	}
448
	if err = db.Delete(key); err != nil {
449
		log.Info("Delete operation returned an error", "key", fmt.Sprintf("0x%#x", key), "error", err)
450 451 452 453 454 455 456 457 458 459 460 461
		return err
	}
	return nil
}

// dbPut overwrite a value in the database
func dbPut(ctx *cli.Context) error {
	if ctx.NArg() != 2 {
		return fmt.Errorf("required arguments: %v", ctx.Command.ArgsUsage)
	}
	stack, _ := makeConfigNode(ctx)
	defer stack.Close()
462 463

	db := utils.MakeChainDatabase(ctx, stack, false)
464
	defer db.Close()
465

466 467 468 469 470 471
	var (
		key   []byte
		value []byte
		data  []byte
		err   error
	)
472
	key, err = common.ParseHexOrString(ctx.Args().Get(0))
473 474 475 476 477 478 479 480 481 482 483
	if err != nil {
		log.Info("Could not decode the key", "error", err)
		return err
	}
	value, err = hexutil.Decode(ctx.Args().Get(1))
	if err != nil {
		log.Info("Could not decode the value", "error", err)
		return err
	}
	data, err = db.Get(key)
	if err == nil {
484
		fmt.Printf("Previous value: %#x\n", data)
485 486 487
	}
	return db.Put(key, value)
}
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

// dbDumpTrie shows the key-value slots of a given storage trie
func dbDumpTrie(ctx *cli.Context) error {
	if ctx.NArg() < 1 {
		return fmt.Errorf("required arguments: %v", ctx.Command.ArgsUsage)
	}
	stack, _ := makeConfigNode(ctx)
	defer stack.Close()

	db := utils.MakeChainDatabase(ctx, stack, true)
	defer db.Close()
	var (
		root  []byte
		start []byte
		max   = int64(-1)
		err   error
	)
	if root, err = hexutil.Decode(ctx.Args().Get(0)); err != nil {
		log.Info("Could not decode the root", "error", err)
		return err
	}
	stRoot := common.BytesToHash(root)
	if ctx.NArg() >= 2 {
		if start, err = hexutil.Decode(ctx.Args().Get(1)); err != nil {
			log.Info("Could not decode the seek position", "error", err)
			return err
		}
	}
	if ctx.NArg() >= 3 {
		if max, err = strconv.ParseInt(ctx.Args().Get(2), 10, 64); err != nil {
			log.Info("Could not decode the max count", "error", err)
			return err
		}
	}
	theTrie, err := trie.New(stRoot, trie.NewDatabase(db))
	if err != nil {
		return err
	}
	var count int64
	it := trie.NewIterator(theTrie.NodeIterator(start))
	for it.Next() {
		if max > 0 && count == max {
			fmt.Printf("Exiting after %d values\n", count)
			break
		}
		fmt.Printf("  %d. key %#x: %#x\n", count, it.Key, it.Value)
		count++
	}
	return it.Err
}
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570

func freezerInspect(ctx *cli.Context) error {
	var (
		start, end    int64
		disableSnappy bool
		err           error
	)
	if ctx.NArg() < 3 {
		return fmt.Errorf("required arguments: %v", ctx.Command.ArgsUsage)
	}
	kind := ctx.Args().Get(0)
	if noSnap, ok := rawdb.FreezerNoSnappy[kind]; !ok {
		var options []string
		for opt := range rawdb.FreezerNoSnappy {
			options = append(options, opt)
		}
		sort.Strings(options)
		return fmt.Errorf("Could read freezer-type '%v'. Available options: %v", kind, options)
	} else {
		disableSnappy = noSnap
	}
	if start, err = strconv.ParseInt(ctx.Args().Get(1), 10, 64); err != nil {
		log.Info("Could read start-param", "error", err)
		return err
	}
	if end, err = strconv.ParseInt(ctx.Args().Get(2), 10, 64); err != nil {
		log.Info("Could read count param", "error", err)
		return err
	}
	stack, _ := makeConfigNode(ctx)
	defer stack.Close()
	path := filepath.Join(stack.ResolvePath("chaindata"), "ancient")
	log.Info("Opening freezer", "location", path, "name", kind)
571
	if f, err := rawdb.NewFreezerTable(path, kind, disableSnappy, true); err != nil {
572 573 574 575 576 577
		return err
	} else {
		f.DumpIndex(start, end)
	}
	return nil
}
578

579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
func importLDBdata(ctx *cli.Context) error {
	start := 0
	switch ctx.NArg() {
	case 1:
		break
	case 2:
		s, err := strconv.Atoi(ctx.Args().Get(1))
		if err != nil {
			return fmt.Errorf("second arg must be an integer: %v", err)
		}
		start = s
	default:
		return fmt.Errorf("required arguments: %v", ctx.Command.ArgsUsage)
	}
	var (
		fName     = ctx.Args().Get(0)
		stack, _  = makeConfigNode(ctx)
		interrupt = make(chan os.Signal, 1)
		stop      = make(chan struct{})
	)
	defer stack.Close()
	signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
	defer signal.Stop(interrupt)
	defer close(interrupt)
	go func() {
		if _, ok := <-interrupt; ok {
			log.Info("Interrupted during ldb import, stopping at next batch")
		}
		close(stop)
	}()
	db := utils.MakeChainDatabase(ctx, stack, false)
	return utils.ImportLDBData(db, fName, int64(start), stop)
}

type preimageIterator struct {
	iter ethdb.Iterator
}

func (iter *preimageIterator) Next() (byte, []byte, []byte, bool) {
	for iter.iter.Next() {
		key := iter.iter.Key()
		if bytes.HasPrefix(key, rawdb.PreimagePrefix) && len(key) == (len(rawdb.PreimagePrefix)+common.HashLength) {
			return utils.OpBatchAdd, key, iter.iter.Value(), true
		}
	}
	return 0, nil, nil, false
}

func (iter *preimageIterator) Release() {
	iter.iter.Release()
}

type snapshotIterator struct {
	init    bool
	account ethdb.Iterator
	storage ethdb.Iterator
}

func (iter *snapshotIterator) Next() (byte, []byte, []byte, bool) {
	if !iter.init {
		iter.init = true
		return utils.OpBatchDel, rawdb.SnapshotRootKey, nil, true
	}
	for iter.account.Next() {
		key := iter.account.Key()
		if bytes.HasPrefix(key, rawdb.SnapshotAccountPrefix) && len(key) == (len(rawdb.SnapshotAccountPrefix)+common.HashLength) {
			return utils.OpBatchAdd, key, iter.account.Value(), true
		}
	}
	for iter.storage.Next() {
		key := iter.storage.Key()
		if bytes.HasPrefix(key, rawdb.SnapshotStoragePrefix) && len(key) == (len(rawdb.SnapshotStoragePrefix)+2*common.HashLength) {
			return utils.OpBatchAdd, key, iter.storage.Value(), true
		}
	}
	return 0, nil, nil, false
}

func (iter *snapshotIterator) Release() {
	iter.account.Release()
	iter.storage.Release()
}

// chainExporters defines the export scheme for all exportable chain data.
var chainExporters = map[string]func(db ethdb.Database) utils.ChainDataIterator{
	"preimage": func(db ethdb.Database) utils.ChainDataIterator {
		iter := db.NewIterator(rawdb.PreimagePrefix, nil)
		return &preimageIterator{iter: iter}
	},
	"snapshot": func(db ethdb.Database) utils.ChainDataIterator {
		account := db.NewIterator(rawdb.SnapshotAccountPrefix, nil)
		storage := db.NewIterator(rawdb.SnapshotStoragePrefix, nil)
		return &snapshotIterator{account: account, storage: storage}
	},
}

func exportChaindata(ctx *cli.Context) error {
	if ctx.NArg() < 2 {
		return fmt.Errorf("required arguments: %v", ctx.Command.ArgsUsage)
	}
	// Parse the required chain data type, make sure it's supported.
	kind := ctx.Args().Get(0)
	kind = strings.ToLower(strings.Trim(kind, " "))
	exporter, ok := chainExporters[kind]
	if !ok {
		var kinds []string
		for kind := range chainExporters {
			kinds = append(kinds, kind)
		}
		return fmt.Errorf("invalid data type %s, supported types: %s", kind, strings.Join(kinds, ", "))
	}
	var (
		stack, _  = makeConfigNode(ctx)
		interrupt = make(chan os.Signal, 1)
		stop      = make(chan struct{})
	)
	defer stack.Close()
	signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
	defer signal.Stop(interrupt)
	defer close(interrupt)
	go func() {
		if _, ok := <-interrupt; ok {
			log.Info("Interrupted during db export, stopping at next batch")
		}
		close(stop)
	}()
	db := utils.MakeChainDatabase(ctx, stack, true)
	return utils.ExportChaindata(ctx.Args().Get(1), kind, exporter(db), stop)
}
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732

func showMetaData(ctx *cli.Context) error {
	stack, _ := makeConfigNode(ctx)
	defer stack.Close()
	db := utils.MakeChainDatabase(ctx, stack, true)
	ancients, err := db.Ancients()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error accessing ancients: %v", err)
	}
	pp := func(val *uint64) string {
		if val == nil {
			return "<nil>"
		}
		return fmt.Sprintf("%d (0x%x)", *val, *val)
	}
	data := [][]string{
		{"databaseVersion", pp(rawdb.ReadDatabaseVersion(db))},
		{"headBlockHash", fmt.Sprintf("%v", rawdb.ReadHeadBlockHash(db))},
		{"headFastBlockHash", fmt.Sprintf("%v", rawdb.ReadHeadFastBlockHash(db))},
		{"headHeaderHash", fmt.Sprintf("%v", rawdb.ReadHeadHeaderHash(db))}}
	if b := rawdb.ReadHeadBlock(db); b != nil {
		data = append(data, []string{"headBlock.Hash", fmt.Sprintf("%v", b.Hash())})
		data = append(data, []string{"headBlock.Root", fmt.Sprintf("%v", b.Root())})
		data = append(data, []string{"headBlock.Number", fmt.Sprintf("%d (0x%x)", b.Number(), b.Number())})
	}
733 734 735
	if b := rawdb.ReadSkeletonSyncStatus(db); b != nil {
		data = append(data, []string{"SkeletonSyncStatus", string(b)})
	}
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757
	if h := rawdb.ReadHeadHeader(db); h != nil {
		data = append(data, []string{"headHeader.Hash", fmt.Sprintf("%v", h.Hash())})
		data = append(data, []string{"headHeader.Root", fmt.Sprintf("%v", h.Root)})
		data = append(data, []string{"headHeader.Number", fmt.Sprintf("%d (0x%x)", h.Number, h.Number)})
	}
	data = append(data, [][]string{{"frozen", fmt.Sprintf("%d items", ancients)},
		{"lastPivotNumber", pp(rawdb.ReadLastPivotNumber(db))},
		{"len(snapshotSyncStatus)", fmt.Sprintf("%d bytes", len(rawdb.ReadSnapshotSyncStatus(db)))},
		{"snapshotGenerator", snapshot.ParseGeneratorStatus(rawdb.ReadSnapshotGenerator(db))},
		{"snapshotDisabled", fmt.Sprintf("%v", rawdb.ReadSnapshotDisabled(db))},
		{"snapshotJournal", fmt.Sprintf("%d bytes", len(rawdb.ReadSnapshotJournal(db)))},
		{"snapshotRecoveryNumber", pp(rawdb.ReadSnapshotRecoveryNumber(db))},
		{"snapshotRoot", fmt.Sprintf("%v", rawdb.ReadSnapshotRoot(db))},
		{"txIndexTail", pp(rawdb.ReadTxIndexTail(db))},
		{"fastTxLookupLimit", pp(rawdb.ReadFastTxLookupLimit(db))},
	}...)
	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Field", "Value"})
	table.AppendBulk(data)
	table.Render()
	return nil
}
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842

func freezerMigrate(ctx *cli.Context) error {
	stack, _ := makeConfigNode(ctx)
	defer stack.Close()

	db := utils.MakeChainDatabase(ctx, stack, false)
	defer db.Close()

	// Check first block for legacy receipt format
	numAncients, err := db.Ancients()
	if err != nil {
		return err
	}
	if numAncients < 1 {
		log.Info("No receipts in freezer to migrate")
		return nil
	}

	isFirstLegacy, firstIdx, err := dbHasLegacyReceipts(db, 0)
	if err != nil {
		return err
	}
	if !isFirstLegacy {
		log.Info("No legacy receipts to migrate")
		return nil
	}

	log.Info("Starting migration", "ancients", numAncients, "firstLegacy", firstIdx)
	start := time.Now()
	if err := db.MigrateTable("receipts", types.ConvertLegacyStoredReceipts); err != nil {
		return err
	}
	if err := db.Close(); err != nil {
		return err
	}
	log.Info("Migration finished", "duration", time.Since(start))

	return nil
}

// dbHasLegacyReceipts checks freezer entries for legacy receipts. It stops at the first
// non-empty receipt and checks its format. The index of this first non-empty element is
// the second return parameter.
func dbHasLegacyReceipts(db ethdb.Database, firstIdx uint64) (bool, uint64, error) {
	// Check first block for legacy receipt format
	numAncients, err := db.Ancients()
	if err != nil {
		return false, 0, err
	}
	if numAncients < 1 {
		return false, 0, nil
	}
	if firstIdx >= numAncients {
		return false, firstIdx, nil
	}
	var (
		legacy       bool
		blob         []byte
		emptyRLPList = []byte{192}
	)
	// Find first block with non-empty receipt, only if
	// the index is not already provided.
	if firstIdx == 0 {
		for i := uint64(0); i < numAncients; i++ {
			blob, err = db.Ancient("receipts", i)
			if err != nil {
				return false, 0, err
			}
			if len(blob) == 0 {
				continue
			}
			if !bytes.Equal(blob, emptyRLPList) {
				firstIdx = i
				break
			}
		}
	}
	// Is first non-empty receipt legacy?
	first, err := db.Ancient("receipts", firstIdx)
	if err != nil {
		return false, 0, err
	}
	legacy, err = types.IsLegacyStoredReceipts(first)
	return legacy, firstIdx, err
}