cosmos-sdk/server/export.go
Christopher Goes ad121f1498 Add a flag to export for zero-height start (#2827)
Closes #2812

This PR adds the flag --for-zero-height to gaiad export, which runs several alterations to the application state to prepare for restarting a new chain in a consistent fashion.

It also:

* Moves Gaia's export code to cmd/gaia/app/export.go for cleaner separation.
* Fixes an inconsistency where we treated the initChainer as happening at height -1 - it should now happen at height 0, since the first header sent by Tendermint has height 1.
* Runs the runtime invariant checks on start (in initChainer)
* Adds a few auxiliary functions to clear slashing periods
* Removes the Height field from Delegation objects in x/stake, which was not used anywhere
2018-11-26 04:21:23 -08:00

90 lines
2.1 KiB
Go

package server
import (
"fmt"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/cosmos/cosmos-sdk/codec"
tmtypes "github.com/tendermint/tendermint/types"
"io/ioutil"
"path"
)
const (
flagHeight = "height"
flagForZeroHeight = "for-zero-height"
)
// ExportCmd dumps app state to JSON.
func ExportCmd(ctx *Context, cdc *codec.Codec, appExporter AppExporter) *cobra.Command {
cmd := &cobra.Command{
Use: "export",
Short: "Export state to JSON",
RunE: func(cmd *cobra.Command, args []string) error {
home := viper.GetString("home")
traceWriterFile := viper.GetString(flagTraceStore)
emptyState, err := isEmptyState(home)
if err != nil {
return err
}
if emptyState {
fmt.Println("WARNING: State is not initialized. Returning genesis file.")
genesisFile := path.Join(home, "config", "genesis.json")
genesis, err := ioutil.ReadFile(genesisFile)
if err != nil {
return err
}
fmt.Println(string(genesis))
return nil
}
db, err := openDB(home)
if err != nil {
return err
}
traceWriter, err := openTraceWriter(traceWriterFile)
if err != nil {
return err
}
height := viper.GetInt64(flagHeight)
forZeroHeight := viper.GetBool(flagForZeroHeight)
appState, validators, err := appExporter(ctx.Logger, db, traceWriter, height, forZeroHeight)
if err != nil {
return errors.Errorf("error exporting state: %v\n", err)
}
doc, err := tmtypes.GenesisDocFromFile(ctx.Config.GenesisFile())
if err != nil {
return err
}
doc.AppState = appState
doc.Validators = validators
encoded, err := codec.MarshalJSONIndent(cdc, doc)
if err != nil {
return err
}
fmt.Println(string(encoded))
return nil
},
}
cmd.Flags().Int64(flagHeight, -1, "Export state from a particular height (-1 means latest height)")
cmd.Flags().Bool(flagForZeroHeight, false, "Export state to start at height zero (perform preproccessing)")
return cmd
}
func isEmptyState(home string) (bool, error) {
files, err := ioutil.ReadDir(path.Join(home, "data"))
if err != nil {
return false, err
}
return len(files) == 0, nil
}