various linter fixes (#6106)
x/staking: Fix all linter warnings. Fixed warnings across base packages. New linters: - unparam - nolintlint Co-authored-by: Alessio Treglia <alessio@tendermint.com>
This commit is contained in:
parent
9251812f69
commit
218ec99508
@ -32,8 +32,10 @@ linters:
|
||||
- typecheck
|
||||
- unconvert
|
||||
- unused
|
||||
- unparam
|
||||
- misspell
|
||||
- wsl
|
||||
- nolintlint
|
||||
|
||||
issues:
|
||||
exclude-rules:
|
||||
@ -54,6 +56,8 @@ issues:
|
||||
- text: "ST1016:"
|
||||
linters:
|
||||
- stylecheck
|
||||
max-issues-per-linter: 10000
|
||||
max-same-issues: 10000
|
||||
|
||||
linters-settings:
|
||||
dogsled:
|
||||
@ -61,3 +65,8 @@ linters-settings:
|
||||
maligned:
|
||||
# print struct with more effective memory layout or not, false by default
|
||||
suggest-new: true
|
||||
nolintlint:
|
||||
allow-unused: false
|
||||
allow-leading-space: true
|
||||
require-explanation: false
|
||||
require-specific: false
|
||||
|
||||
@ -87,6 +87,7 @@ func (app *BaseApp) FilterPeerByAddrPort(info string) abci.ResponseQuery {
|
||||
if app.addrPeerFilter != nil {
|
||||
return app.addrPeerFilter(info)
|
||||
}
|
||||
|
||||
return abci.ResponseQuery{}
|
||||
}
|
||||
|
||||
@ -95,6 +96,7 @@ func (app *BaseApp) FilterPeerByID(info string) abci.ResponseQuery {
|
||||
if app.idPeerFilter != nil {
|
||||
return app.idPeerFilter(info)
|
||||
}
|
||||
|
||||
return abci.ResponseQuery{}
|
||||
}
|
||||
|
||||
@ -136,7 +138,6 @@ func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeg
|
||||
if app.beginBlocker != nil {
|
||||
res = app.beginBlocker(app.deliverState.ctx, req)
|
||||
}
|
||||
|
||||
// set the signed validators for addition to context in deliverTx
|
||||
app.voteInfos = req.LastCommitInfo.GetVotes()
|
||||
return res
|
||||
|
||||
@ -48,6 +48,7 @@ func (app *BaseApp) SetName(name string) {
|
||||
if app.sealed {
|
||||
panic("SetName() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.name = name
|
||||
}
|
||||
|
||||
@ -56,6 +57,7 @@ func (app *BaseApp) SetParamStore(ps ParamStore) {
|
||||
if app.sealed {
|
||||
panic("SetParamStore() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.paramStore = ps
|
||||
}
|
||||
|
||||
@ -64,6 +66,7 @@ func (app *BaseApp) SetAppVersion(v string) {
|
||||
if app.sealed {
|
||||
panic("SetAppVersion() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.appVersion = v
|
||||
}
|
||||
|
||||
@ -71,6 +74,7 @@ func (app *BaseApp) SetDB(db dbm.DB) {
|
||||
if app.sealed {
|
||||
panic("SetDB() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.db = db
|
||||
}
|
||||
|
||||
@ -78,6 +82,7 @@ func (app *BaseApp) SetCMS(cms store.CommitMultiStore) {
|
||||
if app.sealed {
|
||||
panic("SetEndBlocker() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.cms = cms
|
||||
}
|
||||
|
||||
@ -85,6 +90,7 @@ func (app *BaseApp) SetInitChainer(initChainer sdk.InitChainer) {
|
||||
if app.sealed {
|
||||
panic("SetInitChainer() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.initChainer = initChainer
|
||||
}
|
||||
|
||||
@ -92,6 +98,7 @@ func (app *BaseApp) SetBeginBlocker(beginBlocker sdk.BeginBlocker) {
|
||||
if app.sealed {
|
||||
panic("SetBeginBlocker() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.beginBlocker = beginBlocker
|
||||
}
|
||||
|
||||
@ -99,6 +106,7 @@ func (app *BaseApp) SetEndBlocker(endBlocker sdk.EndBlocker) {
|
||||
if app.sealed {
|
||||
panic("SetEndBlocker() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.endBlocker = endBlocker
|
||||
}
|
||||
|
||||
@ -106,6 +114,7 @@ func (app *BaseApp) SetAnteHandler(ah sdk.AnteHandler) {
|
||||
if app.sealed {
|
||||
panic("SetAnteHandler() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.anteHandler = ah
|
||||
}
|
||||
|
||||
@ -113,6 +122,7 @@ func (app *BaseApp) SetAddrPeerFilter(pf sdk.PeerFilter) {
|
||||
if app.sealed {
|
||||
panic("SetAddrPeerFilter() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.addrPeerFilter = pf
|
||||
}
|
||||
|
||||
@ -120,6 +130,7 @@ func (app *BaseApp) SetIDPeerFilter(pf sdk.PeerFilter) {
|
||||
if app.sealed {
|
||||
panic("SetIDPeerFilter() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.idPeerFilter = pf
|
||||
}
|
||||
|
||||
@ -127,6 +138,7 @@ func (app *BaseApp) SetFauxMerkleMode() {
|
||||
if app.sealed {
|
||||
panic("SetFauxMerkleMode() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.fauxMerkleMode = true
|
||||
}
|
||||
|
||||
@ -141,6 +153,7 @@ func (app *BaseApp) SetStoreLoader(loader StoreLoader) {
|
||||
if app.sealed {
|
||||
panic("SetStoreLoader() on sealed BaseApp")
|
||||
}
|
||||
|
||||
app.storeLoader = loader
|
||||
}
|
||||
|
||||
|
||||
@ -38,6 +38,7 @@ func ValidateBlockParams(i interface{}) error {
|
||||
if v.MaxBytes <= 0 {
|
||||
return fmt.Errorf("block maximum bytes must be positive: %d", v.MaxBytes)
|
||||
}
|
||||
|
||||
if v.MaxGas < -1 {
|
||||
return fmt.Errorf("block maximum gas must be greater than or equal to -1: %d", v.MaxGas)
|
||||
}
|
||||
@ -56,6 +57,7 @@ func ValidateEvidenceParams(i interface{}) error {
|
||||
if v.MaxAgeNumBlocks <= 0 {
|
||||
return fmt.Errorf("evidence maximum age in blocks must be positive: %d", v.MaxAgeNumBlocks)
|
||||
}
|
||||
|
||||
if v.MaxAgeDuration <= 0 {
|
||||
return fmt.Errorf("evidence maximum age time duration must be positive: %v", v.MaxAgeDuration)
|
||||
}
|
||||
|
||||
@ -25,11 +25,13 @@ func (qrt *QueryRouter) AddRoute(path string, q sdk.Querier) sdk.QueryRouter {
|
||||
if !isAlphaNumeric(path) {
|
||||
panic("route expressions can only contain alphanumeric characters")
|
||||
}
|
||||
|
||||
if qrt.routes[path] != nil {
|
||||
panic(fmt.Sprintf("route %s has already been initialized", path))
|
||||
}
|
||||
|
||||
qrt.routes[path] = q
|
||||
|
||||
return qrt
|
||||
}
|
||||
|
||||
|
||||
@ -132,7 +132,9 @@ func (ctx CLIContext) Verify(height int64) (tmtypes.SignedHeader, error) {
|
||||
if ctx.Verifier == nil {
|
||||
return tmtypes.SignedHeader{}, fmt.Errorf("missing valid certifier to verify data from distrusted node")
|
||||
}
|
||||
|
||||
check, err := tmliteProxy.GetCertifiedCommit(height, ctx.Client, ctx.Verifier)
|
||||
|
||||
switch {
|
||||
case tmliteErr.IsErrCommitNotFound(err):
|
||||
return tmtypes.SignedHeader{}, ErrVerifyCommit(height)
|
||||
@ -175,8 +177,8 @@ func (ctx CLIContext) verifyProof(queryPath string, resp abci.ResponseQuery) err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
err = prt.VerifyValue(resp.Proof, commit.Header.AppHash, kp.String(), resp.Value)
|
||||
if err != nil {
|
||||
|
||||
if err := prt.VerifyValue(resp.Proof, commit.Header.AppHash, kp.String(), resp.Value); err != nil {
|
||||
return errors.Wrap(err, "failed to prove merkle proof")
|
||||
}
|
||||
|
||||
@ -199,6 +201,7 @@ func isQueryStoreWithProof(path string) bool {
|
||||
}
|
||||
|
||||
paths := strings.SplitN(path[1:], "/", 3)
|
||||
|
||||
switch {
|
||||
case len(paths) != 3:
|
||||
return false
|
||||
@ -218,6 +221,7 @@ func parseQueryStorePath(path string) (storeName string, err error) {
|
||||
}
|
||||
|
||||
paths := strings.SplitN(path[1:], "/", 3)
|
||||
|
||||
switch {
|
||||
case len(paths) != 3:
|
||||
return "", errors.New("expected format like /store/<storeName>/key")
|
||||
|
||||
@ -72,6 +72,7 @@ func GetString(prompt string, buf *bufio.Reader) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return strings.TrimSpace(out), nil
|
||||
}
|
||||
|
||||
@ -90,5 +91,6 @@ func readLineFromBuf(buf *bufio.Reader) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return strings.TrimSpace(pass), nil
|
||||
}
|
||||
|
||||
@ -62,6 +62,7 @@ func (rs *RestServer) Start(listenAddr string, maxOpen int, readTimeout, writeTi
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
rs.log.Info(
|
||||
fmt.Sprintf(
|
||||
"Starting application REST service (chain-id: %q)...",
|
||||
@ -70,6 +71,7 @@ func (rs *RestServer) Start(listenAddr string, maxOpen int, readTimeout, writeTi
|
||||
)
|
||||
|
||||
var h http.Handler = rs.Mux
|
||||
|
||||
if cors {
|
||||
return rpcserver.StartHTTPServer(rs.listener, handlers.CORS()(h), rs.log, cfg)
|
||||
}
|
||||
@ -111,6 +113,7 @@ func (rs *RestServer) registerSwaggerUI() {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
staticServer := http.FileServer(statikFS)
|
||||
rs.Mux.PathPrefix("/").Handler(staticServer)
|
||||
}
|
||||
|
||||
@ -132,9 +132,10 @@ func NewInMemory(opts ...Option) Keyring {
|
||||
func New(
|
||||
appName, backend, rootDir string, userInput io.Reader, opts ...Option,
|
||||
) (Keyring, error) {
|
||||
|
||||
var db keyring.Keyring
|
||||
var err error
|
||||
var (
|
||||
db keyring.Keyring
|
||||
err error
|
||||
)
|
||||
|
||||
switch backend {
|
||||
case BackendMemory:
|
||||
@ -353,8 +354,7 @@ func (ks keystore) SaveLedgerKey(uid string, algo SignatureAlgo, hrp string, coi
|
||||
|
||||
func (ks keystore) writeLedgerKey(name string, pub tmcrypto.PubKey, path hd.BIP44Params, algo hd.PubKeyType) (Info, error) {
|
||||
info := newLedgerInfo(name, pub, path, algo)
|
||||
err := ks.writeInfo(info)
|
||||
if err != nil {
|
||||
if err := ks.writeInfo(info); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@ -422,8 +422,9 @@ func (ks keystore) KeyByAddress(address sdk.Address) (Info, error) {
|
||||
|
||||
func (ks keystore) List() ([]Info, error) {
|
||||
var res []Info
|
||||
|
||||
keys, err := ks.db.Keys()
|
||||
if err != nil {
|
||||
if err != nil { //nolint:unparam
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@ -525,7 +526,8 @@ func SignWithLedger(info Info, msg []byte) (sig []byte, pub tmcrypto.PubKey, err
|
||||
default:
|
||||
return nil, nil, errors.New("not a ledger object")
|
||||
}
|
||||
path, err := info.GetPath()
|
||||
|
||||
path, err := info.GetPath() //nolint:unparam
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@ -573,6 +575,7 @@ func newKWalletBackendKeyringConfig(appName, _ string, _ io.Reader) keyring.Conf
|
||||
|
||||
func newPassBackendKeyringConfig(appName, _ string, _ io.Reader) keyring.Config {
|
||||
prefix := fmt.Sprintf(passKeyringPrefix, appName)
|
||||
|
||||
return keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{keyring.PassBackend},
|
||||
ServiceName: appName,
|
||||
@ -582,6 +585,7 @@ func newPassBackendKeyringConfig(appName, _ string, _ io.Reader) keyring.Config
|
||||
|
||||
func newFileBackendKeyringConfig(name, dir string, buf io.Reader) keyring.Config {
|
||||
fileDir := filepath.Join(dir, keyringFileDirName)
|
||||
|
||||
return keyring.Config{
|
||||
AllowedBackends: []keyring.BackendType{keyring.FileBackend},
|
||||
ServiceName: name,
|
||||
@ -598,6 +602,7 @@ func newRealPrompt(dir string, buf io.Reader) func(string) (string, error) {
|
||||
var keyhash []byte
|
||||
|
||||
_, err := os.Stat(keyhashFilePath)
|
||||
|
||||
switch {
|
||||
case err == nil:
|
||||
keyhash, err = ioutil.ReadFile(keyhashFilePath)
|
||||
@ -615,6 +620,7 @@ func newRealPrompt(dir string, buf io.Reader) func(string) (string, error) {
|
||||
}
|
||||
|
||||
failureCounter := 0
|
||||
|
||||
for {
|
||||
failureCounter++
|
||||
if failureCounter > maxPassphraseEntryAttempts {
|
||||
@ -623,7 +629,7 @@ func newRealPrompt(dir string, buf io.Reader) func(string) (string, error) {
|
||||
|
||||
buf := bufio.NewReader(buf)
|
||||
pass, err := input.GetPassword("Enter keyring passphrase:", buf)
|
||||
if err != nil {
|
||||
if err != nil { //nolint:unparam
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
continue
|
||||
}
|
||||
@ -633,6 +639,7 @@ func newRealPrompt(dir string, buf io.Reader) func(string) (string, error) {
|
||||
fmt.Fprintln(os.Stderr, "incorrect passphrase")
|
||||
continue
|
||||
}
|
||||
|
||||
return pass, nil
|
||||
}
|
||||
|
||||
@ -649,7 +656,7 @@ func newRealPrompt(dir string, buf io.Reader) func(string) (string, error) {
|
||||
|
||||
saltBytes := tmcrypto.CRandBytes(16)
|
||||
passwordHash, err := bcrypt.GenerateFromPassword(saltBytes, []byte(pass), 2)
|
||||
if err != nil {
|
||||
if err != nil { //nolint:unparam
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
continue
|
||||
}
|
||||
@ -668,8 +675,7 @@ func (ks keystore) writeLocalKey(name string, priv tmcrypto.PrivKey, algo hd.Pub
|
||||
pub := priv.PubKey()
|
||||
|
||||
info := newLocalInfo(name, pub, string(priv.Bytes()), algo)
|
||||
err := ks.writeInfo(info)
|
||||
if err != nil {
|
||||
if err := ks.writeInfo(info); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@ -685,6 +691,7 @@ func (ks keystore) writeInfo(info Info) error {
|
||||
if exists {
|
||||
return fmt.Errorf("public key already exist in keybase")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@ -34,7 +34,8 @@ func NewLegacy(name, dir string, opts ...KeybaseOption) (LegacyKeybase, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newDBKeybase(db, opts...), nil
|
||||
|
||||
return newDBKeybase(db), nil
|
||||
}
|
||||
|
||||
var _ LegacyKeybase = dbKeybase{}
|
||||
@ -49,7 +50,7 @@ type dbKeybase struct {
|
||||
|
||||
// newDBKeybase creates a new dbKeybase instance using the provided DB for
|
||||
// reading and writing keys.
|
||||
func newDBKeybase(db dbm.DB, opts ...KeybaseOption) dbKeybase {
|
||||
func newDBKeybase(db dbm.DB) dbKeybase {
|
||||
return dbKeybase{
|
||||
db: db,
|
||||
}
|
||||
@ -202,7 +203,9 @@ func NewInfoImporter(
|
||||
if err != nil {
|
||||
return keyringMigrator{}, err
|
||||
}
|
||||
|
||||
kr := keyring.(keystore)
|
||||
|
||||
return keyringMigrator{kr}, nil
|
||||
}
|
||||
|
||||
|
||||
@ -104,7 +104,6 @@ func (pkl PrivKeyLedgerSecp256k1) Sign(message []byte) ([]byte, error) {
|
||||
// LedgerShowAddress triggers a ledger device to show the corresponding address.
|
||||
func LedgerShowAddress(path hd.BIP44Params, expectedPubKey tmcrypto.PubKey,
|
||||
accountAddressPrefix string) error {
|
||||
|
||||
device, err := getLedgerDevice()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@ -50,7 +50,9 @@ var configTemplate *template.Template
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
|
||||
tmpl := template.New("appConfigFileTemplate")
|
||||
|
||||
if configTemplate, err = tmpl.Parse(defaultConfigTemplate); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@ -61,6 +63,7 @@ func init() {
|
||||
func ParseConfig() (*Config, error) {
|
||||
conf := DefaultConfig()
|
||||
err := viper.Unmarshal(conf)
|
||||
|
||||
return conf, err
|
||||
}
|
||||
|
||||
|
||||
@ -72,7 +72,7 @@ which accepts a path for the resulting pprof file.
|
||||
|
||||
ctx.Logger.Info("starting ABCI with Tendermint")
|
||||
|
||||
_, err := startInProcess(ctx, appCreator)
|
||||
err := startInProcess(ctx, appCreator)
|
||||
return err
|
||||
},
|
||||
}
|
||||
@ -143,26 +143,26 @@ func startStandAlone(ctx *Context, appCreator AppCreator) error {
|
||||
select {}
|
||||
}
|
||||
|
||||
func startInProcess(ctx *Context, appCreator AppCreator) (*node.Node, error) {
|
||||
func startInProcess(ctx *Context, appCreator AppCreator) error {
|
||||
cfg := ctx.Config
|
||||
home := cfg.RootDir
|
||||
|
||||
traceWriterFile := viper.GetString(flagTraceStore)
|
||||
db, err := openDB(home)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
|
||||
traceWriter, err := openTraceWriter(traceWriterFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
|
||||
app := appCreator(ctx.Logger, db, traceWriter)
|
||||
|
||||
nodeKey, err := p2p.LoadOrGenNodeKey(cfg.NodeKeyFile())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
|
||||
// create & start tendermint node
|
||||
@ -177,11 +177,11 @@ func startInProcess(ctx *Context, appCreator AppCreator) (*node.Node, error) {
|
||||
ctx.Logger.With("module", "node"),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tmNode.Start(); err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
|
||||
var cpuProfileCleanup func()
|
||||
@ -189,12 +189,12 @@ func startInProcess(ctx *Context, appCreator AppCreator) (*node.Node, error) {
|
||||
if cpuProfile := viper.GetString(flagCPUProfile); cpuProfile != "" {
|
||||
f, err := os.Create(cpuProfile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
|
||||
ctx.Logger.Info("starting CPU profiler", "profile", cpuProfile)
|
||||
if err := pprof.StartCPUProfile(f); err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
|
||||
cpuProfileCleanup = func() {
|
||||
|
||||
@ -53,21 +53,26 @@ func PersistentPreRunEFn(context *Context) func(*cobra.Command, []string) error
|
||||
if cmd.Name() == version.Cmd.Name() {
|
||||
return nil
|
||||
}
|
||||
|
||||
config, err := interceptLoadConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
|
||||
logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if viper.GetBool(cli.TraceFlag) {
|
||||
logger = log.NewTracingLogger(logger)
|
||||
}
|
||||
|
||||
logger = logger.With("module", "main")
|
||||
context.Config = config
|
||||
context.Logger = logger
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@ -173,6 +178,7 @@ func ExternalIP() (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
for _, iface := range ifaces {
|
||||
if skipInterface(iface) {
|
||||
continue
|
||||
@ -181,6 +187,7 @@ func ExternalIP() (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
for _, addr := range addrs {
|
||||
ip := addrToIP(addr)
|
||||
if ip == nil || ip.IsLoopback() {
|
||||
@ -200,18 +207,22 @@ func ExternalIP() (string, error) {
|
||||
func TrapSignal(cleanupFunc func()) {
|
||||
sigs := make(chan os.Signal, 1)
|
||||
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
go func() {
|
||||
sig := <-sigs
|
||||
|
||||
if cleanupFunc != nil {
|
||||
cleanupFunc()
|
||||
}
|
||||
exitCode := 128
|
||||
|
||||
switch sig {
|
||||
case syscall.SIGINT:
|
||||
exitCode += int(syscall.SIGINT)
|
||||
case syscall.SIGTERM:
|
||||
exitCode += int(syscall.SIGTERM)
|
||||
}
|
||||
|
||||
os.Exit(exitCode)
|
||||
}()
|
||||
}
|
||||
@ -220,14 +231,17 @@ func skipInterface(iface net.Interface) bool {
|
||||
if iface.Flags&net.FlagUp == 0 {
|
||||
return true // interface down
|
||||
}
|
||||
|
||||
if iface.Flags&net.FlagLoopback != 0 {
|
||||
return true // loopback interface
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func addrToIP(addr net.Addr) net.IP {
|
||||
var ip net.IP
|
||||
|
||||
switch v := addr.(type) {
|
||||
case *net.IPNet:
|
||||
ip = v.IP
|
||||
|
||||
@ -172,5 +172,4 @@ func (gi *gasIterator) consumeSeekGas() {
|
||||
|
||||
gi.gasMeter.ConsumeGas(gi.gasConfig.ReadCostPerByte*types.Gas(len(value)), types.GasValuePerByteDesc)
|
||||
gi.gasMeter.ConsumeGas(gi.gasConfig.IterNextCostFlat, types.GasIterNextCostFlatDesc)
|
||||
|
||||
}
|
||||
|
||||
@ -20,8 +20,11 @@ func KVStoreReversePrefixIterator(kvs KVStore, prefix []byte) Iterator {
|
||||
// that differ from one another. It also skips value comparison for a set of provided prefixes.
|
||||
func DiffKVStores(a KVStore, b KVStore, prefixesToSkip [][]byte) (kvAs, kvBs []tmkv.Pair) {
|
||||
iterA := a.Iterator(nil, nil)
|
||||
|
||||
defer iterA.Close()
|
||||
|
||||
iterB := b.Iterator(nil, nil)
|
||||
|
||||
defer iterB.Close()
|
||||
|
||||
for {
|
||||
@ -32,14 +35,18 @@ func DiffKVStores(a KVStore, b KVStore, prefixesToSkip [][]byte) (kvAs, kvBs []t
|
||||
var kvA, kvB tmkv.Pair
|
||||
if iterA.Valid() {
|
||||
kvA = tmkv.Pair{Key: iterA.Key(), Value: iterA.Value()}
|
||||
|
||||
iterA.Next()
|
||||
}
|
||||
|
||||
if iterB.Valid() {
|
||||
kvB = tmkv.Pair{Key: iterB.Key(), Value: iterB.Value()}
|
||||
|
||||
iterB.Next()
|
||||
}
|
||||
|
||||
compareValue := true
|
||||
|
||||
for _, prefix := range prefixesToSkip {
|
||||
// Skip value comparison if we matched a prefix
|
||||
if bytes.HasPrefix(kvA.Key, prefix) || bytes.HasPrefix(kvB.Key, prefix) {
|
||||
@ -71,13 +78,15 @@ func PrefixEndBytes(prefix []byte) []byte {
|
||||
end[len(end)-1]++
|
||||
break
|
||||
}
|
||||
|
||||
end = end[:len(end)-1]
|
||||
|
||||
if len(end) == 0 {
|
||||
end = nil
|
||||
break
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return end
|
||||
}
|
||||
|
||||
|
||||
@ -19,13 +19,6 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
TotalCoins = sdk.NewCoins(
|
||||
sdk.NewCoin(Fee2Denom, sdk.TokensFromConsensusPower(2000000)),
|
||||
sdk.NewCoin(FeeDenom, sdk.TokensFromConsensusPower(2000000)),
|
||||
sdk.NewCoin(FooDenom, sdk.TokensFromConsensusPower(2000)),
|
||||
sdk.NewCoin(Denom, sdk.TokensFromConsensusPower(300).Add(sdk.NewInt(12))), // add coins from inflation
|
||||
)
|
||||
|
||||
StartCoins = sdk.NewCoins(
|
||||
sdk.NewCoin(Fee2Denom, sdk.TokensFromConsensusPower(1000000)),
|
||||
sdk.NewCoin(FeeDenom, sdk.TokensFromConsensusPower(1000000)),
|
||||
|
||||
@ -159,7 +159,6 @@ func NewDecFromStr(str string) (Dec, error) {
|
||||
return Dec{}, ErrInvalidDecimalLength
|
||||
}
|
||||
combinedStr += strs[1]
|
||||
|
||||
} else if len(strs) > 2 {
|
||||
return Dec{}, ErrInvalidDecimalStr
|
||||
}
|
||||
@ -277,7 +276,6 @@ func (d Dec) MulInt64(i int64) Dec {
|
||||
|
||||
// quotient
|
||||
func (d Dec) Quo(d2 Dec) Dec {
|
||||
|
||||
// multiply precision twice
|
||||
mul := new(big.Int).Mul(d.i, precisionReuse)
|
||||
mul.Mul(mul, precisionReuse)
|
||||
@ -293,7 +291,6 @@ func (d Dec) Quo(d2 Dec) Dec {
|
||||
|
||||
// quotient truncate
|
||||
func (d Dec) QuoTruncate(d2 Dec) Dec {
|
||||
|
||||
// multiply precision twice
|
||||
mul := new(big.Int).Mul(d.i, precisionReuse)
|
||||
mul.Mul(mul, precisionReuse)
|
||||
@ -386,6 +383,7 @@ func (d Dec) Power(power uint64) Dec {
|
||||
return OneDec()
|
||||
}
|
||||
tmp := OneDec()
|
||||
|
||||
for i := power; i > 1; {
|
||||
if i%2 == 0 {
|
||||
i /= 2
|
||||
@ -395,6 +393,7 @@ func (d Dec) Power(power uint64) Dec {
|
||||
}
|
||||
d = d.Mul(d)
|
||||
}
|
||||
|
||||
return d.Mul(tmp)
|
||||
}
|
||||
|
||||
@ -423,7 +422,8 @@ func (d Dec) String() string {
|
||||
}
|
||||
|
||||
isNeg := d.IsNegative()
|
||||
if d.IsNegative() {
|
||||
|
||||
if isNeg {
|
||||
d = d.Neg()
|
||||
}
|
||||
|
||||
@ -451,9 +451,7 @@ func (d Dec) String() string {
|
||||
|
||||
// set final digits
|
||||
copy(bzStr[2+(Precision-inputSize):], bzInt)
|
||||
|
||||
} else {
|
||||
|
||||
// inputSize + 1 to account for the decimal point that is being added
|
||||
bzStr = make([]byte, inputSize+1)
|
||||
decPointPlace := inputSize - Precision
|
||||
@ -484,7 +482,6 @@ func (d Dec) String() string {
|
||||
//
|
||||
// Mutates the input. Use the non-mutative version if that is undesired
|
||||
func chopPrecisionAndRound(d *big.Int) *big.Int {
|
||||
|
||||
// remove the negative and add it back when returning
|
||||
if d.Sign() == -1 {
|
||||
// make d positive, compute chopped value, and then un-mutate d
|
||||
@ -517,7 +514,6 @@ func chopPrecisionAndRound(d *big.Int) *big.Int {
|
||||
}
|
||||
|
||||
func chopPrecisionAndRoundUp(d *big.Int) *big.Int {
|
||||
|
||||
// remove the negative and add it back when returning
|
||||
if d.Sign() == -1 {
|
||||
// make d positive, compute chopped value, and then un-mutate d
|
||||
|
||||
@ -33,6 +33,7 @@ func RandomAcc(r *rand.Rand, accs []Account) (Account, int) {
|
||||
// RandomAccounts generates n random accounts
|
||||
func RandomAccounts(r *rand.Rand, n int) []Account {
|
||||
accs := make([]Account, n)
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
// don't need that much entropy for simulation
|
||||
privkeySeed := make([]byte, 15)
|
||||
@ -81,5 +82,6 @@ func RandomFees(r *rand.Rand, ctx sdk.Context, spendableCoins sdk.Coins) (sdk.Co
|
||||
// Create a random fee and verify the fees are within the account's spendable
|
||||
// balance.
|
||||
fees := sdk.NewCoins(sdk.NewCoin(randCoin.Denom, amt))
|
||||
|
||||
return fees, nil
|
||||
}
|
||||
|
||||
@ -27,13 +27,16 @@ func RandStringOfLength(r *rand.Rand, n int) string {
|
||||
if remain == 0 {
|
||||
cache, remain = r.Int63(), letterIdxMax
|
||||
}
|
||||
|
||||
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
|
||||
b[i] = letterBytes[idx]
|
||||
i--
|
||||
}
|
||||
|
||||
cache >>= letterIdxBits
|
||||
remain--
|
||||
}
|
||||
|
||||
return string(b)
|
||||
}
|
||||
|
||||
@ -42,7 +45,9 @@ func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) {
|
||||
if !max.GTE(sdk.OneInt()) {
|
||||
return sdk.Int{}, errors.New("max too small")
|
||||
}
|
||||
|
||||
max = max.Sub(sdk.OneInt())
|
||||
|
||||
return sdk.NewIntFromBigInt(new(big.Int).Rand(r, max.BigInt())).Add(sdk.OneInt()), nil
|
||||
}
|
||||
|
||||
@ -50,6 +55,7 @@ func RandPositiveInt(r *rand.Rand, max sdk.Int) (sdk.Int, error) {
|
||||
// Note: The range of RandomAmount includes max, and is, in fact, biased to return max as well as 0.
|
||||
func RandomAmount(r *rand.Rand, max sdk.Int) sdk.Int {
|
||||
var randInt = big.NewInt(0)
|
||||
|
||||
switch r.Intn(10) {
|
||||
case 0:
|
||||
// randInt = big.NewInt(0)
|
||||
@ -58,6 +64,7 @@ func RandomAmount(r *rand.Rand, max sdk.Int) sdk.Int {
|
||||
default: // NOTE: there are 10 total cases.
|
||||
randInt = big.NewInt(0).Rand(r, max.BigInt()) // up to max - 1
|
||||
}
|
||||
|
||||
return sdk.NewIntFromBigInt(randInt)
|
||||
}
|
||||
|
||||
@ -65,6 +72,7 @@ func RandomAmount(r *rand.Rand, max sdk.Int) sdk.Int {
|
||||
// Note: The range of RandomDecAmount includes max, and is, in fact, biased to return max as well as 0.
|
||||
func RandomDecAmount(r *rand.Rand, max sdk.Dec) sdk.Dec {
|
||||
var randInt = big.NewInt(0)
|
||||
|
||||
switch r.Intn(10) {
|
||||
case 0:
|
||||
// randInt = big.NewInt(0)
|
||||
@ -73,6 +81,7 @@ func RandomDecAmount(r *rand.Rand, max sdk.Dec) sdk.Dec {
|
||||
default: // NOTE: there are 10 total cases.
|
||||
randInt = big.NewInt(0).Rand(r, max.BigInt())
|
||||
}
|
||||
|
||||
return sdk.NewDecFromBigIntWithPrec(randInt, sdk.Precision)
|
||||
}
|
||||
|
||||
@ -103,7 +112,9 @@ func RandSubsetCoins(r *rand.Rand, coins sdk.Coins) sdk.Coins {
|
||||
if err != nil {
|
||||
return sdk.Coins{}
|
||||
}
|
||||
|
||||
subset := sdk.Coins{sdk.NewCoin(coin.Denom, amt)}
|
||||
|
||||
for i, c := range coins {
|
||||
// skip denom that we already chose earlier
|
||||
if i == denomIdx {
|
||||
@ -120,8 +131,10 @@ func RandSubsetCoins(r *rand.Rand, coins sdk.Coins) sdk.Coins {
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
subset = append(subset, sdk.NewCoin(c.Denom, amt))
|
||||
}
|
||||
|
||||
return subset.Sort()
|
||||
}
|
||||
|
||||
@ -133,9 +146,11 @@ func RandSubsetCoins(r *rand.Rand, coins sdk.Coins) sdk.Coins {
|
||||
func DeriveRand(r *rand.Rand) *rand.Rand {
|
||||
const num = 8 // TODO what's a good number? Too large is too slow.
|
||||
ms := multiSource(make([]rand.Source, num))
|
||||
|
||||
for i := 0; i < num; i++ {
|
||||
ms[i] = rand.NewSource(r.Int63())
|
||||
}
|
||||
|
||||
return rand.New(ms)
|
||||
}
|
||||
|
||||
@ -145,6 +160,7 @@ func (ms multiSource) Int63() (r int64) {
|
||||
for _, source := range ms {
|
||||
r ^= source.Int63()
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
|
||||
@ -90,6 +90,7 @@ func (om OperationMsg) String() string {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return string(out)
|
||||
}
|
||||
|
||||
@ -99,6 +100,7 @@ func (om OperationMsg) MustMarshal() json.RawMessage {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
@ -108,6 +110,7 @@ func (om OperationMsg) LogEvent(eventLogger func(route, op, evResult string)) {
|
||||
if !om.OK {
|
||||
pass = "failure"
|
||||
}
|
||||
|
||||
eventLogger(om.Route, om.Name, pass)
|
||||
}
|
||||
|
||||
|
||||
@ -592,7 +592,7 @@ func TestAnteHandlerSetPubKey(t *testing.T) {
|
||||
require.Nil(t, acc2.GetPubKey())
|
||||
}
|
||||
|
||||
func generatePubKeysAndSignatures(n int, msg []byte, keyTypeed25519 bool) (pubkeys []crypto.PubKey, signatures [][]byte) {
|
||||
func generatePubKeysAndSignatures(n int, msg []byte, _ bool) (pubkeys []crypto.PubKey, signatures [][]byte) {
|
||||
pubkeys = make([]crypto.PubKey, n)
|
||||
signatures = make([][]byte, n)
|
||||
for i := 0; i < n; i++ {
|
||||
|
||||
@ -30,6 +30,7 @@ func (vbd ValidateBasicDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulat
|
||||
if ctx.IsReCheckTx() {
|
||||
return next(ctx, tx, simulate)
|
||||
}
|
||||
|
||||
if err := tx.ValidateBasic(); err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
@ -100,6 +101,7 @@ func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, sim
|
||||
return ctx, sdkerrors.Wrap(sdkerrors.ErrTxDecode, "invalid tx type")
|
||||
}
|
||||
params := cgts.ak.GetParams(ctx)
|
||||
|
||||
ctx.GasMeter().ConsumeGas(params.TxSizeCostPerByte*sdk.Gas(len(ctx.TxBytes())), "txSize")
|
||||
|
||||
// simulate gas cost for signatures in simulate mode
|
||||
@ -113,6 +115,7 @@ func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, sim
|
||||
}
|
||||
|
||||
var pubkey crypto.PubKey
|
||||
|
||||
acc := cgts.ak.GetAccount(ctx, signer)
|
||||
|
||||
// use placeholder simSecp256k1Pubkey if sig is nil
|
||||
|
||||
@ -175,7 +175,7 @@ func TestSigIntegration(t *testing.T) {
|
||||
require.Equal(t, initialSigCost*uint64(len(privs)), doubleCost-initialCost)
|
||||
}
|
||||
|
||||
func runSigDecorators(t *testing.T, params types.Params, multisig bool, privs ...crypto.PrivKey) (sdk.Gas, error) {
|
||||
func runSigDecorators(t *testing.T, params types.Params, _ bool, privs ...crypto.PrivKey) (sdk.Gas, error) {
|
||||
// setup
|
||||
app, ctx := createTestApp(true)
|
||||
// Make block-height non-zero to include accNum in SignBytes
|
||||
|
||||
@ -30,6 +30,7 @@ func NewBaseAccount(address sdk.AccAddress, pubKey crypto.PubKey, accountNumber,
|
||||
}
|
||||
|
||||
acc.SetPubKey(pubKey)
|
||||
|
||||
return acc
|
||||
}
|
||||
|
||||
@ -219,6 +220,7 @@ func (ma ModuleAccount) Validate() error {
|
||||
if strings.TrimSpace(ma.Name) == "" {
|
||||
return errors.New("module account name cannot be blank")
|
||||
}
|
||||
|
||||
if !ma.Address.Equals(sdk.AccAddress(crypto.AddressHash([]byte(ma.Name)))) {
|
||||
return fmt.Errorf("address %s cannot be derived from the module name '%s'", ma.Address, ma.Name)
|
||||
}
|
||||
|
||||
@ -31,6 +31,7 @@ func DefaultGenesisState() GenesisState {
|
||||
// genesis state.
|
||||
func GetGenesisStateFromAppState(cdc Codec, appState map[string]json.RawMessage) GenesisState {
|
||||
var genesisState GenesisState
|
||||
|
||||
if appState[ModuleName] != nil {
|
||||
cdc.MustUnmarshalJSON(appState[ModuleName], &genesisState)
|
||||
}
|
||||
@ -60,8 +61,8 @@ func SanitizeGenesisAccounts(genAccs exported.GenesisAccounts) exported.GenesisA
|
||||
// ValidateGenAccounts validates an array of GenesisAccounts and checks for duplicates
|
||||
func ValidateGenAccounts(accounts exported.GenesisAccounts) error {
|
||||
addrMap := make(map[string]bool, len(accounts))
|
||||
for _, acc := range accounts {
|
||||
|
||||
for _, acc := range accounts {
|
||||
// check for duplicated accounts
|
||||
addrStr := acc.GetAddress().String()
|
||||
if _, ok := addrMap[addrStr]; ok {
|
||||
@ -87,7 +88,6 @@ type GenesisAccountIterator struct{}
|
||||
func (GenesisAccountIterator) IterateGenesisAccounts(
|
||||
cdc Codec, appGenesis map[string]json.RawMessage, cb func(exported.Account) (stop bool),
|
||||
) {
|
||||
|
||||
for _, genAcc := range GetGenesisStateFromAppState(cdc, appGenesis).Accounts {
|
||||
if cb(genAcc) {
|
||||
break
|
||||
|
||||
@ -35,7 +35,6 @@ var _ paramtypes.ParamSet = &Params{}
|
||||
func NewParams(
|
||||
maxMemoCharacters, txSigLimit, txSizeCostPerByte, sigVerifyCostED25519, sigVerifyCostSecp256k1 uint64,
|
||||
) Params {
|
||||
|
||||
return Params{
|
||||
MaxMemoCharacters: maxMemoCharacters,
|
||||
TxSigLimit: txSigLimit,
|
||||
|
||||
@ -18,6 +18,7 @@ import (
|
||||
func QueryBalancesRequestHandlerFn(ctx context.CLIContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
|
||||
vars := mux.Vars(r)
|
||||
bech32addr := vars["address"]
|
||||
|
||||
@ -85,11 +86,13 @@ func totalSupplyHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
|
||||
|
||||
params := types.NewQueryTotalSupplyParams(page, limit)
|
||||
bz, err := cliCtx.Codec.MarshalJSON(params)
|
||||
|
||||
if rest.CheckBadRequestError(w, err) {
|
||||
return
|
||||
}
|
||||
|
||||
res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryTotalSupply), bz)
|
||||
|
||||
if rest.CheckInternalServerError(w, err) {
|
||||
return
|
||||
}
|
||||
@ -104,12 +107,13 @@ func supplyOfHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
denom := mux.Vars(r)["denom"]
|
||||
cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r)
|
||||
if !ok {
|
||||
if !ok { //nolint:unparam
|
||||
return
|
||||
}
|
||||
|
||||
params := types.NewQuerySupplyOfParams(denom)
|
||||
bz, err := cliCtx.Codec.MarshalJSON(params)
|
||||
|
||||
if rest.CheckBadRequestError(w, err) {
|
||||
return
|
||||
}
|
||||
|
||||
@ -64,10 +64,7 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operatio
|
||||
return simtypes.NoOpMsg(types.ModuleName), nil, nil
|
||||
}
|
||||
|
||||
simAccount, toSimAcc, coins, skip, err := randomSendFields(r, ctx, accs, bk, ak)
|
||||
if err != nil {
|
||||
return simtypes.NoOpMsg(types.ModuleName), nil, err
|
||||
}
|
||||
simAccount, toSimAcc, coins, skip := randomSendFields(r, ctx, accs, bk, ak)
|
||||
|
||||
if skip {
|
||||
return simtypes.NoOpMsg(types.ModuleName), nil, nil
|
||||
@ -75,7 +72,7 @@ func SimulateMsgSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Operatio
|
||||
|
||||
msg := types.NewMsgSend(simAccount.Address, toSimAcc.Address, coins)
|
||||
|
||||
err = sendMsgSend(r, app, bk, ak, msg, ctx, chainID, []crypto.PrivKey{simAccount.PrivKey})
|
||||
err := sendMsgSend(r, app, bk, ak, msg, ctx, chainID, []crypto.PrivKey{simAccount.PrivKey})
|
||||
if err != nil {
|
||||
return simtypes.NoOpMsg(types.ModuleName), nil, err
|
||||
}
|
||||
@ -150,16 +147,13 @@ func SimulateMsgMultiSend(ak types.AccountKeeper, bk keeper.Keeper) simtypes.Ope
|
||||
var totalSentCoins sdk.Coins
|
||||
for i := range inputs {
|
||||
// generate random input fields, ignore to address
|
||||
simAccount, _, coins, skip, err := randomSendFields(r, ctx, accs, bk, ak)
|
||||
simAccount, _, coins, skip := randomSendFields(r, ctx, accs, bk, ak)
|
||||
|
||||
// make sure account is fresh and not used in previous input
|
||||
for usedAddrs[simAccount.Address.String()] {
|
||||
simAccount, _, coins, skip, err = randomSendFields(r, ctx, accs, bk, ak)
|
||||
simAccount, _, coins, skip = randomSendFields(r, ctx, accs, bk, ak)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return simtypes.NoOpMsg(types.ModuleName), nil, err
|
||||
}
|
||||
if skip {
|
||||
return simtypes.NoOpMsg(types.ModuleName), nil, nil
|
||||
}
|
||||
@ -275,7 +269,7 @@ func sendMsgMultiSend(
|
||||
// nolint: interfacer
|
||||
func randomSendFields(
|
||||
r *rand.Rand, ctx sdk.Context, accs []simtypes.Account, bk keeper.Keeper, ak types.AccountKeeper,
|
||||
) (simtypes.Account, simtypes.Account, sdk.Coins, bool, error) {
|
||||
) (simtypes.Account, simtypes.Account, sdk.Coins, bool) {
|
||||
|
||||
simAccount, _ := simtypes.RandomAcc(r, accs)
|
||||
toSimAcc, _ := simtypes.RandomAcc(r, accs)
|
||||
@ -287,15 +281,15 @@ func randomSendFields(
|
||||
|
||||
acc := ak.GetAccount(ctx, simAccount.Address)
|
||||
if acc == nil {
|
||||
return simAccount, toSimAcc, nil, true, nil // skip error
|
||||
return simAccount, toSimAcc, nil, true
|
||||
}
|
||||
|
||||
spendable := bk.SpendableCoins(ctx, acc.GetAddress())
|
||||
|
||||
sendCoins := simtypes.RandSubsetCoins(r, spendable)
|
||||
if sendCoins.Empty() {
|
||||
return simAccount, toSimAcc, nil, true, nil // skip error
|
||||
return simAccount, toSimAcc, nil, true
|
||||
}
|
||||
|
||||
return simAccount, toSimAcc, sendCoins, false, nil
|
||||
return simAccount, toSimAcc, sendCoins, false
|
||||
}
|
||||
|
||||
@ -67,6 +67,7 @@ func DefaultGenesisState() GenesisState {
|
||||
// genesis state.
|
||||
func GetGenesisStateFromAppState(cdc *codec.Codec, appState map[string]json.RawMessage) GenesisState {
|
||||
var genesisState GenesisState
|
||||
|
||||
if appState[ModuleName] != nil {
|
||||
cdc.MustUnmarshalJSON(appState[ModuleName], &genesisState)
|
||||
}
|
||||
|
||||
@ -23,15 +23,19 @@ func (msg MsgSend) ValidateBasic() error {
|
||||
if msg.FromAddress.Empty() {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing sender address")
|
||||
}
|
||||
|
||||
if msg.ToAddress.Empty() {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing recipient address")
|
||||
}
|
||||
|
||||
if !msg.Amount.IsValid() {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String())
|
||||
}
|
||||
|
||||
if !msg.Amount.IsAllPositive() {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, msg.Amount.String())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -65,6 +69,7 @@ func (msg MsgMultiSend) ValidateBasic() error {
|
||||
if len(msg.Inputs) == 0 {
|
||||
return ErrNoInputs
|
||||
}
|
||||
|
||||
if len(msg.Outputs) == 0 {
|
||||
return ErrNoOutputs
|
||||
}
|
||||
@ -83,6 +88,7 @@ func (msg MsgMultiSend) GetSigners() []sdk.AccAddress {
|
||||
for i, in := range msg.Inputs {
|
||||
addrs[i] = in.Address
|
||||
}
|
||||
|
||||
return addrs
|
||||
}
|
||||
|
||||
@ -91,12 +97,15 @@ func (in Input) ValidateBasic() error {
|
||||
if len(in.Address) == 0 {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "input address missing")
|
||||
}
|
||||
|
||||
if !in.Coins.IsValid() {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, in.Coins.String())
|
||||
}
|
||||
|
||||
if !in.Coins.IsAllPositive() {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, in.Coins.String())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -113,12 +122,15 @@ func (out Output) ValidateBasic() error {
|
||||
if len(out.Address) == 0 {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "output address missing")
|
||||
}
|
||||
|
||||
if !out.Coins.IsValid() {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, out.Coins.String())
|
||||
}
|
||||
|
||||
if !out.Coins.IsAllPositive() {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, out.Coins.String())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@ -53,5 +53,6 @@ func (supply Supply) ValidateBasic() error {
|
||||
if !supply.Total.IsValid() {
|
||||
return fmt.Errorf("invalid total supply: %s", supply.Total.String())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -104,10 +104,12 @@ func (k *Keeper) InitializeAndSeal(ctx sdk.Context) {
|
||||
|
||||
// initialize the in-memory store for all persisted capabilities
|
||||
defer iterator.Close()
|
||||
|
||||
for ; iterator.Valid(); iterator.Next() {
|
||||
index := types.IndexFromKey(iterator.Key())
|
||||
|
||||
var capOwners types.CapabilityOwners
|
||||
|
||||
k.cdc.MustUnmarshalBinaryBare(iterator.Value(), &capOwners)
|
||||
k.InitializeCapability(ctx, index, capOwners)
|
||||
}
|
||||
@ -191,7 +193,6 @@ func (sk ScopedKeeper) NewCapability(ctx sdk.Context, name string) (*types.Capab
|
||||
|
||||
if _, ok := sk.GetCapability(ctx, name); ok {
|
||||
return nil, sdkerrors.Wrapf(types.ErrCapabilityTaken, fmt.Sprintf("module: %s, name: %s", sk.module, name))
|
||||
|
||||
}
|
||||
|
||||
// create new capability with the current global index
|
||||
@ -222,6 +223,7 @@ func (sk ScopedKeeper) NewCapability(ctx sdk.Context, name string) (*types.Capab
|
||||
sk.capMap[index] = cap
|
||||
|
||||
logger(ctx).Info("created new capability", "module", sk.module, "name", name)
|
||||
|
||||
return cap, nil
|
||||
}
|
||||
|
||||
@ -261,6 +263,7 @@ func (sk ScopedKeeper) ClaimCapability(ctx sdk.Context, cap *types.Capability, n
|
||||
memStore.Set(types.RevCapabilityKey(sk.module, name), sdk.Uint64ToBigEndian(cap.GetIndex()))
|
||||
|
||||
logger(ctx).Info("claimed capability", "module", sk.module, "name", name, "capability", cap.GetIndex())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -314,6 +317,7 @@ func (sk ScopedKeeper) GetCapability(ctx sdk.Context, name string) (*types.Capab
|
||||
key := types.RevCapabilityKey(sk.module, name)
|
||||
indexBytes := memStore.Get(key)
|
||||
index := sdk.BigEndianToUint64(indexBytes)
|
||||
|
||||
if len(indexBytes) == 0 {
|
||||
// If a tx failed and NewCapability got reverted, it is possible
|
||||
// to still have the capability in the go map since changes to
|
||||
@ -360,8 +364,8 @@ func (sk ScopedKeeper) GetOwners(ctx sdk.Context, name string) (*types.Capabilit
|
||||
}
|
||||
|
||||
sk.cdc.MustUnmarshalBinaryBare(bz, &capOwners)
|
||||
return &capOwners, true
|
||||
|
||||
return &capOwners, true
|
||||
}
|
||||
|
||||
// LookupModules returns all the module owners for a given capability
|
||||
@ -381,8 +385,8 @@ func (sk ScopedKeeper) LookupModules(ctx sdk.Context, name string) ([]string, *t
|
||||
for i, co := range capOwners.Owners {
|
||||
mods[i] = co.Module
|
||||
}
|
||||
return mods, cap, true
|
||||
|
||||
return mods, cap, true
|
||||
}
|
||||
|
||||
func (sk ScopedKeeper) addOwner(ctx sdk.Context, cap *types.Capability, name string) error {
|
||||
@ -397,6 +401,7 @@ func (sk ScopedKeeper) addOwner(ctx sdk.Context, cap *types.Capability, name str
|
||||
|
||||
// update capability owner set
|
||||
prefixStore.Set(indexKey, sk.cdc.MustMarshalBinaryBare(capOwners))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@ -116,6 +116,7 @@ func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, gs jso
|
||||
cdc.MustUnmarshalJSON(gs, &genState)
|
||||
|
||||
InitGenesis(ctx, am.keeper, genState)
|
||||
|
||||
return []abci.ValidatorUpdate{}
|
||||
}
|
||||
|
||||
|
||||
@ -43,6 +43,7 @@ func handleMsgVerifyInvariant(ctx sdk.Context, msg types.MsgVerifyInvariant, k k
|
||||
if invarRoute.FullRoute() == msgFullRoute {
|
||||
res, stop = invarRoute.Invar(cacheCtx)
|
||||
found = true
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@ -43,11 +43,10 @@ func (h Hooks) AfterValidatorRemoved(ctx sdk.Context, _ sdk.ConsAddress, valAddr
|
||||
|
||||
// add to validator account
|
||||
if !coins.IsZero() {
|
||||
|
||||
accAddr := sdk.AccAddress(valAddr)
|
||||
withdrawAddr := h.k.GetDelegatorWithdrawAddr(ctx, accAddr)
|
||||
err := h.k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, withdrawAddr, coins)
|
||||
if err != nil {
|
||||
|
||||
if err := h.k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, withdrawAddr, coins); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@ -84,6 +83,7 @@ func (h Hooks) BeforeDelegationCreated(ctx sdk.Context, delAddr sdk.AccAddress,
|
||||
func (h Hooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) {
|
||||
val := h.k.stakingKeeper.Validator(ctx, valAddr)
|
||||
del := h.k.stakingKeeper.Delegation(ctx, delAddr, valAddr)
|
||||
|
||||
if _, err := h.k.withdrawDelegationRewards(ctx, val, del); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
@ -99,7 +99,6 @@ func (h Hooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, f
|
||||
h.k.updateValidatorSlashFraction(ctx, valAddr, fraction)
|
||||
}
|
||||
|
||||
// nolint - unused hooks
|
||||
func (h Hooks) BeforeValidatorModified(_ sdk.Context, _ sdk.ValAddress) {}
|
||||
func (h Hooks) AfterValidatorBonded(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) {}
|
||||
func (h Hooks) AfterValidatorBeginUnbonding(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) {}
|
||||
|
||||
@ -48,7 +48,7 @@ func NewQuerier(k Keeper) sdk.Querier {
|
||||
}
|
||||
}
|
||||
|
||||
func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, error) {
|
||||
func queryParams(ctx sdk.Context, _ []string, _ abci.RequestQuery, k Keeper) ([]byte, error) {
|
||||
params := k.GetParams(ctx)
|
||||
|
||||
res, err := codec.MarshalJSONIndent(k.cdc, params)
|
||||
@ -59,7 +59,7 @@ func queryParams(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func queryValidatorOutstandingRewards(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, error) {
|
||||
func queryValidatorOutstandingRewards(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper) ([]byte, error) {
|
||||
var params types.QueryValidatorOutstandingRewardsParams
|
||||
err := k.cdc.UnmarshalJSON(req.Data, ¶ms)
|
||||
if err != nil {
|
||||
@ -79,7 +79,7 @@ func queryValidatorOutstandingRewards(ctx sdk.Context, path []string, req abci.R
|
||||
return bz, nil
|
||||
}
|
||||
|
||||
func queryValidatorCommission(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, error) {
|
||||
func queryValidatorCommission(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper) ([]byte, error) {
|
||||
var params types.QueryValidatorCommissionParams
|
||||
err := k.cdc.UnmarshalJSON(req.Data, ¶ms)
|
||||
if err != nil {
|
||||
@ -99,7 +99,7 @@ func queryValidatorCommission(ctx sdk.Context, path []string, req abci.RequestQu
|
||||
return bz, nil
|
||||
}
|
||||
|
||||
func queryValidatorSlashes(ctx sdk.Context, path []string, req abci.RequestQuery, k Keeper) ([]byte, error) {
|
||||
func queryValidatorSlashes(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper) ([]byte, error) {
|
||||
var params types.QueryValidatorSlashesParams
|
||||
err := k.cdc.UnmarshalJSON(req.Data, ¶ms)
|
||||
if err != nil {
|
||||
@ -167,6 +167,7 @@ func queryDelegatorTotalRewards(ctx sdk.Context, _ []string, req abci.RequestQue
|
||||
ctx, _ = ctx.CacheContext()
|
||||
|
||||
total := sdk.DecCoins{}
|
||||
|
||||
var delRewards []types.DelegationDelegatorReward
|
||||
|
||||
k.stakingKeeper.IterateDelegations(
|
||||
@ -240,7 +241,7 @@ func queryDelegatorWithdrawAddress(ctx sdk.Context, _ []string, req abci.Request
|
||||
return bz, nil
|
||||
}
|
||||
|
||||
func queryCommunityPool(ctx sdk.Context, _ []string, req abci.RequestQuery, k Keeper) ([]byte, error) {
|
||||
func queryCommunityPool(ctx sdk.Context, _ []string, _ abci.RequestQuery, k Keeper) ([]byte, error) {
|
||||
pool := k.GetFeePoolCommunityCoins(ctx)
|
||||
if pool == nil {
|
||||
pool = sdk.DecCoins{}
|
||||
|
||||
@ -20,9 +20,7 @@ import (
|
||||
const flagGenTxDir = "gentx-dir"
|
||||
|
||||
// CollectGenTxsCmd - return the cobra command to collect genesis transactions
|
||||
func CollectGenTxsCmd(ctx *server.Context, cdc *codec.Codec,
|
||||
genBalIterator types.GenesisBalancesIterator, defaultNodeHome string) *cobra.Command {
|
||||
|
||||
func CollectGenTxsCmd(ctx *server.Context, cdc *codec.Codec, genBalIterator types.GenesisBalancesIterator, defaultNodeHome string) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "collect-gentxs",
|
||||
Short: "Collect genesis txs and output a genesis.json file",
|
||||
@ -64,6 +62,7 @@ func CollectGenTxsCmd(ctx *server.Context, cdc *codec.Codec,
|
||||
cmd.Flags().String(flagGenTxDir, "",
|
||||
"override default \"gentx\" directory from which collect and execute "+
|
||||
"genesis transactions; default [--home]/config/gentx/")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@ -43,7 +43,6 @@ type StakingMsgBuildingHelpers interface {
|
||||
// nolint: errcheck
|
||||
func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, smbh StakingMsgBuildingHelpers,
|
||||
genBalIterator types.GenesisBalancesIterator, defaultNodeHome, defaultCLIHome string) *cobra.Command {
|
||||
|
||||
ipDefault, _ := server.ExternalIP()
|
||||
fsCreateValidator, flagNodeID, flagPubKey, flagAmount, defaultsDesc := smbh.CreateValidatorMsgHelpers(ipDefault)
|
||||
|
||||
@ -191,6 +190,7 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm
|
||||
viper.BindPFlag(flags.FlagKeyringBackend, cmd.Flags().Lookup(flags.FlagKeyringBackend))
|
||||
|
||||
cmd.MarkFlagRequired(flags.FlagName)
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@ -199,16 +199,20 @@ func makeOutputFilepath(rootDir, nodeID string) (string, error) {
|
||||
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 {
|
||||
if err != nil { // nolint:unparam
|
||||
return stdTx, err
|
||||
}
|
||||
|
||||
err = cdc.UnmarshalJSON(bytes, &stdTx)
|
||||
|
||||
return stdTx, err
|
||||
}
|
||||
|
||||
@ -218,11 +222,14 @@ func writeSignedGenTx(cdc *codec.Codec, outputDocument string, tx auth.StdTx) er
|
||||
return err
|
||||
}
|
||||
defer outputFile.Close()
|
||||
|
||||
json, err := cdc.MarshalJSON(tx)
|
||||
if err != nil {
|
||||
if err != nil { //nolint:unparam
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = fmt.Fprintf(outputFile, "%s\n", json)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@ -36,9 +36,7 @@ type printInfo struct {
|
||||
AppMessage json.RawMessage `json:"app_message" yaml:"app_message"`
|
||||
}
|
||||
|
||||
func newPrintInfo(moniker, chainID, nodeID, genTxsDir string,
|
||||
appMessage json.RawMessage) printInfo {
|
||||
|
||||
func newPrintInfo(moniker, chainID, nodeID, genTxsDir string, appMessage json.RawMessage) printInfo {
|
||||
return printInfo{
|
||||
Moniker: moniker,
|
||||
ChainID: chainID,
|
||||
@ -55,13 +53,13 @@ func displayInfo(cdc codec.JSONMarshaler, info printInfo) error {
|
||||
}
|
||||
|
||||
_, err = fmt.Fprintf(os.Stderr, "%s\n", string(sdk.MustSortJSON(out)))
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// InitCmd returns a command that initializes all files needed for Tendermint
|
||||
// and the respective application.
|
||||
func InitCmd(ctx *server.Context, cdc codec.JSONMarshaler, mbm module.BasicManager,
|
||||
defaultNodeHome string) *cobra.Command { // nolint: golint
|
||||
func InitCmd(ctx *server.Context, cdc codec.JSONMarshaler, mbm module.BasicManager, defaultNodeHome string) *cobra.Command { // nolint: golint
|
||||
cmd := &cobra.Command{
|
||||
Use: "init [moniker]",
|
||||
Short: "Initialize private validator, p2p, genesis, and application configuration files",
|
||||
|
||||
@ -43,12 +43,14 @@ func GetMigrationVersions() []string {
|
||||
versions := make([]string, len(migrationMap))
|
||||
|
||||
var i int
|
||||
|
||||
for version := range migrationMap {
|
||||
versions[i] = version
|
||||
i++
|
||||
}
|
||||
|
||||
sort.Strings(versions)
|
||||
|
||||
return versions
|
||||
}
|
||||
|
||||
|
||||
@ -74,7 +74,7 @@ func CollectStdTxs(cdc *codec.Codec, moniker, genTxsDir string,
|
||||
|
||||
var fos []os.FileInfo
|
||||
fos, err = ioutil.ReadDir(genTxsDir)
|
||||
if err != nil {
|
||||
if err != nil { //nolint:unparam
|
||||
return appGenTxs, persistentPeers, err
|
||||
}
|
||||
|
||||
@ -86,6 +86,7 @@ func CollectStdTxs(cdc *codec.Codec, moniker, genTxsDir string,
|
||||
}
|
||||
|
||||
balancesMap := make(map[string]bankexported.GenesisBalance)
|
||||
|
||||
genBalIterator.IterateGenesisBalances(
|
||||
cdc, appState,
|
||||
func(balance bankexported.GenesisBalance) (stop bool) {
|
||||
@ -105,6 +106,7 @@ func CollectStdTxs(cdc *codec.Codec, moniker, genTxsDir string,
|
||||
|
||||
// get the genStdTx
|
||||
var jsonRawTx []byte
|
||||
|
||||
if jsonRawTx, err = ioutil.ReadFile(filename); err != nil {
|
||||
return appGenTxs, persistentPeers, err
|
||||
}
|
||||
|
||||
@ -12,11 +12,12 @@ import (
|
||||
func (keeper Keeper) GetDeposit(ctx sdk.Context, proposalID uint64, depositorAddr sdk.AccAddress) (deposit types.Deposit, found bool) {
|
||||
store := ctx.KVStore(keeper.storeKey)
|
||||
bz := store.Get(types.DepositKey(proposalID, depositorAddr))
|
||||
if bz == nil {
|
||||
if bz == nil { //nolint:unparam
|
||||
return deposit, false
|
||||
}
|
||||
|
||||
keeper.cdc.MustUnmarshalBinaryBare(bz, &deposit)
|
||||
|
||||
return deposit, true
|
||||
}
|
||||
|
||||
@ -33,6 +34,7 @@ func (keeper Keeper) GetAllDeposits(ctx sdk.Context) (deposits types.Deposits) {
|
||||
deposits = append(deposits, deposit)
|
||||
return false
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@ -42,6 +44,7 @@ func (keeper Keeper) GetDeposits(ctx sdk.Context, proposalID uint64) (deposits t
|
||||
deposits = append(deposits, deposit)
|
||||
return false
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@ -66,8 +69,10 @@ func (keeper Keeper) IterateAllDeposits(ctx sdk.Context, cb func(deposit types.D
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.DepositsKeyPrefix)
|
||||
|
||||
defer iterator.Close()
|
||||
|
||||
for ; iterator.Valid(); iterator.Next() {
|
||||
var deposit types.Deposit
|
||||
|
||||
keeper.cdc.MustUnmarshalBinaryBare(iterator.Value(), &deposit)
|
||||
|
||||
if cb(deposit) {
|
||||
@ -82,8 +87,10 @@ func (keeper Keeper) IterateDeposits(ctx sdk.Context, proposalID uint64, cb func
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.DepositsKey(proposalID))
|
||||
|
||||
defer iterator.Close()
|
||||
|
||||
for ; iterator.Valid(); iterator.Next() {
|
||||
var deposit types.Deposit
|
||||
|
||||
keeper.cdc.MustUnmarshalBinaryBare(iterator.Value(), &deposit)
|
||||
|
||||
if cb(deposit) {
|
||||
@ -118,13 +125,16 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID uint64, depositorAdd
|
||||
|
||||
// Check if deposit has provided sufficient total funds to transition the proposal into the voting period
|
||||
activatedVotingPeriod := false
|
||||
|
||||
if proposal.Status == types.StatusDepositPeriod && proposal.TotalDeposit.IsAllGTE(keeper.GetDepositParams(ctx).MinDeposit) {
|
||||
keeper.ActivateVotingPeriod(ctx, proposal)
|
||||
|
||||
activatedVotingPeriod = true
|
||||
}
|
||||
|
||||
// Add or update deposit object
|
||||
deposit, found := keeper.GetDeposit(ctx, proposalID, depositorAddr)
|
||||
|
||||
if found {
|
||||
deposit.Amount = deposit.Amount.Add(depositAmount...)
|
||||
} else {
|
||||
@ -140,6 +150,7 @@ func (keeper Keeper) AddDeposit(ctx sdk.Context, proposalID uint64, depositorAdd
|
||||
)
|
||||
|
||||
keeper.SetDeposit(ctx, deposit)
|
||||
|
||||
return activatedVotingPeriod, nil
|
||||
}
|
||||
|
||||
|
||||
@ -16,7 +16,9 @@ import (
|
||||
// HandleMsgCreateClient defines the sdk.Handler for MsgCreateClient
|
||||
func HandleMsgCreateClient(ctx sdk.Context, k Keeper, msg exported.MsgCreateClient) (*sdk.Result, error) {
|
||||
clientType := exported.ClientTypeFromString(msg.GetClientType())
|
||||
|
||||
var clientState exported.ClientState
|
||||
|
||||
switch clientType {
|
||||
case 0:
|
||||
return nil, sdkerrors.Wrap(ErrInvalidClientType, msg.GetClientType())
|
||||
@ -26,6 +28,7 @@ func HandleMsgCreateClient(ctx sdk.Context, k Keeper, msg exported.MsgCreateClie
|
||||
return nil, sdkerrors.Wrap(ErrInvalidClientType, "Msg is not a Tendermint CreateClient msg")
|
||||
}
|
||||
var err error
|
||||
|
||||
clientState, err = ibctmtypes.InitializeFromMsg(tmMsg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -50,6 +53,7 @@ func HandleMsgCreateClient(ctx sdk.Context, k Keeper, msg exported.MsgCreateClie
|
||||
|
||||
attributes := make([]sdk.Attribute, len(msg.GetSigners())+1)
|
||||
attributes[0] = sdk.NewAttribute(sdk.AttributeKeyModule, AttributeValueCategory)
|
||||
|
||||
for i, signer := range msg.GetSigners() {
|
||||
attributes[i+1] = sdk.NewAttribute(sdk.AttributeKeySender, signer.String())
|
||||
}
|
||||
@ -80,6 +84,7 @@ func HandleMsgUpdateClient(ctx sdk.Context, k Keeper, msg exported.MsgUpdateClie
|
||||
|
||||
attributes := make([]sdk.Attribute, len(msg.GetSigners())+1)
|
||||
attributes[0] = sdk.NewAttribute(sdk.AttributeKeyModule, AttributeValueCategory)
|
||||
|
||||
for i, signer := range msg.GetSigners() {
|
||||
attributes[i+1] = sdk.NewAttribute(sdk.AttributeKeySender, signer.String())
|
||||
}
|
||||
|
||||
@ -20,6 +20,7 @@ func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command {
|
||||
GetCmdQueryConnections(queryRoute, cdc),
|
||||
GetCmdQueryConnection(queryRoute, cdc),
|
||||
)...)
|
||||
|
||||
return ics03ConnectionQueryCmd
|
||||
}
|
||||
|
||||
|
||||
@ -44,6 +44,7 @@ $ %s query ibc connection connections
|
||||
}
|
||||
cmd.Flags().Int(flags.FlagPage, 1, "pagination page of light clients to to query for")
|
||||
cmd.Flags().Int(flags.FlagLimit, 100, "pagination limit of light clients to query for")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@ -71,6 +71,7 @@ $ %s tx ibc connection open-init [connection-id] [client-id] \
|
||||
return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
|
||||
},
|
||||
}
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@ -136,6 +137,7 @@ $ %s tx ibc connection open-try connection-id] [client-id] \
|
||||
return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
|
||||
},
|
||||
}
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@ -185,6 +187,7 @@ $ %s tx ibc connection open-ack [connection-id] [path/to/proof_try.json] [versio
|
||||
return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
|
||||
},
|
||||
}
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@ -232,6 +235,7 @@ $ %s tx ibc connection open-confirm [connection-id] [path/to/proof_ack.json]
|
||||
return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
|
||||
},
|
||||
}
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@ -28,7 +28,7 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute st
|
||||
// @Failure 400 {object} rest.ErrorResponse "Invalid connection id"
|
||||
// @Failure 500 {object} rest.ErrorResponse "Internal Server Error"
|
||||
// @Router /ibc/connections/{connection-id} [get]
|
||||
func queryConnectionHandlerFn(cliCtx context.CLIContext, queryRoute string) http.HandlerFunc {
|
||||
func queryConnectionHandlerFn(cliCtx context.CLIContext, _ string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
connectionID := vars[RestConnectionID]
|
||||
@ -61,7 +61,7 @@ func queryConnectionHandlerFn(cliCtx context.CLIContext, queryRoute string) http
|
||||
// @Failure 400 {object} rest.ErrorResponse "Invalid client id"
|
||||
// @Failure 500 {object} rest.ErrorResponse "Internal Server Error"
|
||||
// @Router /ibc/clients/{client-id}/connections [get]
|
||||
func queryClientConnectionsHandlerFn(cliCtx context.CLIContext, queryRoute string) http.HandlerFunc {
|
||||
func queryClientConnectionsHandlerFn(cliCtx context.CLIContext, _ string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
clientID := vars[RestClientID]
|
||||
|
||||
@ -28,7 +28,7 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router, queryRoute st
|
||||
// @Failure 400 {object} rest.ErrorResponse "Invalid port id or channel id"
|
||||
// @Failure 500 {object} rest.ErrorResponse "Internal Server Error"
|
||||
// @Router /ibc/ports/{port-id}/channels/{channel-id} [get]
|
||||
func queryChannelHandlerFn(cliCtx context.CLIContext, queryRoute string) http.HandlerFunc {
|
||||
func queryChannelHandlerFn(cliCtx context.CLIContext, _ string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
portID := vars[RestPortID]
|
||||
|
||||
@ -261,8 +261,9 @@ func (k Keeper) LookupModuleByChannel(ctx sdk.Context, portID, channelID string)
|
||||
}
|
||||
|
||||
// common functionality for IteratePacketCommitment and IteratePacketAcknowledgemen
|
||||
func (k Keeper) iterateHashes(ctx sdk.Context, iterator db.Iterator, cb func(portID, channelID string, sequence uint64, hash []byte) bool) {
|
||||
func (k Keeper) iterateHashes(_ sdk.Context, iterator db.Iterator, cb func(portID, channelID string, sequence uint64, hash []byte) bool) {
|
||||
defer iterator.Close()
|
||||
|
||||
for ; iterator.Valid(); iterator.Next() {
|
||||
keySplit := strings.Split(string(iterator.Key()), "/")
|
||||
portID := keySplit[2]
|
||||
|
||||
@ -80,6 +80,7 @@ $ %s tx ibc client create [client-id] [path/to/consensus_state.json] [trusting_p
|
||||
return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
|
||||
},
|
||||
}
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@ -123,6 +124,7 @@ $ %s tx ibc client update [client-id] [path/to/header.json] --from node0 --home
|
||||
return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
|
||||
},
|
||||
}
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@ -165,5 +167,6 @@ $ %s tx ibc client misbehaviour [path/to/evidence.json] --from node0 --home ../n
|
||||
return authclient.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg})
|
||||
},
|
||||
}
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
@ -16,7 +16,7 @@ import (
|
||||
// ValidateFn function type to validate path and identifier bytestrings
|
||||
type ValidateFn func(string) error
|
||||
|
||||
func defaultIdentifierValidator(id string, min, max int) error {
|
||||
func defaultIdentifierValidator(id string, min, max int) error { //nolint:unparam
|
||||
// valid id MUST NOT contain "/" separator
|
||||
if strings.Contains(id, "/") {
|
||||
return sdkerrors.Wrapf(ErrInvalidID, "identifier %s cannot contain separator '/'", id)
|
||||
|
||||
@ -177,9 +177,11 @@ func MustParseChannelPath(path string) (string, string) {
|
||||
if len(split) != 5 {
|
||||
panic("cannot parse channel path")
|
||||
}
|
||||
|
||||
if split[1] != "ports" || split[3] != "channels" {
|
||||
panic("cannot parse channel path")
|
||||
}
|
||||
|
||||
return split[2], split[4]
|
||||
}
|
||||
|
||||
|
||||
@ -36,6 +36,7 @@ func (proof ValidProof) VerifyMembership(
|
||||
bytes.Equal(value, proof.value) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New("invalid proof")
|
||||
}
|
||||
|
||||
|
||||
@ -27,7 +27,6 @@ func NewKeeper(
|
||||
sk types.StakingKeeper, ak types.AccountKeeper, bk types.BankKeeper,
|
||||
feeCollectorName string,
|
||||
) Keeper {
|
||||
|
||||
// ensure mint module account is set
|
||||
if addr := ak.GetModuleAddress(types.ModuleName); addr == nil {
|
||||
panic("the mint module account has not been set")
|
||||
@ -59,7 +58,7 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger {
|
||||
func (k Keeper) GetMinter(ctx sdk.Context) (minter types.Minter) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
b := store.Get(types.MinterKey)
|
||||
if b == nil {
|
||||
if b == nil { //nolint:unparam
|
||||
panic("stored minter should not have been nil")
|
||||
}
|
||||
|
||||
|
||||
@ -18,6 +18,7 @@ func NewLogWriter(testingmode bool) LogWriter {
|
||||
if !testingmode {
|
||||
return &DummyLogWriter{}
|
||||
}
|
||||
|
||||
return &StandardLogWriter{}
|
||||
}
|
||||
|
||||
@ -34,9 +35,11 @@ func (lw *StandardLogWriter) AddEntry(opEntry OperationEntry) {
|
||||
// PrintLogs - print the logs to a simulation file
|
||||
func (lw *StandardLogWriter) PrintLogs() {
|
||||
f := createLogFile()
|
||||
|
||||
for i := 0; i < len(lw.OpEntries); i++ {
|
||||
writeEntry := fmt.Sprintf("%s\n", (lw.OpEntries[i]).MustMarshal())
|
||||
_, err := f.WriteString(writeEntry)
|
||||
|
||||
if err != nil {
|
||||
panic("Failed to write logs to file")
|
||||
}
|
||||
@ -45,8 +48,8 @@ func (lw *StandardLogWriter) PrintLogs() {
|
||||
|
||||
func createLogFile() *os.File {
|
||||
var f *os.File
|
||||
fileName := fmt.Sprintf("%s.log", time.Now().Format("2006-01-02_15:04:05"))
|
||||
|
||||
fileName := fmt.Sprintf("%s.log", time.Now().Format("2006-01-02_15:04:05"))
|
||||
folderPath := os.ExpandEnv("$HOME/.simapp/simulations")
|
||||
filePath := path.Join(folderPath, fileName)
|
||||
|
||||
@ -54,8 +57,10 @@ func createLogFile() *os.File {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
f, _ = os.Create(filePath)
|
||||
fmt.Printf("Logs to writing to %s\n", filePath)
|
||||
|
||||
return f
|
||||
}
|
||||
|
||||
|
||||
@ -28,10 +28,9 @@ func (mv mockValidator) String() string {
|
||||
type mockValidators map[string]mockValidator
|
||||
|
||||
// get mockValidators from abci validators
|
||||
func newMockValidators(r *rand.Rand, abciVals []abci.ValidatorUpdate,
|
||||
params Params) mockValidators {
|
||||
|
||||
func newMockValidators(r *rand.Rand, abciVals []abci.ValidatorUpdate, params Params) mockValidators {
|
||||
validators := make(mockValidators)
|
||||
|
||||
for _, validator := range abciVals {
|
||||
str := fmt.Sprintf("%v", validator.PubKey)
|
||||
liveliness := GetMemberOfInitialState(r,
|
||||
@ -50,11 +49,14 @@ func newMockValidators(r *rand.Rand, abciVals []abci.ValidatorUpdate,
|
||||
func (vals mockValidators) getKeys() []string {
|
||||
keys := make([]string, len(vals))
|
||||
i := 0
|
||||
|
||||
for key := range vals {
|
||||
keys[i] = key
|
||||
i++
|
||||
}
|
||||
|
||||
sort.Strings(keys)
|
||||
|
||||
return keys
|
||||
}
|
||||
|
||||
@ -66,12 +68,15 @@ func (vals mockValidators) randomProposer(r *rand.Rand) tmbytes.HexBytes {
|
||||
if len(keys) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
key := keys[r.Intn(len(keys))]
|
||||
|
||||
proposer := vals[key].val
|
||||
pk, err := tmtypes.PB2TM.PubKey(proposer.PubKey)
|
||||
if err != nil {
|
||||
if err != nil { //nolint:wsl
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return pk.Address()
|
||||
}
|
||||
|
||||
@ -79,8 +84,8 @@ func (vals mockValidators) randomProposer(r *rand.Rand) tmbytes.HexBytes {
|
||||
// nolint: unparam
|
||||
func updateValidators(tb testing.TB, r *rand.Rand, params Params,
|
||||
current map[string]mockValidator, updates []abci.ValidatorUpdate,
|
||||
event func(route, op, evResult string)) map[string]mockValidator {
|
||||
|
||||
event func(route, op, evResult string)) map[string]mockValidator {
|
||||
for _, update := range updates {
|
||||
str := fmt.Sprintf("%v", update.PubKey)
|
||||
|
||||
@ -88,9 +93,9 @@ func updateValidators(tb testing.TB, r *rand.Rand, params Params,
|
||||
if _, ok := current[str]; !ok {
|
||||
tb.Fatalf("tried to delete a nonexistent validator")
|
||||
}
|
||||
|
||||
event("end_block", "validator_updates", "kicked")
|
||||
delete(current, str)
|
||||
|
||||
} else if mVal, ok := current[str]; ok {
|
||||
// validator already exists
|
||||
mVal.val = update
|
||||
@ -115,7 +120,6 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params,
|
||||
validators mockValidators, pastTimes []time.Time,
|
||||
pastVoteInfos [][]abci.VoteInfo,
|
||||
event func(route, op, evResult string), header abci.Header) abci.RequestBeginBlock {
|
||||
|
||||
if len(validators) == 0 {
|
||||
return abci.RequestBeginBlock{
|
||||
Header: header,
|
||||
@ -123,6 +127,7 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params,
|
||||
}
|
||||
|
||||
voteInfos := make([]abci.VoteInfo, len(validators))
|
||||
|
||||
for i, key := range validators.getKeys() {
|
||||
mVal := validators[key]
|
||||
mVal.livenessState = params.LivenessTransitionMatrix().NextState(r, mVal.livenessState)
|
||||
@ -148,6 +153,7 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params,
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
voteInfos[i] = abci.VoteInfo{
|
||||
Validator: abci.Validator{
|
||||
Address: pubkey.Address(),
|
||||
@ -169,8 +175,8 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params,
|
||||
|
||||
// TODO: Determine capacity before allocation
|
||||
evidence := make([]abci.Evidence, 0)
|
||||
for r.Float64() < params.EvidenceFraction() {
|
||||
|
||||
for r.Float64() < params.EvidenceFraction() {
|
||||
height := header.Height
|
||||
time := header.Time
|
||||
vals := voteInfos
|
||||
@ -181,6 +187,7 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params,
|
||||
time = pastTimes[height-1]
|
||||
vals = pastVoteInfos[height-1]
|
||||
}
|
||||
|
||||
validator := vals[r.Intn(len(vals))].Validator
|
||||
|
||||
var totalVotingPower int64
|
||||
@ -197,6 +204,7 @@ func RandomRequestBeginBlock(r *rand.Rand, params Params,
|
||||
TotalVotingPower: totalVotingPower,
|
||||
},
|
||||
)
|
||||
|
||||
event("begin_block", "evidence", "ok")
|
||||
}
|
||||
|
||||
|
||||
@ -60,6 +60,7 @@ func (oe OperationEntry) MustMarshal() json.RawMessage {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
@ -74,9 +75,7 @@ func NewOperationQueue() OperationQueue {
|
||||
}
|
||||
|
||||
// queueOperations adds all future operations into the operation queue.
|
||||
func queueOperations(queuedOps OperationQueue,
|
||||
queuedTimeOps []simulation.FutureOperation, futureOps []simulation.FutureOperation) {
|
||||
|
||||
func queueOperations(queuedOps OperationQueue, queuedTimeOps []simulation.FutureOperation, futureOps []simulation.FutureOperation) {
|
||||
if futureOps == nil {
|
||||
return
|
||||
}
|
||||
@ -89,6 +88,7 @@ func queueOperations(queuedOps OperationQueue,
|
||||
} else {
|
||||
queuedOps[futureOp.BlockHeight] = []simulation.Operation{futureOp.Op}
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
@ -100,6 +100,7 @@ func queueOperations(queuedOps OperationQueue,
|
||||
return queuedTimeOps[i].BlockTime.After(futureOp.BlockTime)
|
||||
},
|
||||
)
|
||||
|
||||
queuedTimeOps = append(queuedTimeOps, simulation.FutureOperation{})
|
||||
copy(queuedTimeOps[index+1:], queuedTimeOps[index:])
|
||||
queuedTimeOps[index] = futureOp
|
||||
@ -139,17 +140,20 @@ func (ops WeightedOperations) totalWeight() int {
|
||||
for _, op := range ops {
|
||||
totalOpWeight += op.Weight()
|
||||
}
|
||||
|
||||
return totalOpWeight
|
||||
}
|
||||
|
||||
func (ops WeightedOperations) getSelectOpFn() simulation.SelectOpFn {
|
||||
totalOpWeight := ops.totalWeight()
|
||||
|
||||
return func(r *rand.Rand) simulation.Operation {
|
||||
x := r.Intn(totalOpWeight)
|
||||
for i := 0; i < len(ops); i++ {
|
||||
if x <= ops[i].Weight() {
|
||||
return ops[i].Op()
|
||||
}
|
||||
|
||||
x -= ops[i].Weight()
|
||||
}
|
||||
// shouldn't happen
|
||||
|
||||
@ -159,6 +159,7 @@ func RandomConsensusParams(r *rand.Rand, appState json.RawMessage) *abci.Consens
|
||||
cdc := amino.NewCodec()
|
||||
|
||||
var genesisState map[string]json.RawMessage
|
||||
|
||||
cdc.UnmarshalJSON(appState, &genesisState)
|
||||
|
||||
stakingGenesisState := stakingtypes.GetGenesisStateFromAppState(cdc, genesisState)
|
||||
|
||||
@ -24,7 +24,6 @@ func initChain(
|
||||
r *rand.Rand, params Params, accounts []simulation.Account, app *baseapp.BaseApp,
|
||||
appStateFn simulation.AppStateFn, config simulation.Config,
|
||||
) (mockValidators, time.Time, []simulation.Account, string) {
|
||||
|
||||
appState, accounts, chainID, genesisTimestamp := appStateFn(r, accounts, config)
|
||||
|
||||
consensusParams := RandomConsensusParams(r, appState)
|
||||
@ -48,11 +47,10 @@ func SimulateFromSeed(
|
||||
appStateFn simulation.AppStateFn, ops WeightedOperations,
|
||||
blackListedAccs map[string]bool, config simulation.Config,
|
||||
) (stopEarly bool, exportedParams Params, err error) {
|
||||
|
||||
// in case we have to end early, don't os.Exit so that we can run cleanup code.
|
||||
testingMode, t, b := getTestingMode(tb)
|
||||
fmt.Fprintf(w, "Starting SimulateFromSeed with randomness created with seed %d\n", int(config.Seed))
|
||||
testingMode, _, b := getTestingMode(tb)
|
||||
|
||||
fmt.Fprintf(w, "Starting SimulateFromSeed with randomness created with seed %d\n", int(config.Seed))
|
||||
r := rand.New(rand.NewSource(config.Seed))
|
||||
params := RandomParams(r)
|
||||
fmt.Fprintf(w, "Randomized simulation params: \n%s\n", mustMarshalJSONIndent(params))
|
||||
@ -77,6 +75,7 @@ func SimulateFromSeed(
|
||||
|
||||
// remove module account address if they exist in accs
|
||||
var tmpAccs []simulation.Account
|
||||
|
||||
for _, acc := range accs {
|
||||
if !blackListedAccs[acc.Address.String()] {
|
||||
tmpAccs = append(tmpAccs, acc)
|
||||
@ -98,6 +97,7 @@ func SimulateFromSeed(
|
||||
// Setup code to catch SIGTERM's
|
||||
c := make(chan os.Signal)
|
||||
signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
|
||||
|
||||
go func() {
|
||||
receivedSignal := <-c
|
||||
fmt.Fprintf(w, "\nExiting early due to %s, on block %d, operation %d\n", receivedSignal, header.Height, opCount)
|
||||
@ -105,20 +105,23 @@ func SimulateFromSeed(
|
||||
stopEarly = true
|
||||
}()
|
||||
|
||||
var pastTimes []time.Time
|
||||
var pastVoteInfos [][]abci.VoteInfo
|
||||
var (
|
||||
pastTimes []time.Time
|
||||
pastVoteInfos [][]abci.VoteInfo
|
||||
)
|
||||
|
||||
request := RandomRequestBeginBlock(r, params,
|
||||
validators, pastTimes, pastVoteInfos, eventStats.Tally, header)
|
||||
|
||||
// These are operations which have been queued by previous operations
|
||||
operationQueue := NewOperationQueue()
|
||||
|
||||
var timeOperationQueue []simulation.FutureOperation
|
||||
|
||||
logWriter := NewLogWriter(testingMode)
|
||||
|
||||
blockSimulator := createBlockSimulator(
|
||||
testingMode, tb, t, w, params, eventStats.Tally,
|
||||
testingMode, tb, w, params, eventStats.Tally,
|
||||
ops, operationQueue, timeOperationQueue, logWriter, config)
|
||||
|
||||
if !testingMode {
|
||||
@ -175,6 +178,7 @@ func SimulateFromSeed(
|
||||
header.Time = header.Time.Add(
|
||||
time.Duration(int64(r.Intn(int(timeDiff)))) * time.Second)
|
||||
header.ProposerAddress = validators.randomProposer(r)
|
||||
|
||||
logWriter.AddEntry(EndBlockEntry(int64(height)))
|
||||
|
||||
if config.Commit {
|
||||
@ -183,7 +187,9 @@ func SimulateFromSeed(
|
||||
|
||||
if header.ProposerAddress == nil {
|
||||
fmt.Fprintf(w, "\nSimulation stopped early as all validators have been unbonded; nobody left to propose a block!\n")
|
||||
|
||||
stopEarly = true
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
@ -238,7 +244,7 @@ type blockSimFn func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context,
|
||||
|
||||
// Returns a function to simulate blocks. Written like this to avoid constant
|
||||
// parameters being passed everytime, to minimize memory overhead.
|
||||
func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Writer, params Params,
|
||||
func createBlockSimulator(testingMode bool, tb testing.TB, w io.Writer, params Params,
|
||||
event func(route, op, evResult string), ops WeightedOperations,
|
||||
operationQueue OperationQueue, timeOperationQueue []simulation.FutureOperation,
|
||||
logWriter LogWriter, config simulation.Config) blockSimFn {
|
||||
@ -250,7 +256,6 @@ func createBlockSimulator(testingMode bool, tb testing.TB, t *testing.T, w io.Wr
|
||||
return func(
|
||||
r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accounts []simulation.Account, header abci.Header,
|
||||
) (opCount int) {
|
||||
|
||||
_, _ = fmt.Fprintf(
|
||||
w, "\rSimulating... block %d/%d, operation %d/%d.",
|
||||
header.Height, config.NumBlocks, opCount, blocksize,
|
||||
@ -301,6 +306,7 @@ Comment: %s`,
|
||||
|
||||
opCount++
|
||||
}
|
||||
|
||||
return opCount
|
||||
}
|
||||
}
|
||||
@ -324,15 +330,18 @@ func runQueuedOperations(queueOps map[int][]simulation.Operation,
|
||||
// be changed.
|
||||
opMsg, _, err := queuedOp[i](r, app, ctx, accounts, chainID)
|
||||
opMsg.LogEvent(event)
|
||||
|
||||
if !lean || opMsg.OK {
|
||||
logWriter.AddEntry((QueuedMsgEntry(int64(height), opMsg)))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logWriter.PrintLogs()
|
||||
tb.FailNow()
|
||||
}
|
||||
}
|
||||
delete(queueOps, height)
|
||||
|
||||
return numOpsRan
|
||||
}
|
||||
|
||||
@ -350,9 +359,11 @@ func runQueuedTimeOperations(queueOps []simulation.FutureOperation,
|
||||
// be changed.
|
||||
opMsg, _, err := queueOps[0].Op(r, app, ctx, accounts, chainID)
|
||||
opMsg.LogEvent(event)
|
||||
|
||||
if !lean || opMsg.OK {
|
||||
logWriter.AddEntry(QueuedMsgEntry(int64(height), opMsg))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logWriter.PrintLogs()
|
||||
tb.FailNow()
|
||||
@ -361,5 +372,6 @@ func runQueuedTimeOperations(queueOps []simulation.FutureOperation,
|
||||
queueOps = queueOps[1:]
|
||||
numOpsRan++
|
||||
}
|
||||
|
||||
return numOpsRan
|
||||
}
|
||||
|
||||
@ -29,12 +29,15 @@ func CreateTransitionMatrix(weights [][]int) (simulation.TransitionMatrix, error
|
||||
fmt.Errorf("transition matrix: non-square matrix provided, error on row %d", i)
|
||||
}
|
||||
}
|
||||
|
||||
totals := make([]int, n)
|
||||
|
||||
for row := 0; row < n; row++ {
|
||||
for col := 0; col < n; col++ {
|
||||
totals[col] += weights[row][col]
|
||||
}
|
||||
}
|
||||
|
||||
return TransitionMatrix{weights, totals, n}, nil
|
||||
}
|
||||
|
||||
@ -46,6 +49,7 @@ func (t TransitionMatrix) NextState(r *rand.Rand, i int) int {
|
||||
if randNum < t.weights[row][i] {
|
||||
return row
|
||||
}
|
||||
|
||||
randNum -= t.weights[row][i]
|
||||
}
|
||||
// This line should never get executed
|
||||
@ -57,14 +61,18 @@ func (t TransitionMatrix) NextState(r *rand.Rand, i int) int {
|
||||
func GetMemberOfInitialState(r *rand.Rand, weights []int) int {
|
||||
n := len(weights)
|
||||
total := 0
|
||||
|
||||
for i := 0; i < n; i++ {
|
||||
total += weights[i]
|
||||
}
|
||||
|
||||
randNum := r.Intn(total)
|
||||
|
||||
for state := 0; state < n; state++ {
|
||||
if randNum < weights[state] {
|
||||
return state
|
||||
}
|
||||
|
||||
randNum -= weights[state]
|
||||
}
|
||||
// This line should never get executed
|
||||
|
||||
@ -9,12 +9,14 @@ import (
|
||||
|
||||
func getTestingMode(tb testing.TB) (testingMode bool, t *testing.T, b *testing.B) {
|
||||
testingMode = false
|
||||
|
||||
if _t, ok := tb.(*testing.T); ok {
|
||||
t = _t
|
||||
testingMode = true
|
||||
} else {
|
||||
b = tb.(*testing.B)
|
||||
}
|
||||
|
||||
return testingMode, t, b
|
||||
}
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@ var (
|
||||
addr1 = sdk.AccAddress(priv1.PubKey().Address())
|
||||
)
|
||||
|
||||
func checkValidator(t *testing.T, app *simapp.SimApp, addr sdk.AccAddress, expFound bool) staking.Validator {
|
||||
func checkValidator(t *testing.T, app *simapp.SimApp, _ sdk.AccAddress, expFound bool) staking.Validator {
|
||||
ctxCheck := app.BaseApp.NewContext(true, abci.Header{})
|
||||
validator, found := app.StakingKeeper.GetValidator(ctxCheck, sdk.ValAddress(addr1))
|
||||
require.Equal(t, expFound, found)
|
||||
|
||||
@ -66,7 +66,6 @@ func (h Hooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) {
|
||||
h.k.AfterValidatorCreated(ctx, valAddr)
|
||||
}
|
||||
|
||||
// nolint - unused hooks
|
||||
func (h Hooks) AfterValidatorBeginUnbonding(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) {}
|
||||
func (h Hooks) BeforeValidatorModified(_ sdk.Context, _ sdk.ValAddress) {}
|
||||
func (h Hooks) BeforeDelegationCreated(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) {}
|
||||
|
||||
@ -1,8 +1,6 @@
|
||||
package keeper
|
||||
|
||||
// nolint:deadcode,unused
|
||||
// DONTCOVER
|
||||
// noalias
|
||||
|
||||
import (
|
||||
"github.com/tendermint/tendermint/crypto"
|
||||
@ -24,11 +22,13 @@ func TestParams() types.Params {
|
||||
params := types.DefaultParams()
|
||||
params.SignedBlocksWindow = 1000
|
||||
params.DowntimeJailDuration = 60 * 60
|
||||
|
||||
return params
|
||||
}
|
||||
|
||||
func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey crypto.PubKey, amt sdk.Int) staking.MsgCreateValidator {
|
||||
commission := staking.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec())
|
||||
|
||||
return staking.NewMsgCreateValidator(
|
||||
address, pubKey, sdk.NewCoin(sdk.DefaultBondDenom, amt),
|
||||
staking.Description{}, commission, sdk.OneInt(),
|
||||
|
||||
@ -1,7 +1,5 @@
|
||||
package staking
|
||||
|
||||
// nolint
|
||||
|
||||
import (
|
||||
"github.com/cosmos/cosmos-sdk/x/staking/exported"
|
||||
"github.com/cosmos/cosmos-sdk/x/staking/keeper"
|
||||
|
||||
@ -6,7 +6,6 @@ import (
|
||||
"github.com/cosmos/cosmos-sdk/x/staking/types"
|
||||
)
|
||||
|
||||
// nolint
|
||||
const (
|
||||
FlagAddressValidator = "validator"
|
||||
FlagAddressValidatorSrc = "addr-validator-source"
|
||||
|
||||
@ -42,7 +42,6 @@ func GetQueryCmd(queryRoute string, cdc *codec.Codec) *cobra.Command {
|
||||
GetCmdQueryPool(queryRoute, cdc))...)
|
||||
|
||||
return stakingQueryCmd
|
||||
|
||||
}
|
||||
|
||||
// GetCmdQueryValidator implements the validator query command.
|
||||
|
||||
@ -53,6 +53,7 @@ func NewTxCmd(m codec.Marshaler, txg tx.Generator, ar tx.AccountRetriever) *cobr
|
||||
NewRedelegateCmd(m, txg, ar),
|
||||
NewUnbondCmd(m, txg, ar),
|
||||
)...)
|
||||
|
||||
return stakingTxCmd
|
||||
}
|
||||
|
||||
@ -84,10 +85,11 @@ func NewCreateValidatorCmd(m codec.Marshaler, txg tx.Generator, ar tx.AccountRet
|
||||
cmd.Flags().String(FlagIP, "", fmt.Sprintf("The node's public IP. It takes effect only when used in combination with --%s", flags.FlagGenerateOnly))
|
||||
cmd.Flags().String(FlagNodeID, "", "The node's ID")
|
||||
|
||||
cmd.MarkFlagRequired(flags.FlagFrom)
|
||||
cmd.MarkFlagRequired(FlagAmount)
|
||||
cmd.MarkFlagRequired(FlagPubKey)
|
||||
cmd.MarkFlagRequired(FlagMoniker)
|
||||
_ = cmd.MarkFlagRequired(flags.FlagFrom)
|
||||
_ = cmd.MarkFlagRequired(FlagAmount)
|
||||
_ = cmd.MarkFlagRequired(FlagPubKey)
|
||||
_ = cmd.MarkFlagRequired(FlagMoniker)
|
||||
|
||||
return flags.PostCommands(cmd)[0]
|
||||
}
|
||||
|
||||
@ -145,6 +147,7 @@ func NewEditValidatorCmd(m codec.Marshaler, txg tx.Generator, ar tx.AccountRetri
|
||||
return tx.GenerateOrBroadcastTx(cliCtx, txf, msg)
|
||||
},
|
||||
}
|
||||
|
||||
return flags.PostCommands(cmd)[0]
|
||||
}
|
||||
|
||||
@ -241,6 +244,7 @@ $ %s tx staking redelegate cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj
|
||||
return tx.GenerateOrBroadcastTx(cliCtx, txf, msg)
|
||||
},
|
||||
}
|
||||
|
||||
return flags.PostCommands(cmd)[0]
|
||||
}
|
||||
|
||||
@ -285,12 +289,12 @@ $ %s tx staking unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100s
|
||||
return tx.GenerateOrBroadcastTx(cliCtx, txf, msg)
|
||||
},
|
||||
}
|
||||
|
||||
return flags.PostCommands(cmd)[0]
|
||||
}
|
||||
|
||||
func NewBuildCreateValidatorMsg(cliCtx context.CLIContext, txf tx.Factory) (tx.Factory, sdk.Msg, error) {
|
||||
amounstStr := viper.GetString(FlagAmount)
|
||||
amount, err := sdk.ParseCoin(amounstStr)
|
||||
amount, err := sdk.ParseCoin(viper.GetString(FlagAmount))
|
||||
if err != nil {
|
||||
return txf, nil, err
|
||||
}
|
||||
@ -315,6 +319,7 @@ func NewBuildCreateValidatorMsg(cliCtx context.CLIContext, txf tx.Factory) (tx.F
|
||||
rateStr := viper.GetString(FlagCommissionRate)
|
||||
maxRateStr := viper.GetString(FlagCommissionMaxRate)
|
||||
maxChangeRateStr := viper.GetString(FlagCommissionMaxChangeRate)
|
||||
|
||||
commissionRates, err := buildCommissionRates(rateStr, maxRateStr, maxChangeRateStr)
|
||||
if err != nil {
|
||||
return txf, nil, err
|
||||
@ -322,6 +327,7 @@ func NewBuildCreateValidatorMsg(cliCtx context.CLIContext, txf tx.Factory) (tx.F
|
||||
|
||||
// get the initial validator min self delegation
|
||||
msbStr := viper.GetString(FlagMinSelfDelegation)
|
||||
|
||||
minSelfDelegation, ok := sdk.NewIntFromString(msbStr)
|
||||
if !ok {
|
||||
return txf, nil, types.ErrMinSelfDelegationInvalid
|
||||
@ -337,6 +343,7 @@ func NewBuildCreateValidatorMsg(cliCtx context.CLIContext, txf tx.Factory) (tx.F
|
||||
if viper.GetBool(flags.FlagGenerateOnly) {
|
||||
ip := viper.GetString(FlagIP)
|
||||
nodeID := viper.GetString(FlagNodeID)
|
||||
|
||||
if nodeID != "" && ip != "" {
|
||||
txf = txf.WithMemo(fmt.Sprintf("%s@%s:26656", nodeID, ip))
|
||||
}
|
||||
@ -348,7 +355,6 @@ func NewBuildCreateValidatorMsg(cliCtx context.CLIContext, txf tx.Factory) (tx.F
|
||||
// Return the flagset, particular flags, and a description of defaults
|
||||
// this is anticipated to be used with the gen-tx
|
||||
func CreateValidatorMsgHelpers(ipDefault string) (fs *flag.FlagSet, nodeIDFlag, pubkeyFlag, amountFlag, defaultsDesc string) {
|
||||
|
||||
fsCreateValidator := flag.NewFlagSet("", flag.ContinueOnError)
|
||||
fsCreateValidator.String(FlagIP, ipDefault, "The node's public IP")
|
||||
fsCreateValidator.String(FlagNodeID, "", "The node's NodeID")
|
||||
@ -378,10 +384,9 @@ func CreateValidatorMsgHelpers(ipDefault string) (fs *flag.FlagSet, nodeIDFlag,
|
||||
func PrepareFlagsForTxCreateValidator(
|
||||
config *cfg.Config, nodeID, chainID string, valPubKey crypto.PubKey,
|
||||
) {
|
||||
|
||||
ip := viper.GetString(FlagIP)
|
||||
if ip == "" {
|
||||
fmt.Fprintf(os.Stderr, "couldn't retrieve an external IP; "+
|
||||
_, _ = fmt.Fprintf(os.Stderr, "couldn't retrieve an external IP; "+
|
||||
"the tx's memo field will be unset")
|
||||
}
|
||||
|
||||
@ -405,18 +410,23 @@ func PrepareFlagsForTxCreateValidator(
|
||||
if config.Moniker == "" {
|
||||
viper.Set(FlagMoniker, viper.GetString(flags.FlagName))
|
||||
}
|
||||
|
||||
if viper.GetString(FlagAmount) == "" {
|
||||
viper.Set(FlagAmount, defaultAmount)
|
||||
}
|
||||
|
||||
if viper.GetString(FlagCommissionRate) == "" {
|
||||
viper.Set(FlagCommissionRate, defaultCommissionRate)
|
||||
}
|
||||
|
||||
if viper.GetString(FlagCommissionMaxRate) == "" {
|
||||
viper.Set(FlagCommissionMaxRate, defaultCommissionMaxRate)
|
||||
}
|
||||
|
||||
if viper.GetString(FlagCommissionMaxChangeRate) == "" {
|
||||
viper.Set(FlagCommissionMaxChangeRate, defaultCommissionMaxChangeRate)
|
||||
}
|
||||
|
||||
if viper.GetString(FlagMinSelfDelegation) == "" {
|
||||
viper.Set(FlagMinSelfDelegation, defaultMinSelfDelegation)
|
||||
}
|
||||
@ -481,10 +491,10 @@ func GetCmdCreateValidator(cdc *codec.Codec) *cobra.Command {
|
||||
cmd.Flags().String(FlagIP, "", fmt.Sprintf("The node's public IP. It takes effect only when used in combination with --%s", flags.FlagGenerateOnly))
|
||||
cmd.Flags().String(FlagNodeID, "", "The node's ID")
|
||||
|
||||
cmd.MarkFlagRequired(flags.FlagFrom)
|
||||
cmd.MarkFlagRequired(FlagAmount)
|
||||
cmd.MarkFlagRequired(FlagPubKey)
|
||||
cmd.MarkFlagRequired(FlagMoniker)
|
||||
_ = cmd.MarkFlagRequired(flags.FlagFrom)
|
||||
_ = cmd.MarkFlagRequired(FlagAmount)
|
||||
_ = cmd.MarkFlagRequired(FlagPubKey)
|
||||
_ = cmd.MarkFlagRequired(FlagMoniker)
|
||||
|
||||
return cmd
|
||||
}
|
||||
@ -667,6 +677,7 @@ $ %s tx staking unbond cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj 100s
|
||||
func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr auth.TxBuilder) (auth.TxBuilder, sdk.Msg, error) {
|
||||
amounstStr := viper.GetString(FlagAmount)
|
||||
amount, err := sdk.ParseCoin(amounstStr)
|
||||
|
||||
if err != nil {
|
||||
return txBldr, nil, err
|
||||
}
|
||||
@ -692,6 +703,7 @@ func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr auth.TxBuilder) (
|
||||
maxRateStr := viper.GetString(FlagCommissionMaxRate)
|
||||
maxChangeRateStr := viper.GetString(FlagCommissionMaxChangeRate)
|
||||
commissionRates, err := buildCommissionRates(rateStr, maxRateStr, maxChangeRateStr)
|
||||
|
||||
if err != nil {
|
||||
return txBldr, nil, err
|
||||
}
|
||||
@ -699,6 +711,7 @@ func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr auth.TxBuilder) (
|
||||
// get the initial validator min self delegation
|
||||
msbStr := viper.GetString(FlagMinSelfDelegation)
|
||||
minSelfDelegation, ok := sdk.NewIntFromString(msbStr)
|
||||
|
||||
if !ok {
|
||||
return txBldr, nil, types.ErrMinSelfDelegationInvalid
|
||||
}
|
||||
@ -710,6 +723,7 @@ func BuildCreateValidatorMsg(cliCtx context.CLIContext, txBldr auth.TxBuilder) (
|
||||
if viper.GetBool(flags.FlagGenerateOnly) {
|
||||
ip := viper.GetString(FlagIP)
|
||||
nodeID := viper.GetString(FlagNodeID)
|
||||
|
||||
if nodeID != "" && ip != "" {
|
||||
txBldr = txBldr.WithMemo(fmt.Sprintf("%s@%s:26656", nodeID, ip))
|
||||
}
|
||||
|
||||
@ -28,5 +28,6 @@ func buildCommissionRates(rateStr, maxRateStr, maxChangeRateStr string) (commiss
|
||||
}
|
||||
|
||||
commission = types.NewCommissionRates(rate, maxRate, maxChangeRate)
|
||||
|
||||
return commission, nil
|
||||
}
|
||||
|
||||
@ -19,6 +19,7 @@ func TxStakingCreateValidator(f *cli.Fixtures, from, consPubKey string, amount s
|
||||
cmd += fmt.Sprintf(" --amount=%v --moniker=%v --commission-rate=%v", amount, from, "0.05")
|
||||
cmd += fmt.Sprintf(" --commission-max-rate=%v --commission-max-change-rate=%v", "0.20", "0.10")
|
||||
cmd += fmt.Sprintf(" --min-self-delegation=%v", "1")
|
||||
|
||||
return cli.ExecuteWriteRetStdStreams(f.T, cli.AddFlags(cmd, flags), clientkeys.DefaultKeyPass)
|
||||
}
|
||||
|
||||
@ -33,10 +34,12 @@ func TxStakingUnbond(f *cli.Fixtures, from, shares string, validator sdk.ValAddr
|
||||
func QueryStakingValidator(f *cli.Fixtures, valAddr sdk.ValAddress, flags ...string) staking.Validator {
|
||||
cmd := fmt.Sprintf("%s query staking validator %s %v", f.SimcliBinary, valAddr, f.Flags())
|
||||
out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "")
|
||||
|
||||
var validator staking.Validator
|
||||
|
||||
err := f.Cdc.UnmarshalJSON([]byte(out), &validator)
|
||||
require.NoError(f.T, err, "out %v\n, err %v", out, err)
|
||||
|
||||
return validator
|
||||
}
|
||||
|
||||
@ -44,10 +47,12 @@ func QueryStakingValidator(f *cli.Fixtures, valAddr sdk.ValAddress, flags ...str
|
||||
func QueryStakingUnbondingDelegationsFrom(f *cli.Fixtures, valAddr sdk.ValAddress, flags ...string) []staking.UnbondingDelegation {
|
||||
cmd := fmt.Sprintf("%s query staking unbonding-delegations-from %s %v", f.SimcliBinary, valAddr, f.Flags())
|
||||
out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "")
|
||||
|
||||
var ubds []staking.UnbondingDelegation
|
||||
|
||||
err := f.Cdc.UnmarshalJSON([]byte(out), &ubds)
|
||||
require.NoError(f.T, err, "out %v\n, err %v", out, err)
|
||||
|
||||
return ubds
|
||||
}
|
||||
|
||||
@ -55,10 +60,12 @@ func QueryStakingUnbondingDelegationsFrom(f *cli.Fixtures, valAddr sdk.ValAddres
|
||||
func QueryStakingDelegationsTo(f *cli.Fixtures, valAddr sdk.ValAddress, flags ...string) []staking.Delegation {
|
||||
cmd := fmt.Sprintf("%s query staking delegations-to %s %v", f.SimcliBinary, valAddr, f.Flags())
|
||||
out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "")
|
||||
|
||||
var delegations []staking.Delegation
|
||||
|
||||
err := f.Cdc.UnmarshalJSON([]byte(out), &delegations)
|
||||
require.NoError(f.T, err, "out %v\n, err %v", out, err)
|
||||
|
||||
return delegations
|
||||
}
|
||||
|
||||
@ -66,10 +73,12 @@ func QueryStakingDelegationsTo(f *cli.Fixtures, valAddr sdk.ValAddress, flags ..
|
||||
func QueryStakingPool(f *cli.Fixtures, flags ...string) staking.Pool {
|
||||
cmd := fmt.Sprintf("%s query staking pool %v", f.SimcliBinary, f.Flags())
|
||||
out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "")
|
||||
|
||||
var pool staking.Pool
|
||||
|
||||
err := f.Cdc.UnmarshalJSON([]byte(out), &pool)
|
||||
require.NoError(f.T, err, "out %v\n, err %v", out, err)
|
||||
|
||||
return pool
|
||||
}
|
||||
|
||||
@ -77,9 +86,11 @@ func QueryStakingPool(f *cli.Fixtures, flags ...string) staking.Pool {
|
||||
func QueryStakingParameters(f *cli.Fixtures, flags ...string) staking.Params {
|
||||
cmd := fmt.Sprintf("%s query staking params %v", f.SimcliBinary, f.Flags())
|
||||
out, _ := tests.ExecuteT(f.T, cli.AddFlags(cmd, flags), "")
|
||||
|
||||
var params staking.Params
|
||||
|
||||
err := f.Cdc.UnmarshalJSON([]byte(out), ¶ms)
|
||||
require.NoError(f.T, err, "out %v\n, err %v", out, err)
|
||||
|
||||
return params
|
||||
}
|
||||
|
||||
@ -104,7 +104,6 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) {
|
||||
"/staking/parameters",
|
||||
paramsHandlerFn(cliCtx),
|
||||
).Methods("GET")
|
||||
|
||||
}
|
||||
|
||||
// HTTP request handler to query a delegator delegations
|
||||
@ -121,11 +120,11 @@ func delegatorUnbondingDelegationsHandlerFn(cliCtx context.CLIContext) http.Hand
|
||||
func delegatorTxsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var typesQuerySlice []string
|
||||
|
||||
vars := mux.Vars(r)
|
||||
delegatorAddr := vars["delegatorAddr"]
|
||||
|
||||
_, err := sdk.AccAddressFromBech32(delegatorAddr)
|
||||
if rest.CheckBadRequestError(w, err) {
|
||||
if _, err := sdk.AccAddressFromBech32(delegatorAddr); rest.CheckBadRequestError(w, err) {
|
||||
return
|
||||
}
|
||||
|
||||
@ -136,6 +135,7 @@ func delegatorTxsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
|
||||
|
||||
typesQuery := r.URL.Query().Get("type")
|
||||
trimmedQuery := strings.TrimSpace(typesQuery)
|
||||
|
||||
if len(trimmedQuery) != 0 {
|
||||
typesQuerySlice = strings.Split(trimmedQuery, " ")
|
||||
}
|
||||
@ -175,6 +175,7 @@ func delegatorTxsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
|
||||
if rest.CheckInternalServerError(w, errQuery) {
|
||||
return
|
||||
}
|
||||
|
||||
txs = append(txs, foundTxs)
|
||||
}
|
||||
|
||||
@ -211,6 +212,7 @@ func redelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
|
||||
if rest.CheckBadRequestError(w, err) {
|
||||
return
|
||||
}
|
||||
|
||||
params.DelegatorAddr = delegatorAddr
|
||||
}
|
||||
|
||||
@ -219,6 +221,7 @@ func redelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
|
||||
if rest.CheckBadRequestError(w, err) {
|
||||
return
|
||||
}
|
||||
|
||||
params.SrcValidatorAddr = srcValidatorAddr
|
||||
}
|
||||
|
||||
@ -227,6 +230,7 @@ func redelegationsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
|
||||
if rest.CheckBadRequestError(w, err) {
|
||||
return
|
||||
}
|
||||
|
||||
params.DstValidatorAddr = dstValidatorAddr
|
||||
}
|
||||
|
||||
@ -279,12 +283,14 @@ func validatorsHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
|
||||
}
|
||||
|
||||
params := types.NewQueryValidatorsParams(page, limit, status)
|
||||
|
||||
bz, err := cliCtx.Codec.MarshalJSON(params)
|
||||
if rest.CheckBadRequestError(w, err) {
|
||||
return
|
||||
}
|
||||
|
||||
route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryValidators)
|
||||
|
||||
res, height, err := cliCtx.QueryWithData(route, bz)
|
||||
if rest.CheckInternalServerError(w, err) {
|
||||
return
|
||||
@ -315,6 +321,7 @@ func historicalInfoHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
vars := mux.Vars(r)
|
||||
heightStr := vars["height"]
|
||||
|
||||
height, err := strconv.ParseInt(heightStr, 10, 64)
|
||||
if err != nil || height < 0 {
|
||||
rest.WriteErrorResponse(w, http.StatusBadRequest, fmt.Sprintf("Must provide non-negative integer for height: %v", err))
|
||||
@ -322,13 +329,13 @@ func historicalInfoHandlerFn(cliCtx context.CLIContext) http.HandlerFunc {
|
||||
}
|
||||
|
||||
params := types.NewQueryHistoricalInfoParams(height)
|
||||
|
||||
bz, err := cliCtx.Codec.MarshalJSON(params)
|
||||
if rest.CheckInternalServerError(w, err) {
|
||||
return
|
||||
}
|
||||
|
||||
route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryHistoricalInfo)
|
||||
res, height, err := cliCtx.QueryWithData(route, bz)
|
||||
res, height, err := cliCtx.QueryWithData(fmt.Sprintf("custom/%s/%s", types.QuerierRoute, types.QueryHistoricalInfo), bz)
|
||||
if rest.CheckBadRequestError(w, err) {
|
||||
return
|
||||
}
|
||||
|
||||
@ -60,8 +60,8 @@ type (
|
||||
func newPostDelegationsHandlerFn(cliCtx context.CLIContext, m codec.Marshaler, txg tx.Generator) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
cliCtx = cliCtx.WithMarshaler(m)
|
||||
var req DelegateRequest
|
||||
|
||||
var req DelegateRequest
|
||||
if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) {
|
||||
return
|
||||
}
|
||||
@ -93,8 +93,8 @@ func newPostDelegationsHandlerFn(cliCtx context.CLIContext, m codec.Marshaler, t
|
||||
func newPostRedelegationsHandlerFn(cliCtx context.CLIContext, m codec.Marshaler, txg tx.Generator) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
cliCtx = cliCtx.WithMarshaler(m)
|
||||
var req RedelegateRequest
|
||||
|
||||
var req RedelegateRequest
|
||||
if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) {
|
||||
return
|
||||
}
|
||||
@ -126,6 +126,7 @@ func newPostRedelegationsHandlerFn(cliCtx context.CLIContext, m codec.Marshaler,
|
||||
func newPostUnbondingDelegationsHandlerFn(cliCtx context.CLIContext, m codec.Marshaler, txg tx.Generator) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
cliCtx = cliCtx.WithMarshaler(m)
|
||||
|
||||
var req UndelegateRequest
|
||||
if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) {
|
||||
return
|
||||
|
||||
@ -20,6 +20,7 @@ func contains(stringSlice []string, txType string) bool {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@ -20,7 +20,6 @@ func InitGenesis(
|
||||
ctx sdk.Context, keeper Keeper, accountKeeper types.AccountKeeper,
|
||||
bankKeeper types.BankKeeper, data types.GenesisState,
|
||||
) (res []abci.ValidatorUpdate) {
|
||||
|
||||
bondedTokens := sdk.ZeroInt()
|
||||
notBondedTokens := sdk.ZeroInt()
|
||||
|
||||
@ -66,8 +65,8 @@ func InitGenesis(
|
||||
if !data.Exported {
|
||||
keeper.BeforeDelegationCreated(ctx, delegation.DelegatorAddress, delegation.ValidatorAddress)
|
||||
}
|
||||
keeper.SetDelegation(ctx, delegation)
|
||||
|
||||
keeper.SetDelegation(ctx, delegation)
|
||||
// Call the after-modification hook if not exported
|
||||
if !data.Exported {
|
||||
keeper.AfterDelegationModified(ctx, delegation.DelegatorAddress, delegation.ValidatorAddress)
|
||||
@ -76,6 +75,7 @@ func InitGenesis(
|
||||
|
||||
for _, ubd := range data.UnbondingDelegations {
|
||||
keeper.SetUnbondingDelegation(ctx, ubd)
|
||||
|
||||
for _, entry := range ubd.Entries {
|
||||
keeper.InsertUBDQueue(ctx, ubd, entry.CompletionTime)
|
||||
notBondedTokens = notBondedTokens.Add(entry.Balance)
|
||||
@ -84,6 +84,7 @@ func InitGenesis(
|
||||
|
||||
for _, red := range data.Redelegations {
|
||||
keeper.SetRedelegation(ctx, red)
|
||||
|
||||
for _, entry := range red.Entries {
|
||||
keeper.InsertRedelegationQueue(ctx, red, entry.CompletionTime)
|
||||
}
|
||||
@ -126,9 +127,11 @@ func InitGenesis(
|
||||
for _, lv := range data.LastValidatorPowers {
|
||||
keeper.SetLastValidatorPower(ctx, lv.Address, lv.Power)
|
||||
validator, found := keeper.GetValidator(ctx, lv.Address)
|
||||
|
||||
if !found {
|
||||
panic(fmt.Sprintf("validator %s not found", lv.Address))
|
||||
}
|
||||
|
||||
update := validator.ABCIValidatorUpdate()
|
||||
update.Power = lv.Power // keep the next-val-set offset, use the last power for the first block
|
||||
res = append(res, update)
|
||||
@ -145,16 +148,21 @@ func InitGenesis(
|
||||
// the keeper.
|
||||
func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState {
|
||||
var unbondingDelegations []types.UnbondingDelegation
|
||||
|
||||
keeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd types.UnbondingDelegation) (stop bool) {
|
||||
unbondingDelegations = append(unbondingDelegations, ubd)
|
||||
return false
|
||||
})
|
||||
|
||||
var redelegations []types.Redelegation
|
||||
|
||||
keeper.IterateRedelegations(ctx, func(_ int64, red types.Redelegation) (stop bool) {
|
||||
redelegations = append(redelegations, red)
|
||||
return false
|
||||
})
|
||||
|
||||
var lastValidatorPowers []types.LastValidatorPower
|
||||
|
||||
keeper.IterateLastValidatorPowers(ctx, func(addr sdk.ValAddress, power int64) (stop bool) {
|
||||
lastValidatorPowers = append(lastValidatorPowers, types.LastValidatorPower{Address: addr, Power: power})
|
||||
return false
|
||||
@ -190,20 +198,16 @@ func WriteValidators(ctx sdk.Context, keeper Keeper) (vals []tmtypes.GenesisVali
|
||||
// ValidateGenesis validates the provided staking genesis state to ensure the
|
||||
// expected invariants holds. (i.e. params in correct bounds, no duplicate validators)
|
||||
func ValidateGenesis(data types.GenesisState) error {
|
||||
err := validateGenesisStateValidators(data.Validators)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = data.Params.Validate()
|
||||
if err != nil {
|
||||
if err := validateGenesisStateValidators(data.Validators); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
return data.Params.Validate()
|
||||
}
|
||||
|
||||
func validateGenesisStateValidators(validators []types.Validator) (err error) {
|
||||
addrMap := make(map[string]bool, len(validators))
|
||||
|
||||
for i := 0; i < len(validators); i++ {
|
||||
val := validators[i]
|
||||
strKey := string(val.GetConsPubKey().Bytes())
|
||||
@ -211,9 +215,11 @@ func validateGenesisStateValidators(validators []types.Validator) (err error) {
|
||||
if _, ok := addrMap[strKey]; ok {
|
||||
return fmt.Errorf("duplicate validator in genesis state: moniker %v, address %v", val.Description.Moniker, val.GetConsAddr())
|
||||
}
|
||||
|
||||
if val.Jailed && val.IsBonded() {
|
||||
return fmt.Errorf("validator is bonded and jailed in genesis state: moniker %v, address %v", val.Description.Moniker, val.GetConsAddr())
|
||||
}
|
||||
|
||||
if val.DelegatorShares.IsZero() && !val.IsUnbonding() {
|
||||
return fmt.Errorf("bonded/unbonded genesis validator cannot have zero delegator shares, validator: %v", val)
|
||||
}
|
||||
|
||||
@ -16,10 +16,10 @@ import (
|
||||
"github.com/cosmos/cosmos-sdk/x/staking/types"
|
||||
)
|
||||
|
||||
func bootstrapGenesisTest(t *testing.T, power int64, numAddrs int) (*simapp.SimApp, sdk.Context, []sdk.AccAddress, []sdk.ValAddress) {
|
||||
func bootstrapGenesisTest(t *testing.T, power int64, numAddrs int) (*simapp.SimApp, sdk.Context, []sdk.AccAddress) {
|
||||
_, app, ctx := getBaseSimappWithCustomKeeper()
|
||||
|
||||
addrDels, addrVals := generateAddresses(app, ctx, numAddrs, 10000)
|
||||
addrDels, _ := generateAddresses(app, ctx, numAddrs, 10000)
|
||||
|
||||
amt := sdk.TokensFromConsensusPower(power)
|
||||
totalSupply := sdk.NewCoins(sdk.NewCoin(app.StakingKeeper.BondDenom(ctx), amt.MulRaw(int64(len(addrDels)))))
|
||||
@ -31,11 +31,11 @@ func bootstrapGenesisTest(t *testing.T, power int64, numAddrs int) (*simapp.SimA
|
||||
app.AccountKeeper.SetModuleAccount(ctx, notBondedPool)
|
||||
app.BankKeeper.SetSupply(ctx, bank.NewSupply(totalSupply))
|
||||
|
||||
return app, ctx, addrDels, addrVals
|
||||
return app, ctx, addrDels
|
||||
}
|
||||
|
||||
func TestInitGenesis(t *testing.T) {
|
||||
app, ctx, addrs, _ := bootstrapGenesisTest(t, 1000, 10)
|
||||
app, ctx, addrs := bootstrapGenesisTest(t, 1000, 10)
|
||||
|
||||
valTokens := sdk.TokensFromConsensusPower(1)
|
||||
|
||||
@ -92,7 +92,7 @@ func TestInitGenesisLargeValidatorSet(t *testing.T) {
|
||||
size := 200
|
||||
require.True(t, size > 100)
|
||||
|
||||
app, ctx, addrs, _ := bootstrapGenesisTest(t, 1000, 200)
|
||||
app, ctx, addrs := bootstrapGenesisTest(t, 1000, 200)
|
||||
|
||||
params := app.StakingKeeper.GetParams(ctx)
|
||||
delegations := []types.Delegation{}
|
||||
|
||||
@ -152,6 +152,7 @@ func handleMsgEditValidator(ctx sdk.Context, msg types.MsgEditValidator, k keepe
|
||||
if !msg.MinSelfDelegation.GT(validator.MinSelfDelegation) {
|
||||
return nil, ErrMinSelfDelegationDecreased
|
||||
}
|
||||
|
||||
if msg.MinSelfDelegation.GT(validator.Tokens) {
|
||||
return nil, ErrSelfDelegationBelowMinimum
|
||||
}
|
||||
|
||||
@ -14,12 +14,16 @@ import (
|
||||
// iterate through the validator set and perform the provided function
|
||||
func (k Keeper) IterateValidators(ctx sdk.Context, fn func(index int64, validator exported.ValidatorI) (stop bool)) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.ValidatorsKey)
|
||||
defer iterator.Close()
|
||||
|
||||
i := int64(0)
|
||||
|
||||
for ; iterator.Valid(); iterator.Next() {
|
||||
validator := types.MustUnmarshalValidator(k.cdc, iterator.Value())
|
||||
stop := fn(i, validator) // XXX is this safe will the validator unexposed fields be able to get written to?
|
||||
|
||||
if stop {
|
||||
break
|
||||
}
|
||||
@ -54,9 +58,12 @@ func (k Keeper) IterateBondedValidatorsByPower(ctx sdk.Context, fn func(index in
|
||||
func (k Keeper) IterateLastValidators(ctx sdk.Context, fn func(index int64, validator exported.ValidatorI) (stop bool)) {
|
||||
iterator := k.LastValidatorsIterator(ctx)
|
||||
defer iterator.Close()
|
||||
|
||||
i := int64(0)
|
||||
|
||||
for ; iterator.Valid(); iterator.Next() {
|
||||
address := types.AddressFromLastValidatorPowerKey(iterator.Key())
|
||||
|
||||
validator, found := k.GetValidator(ctx, address)
|
||||
if !found {
|
||||
panic(fmt.Sprintf("validator record not found for address: %v\n", address))
|
||||
@ -76,6 +83,7 @@ func (k Keeper) Validator(ctx sdk.Context, address sdk.ValAddress) exported.Vali
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
|
||||
@ -85,6 +93,7 @@ func (k Keeper) ValidatorByConsAddr(ctx sdk.Context, addr sdk.ConsAddress) expor
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
|
||||
return val
|
||||
}
|
||||
|
||||
@ -109,13 +118,15 @@ func (k Keeper) Delegation(ctx sdk.Context, addrDel sdk.AccAddress, addrVal sdk.
|
||||
// iterate through all of the delegations from a delegator
|
||||
func (k Keeper) IterateDelegations(ctx sdk.Context, delAddr sdk.AccAddress,
|
||||
fn func(index int64, del exported.DelegationI) (stop bool)) {
|
||||
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
delegatorPrefixKey := types.GetDelegationsKey(delAddr)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest
|
||||
defer iterator.Close()
|
||||
|
||||
for i := int64(0); iterator.Valid(); iterator.Next() {
|
||||
del := types.MustUnmarshalDelegation(k.cdc, iterator.Value())
|
||||
|
||||
stop := fn(i, del)
|
||||
if stop {
|
||||
break
|
||||
@ -128,6 +139,7 @@ func (k Keeper) IterateDelegations(ctx sdk.Context, delAddr sdk.AccAddress,
|
||||
// TODO: remove this func, change all usage for iterate functionality
|
||||
func (k Keeper) GetAllSDKDelegations(ctx sdk.Context) (delegations []types.Delegation) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.DelegationKey)
|
||||
defer iterator.Close()
|
||||
|
||||
@ -135,5 +147,6 @@ func (k Keeper) GetAllSDKDelegations(ctx sdk.Context) (delegations []types.Deleg
|
||||
delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value())
|
||||
delegations = append(delegations, delegation)
|
||||
}
|
||||
return delegations
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@ -12,23 +12,24 @@ import (
|
||||
|
||||
// return a specific delegation
|
||||
func (k Keeper) GetDelegation(ctx sdk.Context,
|
||||
delAddr sdk.AccAddress, valAddr sdk.ValAddress) (
|
||||
delegation types.Delegation, found bool) {
|
||||
|
||||
delAddr sdk.AccAddress, valAddr sdk.ValAddress) (delegation types.Delegation, found bool) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
key := types.GetDelegationKey(delAddr, valAddr)
|
||||
|
||||
value := store.Get(key)
|
||||
if value == nil {
|
||||
return delegation, false
|
||||
}
|
||||
|
||||
delegation = types.MustUnmarshalDelegation(k.cdc, value)
|
||||
|
||||
return delegation, true
|
||||
}
|
||||
|
||||
// IterateAllDelegations iterate through all of the delegations
|
||||
func (k Keeper) IterateAllDelegations(ctx sdk.Context, cb func(delegation types.Delegation) (stop bool)) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.DelegationKey)
|
||||
defer iterator.Close()
|
||||
|
||||
@ -46,12 +47,14 @@ func (k Keeper) GetAllDelegations(ctx sdk.Context) (delegations []types.Delegati
|
||||
delegations = append(delegations, delegation)
|
||||
return false
|
||||
})
|
||||
|
||||
return delegations
|
||||
}
|
||||
|
||||
// return all delegations to a specific validator. Useful for querier.
|
||||
func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress) (delegations []types.Delegation) { //nolint:interfacer
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.DelegationKey)
|
||||
defer iterator.Close()
|
||||
|
||||
@ -61,17 +64,17 @@ func (k Keeper) GetValidatorDelegations(ctx sdk.Context, valAddr sdk.ValAddress)
|
||||
delegations = append(delegations, delegation)
|
||||
}
|
||||
}
|
||||
|
||||
return delegations
|
||||
}
|
||||
|
||||
// return a given amount of all the delegations from a delegator
|
||||
func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddress,
|
||||
maxRetrieve uint16) (delegations []types.Delegation) {
|
||||
|
||||
delegations = make([]types.Delegation, maxRetrieve)
|
||||
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
delegatorPrefixKey := types.GetDelegationsKey(delegator)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey)
|
||||
defer iterator.Close()
|
||||
|
||||
@ -81,6 +84,7 @@ func (k Keeper) GetDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAddres
|
||||
delegations[i] = delegation
|
||||
i++
|
||||
}
|
||||
|
||||
return delegations[:i] // trim if the array length < maxRetrieve
|
||||
}
|
||||
|
||||
@ -102,11 +106,11 @@ func (k Keeper) RemoveDelegation(ctx sdk.Context, delegation types.Delegation) {
|
||||
// return a given amount of all the delegator unbonding-delegations
|
||||
func (k Keeper) GetUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddress,
|
||||
maxRetrieve uint16) (unbondingDelegations []types.UnbondingDelegation) {
|
||||
|
||||
unbondingDelegations = make([]types.UnbondingDelegation, maxRetrieve)
|
||||
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
delegatorPrefixKey := types.GetUBDsKey(delegator)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey)
|
||||
defer iterator.Close()
|
||||
|
||||
@ -116,6 +120,7 @@ func (k Keeper) GetUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddres
|
||||
unbondingDelegations[i] = unbondingDelegation
|
||||
i++
|
||||
}
|
||||
|
||||
return unbondingDelegations[:i] // trim if the array length < maxRetrieve
|
||||
}
|
||||
|
||||
@ -123,21 +128,23 @@ func (k Keeper) GetUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAddres
|
||||
func (k Keeper) GetUnbondingDelegation(
|
||||
ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress,
|
||||
) (ubd types.UnbondingDelegation, found bool) {
|
||||
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
key := types.GetUBDKey(delAddr, valAddr)
|
||||
value := store.Get(key)
|
||||
|
||||
if value == nil {
|
||||
return ubd, false
|
||||
}
|
||||
|
||||
ubd = types.MustUnmarshalUBD(k.cdc, value)
|
||||
|
||||
return ubd, true
|
||||
}
|
||||
|
||||
// return all unbonding delegations from a particular validator
|
||||
func (k Keeper) GetUnbondingDelegationsFromValidator(ctx sdk.Context, valAddr sdk.ValAddress) (ubds []types.UnbondingDelegation) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.GetUBDsByValIndexKey(valAddr))
|
||||
defer iterator.Close()
|
||||
|
||||
@ -147,12 +154,14 @@ func (k Keeper) GetUnbondingDelegationsFromValidator(ctx sdk.Context, valAddr sd
|
||||
ubd := types.MustUnmarshalUBD(k.cdc, value)
|
||||
ubds = append(ubds, ubd)
|
||||
}
|
||||
|
||||
return ubds
|
||||
}
|
||||
|
||||
// iterate through all of the unbonding delegations
|
||||
func (k Keeper) IterateUnbondingDelegations(ctx sdk.Context, fn func(index int64, ubd types.UnbondingDelegation) (stop bool)) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.UnbondingDelegationKey)
|
||||
defer iterator.Close()
|
||||
|
||||
@ -168,11 +177,11 @@ func (k Keeper) IterateUnbondingDelegations(ctx sdk.Context, fn func(index int64
|
||||
// HasMaxUnbondingDelegationEntries - check if unbonding delegation has maximum number of entries
|
||||
func (k Keeper) HasMaxUnbondingDelegationEntries(ctx sdk.Context,
|
||||
delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) bool {
|
||||
|
||||
ubd, found := k.GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr)
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
|
||||
return len(ubd.Entries) >= int(k.MaxEntries(ctx))
|
||||
}
|
||||
|
||||
@ -199,7 +208,6 @@ func (k Keeper) SetUnbondingDelegationEntry(
|
||||
ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress,
|
||||
creationHeight int64, minTime time.Time, balance sdk.Int,
|
||||
) types.UnbondingDelegation {
|
||||
|
||||
ubd, found := k.GetUnbondingDelegation(ctx, delegatorAddr, validatorAddr)
|
||||
if found {
|
||||
ubd.AddEntry(creationHeight, minTime, balance)
|
||||
@ -208,6 +216,7 @@ func (k Keeper) SetUnbondingDelegationEntry(
|
||||
}
|
||||
|
||||
k.SetUnbondingDelegation(ctx, ubd)
|
||||
|
||||
return ubd
|
||||
}
|
||||
|
||||
@ -217,6 +226,7 @@ func (k Keeper) SetUnbondingDelegationEntry(
|
||||
// corresponding to unbonding delegations that expire at a certain time.
|
||||
func (k Keeper) GetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvPairs []types.DVPair) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
bz := store.Get(types.GetUnbondingDelegationTimeKey(timestamp))
|
||||
if bz == nil {
|
||||
return []types.DVPair{}
|
||||
@ -224,6 +234,7 @@ func (k Keeper) GetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvPa
|
||||
|
||||
pairs := types.DVPairs{}
|
||||
k.cdc.MustUnmarshalBinaryBare(bz, &pairs)
|
||||
|
||||
return pairs.Pairs
|
||||
}
|
||||
|
||||
@ -237,9 +248,9 @@ func (k Keeper) SetUBDQueueTimeSlice(ctx sdk.Context, timestamp time.Time, keys
|
||||
// Insert an unbonding delegation to the appropriate timeslice in the unbonding queue
|
||||
func (k Keeper) InsertUBDQueue(ctx sdk.Context, ubd types.UnbondingDelegation,
|
||||
completionTime time.Time) {
|
||||
dvPair := types.DVPair{DelegatorAddress: ubd.DelegatorAddress, ValidatorAddress: ubd.ValidatorAddress}
|
||||
|
||||
timeSlice := k.GetUBDQueueTimeSlice(ctx, completionTime)
|
||||
dvPair := types.DVPair{DelegatorAddress: ubd.DelegatorAddress, ValidatorAddress: ubd.ValidatorAddress}
|
||||
if len(timeSlice) == 0 {
|
||||
k.SetUBDQueueTimeSlice(ctx, completionTime, []types.DVPair{dvPair})
|
||||
} else {
|
||||
@ -268,6 +279,7 @@ func (k Keeper) DequeueAllMatureUBDQueue(ctx sdk.Context, currTime time.Time) (m
|
||||
k.cdc.MustUnmarshalBinaryBare(value, ×lice)
|
||||
|
||||
matureUnbonds = append(matureUnbonds, timeslice.Pairs...)
|
||||
|
||||
store.Delete(unbondingTimesliceIterator.Key())
|
||||
}
|
||||
|
||||
@ -281,6 +293,7 @@ func (k Keeper) GetRedelegations(ctx sdk.Context, delegator sdk.AccAddress,
|
||||
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
delegatorPrefixKey := types.GetREDsKey(delegator)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey)
|
||||
defer iterator.Close()
|
||||
|
||||
@ -290,27 +303,30 @@ func (k Keeper) GetRedelegations(ctx sdk.Context, delegator sdk.AccAddress,
|
||||
redelegations[i] = redelegation
|
||||
i++
|
||||
}
|
||||
|
||||
return redelegations[:i] // trim if the array length < maxRetrieve
|
||||
}
|
||||
|
||||
// return a redelegation
|
||||
func (k Keeper) GetRedelegation(ctx sdk.Context,
|
||||
delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress) (red types.Redelegation, found bool) {
|
||||
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
key := types.GetREDKey(delAddr, valSrcAddr, valDstAddr)
|
||||
|
||||
value := store.Get(key)
|
||||
if value == nil {
|
||||
return red, false
|
||||
}
|
||||
|
||||
red = types.MustUnmarshalRED(k.cdc, value)
|
||||
|
||||
return red, true
|
||||
}
|
||||
|
||||
// return all redelegations from a particular validator
|
||||
func (k Keeper) GetRedelegationsFromSrcValidator(ctx sdk.Context, valAddr sdk.ValAddress) (reds []types.Redelegation) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.GetREDsFromValSrcIndexKey(valAddr))
|
||||
defer iterator.Close()
|
||||
|
||||
@ -320,15 +336,16 @@ func (k Keeper) GetRedelegationsFromSrcValidator(ctx sdk.Context, valAddr sdk.Va
|
||||
red := types.MustUnmarshalRED(k.cdc, value)
|
||||
reds = append(reds, red)
|
||||
}
|
||||
|
||||
return reds
|
||||
}
|
||||
|
||||
// check if validator is receiving a redelegation
|
||||
func (k Keeper) HasReceivingRedelegation(ctx sdk.Context,
|
||||
delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) bool {
|
||||
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
prefix := types.GetREDsByDelToValDstIndexKey(delAddr, valDstAddr)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, prefix)
|
||||
defer iterator.Close()
|
||||
|
||||
@ -339,11 +356,11 @@ func (k Keeper) HasReceivingRedelegation(ctx sdk.Context,
|
||||
func (k Keeper) HasMaxRedelegationEntries(ctx sdk.Context,
|
||||
delegatorAddr sdk.AccAddress, validatorSrcAddr,
|
||||
validatorDstAddr sdk.ValAddress) bool {
|
||||
|
||||
red, found := k.GetRedelegation(ctx, delegatorAddr, validatorSrcAddr, validatorDstAddr)
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
|
||||
return len(red.Entries) >= int(k.MaxEntries(ctx))
|
||||
}
|
||||
|
||||
@ -364,7 +381,6 @@ func (k Keeper) SetRedelegationEntry(ctx sdk.Context,
|
||||
validatorDstAddr sdk.ValAddress, creationHeight int64,
|
||||
minTime time.Time, balance sdk.Int,
|
||||
sharesSrc, sharesDst sdk.Dec) types.Redelegation {
|
||||
|
||||
red, found := k.GetRedelegation(ctx, delegatorAddr, validatorSrcAddr, validatorDstAddr)
|
||||
if found {
|
||||
red.AddEntry(creationHeight, minTime, balance, sharesDst)
|
||||
@ -372,13 +388,16 @@ func (k Keeper) SetRedelegationEntry(ctx sdk.Context,
|
||||
red = types.NewRedelegation(delegatorAddr, validatorSrcAddr,
|
||||
validatorDstAddr, creationHeight, minTime, balance, sharesDst)
|
||||
}
|
||||
|
||||
k.SetRedelegation(ctx, red)
|
||||
|
||||
return red
|
||||
}
|
||||
|
||||
// iterate through all redelegations
|
||||
func (k Keeper) IterateRedelegations(ctx sdk.Context, fn func(index int64, red types.Redelegation) (stop bool)) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.RedelegationKey)
|
||||
defer iterator.Close()
|
||||
|
||||
@ -406,6 +425,7 @@ func (k Keeper) RemoveRedelegation(ctx sdk.Context, red types.Redelegation) {
|
||||
// that expire at a certain time.
|
||||
func (k Keeper) GetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Time) (dvvTriplets []types.DVVTriplet) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
bz := store.Get(types.GetRedelegationTimeKey(timestamp))
|
||||
if bz == nil {
|
||||
return []types.DVVTriplet{}
|
||||
@ -413,6 +433,7 @@ func (k Keeper) GetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Ti
|
||||
|
||||
triplets := types.DVVTriplets{}
|
||||
k.cdc.MustUnmarshalBinaryBare(bz, &triplets)
|
||||
|
||||
return triplets.Triplets
|
||||
}
|
||||
|
||||
@ -426,7 +447,6 @@ func (k Keeper) SetRedelegationQueueTimeSlice(ctx sdk.Context, timestamp time.Ti
|
||||
// Insert an redelegation delegation to the appropriate timeslice in the redelegation queue
|
||||
func (k Keeper) InsertRedelegationQueue(ctx sdk.Context, red types.Redelegation,
|
||||
completionTime time.Time) {
|
||||
|
||||
timeSlice := k.GetRedelegationQueueTimeSlice(ctx, completionTime)
|
||||
dvvTriplet := types.DVVTriplet{
|
||||
DelegatorAddress: red.DelegatorAddress,
|
||||
@ -460,6 +480,7 @@ func (k Keeper) DequeueAllMatureRedelegationQueue(ctx sdk.Context, currTime time
|
||||
k.cdc.MustUnmarshalBinaryBare(value, ×lice)
|
||||
|
||||
matureRedelegations = append(matureRedelegations, timeslice.Triplets...)
|
||||
|
||||
store.Delete(redelegationTimesliceIterator.Key())
|
||||
}
|
||||
|
||||
@ -472,7 +493,6 @@ func (k Keeper) Delegate(
|
||||
ctx sdk.Context, delAddr sdk.AccAddress, bondAmt sdk.Int, tokenSrc sdk.BondStatus,
|
||||
validator types.Validator, subtractAccount bool,
|
||||
) (newShares sdk.Dec, err error) {
|
||||
|
||||
// In some situations, the exchange rate becomes invalid, e.g. if
|
||||
// Validator loses all tokens due to slashing. In this case,
|
||||
// make all future delegations invalid.
|
||||
@ -502,6 +522,7 @@ func (k Keeper) Delegate(
|
||||
}
|
||||
|
||||
var sendName string
|
||||
|
||||
switch {
|
||||
case validator.IsBonded():
|
||||
sendName = types.BondedPoolName
|
||||
@ -512,12 +533,10 @@ func (k Keeper) Delegate(
|
||||
}
|
||||
|
||||
coins := sdk.NewCoins(sdk.NewCoin(k.BondDenom(ctx), bondAmt))
|
||||
err := k.bankKeeper.DelegateCoinsFromAccountToModule(ctx, delegation.DelegatorAddress, sendName, coins)
|
||||
if err != nil {
|
||||
if err := k.bankKeeper.DelegateCoinsFromAccountToModule(ctx, delegation.DelegatorAddress, sendName, coins); err != nil {
|
||||
return sdk.Dec{}, err
|
||||
}
|
||||
} else {
|
||||
|
||||
// potentially transfer tokens between pools, if
|
||||
switch {
|
||||
case tokenSrc == sdk.Bonded && validator.IsBonded():
|
||||
@ -551,7 +570,6 @@ func (k Keeper) Delegate(
|
||||
func (k Keeper) Unbond(
|
||||
ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, shares sdk.Dec,
|
||||
) (amount sdk.Int, err error) {
|
||||
|
||||
// check if a delegation object exists in the store
|
||||
delegation, found := k.GetDelegation(ctx, delAddr, valAddr)
|
||||
if !found {
|
||||
@ -581,7 +599,6 @@ func (k Keeper) Unbond(
|
||||
// self-delegation below their minimum, we jail the validator.
|
||||
if isValidatorOperator && !validator.Jailed &&
|
||||
validator.TokensFromShares(delegation.Shares).TruncateInt().LT(validator.MinSelfDelegation) {
|
||||
|
||||
k.jailValidator(ctx, validator)
|
||||
validator = k.mustGetValidator(ctx, validator.OperatorAddress)
|
||||
}
|
||||
@ -613,16 +630,15 @@ func (k Keeper) Unbond(
|
||||
func (k Keeper) getBeginInfo(
|
||||
ctx sdk.Context, valSrcAddr sdk.ValAddress,
|
||||
) (completionTime time.Time, height int64, completeNow bool) {
|
||||
|
||||
validator, found := k.GetValidator(ctx, valSrcAddr)
|
||||
|
||||
// TODO: When would the validator not be found?
|
||||
switch {
|
||||
case !found || validator.IsBonded():
|
||||
|
||||
// the longest wait - just unbonding period from now
|
||||
completionTime = ctx.BlockHeader().Time.Add(k.UnbondingTime(ctx))
|
||||
height = ctx.BlockHeight()
|
||||
|
||||
return completionTime, height, false
|
||||
|
||||
case validator.IsUnbonded():
|
||||
@ -644,7 +660,6 @@ func (k Keeper) getBeginInfo(
|
||||
func (k Keeper) Undelegate(
|
||||
ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, sharesAmount sdk.Dec,
|
||||
) (time.Time, error) {
|
||||
|
||||
validator, found := k.GetValidator(ctx, valAddr)
|
||||
if !found {
|
||||
return time.Time{}, types.ErrNoDelegatorForAddress
|
||||
@ -694,10 +709,9 @@ func (k Keeper) CompleteUnbonding(ctx sdk.Context, delAddr sdk.AccAddress, valAd
|
||||
// track undelegation only when remaining or truncated shares are non-zero
|
||||
if !entry.Balance.IsZero() {
|
||||
amt := sdk.NewCoin(bondDenom, entry.Balance)
|
||||
err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(
|
||||
if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(
|
||||
ctx, types.NotBondedPoolName, ubd.DelegatorAddress, sdk.NewCoins(amt),
|
||||
)
|
||||
if err != nil {
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@ -720,7 +734,6 @@ func (k Keeper) CompleteUnbonding(ctx sdk.Context, delAddr sdk.AccAddress, valAd
|
||||
func (k Keeper) BeginRedelegation(
|
||||
ctx sdk.Context, delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress, sharesAmount sdk.Dec,
|
||||
) (completionTime time.Time, err error) {
|
||||
|
||||
if bytes.Equal(valSrcAddr, valDstAddr) {
|
||||
return time.Time{}, types.ErrSelfRedelegation
|
||||
}
|
||||
@ -770,6 +783,7 @@ func (k Keeper) BeginRedelegation(
|
||||
height, completionTime, returnAmount, sharesAmount, sharesCreated,
|
||||
)
|
||||
k.InsertRedelegationQueue(ctx, red, completionTime)
|
||||
|
||||
return completionTime, nil
|
||||
}
|
||||
|
||||
@ -779,7 +793,6 @@ func (k Keeper) BeginRedelegation(
|
||||
func (k Keeper) CompleteRedelegation(
|
||||
ctx sdk.Context, delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.ValAddress,
|
||||
) (sdk.Coins, error) {
|
||||
|
||||
red, found := k.GetRedelegation(ctx, delAddr, valSrcAddr, valDstAddr)
|
||||
if !found {
|
||||
return nil, types.ErrNoRedelegation
|
||||
@ -818,7 +831,6 @@ func (k Keeper) CompleteRedelegation(
|
||||
func (k Keeper) ValidateUnbondAmount(
|
||||
ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress, amt sdk.Int,
|
||||
) (shares sdk.Dec, err error) {
|
||||
|
||||
validator, found := k.GetValidator(ctx, valAddr)
|
||||
if !found {
|
||||
return shares, types.ErrNoValidatorFound
|
||||
|
||||
@ -16,6 +16,7 @@ func (k Keeper) GetHistoricalInfo(ctx sdk.Context, height int64) (types.Historic
|
||||
}
|
||||
|
||||
hi := types.MustUnmarshalHistoricalInfo(k.cdc, value)
|
||||
|
||||
return hi, true
|
||||
}
|
||||
|
||||
@ -41,6 +42,7 @@ func (k Keeper) DeleteHistoricalInfo(ctx sdk.Context, height int64) {
|
||||
// true, the iterator will close and stop.
|
||||
func (k Keeper) IterateHistoricalInfo(ctx sdk.Context, cb func(types.HistoricalInfo) bool) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.HistoricalInfoKey)
|
||||
defer iterator.Close()
|
||||
|
||||
@ -55,10 +57,12 @@ func (k Keeper) IterateHistoricalInfo(ctx sdk.Context, cb func(types.HistoricalI
|
||||
// GetAllHistoricalInfo returns all stored HistoricalInfo objects.
|
||||
func (k Keeper) GetAllHistoricalInfo(ctx sdk.Context) []types.HistoricalInfo {
|
||||
var infos []types.HistoricalInfo
|
||||
|
||||
k.IterateHistoricalInfo(ctx, func(histInfo types.HistoricalInfo) bool {
|
||||
infos = append(infos, histInfo)
|
||||
return false
|
||||
})
|
||||
|
||||
return infos
|
||||
}
|
||||
|
||||
|
||||
@ -11,7 +11,6 @@ import (
|
||||
|
||||
// RegisterInvariants registers all staking invariants
|
||||
func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) {
|
||||
|
||||
ir.RegisterRoute(types.ModuleName, "module-accounts",
|
||||
ModuleAccountInvariants(k))
|
||||
ir.RegisterRoute(types.ModuleName, "nonnegative-power",
|
||||
@ -24,7 +23,6 @@ func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) {
|
||||
|
||||
// AllInvariants runs all invariants of the staking module.
|
||||
func AllInvariants(k Keeper) sdk.Invariant {
|
||||
|
||||
return func(ctx sdk.Context) (string, bool) {
|
||||
res, stop := ModuleAccountInvariants(k)(ctx)
|
||||
if stop {
|
||||
@ -96,11 +94,12 @@ func ModuleAccountInvariants(k Keeper) sdk.Invariant {
|
||||
// NonNegativePowerInvariant checks that all stored validators have >= 0 power.
|
||||
func NonNegativePowerInvariant(k Keeper) sdk.Invariant {
|
||||
return func(ctx sdk.Context) (string, bool) {
|
||||
var msg string
|
||||
var broken bool
|
||||
var (
|
||||
msg string
|
||||
broken bool
|
||||
)
|
||||
|
||||
iterator := k.ValidatorsPowerStoreIterator(ctx)
|
||||
|
||||
for ; iterator.Valid(); iterator.Next() {
|
||||
validator, found := k.GetValidator(ctx, iterator.Value())
|
||||
if !found {
|
||||
@ -122,6 +121,7 @@ func NonNegativePowerInvariant(k Keeper) sdk.Invariant {
|
||||
}
|
||||
}
|
||||
iterator.Close()
|
||||
|
||||
return sdk.FormatInvariant(types.ModuleName, "nonnegative power", fmt.Sprintf("found invalid validator powers\n%s", msg)), broken
|
||||
}
|
||||
}
|
||||
@ -129,20 +129,26 @@ func NonNegativePowerInvariant(k Keeper) sdk.Invariant {
|
||||
// PositiveDelegationInvariant checks that all stored delegations have > 0 shares.
|
||||
func PositiveDelegationInvariant(k Keeper) sdk.Invariant {
|
||||
return func(ctx sdk.Context) (string, bool) {
|
||||
var msg string
|
||||
var count int
|
||||
var (
|
||||
msg string
|
||||
count int
|
||||
)
|
||||
|
||||
delegations := k.GetAllDelegations(ctx)
|
||||
for _, delegation := range delegations {
|
||||
if delegation.Shares.IsNegative() {
|
||||
count++
|
||||
|
||||
msg += fmt.Sprintf("\tdelegation with negative shares: %+v\n", delegation)
|
||||
}
|
||||
|
||||
if delegation.Shares.IsZero() {
|
||||
count++
|
||||
|
||||
msg += fmt.Sprintf("\tdelegation with zero shares: %+v\n", delegation)
|
||||
}
|
||||
}
|
||||
|
||||
broken := count != 0
|
||||
|
||||
return sdk.FormatInvariant(types.ModuleName, "positive delegations", fmt.Sprintf(
|
||||
@ -155,15 +161,16 @@ func PositiveDelegationInvariant(k Keeper) sdk.Invariant {
|
||||
// amount stored in each validator.
|
||||
func DelegatorSharesInvariant(k Keeper) sdk.Invariant {
|
||||
return func(ctx sdk.Context) (string, bool) {
|
||||
var msg string
|
||||
var broken bool
|
||||
var (
|
||||
msg string
|
||||
broken bool
|
||||
)
|
||||
|
||||
validators := k.GetAllValidators(ctx)
|
||||
for _, validator := range validators {
|
||||
|
||||
valTotalDelShares := validator.GetDelegatorShares()
|
||||
|
||||
totalDelShares := sdk.ZeroDec()
|
||||
|
||||
delegations := k.GetValidatorDelegations(ctx, validator.GetOperator())
|
||||
for _, delegation := range delegations {
|
||||
totalDelShares = totalDelShares.Add(delegation.Shares)
|
||||
@ -176,6 +183,7 @@ func DelegatorSharesInvariant(k Keeper) sdk.Invariant {
|
||||
"\tsum of Delegator.Shares: %v\n", valTotalDelShares, totalDelShares)
|
||||
}
|
||||
}
|
||||
|
||||
return sdk.FormatInvariant(types.ModuleName, "delegator shares", msg), broken
|
||||
}
|
||||
}
|
||||
|
||||
@ -37,7 +37,6 @@ func NewKeeper(
|
||||
cdc codec.Marshaler, key sdk.StoreKey, ak types.AccountKeeper, bk types.BankKeeper,
|
||||
ps paramtypes.Subspace,
|
||||
) Keeper {
|
||||
|
||||
// set KeyTable if it has not already been set
|
||||
if !ps.HasKeyTable() {
|
||||
ps = ps.WithKeyTable(ParamKeyTable())
|
||||
@ -74,7 +73,9 @@ func (k *Keeper) SetHooks(sh types.StakingHooks) *Keeper {
|
||||
if k.hooks != nil {
|
||||
panic("cannot set validator hooks twice")
|
||||
}
|
||||
|
||||
k.hooks = sh
|
||||
|
||||
return k
|
||||
}
|
||||
|
||||
@ -82,12 +83,14 @@ func (k *Keeper) SetHooks(sh types.StakingHooks) *Keeper {
|
||||
func (k Keeper) GetLastTotalPower(ctx sdk.Context) sdk.Int {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
bz := store.Get(types.LastTotalPowerKey)
|
||||
|
||||
if bz == nil {
|
||||
return sdk.ZeroInt()
|
||||
}
|
||||
|
||||
ip := sdk.IntProto{}
|
||||
k.cdc.MustUnmarshalBinaryBare(bz, &ip)
|
||||
|
||||
return ip.Int
|
||||
}
|
||||
|
||||
|
||||
@ -19,8 +19,7 @@ func (k Keeper) GetNotBondedPool(ctx sdk.Context) (notBondedPool authexported.Mo
|
||||
// bondedTokensToNotBonded transfers coins from the bonded to the not bonded pool within staking
|
||||
func (k Keeper) bondedTokensToNotBonded(ctx sdk.Context, tokens sdk.Int) {
|
||||
coins := sdk.NewCoins(sdk.NewCoin(k.BondDenom(ctx), tokens))
|
||||
err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.BondedPoolName, types.NotBondedPoolName, coins)
|
||||
if err != nil {
|
||||
if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.BondedPoolName, types.NotBondedPoolName, coins); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@ -28,8 +27,7 @@ func (k Keeper) bondedTokensToNotBonded(ctx sdk.Context, tokens sdk.Int) {
|
||||
// notBondedTokensToBonded transfers coins from the not bonded to the bonded pool within staking
|
||||
func (k Keeper) notBondedTokensToBonded(ctx sdk.Context, tokens sdk.Int) {
|
||||
coins := sdk.NewCoins(sdk.NewCoin(k.BondDenom(ctx), tokens))
|
||||
err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.NotBondedPoolName, types.BondedPoolName, coins)
|
||||
if err != nil {
|
||||
if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.NotBondedPoolName, types.BondedPoolName, coins); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@ -40,7 +38,9 @@ func (k Keeper) burnBondedTokens(ctx sdk.Context, amt sdk.Int) error {
|
||||
// skip as no coins need to be burned
|
||||
return nil
|
||||
}
|
||||
|
||||
coins := sdk.NewCoins(sdk.NewCoin(k.BondDenom(ctx), amt))
|
||||
|
||||
return k.bankKeeper.BurnCoins(ctx, types.BondedPoolName, coins)
|
||||
}
|
||||
|
||||
@ -50,7 +50,9 @@ func (k Keeper) burnNotBondedTokens(ctx sdk.Context, amt sdk.Int) error {
|
||||
// skip as no coins need to be burned
|
||||
return nil
|
||||
}
|
||||
|
||||
coins := sdk.NewCoins(sdk.NewCoin(k.BondDenom(ctx), amt))
|
||||
|
||||
return k.bankKeeper.BurnCoins(ctx, types.NotBondedPoolName, coins)
|
||||
}
|
||||
|
||||
|
||||
@ -127,6 +127,7 @@ func queryValidatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper)
|
||||
}
|
||||
|
||||
delegations := k.GetValidatorDelegations(ctx, params.ValidatorAddr)
|
||||
|
||||
delegationResps, err := delegationsToDelegationResponses(ctx, k, delegations)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -175,6 +176,7 @@ func queryDelegatorDelegations(ctx sdk.Context, req abci.RequestQuery, k Keeper)
|
||||
|
||||
delegations := k.GetAllDelegatorDelegations(ctx, params.DelegatorAddr)
|
||||
delegationResps, err := delegationsToDelegationResponses(ctx, k, delegations)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -367,9 +369,9 @@ func queryHistoricalInfo(ctx sdk.Context, req abci.RequestQuery, k Keeper) ([]by
|
||||
|
||||
func queryPool(ctx sdk.Context, k Keeper) ([]byte, error) {
|
||||
bondDenom := k.BondDenom(ctx)
|
||||
|
||||
bondedPool := k.GetBondedPool(ctx)
|
||||
notBondedPool := k.GetNotBondedPool(ctx)
|
||||
|
||||
if bondedPool == nil || notBondedPool == nil {
|
||||
return nil, errors.New("pool accounts haven't been set")
|
||||
}
|
||||
@ -418,8 +420,8 @@ func delegationToDelegationResponse(ctx sdk.Context, k Keeper, del types.Delegat
|
||||
func delegationsToDelegationResponses(
|
||||
ctx sdk.Context, k Keeper, delegations types.Delegations,
|
||||
) (types.DelegationResponses, error) {
|
||||
|
||||
resp := make(types.DelegationResponses, len(delegations))
|
||||
|
||||
for i, del := range delegations {
|
||||
delResp, err := delegationToDelegationResponse(ctx, k, del)
|
||||
if err != nil {
|
||||
@ -435,8 +437,8 @@ func delegationsToDelegationResponses(
|
||||
func redelegationsToRedelegationResponses(
|
||||
ctx sdk.Context, k Keeper, redels types.Redelegations,
|
||||
) (types.RedelegationResponses, error) {
|
||||
|
||||
resp := make(types.RedelegationResponses, len(redels))
|
||||
|
||||
for i, redel := range redels {
|
||||
val, found := k.GetValidator(ctx, redel.ValidatorDstAddress)
|
||||
if !found {
|
||||
|
||||
@ -9,11 +9,11 @@ import (
|
||||
func (k Keeper) GetDelegatorValidators(
|
||||
ctx sdk.Context, delegatorAddr sdk.AccAddress, maxRetrieve uint32,
|
||||
) []types.Validator {
|
||||
|
||||
validators := make([]types.Validator, maxRetrieve)
|
||||
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
delegatorPrefixKey := types.GetDelegationsKey(delegatorAddr)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest
|
||||
defer iterator.Close()
|
||||
|
||||
@ -37,7 +37,6 @@ func (k Keeper) GetDelegatorValidators(
|
||||
func (k Keeper) GetDelegatorValidator(
|
||||
ctx sdk.Context, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress,
|
||||
) (validator types.Validator, err error) {
|
||||
|
||||
delegation, found := k.GetDelegation(ctx, delegatorAddr, validatorAddr)
|
||||
if !found {
|
||||
return validator, types.ErrNoDelegation
|
||||
@ -59,10 +58,12 @@ func (k Keeper) GetAllDelegatorDelegations(ctx sdk.Context, delegator sdk.AccAdd
|
||||
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
delegatorPrefixKey := types.GetDelegationsKey(delegator)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) //smallest to largest
|
||||
defer iterator.Close()
|
||||
|
||||
i := 0
|
||||
|
||||
for ; iterator.Valid(); iterator.Next() {
|
||||
delegation := types.MustUnmarshalDelegation(k.cdc, iterator.Value())
|
||||
delegations = append(delegations, delegation)
|
||||
@ -78,6 +79,7 @@ func (k Keeper) GetAllUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAdd
|
||||
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
delegatorPrefixKey := types.GetUBDsKey(delegator)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest
|
||||
defer iterator.Close()
|
||||
|
||||
@ -94,9 +96,9 @@ func (k Keeper) GetAllUnbondingDelegations(ctx sdk.Context, delegator sdk.AccAdd
|
||||
func (k Keeper) GetAllRedelegations(
|
||||
ctx sdk.Context, delegator sdk.AccAddress, srcValAddress, dstValAddress sdk.ValAddress,
|
||||
) []types.Redelegation {
|
||||
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
delegatorPrefixKey := types.GetREDsKey(delegator)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, delegatorPrefixKey) // smallest to largest
|
||||
defer iterator.Close()
|
||||
|
||||
@ -110,6 +112,7 @@ func (k Keeper) GetAllRedelegations(
|
||||
if srcValFilter && !(srcValAddress.Equals(redelegation.ValidatorSrcAddress)) {
|
||||
continue
|
||||
}
|
||||
|
||||
if dstValFilter && !(dstValAddress.Equals(redelegation.ValidatorDstAddress)) {
|
||||
continue
|
||||
}
|
||||
|
||||
@ -44,6 +44,7 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh
|
||||
logger.Error(fmt.Sprintf(
|
||||
"WARNING: Ignored attempt to slash a nonexistent validator with address %s, we recommend you investigate immediately",
|
||||
consAddr))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@ -64,21 +65,18 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh
|
||||
|
||||
switch {
|
||||
case infractionHeight > ctx.BlockHeight():
|
||||
|
||||
// Can't slash infractions in the future
|
||||
panic(fmt.Sprintf(
|
||||
"impossible attempt to slash future infraction at height %d but we are at height %d",
|
||||
infractionHeight, ctx.BlockHeight()))
|
||||
|
||||
case infractionHeight == ctx.BlockHeight():
|
||||
|
||||
// Special-case slash at current height for efficiency - we don't need to look through unbonding delegations or redelegations
|
||||
logger.Info(fmt.Sprintf(
|
||||
"slashing at current height %d, not scanning unbonding delegations & redelegations",
|
||||
infractionHeight))
|
||||
|
||||
case infractionHeight < ctx.BlockHeight():
|
||||
|
||||
// Iterate through unbonding delegations from slashed validator
|
||||
unbondingDelegations := k.GetUnbondingDelegationsFromValidator(ctx, operatorAddress)
|
||||
for _, unbondingDelegation := range unbondingDelegations {
|
||||
@ -86,6 +84,7 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh
|
||||
if amountSlashed.IsZero() {
|
||||
continue
|
||||
}
|
||||
|
||||
remainingSlashAmount = remainingSlashAmount.Sub(amountSlashed)
|
||||
}
|
||||
|
||||
@ -96,6 +95,7 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh
|
||||
if amountSlashed.IsZero() {
|
||||
continue
|
||||
}
|
||||
|
||||
remainingSlashAmount = remainingSlashAmount.Sub(amountSlashed)
|
||||
}
|
||||
}
|
||||
@ -136,7 +136,6 @@ func (k Keeper) Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeigh
|
||||
logger.Info(fmt.Sprintf(
|
||||
"validator %s slashed by slash factor of %s; burned %v tokens",
|
||||
validator.GetOperator(), slashFactor.String(), tokensToBurn))
|
||||
|
||||
}
|
||||
|
||||
// jail a validator
|
||||
@ -162,14 +161,12 @@ func (k Keeper) Unjail(ctx sdk.Context, consAddr sdk.ConsAddress) {
|
||||
// insufficient stake remaining)
|
||||
func (k Keeper) SlashUnbondingDelegation(ctx sdk.Context, unbondingDelegation types.UnbondingDelegation,
|
||||
infractionHeight int64, slashFactor sdk.Dec) (totalSlashAmount sdk.Int) {
|
||||
|
||||
now := ctx.BlockHeader().Time
|
||||
totalSlashAmount = sdk.ZeroInt()
|
||||
burnedAmount := sdk.ZeroInt()
|
||||
|
||||
// perform slashing on all entries within the unbonding delegation
|
||||
for i, entry := range unbondingDelegation.Entries {
|
||||
|
||||
// If unbonding started before this height, stake didn't contribute to infraction
|
||||
if entry.CreationHeight < infractionHeight {
|
||||
continue
|
||||
@ -217,14 +214,12 @@ func (k Keeper) SlashUnbondingDelegation(ctx sdk.Context, unbondingDelegation ty
|
||||
// NOTE this is only slashing for prior infractions from the source validator
|
||||
func (k Keeper) SlashRedelegation(ctx sdk.Context, srcValidator types.Validator, redelegation types.Redelegation,
|
||||
infractionHeight int64, slashFactor sdk.Dec) (totalSlashAmount sdk.Int) {
|
||||
|
||||
now := ctx.BlockHeader().Time
|
||||
totalSlashAmount = sdk.ZeroInt()
|
||||
bondedBurnedAmount, notBondedBurnedAmount := sdk.ZeroInt(), sdk.ZeroInt()
|
||||
|
||||
// perform slashing on all entries within the redelegation
|
||||
for _, entry := range redelegation.Entries {
|
||||
|
||||
// If redelegation started before this height, stake didn't contribute to infraction
|
||||
if entry.CreationHeight < infractionHeight {
|
||||
continue
|
||||
@ -245,11 +240,13 @@ func (k Keeper) SlashRedelegation(ctx sdk.Context, srcValidator types.Validator,
|
||||
if sharesToUnbond.IsZero() {
|
||||
continue
|
||||
}
|
||||
|
||||
delegation, found := k.GetDelegation(ctx, redelegation.DelegatorAddress, redelegation.ValidatorDstAddress)
|
||||
if !found {
|
||||
// If deleted, delegation has zero shares, and we can't unbond any more
|
||||
continue
|
||||
}
|
||||
|
||||
if sharesToUnbond.GT(delegation.Shares) {
|
||||
sharesToUnbond = delegation.Shares
|
||||
}
|
||||
|
||||
@ -20,9 +20,11 @@ func TestingUpdateValidator(keeper Keeper, ctx sdk.Context, validator types.Vali
|
||||
|
||||
// Remove any existing power key for validator.
|
||||
store := ctx.KVStore(keeper.storeKey)
|
||||
deleted := false
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.ValidatorsByPowerIndexKey)
|
||||
defer iterator.Close()
|
||||
deleted := false
|
||||
|
||||
for ; iterator.Valid(); iterator.Next() {
|
||||
valAddr := types.ParseValidatorPowerRankKey(iterator.Key())
|
||||
if bytes.Equal(valAddr, validator.OperatorAddress) {
|
||||
@ -31,17 +33,21 @@ func TestingUpdateValidator(keeper Keeper, ctx sdk.Context, validator types.Vali
|
||||
} else {
|
||||
deleted = true
|
||||
}
|
||||
|
||||
store.Delete(iterator.Key())
|
||||
}
|
||||
}
|
||||
|
||||
keeper.SetValidatorByPowerIndex(ctx, validator)
|
||||
|
||||
if apply {
|
||||
keeper.ApplyAndReturnValidatorSetUpdates(ctx)
|
||||
|
||||
validator, found := keeper.GetValidator(ctx, validator.OperatorAddress)
|
||||
if !found {
|
||||
panic("validator expected but not found")
|
||||
}
|
||||
|
||||
return validator
|
||||
}
|
||||
|
||||
@ -64,5 +70,6 @@ func RandomValidator(r *rand.Rand, keeper Keeper, ctx sdk.Context) (val types.Va
|
||||
}
|
||||
|
||||
i := r.Intn(len(vals))
|
||||
|
||||
return vals[i], true
|
||||
}
|
||||
|
||||
@ -87,7 +87,6 @@ func (k Keeper) BlockValidatorUpdates(ctx sdk.Context) []abci.ValidatorUpdate {
|
||||
// at the previous block height or were removed from the validator set entirely
|
||||
// are returned to Tendermint.
|
||||
func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []abci.ValidatorUpdate) {
|
||||
|
||||
maxValidators := k.GetParams(ctx).MaxValidators
|
||||
totalPower := sdk.ZeroInt()
|
||||
amtFromBondedToNotBonded, amtFromNotBondedToBonded := sdk.ZeroInt(), sdk.ZeroInt()
|
||||
@ -100,11 +99,10 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab
|
||||
// Iterate over validators, highest power to lowest.
|
||||
iterator := k.ValidatorsPowerStoreIterator(ctx)
|
||||
defer iterator.Close()
|
||||
for count := 0; iterator.Valid() && count < int(maxValidators); iterator.Next() {
|
||||
|
||||
for count := 0; iterator.Valid() && count < int(maxValidators); iterator.Next() {
|
||||
// everything that is iterated in this loop is becoming or already a
|
||||
// part of the bonded validator set
|
||||
|
||||
valAddr := sdk.ValAddress(iterator.Value())
|
||||
validator := k.mustGetValidator(ctx, valAddr)
|
||||
|
||||
@ -134,27 +132,27 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab
|
||||
|
||||
// fetch the old power bytes
|
||||
var valAddrBytes [sdk.AddrLen]byte
|
||||
|
||||
copy(valAddrBytes[:], valAddr[:])
|
||||
oldPowerBytes, found := last[valAddrBytes]
|
||||
|
||||
newPower := validator.ConsensusPower()
|
||||
newPowerBytes := k.cdc.MustMarshalBinaryBare(&gogotypes.Int64Value{Value: newPower})
|
||||
|
||||
// update the validator set if power has changed
|
||||
if !found || !bytes.Equal(oldPowerBytes, newPowerBytes) {
|
||||
updates = append(updates, validator.ABCIValidatorUpdate())
|
||||
|
||||
k.SetLastValidatorPower(ctx, valAddr, newPower)
|
||||
}
|
||||
|
||||
delete(last, valAddrBytes)
|
||||
|
||||
count++
|
||||
|
||||
totalPower = totalPower.Add(sdk.NewInt(newPower))
|
||||
}
|
||||
|
||||
noLongerBonded := sortNoLongerBonded(last)
|
||||
for _, valAddrBytes := range noLongerBonded {
|
||||
|
||||
validator := k.mustGetValidator(ctx, sdk.ValAddress(valAddrBytes))
|
||||
validator = k.bondedToUnbonding(ctx, validator)
|
||||
amtFromBondedToNotBonded = amtFromBondedToNotBonded.Add(validator.GetTokens())
|
||||
@ -174,8 +172,7 @@ func (k Keeper) ApplyAndReturnValidatorSetUpdates(ctx sdk.Context) (updates []ab
|
||||
k.notBondedTokensToBonded(ctx, amtFromNotBondedToBonded.Sub(amtFromBondedToNotBonded))
|
||||
case amtFromNotBondedToBonded.LT(amtFromBondedToNotBonded):
|
||||
k.bondedTokensToNotBonded(ctx, amtFromBondedToNotBonded.Sub(amtFromNotBondedToBonded))
|
||||
default:
|
||||
// equal amounts of tokens; no update required
|
||||
default: // equal amounts of tokens; no update required
|
||||
}
|
||||
|
||||
// set total power on lookup index if there are any updates
|
||||
@ -192,6 +189,7 @@ func (k Keeper) bondedToUnbonding(ctx sdk.Context, validator types.Validator) ty
|
||||
if !validator.IsBonded() {
|
||||
panic(fmt.Sprintf("bad state transition bondedToUnbonding, validator: %v\n", validator))
|
||||
}
|
||||
|
||||
return k.beginUnbondingValidator(ctx, validator)
|
||||
}
|
||||
|
||||
@ -199,6 +197,7 @@ func (k Keeper) unbondingToBonded(ctx sdk.Context, validator types.Validator) ty
|
||||
if !validator.IsUnbonding() {
|
||||
panic(fmt.Sprintf("bad state transition unbondingToBonded, validator: %v\n", validator))
|
||||
}
|
||||
|
||||
return k.bondValidator(ctx, validator)
|
||||
}
|
||||
|
||||
@ -206,6 +205,7 @@ func (k Keeper) unbondedToBonded(ctx sdk.Context, validator types.Validator) typ
|
||||
if !validator.IsUnbonded() {
|
||||
panic(fmt.Sprintf("bad state transition unbondedToBonded, validator: %v\n", validator))
|
||||
}
|
||||
|
||||
return k.bondValidator(ctx, validator)
|
||||
}
|
||||
|
||||
@ -214,6 +214,7 @@ func (k Keeper) UnbondingToUnbonded(ctx sdk.Context, validator types.Validator)
|
||||
if !validator.IsUnbonding() {
|
||||
panic(fmt.Sprintf("bad state transition unbondingToBonded, validator: %v\n", validator))
|
||||
}
|
||||
|
||||
return k.completeUnbondingValidator(ctx, validator)
|
||||
}
|
||||
|
||||
@ -294,6 +295,7 @@ func (k Keeper) beginUnbondingValidator(ctx sdk.Context, validator types.Validat
|
||||
func (k Keeper) completeUnbondingValidator(ctx sdk.Context, validator types.Validator) types.Validator {
|
||||
validator = validator.UpdateStatus(sdk.Unbonded)
|
||||
k.SetValidator(ctx, validator)
|
||||
|
||||
return validator
|
||||
}
|
||||
|
||||
@ -303,6 +305,7 @@ type validatorsByAddr map[[sdk.AddrLen]byte][]byte
|
||||
// get the last validator set
|
||||
func (k Keeper) getLastValidatorsByAddr(ctx sdk.Context) validatorsByAddr {
|
||||
last := make(validatorsByAddr)
|
||||
|
||||
iterator := k.LastValidatorsIterator(ctx)
|
||||
defer iterator.Close()
|
||||
|
||||
@ -314,6 +317,7 @@ func (k Keeper) getLastValidatorsByAddr(ctx sdk.Context) validatorsByAddr {
|
||||
last[valAddr] = make([]byte, len(powerBytes))
|
||||
copy(last[valAddr], powerBytes)
|
||||
}
|
||||
|
||||
return last
|
||||
}
|
||||
|
||||
@ -323,6 +327,7 @@ func sortNoLongerBonded(last validatorsByAddr) [][]byte {
|
||||
// sort the map keys for determinism
|
||||
noLongerBonded := make([][]byte, len(last))
|
||||
index := 0
|
||||
|
||||
for valAddrBytes := range last {
|
||||
valAddr := make([]byte, sdk.AddrLen)
|
||||
copy(valAddr, valAddrBytes[:])
|
||||
@ -334,5 +339,6 @@ func sortNoLongerBonded(last validatorsByAddr) [][]byte {
|
||||
// -1 means strictly less than
|
||||
return bytes.Compare(noLongerBonded[i], noLongerBonded[j]) == -1
|
||||
})
|
||||
|
||||
return noLongerBonded
|
||||
}
|
||||
|
||||
@ -30,6 +30,7 @@ func newCachedValidator(val types.Validator, marshalled string) cachedValidator
|
||||
// get a single validator
|
||||
func (k Keeper) GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator types.Validator, found bool) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
value := store.Get(types.GetValidatorKey(addr))
|
||||
if value == nil {
|
||||
return validator, false
|
||||
@ -41,6 +42,7 @@ func (k Keeper) GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator ty
|
||||
valToReturn := val.val
|
||||
// Doesn't mutate the cache's value
|
||||
valToReturn.OperatorAddress = addr
|
||||
|
||||
return valToReturn, true
|
||||
}
|
||||
|
||||
@ -57,6 +59,7 @@ func (k Keeper) GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator ty
|
||||
}
|
||||
|
||||
validator = types.MustUnmarshalValidator(k.cdc, value)
|
||||
|
||||
return validator, true
|
||||
}
|
||||
|
||||
@ -65,16 +68,19 @@ func (k Keeper) mustGetValidator(ctx sdk.Context, addr sdk.ValAddress) types.Val
|
||||
if !found {
|
||||
panic(fmt.Sprintf("validator record not found for address: %X\n", addr))
|
||||
}
|
||||
|
||||
return validator
|
||||
}
|
||||
|
||||
// get a single validator by consensus address
|
||||
func (k Keeper) GetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAddress) (validator types.Validator, found bool) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
opAddr := store.Get(types.GetValidatorByConsAddrKey(consAddr))
|
||||
if opAddr == nil {
|
||||
return validator, false
|
||||
}
|
||||
|
||||
return k.GetValidator(ctx, opAddr)
|
||||
}
|
||||
|
||||
@ -83,6 +89,7 @@ func (k Keeper) mustGetValidatorByConsAddr(ctx sdk.Context, consAddr sdk.ConsAdd
|
||||
if !found {
|
||||
panic(fmt.Errorf("validator with consensus-Address %s not found", consAddr))
|
||||
}
|
||||
|
||||
return validator
|
||||
}
|
||||
|
||||
@ -105,6 +112,7 @@ func (k Keeper) SetValidatorByPowerIndex(ctx sdk.Context, validator types.Valida
|
||||
if validator.Jailed {
|
||||
return
|
||||
}
|
||||
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
store.Set(types.GetValidatorsByPowerIndexKey(validator), validator.OperatorAddress)
|
||||
}
|
||||
@ -124,33 +132,33 @@ func (k Keeper) SetNewValidatorByPowerIndex(ctx sdk.Context, validator types.Val
|
||||
// Update the tokens of an existing validator, update the validators power index key
|
||||
func (k Keeper) AddValidatorTokensAndShares(ctx sdk.Context, validator types.Validator,
|
||||
tokensToAdd sdk.Int) (valOut types.Validator, addedShares sdk.Dec) {
|
||||
|
||||
k.DeleteValidatorByPowerIndex(ctx, validator)
|
||||
validator, addedShares = validator.AddTokensFromDel(tokensToAdd)
|
||||
k.SetValidator(ctx, validator)
|
||||
k.SetValidatorByPowerIndex(ctx, validator)
|
||||
|
||||
return validator, addedShares
|
||||
}
|
||||
|
||||
// Update the tokens of an existing validator, update the validators power index key
|
||||
func (k Keeper) RemoveValidatorTokensAndShares(ctx sdk.Context, validator types.Validator,
|
||||
sharesToRemove sdk.Dec) (valOut types.Validator, removedTokens sdk.Int) {
|
||||
|
||||
k.DeleteValidatorByPowerIndex(ctx, validator)
|
||||
validator, removedTokens = validator.RemoveDelShares(sharesToRemove)
|
||||
k.SetValidator(ctx, validator)
|
||||
k.SetValidatorByPowerIndex(ctx, validator)
|
||||
|
||||
return validator, removedTokens
|
||||
}
|
||||
|
||||
// Update the tokens of an existing validator, update the validators power index key
|
||||
func (k Keeper) RemoveValidatorTokens(ctx sdk.Context,
|
||||
validator types.Validator, tokensToRemove sdk.Int) types.Validator {
|
||||
|
||||
k.DeleteValidatorByPowerIndex(ctx, validator)
|
||||
validator = validator.RemoveTokens(tokensToRemove)
|
||||
k.SetValidator(ctx, validator)
|
||||
k.SetValidatorByPowerIndex(ctx, validator)
|
||||
|
||||
return validator
|
||||
}
|
||||
|
||||
@ -158,7 +166,6 @@ func (k Keeper) RemoveValidatorTokens(ctx sdk.Context,
|
||||
// An error is returned if the new commission rate is invalid.
|
||||
func (k Keeper) UpdateValidatorCommission(ctx sdk.Context,
|
||||
validator types.Validator, newRate sdk.Dec) (types.Commission, error) {
|
||||
|
||||
commission := validator.Commission
|
||||
blockTime := ctx.BlockHeader().Time
|
||||
|
||||
@ -175,7 +182,6 @@ func (k Keeper) UpdateValidatorCommission(ctx sdk.Context,
|
||||
// remove the validator record and associated indexes
|
||||
// except for the bonded validator index which is only handled in ApplyAndReturnTendermintUpdates
|
||||
func (k Keeper) RemoveValidator(ctx sdk.Context, address sdk.ValAddress) {
|
||||
|
||||
// first retrieve the old validator record
|
||||
validator, found := k.GetValidator(ctx, address)
|
||||
if !found {
|
||||
@ -185,9 +191,11 @@ func (k Keeper) RemoveValidator(ctx sdk.Context, address sdk.ValAddress) {
|
||||
if !validator.IsUnbonded() {
|
||||
panic("cannot call RemoveValidator on bonded or unbonding validators")
|
||||
}
|
||||
|
||||
if validator.Tokens.IsPositive() {
|
||||
panic("attempting to remove a validator which still contains tokens")
|
||||
}
|
||||
|
||||
if validator.Tokens.IsPositive() {
|
||||
panic("validator being removed should never have positive tokens")
|
||||
}
|
||||
@ -209,6 +217,7 @@ func (k Keeper) RemoveValidator(ctx sdk.Context, address sdk.ValAddress) {
|
||||
// get the set of all validators with no limits, used during genesis dump
|
||||
func (k Keeper) GetAllValidators(ctx sdk.Context) (validators []types.Validator) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
iterator := sdk.KVStorePrefixIterator(store, types.ValidatorsKey)
|
||||
defer iterator.Close()
|
||||
|
||||
@ -256,6 +265,7 @@ func (k Keeper) GetBondedValidatorsByPower(ctx sdk.Context) []types.Validator {
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
return validators[:i] // trim
|
||||
}
|
||||
|
||||
@ -272,6 +282,7 @@ func (k Keeper) ValidatorsPowerStoreIterator(ctx sdk.Context) sdk.Iterator {
|
||||
// Returns zero if the operator was not a validator last block.
|
||||
func (k Keeper) GetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress) (power int64) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
bz := store.Get(types.GetLastValidatorPowerKey(operator))
|
||||
if bz == nil {
|
||||
return 0
|
||||
@ -279,6 +290,7 @@ func (k Keeper) GetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress)
|
||||
|
||||
intV := gogotypes.Int64Value{}
|
||||
k.cdc.MustUnmarshalBinaryBare(bz, &intV)
|
||||
|
||||
return intV.GetValue()
|
||||
}
|
||||
|
||||
@ -299,19 +311,23 @@ func (k Keeper) DeleteLastValidatorPower(ctx sdk.Context, operator sdk.ValAddres
|
||||
func (k Keeper) LastValidatorsIterator(ctx sdk.Context) (iterator sdk.Iterator) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
iterator = sdk.KVStorePrefixIterator(store, types.LastValidatorPowerKey)
|
||||
|
||||
return iterator
|
||||
}
|
||||
|
||||
// Iterate over last validator powers.
|
||||
func (k Keeper) IterateLastValidatorPowers(ctx sdk.Context, handler func(operator sdk.ValAddress, power int64) (stop bool)) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
iter := sdk.KVStorePrefixIterator(store, types.LastValidatorPowerKey)
|
||||
defer iter.Close()
|
||||
|
||||
for ; iter.Valid(); iter.Next() {
|
||||
addr := sdk.ValAddress(iter.Key()[len(types.LastValidatorPowerKey):])
|
||||
intV := &gogotypes.Int64Value{}
|
||||
|
||||
k.cdc.MustUnmarshalBinaryBare(iter.Value(), intV)
|
||||
|
||||
if handler(addr, intV.GetValue()) {
|
||||
break
|
||||
}
|
||||
@ -331,17 +347,18 @@ func (k Keeper) GetLastValidators(ctx sdk.Context) (validators []types.Validator
|
||||
|
||||
i := 0
|
||||
for ; iterator.Valid(); iterator.Next() {
|
||||
|
||||
// sanity check
|
||||
if i >= int(maxValidators) {
|
||||
panic("more validators than maxValidators found")
|
||||
}
|
||||
|
||||
address := types.AddressFromLastValidatorPowerKey(iterator.Key())
|
||||
validator := k.mustGetValidator(ctx, address)
|
||||
|
||||
validators[i] = validator
|
||||
i++
|
||||
}
|
||||
|
||||
return validators[:i] // trim
|
||||
}
|
||||
|
||||
@ -352,6 +369,7 @@ func (k Keeper) GetLastValidators(ctx sdk.Context) (validators []types.Validator
|
||||
// that expire at a certain time.
|
||||
func (k Keeper) GetValidatorQueueTimeSlice(ctx sdk.Context, timestamp time.Time) []sdk.ValAddress {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
bz := store.Get(types.GetValidatorQueueTimeKey(timestamp))
|
||||
if bz == nil {
|
||||
return []sdk.ValAddress{}
|
||||
@ -359,6 +377,7 @@ func (k Keeper) GetValidatorQueueTimeSlice(ctx sdk.Context, timestamp time.Time)
|
||||
|
||||
va := sdk.ValAddresses{}
|
||||
k.cdc.MustUnmarshalBinaryBare(bz, &va)
|
||||
|
||||
return va.Addresses
|
||||
}
|
||||
|
||||
@ -386,6 +405,7 @@ func (k Keeper) InsertValidatorQueue(ctx sdk.Context, val types.Validator) {
|
||||
func (k Keeper) DeleteValidatorQueue(ctx sdk.Context, val types.Validator) {
|
||||
timeSlice := k.GetValidatorQueueTimeSlice(ctx, val.UnbondingTime)
|
||||
newTimeSlice := []sdk.ValAddress{}
|
||||
|
||||
for _, addr := range timeSlice {
|
||||
if !bytes.Equal(addr, val.OperatorAddress) {
|
||||
newTimeSlice = append(newTimeSlice, addr)
|
||||
@ -424,6 +444,7 @@ func (k Keeper) GetAllMatureValidatorQueue(ctx sdk.Context, currTime time.Time)
|
||||
// Unbonds all the unbonding validators that have finished their unbonding period
|
||||
func (k Keeper) UnbondAllMatureValidatorQueue(ctx sdk.Context) {
|
||||
store := ctx.KVStore(k.storeKey)
|
||||
|
||||
validatorTimesliceIterator := k.ValidatorQueueIterator(ctx, ctx.BlockHeader().Time)
|
||||
defer validatorTimesliceIterator.Close()
|
||||
|
||||
|
||||
@ -155,7 +155,9 @@ func (am AppModule) NewQuerierHandler() sdk.Querier {
|
||||
// no validator updates.
|
||||
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate {
|
||||
var genesisState GenesisState
|
||||
|
||||
cdc.MustUnmarshalJSON(data, &genesisState)
|
||||
|
||||
return InitGenesis(ctx, am.keeper, am.accountKeeper, am.bankKeeper, genesisState)
|
||||
}
|
||||
|
||||
|
||||
@ -18,16 +18,18 @@ func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB tmkv.Pair) string {
|
||||
switch {
|
||||
case bytes.Equal(kvA.Key[:1], types.LastTotalPowerKey):
|
||||
var powerA, powerB sdk.IntProto
|
||||
|
||||
cdc.MustUnmarshalBinaryBare(kvA.Value, &powerA)
|
||||
cdc.MustUnmarshalBinaryBare(kvB.Value, &powerB)
|
||||
return fmt.Sprintf("%v\n%v", powerA, powerB)
|
||||
|
||||
return fmt.Sprintf("%v\n%v", powerA, powerB)
|
||||
case bytes.Equal(kvA.Key[:1], types.ValidatorsKey):
|
||||
var validatorA, validatorB types.Validator
|
||||
|
||||
cdc.MustUnmarshalBinaryBare(kvA.Value, &validatorA)
|
||||
cdc.MustUnmarshalBinaryBare(kvB.Value, &validatorB)
|
||||
return fmt.Sprintf("%v\n%v", validatorA, validatorB)
|
||||
|
||||
return fmt.Sprintf("%v\n%v", validatorA, validatorB)
|
||||
case bytes.Equal(kvA.Key[:1], types.LastValidatorPowerKey),
|
||||
bytes.Equal(kvA.Key[:1], types.ValidatorsByConsAddrKey),
|
||||
bytes.Equal(kvA.Key[:1], types.ValidatorsByPowerIndexKey):
|
||||
@ -35,24 +37,27 @@ func NewDecodeStore(cdc codec.Marshaler) func(kvA, kvB tmkv.Pair) string {
|
||||
|
||||
case bytes.Equal(kvA.Key[:1], types.DelegationKey):
|
||||
var delegationA, delegationB types.Delegation
|
||||
|
||||
cdc.MustUnmarshalBinaryBare(kvA.Value, &delegationA)
|
||||
cdc.MustUnmarshalBinaryBare(kvB.Value, &delegationB)
|
||||
return fmt.Sprintf("%v\n%v", delegationA, delegationB)
|
||||
|
||||
return fmt.Sprintf("%v\n%v", delegationA, delegationB)
|
||||
case bytes.Equal(kvA.Key[:1], types.UnbondingDelegationKey),
|
||||
bytes.Equal(kvA.Key[:1], types.UnbondingDelegationByValIndexKey):
|
||||
var ubdA, ubdB types.UnbondingDelegation
|
||||
|
||||
cdc.MustUnmarshalBinaryBare(kvA.Value, &ubdA)
|
||||
cdc.MustUnmarshalBinaryBare(kvB.Value, &ubdB)
|
||||
return fmt.Sprintf("%v\n%v", ubdA, ubdB)
|
||||
|
||||
return fmt.Sprintf("%v\n%v", ubdA, ubdB)
|
||||
case bytes.Equal(kvA.Key[:1], types.RedelegationKey),
|
||||
bytes.Equal(kvA.Key[:1], types.RedelegationByValSrcIndexKey):
|
||||
var redA, redB types.Redelegation
|
||||
|
||||
cdc.MustUnmarshalBinaryBare(kvA.Value, &redA)
|
||||
cdc.MustUnmarshalBinaryBare(kvB.Value, &redB)
|
||||
return fmt.Sprintf("%v\n%v", redA, redB)
|
||||
|
||||
return fmt.Sprintf("%v\n%v", redA, redB)
|
||||
default:
|
||||
panic(fmt.Sprintf("invalid staking key prefix %X", kvA.Key[:1]))
|
||||
}
|
||||
|
||||
@ -40,19 +40,22 @@ func GetHistEntries(r *rand.Rand) uint32 {
|
||||
// RandomizedGenState generates a random GenesisState for staking
|
||||
func RandomizedGenState(simState *module.SimulationState) {
|
||||
// params
|
||||
var unbondTime time.Duration
|
||||
var (
|
||||
unbondTime time.Duration
|
||||
maxVals uint32
|
||||
histEntries uint32
|
||||
)
|
||||
|
||||
simState.AppParams.GetOrGenerate(
|
||||
simState.Cdc, unbondingTime, &unbondTime, simState.Rand,
|
||||
func(r *rand.Rand) { unbondTime = GenUnbondingTime(r) },
|
||||
)
|
||||
|
||||
var maxVals uint32
|
||||
simState.AppParams.GetOrGenerate(
|
||||
simState.Cdc, maxValidators, &maxVals, simState.Rand,
|
||||
func(r *rand.Rand) { maxVals = GenMaxValidators(r) },
|
||||
)
|
||||
|
||||
var histEntries uint32
|
||||
simState.AppParams.GetOrGenerate(
|
||||
simState.Cdc, historicalEntries, &histEntries, simState.Rand,
|
||||
func(r *rand.Rand) { histEntries = GetHistEntries(r) },
|
||||
@ -61,7 +64,6 @@ func RandomizedGenState(simState *module.SimulationState) {
|
||||
// NOTE: the slashing module need to be defined after the staking module on the
|
||||
// NewSimulationManager constructor for this to work
|
||||
simState.UnbondTime = unbondTime
|
||||
|
||||
params := types.NewParams(simState.UnbondTime, maxVals, 7, histEntries, sdk.DefaultBondDenom)
|
||||
|
||||
// validators & delegations
|
||||
@ -71,6 +73,7 @@ func RandomizedGenState(simState *module.SimulationState) {
|
||||
)
|
||||
|
||||
valAddrs := make([]sdk.ValAddress, simState.NumBonded)
|
||||
|
||||
for i := 0; i < int(simState.NumBonded); i++ {
|
||||
valAddr := sdk.ValAddress(simState.Accounts[i].Address)
|
||||
valAddrs[i] = valAddr
|
||||
@ -88,6 +91,7 @@ func RandomizedGenState(simState *module.SimulationState) {
|
||||
validator.Commission = commission
|
||||
|
||||
delegation := types.NewDelegation(simState.Accounts[i].Address, valAddr, sdk.NewDec(simState.InitialStake))
|
||||
|
||||
validators = append(validators, validator)
|
||||
delegations = append(delegations, delegation)
|
||||
}
|
||||
|
||||
@ -29,7 +29,6 @@ func WeightedOperations(
|
||||
appParams simtypes.AppParams, cdc *codec.Codec, ak types.AccountKeeper,
|
||||
bk types.BankKeeper, k keeper.Keeper,
|
||||
) simulation.WeightedOperations {
|
||||
|
||||
var (
|
||||
weightMsgCreateValidator int
|
||||
weightMsgEditValidator int
|
||||
@ -98,7 +97,6 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k
|
||||
return func(
|
||||
r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,
|
||||
) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {
|
||||
|
||||
simAccount, _ := simtypes.RandomAcc(r, accs)
|
||||
address := sdk.ValAddress(simAccount.Address)
|
||||
|
||||
@ -126,6 +124,7 @@ func SimulateMsgCreateValidator(ak types.AccountKeeper, bk types.BankKeeper, k k
|
||||
spendable := bk.SpendableCoins(ctx, account.GetAddress())
|
||||
|
||||
var fees sdk.Coins
|
||||
|
||||
coins, hasNeg := spendable.SafeSub(sdk.Coins{selfDelegation})
|
||||
if !hasNeg {
|
||||
fees, err = simtypes.RandomFees(r, ctx, coins)
|
||||
@ -177,7 +176,6 @@ func SimulateMsgEditValidator(ak types.AccountKeeper, bk types.BankKeeper, k kee
|
||||
return func(
|
||||
r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,
|
||||
) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {
|
||||
|
||||
if len(k.GetAllValidators(ctx)) == 0 {
|
||||
return simtypes.NoOpMsg(types.ModuleName), nil, nil
|
||||
}
|
||||
@ -244,14 +242,15 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K
|
||||
return func(
|
||||
r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,
|
||||
) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {
|
||||
|
||||
denom := k.GetParams(ctx).BondDenom
|
||||
|
||||
if len(k.GetAllValidators(ctx)) == 0 {
|
||||
return simtypes.NoOpMsg(types.ModuleName), nil, nil
|
||||
}
|
||||
|
||||
simAccount, _ := simtypes.RandomAcc(r, accs)
|
||||
val, ok := keeper.RandomValidator(r, k, ctx)
|
||||
|
||||
if !ok {
|
||||
return simtypes.NoOpMsg(types.ModuleName), nil, nil
|
||||
}
|
||||
@ -276,6 +275,7 @@ func SimulateMsgDelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper.K
|
||||
spendable := bk.SpendableCoins(ctx, account.GetAddress())
|
||||
|
||||
var fees sdk.Coins
|
||||
|
||||
coins, hasNeg := spendable.SafeSub(sdk.Coins{bondAmt})
|
||||
if !hasNeg {
|
||||
fees, err = simtypes.RandomFees(r, ctx, coins)
|
||||
@ -311,14 +311,13 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper
|
||||
return func(
|
||||
r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,
|
||||
) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {
|
||||
|
||||
// get random validator
|
||||
validator, ok := keeper.RandomValidator(r, k, ctx)
|
||||
if !ok {
|
||||
return simtypes.NoOpMsg(types.ModuleName), nil, nil
|
||||
}
|
||||
valAddr := validator.GetOperator()
|
||||
|
||||
valAddr := validator.GetOperator()
|
||||
delegations := k.GetValidatorDelegations(ctx, validator.OperatorAddress)
|
||||
|
||||
// get random delegator from validator
|
||||
@ -349,6 +348,7 @@ func SimulateMsgUndelegate(ak types.AccountKeeper, bk types.BankKeeper, k keeper
|
||||
|
||||
// need to retrieve the simulation account associated with delegation to retrieve PrivKey
|
||||
var simAccount simtypes.Account
|
||||
|
||||
for _, simAcc := range accs {
|
||||
if simAcc.Address.Equals(delAddr) {
|
||||
simAccount = simAcc
|
||||
@ -393,7 +393,6 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k
|
||||
return func(
|
||||
r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string,
|
||||
) (simtypes.OperationMsg, []simtypes.FutureOperation, error) {
|
||||
|
||||
// get random source validator
|
||||
srcVal, ok := keeper.RandomValidator(r, k, ctx)
|
||||
if !ok {
|
||||
@ -416,12 +415,9 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k
|
||||
if !ok {
|
||||
return simtypes.NoOpMsg(types.ModuleName), nil, nil
|
||||
}
|
||||
|
||||
destAddr := destVal.GetOperator()
|
||||
|
||||
if srcAddr.Equals(destAddr) ||
|
||||
destVal.InvalidExRate() ||
|
||||
k.HasMaxRedelegationEntries(ctx, delAddr, srcAddr, destAddr) {
|
||||
|
||||
if srcAddr.Equals(destAddr) || destVal.InvalidExRate() || k.HasMaxRedelegationEntries(ctx, delAddr, srcAddr, destAddr) {
|
||||
return simtypes.NoOpMsg(types.ModuleName), nil, nil
|
||||
}
|
||||
|
||||
@ -451,6 +447,7 @@ func SimulateMsgBeginRedelegate(ak types.AccountKeeper, bk types.BankKeeper, k k
|
||||
|
||||
// need to retrieve the simulation account associated with delegation to retrieve PrivKey
|
||||
var simAccount simtypes.Account
|
||||
|
||||
for _, simAcc := range accs {
|
||||
if simAcc.Address.Equals(delAddr) {
|
||||
simAccount = simAcc
|
||||
|
||||
@ -49,6 +49,7 @@ func MustUnmarshalDelegation(cdc codec.Marshaler, value []byte) Delegation {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return delegation
|
||||
}
|
||||
|
||||
@ -58,7 +59,6 @@ func UnmarshalDelegation(cdc codec.Marshaler, value []byte) (delegation Delegati
|
||||
return delegation, err
|
||||
}
|
||||
|
||||
// nolint - for Delegation
|
||||
func (d Delegation) GetDelegatorAddr() sdk.AccAddress { return d.DelegatorAddress }
|
||||
func (d Delegation) GetValidatorAddr() sdk.ValAddress { return d.ValidatorAddress }
|
||||
func (d Delegation) GetShares() sdk.Dec { return d.Shares }
|
||||
@ -76,6 +76,7 @@ func (d Delegations) String() (out string) {
|
||||
for _, del := range d {
|
||||
out += del.String() + "\n"
|
||||
}
|
||||
|
||||
return strings.TrimSpace(out)
|
||||
}
|
||||
|
||||
@ -104,7 +105,6 @@ func NewUnbondingDelegation(
|
||||
delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress,
|
||||
creationHeight int64, minTime time.Time, balance sdk.Int,
|
||||
) UnbondingDelegation {
|
||||
|
||||
return UnbondingDelegation{
|
||||
DelegatorAddress: delegatorAddr,
|
||||
ValidatorAddress: validatorAddr,
|
||||
@ -136,6 +136,7 @@ func MustUnmarshalUBD(cdc codec.Marshaler, value []byte) UnbondingDelegation {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return ubd
|
||||
}
|
||||
|
||||
@ -158,6 +159,7 @@ func (ubd UnbondingDelegation) String() string {
|
||||
Expected balance: %s`, i, entry.CreationHeight,
|
||||
entry.CompletionTime, entry.Balance)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
@ -168,6 +170,7 @@ func (ubds UnbondingDelegations) String() (out string) {
|
||||
for _, u := range ubds {
|
||||
out += u.String() + "\n"
|
||||
}
|
||||
|
||||
return strings.TrimSpace(out)
|
||||
}
|
||||
|
||||
@ -195,7 +198,6 @@ func NewRedelegation(
|
||||
delegatorAddr sdk.AccAddress, validatorSrcAddr, validatorDstAddr sdk.ValAddress,
|
||||
creationHeight int64, minTime time.Time, balance sdk.Int, sharesDst sdk.Dec,
|
||||
) Redelegation {
|
||||
|
||||
return Redelegation{
|
||||
DelegatorAddress: delegatorAddr,
|
||||
ValidatorSrcAddress: validatorSrcAddr,
|
||||
@ -228,6 +230,7 @@ func MustUnmarshalRED(cdc codec.Marshaler, value []byte) Redelegation {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return red
|
||||
}
|
||||
|
||||
@ -268,6 +271,7 @@ func (d Redelegations) String() (out string) {
|
||||
for _, red := range d {
|
||||
out += red.String() + "\n"
|
||||
}
|
||||
|
||||
return strings.TrimSpace(out)
|
||||
}
|
||||
|
||||
@ -318,6 +322,7 @@ func (d DelegationResponses) String() (out string) {
|
||||
for _, del := range d {
|
||||
out += del.String() + "\n"
|
||||
}
|
||||
|
||||
return strings.TrimSpace(out)
|
||||
}
|
||||
|
||||
@ -407,5 +412,6 @@ func (r RedelegationResponses) String() (out string) {
|
||||
for _, red := range r {
|
||||
out += red.String() + "\n"
|
||||
}
|
||||
|
||||
return strings.TrimSpace(out)
|
||||
}
|
||||
|
||||
@ -45,6 +45,7 @@ func DefaultGenesisState() GenesisState {
|
||||
// genesis state.
|
||||
func GetGenesisStateFromAppState(cdc *codec.Codec, appState map[string]json.RawMessage) GenesisState {
|
||||
var genesisState GenesisState
|
||||
|
||||
if appState[ModuleName] != nil {
|
||||
cdc.MustUnmarshalJSON(appState[ModuleName], &genesisState)
|
||||
}
|
||||
|
||||
@ -13,6 +13,7 @@ import (
|
||||
// it will first sort valset before inclusion into historical info
|
||||
func NewHistoricalInfo(header abci.Header, valSet Validators) HistoricalInfo {
|
||||
sort.Sort(valSet)
|
||||
|
||||
return HistoricalInfo{
|
||||
Header: header,
|
||||
Valset: valSet,
|
||||
@ -30,12 +31,14 @@ func MustUnmarshalHistoricalInfo(cdc codec.Marshaler, value []byte) HistoricalIn
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return hi
|
||||
}
|
||||
|
||||
// UnmarshalHistoricalInfo will unmarshal historical info and return any error
|
||||
func UnmarshalHistoricalInfo(cdc codec.Marshaler, value []byte) (hi HistoricalInfo, err error) {
|
||||
err = cdc.UnmarshalBinaryBare(value, &hi)
|
||||
|
||||
return hi, err
|
||||
}
|
||||
|
||||
@ -44,6 +47,7 @@ func ValidateBasic(hi HistoricalInfo) error {
|
||||
if len(hi.Valset) == 0 {
|
||||
return sdkerrors.Wrap(ErrInvalidHistoricalInfo, "validator set is empty")
|
||||
}
|
||||
|
||||
if !sort.IsSorted(Validators(hi.Valset)) {
|
||||
return sdkerrors.Wrap(ErrInvalidHistoricalInfo, "validator set is not sorted by address")
|
||||
}
|
||||
|
||||
@ -11,7 +11,6 @@ func NewMultiStakingHooks(hooks ...StakingHooks) MultiStakingHooks {
|
||||
return hooks
|
||||
}
|
||||
|
||||
// nolint
|
||||
func (h MultiStakingHooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) {
|
||||
for i := range h {
|
||||
h[i].AfterValidatorCreated(ctx, valAddr)
|
||||
|
||||
@ -22,7 +22,6 @@ const (
|
||||
RouterKey = ModuleName
|
||||
)
|
||||
|
||||
//nolint
|
||||
var (
|
||||
// Keys for store prefixes
|
||||
// Last* values are constant during a block.
|
||||
@ -81,7 +80,6 @@ func GetLastValidatorPowerKey(operator sdk.ValAddress) []byte {
|
||||
// get the power ranking of a validator
|
||||
// NOTE the larger values are of higher value
|
||||
func getValidatorPowerRank(validator Validator) []byte {
|
||||
|
||||
consensusPower := sdk.TokensToConsensusPower(validator.Tokens)
|
||||
consensusPowerBytes := make([]byte, 8)
|
||||
binary.BigEndian.PutUint64(consensusPowerBytes, uint64(consensusPower))
|
||||
@ -94,10 +92,13 @@ func getValidatorPowerRank(validator Validator) []byte {
|
||||
|
||||
key[0] = ValidatorsByPowerIndexKey[0]
|
||||
copy(key[1:powerBytesLen+1], powerBytes)
|
||||
|
||||
operAddrInvr := sdk.CopyBytes(validator.OperatorAddress)
|
||||
|
||||
for i, b := range operAddrInvr {
|
||||
operAddrInvr[i] = ^b
|
||||
}
|
||||
|
||||
copy(key[powerBytesLen+1:], operAddrInvr)
|
||||
|
||||
return key
|
||||
@ -109,10 +110,13 @@ func ParseValidatorPowerRankKey(key []byte) (operAddr []byte) {
|
||||
if len(key) != 1+powerBytesLen+sdk.AddrLen {
|
||||
panic("Invalid validator power rank key length")
|
||||
}
|
||||
|
||||
operAddr = sdk.CopyBytes(key[powerBytesLen+1:])
|
||||
|
||||
for i, b := range operAddr {
|
||||
operAddr[i] = ^b
|
||||
}
|
||||
|
||||
return operAddr
|
||||
}
|
||||
|
||||
@ -157,8 +161,10 @@ func GetUBDKeyFromValIndexKey(indexKey []byte) []byte {
|
||||
if len(addrs) != 2*sdk.AddrLen {
|
||||
panic("unexpected key length")
|
||||
}
|
||||
|
||||
valAddr := addrs[:sdk.AddrLen]
|
||||
delAddr := addrs[sdk.AddrLen:]
|
||||
|
||||
return GetUBDKey(delAddr, valAddr)
|
||||
}
|
||||
|
||||
@ -205,6 +211,7 @@ func GetREDByValSrcIndexKey(delAddr sdk.AccAddress, valSrcAddr, valDstAddr sdk.V
|
||||
copy(key[0:offset], REDSFromValsSrcKey)
|
||||
copy(key[offset:offset+sdk.AddrLen], delAddr.Bytes())
|
||||
copy(key[offset+sdk.AddrLen:offset+2*sdk.AddrLen], valDstAddr.Bytes())
|
||||
|
||||
return key
|
||||
}
|
||||
|
||||
@ -229,6 +236,7 @@ func GetREDKeyFromValSrcIndexKey(indexKey []byte) []byte {
|
||||
if len(indexKey) != 3*sdk.AddrLen+1 {
|
||||
panic("unexpected key length")
|
||||
}
|
||||
|
||||
valSrcAddr := indexKey[1 : sdk.AddrLen+1]
|
||||
delAddr := indexKey[sdk.AddrLen+1 : 2*sdk.AddrLen+1]
|
||||
valDstAddr := indexKey[2*sdk.AddrLen+1 : 3*sdk.AddrLen+1]
|
||||
@ -242,9 +250,11 @@ func GetREDKeyFromValDstIndexKey(indexKey []byte) []byte {
|
||||
if len(indexKey) != 3*sdk.AddrLen+1 {
|
||||
panic("unexpected key length")
|
||||
}
|
||||
|
||||
valDstAddr := indexKey[1 : sdk.AddrLen+1]
|
||||
delAddr := indexKey[sdk.AddrLen+1 : 2*sdk.AddrLen+1]
|
||||
valSrcAddr := indexKey[2*sdk.AddrLen+1 : 3*sdk.AddrLen+1]
|
||||
|
||||
return GetREDKey(delAddr, valSrcAddr, valDstAddr)
|
||||
}
|
||||
|
||||
@ -274,9 +284,7 @@ func GetREDsToValDstIndexKey(valDstAddr sdk.ValAddress) []byte {
|
||||
// gets the prefix keyspace for all redelegations redelegating towards a destination validator
|
||||
// from a particular delegator
|
||||
func GetREDsByDelToValDstIndexKey(delAddr sdk.AccAddress, valDstAddr sdk.ValAddress) []byte {
|
||||
return append(
|
||||
GetREDsToValDstIndexKey(valDstAddr),
|
||||
delAddr.Bytes()...)
|
||||
return append(GetREDsToValDstIndexKey(valDstAddr), delAddr.Bytes()...)
|
||||
}
|
||||
|
||||
//________________________________________________________________________________
|
||||
|
||||
@ -23,7 +23,6 @@ func NewMsgCreateValidator(
|
||||
valAddr sdk.ValAddress, pubKey crypto.PubKey, selfDelegation sdk.Coin,
|
||||
description Description, commission CommissionRates, minSelfDelegation sdk.Int,
|
||||
) MsgCreateValidator {
|
||||
|
||||
var pkStr string
|
||||
if pubKey != nil {
|
||||
pkStr = sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, pubKey)
|
||||
@ -57,6 +56,7 @@ func (msg MsgCreateValidator) GetSigners() []sdk.AccAddress {
|
||||
if !bytes.Equal(msg.DelegatorAddress.Bytes(), msg.ValidatorAddress.Bytes()) {
|
||||
addrs = append(addrs, sdk.AccAddress(msg.ValidatorAddress))
|
||||
}
|
||||
|
||||
return addrs
|
||||
}
|
||||
|
||||
@ -72,30 +72,39 @@ func (msg MsgCreateValidator) ValidateBasic() error {
|
||||
if msg.DelegatorAddress.Empty() {
|
||||
return ErrEmptyDelegatorAddr
|
||||
}
|
||||
|
||||
if msg.ValidatorAddress.Empty() {
|
||||
return ErrEmptyValidatorAddr
|
||||
}
|
||||
|
||||
if !sdk.AccAddress(msg.ValidatorAddress).Equals(msg.DelegatorAddress) {
|
||||
return ErrBadValidatorAddr
|
||||
}
|
||||
|
||||
if msg.Pubkey == "" {
|
||||
return ErrEmptyValidatorPubKey
|
||||
}
|
||||
|
||||
if !msg.Value.IsValid() || !msg.Value.Amount.IsPositive() {
|
||||
return ErrBadDelegationAmount
|
||||
}
|
||||
|
||||
if msg.Description == (Description{}) {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "empty description")
|
||||
}
|
||||
|
||||
if msg.Commission == (CommissionRates{}) {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "empty commission")
|
||||
}
|
||||
|
||||
if err := msg.Commission.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !msg.MinSelfDelegation.IsPositive() {
|
||||
return ErrMinSelfDelegationInvalid
|
||||
}
|
||||
|
||||
if msg.Value.Amount.LT(msg.MinSelfDelegation) {
|
||||
return ErrSelfDelegationBelowMinimum
|
||||
}
|
||||
@ -135,12 +144,15 @@ func (msg MsgEditValidator) ValidateBasic() error {
|
||||
if msg.ValidatorAddress.Empty() {
|
||||
return ErrEmptyValidatorAddr
|
||||
}
|
||||
|
||||
if msg.Description == (Description{}) {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "empty description")
|
||||
}
|
||||
|
||||
if msg.MinSelfDelegation != nil && !msg.MinSelfDelegation.IsPositive() {
|
||||
return ErrMinSelfDelegationInvalid
|
||||
}
|
||||
|
||||
if msg.CommissionRate != nil {
|
||||
if msg.CommissionRate.GT(sdk.OneDec()) || msg.CommissionRate.IsNegative() {
|
||||
return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "commission rate must be between 0 and 1 (inclusive)")
|
||||
@ -181,12 +193,15 @@ func (msg MsgDelegate) ValidateBasic() error {
|
||||
if msg.DelegatorAddress.Empty() {
|
||||
return ErrEmptyDelegatorAddr
|
||||
}
|
||||
|
||||
if msg.ValidatorAddress.Empty() {
|
||||
return ErrEmptyValidatorAddr
|
||||
}
|
||||
|
||||
if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() {
|
||||
return ErrBadDelegationAmount
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -224,15 +239,19 @@ func (msg MsgBeginRedelegate) ValidateBasic() error {
|
||||
if msg.DelegatorAddress.Empty() {
|
||||
return ErrEmptyDelegatorAddr
|
||||
}
|
||||
|
||||
if msg.ValidatorSrcAddress.Empty() {
|
||||
return ErrEmptyValidatorAddr
|
||||
}
|
||||
|
||||
if msg.ValidatorDstAddress.Empty() {
|
||||
return ErrEmptyValidatorAddr
|
||||
}
|
||||
|
||||
if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() {
|
||||
return ErrBadSharesAmount
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -265,11 +284,14 @@ func (msg MsgUndelegate) ValidateBasic() error {
|
||||
if msg.DelegatorAddress.Empty() {
|
||||
return ErrEmptyDelegatorAddr
|
||||
}
|
||||
|
||||
if msg.ValidatorAddress.Empty() {
|
||||
return ErrEmptyValidatorAddr
|
||||
}
|
||||
|
||||
if !msg.Amount.IsValid() || !msg.Amount.Amount.IsPositive() {
|
||||
return ErrBadSharesAmount
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@ -32,7 +32,6 @@ const (
|
||||
DefaultHistoricalEntries uint32 = 100
|
||||
)
|
||||
|
||||
// nolint - Keys for parameter access
|
||||
var (
|
||||
KeyUnbondingTime = []byte("UnbondingTime")
|
||||
KeyMaxValidators = []byte("MaxValidators")
|
||||
@ -44,10 +43,7 @@ var (
|
||||
var _ paramtypes.ParamSet = (*Params)(nil)
|
||||
|
||||
// NewParams creates a new Params instance
|
||||
func NewParams(
|
||||
unbondingTime time.Duration, maxValidators, maxEntries, historicalEntries uint32, bondDenom string,
|
||||
) Params {
|
||||
|
||||
func NewParams(unbondingTime time.Duration, maxValidators, maxEntries, historicalEntries uint32, bondDenom string) Params {
|
||||
return Params{
|
||||
UnbondingTime: unbondingTime,
|
||||
MaxValidators: maxValidators,
|
||||
@ -91,6 +87,7 @@ func MustUnmarshalParams(cdc *codec.Codec, value []byte) Params {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return params
|
||||
}
|
||||
|
||||
@ -100,6 +97,7 @@ func UnmarshalParams(cdc *codec.Codec, value []byte) (params Params, err error)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
@ -108,12 +106,15 @@ func (p Params) Validate() error {
|
||||
if err := validateUnbondingTime(p.UnbondingTime); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := validateMaxValidators(p.MaxValidators); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := validateMaxEntries(p.MaxEntries); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := validateBondDenom(p.BondDenom); err != nil {
|
||||
return err
|
||||
}
|
||||
@ -178,6 +179,7 @@ func validateBondDenom(i interface{}) error {
|
||||
if strings.TrimSpace(v) == "" {
|
||||
return errors.New("bond denom cannot be blank")
|
||||
}
|
||||
|
||||
if err := sdk.ValidateDenom(v); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user