export funcs for AragonChain (#423)

* export funcs for AragonChain

* update comments
This commit is contained in:
Federico Kunze
2020-08-04 14:52:32 -04:00
committed by GitHub
parent 9a79bcc4f5
commit 241fb2fe83
7 changed files with 196 additions and 179 deletions
-82
View File
@@ -1,82 +0,0 @@
package main
import (
"bufio"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/ethereum/go-ethereum/common/hexutil"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
emintcrypto "github.com/cosmos/ethermint/crypto"
)
func unsafeExportEthKeyCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "unsafe-export-eth-key [name]",
Short: "**UNSAFE** Export an Ethereum private key",
Long: `**UNSAFE** Export an Ethereum private key unencrypted to use in dev tooling`,
Args: cobra.ExactArgs(1),
RunE: runExportCmd,
}
return cmd
}
func runExportCmd(cmd *cobra.Command, args []string) error {
inBuf := bufio.NewReader(cmd.InOrStdin())
kb, err := keyring.NewKeyring(
sdk.KeyringServiceName(),
viper.GetString(flags.FlagKeyringBackend),
viper.GetString(flags.FlagHome),
inBuf,
)
if err != nil {
return err
}
decryptPassword := ""
conf := true
keyringBackend := viper.GetString(flags.FlagKeyringBackend)
switch keyringBackend {
case keyring.BackendFile:
decryptPassword, err = input.GetPassword(
"**WARNING this is an unsafe way to export your unencrypted private key**\nEnter key password:",
inBuf)
case keyring.BackendOS:
conf, err = input.GetConfirmation(
"**WARNING** this is an unsafe way to export your unencrypted private key, are you sure?",
inBuf)
}
if err != nil || !conf {
return err
}
// Exports private key from keybase using password
privKey, err := kb.ExportPrivateKeyObject(args[0], decryptPassword)
if err != nil {
return err
}
// Converts key to Ethermint secp256 implementation
emintKey, ok := privKey.(emintcrypto.PrivKeySecp256k1)
if !ok {
return fmt.Errorf("invalid private key type, must be Ethereum key: %T", privKey)
}
// Formats key for output
privB := ethcrypto.FromECDSA(emintKey.ToECDSA())
keyS := strings.ToUpper(hexutil.Encode(privB)[2:])
fmt.Println(keyS)
return nil
}
-74
View File
@@ -1,74 +0,0 @@
package main
import (
"bufio"
"io"
"github.com/cosmos/cosmos-sdk/client/flags"
clientkeys "github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/ethermint/crypto"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
flagDryRun = "dry-run"
)
// keyCommands registers a sub-tree of commands to interact with
// local private key storage.
func keyCommands() *cobra.Command {
cmd := &cobra.Command{
Use: "keys",
Short: "Add or view local private keys",
Long: `Keys allows you to manage your local keystore for tendermint.
These keys may be in any format supported by go-crypto and can be
used by light-clients, full nodes, or any other application that
needs to sign with a private key.`,
}
addCmd := clientkeys.AddKeyCommand()
addCmd.RunE = runAddCmd
cmd.AddCommand(
clientkeys.MnemonicKeyCommand(),
addCmd,
clientkeys.ExportKeyCommand(),
clientkeys.ImportKeyCommand(),
clientkeys.ListKeysCmd(),
clientkeys.ShowKeysCmd(),
flags.LineBreak,
clientkeys.DeleteKeyCommand(),
clientkeys.ParseKeyStringCommand(),
clientkeys.MigrateCommand(),
flags.LineBreak,
unsafeExportEthKeyCommand(),
)
return cmd
}
func getKeybase(transient bool, buf io.Reader) (keyring.Keybase, error) {
if transient {
return keyring.NewInMemory(keyring.WithKeygenFunc(crypto.EthermintKeygenFunc)), nil
}
return keyring.NewKeyring(
sdk.KeyringServiceName(),
viper.GetString(flags.FlagKeyringBackend),
viper.GetString(flags.FlagHome),
buf,
keyring.WithKeygenFunc(crypto.EthermintKeygenFunc))
}
func runAddCmd(cmd *cobra.Command, args []string) error {
inBuf := bufio.NewReader(cmd.InOrStdin())
kb, err := getKeybase(viper.GetBool(flagDryRun), inBuf)
if err != nil {
return err
}
return clientkeys.RunAddCmd(cmd, args, kb, inBuf)
}
+12 -37
View File
@@ -2,21 +2,13 @@ package main
import (
"fmt"
"os"
"path"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/cosmos/ethermint/app"
"github.com/cosmos/ethermint/codec"
emintcrypto "github.com/cosmos/ethermint/crypto"
"github.com/cosmos/ethermint/rpc"
tmamino "github.com/tendermint/tendermint/crypto/encoding/amino"
"github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client"
sdkclient "github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
clientkeys "github.com/cosmos/cosmos-sdk/client/keys"
clientrpc "github.com/cosmos/cosmos-sdk/client/rpc"
@@ -28,6 +20,12 @@ import (
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
"github.com/cosmos/cosmos-sdk/x/bank"
bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli"
"github.com/cosmos/ethermint/app"
"github.com/cosmos/ethermint/client"
"github.com/cosmos/ethermint/codec"
"github.com/cosmos/ethermint/crypto"
"github.com/cosmos/ethermint/rpc"
)
var (
@@ -38,8 +36,8 @@ func main() {
// Configure cobra to sort commands
cobra.EnableCommandSorting = false
tmamino.RegisterKeyType(emintcrypto.PubKeySecp256k1{}, emintcrypto.PubKeyAminoName)
tmamino.RegisterKeyType(emintcrypto.PrivKeySecp256k1{}, emintcrypto.PrivKeyAminoName)
tmamino.RegisterKeyType(crypto.PubKeySecp256k1{}, crypto.PubKeyAminoName)
tmamino.RegisterKeyType(crypto.PrivKeySecp256k1{}, crypto.PrivKeyAminoName)
keyring.CryptoCdc = cdc
clientkeys.KeysCdc = cdc
@@ -59,18 +57,18 @@ func main() {
// Add --chain-id to persistent flags and mark it required
rootCmd.PersistentFlags().String(flags.FlagChainID, "", "Chain ID of tendermint node")
rootCmd.PersistentPreRunE = func(_ *cobra.Command, _ []string) error {
return initConfig(rootCmd)
return client.InitConfig(rootCmd)
}
// Construct Root Command
rootCmd.AddCommand(
clientrpc.StatusCommand(),
client.ConfigCmd(app.DefaultCLIHome),
sdkclient.ConfigCmd(app.DefaultCLIHome),
queryCmd(cdc),
txCmd(cdc),
rpc.EmintServeCmd(cdc),
flags.LineBreak,
keyCommands(),
client.KeyCommands(),
flags.LineBreak,
version.Cmd,
flags.NewCompletionCmd(rootCmd, true),
@@ -140,26 +138,3 @@ func txCmd(cdc *sdkcodec.Codec) *cobra.Command {
return txCmd
}
func initConfig(cmd *cobra.Command) error {
home, err := cmd.PersistentFlags().GetString(cli.HomeFlag)
if err != nil {
return err
}
cfgFile := path.Join(home, "config", "config.toml")
if _, err := os.Stat(cfgFile); err == nil {
viper.SetConfigFile(cfgFile)
if err := viper.ReadInConfig(); err != nil {
return err
}
}
if err := viper.BindPFlag(flags.FlagChainID, cmd.PersistentFlags().Lookup(flags.FlagChainID)); err != nil {
return err
}
if err := viper.BindPFlag(cli.EncodingFlag, cmd.PersistentFlags().Lookup(cli.EncodingFlag)); err != nil {
return err
}
return viper.BindPFlag(cli.OutputFlag, cmd.PersistentFlags().Lookup(cli.OutputFlag))
}
+18 -39
View File
@@ -2,9 +2,17 @@ package main
import (
"encoding/json"
"fmt"
"io"
"math/big"
"github.com/spf13/cobra"
"github.com/spf13/viper"
abci "github.com/tendermint/tendermint/abci/types"
tmamino "github.com/tendermint/tendermint/crypto/encoding/amino"
"github.com/tendermint/tendermint/libs/cli"
"github.com/tendermint/tendermint/libs/log"
tmtypes "github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client/flags"
@@ -19,19 +27,10 @@ import (
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/cosmos/cosmos-sdk/x/staking"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/cosmos/ethermint/app"
"github.com/cosmos/ethermint/client"
"github.com/cosmos/ethermint/codec"
emintcrypto "github.com/cosmos/ethermint/crypto"
abci "github.com/tendermint/tendermint/abci/types"
tmamino "github.com/tendermint/tendermint/crypto/encoding/amino"
"github.com/tendermint/tendermint/libs/cli"
"github.com/tendermint/tendermint/libs/log"
tmtypes "github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/ethermint/crypto"
)
const flagInvCheckPeriod = "inv-check-period"
@@ -44,8 +43,8 @@ func main() {
cdc := codec.MakeCodec(app.ModuleBasics)
appCodec := codec.NewAppCodec(cdc)
tmamino.RegisterKeyType(emintcrypto.PubKeySecp256k1{}, emintcrypto.PubKeyAminoName)
tmamino.RegisterKeyType(emintcrypto.PrivKeySecp256k1{}, emintcrypto.PrivKeyAminoName)
tmamino.RegisterKeyType(crypto.PubKeySecp256k1{}, crypto.PubKeyAminoName)
tmamino.RegisterKeyType(crypto.PrivKeySecp256k1{}, crypto.PrivKeyAminoName)
keyring.CryptoCdc = cdc
genutil.ModuleCdc = cdc
@@ -67,7 +66,9 @@ func main() {
}
// CLI commands to initialize the chain
rootCmd.AddCommand(
withChainIDValidation(genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome)),
client.ValidateChainID(
genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome),
),
genutilcli.CollectGenTxsCmd(ctx, cdc, bank.GenesisBalancesIterator{}, app.DefaultNodeHome),
genutilcli.MigrateGenesisCmd(ctx, cdc),
genutilcli.GenTxCmd(
@@ -75,7 +76,7 @@ func main() {
app.DefaultNodeHome, app.DefaultCLIHome,
),
genutilcli.ValidateGenesisCmd(ctx, cdc, app.ModuleBasics),
testnetCmd(ctx, cdc, app.ModuleBasics, bank.GenesisBalancesIterator{}),
client.TestnetCmd(ctx, cdc, app.ModuleBasics, bank.GenesisBalancesIterator{}),
// AddGenesisAccountCmd allows users to add accounts to the genesis file
AddGenesisAccountCmd(ctx, cdc, appCodec, app.DefaultNodeHome, app.DefaultCLIHome),
flags.NewCompletionCmd(rootCmd, true),
@@ -116,25 +117,3 @@ func exportAppStateAndTMValidators(
return emintApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList)
}
// Wraps cobra command with a RunE function with integer chain-id verification
func withChainIDValidation(baseCmd *cobra.Command) *cobra.Command {
// Copy base run command to be used after chain verification
baseRunE := baseCmd.RunE
// Function to replace command's RunE function
chainIDVerify := func(cmd *cobra.Command, args []string) error {
chainIDFlag := viper.GetString(flags.FlagChainID)
// Verify that the chain-id entered is a base 10 integer
_, ok := new(big.Int).SetString(chainIDFlag, 10)
if !ok {
return fmt.Errorf("invalid chainID: %s, must be base-10 integer format", chainIDFlag)
}
return baseRunE(cmd, args)
}
baseCmd.RunE = chainIDVerify
return baseCmd
}
-413
View File
@@ -1,413 +0,0 @@
package main
// DONTCOVER
import (
"bufio"
"encoding/json"
"fmt"
"net"
"os"
"path/filepath"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/spf13/cobra"
tmconfig "github.com/tendermint/tendermint/config"
tmcrypto "github.com/tendermint/tendermint/crypto"
tmos "github.com/tendermint/tendermint/libs/os"
tmrand "github.com/tendermint/tendermint/libs/rand"
tmtypes "github.com/tendermint/tendermint/types"
tmtime "github.com/tendermint/tendermint/types/time"
"github.com/cosmos/cosmos-sdk/client/flags"
clientkeys "github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
srvconfig "github.com/cosmos/cosmos-sdk/server/config"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
authexported "github.com/cosmos/cosmos-sdk/x/auth/exported"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/cosmos/ethermint/crypto"
"github.com/cosmos/ethermint/types"
)
var (
flagNodeDirPrefix = "node-dir-prefix"
flagNumValidators = "v"
flagOutputDir = "output-dir"
flagNodeDaemonHome = "node-daemon-home"
flagNodeCLIHome = "node-cli-home"
flagStartingIPAddress = "starting-ip-address"
)
const nodeDirPerm = 0755
// get cmd to initialize all files for tendermint testnet and application
func testnetCmd(ctx *server.Context, cdc *codec.Codec,
mbm module.BasicManager, genBalIterator banktypes.GenesisBalancesIterator,
) *cobra.Command {
cmd := &cobra.Command{
Use: "testnet",
Short: "Initialize files for a Ethermint testnet",
Long: `testnet will create "v" number of directories and populate each with
necessary files (private validator, genesis, config, etc.).
Note, strict routability for addresses is turned off in the config file.`,
Example: "emintd testnet --v 4 --keyring-backend test --output-dir ./output --starting-ip-address 192.168.10.2",
RunE: func(cmd *cobra.Command, _ []string) error {
config := ctx.Config
outputDir, _ := cmd.Flags().GetString(flagOutputDir)
keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend)
chainID, _ := cmd.Flags().GetString(flags.FlagChainID)
minGasPrices, _ := cmd.Flags().GetString(server.FlagMinGasPrices)
nodeDirPrefix, _ := cmd.Flags().GetString(flagNodeDirPrefix)
nodeDaemonHome, _ := cmd.Flags().GetString(flagNodeDaemonHome)
nodeCLIHome, _ := cmd.Flags().GetString(flagNodeCLIHome)
startingIPAddress, _ := cmd.Flags().GetString(flagStartingIPAddress)
numValidators, _ := cmd.Flags().GetInt(flagNumValidators)
return InitTestnet(
cmd, config, cdc, mbm, genBalIterator, outputDir, chainID, minGasPrices,
nodeDirPrefix, nodeDaemonHome, nodeCLIHome, startingIPAddress, keyringBackend, numValidators,
)
},
}
cmd.Flags().Int(flagNumValidators, 4, "Number of validators to initialize the testnet with")
cmd.Flags().StringP(flagOutputDir, "o", "./build", "Directory to store initialization data for the testnet")
cmd.Flags().String(flagNodeDirPrefix, "node", "Prefix the directory name for each node with (node results in node0, node1, ...)")
cmd.Flags().String(flagNodeDaemonHome, "emintd", "Home directory of the node's daemon configuration")
cmd.Flags().String(flagNodeCLIHome, "emintcli", "Home directory of the node's cli configuration")
cmd.Flags().String(flagStartingIPAddress, "192.168.0.1", "Starting IP address (192.168.0.1 results in persistent peers list ID0@192.168.0.1:46656, ID1@192.168.0.2:46656, ...)")
cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created")
cmd.Flags().String(server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", types.DenomDefault), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photon,0.001stake)")
cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)")
return cmd
}
// InitTestnet initializes the testnet configuration
func InitTestnet(
cmd *cobra.Command, config *tmconfig.Config, cdc *codec.Codec,
mbm module.BasicManager, genBalIterator banktypes.GenesisBalancesIterator,
outputDir, chainID, minGasPrices, nodeDirPrefix, nodeDaemonHome,
nodeCLIHome, startingIPAddress, keyringBackend string, numValidators int,
) error {
if chainID == "" {
chainID = fmt.Sprintf("%d", tmrand.Int63())
}
nodeIDs := make([]string, numValidators)
valPubKeys := make([]tmcrypto.PubKey, numValidators)
simappConfig := srvconfig.DefaultConfig()
simappConfig.MinGasPrices = minGasPrices
var (
genAccounts []authexported.GenesisAccount
genBalances []banktypes.Balance
genFiles []string
)
inBuf := bufio.NewReader(cmd.InOrStdin())
// generate private keys, node IDs, and initial transactions
for i := 0; i < numValidators; i++ {
nodeDirName := fmt.Sprintf("%s%d", nodeDirPrefix, i)
nodeDir := filepath.Join(outputDir, nodeDirName, nodeDaemonHome)
clientDir := filepath.Join(outputDir, nodeDirName, nodeCLIHome)
gentxsDir := filepath.Join(outputDir, "gentxs")
config.SetRoot(nodeDir)
config.RPC.ListenAddress = "tcp://0.0.0.0:26657"
if err := os.MkdirAll(filepath.Join(nodeDir, "config"), nodeDirPerm); err != nil {
_ = os.RemoveAll(outputDir)
return err
}
if err := os.MkdirAll(clientDir, nodeDirPerm); err != nil {
_ = os.RemoveAll(outputDir)
return err
}
config.Moniker = nodeDirName
ip, err := getIP(i, startingIPAddress)
if err != nil {
_ = os.RemoveAll(outputDir)
return err
}
nodeIDs[i], valPubKeys[i], err = genutil.InitializeNodeValidatorFiles(config)
if err != nil {
_ = os.RemoveAll(outputDir)
return err
}
memo := fmt.Sprintf("%s@%s:26656", nodeIDs[i], ip)
genFiles = append(genFiles, config.GenesisFile())
kb, err := keyring.NewKeyring(
sdk.KeyringServiceName(),
keyringBackend,
clientDir,
inBuf,
keyring.WithKeygenFunc(crypto.EthermintKeygenFunc),
)
if err != nil {
return err
}
cmd.Printf(
"Password for account '%s' :\n", nodeDirName,
)
keyPass := clientkeys.DefaultKeyPass
addr, secret, err := server.GenerateSaveCoinKey(kb, nodeDirName, keyPass, true)
if err != nil {
_ = os.RemoveAll(outputDir)
return err
}
info := map[string]string{"secret": secret}
cliPrint, err := json.Marshal(info)
if err != nil {
return err
}
// save private key seed words
if err := writeFile(fmt.Sprintf("%v.json", "key_seed"), clientDir, cliPrint); err != nil {
return err
}
accTokens := sdk.TokensFromConsensusPower(1000)
accStakingTokens := sdk.TokensFromConsensusPower(5000)
coins := sdk.NewCoins(
sdk.NewCoin(sdk.DefaultBondDenom, accTokens),
sdk.NewCoin(types.DenomDefault, accStakingTokens),
)
genBalances = append(genBalances, banktypes.Balance{Address: addr, Coins: coins})
genAccounts = append(genAccounts, types.EthAccount{
BaseAccount: authtypes.NewBaseAccount(addr, nil, 0, 0),
CodeHash: ethcrypto.Keccak256(nil),
})
valTokens := sdk.TokensFromConsensusPower(100)
msg := stakingtypes.NewMsgCreateValidator(
sdk.ValAddress(addr),
valPubKeys[i],
sdk.NewCoin(types.DenomDefault, valTokens),
stakingtypes.NewDescription(nodeDirName, "", "", "", ""),
stakingtypes.NewCommissionRates(sdk.OneDec(), sdk.OneDec(), sdk.OneDec()),
sdk.OneInt(),
)
tx := authtypes.NewStdTx([]sdk.Msg{msg}, authtypes.StdFee{}, []authtypes.StdSignature{}, memo) //nolint:staticcheck // SA1019: authtypes.StdFee is deprecated
txBldr := authtypes.NewTxBuilderFromCLI(inBuf).WithChainID(chainID).WithMemo(memo).WithKeybase(kb)
signedTx, err := txBldr.SignStdTx(nodeDirName, clientkeys.DefaultKeyPass, tx, false)
if err != nil {
_ = os.RemoveAll(outputDir)
return err
}
txBytes, err := cdc.MarshalJSON(signedTx)
if err != nil {
_ = os.RemoveAll(outputDir)
return err
}
// gather gentxs folder
if err := writeFile(fmt.Sprintf("%v.json", nodeDirName), gentxsDir, txBytes); err != nil {
_ = os.RemoveAll(outputDir)
return err
}
srvconfig.WriteConfigFile(filepath.Join(nodeDir, "config/app.toml"), simappConfig)
}
if err := initGenFiles(cdc, mbm, chainID, genAccounts, genBalances, genFiles, numValidators); err != nil {
return err
}
err := collectGenFiles(
cdc, config, chainID, nodeIDs, valPubKeys, numValidators,
outputDir, nodeDirPrefix, nodeDaemonHome, genBalIterator,
)
if err != nil {
return err
}
cmd.PrintErrf("Successfully initialized %d node directories\n", numValidators)
return nil
}
func initGenFiles(
cdc codec.JSONMarshaler, mbm module.BasicManager, chainID string,
genAccounts []authexported.GenesisAccount, genBalances []banktypes.Balance,
genFiles []string, numValidators int,
) error {
appGenState := mbm.DefaultGenesis(cdc)
// set the accounts in the genesis state
var authGenState authtypes.GenesisState
cdc.MustUnmarshalJSON(appGenState[authtypes.ModuleName], &authGenState)
authGenState.Accounts = genAccounts
appGenState[authtypes.ModuleName] = cdc.MustMarshalJSON(authGenState)
// set the balances in the genesis state
var bankGenState banktypes.GenesisState
cdc.MustUnmarshalJSON(appGenState[banktypes.ModuleName], &bankGenState)
bankGenState.Balances = genBalances
appGenState[banktypes.ModuleName] = cdc.MustMarshalJSON(bankGenState)
var stakingGenState stakingtypes.GenesisState
cdc.MustUnmarshalJSON(appGenState[stakingtypes.ModuleName], &stakingGenState)
stakingGenState.Params.BondDenom = types.DenomDefault
appGenState[stakingtypes.ModuleName] = cdc.MustMarshalJSON(stakingGenState)
var govGenState govtypes.GenesisState
cdc.MustUnmarshalJSON(appGenState[govtypes.ModuleName], &govGenState)
govGenState.DepositParams.MinDeposit[0].Denom = types.DenomDefault
appGenState[govtypes.ModuleName] = cdc.MustMarshalJSON(govGenState)
var mintGenState minttypes.GenesisState
cdc.MustUnmarshalJSON(appGenState[minttypes.ModuleName], &mintGenState)
mintGenState.Params.MintDenom = types.DenomDefault
appGenState[minttypes.ModuleName] = cdc.MustMarshalJSON(mintGenState)
var crisisGenState crisistypes.GenesisState
cdc.MustUnmarshalJSON(appGenState[crisistypes.ModuleName], &crisisGenState)
crisisGenState.ConstantFee.Denom = types.DenomDefault
appGenState[crisistypes.ModuleName] = cdc.MustMarshalJSON(crisisGenState)
appGenStateJSON, err := codec.MarshalJSONIndent(cdc, appGenState)
if err != nil {
return err
}
genDoc := tmtypes.GenesisDoc{
ChainID: chainID,
AppState: appGenStateJSON,
Validators: nil,
}
// generate empty genesis files for each validator and save
for i := 0; i < numValidators; i++ {
if err := genDoc.SaveAs(genFiles[i]); err != nil {
return err
}
}
return nil
}
func collectGenFiles(
cdc *codec.Codec, config *tmconfig.Config, chainID string,
nodeIDs []string, valPubKeys []tmcrypto.PubKey,
numValidators int, outputDir, nodeDirPrefix, nodeDaemonHome string,
genBalIterator banktypes.GenesisBalancesIterator,
) error {
var appState json.RawMessage
genTime := tmtime.Now()
for i := 0; i < numValidators; i++ {
nodeDirName := fmt.Sprintf("%s%d", nodeDirPrefix, i)
nodeDir := filepath.Join(outputDir, nodeDirName, nodeDaemonHome)
gentxsDir := filepath.Join(outputDir, "gentxs")
config.Moniker = nodeDirName
config.SetRoot(nodeDir)
nodeID, valPubKey := nodeIDs[i], valPubKeys[i]
initCfg := genutiltypes.NewInitConfig(chainID, gentxsDir, nodeID, nodeID, valPubKey)
genDoc, err := tmtypes.GenesisDocFromFile(config.GenesisFile())
if err != nil {
return err
}
nodeAppState, err := genutil.GenAppStateFromConfig(cdc, config, initCfg, *genDoc, genBalIterator)
if err != nil {
return err
}
if appState == nil {
// set the canonical application state (they should not differ)
appState = nodeAppState
}
genFile := config.GenesisFile()
// overwrite each validator's genesis file to have a canonical genesis time
if err := genutil.ExportGenesisFileWithTime(genFile, chainID, nil, appState, genTime); err != nil {
return err
}
}
return nil
}
func getIP(i int, startingIPAddr string) (ip string, err error) {
if len(startingIPAddr) == 0 {
ip, err = server.ExternalIP()
if err != nil {
return "", err
}
return ip, nil
}
return calculateIP(startingIPAddr, i)
}
func calculateIP(ip string, i int) (string, error) {
ipv4 := net.ParseIP(ip).To4()
if ipv4 == nil {
return "", fmt.Errorf("%v: non ipv4 address", ip)
}
for j := 0; j < i; j++ {
ipv4[3]++
}
return ipv4.String(), nil
}
func writeFile(name string, dir string, contents []byte) error {
writePath := filepath.Join(dir)
file := filepath.Join(writePath, name)
err := tmos.EnsureDir(writePath, 0755)
if err != nil {
return err
}
err = tmos.WriteFile(file, contents, 0644)
if err != nil {
return err
}
return nil
}