cosmos-sdk/types/simulation/types.go

176 lines
5.5 KiB
Go
Raw Normal View History

package simulation
import (
"encoding/json"
"math/rand"
"time"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
refactor: Rename x/{mod}/legacy to x/{mod}/migrations (#9628) <!-- The default pull request template is for types feat, fix, or refactor. For other templates, add one of the following parameters to the url: - template=docs.md - template=other.md --> ## Description Closes: #8700 <!-- Add a description of the changes that this PR introduces and the files that are the most critical to review. --> --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [x] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [x] provided a link to the relevant issue or specification - [x] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [x] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [x] added a changelog entry to `CHANGELOG.md` - [x] included comments for [documenting Go code](https://blog.golang.org/godoc) - [x] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
2021-07-05 07:55:51 -07:00
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx"
)
type WeightedProposalContent interface {
AppParamsKey() string // key used to retrieve the value of the weight from the simulation application params
DefaultWeight() int // default weight
ContentSimulatorFn() ContentSimulatorFn // content simulator function
}
type ContentSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account) Content
type Content interface {
GetTitle() string
GetDescription() string
ProposalRoute() string
ProposalType() string
ValidateBasic() error
String() string
}
type SimValFn func(r *rand.Rand) string
type ParamChange interface {
Subspace() string
Key() string
SimValue() SimValFn
ComposedKey() string
}
type WeightedOperation interface {
Weight() int
Op() Operation
}
// Operation runs a state machine transition, and ensures the transition
// happened as expected. The operation could be running and testing a fuzzed
// transaction, or doing the same for a message.
//
// For ease of debugging, an operation returns a descriptive message "action",
// which details what this fuzzed state machine transition actually did.
//
// Operations can optionally provide a list of "FutureOperations" to run later
// These will be ran at the beginning of the corresponding block.
type Operation func(r *rand.Rand, app *baseapp.BaseApp,
ctx sdk.Context, accounts []Account, chainID string) (
OperationMsg OperationMsg, futureOps []FutureOperation, err error)
// OperationMsg - structure for operation output
type OperationMsg struct {
Route string `json:"route" yaml:"route"` // msg route (i.e module name)
Name string `json:"name" yaml:"name"` // operation name (msg Type or "no-operation")
Comment string `json:"comment" yaml:"comment"` // additional comment
OK bool `json:"ok" yaml:"ok"` // success
Msg json.RawMessage `json:"msg" yaml:"msg"` // JSON encoded msg
}
// NewOperationMsgBasic creates a new operation message from raw input.
func NewOperationMsgBasic(route, name, comment string, ok bool, msg []byte) OperationMsg {
return OperationMsg{
Route: route,
Name: name,
Comment: comment,
OK: ok,
Msg: msg,
}
}
// NewOperationMsg - create a new operation message from sdk.Msg
implement x/authz module (#7629) * WIP: Msg authorization module added * fixing errors * fixed errors * fixed module.go * Add msg_tests * fixes compile issues * fix test * fix test * Add msg types tests * Fix Getmsgs * fixed codec issue * Fix syntax issues * Fix keeper * fixed proto issues * Fix keeper tests * fixed router in keeper * Fix query proto * Fix cli txs * Add grpc query client implementation * Add grpc-keeper test * Add grpc query tests Add revoke and exec authorization cli commands * Fix linting issues * Fix cli query * fix lint errors * Add Genesis state * Fix query authorization * Review changes * Fix grant authorization handler * Add cli tests * Add cli tests * Fix genesis test * Fix issues * update module to use proto msg services * Add simultion tests * Fix lint * fix lint * WIP simulations * WIP simulations * add msg tests * Fix simulation * Fix errors * fix genesis import export * fix sim tests * fix sim * fix test * Register RegisterMsgServer * WIP * WIP * Update keeper test * change msg_authorization module name to authz * changed type conversion for serviceMsg * serviceMsg change to any * Fix issues * fix msg tests * fix errors * proto format * remove LegacyQuerierHandler * Use MsgServiceRouter * fix keeper-test * fix query authorizations * fix NewCmdSendAs * fix simtests * fix error * fix lint * fix lint * add tests for generic authorization * fix imports * format * Update error message * remove println * add query all grants * Add pagination for queries * format * fix lint * review changes * fix grpc tests * add pagination to cli query * review changes * replace panic with error * lint * fix errors * fix tests * remove gogoproto extensions * update function doc * review changes * fix errors * fix query flags * fix grpc query test * init service-msg * remove unsed field * add proto-codec for simulations * fix codec issue * update authz simulations * change msgauth to authz * add check for invalid msg-type * change expiration flag to Unix * doc * update module.go * fix sims * fix grant-authorization sims * fix error * fix error * add build flag * fix codec issue * rename * review changes * format * review changes * go.mod * refactor * proto-gen * Update x/authz/keeper/grpc_query_test.go Co-authored-by: Amaury <amaury.martiny@protonmail.com> * Update x/authz/keeper/grpc_query_test.go Co-authored-by: Amaury <amaury.martiny@protonmail.com> * Update x/authz/keeper/grpc_query_test.go Co-authored-by: Amaury <amaury.martiny@protonmail.com> * Fix review comments * fix protogen * Follow Msg...Request style for msg requests * update comment * Fix error codes * fix review comment * improve msg validations * Handle error in casting msgs * rename actor => grantStoreKey * add godoc * add godoc * Fix simulations * Fix cli, cli_tests * Fix simulations * rename to GetOrRevokeAuthorization * Move events to keeper * Fix fmt * Update x/authz/client/cli/tx.go Co-authored-by: Amaury <amaury.martiny@protonmail.com> * rename actor * fix lint Co-authored-by: atheesh <atheesh@vitwit.com> Co-authored-by: atheeshp <59333759+atheeshp@users.noreply.github.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: MD Aleem <72057206+aleem1413@users.noreply.github.com> Co-authored-by: Anil Kumar Kammari <anil@vitwit.com>
2021-01-25 08:41:30 -08:00
func NewOperationMsg(msg sdk.Msg, ok bool, comment string, cdc *codec.ProtoCodec) OperationMsg {
if legacyMsg, okType := msg.(legacytx.LegacyMsg); okType {
return NewOperationMsgBasic(legacyMsg.Route(), legacyMsg.Type(), comment, ok, legacyMsg.GetSignBytes())
implement x/authz module (#7629) * WIP: Msg authorization module added * fixing errors * fixed errors * fixed module.go * Add msg_tests * fixes compile issues * fix test * fix test * Add msg types tests * Fix Getmsgs * fixed codec issue * Fix syntax issues * Fix keeper * fixed proto issues * Fix keeper tests * fixed router in keeper * Fix query proto * Fix cli txs * Add grpc query client implementation * Add grpc-keeper test * Add grpc query tests Add revoke and exec authorization cli commands * Fix linting issues * Fix cli query * fix lint errors * Add Genesis state * Fix query authorization * Review changes * Fix grant authorization handler * Add cli tests * Add cli tests * Fix genesis test * Fix issues * update module to use proto msg services * Add simultion tests * Fix lint * fix lint * WIP simulations * WIP simulations * add msg tests * Fix simulation * Fix errors * fix genesis import export * fix sim tests * fix sim * fix test * Register RegisterMsgServer * WIP * WIP * Update keeper test * change msg_authorization module name to authz * changed type conversion for serviceMsg * serviceMsg change to any * Fix issues * fix msg tests * fix errors * proto format * remove LegacyQuerierHandler * Use MsgServiceRouter * fix keeper-test * fix query authorizations * fix NewCmdSendAs * fix simtests * fix error * fix lint * fix lint * add tests for generic authorization * fix imports * format * Update error message * remove println * add query all grants * Add pagination for queries * format * fix lint * review changes * fix grpc tests * add pagination to cli query * review changes * replace panic with error * lint * fix errors * fix tests * remove gogoproto extensions * update function doc * review changes * fix errors * fix query flags * fix grpc query test * init service-msg * remove unsed field * add proto-codec for simulations * fix codec issue * update authz simulations * change msgauth to authz * add check for invalid msg-type * change expiration flag to Unix * doc * update module.go * fix sims * fix grant-authorization sims * fix error * fix error * add build flag * fix codec issue * rename * review changes * format * review changes * go.mod * refactor * proto-gen * Update x/authz/keeper/grpc_query_test.go Co-authored-by: Amaury <amaury.martiny@protonmail.com> * Update x/authz/keeper/grpc_query_test.go Co-authored-by: Amaury <amaury.martiny@protonmail.com> * Update x/authz/keeper/grpc_query_test.go Co-authored-by: Amaury <amaury.martiny@protonmail.com> * Fix review comments * fix protogen * Follow Msg...Request style for msg requests * update comment * Fix error codes * fix review comment * improve msg validations * Handle error in casting msgs * rename actor => grantStoreKey * add godoc * add godoc * Fix simulations * Fix cli, cli_tests * Fix simulations * rename to GetOrRevokeAuthorization * Move events to keeper * Fix fmt * Update x/authz/client/cli/tx.go Co-authored-by: Amaury <amaury.martiny@protonmail.com> * rename actor * fix lint Co-authored-by: atheesh <atheesh@vitwit.com> Co-authored-by: atheeshp <59333759+atheeshp@users.noreply.github.com> Co-authored-by: Amaury Martiny <amaury.martiny@protonmail.com> Co-authored-by: MD Aleem <72057206+aleem1413@users.noreply.github.com> Co-authored-by: Anil Kumar Kammari <anil@vitwit.com>
2021-01-25 08:41:30 -08:00
}
bz := cdc.MustMarshalJSON(msg)
return NewOperationMsgBasic(sdk.MsgTypeURL(msg), sdk.MsgTypeURL(msg), comment, ok, bz)
}
// NoOpMsg - create a no-operation message
func NoOpMsg(route, msgType, comment string) OperationMsg {
return NewOperationMsgBasic(route, msgType, comment, false, nil)
}
// log entry text for this operation msg
func (om OperationMsg) String() string {
out, err := json.Marshal(om)
if err != nil {
panic(err)
}
return string(out)
}
// MustMarshal Marshals the operation msg, panic on error
func (om OperationMsg) MustMarshal() json.RawMessage {
out, err := json.Marshal(om)
if err != nil {
panic(err)
}
return out
}
// LogEvent adds an event for the events stats
func (om OperationMsg) LogEvent(eventLogger func(route, op, evResult string)) {
pass := "ok"
if !om.OK {
pass = "failure"
}
eventLogger(om.Route, om.Name, pass)
}
// FutureOperation is an operation which will be ran at the beginning of the
// provided BlockHeight. If both a BlockHeight and BlockTime are specified, it
// will use the BlockHeight. In the (likely) event that multiple operations
// are queued at the same block height, they will execute in a FIFO pattern.
type FutureOperation struct {
BlockHeight int
BlockTime time.Time
Op Operation
}
// AppParams defines a flat JSON of key/values for all possible configurable
// simulation parameters. It might contain: operation weights, simulation parameters
// and flattened module state parameters (i.e not stored under it's respective module name).
type AppParams map[string]json.RawMessage
// GetOrGenerate attempts to get a given parameter by key from the AppParams
// object. If it exists, it'll be decoded and returned. Otherwise, the provided
// ParamSimulator is used to generate a random value or default value (eg: in the
// case of operation weights where Rand is not used).
func (sp AppParams) GetOrGenerate(_ codec.JSONCodec, key string, ptr interface{}, r *rand.Rand, ps ParamSimulator) {
if v, ok := sp[key]; ok && v != nil {
err := json.Unmarshal(v, ptr)
if err != nil {
panic(err)
}
return
}
ps(r)
}
type ParamSimulator func(r *rand.Rand)
type SelectOpFn func(r *rand.Rand) Operation
// AppStateFn returns the app state json bytes and the genesis accounts
type AppStateFn func(r *rand.Rand, accs []Account, config Config) (
appState json.RawMessage, accounts []Account, chainId string, genesisTimestamp time.Time,
)
// RandomAccountFn returns a slice of n random simulation accounts
type RandomAccountFn func(r *rand.Rand, n int) []Account
type Params interface {
PastEvidenceFraction() float64
NumKeys() int
EvidenceFraction() float64
InitialLivenessWeightings() []int
LivenessTransitionMatrix() TransitionMatrix
BlockSizeTransitionMatrix() TransitionMatrix
}