-
Notifications
You must be signed in to change notification settings - Fork 182
/
gentx.go
229 lines (191 loc) · 6.97 KB
/
gentx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package cli
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
clictx "github.com/okex/exchain/libs/cosmos-sdk/client/context"
"github.com/okex/exchain/libs/cosmos-sdk/client/flags"
"github.com/okex/exchain/libs/cosmos-sdk/codec"
"github.com/okex/exchain/libs/cosmos-sdk/crypto/keys"
kbkeys "github.com/okex/exchain/libs/cosmos-sdk/crypto/keys"
"github.com/okex/exchain/libs/cosmos-sdk/server"
sdk "github.com/okex/exchain/libs/cosmos-sdk/types"
"github.com/okex/exchain/libs/cosmos-sdk/types/module"
"github.com/okex/exchain/libs/cosmos-sdk/x/auth"
"github.com/okex/exchain/libs/cosmos-sdk/x/auth/client/utils"
tmos "github.com/okex/exchain/libs/tendermint/libs/os"
tmtypes "github.com/okex/exchain/libs/tendermint/types"
"github.com/okex/exchain/x/genutil"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// GenTxCmd builds the application's gentx command
func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, smbh stakingMsgBuildingHelpers,
genAccIterator genutil.GenesisAccountsIterator, defaultNodeHome, defaultCLIHome string) *cobra.Command {
ipDefault, err := server.ExternalIP()
if err != nil {
ctx.Logger.Error(err.Error())
}
fsCreateValidator, flagNodeID, flagPubKey, flagAmount, defaultsDesc := smbh.CreateValidatorMsgHelpers(ipDefault)
cmd := &cobra.Command{
Use: "gentx",
Short: "Generate a genesis tx carrying a self delegation",
Args: cobra.NoArgs,
Long: fmt.Sprintf(`This command is an alias of the 'tx create-validator' command'.
It creates a genesis transaction to create a validator.
The following default parameters are included:
%s`, defaultsDesc),
RunE: func(cmd *cobra.Command, args []string) error {
config := ctx.Config
config.SetRoot(viper.GetString(flags.FlagHome))
nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(ctx.Config)
if err != nil {
return err
}
// Read --nodeID, if empty take it from priv_validator.json
if nodeIDString := viper.GetString(flagNodeID); nodeIDString != "" {
nodeID = nodeIDString
}
// Read --pubkey, if empty take it from priv_validator.json
if valPubKeyString := viper.GetString(flagPubKey); valPubKeyString != "" {
valPubKey, err = sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeConsPub, valPubKeyString)
if err != nil {
return err
}
}
genDoc, err := tmtypes.GenesisDocFromFile(config.GenesisFile())
if err != nil {
return err
}
var genesisState map[string]json.RawMessage
if err = cdc.UnmarshalJSON(genDoc.AppState, &genesisState); err != nil {
return err
}
if err = mbm.ValidateGenesis(genesisState); err != nil {
return err
}
inBuf := bufio.NewReader(cmd.InOrStdin())
kb, err := keys.NewKeyring(sdk.KeyringServiceName(),
viper.GetString(flags.FlagKeyringBackend), viper.GetString(flagClientHome), inBuf)
if err != nil {
return err
}
name := viper.GetString(flags.FlagName)
key, err := kb.Get(name)
if err != nil {
return err
}
// Set flags for creating gentx
viper.Set(flags.FlagHome, viper.GetString(flagClientHome))
smbh.PrepareFlagsForTxCreateValidator(config, nodeID, genDoc.ChainID, valPubKey)
// Fetch the amount of coins staked
amount := viper.GetString(flagAmount)
coins, err := sdk.ParseCoins(amount)
if err != nil {
return err
}
err = genutil.ValidateAccountInGenesis(genesisState, genAccIterator, key.GetAddress(), coins, cdc)
if err != nil {
return err
}
txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc))
cliCtx := clictx.NewCLIContext().WithCodec(cdc)
// Set the generate-only flag here after the CLI context has
// been created. This allows the from name/key to be correctly populated.
//
// TODO: Consider removing the manual setting of generate-only in
// favor of a 'gentx' flag in the create-validator command.
viper.Set(flags.FlagGenerateOnly, true)
// create a 'create-validator' message
txBldr, msg, err := smbh.BuildCreateValidatorMsg(cliCtx, txBldr)
if err != nil {
return err
}
info, err := txBldr.Keybase().Get(name)
if err != nil {
return err
}
if info.GetType() == kbkeys.TypeOffline || info.GetType() == kbkeys.TypeMulti {
fmt.Println("Offline key passed in. Use `tx sign` command to sign:")
return utils.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg})
}
// write the unsigned transaction to the buffer
w := bytes.NewBuffer([]byte{})
cliCtx = cliCtx.WithOutput(w)
if err = utils.PrintUnsignedStdTx(txBldr, cliCtx, []sdk.Msg{msg}); err != nil {
return err
}
// read the transaction
stdTx, err := readUnsignedGenTxFile(cdc, w)
if err != nil {
return err
}
// sign the transaction and write it to the output file
signedTx, err := utils.SignStdTx(txBldr, cliCtx, name, stdTx, false, true)
if err != nil {
return err
}
// Fetch output file name
outputDocument := viper.GetString(flags.FlagOutputDocument)
if outputDocument == "" {
outputDocument, err = makeOutputFilepath(config.RootDir, nodeID)
if err != nil {
return err
}
}
if err := writeSignedGenTx(cdc, outputDocument, signedTx); err != nil {
return err
}
if _, err := fmt.Fprintf(os.Stderr, "Genesis transaction written to %q\n", outputDocument); err != nil {
ctx.Logger.Error(err.Error())
}
return nil
},
}
cmd.Flags().String(flags.FlagHome, defaultNodeHome, "node's home directory")
cmd.Flags().String(flagClientHome, defaultCLIHome, "client's home directory")
cmd.Flags().String(flags.FlagName, "", "name of private key with which to sign the gentx")
cmd.Flags().String(flags.FlagOutputDocument, "",
"write the genesis transaction JSON document to the given file instead of the default location")
cmd.Flags().AddFlagSet(fsCreateValidator)
cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)")
viper.BindPFlag(flags.FlagKeyringBackend, cmd.Flags().Lookup(flags.FlagKeyringBackend))
if err := cmd.MarkFlagRequired(flags.FlagName); err != nil {
ctx.Logger.Error(err.Error())
}
return cmd
}
func makeOutputFilepath(rootDir, nodeID string) (string, error) {
writePath := filepath.Join(rootDir, "config", "gentx")
if err := tmos.EnsureDir(writePath, 0700); err != nil {
return "", err
}
return filepath.Join(writePath, fmt.Sprintf("gentx-%v.json", nodeID)), nil
}
func readUnsignedGenTxFile(cdc *codec.Codec, r io.Reader) (auth.StdTx, error) {
var stdTx auth.StdTx
bytes, err := ioutil.ReadAll(r)
if err != nil {
return stdTx, err
}
err = cdc.UnmarshalJSON(bytes, &stdTx)
return stdTx, err
}
func writeSignedGenTx(cdc *codec.Codec, outputDocument string, tx auth.StdTx) error {
outputFile, err := os.OpenFile(outputDocument, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer outputFile.Close()
jsonBytes, err := cdc.MarshalJSON(tx)
if err != nil {
return err
}
_, err = fmt.Fprintf(outputFile, "%s\n", jsonBytes)
return err
}