chore: fix godoc comments for functions and structs (#24736)

This commit is contained in:
Alex | Interchain Labs 2025-05-13 09:48:13 -04:00 committed by GitHub
parent bedfc39334
commit a2d6d1f6ac
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
141 changed files with 461 additions and 412 deletions

View File

@ -51,6 +51,9 @@ linters:
rules:
- name: redefines-builtin-id
disabled: true
- name: exported
severity: error
disabled: false
staticcheck:
checks:
- all
@ -59,11 +62,16 @@ linters:
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
rules:
- linters:
- staticcheck
text: 'ST1000:'
- linters:
- revive
text: 'or be unexported' # don't report types that have no comments at all. there are way too many of these.
- linters:
- staticcheck
text: 'ST1003:'
@ -127,6 +135,7 @@ formatters:
gofumpt:
extra-rules: true
exclusions:
generated: lax
paths:
- server/grpc/gogoreflection/fix_registration.go

View File

@ -382,7 +382,7 @@ benchmark:
### Linting ###
###############################################################################
golangci_version=v2.1.5
golangci_version=v2.1.6
lint-install:
@echo "--> Installing golangci-lint $(golangci_version)"

View File

@ -589,6 +589,7 @@ func (app *BaseApp) getBlockGasMeter(ctx sdk.Context) storetypes.GasMeter {
return storetypes.NewInfiniteGasMeter()
}
// getContextForTx retrieves the context for the tx w/ txBytes and other memoized values.
// retrieve the context for the tx w/ txBytes and other memoized values.
func (app *BaseApp) getContextForTx(mode sdk.ExecMode, txBytes []byte) sdk.Context {
app.mu.Lock()

View File

@ -267,7 +267,7 @@ func (app *BaseApp) SetFauxMerkleMode() {
app.fauxMerkleMode = true
}
// SetNotSigverify during simulation testing, transaction signature verification needs to be ignored.
// SetNotSigverifyTx during simulation testing, transaction signature verification needs to be ignored.
func (app *BaseApp) SetNotSigverifyTx() {
app.sigverifyTx = false
}

View File

@ -294,7 +294,7 @@ func (ctx Context) WithAux(isAux bool) Context {
return ctx
}
// WithLedgerHasProto returns the context with the provided boolean value, indicating
// WithLedgerHasProtobuf returns the context with the provided boolean value, indicating
// whether the target Ledger application can support Protobuf payloads.
func (ctx Context) WithLedgerHasProtobuf(val bool) Context {
ctx.LedgerHasProtobuf = val

View File

@ -18,7 +18,6 @@ const (
DefaultGasLimit = 200000
GasFlagAuto = "auto"
// DefaultKeyringBackend
DefaultKeyringBackend = keyring.BackendOS
// BroadcastSync defines a tx broadcasting mode where the client waits for

View File

@ -22,7 +22,7 @@ func NewAddNewKey(name, password, mnemonic string, account, index int) AddNewKey
}
}
// RecoverKeyBody recovers a key
// RecoverKey is the needed info to recover a key.
type RecoverKey struct {
Password string `json:"password"`
Mnemonic string `json:"mnemonic"`

View File

@ -33,11 +33,12 @@ func GetChainHeight(clientCtx client.Context) (int64, error) {
//
// To tell which events you want, you need to provide a query. query is a
// string, which has a form: "condition AND condition ..." (no OR at the
// moment). condition has a form: "key operation operand". key is a string with
// a restricted set of possible symbols ( \t\n\r\\()"'=>< are not allowed).
// operation can be "=", "<", "<=", ">", ">=", "CONTAINS" AND "EXISTS". operand
// can be a string (escaped with single quotes), number, date or time.
//
// moment). condition has a form: "key operation operand". key is a string with
// a restricted set of possible symbols ( \t\n\r\\()"'=>< are not allowed).
// operation can be "=", "<", "<=", ">", ">=", "CONTAINS" AND "EXISTS". operand
// can be a string (escaped with single quotes), number, date or time.
//
// Examples:
// tm.event = 'NewBlock' # new blocks
// tm.event = 'CompleteProposal' # node got a complete proposal
@ -67,7 +68,7 @@ func QueryBlocks(clientCtx client.Context, page, limit int, query, orderBy strin
return result, nil
}
// get block by height
// GetBlockByHeight gets a block by height
func GetBlockByHeight(clientCtx client.Context, height *int64) (*cmt.Block, error) {
// get the node
node, err := clientCtx.GetNode()

View File

@ -94,7 +94,7 @@ func QueryEventForTxCmd() *cobra.Command {
return WaitTxCmd()
}
// WaitTx returns a CLI command that waits for a transaction with the given hash to be included in a block.
// WaitTxCmd returns a CLI command that waits for a transaction with the given hash to be included in a block.
func WaitTxCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "wait-tx [hash]",

View File

@ -165,7 +165,7 @@ func (b *AuxTxBuilder) SetExtensionOptions(extOpts ...*codectypes.Any) {
b.auxSignerData.SignDoc.BodyBytes = nil
}
// SetSignature sets the aux signer's signature.
// SetNonCriticalExtensionOptions sets the aux signer's signature.
func (b *AuxTxBuilder) SetNonCriticalExtensionOptions(extOpts ...*codectypes.Any) {
b.checkEmptyFields()

View File

@ -14,7 +14,7 @@ var KeyringContextKey struct{}
var _ Keyring = &KeyringImpl{}
type KeyringImpl struct {
type KeyringImpl struct { //nolint: revive // we can ignore this, as this type is being used
k Keyring
}

View File

@ -19,7 +19,7 @@ import (
// later versions unsupported by the current version can be added
var buildInfo, _ = debug.ReadBuildInfo()
// DescriptorName returns the name of the descriptor in kebab case.
// DescriptorKebabName returns the name of the descriptor in kebab case.
func DescriptorKebabName(descriptor protoreflect.Descriptor) string {
return strcase.ToKebab(string(descriptor.Name()))
}

View File

@ -4,9 +4,10 @@ import (
"github.com/cosmos/gogoproto/proto"
)
// Deprecated: AminoCodec defines a codec that utilizes Codec for both binary and JSON
// AminoCodec defines a codec that utilizes Codec for both binary and JSON
// encoding. Any usage of amino should be done using the LegacyAmino type directly.
// Usage of amino with the Codec type is not well-supported and may be removed in the future.
//
// Deprecated: Usage of amino with the Codec type is not well-supported and may be removed in the future.
type AminoCodec struct {
*LegacyAmino
}

View File

@ -4,9 +4,6 @@ import (
gogoany "github.com/cosmos/gogoproto/types/any"
)
// Deprecated: this is no longer used for anything.
var Debug = true
// AminoUnpacker is an alias for github.com/cosmos/gogoproto/types/any.AminoUnpacker.
type AminoUnpacker = gogoany.AminoUnpacker

View File

@ -148,7 +148,7 @@ func NewMemoryStoreSchema(service core.MemoryStoreService) Schema {
// function. Modules built against versions of the SDK which do not support
// the cosmossdk.io/core/appmodule APIs should use this method.
// Ex:
//
// NewSchemaFromAccessor(func(ctx context.Context) store.KVStore {
// return sdk.UnwrapSDKContext(ctx).KVStore(kvStoreKey)
// }

View File

@ -61,7 +61,7 @@ type VoteInfos interface {
Get(int) VoteInfo
}
// BlockIdFlag indicates which BlockID the signature is for
// BlockIDFlag indicates which BlockID the signature is for
type BlockIDFlag int32
const (

View File

@ -37,7 +37,7 @@ type Manager interface {
EmitNonConsensus(ctx context.Context, event protoiface.MessageV1) error
}
// KVEventAttribute is a kv-pair event attribute.
// Attribute is a kv-pair event attribute.
type Attribute struct {
Key, Value string
}

View File

@ -62,7 +62,7 @@ var BcryptSecurityParameter uint32 = 12
//-----------------------------------------------------------------
// add armor
// Armor the InfoBytes
// ArmorInfoBytes returns the info from info bytes.
func ArmorInfoBytes(bz []byte) string {
header := map[string]string{
headerType: "Info",
@ -72,7 +72,7 @@ func ArmorInfoBytes(bz []byte) string {
return EncodeArmor(blockTypeKeyInfo, header, bz)
}
// Armor the PubKeyBytes
// ArmorPubKeyBytes return the pubkey from info bytes.
func ArmorPubKeyBytes(bz []byte, algo string) string {
header := map[string]string{
headerVersion: "0.0.1",
@ -87,7 +87,7 @@ func ArmorPubKeyBytes(bz []byte, algo string) string {
//-----------------------------------------------------------------
// remove armor
// Unarmor the InfoBytes
// UnarmorInfoBytes returns the info bytes from an armored string.
func UnarmorInfoBytes(armorStr string) ([]byte, error) {
bz, header, err := unarmorBytes(armorStr, blockTypeKeyInfo)
if err != nil {
@ -142,7 +142,7 @@ func unarmorBytes(armorStr, blockType string) (bz []byte, header map[string]stri
//-----------------------------------------------------------------
// encrypt/decrypt with armor
// Encrypt and armor the private key.
// EncryptArmorPrivKey encrypts and armors the private key.
func EncryptArmorPrivKey(privKey cryptotypes.PrivKey, passphrase, algo string) string {
saltBytes, encBytes := encryptPrivKey(privKey, passphrase)
header := map[string]string{

View File

@ -105,7 +105,7 @@ type Keyring interface {
Migrator
}
type KeyringWithDB interface {
type KeyringWithDB interface { //nolint: revive // we can ignore this, as this type is being used
Keyring
// Get the db keyring used in the keystore.

View File

@ -15,6 +15,7 @@ import (
)
// Linux-only backend options.
const BackendKeyctl = "keyctl"
func KeyctlScopeUser(options *Options) { setKeyctlScope(options, "user") }
@ -25,17 +26,17 @@ func KeyctlScopeThread(options *Options) { setKeyctlScope(options, "thread"
// Options define the options of the Keyring.
type Options struct {
// supported signing algorithms for keyring
// SupportedAlgos is the supported signing algorithms for keyring
SupportedAlgos SigningAlgoList
// supported signing algorithms for Ledger
// SupportedAlgosLedger is the supported signing algorithms for Ledger
SupportedAlgosLedger SigningAlgoList
// define Ledger Derivation function
// LedgerDerivation defines the Ledger Derivation function
LedgerDerivation func() (ledger.SECP256K1, error)
// define Ledger key generation function
// LedgerCreateKey defines the Ledger key generation function
LedgerCreateKey func([]byte) types.PubKey
// define Ledger app name
// LedgerAppName defines Ledger app name
LedgerAppName string
// indicate whether Ledger should skip DER Conversion on signature,
// LedgerSigSkipDERConv indicates whether Ledger should skip DER Conversion on signature,
// depending on which format (DER or BER) the Ledger app returns signatures
LedgerSigSkipDERConv bool
// KeyctlScope defines the scope of the keyctl's keyring.

View File

@ -11,7 +11,9 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
// Deprecated: LegacyInfo is the publicly exposed information about a keypair
// LegacyInfo is the publicly exposed information about a keypair
//
// Deprecated: not to be used, but kept for backwards compatibility.
type LegacyInfo interface {
// Human-readable type for key listing
GetType() KeyType
@ -167,7 +169,7 @@ type multisigPubKeyInfo struct {
Weight uint `json:"weight"`
}
// multiInfo is the public information about a multisig key
// LegacyMultiInfo is the public information about a multisig key
type LegacyMultiInfo struct {
Name string `json:"name"`
PubKey cryptotypes.PubKey `json:"pubkey"`
@ -206,7 +208,7 @@ func (i LegacyMultiInfo) GetAddress() sdk.AccAddress {
return i.PubKey.Address().Bytes()
}
// GetPath implements Info interface
// GetAlgo implements Info interface
func (i LegacyMultiInfo) GetAlgo() hd.PubKeyType {
return hd.MultiType
}
@ -223,7 +225,6 @@ func (i LegacyMultiInfo) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error
return codectypes.UnpackInterfaces(multiPK, unpacker)
}
// encoding info
func MarshalInfo(i LegacyInfo) []byte {
return legacy.Cdc.MustMarshalLengthPrefixed(i)
}

View File

@ -32,7 +32,7 @@ var ErrMismatchedHashAndPassword = errors.New("crypto/bcrypt: hashedPassword is
// be a bcrypt hash.
var ErrHashTooShort = errors.New("crypto/bcrypt: hashedSecret too short to be a bcrypted password")
// The error returned from CompareHashAndPassword when a hash was created with
// HashVersionTooNewError is the error returned from CompareHashAndPassword when a hash was created with
// a bcrypt algorithm newer than this implementation.
type HashVersionTooNewError byte
@ -40,7 +40,7 @@ func (hv HashVersionTooNewError) Error() string {
return fmt.Sprintf("crypto/bcrypt: bcrypt algorithm version '%c' requested is newer than current version '%c'", byte(hv), majorVersion)
}
// The error returned from CompareHashAndPassword when a hash starts with something other than '$'
// InvalidHashPrefixError is the error returned from CompareHashAndPassword when a hash starts with something other than '$'
type InvalidHashPrefixError byte
func (ih InvalidHashPrefixError) Error() string {

View File

@ -26,7 +26,7 @@ const (
PubKeySize = 32
// PrivKeySize is the size, in bytes, of private keys as used in this package.
PrivKeySize = 64
// Size of an Edwards25519 signature. Namely the size of a compressed
// SignatureSize is the size of an Edwards25519 signature. Namely the size of a compressed
// Edwards25519 point, and a field element. Both of which are 32 bytes.
SignatureSize = 64
// SeedSize is the size, in bytes, of private key seeds. These are the

View File

@ -21,7 +21,7 @@ func (privKey *PrivKey) Sign(msg []byte) ([]byte, error) {
return sig[1:], nil
}
// VerifyBytes verifies a signature of the form R || S.
// VerifySignature verifies a signature of the form R || S.
// It rejects signatures which are not in lower-S form.
func (pubKey *PubKey) VerifySignature(msg, sigStr []byte) bool {
if len(sigStr) != 64 {

View File

@ -29,7 +29,7 @@ func init() {
initOptionsDefault()
}
type LedgerSECP256K1Mock struct{}
type LedgerSECP256K1Mock struct{} //nolint: revive // we can ignore this, as this type is being used
func (mock LedgerSECP256K1Mock) Close() error {
return nil

View File

@ -30,11 +30,11 @@ type (
// SECP256K1 reflects an interface a Ledger API must implement for SECP256K1
SECP256K1 interface {
Close() error
// Returns an uncompressed pubkey
// GetPublicKeySECP256K1 returns an uncompressed pubkey
GetPublicKeySECP256K1([]uint32) ([]byte, error)
// Returns a compressed pubkey and bech32 address (requires user confirmation)
// GetAddressPubKeySECP256K1 returns a compressed pubkey and bech32 address (requires user confirmation)
GetAddressPubKeySECP256K1([]uint32, string) ([]byte, string, error)
// Signs a message (requires user confirmation)
// SignSECP256K1 signs a message (requires user confirmation)
// The last byte denotes the SIGN_MODE to be used by Ledger: 0 for
// LEGACY_AMINO_JSON, 1 for TEXTUAL. It corresponds to the P2 value
// in https://github.com/cosmos/ledger-cosmos/blob/main/docs/APDUSPEC.md
@ -70,22 +70,22 @@ func initOptionsDefault() {
options.skipDERConversion = false
}
// Set the discoverLedger function to use a different Ledger derivation
// SetDiscoverLedger sets the discoverLedger function to use a different Ledger derivation
func SetDiscoverLedger(fn discoverLedgerFn) {
options.discoverLedger = fn
}
// Set the createPubkey function to use a different public key
// SetCreatePubkey sets the createPubkey function to use a different public key
func SetCreatePubkey(fn createPubkeyFn) {
options.createPubkey = fn
}
// Set the Ledger app name to use a different app name
// SetAppName sets the Ledger app name to use a different app name
func SetAppName(appName string) {
options.appName = appName
}
// Set the DER Conversion requirement to true (false by default)
// SetSkipDERConversion sets the DER Conversion requirement to true (false by default)
func SetSkipDERConversion() {
options.skipDERConversion = true
}

View File

@ -17,6 +17,8 @@ const (
var ErrCiphertextDecrypt = errors.New("ciphertext decryption failed")
// EncryptSymmetric encrypts the given plaintext with the given secret. The
//
// secret must be 32 bytes long. Use something like Sha256(Bcrypt(passphrase))
// The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext.
func EncryptSymmetric(plaintext, secret []byte) (ciphertext []byte) {
@ -34,6 +36,8 @@ func EncryptSymmetric(plaintext, secret []byte) (ciphertext []byte) {
return ciphertext
}
// DecryptSymmetric decrypts the given ciphertext with the given secret. The
//
// secret must be 32 bytes long. Use something like Sha256(Bcrypt(passphrase))
// The ciphertext is (secretbox.Overhead + 24) bytes longer than the plaintext.
func DecryptSymmetric(ciphertext, secret []byte) (plaintext []byte, err error) {

View File

@ -34,12 +34,12 @@ func NewEventManager(ctx context.Context) event.Manager {
// Emit emits an typed event that is defined in the protobuf file.
// In the future these events will be added to consensus.
func (e Events) Emit(ctx context.Context, event protoiface.MessageV1) error {
func (e Events) Emit(_ context.Context, event protoiface.MessageV1) error {
return e.EmitTypedEvent(event)
}
// EmitKV emits a key value pair event.
func (e Events) EmitKV(ctx context.Context, eventType string, attrs ...event.Attribute) error {
func (e Events) EmitKV(_ context.Context, eventType string, attrs ...event.Attribute) error {
attributes := make([]sdk.Attribute, 0, len(attrs))
for _, attr := range attrs {
@ -50,8 +50,8 @@ func (e Events) EmitKV(ctx context.Context, eventType string, attrs ...event.Att
return nil
}
// Emit emits an typed event that is defined in the protobuf file.
// EmitNonConsensus emits an typed event that is defined in the protobuf file.
// In the future these events will be added to consensus.
func (e Events) EmitNonConsensus(ctx context.Context, event protoiface.MessageV1) error {
func (e Events) EmitNonConsensus(_ context.Context, event protoiface.MessageV1) error {
return e.EmitTypedEvent(event)
}

View File

@ -11,31 +11,31 @@ import (
const ModuleName = "runtime"
// App implements the common methods for a Cosmos SDK-based application
// AppI implements the common methods for a Cosmos SDK-based application
// specific blockchain.
type AppI interface {
// The assigned name of the app.
// Name is the assigned name of the app.
Name() string
// The application types codec.
// LegacyAmino is the application types codec.
// NOTE: This should NOT be sealed before being returned.
LegacyAmino() *codec.LegacyAmino
// Application updates every begin block.
// BeginBlocker is logic run every begin block.
BeginBlocker(ctx sdk.Context) (sdk.BeginBlock, error)
// Application updates every end block.
// EndBlocker is logic run every end block.
EndBlocker(ctx sdk.Context) (sdk.EndBlock, error)
// Application update at chain (i.e app) initialization.
// InitChainer is the application update at chain (i.e app) initialization.
InitChainer(ctx sdk.Context, req *abci.InitChainRequest) (*abci.InitChainResponse, error)
// Loads the app at a given height.
// LoadHeight loads the app at a given height.
LoadHeight(height int64) error
// Exports the state of the application for a genesis file.
// ExportAppStateAndValidators exports the state of the application for a genesis file.
ExportAppStateAndValidators(forZeroHeight bool, jailAllowedAddrs, modulesToExport []string) (types.ExportedApp, error)
// Helper for the simulation framework.
// SimulationManager is a helper for the simulation framework.
SimulationManager() *module.SimulationManager
}

View File

@ -89,13 +89,11 @@ func KVStoreHandler(storeKey storetypes.StoreKey) bam.MsgServiceHandler {
}
}
// basic KV structure
type KV struct {
Key string `json:"key"`
Value string `json:"value"`
}
// What Genesis JSON is formatted as
type GenesisJSON struct {
Values []KV `json:"values"`
}
@ -145,6 +143,7 @@ func AppGenStateEmpty(_ *codec.LegacyAmino, _ genutiltypes.AppGenesis, _ []json.
}
// Manually write the handlers for this custom message
type MsgServer interface {
Test(ctx context.Context, msg *KVStoreTx) (*sdk.Result, error)
}

View File

@ -16,7 +16,6 @@ import (
"github.com/cosmos/cosmos-sdk/x/auth/signing"
)
// An sdk.Tx which is its own sdk.Msg.
type KVStoreTx struct {
key []byte
value []byte
@ -71,7 +70,6 @@ func (msg *KVStoreTx) Equals(key cryptotypes.PubKey) bool {
panic("implement me")
}
// dummy implementation of proto.Message
func (msg *KVStoreTx) Reset() {}
func (msg *KVStoreTx) String() string { return "TODO" }
func (msg *KVStoreTx) ProtoMessage() {}
@ -110,7 +108,6 @@ func (msg *KVStoreTx) GetSignBytes() []byte {
return msg.bytes
}
// Should the app be calling this? Or only handlers?
func (msg *KVStoreTx) ValidateBasic() error {
return nil
}

View File

@ -53,8 +53,9 @@ import (
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
)
// CometBFT full-node start flags
const (
// CometBFT full-node start flags
flagWithComet = "with-comet"
flagAddress = "address"
flagTransport = "transport"
@ -80,10 +81,12 @@ const (
FlagShutdownGrace = "shutdown-grace"
// state sync-related flags
FlagStateSyncSnapshotInterval = "state-sync.snapshot-interval"
FlagStateSyncSnapshotKeepRecent = "state-sync.snapshot-keep-recent"
// api-related flags
FlagAPIEnable = "api.enable"
FlagAPISwagger = "api.swagger"
FlagAPIAddress = "api.address"
@ -94,6 +97,7 @@ const (
FlagAPIEnableUnsafeCORS = "api.enabled-unsafe-cors"
// gRPC-related flags
flagGRPCOnly = "grpc-only"
flagGRPCEnable = "grpc.enable"
flagGRPCAddress = "grpc.address"
@ -101,9 +105,11 @@ const (
flagGRPCSkipCheckHeader = "grpc.skip-check-header"
// mempool flags
FlagMempoolMaxTxs = "mempool.max-txs"
// testnet keys
KeyIsTestnet = "is-testnet"
KeyNewChainID = "new-chain-ID"
KeyNewOpAddr = "new-operator-addr"

View File

@ -44,7 +44,6 @@ import (
// a command's Context.
const ServerContextKey = sdk.ContextKey("server.context")
// server context
type Context struct {
Viper *viper.Viper
Config *cmtcfg.Config
@ -311,7 +310,6 @@ func interceptConfigs(rootViper *viper.Viper, customAppTemplate string, customCo
return conf, nil
}
// add server commands
func AddCommands(rootCmd *cobra.Command, defaultNodeHome string, appCreator types.AppCreator, appExport types.AppExporter, addStartFlags types.ModuleInitFlags) {
cometCmd := &cobra.Command{
Use: "comet",
@ -378,6 +376,8 @@ func AddTestnetCreatorCommand(rootCmd *cobra.Command, appCreator types.AppCreato
rootCmd.AddCommand(testnetCreateCmd)
}
// ExternalIP gets the external IP address of the machine.
//
// https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go
// TODO there must be a better way to get external IP
func ExternalIP() (string, error) {

View File

@ -153,7 +153,7 @@ func (iter *cacheMergeIterator) Error() error {
return nil
}
// If not valid, panics.
// assertValid checks if not valid, panics.
// NOTE: May have side-effect of iterating over cache.
func (iter *cacheMergeIterator) assertValid() {
if err := iter.Error(); err != nil {
@ -161,7 +161,7 @@ func (iter *cacheMergeIterator) assertValid() {
}
}
// Like bytes.Compare but opposite if not ascending.
// compare is like bytes.Compare but opposite if not ascending.
func (iter *cacheMergeIterator) compare(a, b []byte) int {
if iter.ascending {
return bytes.Compare(a, b)
@ -170,7 +170,7 @@ func (iter *cacheMergeIterator) compare(a, b []byte) int {
return bytes.Compare(a, b) * -1
}
// Skip all delete-items from the cache w/ `key < until`. After this function,
// skipCacheDeletes skips all delete-items from the cache w/ `key < until`. After this function,
// current cache item is a non-delete-item, or `until <= key`.
// If the current cache item is not a delete item, does nothing.
// If `until` is nil, there is no limit, and cache may end up invalid.
@ -183,7 +183,7 @@ func (iter *cacheMergeIterator) skipCacheDeletes(until []byte) {
}
}
// Fast forwards cache (or parent+cache in case of deleted items) until current
// skipUntilExistsOrInvalid fast forwards cache (or parent+cache in case of deleted items) until current
// item exists, or until iterator becomes invalid.
// Returns whether the iterator is valid.
func (iter *cacheMergeIterator) skipUntilExistsOrInvalid() bool {

View File

@ -115,7 +115,7 @@ func (store *Store) resetCaches() {
store.sortedCache = internal.NewBTree()
}
// Implements Cachetypes.KVStore.
// Write implements Cachetypes.KVStore.
func (store *Store) Write() {
store.mtx.Lock()
defer store.mtx.Unlock()
@ -292,7 +292,7 @@ const (
const minSortSize = 1024
// Constructs a slice of dirty items, to use w/ memIterator.
// dirtyItems constructs a slice of dirty items, to use w/ memIterator.
func (store *Store) dirtyItems(start, end []byte) {
startStr, endStr := conv.UnsafeBytesToStr(start), conv.UnsafeBytesToStr(end)
if end != nil && startStr > endStr {
@ -394,7 +394,7 @@ func (store *Store) clearUnsortedCacheSubset(unsorted []*kv.Pair, sortState sort
//----------------------------------------
// etc
// Only entrypoint to mutate store.cache.
// setCacheValue is the only entrypoint to mutate store.cache.
// A `nil` value means a deletion.
func (store *Store) setCacheValue(key, value []byte, dirty bool) {
keyStr := conv.UnsafeBytesToStr(key)

View File

@ -126,7 +126,7 @@ func (cms Store) Write() {
}
}
// Implements CacheWrapper.
// CacheWrap implements CacheWrapper, returns the cache multi-store as a CacheWrap.
func (cms Store) CacheWrap() types.CacheWrap {
return cms.CacheMultiStore().(types.CacheWrap)
}
@ -136,7 +136,8 @@ func (cms Store) CacheWrapWithTrace(_ io.Writer, _ types.TraceContext) types.Cac
return cms.CacheWrap()
}
// Implements MultiStore.
// CacheMultiStore implements MultiStore, returns a new CacheMultiStore from the
// underlying CacheMultiStore.
func (cms Store) CacheMultiStore() types.CacheMultiStore {
return newCacheMultiStoreFromCMS(cms)
}

View File

@ -10,7 +10,7 @@ import (
"cosmossdk.io/store/types"
)
// Wrapper type for dbm.Db with implementation of KVStore
// Store is a wrapper type for dbm.Db with implementation of KVStore
type Store struct {
dbm.DB
}

View File

@ -26,12 +26,13 @@ func NewStore(parent types.KVStore, gasMeter types.GasMeter, gasConfig types.Gas
return kvs
}
// Implements Store.
// GetStoreType implements Store, consuming no gas and returning the underlying
// store's type.
func (gs *Store) GetStoreType() types.StoreType {
return gs.parent.GetStoreType()
}
// Implements KVStore.
// Get implements KVStore, consuming gas based on ReadCostFlat and the read per bytes cost.
func (gs *Store) Get(key []byte) (value []byte) {
gs.gasMeter.ConsumeGas(gs.gasConfig.ReadCostFlat, types.GasReadCostFlatDesc)
value = gs.parent.Get(key)
@ -43,7 +44,7 @@ func (gs *Store) Get(key []byte) (value []byte) {
return value
}
// Implements KVStore.
// Set implements KVStore, consuming gas based on WriteCostFlat and the write per bytes cost.
func (gs *Store) Set(key, value []byte) {
types.AssertValidKey(key)
types.AssertValidValue(value)
@ -54,13 +55,13 @@ func (gs *Store) Set(key, value []byte) {
gs.parent.Set(key, value)
}
// Implements KVStore.
// Has implements KVStore, consuming gas based on HasCost.
func (gs *Store) Has(key []byte) bool {
gs.gasMeter.ConsumeGas(gs.gasConfig.HasCost, types.GasHasDesc)
return gs.parent.Has(key)
}
// Implements KVStore.
// Delete implements KVStore consuming gas based on DeleteCost.
func (gs *Store) Delete(key []byte) {
// charge gas to prevent certain attack vectors even though space is being freed
gs.gasMeter.ConsumeGas(gs.gasConfig.DeleteCost, types.GasDeleteDesc)
@ -82,7 +83,7 @@ func (gs *Store) ReverseIterator(start, end []byte) types.Iterator {
return gs.iterator(start, end, false)
}
// Implements KVStore.
// CacheWrap implements KVStore - it PANICS as you cannot cache a GasKVStore.
func (gs *Store) CacheWrap() types.CacheWrap {
panic("cannot CacheWrap a GasKVStore")
}
@ -120,12 +121,12 @@ func newGasIterator(gasMeter types.GasMeter, gasConfig types.GasConfig, parent t
}
}
// Implements Iterator.
// Domain implements Iterator, getting the underlying iterator's domain'.
func (gi *gasIterator) Domain() (start, end []byte) {
return gi.parent.Domain()
}
// Implements Iterator.
// Valid implements Iterator by checking the underlying iterator.
func (gi *gasIterator) Valid() bool {
return gi.parent.Valid()
}
@ -152,7 +153,7 @@ func (gi *gasIterator) Value() (value []byte) {
return value
}
// Implements Iterator.
// Close implements Iterator by closing the underlying iterator.
func (gi *gasIterator) Close() error {
return gi.parent.Close()
}

View File

@ -162,7 +162,7 @@ func (st *Store) SetPruning(_ pruningtypes.PruningOptions) {
panic("cannot set pruning options on an initialized IAVL store")
}
// SetPruning panics as pruning options should be provided at initialization
// GetPruning panics as pruning options should be provided at initialization
// since IAVl accepts pruning options directly.
func (st *Store) GetPruning() pruningtypes.PruningOptions {
panic("cannot get pruning options on an initialized IAVL store")
@ -178,12 +178,12 @@ func (st *Store) GetAllVersions() []int {
return st.tree.AvailableVersions()
}
// Implements Store.
// GetStoreType implements Store, returns StoreTypeIAVL.
func (st *Store) GetStoreType() types.StoreType {
return types.StoreTypeIAVL
}
// Implements Store.
// CacheWrap implements Store, returns a cachewrap around the store.
func (st *Store) CacheWrap() types.CacheWrap {
return cachekv.NewStore(st)
}
@ -193,7 +193,7 @@ func (st *Store) CacheWrapWithTrace(w io.Writer, tc types.TraceContext) types.Ca
return cachekv.NewStore(tracekv.NewStore(st, w, tc))
}
// Implements types.KVStore.
// Set implements types.KVStore, creates a new key/value pair in the underlying IAVL tree.
func (st *Store) Set(key, value []byte) {
types.AssertValidKey(key)
types.AssertValidValue(value)
@ -203,7 +203,7 @@ func (st *Store) Set(key, value []byte) {
}
}
// Implements types.KVStore.
// Get implements types.KVStore.
func (st *Store) Get(key []byte) []byte {
defer st.metrics.MeasureSince("store", "iavl", "get")
value, err := st.tree.Get(key)
@ -213,7 +213,7 @@ func (st *Store) Get(key []byte) []byte {
return value
}
// Implements types.KVStore.
// Has implements types.KVStore, returns true if the key exists in the underlying IAVL tree.
func (st *Store) Has(key []byte) (exists bool) {
defer st.metrics.MeasureSince("store", "iavl", "has")
has, err := st.tree.Has(key)
@ -223,7 +223,7 @@ func (st *Store) Has(key []byte) (exists bool) {
return has
}
// Implements types.KVStore.
// Delete implements types.KVStore, removes the given key from the underlying IAVL tree.
func (st *Store) Delete(key []byte) {
defer st.metrics.MeasureSince("store", "iavl", "delete")
_, _, err := st.tree.Remove(key)
@ -232,7 +232,7 @@ func (st *Store) Delete(key []byte) {
}
}
// DeleteVersionsTo deletes versions upto the given version from the MutableTree. An error
// DeleteVersionsTo deletes versions up to the given version from the MutableTree. An error
// is returned if any single version is invalid or the delete fails. All writes
// happen in a single batch with a single commit.
func (st *Store) DeleteVersionsTo(version int64) error {
@ -245,7 +245,7 @@ func (st *Store) LoadVersionForOverwriting(targetVersion int64) error {
return st.tree.LoadVersionForOverwriting(targetVersion)
}
// Implements types.KVStore.
// Iterator implements types.KVStore, returns an iterator from the underlying IAVL tree.
func (st *Store) Iterator(start, end []byte) types.Iterator {
iterator, err := st.tree.Iterator(start, end, true)
if err != nil {
@ -254,7 +254,7 @@ func (st *Store) Iterator(start, end []byte) types.Iterator {
return iterator
}
// Implements types.KVStore.
// ReverseIterator implements types.KVStore, returns a reverse iterator from the underlying IAVL tree.
func (st *Store) ReverseIterator(start, end []byte) types.Iterator {
iterator, err := st.tree.Iterator(start, end, false)
if err != nil {
@ -269,7 +269,7 @@ func (st *Store) SetInitialVersion(version int64) {
st.tree.SetInitialVersion(uint64(version))
}
// Exports the IAVL store at the given version, returning an iavl.Exporter for the tree.
// Export exports the IAVL store at the given version, returning an iavl.Exporter for the tree.
func (st *Store) Export(version int64) (*iavl.Exporter, error) {
istore, err := st.GetImmutable(version)
if err != nil {

View File

@ -25,7 +25,7 @@ func newMerkleMap() *merkleMap {
}
}
// Set creates a kv.Pair from the provided key and value. The value is hashed prior
// set creates a kv.Pair from the provided key and value. The value is hashed prior
// to creating a kv.Pair. The created kv.Pair is appended to the MerkleMap's slice
// of kv.Pairs. Whenever called, the MerkleMap must be resorted.
func (sm *merkleMap) set(key string, value []byte) {
@ -44,7 +44,7 @@ func (sm *merkleMap) set(key string, value []byte) {
})
}
// Hash returns the merkle root of items sorted by key. Note, it is unstable.
// hash returns the merkle root of items sorted by key. Note, it is unstable.
func (sm *merkleMap) hash() []byte {
sm.sort()
return hashKVPairs(sm.kvs)
@ -120,7 +120,7 @@ func (sm *simpleMap) Sort() {
sm.sorted = true
}
// Returns a copy of sorted KVPairs.
// KVPairs returns a copy of sorted KVPairs.
// NOTE these contain the hashed key and value.
func (sm *simpleMap) KVPairs() kv.Pairs {
sm.Sort()
@ -134,7 +134,7 @@ func (sm *simpleMap) KVPairs() kv.Pairs {
//----------------------------------------
// A local extension to KVPair that can be hashed.
// KVPair is a local extension to KVPair that can be hashed.
// Key and value are length prefixed and concatenated,
// then hashed.
type KVPair kv.Pair

View File

@ -28,7 +28,7 @@ func ConvertExistenceProof(p *cmtprotocrypto.Proof, key, value []byte) (*ics23.E
return proof, nil
}
// this is adapted from merkle/hash.go:leafHash()
// convertLeafOp is adapted from merkle/hash.go:leafHash()
// and merkle/simple_map.go:KVPair.Bytes()
func convertLeafOp() *ics23.LeafOp {
prefix := []byte{0}

View File

@ -31,7 +31,7 @@ func hashFromByteSlices(sha hash.Hash, items [][]byte) []byte {
}
}
// returns tmhash(0x00 || leaf)
// leafHashOpt returns tmhash(0x00 || leaf)
func leafHashOpt(s hash.Hash, leaf []byte) []byte {
s.Reset()
s.Write(leafPrefix)
@ -47,7 +47,7 @@ func innerHashOpt(s hash.Hash, left, right []byte) []byte {
return s.Sum(nil)
}
// returns tmhash(<empty>)
// emptyHash returns tmhash(<empty>)
func emptyHash() []byte {
h := sha256.Sum256([]byte{})
return h[:]

View File

@ -42,12 +42,12 @@ func (s Store) key(key []byte) (res []byte) {
return
}
// Implements Store
// GetStoreType implements Store, returning the parent store's type'
func (s Store) GetStoreType() types.StoreType {
return s.parent.GetStoreType()
}
// Implements CacheWrap
// CacheWrap implements CacheWrap, returning a new CacheWrap with the parent store as the underlying store
func (s Store) CacheWrap() types.CacheWrap {
return cachekv.NewStore(s)
}
@ -57,42 +57,42 @@ func (s Store) CacheWrapWithTrace(w io.Writer, tc types.TraceContext) types.Cach
return cachekv.NewStore(tracekv.NewStore(s, w, tc))
}
// Implements KVStore
// Get implements KVStore, calls Get on the parent store with the key prefixed with the prefix
func (s Store) Get(key []byte) []byte {
res := s.parent.Get(s.key(key))
return res
}
// Implements KVStore
// Has implements KVStore, calls Has on the parent store with the key prefixed with the prefix
func (s Store) Has(key []byte) bool {
return s.parent.Has(s.key(key))
}
// Implements KVStore
// Set implements KVStore, calls Set on the parent store with the key prefixed with the prefix
func (s Store) Set(key, value []byte) {
types.AssertValidKey(key)
types.AssertValidValue(value)
s.parent.Set(s.key(key), value)
}
// Implements KVStore
// Delete implements KVStore, calls delete on the parent store with the key prefixed with the prefix
func (s Store) Delete(key []byte) {
s.parent.Delete(s.key(key))
}
// Implements KVStore
// Iterator implements KVStore
// Check https://github.com/cometbft/cometbft/blob/master/libs/db/prefix_db.go#L106
func (s Store) Iterator(start, end []byte) types.Iterator {
newstart := cloneAppend(s.prefix, start)
newStart := cloneAppend(s.prefix, start)
var newend []byte
var newEnd []byte
if end == nil {
newend = cpIncr(s.prefix)
newEnd = cpIncr(s.prefix)
} else {
newend = cloneAppend(s.prefix, end)
newEnd = cloneAppend(s.prefix, end)
}
iter := s.parent.Iterator(newstart, newend)
iter := s.parent.Iterator(newStart, newEnd)
return newPrefixIterator(s.prefix, start, end, iter)
}
@ -134,17 +134,17 @@ func newPrefixIterator(prefix, start, end []byte, parent types.Iterator) *prefix
}
}
// Implements Iterator
// Domain implements Iterator, returning the start and end keys of the prefixIterator.
func (pi *prefixIterator) Domain() ([]byte, []byte) {
return pi.start, pi.end
}
// Implements Iterator
// Valid implements Iterator, checking if the prefixIterator is valid and if the underlying iterator is valid.
func (pi *prefixIterator) Valid() bool {
return pi.valid && pi.iter.Valid()
}
// Implements Iterator
// Next implements Iterator, moving the underlying iterator to the next key/value pair that starts with the prefix.
func (pi *prefixIterator) Next() {
if !pi.valid {
panic("prefixIterator invalid, cannot call Next()")
@ -156,7 +156,7 @@ func (pi *prefixIterator) Next() {
}
}
// Implements Iterator
// Key implements Iterator, returning the stripped prefix key
func (pi *prefixIterator) Key() (key []byte) {
if !pi.valid {
panic("prefixIterator invalid, cannot call Key()")
@ -177,7 +177,7 @@ func (pi *prefixIterator) Value() []byte {
return pi.iter.Value()
}
// Implements Iterator
// Close implements Iterator, closing the underlying iterator.
func (pi *prefixIterator) Close() error {
return pi.iter.Close()
}
@ -192,7 +192,7 @@ func (pi *prefixIterator) Error() error {
return nil
}
// copied from github.com/cometbft/cometbft/libs/db/prefix_db.go
// stripPrefix is copied from github.com/cometbft/cometbft/libs/db/prefix_db.go
func stripPrefix(key, prefix []byte) []byte {
if len(key) < len(prefix) || !bytes.Equal(key[:len(prefix)], prefix) {
panic("should not happen")
@ -201,7 +201,7 @@ func stripPrefix(key, prefix []byte) []byte {
return key[len(prefix):]
}
// wrapping types.PrefixEndBytes
// cpIncr wraps the bytes in types.PrefixEndBytes
func cpIncr(bz []byte) []byte {
return types.PrefixEndBytes(bz)
}

View File

@ -4,7 +4,6 @@ import (
"cosmossdk.io/store/types"
)
// Import cosmos-sdk/types/store.go for convenience.
type (
Store = types.Store
Committer = types.Committer

View File

@ -17,6 +17,11 @@ func RequireProof(subpath string) bool {
//-----------------------------------------------------------------------------
// DefaultProofRuntime returns a default proof runtime for the rootMultiStore.
//
// The default proof runtime registers the commitment op decoder for IAVL and
// SimpleMerkle commitments.
//
// XXX: This should be managed by the rootMultiStore which may want to register
// more proof ops?
func DefaultProofRuntime() (prt *merkle.ProofRuntime) {

View File

@ -336,7 +336,7 @@ func deleteKVStore(kv types.KVStore) error {
return nil
}
// we simulate move by a copy and delete
// moveKVStoreData implements a move by a copy and delete.
func moveKVStoreData(oldDB, newDB types.KVStore) error {
// we read from one and write to another
itr := oldDB.Iterator(nil, nil)
@ -724,7 +724,7 @@ func (rs *Store) PruneStores(pruningHeight int64) (err error) {
return nil
}
// getStoreByName performs a lookup of a StoreKey given a store name typically
// GetStoreByName performs a lookup of a StoreKey given a store name typically
// provided in a path. The StoreKey is then used to perform a lookup and return
// a Store. If the Store is wrapped in an inter-block cache, it will be unwrapped
// prior to being returned. If the StoreKey does not exist, nil is returned.
@ -1185,7 +1185,7 @@ func GetLatestVersion(db dbm.DB) int64 {
return latestVersion
}
// Commits each store and returns a new commitInfo.
// commitStores commits each store and returns a new commitInfo.
func commitStores(version int64, storeMap map[types.StoreKey]types.CommitKVStore, removalMap map[types.StoreKey]bool) *types.CommitInfo {
storeInfos := make([]types.StoreInfo, 0, len(storeMap))
storeKeys := keysFromStoreKeyMap(storeMap)

View File

@ -91,7 +91,7 @@ func (s *Store) Get(height uint64, format uint32) (*types.Snapshot, error) {
return snapshot, nil
}
// Get fetches the latest snapshot from the database, if any.
// GetLatest fetches the latest snapshot from the database, if any.
func (s *Store) GetLatest() (*types.Snapshot, error) {
iter, err := s.db.ReverseIterator(encodeKey(0, 0), encodeKey(uint64(math.MaxUint64), math.MaxUint32))
if err != nil {

View File

@ -7,7 +7,7 @@ import (
"cosmossdk.io/errors"
)
// Converts an ABCI snapshot to a snapshot. Mainly to decode the SDK metadata.
// SnapshotFromABCI converts an ABCI snapshot to a snapshot. Mainly to decode the SDK metadata.
func SnapshotFromABCI(in *abci.Snapshot) (Snapshot, error) {
snapshot := Snapshot{
Height: in.Height,
@ -22,7 +22,7 @@ func SnapshotFromABCI(in *abci.Snapshot) (Snapshot, error) {
return snapshot, nil
}
// Converts a Snapshot to its ABCI representation. Mainly to encode the SDK metadata.
// ToABCI converts a Snapshot to its ABCI representation. Mainly to encode the SDK metadata.
func (s Snapshot) ToABCI() (abci.Snapshot, error) {
out := abci.Snapshot{
Height: s.Height,

View File

@ -17,7 +17,7 @@ type GRPCClient struct {
client ABCIListenerServiceClient
}
// ListenEndBlock listens to end block request and responses.
// ListenFinalizeBlock listens to end block request and responses.
// In addition, it retrieves a types.Context from a context.Context instance.
// It panics if a types.Context was not properly attached.
// When the node is configured to stop on listening errors,

View File

@ -18,13 +18,13 @@ type Store struct {
dbadapter.Store
}
// Constructs new MemDB adapter
// NewStore constructs new MemDB adapter
func NewStore() *Store {
return &Store{Store: dbadapter.Store{DB: dbm.NewMemDB()}}
}
// Implements CommitStore
// Commit cleans up Store.
// Implements CommitStore
func (ts *Store) Commit() (id types.CommitID) {
ts.Store = dbadapter.Store{DB: dbm.NewMemDB()}
return
@ -38,7 +38,7 @@ func (ts *Store) GetPruning() pruningtypes.PruningOptions {
return pruningtypes.NewPruningOptions(pruningtypes.PruningUndefined)
}
// Implements CommitStore
// LastCommitID implements CommitStore, returns empty CommitID.
func (ts *Store) LastCommitID() types.CommitID {
return types.CommitID{}
}
@ -47,7 +47,7 @@ func (ts *Store) WorkingHash() []byte {
return []byte{}
}
// Implements Store.
// GetStoreType implements Store, returns StoreTypeTransient.
func (ts *Store) GetStoreType() types.StoreType {
return types.StoreTypeTransient
}

View File

@ -19,12 +19,13 @@ type Codec interface {
// in the value pointed to by v.
Unmarshal(bz []byte, ptr proto.Message) error
// Unmarshal parses the data encoded with UnmarshalLengthPrefixed method and stores
// UnmarshalLengthPrefixed parses the data encoded with UnmarshalLengthPrefixed method and stores
// the result in the value pointed to by v.
UnmarshalLengthPrefixed(bz []byte, ptr proto.Message) error
}
// ============= TestCodec =============
// TestCodec defines a codec that utilizes Protobuf for both binary and JSON
// encoding.
type TestCodec struct{}

View File

@ -19,7 +19,7 @@ type Store interface {
CacheWrapper
}
// something that can persist to disk
// Committer is an interface for functionality to persist to disk.
type Committer interface {
Commit() CommitID
LastCommitID() CommitID
@ -31,7 +31,7 @@ type Committer interface {
GetPruning() pruningtypes.PruningOptions
}
// Stores of MultiStore must implement CommitStore.
// CommitStore is an interface for Commit and Store capabilities.
type CommitStore interface {
Committer
Store
@ -146,7 +146,7 @@ type MultiStore interface {
LatestVersion() int64
}
// From MultiStore.CacheMultiStore()....
// CacheMultiStore extends MultiStore with a Write() method.
type CacheMultiStore interface {
MultiStore
Write() // Writes operations to underlying KVStore
@ -319,7 +319,7 @@ func (cid CommitID) String() string {
//----------------------------------------
// Store types
// kind of store
// StoreType is an enum for a kind of store.
type StoreType int
const (
@ -415,7 +415,7 @@ type TransientStoreKey struct {
name string
}
// Constructs new TransientStoreKey
// NewTransientStoreKey constructs new TransientStoreKey
// Must return a pointer according to the ocap principle
func NewTransientStoreKey(name string) *TransientStoreKey {
return &TransientStoreKey{
@ -423,12 +423,12 @@ func NewTransientStoreKey(name string) *TransientStoreKey {
}
}
// Implements StoreKey
// Name implements StoreKey, returning the key name.
func (key *TransientStoreKey) Name() string {
return key.name
}
// Implements StoreKey
// String implements StoreKey, returning a human-readable string representation of the key.
func (key *TransientStoreKey) String() string {
return fmt.Sprintf("TransientStoreKey{%p, %s}", key, key.name)
}

View File

@ -1,9 +1,9 @@
package types
var (
// 128K - 1
// MaxKeyLength is 128K - 1
MaxKeyLength = (1 << 17) - 1
// 2G - 1
// MaxValueLength is 2G - 1
MaxValueLength = (1 << 31) - 1
)

View File

@ -7,7 +7,7 @@ import (
var _ idb.DB = &DBWrapper{}
// DBwrapper is a simple wrapper of dbm.DB that implements the iavl.DB interface.
// DBWrapper is a simple wrapper of dbm.DB that implements the iavl.DB interface.
type DBWrapper struct {
dbm.DB
}

View File

@ -52,7 +52,7 @@ func (s *WithdrawAllTestSuite) TearDownSuite() {
s.network.Cleanup()
}
// This test requires multiple validators, if I add this test to `E2ETestSuite` by increasing
// TestNewWithdrawAllRewardsGenerateOnly requires multiple validators, if I add this test to `E2ETestSuite` by increasing
// `NumValidators` the existing tests are leading to non-determnism so created new suite for this test.
func (s *WithdrawAllTestSuite) TestNewWithdrawAllRewardsGenerateOnly() {
require := s.Require()

View File

@ -923,11 +923,11 @@ func (s *E2ETestSuite) TestTxDecode_GRPCGateway() {
}
}
func (s *E2ETestSuite) readTestAminoTxJSON() ([]byte, *legacytx.StdTx) {
func (s *E2ETestSuite) readTestAminoTxJSON() ([]byte, *legacytx.StdTx) { // nolint:staticcheck // legacy testing
val := s.network.Validators[0]
txJSONBytes, err := os.ReadFile("testdata/tx_amino1.json")
s.Require().NoError(err)
var stdTx legacytx.StdTx
var stdTx legacytx.StdTx // nolint:staticcheck // legacy testing
err = val.ClientCtx.LegacyAmino.UnmarshalJSON(txJSONBytes, &stdTx)
s.Require().NoError(err)
return txJSONBytes, &stdTx
@ -960,7 +960,7 @@ func (s *E2ETestSuite) TestTxEncodeAmino_GRPC() {
s.Require().NoError(err)
s.Require().NotEmpty(res.GetAminoBinary())
var decodedTx legacytx.StdTx
var decodedTx legacytx.StdTx // nolint:staticcheck // legacy testing
err = val.ClientCtx.LegacyAmino.Unmarshal(res.AminoBinary, &decodedTx)
s.Require().NoError(err)
s.Require().Equal(decodedTx.GetMsgs(), stdTx.GetMsgs())
@ -998,7 +998,7 @@ func (s *E2ETestSuite) TestTxEncodeAmino_GRPCGateway() {
err := val.ClientCtx.Codec.UnmarshalJSON(res, &result)
s.Require().NoError(err)
var decodedTx legacytx.StdTx
var decodedTx legacytx.StdTx // nolint:staticcheck // legacy testing
err = val.ClientCtx.LegacyAmino.Unmarshal(result.AminoBinary, &decodedTx)
s.Require().NoError(err)
s.Require().Equal(decodedTx.GetMsgs(), stdTx.GetMsgs())
@ -1007,11 +1007,11 @@ func (s *E2ETestSuite) TestTxEncodeAmino_GRPCGateway() {
}
}
func (s *E2ETestSuite) readTestAminoTxBinary() ([]byte, *legacytx.StdTx) {
func (s *E2ETestSuite) readTestAminoTxBinary() ([]byte, *legacytx.StdTx) { // nolint:staticcheck // legacy testing
val := s.network.Validators[0]
txJSONBytes, err := os.ReadFile("testdata/tx_amino1.bin")
s.Require().NoError(err)
var stdTx legacytx.StdTx
var stdTx legacytx.StdTx // nolint:staticcheck // legacy testing
err = val.ClientCtx.LegacyAmino.Unmarshal(txJSONBytes, &stdTx)
s.Require().NoError(err)
return txJSONBytes, &stdTx
@ -1045,7 +1045,7 @@ func (s *E2ETestSuite) TestTxDecodeAmino_GRPC() {
s.Require().NoError(err)
s.Require().NotEmpty(res.GetAminoJson())
var decodedTx legacytx.StdTx
var decodedTx legacytx.StdTx // nolint:staticcheck // legacy testing
err = s.network.Validators[0].ClientCtx.LegacyAmino.UnmarshalJSON([]byte(res.GetAminoJson()), &decodedTx)
s.Require().NoError(err)
s.Require().Equal(stdTx.GetMsgs(), decodedTx.GetMsgs())
@ -1085,7 +1085,7 @@ func (s *E2ETestSuite) TestTxDecodeAmino_GRPCGateway() {
err := val.ClientCtx.Codec.UnmarshalJSON(res, &result)
s.Require().NoError(err)
var decodedTx legacytx.StdTx
var decodedTx legacytx.StdTx // nolint:staticcheck // legacy testing
err = val.ClientCtx.LegacyAmino.UnmarshalJSON([]byte(result.AminoJson), &decodedTx)
s.Require().NoError(err)
s.Require().Equal(stdTx.GetMsgs(), decodedTx.GetMsgs())

View File

@ -50,7 +50,7 @@ func ApplyMockIODiscardOutErr(c *cobra.Command) BufferReader {
return mockIn
}
// Write the given string to a new temporary file.
// WriteToNewTempFile writes the given string to a new temporary file.
// Returns an open file for the test to use.
func WriteToNewTempFile(tb testing.TB, s string) *os.File {
tb.Helper()

View File

@ -88,9 +88,9 @@ func init() {
}
}
// AppConstructor defines a function which accepts a network configuration and
// creates an ABCI Application to provide to CometBFT.
type (
// AppConstructor defines a function which accepts a network configuration and
// creates an ABCI Application to provide to CometBFT.
AppConstructor = func(val ValidatorI) servertypes.Application
TestFixtureFactory = func() TestFixture
)

View File

@ -231,7 +231,7 @@ func writeFile(name, dir string, contents []byte) error {
return nil
}
// Get a free address for a test CometBFT server
// FreeTCPAddr gets a free address for a test CometBFT server
// protocol is either tcp, http, etc
func FreeTCPAddr() (addr, port string, closeFn func() error, err error) {
l, err := net.Listen("tcp", "127.0.0.1:0")

View File

@ -208,10 +208,10 @@ func AccAddressFromBech32(address string) (addr AccAddress, err error) {
return nil, err
}
return AccAddress(bz), nil
return bz, nil
}
// Returns boolean for whether two AccAddresses are Equal
// Equals returns boolean for whether two AccAddresses are Equal
func (aa AccAddress) Equals(aa2 Address) bool {
if aa.Empty() && aa2.Empty() {
return true
@ -220,7 +220,7 @@ func (aa AccAddress) Equals(aa2 Address) bool {
return bytes.Equal(aa.Bytes(), aa2.Bytes())
}
// Returns boolean for whether an AccAddress is empty
// Empty returns boolean for whether an AccAddress is empty
func (aa AccAddress) Empty() bool {
return len(aa) == 0
}
@ -373,7 +373,7 @@ func MustValAddressFromBech32(address string) ValAddress {
return addr
}
// Returns boolean for whether two ValAddresses are Equal
// Equals returns boolean for whether two ValAddresses are Equal
func (va ValAddress) Equals(va2 Address) bool {
if va.Empty() && va2.Empty() {
return true
@ -382,7 +382,7 @@ func (va ValAddress) Equals(va2 Address) bool {
return bytes.Equal(va.Bytes(), va2.Bytes())
}
// Returns boolean for whether an ValAddress is empty
// Empty returns boolean for whether an ValAddress is empty
func (va ValAddress) Empty() bool {
return len(va) == 0
}
@ -501,6 +501,7 @@ func (va ValAddress) Format(s fmt.State, verb rune) {
type ConsAddress []byte
// ConsAddressFromHex creates a ConsAddress from a hex string.
//
// Deprecated: use ConsensusAddressCodec from Staking keeper
func ConsAddressFromHex(address string) (addr ConsAddress, err error) {
bz, err := addressBytesFromHexString(address)
@ -525,15 +526,15 @@ func ConsAddressFromBech32(address string) (addr ConsAddress, err error) {
return nil, err
}
return ConsAddress(bz), nil
return bz, nil
}
// get ConsAddress from pubkey
// GetConsAddress get ConsAddress from pubkey.
func GetConsAddress(pubkey cryptotypes.PubKey) ConsAddress {
return ConsAddress(pubkey.Address())
}
// Returns boolean for whether two ConsAddress are Equal
// Equals returns boolean for whether two ConsAddress are Equal
func (ca ConsAddress) Equals(ca2 Address) bool {
if ca.Empty() && ca2.Empty() {
return true
@ -542,7 +543,7 @@ func (ca ConsAddress) Equals(ca2 Address) bool {
return bytes.Equal(ca.Bytes(), ca2.Bytes())
}
// Returns boolean for whether an ConsAddress is empty
// Empty returns boolean for whether an ConsAddress is empty
func (ca ConsAddress) Empty() bool {
return len(ca) == 0
}

View File

@ -13,7 +13,9 @@ import (
// + sdk:config.GetBech32AccountPubPrefix (and other related functions)
// + Bech32PrefixAccAddr and other related constants
// Deprecated: Bech32PubKeyType defines a string type alias for a Bech32 public key type.
// Bech32PubKeyType defines a string type alias for a Bech32 public key type.
//
// Deprecated: to be removed in a future release.
type Bech32PubKeyType string
// Bech32 conversion constants

View File

@ -34,7 +34,7 @@ var (
initConfig sync.Once
)
// New returns a new Config with default values.
// NewConfig returns a new Config with default values.
func NewConfig() *Config {
return &Config{
sealedch: make(chan struct{}),
@ -120,7 +120,7 @@ func (config *Config) SetAddressVerifier(addressVerifier func([]byte) error) {
config.addressVerifier = addressVerifier
}
// Set the FullFundraiserPath (BIP44Prefix) on the config.
// SetFullFundraiserPath sets the FullFundraiserPath (BIP44Prefix) on the config.
//
// Deprecated: This method is supported for backward compatibility only and will be removed in a future release. Use SetPurpose and SetCoinType instead.
func (config *Config) SetFullFundraiserPath(fullFundraiserPath string) {
@ -128,13 +128,13 @@ func (config *Config) SetFullFundraiserPath(fullFundraiserPath string) {
config.fullFundraiserPath = fullFundraiserPath
}
// Set the BIP-0044 Purpose code on the config
// SetPurpose sets the BIP-0044 Purpose code on the config
func (config *Config) SetPurpose(purpose uint32) {
config.assertNotSealed()
config.purpose = purpose
}
// Set the BIP-0044 CoinType code on the config
// SetCoinType sets the BIP-0044 CoinType code on the config
func (config *Config) SetCoinType(coinType uint32) {
config.assertNotSealed()
config.coinType = coinType

View File

@ -67,9 +67,11 @@ type Context struct {
}
// Proposed rename, not done to avoid API breakage
type Request = Context
// Read-only accessors
func (c Context) Context() context.Context { return c.baseCtx }
func (c Context) MultiStore() storetypes.MultiStore { return c.ms }
func (c Context) BlockHeight() int64 { return c.header.Height }
@ -121,7 +123,6 @@ func (c Context) Err() error {
return c.baseCtx.Err()
}
// create a new context
func NewContext(ms storetypes.MultiStore, header cmtproto.Header, isCheckTx bool, logger log.Logger) Context {
// https://github.com/gogo/protobuf/issues/519
header.Time = header.Time.UTC()
@ -250,7 +251,7 @@ func (c Context) WithIsCheckTx(isCheckTx bool) Context {
return c
}
// WithIsRecheckTx called with true will also set true on checkTx in order to
// WithIsReCheckTx called with true will also set true on checkTx in order to
// enforce the invariant that if recheckTx = true then checkTx = true as well.
func (c Context) WithIsReCheckTx(isRecheckTx bool) Context {
if isRecheckTx {
@ -318,6 +319,7 @@ func (c Context) WithHeaderInfo(headerInfo header.Info) Context {
}
// TODO: remove???
func (c Context) IsZero() bool {
return c.ms == nil
}

View File

@ -268,7 +268,7 @@ const (
)
type (
// StringAttributes defines a slice of StringEvents objects.
// StringEvents defines a slice of StringEvents objects.
StringEvents []StringEvent
)

View File

@ -15,7 +15,7 @@ type Invariant func(ctx Context) (string, bool)
// Deprecated: the Invariants type is deprecated and will be removed once x/crisis is removed.
type Invariants []Invariant
// expected interface for registering invariants
// InvariantRegistry is the expected interface for registering invariants
//
// Deprecated: the InvariantRegistry type is deprecated and will be removed once x/crisis is removed.
type InvariantRegistry interface {

View File

@ -2,7 +2,7 @@ package types
import "cosmossdk.io/math"
// map coins is a map representation of sdk.Coins
// MapCoins is a map representation of sdk.Coins
// intended solely for use in bulk additions.
// All serialization and iteration should be done after conversion to sdk.Coins.
type MapCoins map[string]math.Int

View File

@ -12,7 +12,7 @@ import (
"cosmossdk.io/x/tx/signing"
)
// ValidateAnnotations validates that the proto annotations are correct.
// ValidateProtoAnnotations validates that the proto annotations are correct.
// More specifically, it verifies:
// - all services named "Msg" have `(cosmos.msg.v1.service) = true`,
//

View File

@ -13,6 +13,8 @@ import (
"github.com/cosmos/cosmos-sdk/types/kv"
)
// WeightedProposalContent is a legacy type.
//
// Deprecated: Use WeightedProposalMsg instead.
type WeightedProposalContent interface {
AppParamsKey() string // key used to retrieve the value of the weight from the simulation application params
@ -20,9 +22,13 @@ type WeightedProposalContent interface {
ContentSimulatorFn() ContentSimulatorFn // content simulator function
}
// ContentSimulatorFn is a legacy type.
//
// Deprecated: Use MsgSimulatorFn instead.
type ContentSimulatorFn func(r *rand.Rand, ctx sdk.Context, accs []Account) Content
// Content is a legacy type.
//
// Deprecated: Use MsgSimulatorFn instead.
type Content interface {
GetTitle() string
@ -108,7 +114,7 @@ func NoOpMsg(moduleName, msgType, comment string) OperationMsg {
return NewOperationMsgBasic(moduleName, msgType, comment, false, nil)
}
// log entry text for this operation msg
// String logs entry text for this operation msg
func (om OperationMsg) String() string {
out, err := json.Marshal(om)
if err != nil {

View File

@ -4,7 +4,7 @@ import (
sdkmath "cosmossdk.io/math"
)
// Delay, in blocks, between when validator updates are returned to the
// ValidatorUpdateDelay is the delay, in blocks, between when validator updates are returned to the
// consensus-engine and when they are applied. For example, if
// ValidatorUpdateDelay is set to X, and if a validator set update is
// returned with new validators at the end of block 10, then the new

View File

@ -42,7 +42,7 @@ func (a *AuxSignerData) ValidateBasic() error {
return a.GetSignDoc().ValidateBasic()
}
// GetSignaturesV2 gets the SignatureV2 of the aux signer.
// GetSignatureV2 gets the SignatureV2 of the aux signer.
func (a *AuxSignerData) GetSignatureV2() (signing.SignatureV2, error) {
pk, ok := a.SignDoc.PublicKey.GetCachedValue().(cryptotypes.PubKey)
if !ok {

View File

@ -5,7 +5,7 @@ import (
)
// TxExtensionOptionI defines the interface for tx extension options
type TxExtensionOptionI any
type TxExtensionOptionI any //nolint: revive // we can ignore this, as this type is being used
// unpackTxExtensionOptionsI unpacks Any's to TxExtensionOptionI's.
func unpackTxExtensionOptionsI(unpacker types.AnyUnpacker, anys []*types.Any) error {

View File

@ -11,11 +11,12 @@ import (
"github.com/cosmos/cosmos-sdk/types/kv"
)
// SortedJSON takes any JSON and returns it sorted by keys. Also, all white-spaces
// SortJSON takes any JSON and returns it sorted by keys. Also, all white-spaces
// are removed.
// This method can be used to canonicalize JSON to be returned by GetSignBytes,
// e.g. for the ledger integration.
// If the passed JSON isn't valid it will return an error.
//
// Deprecated: SortJSON was used for GetSignbytes, this is now automatic with amino signing
func SortJSON(toSortJSON []byte) ([]byte, error) {
var c any
@ -32,6 +33,7 @@ func SortJSON(toSortJSON []byte) ([]byte, error) {
// MustSortJSON is like SortJSON but panic if an error occurs, e.g., if
// the passed JSON isn't valid.
//
// Deprecated: SortJSON was used for GetSignbytes, this is now automatic with amino signing
func MustSortJSON(toSortJSON []byte) []byte {
js, err := SortJSON(toSortJSON)
@ -58,25 +60,25 @@ func BigEndianToUint64(bz []byte) uint64 {
return binary.BigEndian.Uint64(bz)
}
// Slight modification of the RFC3339Nano but it right pads all zeros and drops the time zone info
// SortableTimeFormat is a slight modification of the RFC3339Nano but it right pads all zeros and drops the time zone info
const SortableTimeFormat = "2006-01-02T15:04:05.000000000"
// Formats a time.Time into a []byte that can be sorted
// FormatTimeBytes formats a time.Time into a []byte that can be sorted
func FormatTimeBytes(t time.Time) []byte {
return []byte(FormatTimeString(t))
}
// Formats a time.Time into a string
// FormatTimeString formats a time.Time into a string
func FormatTimeString(t time.Time) string {
return t.UTC().Round(0).Format(SortableTimeFormat)
}
// Parses a []byte encoded using FormatTimeKey back into a time.Time
// ParseTimeBytes parses a []byte encoded using FormatTimeKey back into a time.Time
func ParseTimeBytes(bz []byte) (time.Time, error) {
return ParseTime(bz)
}
// Parses an encoded type using FormatTimeKey back into a time.Time
// ParseTime parses an encoded type using FormatTimeKey back into a time.Time
func ParseTime(t any) (time.Time, error) {
var (
result time.Time
@ -101,7 +103,7 @@ func ParseTime(t any) (time.Time, error) {
return result.UTC().Round(0), nil
}
// copy bytes
// CopyBytes copies the given bytes to a new slice.
func CopyBytes(bz []byte) (ret []byte) {
if bz == nil {
return nil

View File

@ -27,15 +27,13 @@ import (
type ContextKey struct{}
var (
// application's name
// Name is the application's name
Name = ""
// application binary name
// AppName is the application binary name
AppName = "<appd>"
// application's version string
Version = ""
// commit
Commit = ""
// build tags
// Version is the application's version string
Version = ""
Commit = ""
BuildTags = ""
)

View File

@ -192,7 +192,7 @@ type (
}
)
// TxTimeoutHeightDecorator defines an AnteHandler decorator that checks for a
// NewTxTimeoutHeightDecorator defines an AnteHandler decorator that checks for a
// tx height timeout.
func NewTxTimeoutHeightDecorator() TxTimeoutHeightDecorator {
return TxTimeoutHeightDecorator{}

View File

@ -152,7 +152,7 @@ func (spkd SetPubKeyDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate b
return next(ctx, tx, simulate)
}
// Consume parameter-defined amount of gas for each signature according to the passed-in SignatureVerificationGasConsumer function
// SigGasConsumeDecorator consumes parameter-defined amount of gas for each signature according to the passed-in SignatureVerificationGasConsumer function
// before calling the next AnteHandler
// CONTRACT: Pubkeys are set in context for all signers before this decorator runs
// CONTRACT: Tx must implement SigVerifiableTx interface

View File

@ -88,7 +88,7 @@ func SignTxWithSignerAddress(txFactory tx.Factory, clientCtx client.Context, add
return tx.Sign(clientCtx.GetCmdContextWithFallback(), txFactory, name, txBuilder, overwrite)
}
// Read and decode a StdTx from the given filename. Can pass "-" to read from stdin.
// ReadTxFromFile reads and decodes a StdTx from the given filename. Can pass "-" to read from stdin.
func ReadTxFromFile(ctx client.Context, filename string) (tx sdk.Tx, err error) {
var bytes []byte

View File

@ -67,7 +67,7 @@ func (m Migrator) Migrate4To5(ctx sdk.Context) error {
return v5.Migrate(ctx, m.keeper.storeService, m.keeper.AccountNumber)
}
// V45_SetAccount implements V45_SetAccount
// V45SetAccount implements V45_SetAccount
// set the account without map to accAddr to accNumber.
//
// NOTE: This is used for testing purposes only.

View File

@ -86,13 +86,17 @@ func StdSignBytes(chainID string, accnum, sequence, timeout uint64, fee StdFee,
return mustSortJSON(bz)
}
// Deprecated: StdSignature represents a sig
// StdSignature represents a sig
//
// Deprecated: will be removed in the future.
type StdSignature struct {
cryptotypes.PubKey `json:"pub_key" yaml:"pub_key"` // optional
Signature []byte `json:"signature" yaml:"signature"`
}
// Deprecated
// NewStdSignature is a legacy function
//
// Deprecated: will be removed in the future.
func NewStdSignature(pk cryptotypes.PubKey, sig []byte) StdSignature {
return StdSignature{PubKey: pk, Signature: sig}
}

View File

@ -79,7 +79,8 @@ type StdTip struct {
// StdTx is the legacy transaction format for wrapping a Msg with Fee and Signatures.
// It only works with Amino, please prefer the new protobuf Tx in types/tx.
// NOTE: the first signature is the fee payer (Signatures must not be nil).
// Deprecated
//
// Deprecated: may be removed in the future.
type StdTx struct {
Msgs []sdk.Msg `json:"msg" yaml:"msg"`
Fee StdFee `json:"fee" yaml:"fee"`
@ -88,7 +89,9 @@ type StdTx struct {
TimeoutHeight uint64 `json:"timeout_height" yaml:"timeout_height"`
}
// Deprecated
// NewStdTx is a legacy function.
//
// Deprecated: may be removed in the future.
func NewStdTx(msgs []sdk.Msg, fee StdFee, sigs []StdSignature, memo string) StdTx {
return StdTx{
Msgs: msgs,
@ -146,7 +149,7 @@ func (tx StdTx) GetSignaturesV2() ([]signing.SignatureV2, error) {
return res, nil
}
// GetPubkeys returns the pubkeys of signers if the pubkey is included in the signature
// GetPubKeys returns the pubkeys of signers if the pubkey is included in the signature
// If pubkey is not included in the signature, then nil is in the slice instead
func (tx StdTx) GetPubKeys() ([]cryptotypes.PubKey, error) {
pks := make([]cryptotypes.PubKey, len(tx.Signatures))

View File

@ -71,7 +71,7 @@ type StdTxConfig struct {
Cdc *codec.LegacyAmino
}
// MarshalTx implements TxConfig.MarshalTx
// TxEncoder implements TxConfig.MarshalTx
func (s StdTxConfig) TxEncoder() sdk.TxEncoder {
return DefaultTxEncoder(s.Cdc)
}

View File

@ -240,12 +240,12 @@ func (s txServer) TxEncode(ctx context.Context, req *txtypes.TxEncodeRequest) (*
}
// TxEncodeAmino implements the ServiceServer.TxEncodeAmino RPC method.
func (s txServer) TxEncodeAmino(ctx context.Context, req *txtypes.TxEncodeAminoRequest) (*txtypes.TxEncodeAminoResponse, error) {
func (s txServer) TxEncodeAmino(_ context.Context, req *txtypes.TxEncodeAminoRequest) (*txtypes.TxEncodeAminoResponse, error) {
if req.AminoJson == "" {
return nil, status.Error(codes.InvalidArgument, "invalid empty tx json")
}
var stdTx legacytx.StdTx
var stdTx legacytx.StdTx // nolint:staticcheck // legacy testing
err := s.clientCtx.LegacyAmino.UnmarshalJSON([]byte(req.AminoJson), &stdTx)
if err != nil {
return nil, err
@ -283,12 +283,12 @@ func (s txServer) TxDecode(ctx context.Context, req *txtypes.TxDecodeRequest) (*
}
// TxDecodeAmino implements the ServiceServer.TxDecodeAmino RPC method.
func (s txServer) TxDecodeAmino(ctx context.Context, req *txtypes.TxDecodeAminoRequest) (*txtypes.TxDecodeAminoResponse, error) {
func (s txServer) TxDecodeAmino(_ context.Context, req *txtypes.TxDecodeAminoRequest) (*txtypes.TxDecodeAminoResponse, error) {
if req.AminoBinary == nil {
return nil, status.Error(codes.InvalidArgument, "invalid empty tx bytes")
}
var stdTx legacytx.StdTx
var stdTx legacytx.StdTx // nolint:staticcheck // legacy testing
err := s.clientCtx.LegacyAmino.Unmarshal(req.AminoBinary, &stdTx)
if err != nil {
return nil, err

View File

@ -143,7 +143,7 @@ func (acc BaseAccount) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
return unpacker.UnpackAny(acc.PubKey, &pubKey)
}
// NewModuleAddressOrAddress gets an input string and returns an AccAddress.
// NewModuleAddressOrBech32Address gets an input string and returns an AccAddress.
// If the input is a valid address, it returns the address.
// If the input is a module name, it returns the module address.
func NewModuleAddressOrBech32Address(input string) sdk.AccAddress {

View File

@ -5,7 +5,6 @@ import (
)
const (
// module name
ModuleName = "auth"
// StoreKey is string representation of the store key for auth
@ -32,6 +31,6 @@ var (
// UnorderedNoncesKey prefix for the unordered sequence storage.
UnorderedNoncesKey = collections.NewPrefix(90)
// legacy param key for global account number
// LegacyGlobalAccountNumberKey is the legacy param key for global account number
LegacyGlobalAccountNumberKey = []byte("globalAccountNumber")
)

View File

@ -42,7 +42,7 @@ func (AppModuleBasic) Name() string {
return types.ModuleName
}
// RegisterCodec registers the module's types with the given codec.
// RegisterLegacyAminoCodec registers the module's types with the given codec.
func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
types.RegisterLegacyAminoCodec(cdc)
}

View File

@ -24,7 +24,7 @@ func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {
legacy.RegisterAminoMsg(cdc, &MsgCreatePeriodicVestingAccount{}, "cosmos-sdk/MsgCreatePeriodVestAccount")
}
// RegisterInterface associates protoName with AccountI and VestingAccount
// RegisterInterfaces associates protoName with AccountI and VestingAccount
// Interfaces and creates a registry of it's concrete implementations
func RegisterInterfaces(registry types.InterfaceRegistry) {
registry.RegisterInterface(

View File

@ -31,7 +31,7 @@ func (p Periods) TotalDuration() time.Duration {
return time.Duration(len) * time.Second
}
// TotalDuration returns the sum of coins for the period
// TotalAmount returns the sum of coins for the period
func (p Periods) TotalAmount() sdk.Coins {
total := sdk.Coins{}
for _, period := range p {

View File

@ -48,7 +48,7 @@ func NewKeeper(storeService corestoretypes.KVStoreService, cdc codec.Codec, rout
}
}
// Super ugly hack to not be breaking in v0.50 and v0.47
// SetBankKeeper is a super ugly hack to not be breaking in v0.50 and v0.47
// DO NOT USE.
func (k Keeper) SetBankKeeper(bk authz.BankKeeper) Keeper {
k.bankKeeper = bk

View File

@ -57,7 +57,7 @@ func TestAminoJSON(t *testing.T) {
FileResolver: proto.HybridResolver,
})
tx := legacytx.StdTx{}
tx := legacytx.StdTx{} // nolint:staticcheck // legacy testing
blockTime := time.Date(1, 1, 1, 1, 1, 1, 1, time.UTC)
expiresAt := blockTime.Add(time.Hour)
msgSend := banktypes.MsgSend{FromAddress: "cosmos1ghi", ToAddress: "cosmos1jkl"}

View File

@ -24,10 +24,11 @@ func NewCircuitBreakerDecorator(ck CircuitBreaker) CircuitBreakerDecorator {
}
}
// AnteHandle handles this with baseapp's service router: https://github.com/cosmos/cosmos-sdk/issues/18632.
//
// If you copy this as reference and your app has the authz module enabled, you must either:
// - recursively check for nested authz.Exec messages in this function.
// - or error early if a nested authz grant is found.
// The circuit AnteHandler handles this with baseapp's service router: https://github.com/cosmos/cosmos-sdk/issues/18632.
func (cbd CircuitBreakerDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) {
// loop through all the messages and check if the message type is allowed
for _, msg := range tx.GetMsgs() {

View File

@ -34,7 +34,7 @@ func (qs QueryServer) Account(ctx context.Context, req *types.QueryAccountReques
return &types.AccountResponse{Permission: &perms}, nil
}
// Account returns account permissions.
// Accounts returns account permissions.
func (qs QueryServer) Accounts(ctx context.Context, req *types.QueryAccountsRequest) (*types.AccountsResponse, error) {
results, pageRes, err := query.CollectionPaginate(
ctx,

View File

@ -7,7 +7,7 @@ import (
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
// get outstanding rewards
// GetValidatorOutstandingRewardsCoins gets outstanding rewards
func (k Keeper) GetValidatorOutstandingRewardsCoins(ctx context.Context, val sdk.ValAddress) (sdk.DecCoins, error) {
rewards, err := k.GetValidatorOutstandingRewards(ctx, val)
if err != nil {

View File

@ -11,7 +11,7 @@ import (
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
// initialize starting info for a new delegation
// initializeDelegation initializes starting info for a new delegation
func (k Keeper) initializeDelegation(ctx context.Context, val sdk.ValAddress, del sdk.AccAddress) error {
// period has already been incremented - we want to store the period ended by this delegation action
valCurrentRewards, err := k.GetValidatorCurrentRewards(ctx, val)
@ -44,7 +44,7 @@ func (k Keeper) initializeDelegation(ctx context.Context, val sdk.ValAddress, de
return k.SetDelegatorStartingInfo(ctx, val, del, types.NewDelegatorStartingInfo(previousPeriod, stake, uint64(sdkCtx.BlockHeight())))
}
// calculate the rewards accrued by a delegation between two periods
// calculateDelegationRewardsBetween calculates the rewards accrued by a delegation between two periods
func (k Keeper) calculateDelegationRewardsBetween(ctx context.Context, val stakingtypes.ValidatorI,
startingPeriod, endingPeriod uint64, stake math.LegacyDec,
) (sdk.DecCoins, error) {
@ -83,7 +83,7 @@ func (k Keeper) calculateDelegationRewardsBetween(ctx context.Context, val staki
return rewards, nil
}
// calculate the total rewards accrued by a delegation
// CalculateDelegationRewards calculates the total rewards accrued by a delegation
func (k Keeper) CalculateDelegationRewards(ctx context.Context, val stakingtypes.ValidatorI, del stakingtypes.DelegationI, endingPeriod uint64) (rewards sdk.DecCoins, err error) {
addrCodec := k.authKeeper.AddressCodec()
delAddr, err := addrCodec.StringToBytes(del.GetDelegatorAddr())

View File

@ -10,19 +10,18 @@ import (
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
// Wrapper struct
type Hooks struct {
k Keeper
}
var _ stakingtypes.StakingHooks = Hooks{}
// Create new distribution hooks
// Hooks creates new distribution hooks
func (k Keeper) Hooks() Hooks {
return Hooks{k}
}
// initialize validator distribution record
// AfterValidatorCreated initializes validator distribution record
func (h Hooks) AfterValidatorCreated(ctx context.Context, valAddr sdk.ValAddress) error {
val, err := h.k.stakingKeeper.Validator(ctx, valAddr)
if err != nil {
@ -121,7 +120,7 @@ func (h Hooks) AfterValidatorRemoved(ctx context.Context, _ sdk.ConsAddress, val
return nil
}
// increment period
// BeforeDelegationCreated increments period
func (h Hooks) BeforeDelegationCreated(ctx context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error {
val, err := h.k.stakingKeeper.Validator(ctx, valAddr)
if err != nil {
@ -132,7 +131,7 @@ func (h Hooks) BeforeDelegationCreated(ctx context.Context, delAddr sdk.AccAddre
return err
}
// withdraw delegation rewards (which also increments period)
// BeforeDelegationSharesModified withdraws delegation rewards (which also increments period)
func (h Hooks) BeforeDelegationSharesModified(ctx context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error {
val, err := h.k.stakingKeeper.Validator(ctx, valAddr)
if err != nil {
@ -151,12 +150,12 @@ func (h Hooks) BeforeDelegationSharesModified(ctx context.Context, delAddr sdk.A
return nil
}
// create new delegation period record
// AfterDelegationModified creates a new delegation period record
func (h Hooks) AfterDelegationModified(ctx context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error {
return h.k.initializeDelegation(ctx, valAddr, delAddr)
}
// record the slash event
// BeforeValidatorSlashed records the slash event
func (h Hooks) BeforeValidatorSlashed(ctx context.Context, valAddr sdk.ValAddress, fraction sdkmath.LegacyDec) error {
return h.k.updateValidatorSlashFraction(ctx, valAddr, fraction)
}

View File

@ -13,29 +13,29 @@ import (
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
// get the delegator withdraw address, defaulting to the delegator address
// GetDelegatorWithdrawAddr get the delegator withdraw address, defaulting to the delegator address
func (k Keeper) GetDelegatorWithdrawAddr(ctx context.Context, delAddr sdk.AccAddress) (sdk.AccAddress, error) {
store := k.storeService.OpenKVStore(ctx)
b, err := store.Get(types.GetDelegatorWithdrawAddrKey(delAddr))
if b == nil {
return delAddr, err
}
return sdk.AccAddress(b), nil
return b, nil
}
// set the delegator withdraw address
// SetDelegatorWithdrawAddr sets the delegator withdraw address
func (k Keeper) SetDelegatorWithdrawAddr(ctx context.Context, delAddr, withdrawAddr sdk.AccAddress) error {
store := k.storeService.OpenKVStore(ctx)
return store.Set(types.GetDelegatorWithdrawAddrKey(delAddr), withdrawAddr.Bytes())
}
// delete a delegator withdraw addr
// DeleteDelegatorWithdrawAddr deletes a delegator withdraw addr
func (k Keeper) DeleteDelegatorWithdrawAddr(ctx context.Context, delAddr, withdrawAddr sdk.AccAddress) error {
store := k.storeService.OpenKVStore(ctx)
return store.Delete(types.GetDelegatorWithdrawAddrKey(delAddr))
}
// iterate over delegator withdraw addrs
// IterateDelegatorWithdrawAddrs iterates over delegator withdraw addrs
func (k Keeper) IterateDelegatorWithdrawAddrs(ctx context.Context, handler func(del, addr sdk.AccAddress) (stop bool)) {
store := k.storeService.OpenKVStore(ctx)
iter := storetypes.KVStorePrefixIterator(runtime.KVStoreAdapter(store), types.DelegatorWithdrawAddrPrefix)
@ -71,14 +71,14 @@ func (k Keeper) GetPreviousProposerConsAddr(ctx context.Context) (sdk.ConsAddres
return addrValue.GetValue(), nil
}
// set the proposer public key for this block
// SetPreviousProposerConsAddr sets the proposer public key for this block
func (k Keeper) SetPreviousProposerConsAddr(ctx context.Context, consAddr sdk.ConsAddress) error {
store := k.storeService.OpenKVStore(ctx)
bz := k.cdc.MustMarshal(&gogotypes.BytesValue{Value: consAddr})
return store.Set(types.ProposerKey, bz)
}
// get the starting info associated with a delegator
// GetDelegatorStartingInfo gets the starting info associated with a delegator
func (k Keeper) GetDelegatorStartingInfo(ctx context.Context, val sdk.ValAddress, del sdk.AccAddress) (period types.DelegatorStartingInfo, err error) {
store := k.storeService.OpenKVStore(ctx)
b, err := store.Get(types.GetDelegatorStartingInfoKey(val, del))
@ -90,7 +90,7 @@ func (k Keeper) GetDelegatorStartingInfo(ctx context.Context, val sdk.ValAddress
return period, err
}
// set the starting info associated with a delegator
// SetDelegatorStartingInfo sets the starting info associated with a delegator
func (k Keeper) SetDelegatorStartingInfo(ctx context.Context, val sdk.ValAddress, del sdk.AccAddress, period types.DelegatorStartingInfo) error {
store := k.storeService.OpenKVStore(ctx)
b, err := k.cdc.Marshal(&period)
@ -101,19 +101,19 @@ func (k Keeper) SetDelegatorStartingInfo(ctx context.Context, val sdk.ValAddress
return store.Set(types.GetDelegatorStartingInfoKey(val, del), b)
}
// check existence of the starting info associated with a delegator
// HasDelegatorStartingInfo checks existence of the starting info associated with a delegator
func (k Keeper) HasDelegatorStartingInfo(ctx context.Context, val sdk.ValAddress, del sdk.AccAddress) (bool, error) {
store := k.storeService.OpenKVStore(ctx)
return store.Has(types.GetDelegatorStartingInfoKey(val, del))
}
// delete the starting info associated with a delegator
// DeleteDelegatorStartingInfo deletes the starting info associated with a delegator
func (k Keeper) DeleteDelegatorStartingInfo(ctx context.Context, val sdk.ValAddress, del sdk.AccAddress) error {
store := k.storeService.OpenKVStore(ctx)
return store.Delete(types.GetDelegatorStartingInfoKey(val, del))
}
// iterate over delegator starting infos
// IterateDelegatorStartingInfos iterates over delegator starting infos
func (k Keeper) IterateDelegatorStartingInfos(ctx context.Context, handler func(val sdk.ValAddress, del sdk.AccAddress, info types.DelegatorStartingInfo) (stop bool)) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, types.DelegatorStartingInfoPrefix)
@ -128,7 +128,7 @@ func (k Keeper) IterateDelegatorStartingInfos(ctx context.Context, handler func(
}
}
// get historical rewards for a particular period
// GetValidatorHistoricalRewards gets historical rewards for a particular period
func (k Keeper) GetValidatorHistoricalRewards(ctx context.Context, val sdk.ValAddress, period uint64) (rewards types.ValidatorHistoricalRewards, err error) {
store := k.storeService.OpenKVStore(ctx)
b, err := store.Get(types.GetValidatorHistoricalRewardsKey(val, period))
@ -140,7 +140,7 @@ func (k Keeper) GetValidatorHistoricalRewards(ctx context.Context, val sdk.ValAd
return
}
// set historical rewards for a particular period
// SetValidatorHistoricalRewards sets historical rewards for a particular period
func (k Keeper) SetValidatorHistoricalRewards(ctx context.Context, val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) error {
store := k.storeService.OpenKVStore(ctx)
b, err := k.cdc.Marshal(&rewards)
@ -151,7 +151,7 @@ func (k Keeper) SetValidatorHistoricalRewards(ctx context.Context, val sdk.ValAd
return store.Set(types.GetValidatorHistoricalRewardsKey(val, period), b)
}
// iterate over historical rewards
// IterateValidatorHistoricalRewards iterates over historical rewards
func (k Keeper) IterateValidatorHistoricalRewards(ctx context.Context, handler func(val sdk.ValAddress, period uint64, rewards types.ValidatorHistoricalRewards) (stop bool)) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, types.ValidatorHistoricalRewardsPrefix)
@ -166,13 +166,13 @@ func (k Keeper) IterateValidatorHistoricalRewards(ctx context.Context, handler f
}
}
// delete a historical reward
// DeleteValidatorHistoricalReward deletes a historical reward
func (k Keeper) DeleteValidatorHistoricalReward(ctx context.Context, val sdk.ValAddress, period uint64) error {
store := k.storeService.OpenKVStore(ctx)
return store.Delete(types.GetValidatorHistoricalRewardsKey(val, period))
}
// delete historical rewards for a validator
// DeleteValidatorHistoricalRewards deletes historical rewards for a validator
func (k Keeper) DeleteValidatorHistoricalRewards(ctx context.Context, val sdk.ValAddress) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, types.GetValidatorHistoricalRewardsPrefix(val))
@ -182,7 +182,7 @@ func (k Keeper) DeleteValidatorHistoricalRewards(ctx context.Context, val sdk.Va
}
}
// delete all historical rewards
// DeleteAllValidatorHistoricalRewards deletes all historical rewards
func (k Keeper) DeleteAllValidatorHistoricalRewards(ctx context.Context) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, types.ValidatorHistoricalRewardsPrefix)
@ -192,7 +192,7 @@ func (k Keeper) DeleteAllValidatorHistoricalRewards(ctx context.Context) {
}
}
// historical reference count (used for testcases)
// GetValidatorHistoricalReferenceCount gets a historical reference count (used for testcases)
func (k Keeper) GetValidatorHistoricalReferenceCount(ctx context.Context) (count uint64) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, types.ValidatorHistoricalRewardsPrefix)
@ -205,7 +205,7 @@ func (k Keeper) GetValidatorHistoricalReferenceCount(ctx context.Context) (count
return
}
// get current rewards for a validator
// GetValidatorCurrentRewards gets current rewards for a validator
func (k Keeper) GetValidatorCurrentRewards(ctx context.Context, val sdk.ValAddress) (rewards types.ValidatorCurrentRewards, err error) {
store := k.storeService.OpenKVStore(ctx)
b, err := store.Get(types.GetValidatorCurrentRewardsKey(val))
@ -217,7 +217,7 @@ func (k Keeper) GetValidatorCurrentRewards(ctx context.Context, val sdk.ValAddre
return
}
// set current rewards for a validator
// SetValidatorCurrentRewards sets current rewards for a validator
func (k Keeper) SetValidatorCurrentRewards(ctx context.Context, val sdk.ValAddress, rewards types.ValidatorCurrentRewards) error {
store := k.storeService.OpenKVStore(ctx)
b, err := k.cdc.Marshal(&rewards)
@ -228,13 +228,13 @@ func (k Keeper) SetValidatorCurrentRewards(ctx context.Context, val sdk.ValAddre
return store.Set(types.GetValidatorCurrentRewardsKey(val), b)
}
// delete current rewards for a validator
// DeleteValidatorCurrentRewards deletes current rewards for a validator
func (k Keeper) DeleteValidatorCurrentRewards(ctx context.Context, val sdk.ValAddress) error {
store := k.storeService.OpenKVStore(ctx)
return store.Delete(types.GetValidatorCurrentRewardsKey(val))
}
// iterate over current rewards
// IterateValidatorCurrentRewards iterates over current rewards
func (k Keeper) IterateValidatorCurrentRewards(ctx context.Context, handler func(val sdk.ValAddress, rewards types.ValidatorCurrentRewards) (stop bool)) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, types.ValidatorCurrentRewardsPrefix)
@ -249,7 +249,7 @@ func (k Keeper) IterateValidatorCurrentRewards(ctx context.Context, handler func
}
}
// get accumulated commission for a validator
// GetValidatorAccumulatedCommission gets accumulated commission for a validator
func (k Keeper) GetValidatorAccumulatedCommission(ctx context.Context, val sdk.ValAddress) (commission types.ValidatorAccumulatedCommission, err error) {
store := k.storeService.OpenKVStore(ctx)
b, err := store.Get(types.GetValidatorAccumulatedCommissionKey(val))
@ -268,7 +268,7 @@ func (k Keeper) GetValidatorAccumulatedCommission(ctx context.Context, val sdk.V
return
}
// set accumulated commission for a validator
// SetValidatorAccumulatedCommission sets accumulated commission for a validator
func (k Keeper) SetValidatorAccumulatedCommission(ctx context.Context, val sdk.ValAddress, commission types.ValidatorAccumulatedCommission) error {
var (
bz []byte
@ -289,13 +289,13 @@ func (k Keeper) SetValidatorAccumulatedCommission(ctx context.Context, val sdk.V
return store.Set(types.GetValidatorAccumulatedCommissionKey(val), bz)
}
// delete accumulated commission for a validator
// DeleteValidatorAccumulatedCommission deletes accumulated commission for a validator
func (k Keeper) DeleteValidatorAccumulatedCommission(ctx context.Context, val sdk.ValAddress) error {
store := k.storeService.OpenKVStore(ctx)
return store.Delete(types.GetValidatorAccumulatedCommissionKey(val))
}
// iterate over accumulated commissions
// IterateValidatorAccumulatedCommissions iterates over accumulated commissions
func (k Keeper) IterateValidatorAccumulatedCommissions(ctx context.Context, handler func(val sdk.ValAddress, commission types.ValidatorAccumulatedCommission) (stop bool)) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, types.ValidatorAccumulatedCommissionPrefix)
@ -310,7 +310,7 @@ func (k Keeper) IterateValidatorAccumulatedCommissions(ctx context.Context, hand
}
}
// get validator outstanding rewards
// GetValidatorOutstandingRewards gets validator outstanding rewards
func (k Keeper) GetValidatorOutstandingRewards(ctx context.Context, val sdk.ValAddress) (rewards types.ValidatorOutstandingRewards, err error) {
store := k.storeService.OpenKVStore(ctx)
bz, err := store.Get(types.GetValidatorOutstandingRewardsKey(val))
@ -321,7 +321,7 @@ func (k Keeper) GetValidatorOutstandingRewards(ctx context.Context, val sdk.ValA
return
}
// set validator outstanding rewards
// SetValidatorOutstandingRewards sets validator outstanding rewards
func (k Keeper) SetValidatorOutstandingRewards(ctx context.Context, val sdk.ValAddress, rewards types.ValidatorOutstandingRewards) error {
store := k.storeService.OpenKVStore(ctx)
b, err := k.cdc.Marshal(&rewards)
@ -331,13 +331,13 @@ func (k Keeper) SetValidatorOutstandingRewards(ctx context.Context, val sdk.ValA
return store.Set(types.GetValidatorOutstandingRewardsKey(val), b)
}
// delete validator outstanding rewards
// DeleteValidatorOutstandingRewards deletes validator outstanding rewards
func (k Keeper) DeleteValidatorOutstandingRewards(ctx context.Context, val sdk.ValAddress) error {
store := k.storeService.OpenKVStore(ctx)
return store.Delete(types.GetValidatorOutstandingRewardsKey(val))
}
// iterate validator outstanding rewards
// IterateValidatorOutstandingRewards iterates validator outstanding rewards
func (k Keeper) IterateValidatorOutstandingRewards(ctx context.Context, handler func(val sdk.ValAddress, rewards types.ValidatorOutstandingRewards) (stop bool)) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, types.ValidatorOutstandingRewardsPrefix)
@ -352,7 +352,7 @@ func (k Keeper) IterateValidatorOutstandingRewards(ctx context.Context, handler
}
}
// get slash event for height
// GetValidatorSlashEvent gets slash event for height
func (k Keeper) GetValidatorSlashEvent(ctx context.Context, val sdk.ValAddress, height, period uint64) (event types.ValidatorSlashEvent, found bool, err error) {
store := k.storeService.OpenKVStore(ctx)
b, err := store.Get(types.GetValidatorSlashEventKey(val, height, period))
@ -372,7 +372,7 @@ func (k Keeper) GetValidatorSlashEvent(ctx context.Context, val sdk.ValAddress,
return event, true, nil
}
// set slash event for height
// SetValidatorSlashEvent sets slash event for height
func (k Keeper) SetValidatorSlashEvent(ctx context.Context, val sdk.ValAddress, height, period uint64, event types.ValidatorSlashEvent) error {
store := k.storeService.OpenKVStore(ctx)
b, err := k.cdc.Marshal(&event)
@ -383,7 +383,7 @@ func (k Keeper) SetValidatorSlashEvent(ctx context.Context, val sdk.ValAddress,
return store.Set(types.GetValidatorSlashEventKey(val, height, period), b)
}
// iterate over slash events between heights, inclusive
// IterateValidatorSlashEventsBetween iterates over slash events between heights, inclusive
func (k Keeper) IterateValidatorSlashEventsBetween(ctx context.Context, val sdk.ValAddress, startingHeight, endingHeight uint64,
handler func(height uint64, event types.ValidatorSlashEvent) (stop bool),
) {
@ -403,7 +403,7 @@ func (k Keeper) IterateValidatorSlashEventsBetween(ctx context.Context, val sdk.
}
}
// iterate over all slash events
// IterateValidatorSlashEvents iterates over all slash events
func (k Keeper) IterateValidatorSlashEvents(ctx context.Context, handler func(val sdk.ValAddress, height uint64, event types.ValidatorSlashEvent) (stop bool)) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, types.ValidatorSlashEventPrefix)
@ -418,7 +418,7 @@ func (k Keeper) IterateValidatorSlashEvents(ctx context.Context, handler func(va
}
}
// delete slash events for a particular validator
// DeleteValidatorSlashEvents deletes slash events for a particular validator
func (k Keeper) DeleteValidatorSlashEvents(ctx context.Context, val sdk.ValAddress) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, types.GetValidatorSlashEventPrefix(val))
@ -428,7 +428,7 @@ func (k Keeper) DeleteValidatorSlashEvents(ctx context.Context, val sdk.ValAddre
}
}
// delete all slash events
// DeleteAllValidatorSlashEvents deletes all slash events
func (k Keeper) DeleteAllValidatorSlashEvents(ctx context.Context) {
store := runtime.KVStoreAdapter(k.storeService.OpenKVStore(ctx))
iter := storetypes.KVStorePrefixIterator(store, types.ValidatorSlashEventPrefix)

View File

@ -11,7 +11,7 @@ import (
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
// initialize rewards for a new validator
// initializeValidator initializes rewards for a new validator
func (k Keeper) initializeValidator(ctx context.Context, val stakingtypes.ValidatorI) error {
valBz, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator())
if err != nil {
@ -40,7 +40,7 @@ func (k Keeper) initializeValidator(ctx context.Context, val stakingtypes.Valida
return err
}
// increment validator period, returning the period just ended
// IncrementValidatorPeriod increments validator period, returning the period just ended
func (k Keeper) IncrementValidatorPeriod(ctx context.Context, val stakingtypes.ValidatorI) (uint64, error) {
valBz, err := k.stakingKeeper.ValidatorAddressCodec().StringToBytes(val.GetOperator())
if err != nil {
@ -116,7 +116,7 @@ func (k Keeper) IncrementValidatorPeriod(ctx context.Context, val stakingtypes.V
return rewards.Period, nil
}
// increment the reference count for a historical rewards value
// incrementReferenceCount increments the reference count for a historical rewards value
func (k Keeper) incrementReferenceCount(ctx context.Context, valAddr sdk.ValAddress, period uint64) error {
historical, err := k.GetValidatorHistoricalRewards(ctx, valAddr, period)
if err != nil {
@ -131,7 +131,7 @@ func (k Keeper) incrementReferenceCount(ctx context.Context, valAddr sdk.ValAddr
return k.SetValidatorHistoricalRewards(ctx, valAddr, period, historical)
}
// decrement the reference count for a historical rewards value, and delete if zero references remain
// decrementReferenceCount decrements the reference count for a historical rewards value, and delete if zero references remain
func (k Keeper) decrementReferenceCount(ctx context.Context, valAddr sdk.ValAddress, period uint64) error {
historical, err := k.GetValidatorHistoricalRewards(ctx, valAddr, period)
if err != nil {

View File

@ -55,7 +55,7 @@ var (
ValidatorSlashEventPrefix = []byte{0x08} // key for validator slash fraction
)
// gets an address from a validator's outstanding rewards key
// GetValidatorOutstandingRewardsAddress gets an address from a validator's outstanding rewards key
func GetValidatorOutstandingRewardsAddress(key []byte) (valAddr sdk.ValAddress) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
@ -63,7 +63,7 @@ func GetValidatorOutstandingRewardsAddress(key []byte) (valAddr sdk.ValAddress)
return sdk.ValAddress(addr)
}
// gets an address from a delegator's withdraw info key
// GetDelegatorWithdrawInfoAddress gets an address from a delegator's withdraw info key
func GetDelegatorWithdrawInfoAddress(key []byte) (delAddr sdk.AccAddress) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
@ -71,31 +71,31 @@ func GetDelegatorWithdrawInfoAddress(key []byte) (delAddr sdk.AccAddress) {
return sdk.AccAddress(addr)
}
// gets the addresses from a delegator starting info key
// GetDelegatorStartingInfoAddresses gets the addresses from a delegator starting info key
func GetDelegatorStartingInfoAddresses(key []byte) (valAddr sdk.ValAddress, delAddr sdk.AccAddress) {
kv.AssertKeyAtLeastLength(key, 2+v1auth.AddrLen)
addr := key[1 : 1+v1auth.AddrLen]
kv.AssertKeyLength(addr, v1auth.AddrLen)
valAddr = sdk.ValAddress(addr)
valAddr = addr
addr = key[1+v1auth.AddrLen:]
kv.AssertKeyLength(addr, v1auth.AddrLen)
delAddr = sdk.AccAddress(addr)
delAddr = addr
return
}
// gets the address & period from a validator's historical rewards key
// GetValidatorHistoricalRewardsAddressPeriod gets the address & period from a validator's historical rewards key
func GetValidatorHistoricalRewardsAddressPeriod(key []byte) (valAddr sdk.ValAddress, period uint64) {
kv.AssertKeyAtLeastLength(key, 2+v1auth.AddrLen)
addr := key[1 : 1+v1auth.AddrLen]
kv.AssertKeyLength(addr, v1auth.AddrLen)
valAddr = sdk.ValAddress(addr)
valAddr = addr
b := key[1+v1auth.AddrLen:]
kv.AssertKeyLength(addr, 8)
period = binary.LittleEndian.Uint64(b)
return
}
// gets the address from a validator's current rewards key
// GetValidatorCurrentRewardsAddress gets the address from a validator's current rewards key
func GetValidatorCurrentRewardsAddress(key []byte) (valAddr sdk.ValAddress) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
@ -103,20 +103,20 @@ func GetValidatorCurrentRewardsAddress(key []byte) (valAddr sdk.ValAddress) {
return sdk.ValAddress(addr)
}
// gets the address from a validator's accumulated commission key
// GetValidatorAccumulatedCommissionAddress gets the address from a validator's accumulated commission key
func GetValidatorAccumulatedCommissionAddress(key []byte) (valAddr sdk.ValAddress) {
kv.AssertKeyAtLeastLength(key, 2)
addr := key[1:]
kv.AssertKeyLength(addr, v1auth.AddrLen)
return sdk.ValAddress(addr)
return addr
}
// gets the height from a validator's slash event key
// GetValidatorSlashEventAddressHeight gets the height from a validator's slash event key
func GetValidatorSlashEventAddressHeight(key []byte) (valAddr sdk.ValAddress, height uint64) {
kv.AssertKeyAtLeastLength(key, 2+v1auth.AddrLen)
addr := key[1 : 1+v1auth.AddrLen]
kv.AssertKeyLength(addr, v1auth.AddrLen)
valAddr = sdk.ValAddress(addr)
valAddr = addr
startB := 1 + v1auth.AddrLen
kv.AssertKeyAtLeastLength(key, startB+9)
b := key[startB : startB+8] // the next 8 bytes represent the height
@ -124,49 +124,49 @@ func GetValidatorSlashEventAddressHeight(key []byte) (valAddr sdk.ValAddress, he
return
}
// gets the outstanding rewards key for a validator
// GetValidatorOutstandingRewardsKey gets the outstanding rewards key for a validator
func GetValidatorOutstandingRewardsKey(valAddr sdk.ValAddress) []byte {
return append(ValidatorOutstandingRewardsPrefix, valAddr.Bytes()...)
}
// gets the key for a delegator's withdraw addr
// GetDelegatorWithdrawAddrKey gets the key for a delegator's withdraw addr
func GetDelegatorWithdrawAddrKey(delAddr sdk.AccAddress) []byte {
return append(DelegatorWithdrawAddrPrefix, delAddr.Bytes()...)
}
// gets the key for a delegator's starting info
// GetDelegatorStartingInfoKey gets the key for a delegator's starting info
func GetDelegatorStartingInfoKey(v sdk.ValAddress, d sdk.AccAddress) []byte {
return append(append(DelegatorStartingInfoPrefix, v.Bytes()...), d.Bytes()...)
}
// gets the prefix key for a validator's historical rewards
// GetValidatorHistoricalRewardsPrefix gets the prefix key for a validator's historical rewards
func GetValidatorHistoricalRewardsPrefix(v sdk.ValAddress) []byte {
return append(ValidatorHistoricalRewardsPrefix, v.Bytes()...)
}
// gets the key for a validator's historical rewards
// GetValidatorHistoricalRewardsKey gets the key for a validator's historical rewards
func GetValidatorHistoricalRewardsKey(v sdk.ValAddress, k uint64) []byte {
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, k)
return append(append(ValidatorHistoricalRewardsPrefix, v.Bytes()...), b...)
}
// gets the key for a validator's current rewards
// GetValidatorCurrentRewardsKey gets the key for a validator's current rewards
func GetValidatorCurrentRewardsKey(v sdk.ValAddress) []byte {
return append(ValidatorCurrentRewardsPrefix, v.Bytes()...)
}
// gets the key for a validator's current commission
// GetValidatorAccumulatedCommissionKey gets the key for a validator's current commission
func GetValidatorAccumulatedCommissionKey(v sdk.ValAddress) []byte {
return append(ValidatorAccumulatedCommissionPrefix, v.Bytes()...)
}
// gets the prefix key for a validator's slash fractions
// GetValidatorSlashEventPrefix gets the prefix key for a validator's slash fractions
func GetValidatorSlashEventPrefix(v sdk.ValAddress) []byte {
return append(ValidatorSlashEventPrefix, v.Bytes()...)
}
// gets the prefix key for a validator's slash fraction (ValidatorSlashEventPrefix + height)
// GetValidatorSlashEventKeyPrefix gets the prefix key for a validator's slash fraction (ValidatorSlashEventPrefix + height)
func GetValidatorSlashEventKeyPrefix(v sdk.ValAddress, height uint64) []byte {
heightBz := make([]byte, 8)
binary.BigEndian.PutUint64(heightBz, height)
@ -176,7 +176,7 @@ func GetValidatorSlashEventKeyPrefix(v sdk.ValAddress, height uint64) []byte {
)
}
// gets the key for a validator's slash fraction
// GetValidatorSlashEventKey gets the key for a validator's slash fraction
func GetValidatorSlashEventKey(v sdk.ValAddress, height, period uint64) []byte {
periodBz := make([]byte, 8)
binary.BigEndian.PutUint64(periodBz, period)

View File

@ -2,7 +2,7 @@ package types
import sdkmath "cosmossdk.io/math"
// create a new DelegatorStartingInfo
// NewDelegatorStartingInfo creates a new DelegatorStartingInfo
func NewDelegatorStartingInfo(previousPeriod uint64, stake sdkmath.LegacyDec, height uint64) DelegatorStartingInfo {
return DelegatorStartingInfo{
PreviousPeriod: previousPeriod,

View File

@ -6,7 +6,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
)
// zero fee pool
// InitialFeePool returns a zero fee pool
func InitialFeePool() FeePool {
return FeePool{
CommunityPool: sdk.DecCoins{},

View File

@ -23,7 +23,7 @@ func NewGenesisState(
}
}
// get raw genesis raw message for testing
// DefaultGenesisState returns the default genesis state of distribution.
func DefaultGenesisState() *GenesisState {
return &GenesisState{
FeePool: InitialFeePool(),

View File

@ -10,7 +10,7 @@ func (csp *CommunityPoolSpendProposal) GetTitle() string { return csp.Title }
// GetDescription returns the description of a community pool spend proposal.
func (csp *CommunityPoolSpendProposal) GetDescription() string { return csp.Description }
// GetDescription returns the routing key of a community pool spend proposal.
// ProposalRoute returns the routing key of a community pool spend proposal.
func (csp *CommunityPoolSpendProposal) ProposalRoute() string { return RouterKey }
// ProposalType returns the type of a community pool spend proposal.

Some files were not shown because too many files have changed in this diff Show More