-
Notifications
You must be signed in to change notification settings - Fork 12
/
collect_gentx.go
220 lines (180 loc) · 7 KB
/
collect_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
package cli
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
bankexported "github.com/cosmos/cosmos-sdk/x/bank/exported"
"github.com/cosmos/cosmos-sdk/x/genutil"
"github.com/cosmos/cosmos-sdk/x/genutil/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/pkg/errors"
"github.com/spf13/cobra"
cfg "github.com/tendermint/tendermint/config"
tmtypes "github.com/tendermint/tendermint/types"
)
const flagGenTxDir = "gentx-dir"
// CollectGenTxsCmd - return the cobra command to collect genesis transactions
func CollectGenTxsCmd(genBalIterator types.GenesisBalancesIterator, defaultNodeHome string) *cobra.Command {
cmd := &cobra.Command{
Use: "collect-gentxs",
Short: "Collect genesis txs and output a genesis.json file",
RunE: func(cmd *cobra.Command, _ []string) error {
serverCtx := server.GetServerContextFromCmd(cmd)
config := serverCtx.Config
clientCtx := client.GetClientContextFromCmd(cmd)
config.SetRoot(clientCtx.HomeDir)
nodeID, valPubKey, err := genutil.InitializeNodeValidatorFiles(config)
if err != nil {
return errors.Wrap(err, "failed to initialize node validator files")
}
genDoc, err := tmtypes.GenesisDocFromFile(config.GenesisFile())
if err != nil {
return errors.Wrap(err, "failed to read genesis doc from file")
}
genTxDir, _ := cmd.Flags().GetString(flagGenTxDir)
genTxsDir := genTxDir
if genTxsDir == "" {
genTxsDir = filepath.Join(config.RootDir, "config", "gentx")
}
toPrint := NewPrintInfo(config.Moniker, genDoc.ChainID, nodeID, genTxsDir, json.RawMessage(""))
initCfg := types.NewInitConfig(genDoc.ChainID, genTxsDir, nodeID, valPubKey)
toPrint.AppMessage, err = GenAppStateFromConfig(clientCtx.Codec, clientCtx.TxConfig, config, initCfg, *genDoc, genBalIterator)
if err != nil {
return errors.Wrap(err, "failed to get genesis app state from config")
}
out, err := json.MarshalIndent(toPrint, "", " ")
if err != nil {
return err
}
return clientCtx.PrintString(string(sdk.MustSortJSON(out)) + "\n")
},
}
cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
cmd.Flags().String(flagGenTxDir, "", "override default \"gentx\" directory from which collect and execute genesis transactions; default [--home]/config/gentx/")
return cmd
}
// GenAppStateFromConfig gets the genesis app state from the config
func GenAppStateFromConfig(cdc codec.JSONCodec, txEncodingConfig client.TxEncodingConfig,
config *cfg.Config, initCfg types.InitConfig, genDoc tmtypes.GenesisDoc, genBalIterator types.GenesisBalancesIterator,
) (appState json.RawMessage, err error) {
// process genesis transactions, else create default genesis.json
appGenTxs, persistentPeers, err := CollectTxs(
cdc, txEncodingConfig.TxJSONDecoder(), config.Moniker, initCfg.GenTxsDir, genDoc, genBalIterator,
)
if err != nil {
return appState, err
}
config.P2P.PersistentPeers = persistentPeers
cfg.WriteConfigFile(filepath.Join(config.RootDir, "config", "config.toml"), config)
// if there are no gen txs to be processed, return the default empty state
if len(appGenTxs) == 0 {
return appState, errors.New("there must be at least one genesis tx")
}
// create the app state
appGenesisState, err := types.GenesisStateFromGenDoc(genDoc)
if err != nil {
return appState, err
}
appGenesisState, err = genutil.SetGenTxsInAppGenesisState(cdc, txEncodingConfig.TxJSONEncoder(), appGenesisState, appGenTxs)
if err != nil {
return appState, err
}
appState, err = json.MarshalIndent(appGenesisState, "", " ")
if err != nil {
return appState, err
}
genDoc.AppState = appState
err = genutil.ExportGenesisFile(&genDoc, config.GenesisFile())
return appState, err
}
// CollectTxs processes and validates application's genesis Txs and returns
// the list of appGenTxs, and persistent peers required to generate genesis.json.
func CollectTxs(cdc codec.JSONCodec, txJSONDecoder sdk.TxDecoder, moniker, genTxsDir string,
genDoc tmtypes.GenesisDoc, genBalIterator types.GenesisBalancesIterator,
) (appGenTxs []sdk.Tx, persistentPeers string, err error) {
// prepare a map of all balances in genesis state to then validate
// against the validators addresses
var appState map[string]json.RawMessage
if err := json.Unmarshal(genDoc.AppState, &appState); err != nil {
return appGenTxs, persistentPeers, err
}
var fos []os.DirEntry
fos, err = os.ReadDir(genTxsDir)
if err != nil {
return appGenTxs, persistentPeers, err
}
balancesMap := make(map[string]bankexported.GenesisBalance)
genBalIterator.IterateGenesisBalances(
cdc, appState,
func(balance bankexported.GenesisBalance) (stop bool) {
balancesMap[balance.GetAddress().String()] = balance
return false
},
)
for _, fo := range fos {
if fo.IsDir() {
continue
}
if !strings.HasSuffix(fo.Name(), ".json") {
continue
}
// get the genTx
jsonRawTx, err := os.ReadFile(filepath.Join(genTxsDir, fo.Name()))
if err != nil {
return appGenTxs, persistentPeers, err
}
var genTx sdk.Tx
if genTx, err = txJSONDecoder(jsonRawTx); err != nil {
return appGenTxs, persistentPeers, err
}
appGenTxs = append(appGenTxs, genTx)
_, ok := genTx.(sdk.TxWithMemo)
if !ok {
return appGenTxs, persistentPeers, fmt.Errorf("expected TxWithMemo, got %T", genTx)
}
// genesis transactions must be single-message
msgs := genTx.GetMsgs()
if len(msgs) != 1 {
return appGenTxs, persistentPeers, errors.New("each genesis transaction must provide a single genesis message")
}
// abstract out staking message validation back to staking
msg := msgs[0].(*stakingtypes.MsgCreateValidator)
// validate delegator and validator addresses and funds against the accounts in the state
delAddr := msg.DelegatorAddress
valAddr, err := sdk.ValAddressFromBech32(msg.ValidatorAddress)
if err != nil {
return appGenTxs, persistentPeers, err
}
delBal, delOk := balancesMap[delAddr]
if !delOk {
_, file, no, ok := runtime.Caller(1)
if ok {
fmt.Printf("CollectTxs-1, called from %s#%d\n", file, no)
}
return appGenTxs, persistentPeers, fmt.Errorf("account %s balance not in genesis state: %+v", delAddr, balancesMap)
}
_, valOk := balancesMap[sdk.AccAddress(valAddr).String()]
if !valOk {
_, file, no, ok := runtime.Caller(1)
if ok {
fmt.Printf("CollectTxs-2, called from %s#%d - %s\n", file, no, sdk.AccAddress(msg.ValidatorAddress).String())
}
return appGenTxs, persistentPeers, fmt.Errorf("account %s balance not in genesis state: %+v", valAddr, balancesMap)
}
if delBal.GetCoins().AmountOf(msg.Value.Denom).LT(msg.Value.Amount) {
return appGenTxs, persistentPeers, fmt.Errorf(
"insufficient fund for delegation %v: %v < %v",
delBal.GetAddress().String(), delBal.GetCoins().AmountOf(msg.Value.Denom), msg.Value.Amount,
)
}
}
return appGenTxs, persistentPeers, nil
}