forked from NoahSaso/wasmd
/
genesis_msg.go
526 lines (480 loc) · 17.5 KB
/
genesis_msg.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
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
298
299
300
301
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
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
package cli
import (
"bufio"
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/spf13/cobra"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/CosmWasm/wasmd/x/wasm/ioutils"
"github.com/CosmWasm/wasmd/x/wasm/keeper"
"github.com/CosmWasm/wasmd/x/wasm/types"
)
// GenesisReader reads genesis data. Extension point for custom genesis state readers.
type GenesisReader interface {
ReadWasmGenesis(cmd *cobra.Command) (*GenesisData, error)
}
// GenesisMutator extension point to modify the wasm module genesis state.
// This gives flexibility to customize the data structure in the genesis file a bit.
type GenesisMutator interface {
// AlterWasmModuleState loads the genesis from the default or set home dir,
// unmarshalls the wasm module section into the object representation
// calls the callback function to modify it
// and marshals the modified state back into the genesis file
AlterWasmModuleState(cmd *cobra.Command, callback func(state *types.GenesisState, appState map[string]json.RawMessage) error) error
}
// GenesisStoreCodeCmd cli command to add a `MsgStoreCode` to the wasm section of the genesis
// that is executed on block 0.
func GenesisStoreCodeCmd(defaultNodeHome string, genesisMutator GenesisMutator) *cobra.Command {
cmd := &cobra.Command{
Use: "store [wasm file] --run-as [owner_address_or_key_name]\",",
Short: "Upload a wasm binary",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
senderAddr, err := getActorAddress(cmd)
if err != nil {
return err
}
msg, err := parseStoreCodeArgs(args[0], senderAddr, cmd.Flags())
if err != nil {
return err
}
if err = msg.ValidateBasic(); err != nil {
return err
}
return genesisMutator.AlterWasmModuleState(cmd, func(state *types.GenesisState, _ map[string]json.RawMessage) error {
state.GenMsgs = append(state.GenMsgs, types.GenesisState_GenMsgs{
Sum: &types.GenesisState_GenMsgs_StoreCode{StoreCode: &msg},
})
return nil
})
},
SilenceUsage: true,
}
cmd.Flags().String(flagRunAs, "", "The address that is stored as code creator")
cmd.Flags().String(flagInstantiateByEverybody, "", "Everybody can instantiate a contract from the code, optional")
cmd.Flags().String(flagInstantiateNobody, "", "Nobody except the governance process can instantiate a contract from the code, optional")
cmd.Flags().String(flagInstantiateByAddress, "", "Only this address can instantiate a contract instance from the code, optional")
cmd.Flags().StringSlice(flagInstantiateByAnyOfAddress, []string{}, "Any of the addresses can instantiate a contract from the code, optional")
cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)")
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GenesisInstantiateContractCmd cli command to add a `MsgInstantiateContract` to the wasm section of the genesis
// that is executed on block 0.
func GenesisInstantiateContractCmd(defaultNodeHome string, genesisMutator GenesisMutator) *cobra.Command {
cmd := &cobra.Command{
Use: "instantiate-contract [code_id_int64] [json_encoded_init_args] --label [text] --run-as [address] --admin [address,optional] --amount [coins,optional]",
Short: "Instantiate a wasm contract",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
senderAddr, err := getActorAddress(cmd)
if err != nil {
return err
}
msg, err := parseInstantiateArgs(args[0], args[1], senderAddr, cmd.Flags())
if err != nil {
return err
}
if err = msg.ValidateBasic(); err != nil {
return err
}
return genesisMutator.AlterWasmModuleState(cmd, func(state *types.GenesisState, appState map[string]json.RawMessage) error {
// simple sanity check that sender has some balance, although it may be consumed by appState previous message already
switch ok, err := hasAccountBalance(cmd, appState, senderAddr, msg.Funds); {
case err != nil:
return err
case !ok:
return errors.New("sender has not enough account balance")
}
// does code id exists?
codeInfos := GetAllCodes(state)
if err != nil {
return err
}
var codeInfo *CodeMeta
for i := range codeInfos {
if codeInfos[i].CodeID == msg.CodeID {
codeInfo = &codeInfos[i]
break
}
}
if codeInfo == nil {
return fmt.Errorf("unknown code id: %d", msg.CodeID)
}
// permissions correct?
if !codeInfo.Info.InstantiateConfig.Allowed(senderAddr) {
return fmt.Errorf("permissions were not granted for %s", senderAddr)
}
state.GenMsgs = append(state.GenMsgs, types.GenesisState_GenMsgs{
Sum: &types.GenesisState_GenMsgs_InstantiateContract{InstantiateContract: msg},
})
return nil
})
},
SilenceUsage: true,
}
cmd.Flags().String(flagAmount, "", "Coins to send to the contract during instantiation")
cmd.Flags().String(flagLabel, "", "A human-readable name for this contract in lists")
cmd.Flags().String(flagAdmin, "", "Address of an admin")
cmd.Flags().Bool(flagNoAdmin, false, "You must set this explicitly if you don't want an admin")
cmd.Flags().String(flagRunAs, "", "The address that pays the init funds. It is the creator of the contract.")
cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)")
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GenesisExecuteContractCmd cli command to add a `MsgExecuteContract` to the wasm section of the genesis
// that is executed on block 0.
func GenesisExecuteContractCmd(defaultNodeHome string, genesisMutator GenesisMutator) *cobra.Command {
cmd := &cobra.Command{
Use: "execute [contract_addr_bech32] [json_encoded_send_args] --run-as [address] --amount [coins,optional]",
Short: "Execute a command on a wasm contract",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
senderAddr, err := getActorAddress(cmd)
if err != nil {
return err
}
msg, err := parseExecuteArgs(args[0], args[1], senderAddr, cmd.Flags())
if err != nil {
return err
}
if err = msg.ValidateBasic(); err != nil {
return err
}
return genesisMutator.AlterWasmModuleState(cmd, func(state *types.GenesisState, appState map[string]json.RawMessage) error {
// simple sanity check that sender has some balance, although it may be consumed by appState previous message already
switch ok, err := hasAccountBalance(cmd, appState, senderAddr, msg.Funds); {
case err != nil:
return err
case !ok:
return errors.New("sender has not enough account balance")
}
// - does contract address exists?
if !hasContract(state, msg.Contract) {
return fmt.Errorf("unknown contract: %s", msg.Contract)
}
state.GenMsgs = append(state.GenMsgs, types.GenesisState_GenMsgs{
Sum: &types.GenesisState_GenMsgs_ExecuteContract{ExecuteContract: &msg},
})
return nil
})
},
SilenceUsage: true,
}
cmd.Flags().String(flagAmount, "", "Coins to send to the contract along with command")
cmd.Flags().String(flagRunAs, "", "The address that pays the funds.")
cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)")
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GenesisListCodesCmd cli command to list all codes stored in the genesis wasm.code section
// as well as from messages that are queued in the wasm.genMsgs section.
func GenesisListCodesCmd(defaultNodeHome string, genReader GenesisReader) *cobra.Command {
cmd := &cobra.Command{
Use: "list-codes ",
Short: "Lists all codes from genesis code dump and queued messages",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
g, err := genReader.ReadWasmGenesis(cmd)
if err != nil {
return err
}
all := GetAllCodes(g.WasmModuleState)
if err != nil {
return err
}
return printJSONOutput(cmd, all)
},
SilenceUsage: true,
}
cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// GenesisListContractsCmd cli command to list all contracts stored in the genesis wasm.contract section
// as well as from messages that are queued in the wasm.genMsgs section.
func GenesisListContractsCmd(defaultNodeHome string, genReader GenesisReader) *cobra.Command {
cmd := &cobra.Command{
Use: "list-contracts ",
Short: "Lists all contracts from genesis contract dump and queued messages",
Args: cobra.ExactArgs(0),
RunE: func(cmd *cobra.Command, args []string) error {
g, err := genReader.ReadWasmGenesis(cmd)
if err != nil {
return err
}
state := g.WasmModuleState
all := GetAllContracts(state)
return printJSONOutput(cmd, all)
},
SilenceUsage: true,
}
cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
flags.AddQueryFlagsToCmd(cmd)
return cmd
}
// clientCtx marshaller works only with proto or bytes, so we marshal the output ourselves
func printJSONOutput(cmd *cobra.Command, obj interface{}) error {
clientCtx := client.GetClientContextFromCmd(cmd)
bz, err := json.MarshalIndent(obj, "", " ")
if err != nil {
return err
}
return clientCtx.PrintString(string(bz))
}
type CodeMeta struct {
CodeID uint64 `json:"code_id"`
Info types.CodeInfo `json:"info"`
}
func GetAllCodes(state *types.GenesisState) []CodeMeta {
all := make([]CodeMeta, len(state.Codes))
for i, c := range state.Codes {
all[i] = CodeMeta{
CodeID: c.CodeID,
Info: c.CodeInfo,
}
}
// add inflight
seq := codeSeqValue(state)
for _, m := range state.GenMsgs {
if msg := m.GetStoreCode(); msg != nil {
var accessConfig types.AccessConfig
if msg.InstantiatePermission != nil {
accessConfig = *msg.InstantiatePermission
} else {
// default
creator := sdk.MustAccAddressFromBech32(msg.Sender)
accessConfig = state.Params.InstantiateDefaultPermission.With(creator)
}
bz := msg.WASMByteCode
if ioutils.IsGzip(msg.WASMByteCode) {
var err error
bz, err = ioutils.Uncompress(msg.WASMByteCode, uint64(types.MaxWasmSize))
if err != nil {
panic(fmt.Sprintf("failed to unzip wasm binary: %s", err))
}
}
hash := sha256.Sum256(bz)
all = append(all, CodeMeta{
CodeID: seq,
Info: types.CodeInfo{
CodeHash: hash[:],
Creator: msg.Sender,
InstantiateConfig: accessConfig,
},
})
seq++
}
}
return all
}
type ContractMeta struct {
ContractAddress string `json:"contract_address"`
Info types.ContractInfo `json:"info"`
}
func GetAllContracts(state *types.GenesisState) []ContractMeta {
all := make([]ContractMeta, len(state.Contracts))
for i, c := range state.Contracts {
all[i] = ContractMeta{
ContractAddress: c.ContractAddress,
Info: c.ContractInfo,
}
}
// add inflight
seq := contractSeqValue(state)
for _, m := range state.GenMsgs {
if msg := m.GetInstantiateContract(); msg != nil {
all = append(all, ContractMeta{
ContractAddress: keeper.BuildContractAddressClassic(msg.CodeID, seq).String(),
Info: types.ContractInfo{
CodeID: msg.CodeID,
Creator: msg.Sender,
Admin: msg.Admin,
Label: msg.Label,
},
})
seq++
}
}
return all
}
func hasAccountBalance(cmd *cobra.Command, appState map[string]json.RawMessage, sender sdk.AccAddress, coins sdk.Coins) (bool, error) {
// no coins needed, no account needed
if coins.IsZero() {
return true, nil
}
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return false, err
}
cdc := clientCtx.Codec
var genBalIterator banktypes.GenesisBalancesIterator
err = genutil.ValidateAccountInGenesis(appState, genBalIterator, sender, coins, cdc)
if err != nil {
return false, err
}
return true, nil
}
func hasContract(state *types.GenesisState, contractAddr string) bool {
for _, c := range state.Contracts {
if c.ContractAddress == contractAddr {
return true
}
}
seq := contractSeqValue(state)
for _, m := range state.GenMsgs {
if msg := m.GetInstantiateContract(); msg != nil {
if keeper.BuildContractAddressClassic(msg.CodeID, seq).String() == contractAddr {
return true
}
seq++
}
}
return false
}
// GenesisData contains raw and unmarshalled data from the genesis file
type GenesisData struct {
GenesisFile string
GenDoc *tmtypes.GenesisDoc
AppState map[string]json.RawMessage
WasmModuleState *types.GenesisState
}
func NewGenesisData(genesisFile string, genDoc *tmtypes.GenesisDoc, appState map[string]json.RawMessage, wasmModuleState *types.GenesisState) *GenesisData {
return &GenesisData{GenesisFile: genesisFile, GenDoc: genDoc, AppState: appState, WasmModuleState: wasmModuleState}
}
type DefaultGenesisReader struct{}
func (d DefaultGenesisReader) ReadWasmGenesis(cmd *cobra.Command) (*GenesisData, error) {
clientCtx := client.GetClientContextFromCmd(cmd)
serverCtx := server.GetServerContextFromCmd(cmd)
config := serverCtx.Config
config.SetRoot(clientCtx.HomeDir)
genFile := config.GenesisFile()
appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genFile)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal genesis state: %w", err)
}
var wasmGenesisState types.GenesisState
if appState[types.ModuleName] != nil {
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx.Codec.MustUnmarshalJSON(appState[types.ModuleName], &wasmGenesisState)
}
return NewGenesisData(
genFile,
genDoc,
appState,
&wasmGenesisState,
), nil
}
var (
_ GenesisReader = DefaultGenesisIO{}
_ GenesisMutator = DefaultGenesisIO{}
)
// DefaultGenesisIO implements both interfaces to read and modify the genesis state for this module.
// This implementation uses the default data structure that is used by the module.go genesis import/ export.
type DefaultGenesisIO struct {
DefaultGenesisReader
}
// NewDefaultGenesisIO constructor to create a new instance
func NewDefaultGenesisIO() *DefaultGenesisIO {
return &DefaultGenesisIO{DefaultGenesisReader: DefaultGenesisReader{}}
}
// AlterWasmModuleState loads the genesis from the default or set home dir,
// unmarshalls the wasm module section into the object representation
// calls the callback function to modify it
// and marshals the modified state back into the genesis file
func (x DefaultGenesisIO) AlterWasmModuleState(cmd *cobra.Command, callback func(state *types.GenesisState, appState map[string]json.RawMessage) error) error {
g, err := x.ReadWasmGenesis(cmd)
if err != nil {
return err
}
if err := callback(g.WasmModuleState, g.AppState); err != nil {
return err
}
// and store update
if err := g.WasmModuleState.ValidateBasic(); err != nil {
return err
}
clientCtx := client.GetClientContextFromCmd(cmd)
wasmGenStateBz, err := clientCtx.Codec.MarshalJSON(g.WasmModuleState)
if err != nil {
return sdkerrors.Wrap(err, "marshal wasm genesis state")
}
g.AppState[types.ModuleName] = wasmGenStateBz
appStateJSON, err := json.Marshal(g.AppState)
if err != nil {
return sdkerrors.Wrap(err, "marshal application genesis state")
}
g.GenDoc.AppState = appStateJSON
return genutil.ExportGenesisFile(g.GenDoc, g.GenesisFile)
}
// contractSeqValue reads the contract sequence from the genesis or
// returns default start value used in the keeper
func contractSeqValue(state *types.GenesisState) uint64 {
var seq uint64 = 1
for _, s := range state.Sequences {
if bytes.Equal(s.IDKey, types.KeyLastInstanceID) {
seq = s.Value
break
}
}
return seq
}
// codeSeqValue reads the code sequence from the genesis or
// returns default start value used in the keeper
func codeSeqValue(state *types.GenesisState) uint64 {
var seq uint64 = 1
for _, s := range state.Sequences {
if bytes.Equal(s.IDKey, types.KeyLastCodeID) {
seq = s.Value
break
}
}
return seq
}
// getActorAddress returns the account address for the `--run-as` flag.
// The flag value can either be an address already or a key name where the
// address is read from the keyring instead.
func getActorAddress(cmd *cobra.Command) (sdk.AccAddress, error) {
actorArg, err := cmd.Flags().GetString(flagRunAs)
if err != nil {
return nil, fmt.Errorf("run-as: %s", err.Error())
}
if len(actorArg) == 0 {
return nil, errors.New("run-as address is required")
}
actorAddr, err := sdk.AccAddressFromBech32(actorArg)
if err == nil {
return actorAddr, nil
}
inBuf := bufio.NewReader(cmd.InOrStdin())
keyringBackend, err := cmd.Flags().GetString(flags.FlagKeyringBackend)
if err != nil {
return nil, err
}
homeDir := client.GetClientContextFromCmd(cmd).HomeDir
// attempt to lookup address from Keybase if no address was provided
kb, err := keyring.New(sdk.KeyringServiceName(), keyringBackend, homeDir, inBuf)
if err != nil {
return nil, err
}
info, err := kb.Key(actorArg)
if err != nil {
return nil, fmt.Errorf("failed to get address from Keybase: %w", err)
}
return info.GetAddress(), nil
}