From f9e621f1695ae7dea3d0d4c616769c72eb8fd14a Mon Sep 17 00:00:00 2001 From: tac0turtle <24299864+tac0turtle@users.noreply.github.com> Date: Wed, 13 Aug 2025 00:53:56 +0000 Subject: [PATCH] chore: Sync docs from cosmos-sdk/docs --- docs/build/abci/00-introduction.md | 4 +- docs/build/abci/02-process-proposal.md | 2 +- docs/build/abci/03-vote-extensions.md | 6 +- docs/build/architecture/PROCESS.md | 12 +- docs/build/architecture/README.md | 6 +- .../adr-004-split-denomination-keys.md | 2 +- .../adr-006-secret-store-replacement.md | 2 +- .../adr-007-specialization-groups.md | 2 +- .../build/architecture/adr-008-dCERT-group.md | 2 +- .../adr-010-modular-antehandler.md | 2 +- .../architecture/adr-012-state-accessors.md | 4 +- .../adr-014-proportional-slashing.md | 2 +- ...dr-016-validator-consensus-key-rotation.md | 22 +- .../adr-018-extendable-voting-period.md | 2 +- .../adr-019-protobuf-state-encoding.md | 18 +- .../adr-020-protobuf-transaction-encoding.md | 18 +- .../adr-021-protobuf-query-encoding.md | 8 +- .../adr-022-custom-panic-handling.md | 18 +- .../architecture/adr-023-protobuf-naming.md | 12 +- ...27-deterministic-protobuf-serialization.md | 16 +- .../adr-028-public-key-addresses.md | 42 ++-- .../architecture/adr-029-fee-grant-module.md | 8 +- .../architecture/adr-030-authz-module.md | 2 +- .../build/architecture/adr-031-msg-service.md | 16 +- .../architecture/adr-032-typed-events.md | 12 +- .../adr-033-protobuf-inter-module-comm.md | 16 +- .../architecture/adr-034-account-rekeying.md | 18 +- .../adr-035-rosetta-api-support.md | 14 +- .../adr-036-arbitrary-signature.md | 20 +- .../architecture/adr-037-gov-split-vote.md | 8 +- .../architecture/adr-038-state-listening.md | 40 +-- .../architecture/adr-039-epoched-staking.md | 24 +- ...r-040-storage-and-smt-state-commitments.md | 12 +- .../adr-041-in-place-store-migrations.md | 2 +- .../architecture/adr-042-group-module.md | 6 +- docs/build/architecture/adr-043-nft-module.md | 6 +- .../adr-044-protobuf-updates-guidelines.md | 4 +- .../adr-045-check-delivertx-middlewares.md | 6 +- .../architecture/adr-046-module-params.md | 6 +- .../adr-047-extend-upgrade-plan.md | 7 +- .../architecture/adr-048-consensus-fees.md | 6 +- .../architecture/adr-049-state-sync-hooks.md | 10 +- .../adr-050-sign-mode-textual-annex1.md | 13 +- .../adr-050-sign-mode-textual-annex2.md | 4 +- .../architecture/adr-050-sign-mode-textual.md | 20 +- .../adr-053-go-module-refactoring.md | 4 +- .../adr-054-semver-compatible-modules.md | 9 +- docs/build/architecture/adr-055-orm.md | 1 + docs/build/architecture/adr-057-app-wiring.md | 18 +- .../adr-058-auto-generated-cli.md | 2 +- .../build/architecture/adr-059-test-scopes.md | 8 +- docs/build/architecture/adr-060-abci-1.0.md | 4 +- .../architecture/adr-061-liquid-staking.md | 4 +- .../adr-062-collections-state-layer.md | 81 ++++--- .../architecture/adr-063-core-module-api.md | 23 +- docs/build/architecture/adr-064-abci-2.0.md | 28 +-- docs/build/architecture/adr-065-store-v2.md | 10 +- docs/build/architecture/adr-068-preblock.md | 12 +- .../architecture/adr-070-unordered-account.md | 20 +- .../architecture/adr-076-tx-malleability.md | 35 +-- docs/build/architecture/adr-template.md | 2 +- docs/build/build.md | 2 +- docs/build/building-apps/01-app-go-di.md | 10 +- docs/build/building-apps/02-app-mempool.md | 10 +- docs/build/building-apps/03-app-upgrade.md | 10 +- .../build/building-apps/04-vote-extensions.md | 6 +- docs/build/building-apps/05-app-testnet.md | 2 +- docs/build/building-modules/00-intro.md | 2 +- .../building-modules/01-module-manager.md | 14 +- .../02-messages-and-queries.md | 10 +- .../build/building-modules/03-msg-services.md | 10 +- .../05-protobuf-annotations.md | 16 +- .../06-beginblock-endblock.md | 4 +- docs/build/building-modules/06-keeper.md | 4 +- docs/build/building-modules/08-genesis.md | 4 +- .../building-modules/09-module-interfaces.md | 7 +- docs/build/building-modules/11-structure.md | 2 +- docs/build/building-modules/13-upgrade.md | 2 +- docs/build/building-modules/14-simulator.md | 15 +- docs/build/building-modules/15-depinject.md | 2 +- docs/build/building-modules/16-testing.md | 12 +- docs/build/building-modules/17-preblock.md | 9 +- docs/build/migrations/01-intro.md | 2 +- docs/build/migrations/02-upgrade-reference.md | 229 ++---------------- docs/build/migrations/02-upgrading.md | 20 +- docs/build/migrations/03-upgrade-guide.md | 34 +-- docs/build/modules/README.md | 8 +- docs/build/modules/auth/1-vesting.md | 12 +- docs/build/modules/auth/2-tx.md | 4 +- docs/build/modules/auth/README.md | 2 +- docs/build/modules/authz/README.md | 17 +- docs/build/modules/bank/README.md | 2 +- docs/build/modules/circuit/README.md | 93 ++++++- docs/build/modules/crisis/README.md | 2 +- docs/build/modules/distribution/README.md | 6 +- docs/build/modules/epochs/README.md | 2 +- docs/build/modules/evidence/README.md | 2 +- docs/build/modules/feegrant/README.md | 2 +- docs/build/modules/genutil/README.md | 2 +- docs/build/modules/gov/README.md | 24 +- docs/build/modules/group/README.md | 4 +- docs/build/modules/params/README.md | 2 +- docs/build/modules/protocolpool/README.md | 18 +- docs/build/modules/slashing/README.md | 10 +- docs/build/modules/staking/README.md | 10 +- docs/build/modules/upgrade/README.md | 8 +- docs/build/packages/02-collections.md | 4 +- docs/build/packages/README.md | 2 +- docs/build/rfc/rfc/PROCESS.md | 8 +- docs/build/rfc/rfc/rfc-001-tx-validation.md | 6 +- docs/build/rfc/rfc/rfc-template.md | 2 +- docs/build/spec/README.md | 2 +- docs/build/spec/addresses/bech32.md | 2 +- .../spec/fee_distribution/f1_fee_distr.tex | 4 +- docs/build/spec/store/README.md | 8 +- docs/build/tooling/00-protobuf.md | 18 +- docs/build/tooling/01-cosmovisor.md | 2 +- docs/build/tooling/README.md | 4 +- docs/learn/advanced/00-baseapp.md | 26 +- docs/learn/advanced/01-transactions.md | 4 +- docs/learn/advanced/02-context.md | 8 +- docs/learn/advanced/04-store.md | 2 +- docs/learn/advanced/05-encoding.md | 4 +- docs/learn/advanced/06-grpc_rest.md | 2 +- docs/learn/advanced/07-cli.md | 4 +- docs/learn/advanced/08-events.md | 4 +- docs/learn/advanced/09-telemetry.md | 4 +- docs/learn/advanced/11-runtx_middleware.md | 6 +- docs/learn/advanced/15-upgrade.md | 4 +- docs/learn/advanced/17-autocli.md | 8 +- docs/learn/beginner/00-app-anatomy.md | 10 +- docs/learn/beginner/01-tx-lifecycle.md | 16 +- docs/learn/beginner/02-query-lifecycle.md | 12 +- docs/learn/beginner/03-accounts.md | 4 +- docs/learn/beginner/04-gas-fees.md | 18 +- docs/learn/intro/00-overview.md | 2 +- docs/learn/intro/01-why-app-specific.md | 4 +- docs/learn/intro/02-sdk-app-architecture.md | 2 +- docs/learn/learn.md | 2 +- docs/user/run-node/00-keyring.md | 10 +- docs/user/run-node/01-run-node.md | 4 +- docs/user/run-node/02-interact-node.md | 12 +- docs/user/run-node/03-txs.md | 6 +- docs/user/run-node/06-run-production.md | 6 +- docs/user/user.md | 2 +- .../build/migrations/02-upgrading.md | 20 +- .../build/modules/circuit/README.md | 87 +++++++ .../build/modules/staking/README.md | 4 +- 148 files changed, 902 insertions(+), 868 deletions(-) diff --git a/docs/build/abci/00-introduction.md b/docs/build/abci/00-introduction.md index cec8a7401..fa648be05 100644 --- a/docs/build/abci/00-introduction.md +++ b/docs/build/abci/00-introduction.md @@ -19,7 +19,7 @@ The 5 methods introduced in ABCI 2.0 are: Based on validator voting power, CometBFT chooses a block proposer and calls `PrepareProposal` on the block proposer's application (Cosmos SDK). The selected block proposer is responsible for collecting outstanding transactions from the mempool, adhering to the application's specifications. The application can enforce custom transaction ordering and incorporate additional transactions, potentially generated from vote extensions in the previous block. -To perform this manipulation on the application side, a custom handler must be implemented. By default, the Cosmos SDK provides `PrepareProposalHandler`, used in conjunction with an application specific mempool. A custom handler can be written by application developer, if a noop handler provided, all transactions are considered valid. +To perform this manipulation on the application side, a custom handler must be implemented. By default, the Cosmos SDK provides `PrepareProposalHandler`, used in conjunction with an application specific mempool. A custom handler can be written by an application developer, if a noop handler is provided, all transactions are considered valid. Please note that vote extensions will only be available on the following height in which vote extensions are enabled. More information about vote extensions can be found [here](https://docs.cosmos.network/main/build/abci/vote-extensions). @@ -39,7 +39,7 @@ These methods allow applications to extend the voting process by requiring valid If vote extensions are enabled, `ExtendVote` will be called on every validator and each one will return its vote extension which is in practice a bunch of bytes. As mentioned above this data (vote extension) can only be retrieved in the next block height during `PrepareProposal`. Additionally, this data can be arbitrary, but in the provided tutorials, it serves as an oracle or proof of transactions in the mempool. Essentially, vote extensions are processed and injected as transactions. Examples of use-cases for vote extensions include prices for a price oracle or encryption shares for an encrypted transaction mempool. `ExtendVote` CAN be non-deterministic. -`VerifyVoteExtensions` is performed on every validator multiple times in order to verify other validators' vote extensions. This check is submitted to validate the integrity and validity of the vote extensions preventing malicious or invalid vote extensions. +`VerifyVoteExtensions` is performed on every validator multiple times in order to verify other validators' vote extensions. This check is performed to validate the integrity and validity of the vote extensions preventing malicious or invalid vote extensions. Additionally, applications must keep the vote extension data concise as it can degrade the performance of their chain, see testing results [here](https://docs.cometbft.com/v0.38/qa/cometbft-qa-38#vote-extensions-testbed). diff --git a/docs/build/abci/02-process-proposal.md b/docs/build/abci/02-process-proposal.md index c1faf9f40..221aa66d4 100644 --- a/docs/build/abci/02-process-proposal.md +++ b/docs/build/abci/02-process-proposal.md @@ -7,7 +7,7 @@ default implementation of `PrepareProposal` runs basic validity checks on each transaction. Note, `ProcessProposal` MUST be deterministic. Non-deterministic behaviors will cause apphash mismatches. -This means if `ProcessProposal` panics or fails and we reject, all honest validator +This means that if `ProcessProposal` panics or fails and we reject, all honest validator processes should reject (i.e., prevote nil). If so, CometBFT will start a new round with a new block proposal and the same cycle will happen with `PrepareProposal` and `ProcessProposal` for the new proposal. diff --git a/docs/build/abci/03-vote-extensions.md b/docs/build/abci/03-vote-extensions.md index f3744660a..a57395e30 100644 --- a/docs/build/abci/03-vote-extensions.md +++ b/docs/build/abci/03-vote-extensions.md @@ -11,7 +11,7 @@ ABCI 2.0 (colloquially called ABCI++) allows an application to extend a pre-comm validator process. The Cosmos SDK defines [`baseapp.ExtendVoteHandler`](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/abci.go#L32): ```go -type ExtendVoteHandler func(Context, *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) +type ExtendVoteHandler func(Context, *abci.ExtendVoteRequest) (*abci.ExtendVoteResponse, error) ``` An application can set this handler in `app.go` via the `baseapp.SetExtendVoteHandler` @@ -38,7 +38,7 @@ other validators when validating their pre-commits. For a given vote extension, this process MUST be deterministic. The Cosmos SDK defines [`sdk.VerifyVoteExtensionHandler`](https://github.com/cosmos/cosmos-sdk/blob/v0.50.1/types/abci.go#L29-L31): ```go -type VerifyVoteExtensionHandler func(Context, *abci.RequestVerifyVoteExtension) (*abci.ResponseVerifyVoteExtension, error) +type VerifyVoteExtensionHandler func(Context, *abci.VerifyVoteExtensionRequest) (*abci.VerifyVoteExtensionResponse, error) ``` An application can set this handler in `app.go` via the `baseapp.SetVerifyVoteExtensionHandler` @@ -78,7 +78,7 @@ will be available to the application during the subsequent `FinalizeBlock` call. An example of how a pre-FinalizeBlock hook could look like is shown below: ```go -app.SetPreBlocker(func(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { +app.SetPreBlocker(func(ctx sdk.Context, req *abci.FinalizeBlockRequest) error { allVEs := []VE{} // store all parsed vote extensions here for _, tx := range req.Txs { // define a custom function that tries to parse the tx as a vote extension diff --git a/docs/build/architecture/PROCESS.md b/docs/build/architecture/PROCESS.md index 0e9a34eb7..5ba1b86cd 100644 --- a/docs/build/architecture/PROCESS.md +++ b/docs/build/architecture/PROCESS.md @@ -8,7 +8,7 @@ ## What is an ADR? -An ADR is a document to document an implementation and design that may or may not have been discussed in an RFC. While an RFC is meant to replace synchronous communication in a distributed environment, an ADR is meant to document an already made decision. An ADR won't come with much of a communication overhead because the discussion was recorded in an RFC or a synchronous discussion. If the consensus came from a synchronous discussion, then a short excerpt should be added to the ADR to explain the goals. +An ADR is a document that documents an implementation and design that may or may not have been discussed in an RFC. While an RFC is meant to replace synchronous communication in a distributed environment, an ADR is meant to document an already made decision. An ADR won't come with much of a communication overhead because the discussion was recorded in an RFC or a synchronous discussion. If the consensus came from a synchronous discussion, then a short excerpt should be added to the ADR to explain the goals. ## ADR life cycle @@ -20,7 +20,7 @@ ADR creation is an **iterative** process. Instead of having a high amount of com 3. If a _proposed_ ADR is merged, then it should clearly document outstanding issues either in ADR document notes or in a GitHub Issue. -4. The PR SHOULD always be merged. In the case of a faulty ADR, we still prefer to merge it with a _rejected_ status. The only time the ADR SHOULD NOT be merged is if the author abandons it. +4. The PR SHOULD always be merged. In the case of a faulty ADR, we still prefer to merge it with a _rejected_ status. The only time the ADR SHOULD NOT be merged is if the author abandons it. 5. Merged ADRs SHOULD NOT be pruned. @@ -44,15 +44,15 @@ DRAFT -> PROPOSED -> LAST CALL yyyy-mm-dd -> ACCEPTED | REJECTED -> SUPERSEDED b ABANDONED ``` -* `DRAFT`: [optional] an ADR which is a work in progress, not being ready for a general review. This is to present an early work and get early feedback in a Draft Pull Request form. +* `DRAFT`: [optional] an ADR which is a work in progress, not ready for a general review. This is to present an early work and get early feedback in a Draft Pull Request form. * `PROPOSED`: an ADR covering a full solution architecture and still in the review - project stakeholders haven't reached an agreement yet. * `LAST CALL `: [optional] Notify that we are close to accepting updates. Changing a status to `LAST CALL` means that social consensus (of Cosmos SDK maintainers) has been reached, and we still want to give it a time to let the community react or analyze. -* `ACCEPTED`: ADR which will represent a currently implemented or to be implemented architecture design. +* `ACCEPTED`: an ADR that represents a currently implemented or to be implemented architecture design. * `REJECTED`: ADR can go from PROPOSED or ACCEPTED to rejected if the consensus among project stakeholders will decide so. -* `SUPERSEDED by ADR-xxx`: ADR which has been superseded by a new ADR. +* `SUPERSEDED by ADR-xxx`: an ADR that has been superseded by a new ADR. * `ABANDONED`: the ADR is no longer pursued by the original authors. ## Language used in ADR * The context/background should be written in the present tense. -* Avoid using a first, personal form. +* Avoid using the first person. diff --git a/docs/build/architecture/README.md b/docs/build/architecture/README.md index fa4ca0225..e75d9e258 100644 --- a/docs/build/architecture/README.md +++ b/docs/build/architecture/README.md @@ -8,7 +8,7 @@ This is a location to record all high-level architecture decisions in the Cosmos An Architectural Decision (**AD**) is a software design choice that addresses a functional or non-functional requirement that is architecturally significant. An Architecturally Significant Requirement (**ASR**) is a requirement that has a measurable effect on a software system’s architecture and quality. -An Architectural Decision Record (**ADR**) captures a single AD, such as often done when writing personal notes or meeting minutes; the collection of ADRs created and maintained in a project constitute its decision log. All these are within the topic of Architectural Knowledge Management (AKM). +An Architectural Decision Record (**ADR**) captures a single AD, such as is often done when writing personal notes or meeting minutes; the collection of ADRs created and maintained in a project constitute its decision log. All these are within the topic of Architectural Knowledge Management (AKM). You can read more about the ADR concept in this [blog post](https://product.reverb.com/documenting-architecture-decisions-the-reverb-way-a3563bb24bd0#.78xhdix6t). @@ -25,12 +25,12 @@ An ADR should provide: Note the distinction between an ADR and a spec. The ADR provides the context, intuition, reasoning, and justification for a change in architecture, or for the architecture of something -new. The spec is much more compressed and streamlined summary of everything as +new. The spec is a much more compressed and streamlined summary of everything as it stands today. If recorded decisions turned out to be lacking, convene a discussion, record the new decisions here, and then modify the code to match. -## Creating new ADR +## Creating a new ADR Read about the [PROCESS](./PROCESS.md). diff --git a/docs/build/architecture/adr-004-split-denomination-keys.md b/docs/build/architecture/adr-004-split-denomination-keys.md index 8abf25fda..53c7b0977 100644 --- a/docs/build/architecture/adr-004-split-denomination-keys.md +++ b/docs/build/architecture/adr-004-split-denomination-keys.md @@ -74,7 +74,7 @@ This will result in the balances being indexed by the byte representation of `DelegateCoins()` and `UndelegateCoins()` will be altered to only load each individual account balance by denomination found in the (un)delegation amount. As a result, -any mutations to the account balance by will made by denomination. +any mutations to the account balance will be made by denomination. `SubtractCoins()` and `AddCoins()` will be altered to read & write the balances directly instead of calling `GetCoins()` / `SetCoins()` (which no longer exist). diff --git a/docs/build/architecture/adr-006-secret-store-replacement.md b/docs/build/architecture/adr-006-secret-store-replacement.md index fe2e25467..500ba40ca 100644 --- a/docs/build/architecture/adr-006-secret-store-replacement.md +++ b/docs/build/architecture/adr-006-secret-store-replacement.md @@ -21,7 +21,7 @@ We are seeking solution that provides a common abstraction layer to the many dif We recommend replacing the current Keybase backend based on LevelDB with [Keyring](https://github.com/99designs/keyring) by 99 designs. This application is designed to provide a common abstraction and uniform interface between many secret stores and is used by AWS Vault application by 99-designs application. -This appears to fulfill the requirement of protecting both key material and metadata from rouge software on a user’s machine. +This appears to fulfill the requirement of protecting both key material and metadata from rogue software on a user’s machine. ## Status diff --git a/docs/build/architecture/adr-007-specialization-groups.md b/docs/build/architecture/adr-007-specialization-groups.md index 58f78abf5..bafcc697b 100644 --- a/docs/build/architecture/adr-007-specialization-groups.md +++ b/docs/build/architecture/adr-007-specialization-groups.md @@ -51,7 +51,7 @@ the members already in a specialization group to internally elect new members, or maybe the community may assign a permission to a particular specialization group to appoint members to other 3rd party groups. The sky is really the limit as to how membership admittance can be structured. We attempt to capture -some of these possiblities in a common interface dubbed the `Electionator`. For +some of these possibilities in a common interface dubbed the `Electionator`. For its initial implementation as a part of this ADR we recommend that the general election abstraction (`Electionator`) is provided as well as a basic implementation of that abstraction which allows for a continuous election of diff --git a/docs/build/architecture/adr-008-dCERT-group.md b/docs/build/architecture/adr-008-dCERT-group.md index 2b2d2b826..5ee5670bd 100644 --- a/docs/build/architecture/adr-008-dCERT-group.md +++ b/docs/build/architecture/adr-008-dCERT-group.md @@ -151,7 +151,7 @@ they should all be severely slashed. ## Status -> Proposed +Proposed ## Consequences diff --git a/docs/build/architecture/adr-010-modular-antehandler.md b/docs/build/architecture/adr-010-modular-antehandler.md index 386af1a77..4eb5b8855 100644 --- a/docs/build/architecture/adr-010-modular-antehandler.md +++ b/docs/build/architecture/adr-010-modular-antehandler.md @@ -142,7 +142,7 @@ type ModuleManager struct { } func (mm ModuleManager) GetAnteHandler() AnteHandler { - retun Chainer(mm.AnteHandlerOrder) + return Chainer(mm.AnteHandlerOrder) } ``` diff --git a/docs/build/architecture/adr-012-state-accessors.md b/docs/build/architecture/adr-012-state-accessors.md index 93600000f..009e34927 100644 --- a/docs/build/architecture/adr-012-state-accessors.md +++ b/docs/build/architecture/adr-012-state-accessors.md @@ -67,7 +67,7 @@ func (Value) Set(ctx Context, o interface{}) {} // Check if a raw value exists func (Value) Exists(ctx Context) bool {} -// Delete a raw value value +// Delete a raw value func (Value) Delete(ctx Context) {} ``` @@ -92,7 +92,7 @@ func (Mapping) Set(ctx Context, key []byte, o interface{}) {} // Check if a raw value exists func (Mapping) Has(ctx Context, key []byte) bool {} -// Delete a raw value value +// Delete a raw value func (Mapping) Delete(ctx Context, key []byte) {} ``` diff --git a/docs/build/architecture/adr-014-proportional-slashing.md b/docs/build/architecture/adr-014-proportional-slashing.md index 63cd04dee..976136a9f 100644 --- a/docs/build/architecture/adr-014-proportional-slashing.md +++ b/docs/build/architecture/adr-014-proportional-slashing.md @@ -49,7 +49,7 @@ Griefing, the act of intentionally getting oneself slashed in order to make anot ### Implementation -In the slashing module, we will add two queues that will track all of the recent slash events. For double sign faults, we will define "recent slashes" as ones that have occurred within the last `unbonding period`. For liveness faults, we will define "recent slashes" as ones that have occurred withing the last `jail period`. +In the slashing module, we will add two queues that will track all of the recent slash events. For double sign faults, we will define "recent slashes" as ones that have occurred within the last `unbonding period`. For liveness faults, we will define "recent slashes" as ones that have occurred within the last `jail period`. ```go type SlashEvent struct { diff --git a/docs/build/architecture/adr-016-validator-consensus-key-rotation.md b/docs/build/architecture/adr-016-validator-consensus-key-rotation.md index 1d91a8de7..37ba3e52f 100644 --- a/docs/build/architecture/adr-016-validator-consensus-key-rotation.md +++ b/docs/build/architecture/adr-016-validator-consensus-key-rotation.md @@ -9,30 +9,30 @@ Validator consensus key rotation feature has been discussed and requested for a long time, for the sake of safer validator key management policy (e.g. https://github.com/tendermint/tendermint/issues/1136). So, we suggest one of the simplest form of validator consensus key rotation implementation mostly onto Cosmos SDK. -We don't need to make any update on consensus logic in Tendermint because Tendermint does not have any mapping information of consensus key and validator operator key, meaning that from Tendermint point of view, a consensus key rotation of a validator is simply a replacement of a consensus key to another. +We don't need to make any update on consensus logic in Tendermint because Tendermint does not have any mapping information of consensus key and validator operator key, meaning that from Tendermint's point of view, a consensus key rotation of a validator is simply a replacement of a consensus key to another. -Also, it should be noted that this ADR includes only the simplest form of consensus key rotation without considering multiple consensus keys concept. Such multiple consensus keys concept shall remain a long term goal of Tendermint and Cosmos SDK. +Also, it should be noted that this ADR includes only the simplest form of consensus key rotation without considering the multiple consensus keys concept. Such multiple consensus keys concept shall remain a long term goal of Tendermint and Cosmos SDK. ## Decision ### Pseudo procedure for consensus key rotation * create new random consensus key. -* create and broadcast a transaction with a `MsgRotateConsPubKey` that states the new consensus key is now coupled with the validator operator with signature from the validator's operator key. +* create and broadcast a transaction with a `MsgRotateConsPubKey` that states the new consensus key is now coupled with the validator operator with a signature from the validator's operator key. * old consensus key becomes unable to participate on consensus immediately after the update of key mapping state on-chain. * start validating with new consensus key. -* validators using HSM and KMS should update the consensus key in HSM to use the new rotated key after the height `h` when `MsgRotateConsPubKey` committed to the blockchain. +* validators using HSM and KMS should update the consensus key in HSM to use the new rotated key after the height `h` when `MsgRotateConsPubKey` is committed to the blockchain. ### Considerations * consensus key mapping information management strategy * store history of each key mapping changes in the kvstore. - * the state machine can search corresponding consensus key paired with given validator operator for any arbitrary height in a recent unbonding period. + * the state machine can search corresponding consensus key paired with the given validator operator for any arbitrary height in a recent unbonding period. * the state machine does not need any historical mapping information which is past more than unbonding period. * key rotation costs related to LCD and IBC - * LCD and IBC will have traffic/computation burden when there exists frequent power changes + * LCD and IBC will have a traffic/computation burden when there exists frequent power changes * In current Tendermint design, consensus key rotations are seen as power changes from LCD or IBC perspective - * Therefore, to minimize unnecessary frequent key rotation behavior, we limited maximum number of rotation in recent unbonding period and also applied exponentially increasing rotation fee + * Therefore, to minimize unnecessary frequent key rotation behavior, we limited the maximum number of rotation in recent unbonding period and also applied exponentially increasing rotation fee * limits * a validator cannot rotate its consensus key more than `MaxConsPubKeyRotations` time for any unbonding period, to prevent spam. * parameters can be decided by governance and stored in genesis file. @@ -40,11 +40,11 @@ Also, it should be noted that this ADR includes only the simplest form of consen * a validator should pay `KeyRotationFee` to rotate the consensus key which is calculated as below * `KeyRotationFee` = (max(`VotingPowerPercentage` *100, 1)* `InitialKeyRotationFee`) * 2^(number of rotations in `ConsPubKeyRotationHistory` in recent unbonding period) * evidence module - * evidence module can search corresponding consensus key for any height from slashing keeper so that it can decide which consensus key is supposed to be used for given height. + * evidence module can search corresponding consensus key for any height from slashing keeper so that it can decide which consensus key is supposed to be used for the given height. * abci.ValidatorUpdate * tendermint already has ability to change a consensus key by ABCI communication(`ValidatorUpdate`). * validator consensus key update can be done via creating new + delete old by change the power to zero. - * therefore, we expect we even do not need to change tendermint codebase at all to implement this feature. + * therefore, we expect we do not even need to change Tendermint codebase at all to implement this feature. * new genesis parameters in `staking` module * `MaxConsPubKeyRotations` : maximum number of rotation can be executed by a validator in recent unbonding period. default value 10 is suggested(11th key rotation will be rejected) * `InitialKeyRotationFee` : the initial key rotation fee when no key rotation has happened in recent unbonding period. default value 1atom is suggested(1atom fee for the first key rotation in recent unbonding period) @@ -108,12 +108,12 @@ Proposed ### Positive -* Validators can immediately or periodically rotate their consensus key to have better security policy +* Validators can immediately or periodically rotate their consensus key to have a better security policy * improved security against Long-Range attacks (https://nearprotocol.com/blog/long-range-attacks-and-a-new-fork-choice-rule) given a validator throws away the old consensus key(s) ### Negative -* Slash module needs more computation because it needs to lookup corresponding consensus key of validators for each height +* Slash module needs more computation because it needs to look up the corresponding consensus key of validators for each height * frequent key rotations will make light client bisection less efficient ### Neutral diff --git a/docs/build/architecture/adr-018-extendable-voting-period.md b/docs/build/architecture/adr-018-extendable-voting-period.md index 5e8f058d1..2624e21e6 100644 --- a/docs/build/architecture/adr-018-extendable-voting-period.md +++ b/docs/build/architecture/adr-018-extendable-voting-period.md @@ -27,7 +27,7 @@ There is a new `Msg` type called `MsgExtendVotingPeriod`, which can be sent by a So for example, if the `MaxVotingPeriodExtension` is set to 100 Days, then anyone with 1% of voting power can extend the voting power by 1 day. If 33% of voting power has sent the message, the voting period will be extended by 33 days. Thus, if absolutely everyone chooses to extend the voting period, the absolute maximum voting period will be `MinVotingPeriod + MaxVotingPeriodExtension`. -This system acts as a sort of distributed coordination, where individual stakers choosing to extend or not, allows the system the guage the conentiousness/complexity of the proposal. It is extremely unlikely that many stakers will choose to extend at the exact same time, it allows stakers to view how long others have already extended thus far, to decide whether or not to extend further. +This system acts as a sort of distributed coordination, where individual stakers choosing to extend or not, allows the system the gauge the contentiousness/complexity of the proposal. It is extremely unlikely that many stakers will choose to extend at the exact same time, it allows stakers to view how long others have already extended thus far, to decide whether or not to extend further. ### Dealing with Unbonding/Redelegation diff --git a/docs/build/architecture/adr-019-protobuf-state-encoding.md b/docs/build/architecture/adr-019-protobuf-state-encoding.md index 5ad1b953e..d0fc506e2 100644 --- a/docs/build/architecture/adr-019-protobuf-state-encoding.md +++ b/docs/build/architecture/adr-019-protobuf-state-encoding.md @@ -28,7 +28,7 @@ From the Amino docs: Amino also aims to have the following goals (not a complete list): -* Binary bytes must be decode-able with a schema. +* Binary bytes must be decodable with a schema. * Schema must be upgradeable. * The encoder and decoder logic must be reasonably simple. @@ -65,7 +65,7 @@ will provide two concrete implementations of the `Marshaler` interface: `AminoCo * `AminoCodec`: Uses Amino for both binary and JSON encoding. * `ProtoCodec`: Uses Protobuf for both binary and JSON encoding. -Modules will use whichever codec that is instantiated in the app. By default, the Cosmos SDK's `simapp` +Modules will use whichever codec is instantiated in the app. By default, the Cosmos SDK's `simapp` instantiates a `ProtoCodec` as the concrete implementation of `Marshaler`, inside the `MakeTestEncodingConfig` function. This can be easily overwritten by app developers if they so desire. @@ -136,7 +136,7 @@ to be reimplemented for each chain The main counter-argument to using `Any` centers around its additional space and possibly performance overhead. The space overhead could be dealt with using compression at the persistence layer in the future and the performance impact -is likely to be small. Thus, not using `Any` is seem as a pre-mature optimization, +is likely to be small. Thus, not using `Any` is seen as a pre-mature optimization, with user experience as the higher order concern. Note, that given the Cosmos SDK's decision to adopt the `Codec` interfaces described @@ -144,7 +144,7 @@ above, apps can still choose to use `oneof` to encode state and transactions but it is not the recommended approach. If apps do choose to use `oneof`s instead of `Any` they will likely lose compatibility with client apps that support multiple chains. Thus developers should think carefully about whether -they care more about what is possibly a pre-mature optimization or end-user +they care more about what is possibly a premature optimization or end-user and client developer UX. ### Safe usage of `Any` @@ -169,7 +169,7 @@ type InterfaceRegistry interface { // registry.RegisterInterface("cosmos_sdk.Msg", (*sdk.Msg)(nil)) RegisterInterface(protoName string, iface interface{}) - // RegisterImplementations registers impls as a concrete implementations of + // RegisterImplementations registers impls as concrete implementations of // the interface iface // Ex: // registry.RegisterImplementations((*sdk.Msg)(nil), &MsgSend{}, &MsgMultiSend{}) @@ -226,7 +226,7 @@ every module that implements it in order to populate the `InterfaceRegistry`. ### Using `Any` to encode state -The Cosmos SDK will provide support methods `MarshalInterface` and `UnmarshalInterface` to hide a complexity of wrapping interface types into `Any` and allow easy serialization. +The Cosmos SDK will provide support methods `MarshalInterface` and `UnmarshalInterface` to hide the complexity of wrapping interface types into `Any` and allow easy serialization. ```go import "github.com/cosmos/cosmos-sdk/codec" @@ -245,7 +245,7 @@ func UnmarshalEvidence(cdc codec.BinaryCodec, bz []byte) (eviexported.Evidence, ### Using `Any` in `sdk.Msg`s -A similar concept is to be applied for messages that contain interfaces fields. +A similar concept is to be applied for messages that contain interface fields. For example, we can define `MsgSubmitEvidence` as follows where `Evidence` is an interface: @@ -333,7 +333,7 @@ For a more complete comparison to alternative protocols, see [here](https://code ### Cap'n Proto While [Cap’n Proto](https://capnproto.org/) does seem like an advantageous alternative to Protobuf -due to it's native support for interfaces/generics and built in canonicalization, it does lack the +due to its native support for interfaces/generics and built-in canonicalization, it does lack the rich client ecosystem compared to Protobuf and is a bit less mature. ### FlatBuffers @@ -342,7 +342,7 @@ rich client ecosystem compared to Protobuf and is a bit less mature. primary difference being that FlatBuffers does not need a parsing/unpacking step to a secondary representation before you can access data, often coupled with per-object memory allocation. -However, it would require great efforts into research and full understanding the scope of the migration +However, it would require great efforts into research and a full understanding the scope of the migration and path forward -- which isn't immediately clear. In addition, FlatBuffers aren't designed for untrusted inputs. diff --git a/docs/build/architecture/adr-020-protobuf-transaction-encoding.md b/docs/build/architecture/adr-020-protobuf-transaction-encoding.md index b26f394bd..9633fb20b 100644 --- a/docs/build/architecture/adr-020-protobuf-transaction-encoding.md +++ b/docs/build/architecture/adr-020-protobuf-transaction-encoding.md @@ -44,18 +44,18 @@ approach to the approach described below. ### Transactions Since interface values are encoded with `google.protobuf.Any` in state (see [ADR 019](adr-019-protobuf-state-encoding.md)), -`sdk.Msg`s are encoding with `Any` in transactions. +`sdk.Msg`s are encoded with `Any` in transactions. One of the main goals of using `Any` to encode interface values is to have a core set of types which is reused by apps so that clients can safely be compatible with as many chains as possible. It is one of the goals of this specification to provide a flexible cross-chain transaction -format that can serve a wide variety of use cases without breaking client +format that can serve a wide variety of use cases without breaking the client compatibility. In order to facilitate signing, transactions are separated into `TxBody`, -which will be re-used by `SignDoc` below, and `signatures`: +which will be reused by `SignDoc` below, and `signatures`: ```protobuf // types/types.proto @@ -69,7 +69,7 @@ message Tx { repeated bytes signatures = 3; } -// A variant of Tx that pins the signer's exact binary represenation of body and +// A variant of Tx that pins the signer's exact binary representation of body and // auth_info. This is used for signing, broadcasting and verification. The binary // `serialize(tx: TxRaw)` is stored in Tendermint and the hash `sha256(serialize(tx: TxRaw))` // becomes the "txhash", commonly used as the transaction ID. @@ -173,7 +173,7 @@ All of the signing modes below aim to provide the following guarantees: * **Predictable Gas**: if I am signing a transaction where I am paying a fee, the final gas is fully dependent on what I am signing -These guarantees give the maximum amount confidence to message signers that +These guarantees give the maximum amount of confidence to message signers that manipulation of `Tx`s by intermediaries can't result in any meaningful changes. #### `SIGN_MODE_DIRECT` @@ -228,7 +228,7 @@ Signature verifiers do: In order to support legacy wallets and exchanges, Amino JSON will be temporarily supported transaction signing. Once wallets and exchanges have had a -chance to upgrade to protobuf based signing, this option will be disabled. In +chance to upgrade to protobuf-based signing, this option will be disabled. In the meantime, it is foreseen that disabling the current Amino signing would cause too much breakage to be feasible. Note that this is mainly a requirement of the Cosmos Hub and other chains may choose to disable Amino signing immediately. @@ -260,7 +260,7 @@ by `SIGN_MODE_TEXTUAL` when it is implemented. ### Unknown Field Filtering -Unknown fields in protobuf messages should generally be rejected by transaction +Unknown fields in protobuf messages should generally be rejected by the transaction processors because: * important data may be present in the unknown fields, that if ignored, will @@ -415,7 +415,7 @@ To generate a signature in `SIGN_MODE_DIRECT_AUX` these steps would be followed: // PublicKey is included in SignDocAux : // 1. as a special case for multisig public keys. For multisig public keys, // the signer should use the top-level multisig public key they are signing - // against, not their own public key. This is to prevent against a form + // against, not their own public key. This is to prevent a form // of malleability where a signature could be taken out of context of the // multisig key that was intended to be signed for // 2. to guard against scenario where configuration information is encoded @@ -431,7 +431,7 @@ To generate a signature in `SIGN_MODE_DIRECT_AUX` these steps would be followed: ``` 2. Sign the encoded `SignDocAux` bytes -3. Send their signature and `SignerInfo` to primary signer who will then +3. Send their signature and `SignerInfo` to the primary signer who will then sign and broadcast the final transaction (with `SIGN_MODE_DIRECT` and `AuthInfo` added) once enough signatures have been collected diff --git a/docs/build/architecture/adr-021-protobuf-query-encoding.md b/docs/build/architecture/adr-021-protobuf-query-encoding.md index a90e807d5..ba155cba2 100644 --- a/docs/build/architecture/adr-021-protobuf-query-encoding.md +++ b/docs/build/architecture/adr-021-protobuf-query-encoding.md @@ -15,7 +15,7 @@ This ADR is a continuation of the motivation, design, and context established in [ADR 020](./adr-020-protobuf-transaction-encoding.md), namely, we aim to design the Protocol Buffer migration path for the client-side of the Cosmos SDK. -This ADR continues from [ADD 020](./adr-020-protobuf-transaction-encoding.md) +This ADR continues from [ADR 020](./adr-020-protobuf-transaction-encoding.md) to specify the encoding of queries. ## Decision @@ -50,7 +50,7 @@ provide query methods that expose these interfaces via `google.protobuf.Any`. There is a concern on the transaction level that the overhead of `Any` is too high to justify its usage. However for queries this is not a concern, and providing generic module-level queries that use `Any` does not preclude apps -from also providing app-level queries that return use the app-level `oneof`s. +from also providing app-level queries that return using the app-level `oneof`s. A hypothetical example for the `gov` module would look something like: @@ -176,7 +176,7 @@ service Query { } ``` -grpc-gateway will work direcly against the GRPC proxy described above which will +grpc-gateway will work directly against the GRPC proxy described above which will translate requests to ABCI queries under the hood. grpc-gateway can also generate Swagger definitions automatically. @@ -205,7 +205,7 @@ type QueryClient interface { ``` Via a small patch to gogo protobuf ([gogo/protobuf#675](https://github.com/gogo/protobuf/pull/675)) -we have tweaked the grpc codegen to use an interface rather than concrete type +we have tweaked the grpc codegen to use an interface rather than a concrete type for the generated client struct. This allows us to also reuse the GRPC infrastructure for ABCI client queries. diff --git a/docs/build/architecture/adr-022-custom-panic-handling.md b/docs/build/architecture/adr-022-custom-panic-handling.md index 8cb5d9687..a99868b27 100644 --- a/docs/build/architecture/adr-022-custom-panic-handling.md +++ b/docs/build/architecture/adr-022-custom-panic-handling.md @@ -23,11 +23,11 @@ We propose middleware-solution, which could help developers implement the follow * call panic for specific error cases; It will also make `OutOfGas` case and `default` case one of the middlewares. -`Default` case wraps recovery object to an error and logs it ([example middleware implementation](#Recovery-middleware)). +`Default` case wraps recovery object to an error and logs it ([example middleware implementation](#recovery-middleware)). Our project has a sidecar service running alongside the blockchain node (smart contracts virtual machine). It is essential that node <-> sidecar connectivity stays stable for TXs processing. So when the communication breaks we need -to crash the node and reboot it once the problem is solved. That behaviour makes node's state machine execution +to crash the node and reboot it once the problem is solved. That behaviour makes the node's state machine execution deterministic. As all keeper panics are caught by runTx's `defer()` handler, we have to adjust the BaseApp code in order to customize it. @@ -37,8 +37,8 @@ in order to customize it. #### Overview -Instead of hardcoding custom error handling into BaseApp we suggest using set of middlewares which can be customized -externally and will allow developers use as many custom error handlers as they want. Implementation with tests +Instead of hardcoding custom error handling into BaseApp we suggest using a set of middlewares which can be customized +externally and will allow developers to use as many custom error handlers as they want. Implementation with tests can be found [here](https://github.com/cosmos/cosmos-sdk/pull/6053). #### Implementation details @@ -52,9 +52,9 @@ New `RecoveryHandler` type added. `recoveryObj` input argument is an object retu type RecoveryHandler func(recoveryObj interface{}) error ``` -Handler should type assert (or other methods) an object to define if object should be handled. -`nil` should be returned if input object can't be handled by that `RecoveryHandler` (not a handler's target type). -Not `nil` error should be returned if input object was handled and middleware chain execution should be stopped. +Handler should type assert (or other methods) an object to define if the object should be handled. +`nil` should be returned if the input object can't be handled by that `RecoveryHandler` (not a handler's target type). +Not `nil` error should be returned if the input object was handled and the middleware chain execution should be stopped. An example: @@ -196,11 +196,11 @@ This method would prepend handlers to an existing chain. ### Positive -* Developers of Cosmos SDK based projects can add custom panic handlers to: +* Developers of Cosmos SDK-based projects can add custom panic handlers to: * add error context for custom panic sources (panic inside of custom keepers); * emit `panic()`: passthrough recovery object to the Tendermint core; * other necessary handling; -* Developers can use standard Cosmos SDK `BaseApp` implementation, rather that rewriting it in their projects; +* Developers can use standard Cosmos SDK `BaseApp` implementation, rather than rewriting it in their projects; * Proposed solution doesn't break the current "standard" `runTx()` flow; ### Negative diff --git a/docs/build/architecture/adr-023-protobuf-naming.md b/docs/build/architecture/adr-023-protobuf-naming.md index a192dfce3..466207600 100644 --- a/docs/build/architecture/adr-023-protobuf-naming.md +++ b/docs/build/architecture/adr-023-protobuf-naming.md @@ -70,7 +70,7 @@ Further guidelines to be described below. Names should be descriptive enough to convey their meaning and distinguish them from other names. -Given that we are using fully-qualifed names within +Given that we are using fully-qualified names within `google.protobuf.Any` as well as within gRPC query routes, we should aim to keep names concise, without going overboard. The general rule of thumb should be if a shorter name would convey more or else the same thing, pick the shorter @@ -117,7 +117,7 @@ Instead of breaking things, we should make every effort to evolve schemas rather to prevent such breakage. With that in mind, different stable versions (i.e. `v1` or `v2`) of a package should more or less be considered -different packages and this should be last resort approach for upgrading protobuf schemas. Scenarios where creating +different packages and this should be a last resort approach for upgrading protobuf schemas. Scenarios where creating a `v2` may make sense are: * we want to create a new module with similar functionality to an existing module and adding `v2` is the most natural @@ -135,14 +135,14 @@ stable package (i.e. `v1` or `v2`) should be preferred * a package _should_ be marked as `alpha` _if and only if_ there are active discussions to remove or significantly alter the package in the near future * a package _should_ be marked as `beta` _if and only if_ there is an active discussion to -significantly refactor/rework the functionality in the near future but not remove it +significantly refactor/rework the functionality in the near future but do not remove it * modules _can and should_ have types in both stable (i.e. `v1` or `v2`) and unstable (`alpha` or `beta`) packages. _`alpha` and `beta` should not be used to avoid responsibility for maintaining compatibility._ Whenever code is released into the wild, especially on a blockchain, there is a high cost to changing things. In some cases, for instance with immutable smart contracts, a breaking change may be impossible to fix. -When marking something as `alpha` or `beta`, maintainers should ask the questions: +When marking something as `alpha` or `beta`, maintainers should ask the following questions: * what is the cost of asking others to change their code vs the benefit of us maintaining the optionality to change it? * what is the plan for moving this to `v1` and how will that affect users? @@ -174,7 +174,7 @@ or `.v3`. #### Adopt a short, unique top-level package name -Top-level packages should adopt a short name that is known to not collide with +Top-level packages should adopt a short name that is known not to collide with other names in common usage within the Cosmos ecosystem. In the near future, a registry should be created to reserve and index top-level package names used within the Cosmos ecosystem. Because the Cosmos SDK is intended to provide @@ -200,7 +200,7 @@ go package names, i.e. the `cosmos.bank` protobuf package will still live in ### Message Naming -Message type names should be as concise possible without losing clarity. `sdk.Msg` +Message type names should be as concise as possible without losing clarity. `sdk.Msg` types which are used in transactions will retain the `Msg` prefix as that provides helpful context. diff --git a/docs/build/architecture/adr-027-deterministic-protobuf-serialization.md b/docs/build/architecture/adr-027-deterministic-protobuf-serialization.md index 66ce6e2b7..0b0b4c9fb 100644 --- a/docs/build/architecture/adr-027-deterministic-protobuf-serialization.md +++ b/docs/build/architecture/adr-027-deterministic-protobuf-serialization.md @@ -16,7 +16,7 @@ is needed when signing messages. We need to be sure that whenever we serialize a data structure, no matter in which supported language, the raw bytes will stay the same. [Protobuf](https://developers.google.com/protocol-buffers/docs/proto3) -serialization is not bijective (i.e. there exist a practically unlimited number of +serialization is not bijective (i.e. there exists a practically unlimited number of valid binary representations for a given protobuf document)1. This document describes a deterministic serialization scheme for @@ -100,12 +100,12 @@ with the following additions: it must be `0` or `1`). Per rule 3 above, the default value of `0` must be omitted, so if a Boolean is included it must have a value of `1`. -While rule number 1. and 2. should be pretty straight forward and describe the +While rules number 1. and 2. should be pretty straightforward and describe the default behavior of all protobuf encoders the author is aware of, the 3rd rule is more interesting. After a protobuf3 deserialization you cannot differentiate between unset fields and fields set to the default value3. At serialization level however, it is possible to set the fields with an empty -value or omitting them entirely. This is a significant difference to e.g. JSON +value or omit them entirely. This is a significant difference to e.g. JSON where a property can be empty (`""`, `0`), `null` or undefined, leading to 3 different documents. @@ -128,11 +128,11 @@ most custom development: * **Use a protobuf serializer that follows the above rules by default.** E.g. [gogoproto](https://pkg.go.dev/github.com/cosmos/gogoproto/gogoproto) is known to - be compliant by in most cases, but not when certain annotations such as + be compliant in most cases, but not when certain annotations such as `nullable = false` are used. It might also be an option to configure an existing serializer accordingly. * **Normalize default values before encoding them.** If your serializer follows - rule 1. and 2. and allows you to explicitly unset fields for serialization, + rules 1. and 2. and allows you to explicitly unset fields for serialization, you can normalize default values to unset. This can be done when working with [protobuf.js](https://www.npmjs.com/package/protobufjs): @@ -255,9 +255,9 @@ for all protobuf documents we need in the context of Cosmos SDK signing. ### Positive -* Well defined rules that can be verified independent of a reference +* Well defined rules that can be verified independently of a reference implementation -* Simple enough to keep the barrier to implement transaction signing low +* Simple enough to keep the barrier to implementing transaction signing low * It allows us to continue to use 0 and other empty values in SignDoc, avoiding the need to work around 0 sequences. This does not imply the change from https://github.com/cosmos/cosmos-sdk/pull/6949 should not be merged, but not @@ -279,7 +279,7 @@ for all protobuf documents we need in the context of Cosmos SDK signing. For the reasons mentioned above ("Negative" section) we prefer to keep workarounds for shared data structure. Example: the aforementioned `TxRaw` is using raw bytes as a workaround. This allows them to use any valid Protobuf library without -the need of implementing a custom serializer that adheres to this standard (and related risks of bugs). +the need to implement a custom serializer that adheres to this standard (and related risks of bugs). ## References diff --git a/docs/build/architecture/adr-028-public-key-addresses.md b/docs/build/architecture/adr-028-public-key-addresses.md index 9f394f7a2..f24d24ae7 100644 --- a/docs/build/architecture/adr-028-public-key-addresses.md +++ b/docs/build/architecture/adr-028-public-key-addresses.md @@ -21,12 +21,12 @@ address spaces are currently overlapping. We confirmed that it significantly dec ### Problem An attacker can control an input for an address generation function. This leads to a birthday attack, which significantly decreases the security space. -To overcome this, we need to separate the inputs for different kind of account types: +To overcome this, we need to separate the inputs for different kinds of account types: a security break of one account type shouldn't impact the security of other account types. ### Initial proposals -One initial proposal was extending the address length and +One initial proposal was to extend the address length and adding prefixes for different types of addresses. @ethanfrey explained an alternate approach originally used in https://github.com/iov-one/weave: @@ -38,7 +38,7 @@ adding prefixes for different types of addresses. And explained how this approach should be sufficiently collision resistant: -> Yeah, AFAIK, 20 bytes should be collision resistance when the preimages are unique and not malleable. A space of 2^160 would expect some collision to be likely around 2^80 elements (birthday paradox). And if you want to find a collision for some existing element in the database, it is still 2^160. 2^80 only is if all these elements are written to state. +> Yeah, AFAIK, 20 bytes should be collision resistance when the preimages are unique and not malleable. A space of 2^160 would expect some collision to be likely around 2^80 elements (birthday paradox). And if you want to find a collision for some existing element in the database, it is still 2^160. 2^80 only if all these elements are written to state. > The good example you brought up was eg. a public key bytes being a valid public key on two algorithms supported by the codec. Meaning if either was broken, you would break accounts even if they were secured with the safer variant. This is only as the issue when no differentiating type info is present in the preimage (before hashing into an address). > I would like to hear an argument if the 20 bytes space is an actual issue for security, as I would be happy to increase my address sizes in weave. I just figured cosmos and ethereum and bitcoin all use 20 bytes, it should be good enough. And the arguments above which made me feel it was secure. But I have not done a deeper analysis. @@ -56,7 +56,7 @@ In the issue we discussed various modifications: * Choice of the hash function. * Move the prefix out of the hash function: `keyTypePrefix + sha256(keybytes)[:20]` [post-hash-prefix-proposal]. * Use double hashing: `sha256(keyTypePrefix + sha256(keybytes)[:20])`. -* Increase to keybytes hash slice from 20 byte to 32 or 40 bytes. We concluded that 32 bytes, produced by a good hash functions is future secure. +* Increase to keybytes hash slice from 20 bytes to 32 or 40 bytes. We concluded that 32 bytes, produced by a good hash functions is future secure. ### Requirements @@ -97,7 +97,7 @@ As in other parts of the Cosmos SDK, we will use `sha256`. ### Basic Address -We start with defining a base algorithm for generating addresses which we will call `Hash`. Notably, it's used for accounts represented by a single key pair. For each public key schema we have to have an associated `typ` string, explained in the next section. `hash` is the cryptographic hash function defined in the previous section. +We start by defining a base algorithm for generating addresses which we will call `Hash`. Notably, it's used for accounts represented by a single key pair. For each public key schema we have to have an associated `typ` string, explained in the next section. `hash` is the cryptographic hash function defined in the previous section. ```go const A_LEN = 32 @@ -179,7 +179,7 @@ We must be able to cryptographically derive one address from another one. The de ```go func Derive(address, derivationKey []byte) []byte { - return Hash(addres, derivationKey) + return Hash(address, derivationKey) } ``` @@ -198,16 +198,16 @@ groupPolicyAddresses := []byte{1} address.Module(moduleName, groupPolicyAddresses, policyID) ``` -The `address.Module` function is using `address.Hash` with `"module"` as the type argument, and byte representation of the module name concatenated with submodule key. The two last component must be uniquely separated to avoid potential clashes (example: modulename="ab" & submodulekey="bc" will have the same derivation key as modulename="a" & submodulekey="bbc"). +The `address.Module` function is using `address.Hash` with `"module"` as the type argument, and byte representation of the module name concatenated with submodule key. The last two components must be uniquely separated to avoid potential clashes (example: modulename="ab" & submodulekey="bc" will have the same derivation key as modulename="a" & submodulekey="bbc"). We use a null byte (`'\x00'`) to separate module name from the submodule key. This works, because null byte is not a part of a valid module name. Finally, the sub-submodule accounts are created by applying the `Derive` function recursively. -We could use `Derive` function also in the first step (rather than concatenating module name with zero byte and the submodule key). We decided to do concatenation to avoid one level of derivation and speed up computation. +We could use `Derive` function also in the first step (rather than concatenating the module name with a zero byte and the submodule key). We decided to do concatenation to avoid one level of derivation and speed up computation. For backward compatibility with the existing `authtypes.NewModuleAddress`, we add a special case in `Module` function: when no derivation key is provided, we fallback to the "legacy" implementation. ```go func Module(moduleName string, derivationKeys ...[]byte) []byte{ if len(derivationKeys) == 0 { - return authtypes.NewModuleAddress(modulenName) // legacy case + return authtypes.NewModuleAddress(moduleName) // legacy case } submoduleAddress := Hash("module", []byte(moduleName) + 0 + key) return fold((a, k) => Derive(a, k), subsubKeys, submoduleAddress) @@ -283,7 +283,7 @@ This ADR is compatible with what was committed and directly supported in the Cos ## Further Discussions -Some accounts can have a fixed name or may be constructed in other way (eg: modules). We were discussing an idea of an account with a predefined name (eg: `me.regen`), which could be used by institutions. +Some accounts can have a fixed name or may be constructed in another way (eg: modules). We were discussing an idea of an account with a predefined name (eg: `me.regen`), which could be used by institutions. Without going into details, these kinds of addresses are compatible with the hash based addresses described here as long as they don't have the same length. More specifically, any special account address must not have a length equal to 20 or 32 bytes. @@ -295,9 +295,9 @@ Alan general observations: * we don’t need 2-preimage resistance * we need 32bytes address space for collision resistance -* when an attacker can control an input for object with an address then we have a problem with birthday attack +* when an attacker can control an input for an object with an address then we have a problem with a birthday attack * there is an issue with smart-contracts for hashing -* sha2 mining can be use to breaking address pre-image +* sha2 mining can be used to break the address pre-image Hashing algorithm @@ -315,27 +315,27 @@ Algorithm: Algorithm for complex / composed keys: -* merging tree like addresses with same algorithm are fine +* merging tree-like addresses with same algorithm are fine -Module addresses: Should module addresses have different size to differentiate it? +Module addresses: Should module addresses have a different size to differentiate it? -* we will need to set a pre-image prefix for module addresse to keept them in 32-byte space: `hash(hash('module') + module_key)` +* we will need to set a pre-image prefix for module addresses to keep them in 32-byte space: `hash(hash('module') + module_key)` * Aaron observation: we already need to deal with variable length (to not break secp256k1 keys). -Discssion about arithmetic hash function for ZKP +Discussion about an arithmetic hash function for ZKP -* Posseidon / Rescue -* Problem: much bigger risk because we don’t know much techniques and history of crypto-analysis of arithmetic constructions. It’s still a new ground and area of active research. +* Poseidon / Rescue +* Problem: much bigger risk because we don’t know much techniques and the history of crypto-analysis of arithmetic constructions. It’s still a new ground and area of active research. Post quantum signature size -* Alan suggestion: Falcon: speed / size ration - very good. +* Alan suggestion: Falcon: speed / size ratio - very good. * Aaron - should we think about it? - Alan: based on early extrapolation this thing will get able to break EC cryptography in 2050 . But that’s a lot of uncertainty. But there is magic happening with recurions / linking / simulation and that can speedup the progress. + Alan: based on early extrapolation this thing will get able to break EC cryptography in 2050. But that’s a lot of uncertainty. But there is magic happening with recursions / linking / simulation and that can speedup the progress. Other ideas -* Let’s say we use same key and two different address algorithms for 2 different use cases. Is it still safe to use it? Alan: if we want to hide the public key (which is not our use case), then it’s less secure but there are fixes. +* Let’s say we use the same key and two different address algorithms for 2 different use cases. Is it still safe to use it? Alan: if we want to hide the public key (which is not our use case), then it’s less secure but there are fixes. ### References diff --git a/docs/build/architecture/adr-029-fee-grant-module.md b/docs/build/architecture/adr-029-fee-grant-module.md index 6b52556ff..597ea5f7a 100644 --- a/docs/build/architecture/adr-029-fee-grant-module.md +++ b/docs/build/architecture/adr-029-fee-grant-module.md @@ -15,19 +15,19 @@ In order to make blockchain transactions, the signing account must possess a suf in order to pay fees. There are classes of transactions where needing to maintain a wallet with sufficient fees is a barrier to adoption. -For instance, when proper permissions are setup, someone may temporarily delegate the ability to vote on proposals to +For instance, when proper permissions are set up, someone may temporarily delegate the ability to vote on proposals to a "burner" account that is stored on a mobile phone with only minimal security. Other use cases include workers tracking items in a supply chain or farmers submitting field data for analytics or compliance purposes. For all of these use cases, UX would be significantly enhanced by obviating the need for these accounts to always -maintain the appropriate fee balance. This is especially true if we wanted to achieve enterprise adoption for something +maintain the appropriate fee balance. This is especially true if we want to achieve enterprise adoption for something like supply chain tracking. While one solution would be to have a service that fills up these accounts automatically with the appropriate fees, a better UX would be provided by allowing these accounts to pull from a common fee pool account with proper spending limits. -A single pool would reduce the churn of making lots of small "fill up" transactions and also more effectively leverages +A single pool would reduce the churn of making lots of small "fill up" transactions and also more effectively leverage the resources of the organization setting up the pool. ## Decision @@ -128,7 +128,7 @@ message Fee { ``` `granter` must either be left empty or must correspond to an account which has granted -a fee allowance to fee payer (either the first signer or the value of the `payer` field). +a fee allowance to the fee payer (either the first signer or the value of the `payer` field). A new `AnteDecorator` named `DeductGrantedFeeDecorator` will be created in order to process transactions with `fee_payer` set and correctly deduct fees based on fee allowances. diff --git a/docs/build/architecture/adr-030-authz-module.md b/docs/build/architecture/adr-030-authz-module.md index 5aab72c5c..e8b64f184 100644 --- a/docs/build/architecture/adr-030-authz-module.md +++ b/docs/build/architecture/adr-030-authz-module.md @@ -165,7 +165,7 @@ message MsgExecResponse { message MsgExec { string grantee = 1; // Authorization Msg requests to execute. Each msg must implement Authorization interface - repeated google.protobuf.Any msgs = 2 [(cosmos_proto.accepts_interface) = "cosmos.base.v1beta1.Msg"];; + repeated google.protobuf.Any msgs = 2 [(cosmos_proto.accepts_interface) = "cosmos.base.v1beta1.Msg"]; } ``` diff --git a/docs/build/architecture/adr-031-msg-service.md b/docs/build/architecture/adr-031-msg-service.md index 861f4b3f3..65d3bc5c0 100644 --- a/docs/build/architecture/adr-031-msg-service.md +++ b/docs/build/architecture/adr-031-msg-service.md @@ -11,12 +11,12 @@ Accepted ## Abstract -We want to leverage protobuf `service` definitions for defining `Msg`s which will give us significant developer UX +We want to leverage protobuf `service` definitions for defining `Msg`s, which will give us significant developer UX improvements in terms of the code that is generated and the fact that return types will now be well defined. ## Context -Currently `Msg` handlers in the Cosmos SDK do have return values that are placed in the `data` field of the response. +Currently `Msg` handlers in the Cosmos SDK have return values that are placed in the `data` field of the response. These return values, however, are not specified anywhere except in the golang handler code. In early conversations [it was proposed](https://docs.google.com/document/d/1eEgYgvgZqLE45vETjhwIw4VOqK-5hwQtZtjVbiXnIGc/edit) @@ -40,7 +40,7 @@ in `x/gov`, `MsgSubmitProposal` returns the proposal ID as a big-endian `uint64 This isn’t really documented anywhere and clients would need to know the internals of the Cosmos SDK to parse that value and return it to users. -Also, there may be cases where we want to use these return values programatically. +Also, there may be cases where we want to use these return values programmatically. For instance, https://github.com/cosmos/cosmos-sdk/issues/7093 proposes a method for doing inter-module Ocaps using the `Msg` router. A well-defined return type would improve the developer UX for this approach. @@ -82,7 +82,7 @@ the intent of the [protobuf spec](https://developers.google.com/protocol-buffers With this approach, we would get an auto-generated `MsgServer` interface: In addition to clearly specifying return types, this has the benefit of generating client and server code. On the server -side, this is almost like an automatically generated keeper method and could maybe be used intead of keepers eventually +side, this is almost like an automatically generated keeper method and could maybe be used instead of keepers eventually (see [\#7093](https://github.com/cosmos/cosmos-sdk/issues/7093)): ```go @@ -105,12 +105,12 @@ One consequence of this convention is that each `Msg` type can be the request pa ### Encoding -Encoding of transactions generated with `Msg` services do not differ from current Protobuf transaction encoding as defined in [ADR-020](./adr-020-protobuf-transaction-encoding.md). We are encoding `Msg` types (which are exactly `Msg` service methods' request parameters) as `Any` in `Tx`s which involves packing the +Encoding of transactions generated with `Msg` services does not differ from current Protobuf transaction encoding as defined in [ADR-020](./adr-020-protobuf-transaction-encoding.md). We are encoding `Msg` types (which are exactly `Msg` service methods' request parameters) as `Any` in `Tx`s which involves packing the binary-encoded `Msg` with its type URL. ### Decoding -Since `Msg` types are packed into `Any`, decoding transactions messages are done by unpacking `Any`s into `Msg` types. For more information, please refer to [ADR-020](./adr-020-protobuf-transaction-encoding.md#transactions). +Since `Msg` types are packed into `Any`, decoding transaction messages is done by unpacking `Any`s into `Msg` types. For more information, please refer to [ADR-020](./adr-020-protobuf-transaction-encoding.md#transactions). ### Routing @@ -118,7 +118,7 @@ We propose to add a `msg_service_router` in BaseApp. This router is a key/value When a transaction is processed by BaseApp (in CheckTx or in DeliverTx), its `TxBody.messages` are decoded as `Msg`s. Each `Msg`'s `type_url` is matched against an entry in the `msg_service_router`, and the respective `Msg` service method handler is called. -For backward compatability, the old handlers are not removed yet. If BaseApp receives a legacy `Msg` with no correspoding entry in the `msg_service_router`, it will be routed via its legacy `Route()` method into the legacy handler. +For backward compatibility, the old handlers are not removed yet. If BaseApp receives a legacy `Msg` with no corresponding entry in the `msg_service_router`, it will be routed via its legacy `Route()` method into the legacy handler. ### Module Configuration @@ -157,7 +157,7 @@ than later when transactions are processed. ### `Msg` Service Implementation Just like query services, `Msg` service methods can retrieve the `sdk.Context` -from the `context.Context` parameter method using the `sdk.UnwrapSDKContext` +from the `context.Context` parameter using the `sdk.UnwrapSDKContext` method: ```go diff --git a/docs/build/architecture/adr-032-typed-events.md b/docs/build/architecture/adr-032-typed-events.md index c1dd0a73c..0a5122da5 100644 --- a/docs/build/architecture/adr-032-typed-events.md +++ b/docs/build/architecture/adr-032-typed-events.md @@ -16,13 +16,13 @@ Proposed ## Abstract -Currently in the Cosmos SDK, events are defined in the handlers for each message as well as `BeginBlock` and `EndBlock`. Each module doesn't have types defined for each event, they are implemented as `map[string]string`. Above all else this makes these events difficult to consume as it requires a great deal of raw string matching and parsing. This proposal focuses on updating the events to use **typed events** defined in each module such that emiting and subscribing to events will be much easier. This workflow comes from the experience of the Akash Network team. +Currently in the Cosmos SDK, events are defined in the handlers for each message as well as `BeginBlock` and `EndBlock`. Each module doesn't have types defined for each event, they are implemented as `map[string]string`. Above all else this makes these events difficult to consume as it requires a great deal of raw string matching and parsing. This proposal focuses on updating the events to use **typed events** defined in each module such that emitting and subscribing to events will be much easier. This workflow comes from the experience of the Akash Network team. ## Context -Currently in the Cosmos SDK, events are defined in the handlers for each message, meaning each module doesn't have a cannonical set of types for each event. Above all else this makes these events difficult to consume as it requires a great deal of raw string matching and parsing. This proposal focuses on updating the events to use **typed events** defined in each module such that emiting and subscribing to events will be much easier. This workflow comes from the experience of the Akash Network team. +Currently in the Cosmos SDK, events are defined in the handlers for each message, meaning each module doesn't have a canonical set of types for each event. Above all else this makes these events difficult to consume as it requires a great deal of raw string matching and parsing. This proposal focuses on updating the events to use **typed events** defined in each module such that emitting and subscribing to events will be much easier. This workflow comes from the experience of the Akash Network team. -[Our platform](http://github.com/ovrclk/akash) requires a number of programatic on chain interactions both on the provider (datacenter - to bid on new orders and listen for leases created) and user (application developer - to send the app manifest to the provider) side. In addition the Akash team is now maintaining the IBC [`relayer`](https://github.com/ovrclk/relayer), another very event driven process. In working on these core pieces of infrastructure, and integrating lessons learned from Kubernetes developement, our team has developed a standard method for defining and consuming typed events in Cosmos SDK modules. We have found that it is extremely useful in building this type of event driven application. +[Our platform](http://github.com/ovrclk/akash) requires a number of programmatic on chain interactions both on the provider (datacenter - to bid on new orders and listen for leases created) and user (application developer - to send the app manifest to the provider) side. In addition the Akash team is now maintaining the IBC [`relayer`](https://github.com/ovrclk/relayer), another very event driven process. In working on these core pieces of infrastructure, and integrating lessons learned from Kubernetes development, our team has developed a standard method for defining and consuming typed events in Cosmos SDK modules. We have found that it is extremely useful in building this type of event driven application. As the Cosmos SDK gets used more extensively for apps like `peggy`, other peg zones, IBC, DeFi, etc... there will be an exploding demand for event driven applications to support new features desired by users. We propose upstreaming our findings into the Cosmos SDK to enable all Cosmos SDK applications to quickly and easily build event driven apps to aid their core application. Wallets, exchanges, explorers, and defi protocols all stand to benefit from this work. @@ -153,7 +153,7 @@ Users will be able to subscribe using `client.Context.Client.Subscribe` and cons Akash Network has built a simple [`pubsub`](https://github.com/ovrclk/akash/blob/90d258caeb933b611d575355b8df281208a214f8/pubsub/bus.go#L20). This can be used to subscribe to `abci.Events` and [publish](https://github.com/ovrclk/akash/blob/90d258caeb933b611d575355b8df281208a214f8/events/publish.go#L21) them as typed events. -Please see the below code sample for more detail on this flow looks for clients. +Please see the below code sample for more detail on how this flow looks for clients. ## Consequences @@ -294,7 +294,7 @@ func PublishChainTxEvents(ctx context.Context, client cmtclient.EventsClient, bu for _, abciEv := range events { typedEvent, err := sdk.ParseTypedEvent(abciEv) if err != nil { - return er + return err } if err := bus.Publish(typedEvent); err != nil { bus.Close() @@ -308,7 +308,7 @@ func PublishChainTxEvents(ctx context.Context, client cmtclient.EventsClient, bu return err }) - // Exit on error or context cancelation + // Exit on error or context cancellation return g.Wait() } ``` diff --git a/docs/build/architecture/adr-033-protobuf-inter-module-comm.md b/docs/build/architecture/adr-033-protobuf-inter-module-comm.md index 28c69a910..acbc98e15 100644 --- a/docs/build/architecture/adr-033-protobuf-inter-module-comm.md +++ b/docs/build/architecture/adr-033-protobuf-inter-module-comm.md @@ -20,7 +20,7 @@ service definitions defined in [ADR 021](./adr-021-protobuf-query-encoding.md) a ## Context -In the current Cosmos SDK documentation on the [Object-Capability Model](../../learn/advanced/10-ocap.md), it is stated that: +In the current Cosmos SDK documentation on the [Object-Capability Model](../docs/learn/advanced/10-ocap.md), it is stated that: > We assume that a thriving ecosystem of Cosmos SDK modules that are easy to compose into a blockchain application will contain faulty or malicious modules. @@ -42,7 +42,7 @@ own account. These permissions are actually stored as a `[]string` array on the However, these permissions don’t really do much. They control what modules can be referenced in the `MintCoins`, `BurnCoins` and `DelegateCoins***` methods, but for one there is no unique object capability token that controls access — -just a simple string. So the `x/upgrade` module could mint tokens for the `x/staking` module simple by calling +just a simple string. So the `x/upgrade` module could mint tokens for the `x/staking` module simply by calling `MintCoins(“staking”)`. Furthermore, all modules which have access to these keeper methods, also have access to `SetBalance` negating any other attempt at OCAPs and breaking even basic object-oriented encapsulation. @@ -94,7 +94,7 @@ evolution. the two which checks if one module is authorized to send the specified `Msg` to the other module providing a proper object capability system (see below). 3. The router for inter-module communication gives us a convenient place to handle rollback of transactions, -enabling atomicy of operations ([currently a problem](https://github.com/cosmos/cosmos-sdk/issues/8030)). Any failure within a module-to-module call would result in a failure of the entire +enabling atomicity of operations ([currently a problem](https://github.com/cosmos/cosmos-sdk/issues/8030)). Any failure within a module-to-module call would result in a failure of the entire transaction This mechanism has the added benefits of: @@ -111,7 +111,7 @@ key" corresponding to a module account, where authentication is provided through described in more detail below. Blockchain users (external clients) use their account's private key to sign transactions containing `Msg`s where they are listed as signers (each -message specifies required signers with `Msg.GetSigner`). The authentication checks is performed by `AnteHandler`. +message specifies required signers with `Msg.GetSigner`). The authentication check is performed by `AnteHandler`. Here, we extend this process, by allowing modules to be identified in `Msg.GetSigners`. When a module wants to trigger the execution a `Msg` in another module, its `ModuleKey` acts as the sender (through the `ClientConn` interface we describe below) and is set as a sole "signer". It's worth to note @@ -144,7 +144,7 @@ func NewFooMsgServer(moduleKey RootModuleKey, ...) FooMsgServer { } func (foo *FooMsgServer) Bar(ctx context.Context, req *MsgBarRequest) (*MsgBarResponse, error) { - balance, err := foo.bankQuery.Balance(&bank.QueryBalanceRequest{Address: fooMsgServer.moduleKey.Address(), Denom: "foo"}) + balance, err := foo.bankQuery.Balance(&bank.QueryBalanceRequest{Address: foo.moduleKey.Address(), Denom: "foo"}) ... @@ -270,7 +270,7 @@ introduced in the future. The `ModuleManager` will handle creation of module acc Because modules do not get direct access to each other anymore, modules may have unfulfilled dependencies. To make sure that module dependencies are resolved at startup, the `Configurator.RequireServer` method should be added. The `ModuleManager` will make sure that all dependencies declared with `RequireServer` can be resolved before the app starts. An example -module `foo` could declare it's dependency on `x/bank` like this: +module `foo` could declare its dependency on `x/bank` like this: ```go package foo @@ -331,7 +331,7 @@ ADR. By default, the inter-module router requires that messages are sent by the first signer returned by `GetSigners`. The inter-module router should also accept authorization middleware such as that provided by [ADR 030](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-030-authz-module.md). -This middleware will allow accounts to otherwise specific module accounts to perform actions on their behalf. +This middleware will allow accounts to authorize specific module accounts to perform actions on their behalf. Authorization middleware should take into account the need to grant certain modules effectively "admin" privileges to other modules. This will be addressed in separate ADRs or updates to this ADR. @@ -378,7 +378,7 @@ replacing `Keeper` interfaces altogether. * an alternative to keepers which can more easily lead to stable inter-module interfaces * proper inter-module OCAPs -* improved module developer DevX, as commented on by several particpants on +* improved module developer DevX, as commented on by several participants on [Architecture Review Call, Dec 3](https://hackmd.io/E0wxxOvRQ5qVmTf6N_k84Q) * lays the groundwork for what can be a greatly simplified `app.go` * router can be setup to enforce atomic transactions for module-to-module calls diff --git a/docs/build/architecture/adr-034-account-rekeying.md b/docs/build/architecture/adr-034-account-rekeying.md index cd9b91469..06825c5d0 100644 --- a/docs/build/architecture/adr-034-account-rekeying.md +++ b/docs/build/architecture/adr-034-account-rekeying.md @@ -10,13 +10,13 @@ PROPOSED ## Abstract -Account rekeying is a process hat allows an account to replace its authentication pubkey with a new one. +Account rekeying is a process that allows an account to replace its authentication pubkey with a new one. ## Context -Currently, in the Cosmos SDK, the address of an auth `BaseAccount` is based on the hash of the public key. Once an account is created, the public key for the account is set in stone, and cannot be changed. This can be a problem for users, as key rotation is a useful security practice, but is not possible currently. Furthermore, as multisigs are a type of pubkey, once a multisig for an account is set, it can not be updated. This is problematic, as multisigs are often used by organizations or companies, who may need to change their set of multisig signers for internal reasons. +Currently, in the Cosmos SDK, the address of an auth `BaseAccount` is based on the hash of the public key. Once an account is created, the public key for the account is set in stone, and cannot be changed. This can be a problem for users, as key rotation is a useful security practice, but is not possible currently. Furthermore, as multisigs are a type of pubkey, once a multisig for an account is set, it cannot be updated. This is problematic, as multisigs are often used by organizations or companies, who may need to change their set of multisig signers for internal reasons. -Transferring all the assets of an account to a new account with the updated pubkey is not sufficient, because some "engagements" of an account are not easily transferable. For example, in staking, to transfer bonded Atoms, an account would have to unbond all delegations and wait the three week unbonding period. Even more significantly, for validator operators, ownership over a validator is not transferrable at all, meaning that the operator key for a validator can never be updated, leading to poor operational security for validators. +Transferring all the assets of an account to a new account with the updated pubkey is not sufficient, because some "engagements" of an account are not easily transferable. For example, in staking, to transfer bonded Atoms, an account would have to unbond all delegations and wait the three-week unbonding period. Even more significantly, for validator operators, ownership over a validator is not transferable at all, meaning that the operator key for a validator can never be updated, leading to poor operational security for validators. ## Decision @@ -41,16 +41,16 @@ message MsgChangePubKeyResponse {} The MsgChangePubKey transaction needs to be signed by the existing pubkey in state. -Once, approved, the handler for this message type, which takes in the AccountKeeper, will update the in-state pubkey for the account and replace it with the pubkey from the Msg. +Once approved, the handler for this message type, which takes in the AccountKeeper, will update the in-state pubkey for the account and replace it with the pubkey from the Msg. -An account that has had its pubkey changed cannot be automatically pruned from state. This is because if pruned, the original pubkey of the account would be needed to recreate the same address, but the owner of the address may not have the original pubkey anymore. Currently, we do not automatically prune any accounts anyways, but we would like to keep this option open the road (this is the purpose of account numbers). To resolve this, we charge an additional gas fee for this operation to compensate for this this externality (this bound gas amount is configured as parameter `PubKeyChangeCost`). The bonus gas is charged inside the handler, using the `ConsumeGas` function. Furthermore, in the future, we can allow accounts that have rekeyed manually prune themselves using a new Msg type such as `MsgDeleteAccount`. Manually pruning accounts can give a gas refund as an incentive for performing the action. +An account that has had its pubkey changed cannot be automatically pruned from state. This is because if pruned, the original pubkey of the account would be needed to recreate the same address, but the owner of the address may not have the original pubkey anymore. Currently, we do not automatically prune any accounts anyways, but we would like to keep this option open down the road (this is the purpose of account numbers). To resolve this, we charge an additional gas fee for this operation to compensate for this externality (this bound gas amount is configured as a parameter `PubKeyChangeCost`). The bonus gas is charged inside the handler, using the `ConsumeGas` function. Furthermore, in the future, we can allow accounts that have rekeyed manually prune themselves using a new Msg type such as `MsgDeleteAccount`. Manually pruning accounts can give a gas refund as an incentive for performing the action. ```go amount := ak.GetParams(ctx).PubKeyChangeCost ctx.GasMeter().ConsumeGas(amount, "pubkey change fee") ``` -Everytime a key for an address is changed, we will store a log of this change in the state of the chain, thus creating a stack of all previous keys for an address and the time intervals for which they were active. This allows dapps and clients to easily query past keys for an account which may be useful for features such as verifying timestamped off-chain signed messages. +Every time a key for an address is changed, we will store a log of this change in the state of the chain, thus creating a stack of all previous keys for an address and the time intervals for which they were active. This allows dapps and clients to easily query past keys for an account which may be useful for features such as verifying timestamped off-chain signed messages. ## Consequences @@ -61,14 +61,14 @@ Everytime a key for an address is changed, we will store a log of this change in ### Negative -Breaks the current assumed relationship between address and pubkeys as H(pubkey) = address. This has a couple of consequences. +Breaks the current assumed relationship between address and pubkey as H(pubkey) = address. This has a couple of consequences. -* This makes wallets that support this feature more complicated. For example, if an address on chain was updated, the corresponding key in the CLI wallet also needs to be updated. +* This makes wallets that support this feature more complicated. For example, if an address on-chain was updated, the corresponding key in the CLI wallet also needs to be updated. * Cannot automatically prune accounts with 0 balance that have had their pubkey changed. ### Neutral -* While the purpose of this is intended to allow the owner of an account to update to a new pubkey they own, this could technically also be used to transfer ownership of an account to a new owner. For example, this could be use used to sell a staked position without unbonding or an account that has vesting tokens. However, the friction of this is very high as this would essentially have to be done as a very specific OTC trade. Furthermore, additional constraints could be added to prevent accouns with Vesting tokens to use this feature. +* While the purpose of this is intended to allow the owner of an account to update to a new pubkey they own, this could technically also be used to transfer ownership of an account to a new owner. For example, this could be used to sell a staked position without unbonding or an account that has vesting tokens. However, the friction of this is very high as this would essentially have to be done as a very specific OTC trade. Furthermore, additional constraints could be added to prevent accounts with Vesting tokens to use this feature. * Will require that PubKeys for an account are included in the genesis exports. ## References diff --git a/docs/build/architecture/adr-035-rosetta-api-support.md b/docs/build/architecture/adr-035-rosetta-api-support.md index 01a81048b..5b910262d 100644 --- a/docs/build/architecture/adr-035-rosetta-api-support.md +++ b/docs/build/architecture/adr-035-rosetta-api-support.md @@ -9,7 +9,7 @@ ## Changelog -* 2021-05-12: the external library [cosmos-rosetta-gateway](https://github.com/tendermint/cosmos-rosetta-gateway) has been moved within the Cosmos SDK. +* 2021-05-12: the external library [cosmos-rosetta-gateway](https://github.com/tendermint/cosmos-rosetta-gateway) has been moved within the Cosmos SDK. ## Context @@ -32,11 +32,11 @@ The driving principles of the proposed design are: 1. **Extensibility:** it must be as riskless and painless as possible for application developers to set-up network configurations to expose Rosetta API-compliant services. -2. **Long term support:** This proposal aims to provide support for all the supported Cosmos SDK release series. +2. **Long term support:** This proposal aims to provide support for all the Cosmos SDK release series. 3. **Cost-efficiency:** Backporting changes to Rosetta API specifications from `master` to the various stable branches of Cosmos SDK is a cost that needs to be reduced. -We will achieve these delivering on these principles by the following: +We will achieve these by delivering on these principles by the following: 1. There will be a package `rosetta/lib` for the implementation of the core Rosetta API features, particularly: @@ -53,7 +53,7 @@ We will achieve these delivering on these principles by the following: ### The External Repo -As section will describe the proposed external library, including the service implementation, plus the defined types and interfaces. +This section will describe the proposed external library, including the service implementation, plus the defined types and interfaces. #### Server @@ -120,8 +120,8 @@ type Client interface { // BlockTransactionsByHash gets the block, parent block and transactions // given the block hash. BlockTransactionsByHash(ctx context.Context, hash string) (BlockTransactionsResponse, error) - // BlockTransactionsByHash gets the block, parent block and transactions - // given the block hash. + // BlockTransactionsByHeight gets the block, parent block and transactions + // given the block height. BlockTransactionsByHeight(ctx context.Context, height *int64) (BlockTransactionsResponse, error) // GetTx gets a transaction given its hash GetTx(ctx context.Context, hash string) (*types.Transaction, error) @@ -189,7 +189,7 @@ As stated at the start, application developers will have two methods for invocat #### Shared Process (Only Stargate) -Rosetta API service could run within the same execution process as the application. This would be enabled via app.toml settings, and if gRPC is not enabled the rosetta instance would be spinned in offline mode (tx building capabilities only). +Rosetta API service could run within the same execution process as the application. This would be enabled via app.toml settings, and if gRPC is not enabled the rosetta instance would be spun in offline mode (tx building capabilities only). #### Separate API service diff --git a/docs/build/architecture/adr-036-arbitrary-signature.md b/docs/build/architecture/adr-036-arbitrary-signature.md index fe9dada54..187a34e5d 100644 --- a/docs/build/architecture/adr-036-arbitrary-signature.md +++ b/docs/build/architecture/adr-036-arbitrary-signature.md @@ -17,27 +17,27 @@ Draft ## Abstract -Currently, in the Cosmos SDK, there is no convention to sign arbitrary message like on Ethereum. We propose with this specification, for Cosmos SDK ecosystem, a way to sign and validate off-chain arbitrary messages. +Currently, in the Cosmos SDK, there is no convention to sign arbitrary messages like in Ethereum. We propose with this specification, for Cosmos SDK ecosystem, a way to sign and validate off-chain arbitrary messages. -This specification serves the purpose of covering every use case, this means that cosmos-sdk applications developers decide how to serialize and represent `Data` to users. +This specification serves the purpose of covering every use case; this means that Cosmos SDK application developers decide how to serialize and represent `Data` to users. ## Context -Having the ability to sign messages off-chain has proven to be a fundamental aspect of nearly any blockchain. The notion of signing messages off-chain has many added benefits such as saving on computational costs and reducing transaction throughput and overhead. Within the context of the Cosmos, some of the major applications of signing such data includes, but is not limited to, providing a cryptographic secure and verifiable means of proving validator identity and possibly associating it with some other framework or organization. In addition, having the ability to sign Cosmos messages with a Ledger or similar HSM device. +Having the ability to sign messages off-chain has proven to be a fundamental aspect of nearly any blockchain. The notion of signing messages off-chain has many added benefits such as saving on computational costs and reducing transaction throughput and overhead. Within the context of the Cosmos, some of the major applications of signing such data include, but is not limited to, providing a cryptographic secure and verifiable means of proving validator identity and possibly associating it with some other framework or organization. In addition, having the ability to sign Cosmos messages with a Ledger or similar HSM device. -Further context and use cases can be found in the references links. +Further context and use cases can be found in the reference links. ## Decision The aim is being able to sign arbitrary messages, even using Ledger or similar HSM devices. -As a result signed messages should look roughly like Cosmos SDK messages but **must not** be a valid on-chain transaction. `chain-id`, `account_number` and `sequence` can all be assigned invalid values. +As a result, signed messages should look roughly like Cosmos SDK messages but **must not** be a valid on-chain transaction. `chain-id`, `account_number` and `sequence` can all be assigned invalid values. Cosmos SDK 0.40 also introduces a concept of “auth_info” this can specify SIGN_MODES. A spec should include an `auth_info` that supports SIGN_MODE_DIRECT and SIGN_MODE_LEGACY_AMINO. -Create the `offchain` proto definitions, we extend the auth module with `offchain` package to offer functionalities to verify and sign offline messages. +To create the `offchain` proto definitions, we extend the auth module with `offchain` package to offer functionalities to verify and sign offline messages. An offchain transaction follows these rules: @@ -51,7 +51,7 @@ Verification of an offchain transaction follows the same rules as an onchain one The first message added to the `offchain` package is `MsgSignData`. -`MsgSignData` allows developers to sign arbitrary bytes valid offchain only. Where `Signer` is the account address of the signer. `Data` is arbitrary bytes which can represent `text`, `files`, `object`s. It's applications developers decision how `Data` should be deserialized, serialized and the object it can represent in their context. +`MsgSignData` allows developers to sign arbitrary bytes validatable offchain only. `Signer` is the account address of the signer. `Data` is arbitrary bytes which can represent `text`, `files`, `object`s. It's applications developers decision how `Data` should be deserialized, serialized and the object it can represent in their context. It's applications developers decision how `Data` should be treated, by treated we mean the serialization and deserialization process and the Object `Data` should represent. @@ -116,13 +116,13 @@ Backwards compatibility is maintained as this is a new message spec definition. ### Negative -* Current proposal requires a fixed relationship between an account address and a public key. +* The current proposal requires a fixed relationship between an account address and a public key. * Doesn't work with multisig accounts. ## Further discussion -* Regarding security in `MsgSignData`, the developer using `MsgSignData` is in charge of making the content laying in `Data` non-replayable when, and if, needed. -* the offchain package will be further extended with extra messages that target specific use cases such as, but not limited to, authentication in applications, payment channels, L2 solutions in general. +* Regarding security in `MsgSignData`, the developer using `MsgSignData` is in charge of making the content contained in `Data` non-replayable when, and if, needed. +* The offchain package will be further extended with extra messages that target specific use cases such as, but not limited to, authentication in applications, payment channels, L2 solutions in general. ## References diff --git a/docs/build/architecture/adr-037-gov-split-vote.md b/docs/build/architecture/adr-037-gov-split-vote.md index 0a3b9bc43..e7d6e6935 100644 --- a/docs/build/architecture/adr-037-gov-split-vote.md +++ b/docs/build/architecture/adr-037-gov-split-vote.md @@ -2,7 +2,7 @@ ## Changelog -* 2020/10/28: Intial draft +* 2020/10/28: Initial draft ## Status @@ -14,9 +14,9 @@ This ADR defines a modification to the governance module that would allow a stak ## Context -Currently, an address can cast a vote with only one options (Yes/No/Abstain/NoWithVeto) and use their full voting power behind that choice. +Currently, an address can cast a vote with only one option (Yes/No/Abstain/NoWithVeto) and use their full voting power behind that choice. -However, often times the entity owning that address might not be a single individual. For example, a company might have different stakeholders who want to vote differently, and so it makes sense to allow them to split their voting power. Another example use case is exchanges. Many centralized exchanges often stake a portion of their users' tokens in their custody. Currently, it is not possible for them to do "passthrough voting" and giving their users voting rights over their tokens. However, with this system, exchanges can poll their users for voting preferences, and then vote on-chain proportionally to the results of the poll. +However, oftentimes the entity owning that address might not be a single individual. For example, a company might have different stakeholders who want to vote differently, and so it makes sense to allow them to split their voting power. Another example use case is exchanges. Many centralized exchanges often stake a portion of their users' tokens in their custody. Currently, it is not possible for them to do "passthrough voting" and giving their users voting rights over their tokens. However, with this system, exchanges can poll their users for voting preferences, and then vote on-chain proportionally to the results of the poll. ## Decision @@ -53,7 +53,7 @@ type MsgVoteWeighted struct { The `ValidateBasic` of a `MsgVoteWeighted` struct would require that -1. The sum of all the Rates is equal to 1.0 +1. The sum of all the rates is equal to 1.0 2. No Option is repeated The governance tally function will iterate over all the options in a vote and add to the tally the result of the voter's voting power * the rate for that option. diff --git a/docs/build/architecture/adr-038-state-listening.md b/docs/build/architecture/adr-038-state-listening.md index 319d872be..63f2ec163 100644 --- a/docs/build/architecture/adr-038-state-listening.md +++ b/docs/build/architecture/adr-038-state-listening.md @@ -7,7 +7,7 @@ * 10/14/2022: * Add `ListenCommit`, flatten the state writes in a block to a single batch. * Remove listeners from cache stores, should only listen to `rootmulti.Store`. - * Remove `HaltAppOnDeliveryError()`, the errors are propagated by default, the implementations should return nil if don't want to propogate errors. + * Remove `HaltAppOnDeliveryError()`, the errors are propagated by default, the implementations should return nil if they don't want to propagate errors. * 26/05/2023: Update with ABCI 2.0 ## Status @@ -20,7 +20,7 @@ This ADR defines a set of changes to enable listening to state changes of indivi ## Context -Currently, KVStore data can be remotely accessed through [Queries](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules/messages-and-queries.md#queries) +Currently, KVStore data can be remotely accessed through [Queries](https://docs.cosmos.network/main/build/building-modules/messages-and-queries#queries) which proceed either through Tendermint and the ABCI, or through the gRPC server. In addition to these request/response queries, it would be beneficial to have a means of listening to state changes as they occur in real time. @@ -40,7 +40,7 @@ type MemoryListener struct { stateCache []StoreKVPair } -// NewMemoryListener creates a listener that accumulate the state writes in memory. +// NewMemoryListener creates a listener that accumulates the state writes in memory. func NewMemoryListener() *MemoryListener { return &MemoryListener{} } @@ -114,7 +114,7 @@ func (s *Store) Delete(key []byte) { ### MultiStore interface updates -We will update the `CommitMultiStore` interface to allow us to wrap a `Memorylistener` to a specific `KVStore`. +We will update the `CommitMultiStore` interface to allow us to wrap a `MemoryListener` to a specific `KVStore`. Note that the `MemoryListener` will be attached internally by the concrete `rootmulti` implementation. ```go @@ -224,9 +224,9 @@ so that the service can group the state changes with the ABCI requests. // ABCIListener is the interface that we're exposing as a streaming service. type ABCIListener interface { // ListenFinalizeBlock updates the streaming service with the latest FinalizeBlock messages - ListenFinalizeBlock(ctx context.Context, req abci.RequestFinalizeBlock, res abci.ResponseFinalizeBlock) error - // ListenCommit updates the steaming service with the latest Commit messages and state changes - ListenCommit(ctx context.Context, res abci.ResponseCommit, changeSet []*StoreKVPair) error + ListenFinalizeBlock(ctx context.Context, req abci.FinalizeBlockRequest, res abci.FinalizeBlockResponse) error + // ListenCommit updates the streaming service with the latest Commit messages and state changes + ListenCommit(ctx context.Context, res abci.CommitResponse, changeSet []*StoreKVPair) error } ``` @@ -267,16 +267,16 @@ We will modify the `FinalizeBlock` and `Commit` methods to pass ABCI requests an to any streaming service hooks registered with the `BaseApp`. ```go -func (app *BaseApp) FinalizeBlock(req abci.RequestFinalizeBlock) abci.ResponseFinalizeBlock { +func (app *BaseApp) FinalizeBlock(req abci.FinalizeBlockRequest) abci.FinalizeBlockResponse { - var abciRes abci.ResponseFinalizeBlock + var abciRes abci.FinalizeBlockResponse defer func() { // call the streaming service hook with the FinalizeBlock messages for _, abciListener := range app.abciListeners { ctx := app.finalizeState.ctx blockHeight := ctx.BlockHeight() if app.abciListenersAsync { - go func(req abci.RequestFinalizeBlock, res abci.ResponseFinalizeBlock) { + go func(req abci.FinalizeBlockRequest, res abci.FinalizeBlockResponse) { if err := app.abciListener.FinalizeBlock(blockHeight, req, res); err != nil { app.logger.Error("FinalizeBlock listening hook failed", "height", blockHeight, "err", err) } @@ -299,11 +299,11 @@ func (app *BaseApp) FinalizeBlock(req abci.RequestFinalizeBlock) abci.ResponseFi ``` ```go -func (app *BaseApp) Commit() abci.ResponseCommit { +func (app *BaseApp) Commit() abci.CommitResponse { ... - res := abci.ResponseCommit{ + res := abci.CommitResponse{ Data: commitID.Hash, RetainHeight: retainHeight, } @@ -314,7 +314,7 @@ func (app *BaseApp) Commit() abci.ResponseCommit { blockHeight := ctx.BlockHeight() changeSet := app.cms.PopStateCache() if app.abciListenersAsync { - go func(res abci.ResponseCommit, changeSet []store.StoreKVPair) { + go func(res abci.CommitResponse, changeSet []store.StoreKVPair) { if err := app.abciListener.ListenCommit(ctx, res, changeSet); err != nil { app.logger.Error("ListenCommit listening hook failed", "height", blockHeight, "err", err) } @@ -354,7 +354,7 @@ var Handshake = plugin.HandshakeConfig{ MagicCookieValue: "ef78114d-7bdf-411c-868f-347c99a78345", } -// ListenerPlugin is the base struc for all kinds of go-plugin implementations +// ListenerPlugin is the base struct for all kinds of go-plugin implementations // It will be included in interfaces of different Plugins type ABCIListenerPlugin struct { // GRPCPlugin must still implement the Plugin interface @@ -433,13 +433,13 @@ type GRPCClient struct { client ABCIListenerServiceClient } -func (m *GRPCClient) ListenFinalizeBlock(goCtx context.Context, req abci.RequestFinalizeBlock, res abci.ResponseFinalizeBlock) error { +func (m *GRPCClient) ListenFinalizeBlock(goCtx context.Context, req abci.FinalizeBlockRequest, res abci.FinalizeBlockResponse) error { ctx := sdk.UnwrapSDKContext(goCtx) _, err := m.client.ListenDeliverTx(ctx, &ListenDeliverTxRequest{BlockHeight: ctx.BlockHeight(), Req: req, Res: res}) return err } -func (m *GRPCClient) ListenCommit(goCtx context.Context, res abci.ResponseCommit, changeSet []store.StoreKVPair) error { +func (m *GRPCClient) ListenCommit(goCtx context.Context, res abci.CommitResponse, changeSet []store.StoreKVPair) error { ctx := sdk.UnwrapSDKContext(goCtx) _, err := m.client.ListenCommit(ctx, &ListenCommitRequest{BlockHeight: ctx.BlockHeight(), Res: res, ChangeSet: changeSet}) return err @@ -471,11 +471,11 @@ And the pre-compiled Go plugin `Impl`(*this is only used for plugins that are wr // ABCIListener is the implementation of the baseapp.ABCIListener interface type ABCIListener struct{} -func (m *ABCIListenerPlugin) ListenFinalizeBlock(ctx context.Context, req abci.RequestFinalizeBlock, res abci.ResponseFinalizeBlock) error { +func (m *ABCIListenerPlugin) ListenFinalizeBlock(ctx context.Context, req abci.FinalizeBlockRequest, res abci.FinalizeBlockResponse) error { // send data to external system } -func (m *ABCIListenerPlugin) ListenCommit(ctx context.Context, res abci.ResponseCommit, changeSet []store.StoreKVPair) error { +func (m *ABCIListenerPlugin) ListenCommit(ctx context.Context, res abci.CommitResponse, changeSet []store.StoreKVPair) error { // send data to external system } @@ -529,7 +529,7 @@ func NewStreamingPlugin(name string, logLevel string) (interface{}, error) { We propose a `RegisterStreamingPlugin` function for the App to register `NewStreamingPlugin`s with the App's BaseApp. Streaming plugins can be of `Any` type; therefore, the function takes in an interface vs a concrete type. -For example, we could have plugins of `ABCIListener`, `WasmListener` or `IBCListener`. Note that `RegisterStreamingPluing` function +For example, we could have plugins of `ABCIListener`, `WasmListener` or `IBCListener`. Note that `RegisterStreamingPlugin` function is helper function and not a requirement. Plugin registration can easily be moved from the App to the BaseApp directly. ```go @@ -720,5 +720,5 @@ These changes will provide a means of subscribing to KVStore state changes in re ### Neutral -* Introduces additional- but optional- complexity to configuring and running a cosmos application +* Introduces additional—but optional—complexity to configuring and running a cosmos application * If an application developer opts to use these features to expose data, they need to be aware of the ramifications/risks of that data exposure as it pertains to the specifics of their application diff --git a/docs/build/architecture/adr-039-epoched-staking.md b/docs/build/architecture/adr-039-epoched-staking.md index 9b5ce9af9..bc74b6ab2 100644 --- a/docs/build/architecture/adr-039-epoched-staking.md +++ b/docs/build/architecture/adr-039-epoched-staking.md @@ -19,9 +19,9 @@ This ADR updates the proof of stake module to buffer the staking weight updates ## Context -The current proof of stake module takes the design decision to apply staking weight changes to the consensus engine immediately. This means that delegations and unbonds get applied immediately to the validator set. This decision was primarily done as it was implementationally simplest, and because we at the time believed that this would lead to better UX for clients. +The current proof of stake module takes the design decision to apply staking weight changes to the consensus engine immediately. This means that delegations and unbonds get applied immediately to the validator set. This decision was primarily done as it was the simplest from an implementation perspective, and because we at the time believed that this would lead to better UX for clients. -An alternative design choice is to allow buffering staking updates (delegations, unbonds, validators joining) for a number of blocks. This 'epoch'd proof of stake consensus provides the guarantee that the consensus weights for validators will not change mid-epoch, except in the event of a slash condition. +An alternative design choice is to allow buffering staking updates (delegations, unbonds, validators joining) for a number of blocks. This epoched proof of stake consensus provides the guarantee that the consensus weights for validators will not change mid-epoch, except in the event of a slash condition. Additionally, the UX hurdle may not be as significant as was previously thought. This is because it is possible to provide users immediate acknowledgement that their bond was recorded and will be executed. @@ -29,9 +29,9 @@ Furthermore, it has become clearer over time that immediate execution of staking * Threshold based cryptography. One of the main limitations is that because the validator set can change so regularly, it makes the running of multiparty computation by a fixed validator set difficult. Many threshold-based cryptographic features for blockchains such as randomness beacons and threshold decryption require a computationally-expensive DKG process (will take much longer than 1 block to create). To productively use these, we need to guarantee that the result of the DKG will be used for a reasonably long time. It wouldn't be feasible to rerun the DKG every block. By epoching staking, it guarantees we'll only need to run a new DKG once every epoch. -* Light client efficiency. This would lessen the overhead for IBC when there is high churn in the validator set. In the Tendermint light client bisection algorithm, the number of headers you need to verify is related to bounding the difference in validator sets between a trusted header and the latest header. If the difference is too great, you verify more header in between the two. By limiting the frequency of validator set changes, we can reduce the worst case size of IBC lite client proofs, which occurs when a validator set has high churn. +* Light client efficiency. This would lessen the overhead for IBC when there is high churn in the validator set. In the Tendermint light client bisection algorithm, the number of headers you need to verify is related to bounding the difference in validator sets between a trusted header and the latest header. If the difference is too great, you verify more headers in between the two. By limiting the frequency of validator set changes, we can reduce the worst case size of IBC lite client proofs, which occurs when a validator set has high churn. -* Fairness of deterministic leader election. Currently we have no ways of reasoning of fairness of deterministic leader election in the presence of staking changes without epochs (tendermint/spec#217). Breaking fairness of leader election is profitable for validators, as they earn additional rewards from being the proposer. Adding epochs at least makes it easier for our deterministic leader election to match something we can prove secure. (Albeit, we still haven’t proven if our current algorithm is fair with > 2 validators in the presence of stake changes) +* Fairness of deterministic leader election. Currently we have no ways of reasoning about fairness of deterministic leader election in the presence of staking changes without epochs (tendermint/spec#217). Breaking fairness of leader election is profitable for validators, as they earn additional rewards from being the proposer. Adding epochs at least makes it easier for our deterministic leader election to match something we can prove secure. (Albeit, we still haven’t proven if our current algorithm is fair with > 2 validators in the presence of stake changes) * Staking derivative design. Currently, reward distribution is done lazily using the F1 fee distribution. While saving computational complexity, lazy accounting requires a more stateful staking implementation. Right now, each delegation entry has to track the time of last withdrawal. Handling this can be a challenge for some staking derivatives designs that seek to provide fungibility for all tokens staked to a single validator. Force-withdrawing rewards to users can help solve this, however it is infeasible to force-withdraw rewards to users on a per block basis. With epochs, a chain could more easily alter the design to have rewards be forcefully withdrawn (iterating over delegator accounts only once per-epoch), and can thus remove delegation timing from state. This may be useful for certain staking derivative designs. @@ -41,11 +41,11 @@ Furthermore, it has become clearer over time that immediate execution of staking There is a design consideration for whether to apply a slash immediately or at the end of an epoch. A slash event should apply to only members who are actually staked during the time of the infraction, namely during the epoch the slash event occurred. -Applying it immediately can be viewed as offering greater consensus layer security, at potential costs to the aforementioned usecases. The benefits of immediate slashing for consensus layer security can be all be obtained by executing the validator jailing immediately (thus removing it from the validator set), and delaying the actual slash change to the validator's weight until the epoch boundary. For the use cases mentioned above, workarounds can be integrated to avoid problems, as follows: +Applying it immediately can be viewed as offering greater consensus layer security, at potential costs to the aforementioned use cases. The benefits of immediate slashing for consensus layer security can be all be obtained by executing the validator jailing immediately (thus removing it from the validator set), and delaying the actual slash change to the validator's weight until the epoch boundary. For the use cases mentioned above, workarounds can be integrated to avoid problems, as follows: * For threshold based cryptography, this setting will have the threshold cryptography use the original epoch weights, while consensus has an update that lets it more rapidly benefit from additional security. If the threshold based cryptography blocks liveness of the chain, then we have effectively raised the liveness threshold of the remaining validators for the rest of the epoch. (Alternatively, jailed nodes could still contribute shares) This plan will fail in the extreme case that more than 1/3rd of the validators have been jailed within a single epoch. For such an extreme scenario, the chain already have its own custom incident response plan, and defining how to handle the threshold cryptography should be a part of that. * For light client efficiency, there can be a bit included in the header indicating an intra-epoch slash (ala https://github.com/tendermint/spec/issues/199). -* For fairness of deterministic leader election, applying a slash or jailing within an epoch would break the guarantee we were seeking to provide. This then re-introduces a new (but significantly simpler) problem for trying to provide fairness guarantees. Namely, that validators can adversarially elect to remove themself from the set of proposers. From a security perspective, this could potentially be handled by two different mechanisms (or prove to still be too difficult to achieve). One is making a security statement acknowledging the ability for an adversary to force an ahead-of-time fixed threshold of users to drop out of the proposer set within an epoch. The second method would be to parameterize such that the cost of a slash within the epoch far outweights benefits due to being a proposer. However, this latter criterion is quite dubious, since being a proposer can have many advantageous side-effects in chains with complex state machines. (Namely, DeFi games such as Fomo3D) +* For fairness of deterministic leader election, applying a slash or jailing within an epoch would break the guarantee we were seeking to provide. This then re-introduces a new (but significantly simpler) problem for trying to provide fairness guarantees. Namely, that validators can adversarially elect to remove themselves from the set of proposers. From a security perspective, this could potentially be handled by two different mechanisms (or prove to still be too difficult to achieve). One is making a security statement acknowledging the ability for an adversary to force an ahead-of-time fixed threshold of users to drop out of the proposer set within an epoch. The second method would be to parameterize such that the cost of a slash within the epoch far outweighs benefits due to being a proposer. However, this latter criterion is quite dubious, since being a proposer can have many advantageous side-effects in chains with complex state machines. (Namely, DeFi games such as Fomo3D) * For staking derivative design, there is no issue introduced. This does not increase the state size of staking records, since whether a slash has occurred is fully queryable given the validator address. ### Token lockup @@ -67,7 +67,7 @@ Even though all staking updates are applied at epoch boundaries, rewards can sti ### Parameterizing the epoch length -When choosing the epoch length, there is a trade-off queued state/computation buildup, and countering the previously discussed limitations of immediate execution if they apply to a given chain. +When choosing the epoch length, there is a trade-off between queued state/computation buildup, and countering the previously discussed limitations of immediate execution if they apply to a given chain. Until an ABCI mechanism for variable block times is introduced, it is ill-advised to be using high epoch lengths due to the computation buildup. This is because when a block's execution time is greater than the expected block time from Tendermint, rounds may increment. @@ -79,16 +79,16 @@ First we create a pool for storing tokens that are being bonded, but should be a ### Staking messages -* **MsgCreateValidator**: Move user's self-bond to `EpochDelegationPool` immediately. Queue a message for the epoch boundary to handle the self-bond, taking the funds from the `EpochDelegationPool`. If Epoch execution fail, return back funds from `EpochDelegationPool` to user's account. +* **MsgCreateValidator**: Move user's self-bond to `EpochDelegationPool` immediately. Queue a message for the epoch boundary to handle the self-bond, taking the funds from the `EpochDelegationPool`. If Epoch execution fails, return back funds from `EpochDelegationPool` to user's account. * **MsgEditValidator**: Validate message and if valid queue the message for execution at the end of the Epoch. -* **MsgDelegate**: Move user's funds to `EpochDelegationPool` immediately. Queue a message for the epoch boundary to handle the delegation, taking the funds from the `EpochDelegationPool`. If Epoch execution fail, return back funds from `EpochDelegationPool` to user's account. +* **MsgDelegate**: Move user's funds to `EpochDelegationPool` immediately. Queue a message for the epoch boundary to handle the delegation, taking the funds from the `EpochDelegationPool`. If Epoch execution fails, return back funds from `EpochDelegationPool` to user's account. * **MsgBeginRedelegate**: Validate message and if valid queue the message for execution at the end of the Epoch. * **MsgUndelegate**: Validate message and if valid queue the message for execution at the end of the Epoch. ### Slashing messages * **MsgUnjail**: Validate message and if valid queue the message for execution at the end of the Epoch. -* **Slash Event**: Whenever a slash event is created, it gets queued in the slashing module to apply at the end of the epoch. The queues should be setup such that this slash applies immediately. +* **Slash Event**: Whenever a slash event is created, it gets queued in the slashing module to apply at the end of the epoch. The queues should be set up such that this slash applies immediately. ### Evidence Messages @@ -100,14 +100,14 @@ Then we add methods to the end blockers, to ensure that at the epoch boundary th When querying the staking activity of a given address, the status should return not only the amount of tokens staked, but also if there are any queued stake events for that address. This will require more work to be done in the querying logic, to trace the queued upcoming staking events. -As an initial implementation, this can be implemented as a linear search over all queued staking events. However, for chains that need long epochs, they should eventually build additional support for nodes that support querying to be able to produce results in constant time. (This is do-able by maintaining an auxilliary hashmap for indexing upcoming staking events by address) +As an initial implementation, this can be implemented as a linear search over all queued staking events. However, for chains that need long epochs, they should eventually build additional support for nodes that support querying to be able to produce results in constant time. (This is doable by maintaining an auxiliary hashmap for indexing upcoming staking events by address) **Step-3**: Adjust gas Currently gas represents the cost of executing a transaction when its done immediately. (Merging together costs of p2p overhead, state access overhead, and computational overhead) However, now a transaction can cause computation in a future block, namely at the epoch boundary. To handle this, we should initially include parameters for estimating the amount of future computation (denominated in gas), and add that as a flat charge needed for the message. -We leave it as out of scope for how to weight future computation versus current computation in gas pricing, and have it set such that the are weighted equally for now. +We leave it out of scope for how to weight future computation versus current computation in gas pricing, and have it set such that they are weighted equally for now. ## Consequences diff --git a/docs/build/architecture/adr-040-storage-and-smt-state-commitments.md b/docs/build/architecture/adr-040-storage-and-smt-state-commitments.md index f60e3adcf..6259e588f 100644 --- a/docs/build/architecture/adr-040-storage-and-smt-state-commitments.md +++ b/docs/build/architecture/adr-040-storage-and-smt-state-commitments.md @@ -17,7 +17,7 @@ Sparse Merkle Tree ([SMT](https://osf.io/8mcnh/)) is a version of a Merkle Tree Currently, Cosmos SDK uses IAVL for both state [commitments](https://cryptography.fandom.com/wiki/Commitment_scheme) and data storage. IAVL has effectively become an orphaned project within the Cosmos ecosystem and it's proven to be an inefficient state commitment data structure. -In the current design, IAVL is used for both data storage and as a Merkle Tree for state commitments. IAVL is meant to be a standalone Merkelized key/value database, however it's using a KV DB engine to store all tree nodes. So, each node is stored in a separate record in the KV DB. This causes many inefficiencies and problems: +In the current design, IAVL is used for both data storage and as a Merkle Tree for state commitments. IAVL is meant to be a standalone Merkleized key/value database, however it's using a KV DB engine to store all tree nodes. So, each node is stored in a separate record in the KV DB. This causes many inefficiencies and problems: * Each object query requires a tree traversal from the root. Subsequent queries for the same object are cached on the Cosmos SDK level. * Each edge traversal requires a DB query. @@ -30,7 +30,7 @@ Moreover, the IAVL project lacks support and a maintainer and we already see bet ## Decision -We propose to separate the concerns of state commitment (**SC**), needed for consensus, and state storage (**SS**), needed for state machine. Finally we replace IAVL with [Celestia's SMT](https://github.com/lazyledger/smt). Celestia SMT is based on Diem (called jellyfish) design [*] - it uses a compute-optimised SMT by replacing subtrees with only default values with a single node (same approach is used by Ethereum2) and implements compact proofs. +We propose to separate the concerns of state commitment (**SC**), needed for consensus, and state storage (**SS**), needed for state machine. Finally we replace IAVL with [Celestia's SMT](https://github.com/lazyledger/smt). Celestia SMT is based on Diem (called jellyfish) design [*] - it uses a compute-optimized SMT by replacing subtrees with only default values with a single node (same approach is used by Ethereum2) and implements compact proofs. The storage model presented here doesn't deal with data structure nor serialization. It's a Key-Value database, where both key and value are binaries. The storage user is responsible for data serialization. @@ -92,7 +92,7 @@ A new database snapshot will be created in every `EndBlocker` and identified by NOTE: `Commit` must be called exactly once per block. Otherwise we risk going out of sync for the version number and block height. NOTE: For the Cosmos SDK storage, we may consider splitting that interface into `Committer` and `PruningCommitter` - only the multiroot should implement `PruningCommitter` (cache and prefix store don't need pruning). -Number of historical versions for `abci.RequestQuery` and state sync snapshots is part of a node configuration, not a chain configuration (configuration implied by the blockchain consensus). A configuration should allow to specify number of past blocks and number of past blocks modulo some number (eg: 100 past blocks and one snapshot every 100 blocks for past 2000 blocks). Archival nodes can keep all past versions. +Number of historical versions for `abci.QueryRequest` and state sync snapshots is part of a node configuration, not a chain configuration (configuration implied by the blockchain consensus). A configuration should allow to specify number of past blocks and number of past blocks modulo some number (eg: 100 past blocks and one snapshot every 100 blocks for past 2000 blocks). Archival nodes can keep all past versions. Pruning old snapshots is effectively done by a database. Whenever we update a record in `SC`, SMT won't update nodes - instead it creates new nodes on the update path, without removing the old one. Since we are snapshotting each block, we need to change that mechanism to immediately remove orphaned nodes from the database. This is a safe operation - snapshots will keep track of the records and make it available when accessing past versions. @@ -100,8 +100,8 @@ To manage the active snapshots we will either use a DB _max number of snapshots_ #### Accessing old state versions -One of the functional requirements is to access old state. This is done through `abci.RequestQuery` structure. The version is specified by a block height (so we query for an object by a key `K` at block height `H`). The number of old versions supported for `abci.RequestQuery` is configurable. Accessing an old state is done by using available snapshots. -`abci.RequestQuery` doesn't need old state of `SC` unless the `prove=true` parameter is set. The SMT merkle proof must be included in the `abci.ResponseQuery` only if both `SC` and `SS` have a snapshot for requested version. +One of the functional requirements is to access old state. This is done through `abci.QueryRequest` structure. The version is specified by a block height (so we query for an object by a key `K` at block height `H`). The number of old versions supported for `abci.QueryRequest` is configurable. Accessing an old state is done by using available snapshots. +`abci.QueryRequest` doesn't need old state of `SC` unless the `prove=true` parameter is set. The SMT merkle proof must be included in the `abci.QueryResponse` only if both `SC` and `SS` have a snapshot for requested version. Moreover, Cosmos SDK could provide a way to directly access a historical state. However, a state machine shouldn't do that - since the number of snapshots is configurable, it would lead to nondeterministic execution. @@ -285,5 +285,5 @@ We were discussing use case where modules can use a support database, which is n * Facebook Diem (Libra) SMT [design](https://developers.diem.com/papers/jellyfish-merkle-tree/2021-01-14.pdf) * [Trillian Revocation Transparency](https://github.com/google/trillian/blob/master/docs/papers/RevocationTransparency.pdf), [Trillian Verifiable Data Structures](https://github.com/google/trillian/blob/master/docs/papers/VerifiableDataStructures.pdf). * Design and implementation [discussion](https://github.com/cosmos/cosmos-sdk/discussions/8297). -* [How to Upgrade IBC Chains and their Clients](https://github.com/cosmos/ibc-go/blob/main/docs/ibc/upgrades/quick-guide.md) +* [How to Upgrade IBC Chains and their Clients](https://ibc.cosmos.network/main/ibc/upgrades/quick-guide/) * [ADR-40 Effect on IBC](https://github.com/cosmos/ibc-go/discussions/256) diff --git a/docs/build/architecture/adr-041-in-place-store-migrations.md b/docs/build/architecture/adr-041-in-place-store-migrations.md index 2237b610d..15c79589a 100644 --- a/docs/build/architecture/adr-041-in-place-store-migrations.md +++ b/docs/build/architecture/adr-041-in-place-store-migrations.md @@ -134,7 +134,7 @@ app.UpgradeKeeper.SetUpgradeHandler("my-plan", func(ctx sdk.Context, plan upgrad Assuming a chain upgrades at block `n`, the procedure should run as follows: * the old binary will halt in `BeginBlock` when starting block `N`. In its store, the ConsensusVersions of the old binary's modules are stored. -* the new binary will start at block `N`. The UpgradeHandler is set in the new binary, so will run at `BeginBlock` of the new binary. Inside `x/upgrade`'s `ApplyUpgrade`, the `VersionMap` will be retrieved from the (old binary's) store, and passed into the `RunMigrations` functon, migrating all module stores in-place before the modules' own `BeginBlock`s. +* the new binary will start at block `N`. The UpgradeHandler is set in the new binary, so will run at `BeginBlock` of the new binary. Inside `x/upgrade`'s `ApplyUpgrade`, the `VersionMap` will be retrieved from the (old binary's) store, and passed into the `RunMigrations` function, migrating all module stores in-place before the modules' own `BeginBlock`s. ## Consequences diff --git a/docs/build/architecture/adr-042-group-module.md b/docs/build/architecture/adr-042-group-module.md index 52e94327d..03fbe34be 100644 --- a/docs/build/architecture/adr-042-group-module.md +++ b/docs/build/architecture/adr-042-group-module.md @@ -22,13 +22,13 @@ The legacy amino multi-signature mechanism of the Cosmos SDK has certain limitat * It requires `legacy_amino` sign mode ([#8141](https://github.com/cosmos/cosmos-sdk/issues/8141)). While the group module is not meant to be a total replacement for the current multi-signature accounts, it provides a solution to the limitations described above, with a more flexible key management system where keys can be added, updated or removed, as well as configurable thresholds. -It's meant to be used with other access control modules such as [`x/feegrant`](./adr-029-fee-grant-module.md) ans [`x/authz`](adr-030-authz-module.md) to simplify key management for individuals and organizations. +It's meant to be used with other access control modules such as [`x/feegrant`](./adr-029-fee-grant-module.md) and [`x/authz`](adr-030-authz-module.md) to simplify key management for individuals and organizations. -The proof of concept of the group module can be found in https://github.com/regen-network/regen-ledger/tree/master/proto/regen/group/v1alpha1 and https://github.com/regen-network/regen-ledger/tree/master/x/group. +The proof of concept of the group module can be found in https://github.com/cosmos/cosmos-sdk/tree/main/proto/cosmos/group/v1 and https://github.com/cosmos/cosmos-sdk/tree/main/x/group. ## Decision -We propose merging the `x/group` module with its supporting [ORM/Table Store package](https://github.com/regen-network/regen-ledger/tree/master/orm) ([#7098](https://github.com/cosmos/cosmos-sdk/issues/7098)) into the Cosmos SDK and continuing development here. There will be a dedicated ADR for the ORM package. +We propose merging the `x/group` module with its supporting [ORM/Table Store package](https://github.com/cosmos/cosmos-sdk/tree/main/x/group/internal/orm) ([#7098](https://github.com/cosmos/cosmos-sdk/issues/7098)) into the Cosmos SDK and continuing development here. There will be a dedicated ADR for the ORM package. ### Group diff --git a/docs/build/architecture/adr-043-nft-module.md b/docs/build/architecture/adr-043-nft-module.md index 87b4dbb5e..7c8dfcd11 100644 --- a/docs/build/architecture/adr-043-nft-module.md +++ b/docs/build/architecture/adr-043-nft-module.md @@ -156,7 +156,7 @@ message MsgSend { string class_id = 1; string id = 2; string sender = 3; - string reveiver = 4; + string receiver = 4; } message MsgSendResponse {} ``` @@ -253,7 +253,7 @@ message QuerySupplyResponse { uint64 amount = 1; } -// QueryNFTstRequest is the request type for the Query/NFTs RPC method +// QueryNFTsRequest is the request type for the Query/NFTs RPC method message QueryNFTsRequest { string class_id = 1; string owner = 2; @@ -315,7 +315,7 @@ No backward incompatibilities. ### Forward Compatibility -This specification conforms to the ERC-721 smart contract specification for NFT identifiers. Note that ERC-721 defines uniqueness based on (contract address, uint256 tokenId), and we conform to this implicitly because a single module is currently aimed to track NFT identifiers. Note: use of the (mutable) data field to determine uniqueness is not safe.s +This specification conforms to the ERC-721 smart contract specification for NFT identifiers. Note that ERC-721 defines uniqueness based on (contract address, uint256 tokenId), and we conform to this implicitly because a single module is currently aimed to track NFT identifiers. Note: use of the (mutable) data field to determine uniqueness is not safe. ### Positive diff --git a/docs/build/architecture/adr-044-protobuf-updates-guidelines.md b/docs/build/architecture/adr-044-protobuf-updates-guidelines.md index a5ea31316..595b16de0 100644 --- a/docs/build/architecture/adr-044-protobuf-updates-guidelines.md +++ b/docs/build/architecture/adr-044-protobuf-updates-guidelines.md @@ -20,7 +20,7 @@ The Cosmos SDK maintains a set of [Protobuf definitions](https://github.com/cosm When making changes to these Protobuf definitions, the Cosmos SDK currently only follows [Buf's](https://docs.buf.build/) recommendations. We noticed however that Buf's recommendations might still result in breaking changes in the SDK in some cases. For example: -* Adding fields to `Msg`s. Adding fields is a not a Protobuf spec-breaking operation. However, when adding new fields to `Msg`s, the unknown field rejection will throw an error when sending the new `Msg` to an older node. +* Adding fields to `Msg`s. Adding fields is not a Protobuf spec-breaking operation. However, when adding new fields to `Msg`s, the unknown field rejection will throw an error when sending the new `Msg` to an older node. * Marking fields as `reserved`. Protobuf proposes the `reserved` keyword for removing fields without the need to bump the package version. However, by doing so, client backwards compatibility is broken as Protobuf doesn't generate anything for `reserved` fields. See [#9446](https://github.com/cosmos/cosmos-sdk/issues/9446) for more details on this issue. Moreover, module developers often face other questions around Protobuf definitions such as "Can I rename a field?" or "Can I deprecate a field?" This ADR aims to answer all these questions by providing clear guidelines about allowed updates for Protobuf definitions. @@ -49,7 +49,7 @@ The SDK requires the Protobuf comment of the new addition to contain one line wi // Since: cosmos-sdk {, ...} ``` -Where each `version` denotes a minor ("0.45") or patch ("0.44.5") version from which the field is available. This will greatly help client libraries, who can optionally use reflection or custom code generation to show/hide these fields depending on the targetted node version. +Where each `version` denotes a minor ("0.45") or patch ("0.44.5") version from which the field is available. This will greatly help client libraries, who can optionally use reflection or custom code generation to show/hide these fields depending on the targeted node version. As examples, the following comments are valid: diff --git a/docs/build/architecture/adr-045-check-delivertx-middlewares.md b/docs/build/architecture/adr-045-check-delivertx-middlewares.md index 60172977c..f55c21598 100644 --- a/docs/build/architecture/adr-045-check-delivertx-middlewares.md +++ b/docs/build/architecture/adr-045-check-delivertx-middlewares.md @@ -18,7 +18,7 @@ This ADR replaces the current BaseApp `runTx` and antehandlers design with a mid BaseApp's implementation of ABCI `{Check,Deliver}Tx()` and its own `Simulate()` method call the `runTx` method under the hood, which first runs antehandlers, then executes `Msg`s. However, the [transaction Tips](https://github.com/cosmos/cosmos-sdk/issues/9406) and [refunding unused gas](https://github.com/cosmos/cosmos-sdk/issues/2150) use cases require custom logic to be run after the `Msg`s execution. There is currently no way to achieve this. -An naive solution would be to add post-`Msg` hooks to BaseApp. However, the Cosmos SDK team thinks in parallel about the bigger picture of making app wiring simpler ([#9181](https://github.com/cosmos/cosmos-sdk/discussions/9182)), which includes making BaseApp more lightweight and modular. +A naive solution would be to add post-`Msg` hooks to BaseApp. However, the Cosmos SDK team thinks in parallel about the bigger picture of making app wiring simpler ([#9181](https://github.com/cosmos/cosmos-sdk/discussions/9182)), which includes making BaseApp more lightweight and modular. ## Decision @@ -64,7 +64,7 @@ type ResponseCheckTx struct { } ``` -Please note that because CheckTx handles separate logic related to mempool priotization, its signature is different than DeliverTx and SimulateTx. +Please note that because CheckTx handles separate logic related to mempool prioritization, its signature is different than DeliverTx and SimulateTx. BaseApp holds a reference to a `tx.Handler`: @@ -185,7 +185,7 @@ func (h myTxHandler) SimulateTx(ctx context.Context, req Request) (Response, err While BaseApp simply holds a reference to a `tx.Handler`, this `tx.Handler` itself is defined using a middleware stack. The Cosmos SDK exposes a base (i.e. innermost) `tx.Handler` called `RunMsgsTxHandler`, which executes messages. -Then, the app developer can compose multiple middlewares on top on the base `tx.Handler`. Each middleware can run pre-and-post-processing logic around its next middleware, as described in the section above. Conceptually, as an example, given the middlewares `A`, `B`, and `C` and the base `tx.Handler` `H` the stack looks like: +Then, the app developer can compose multiple middlewares on top of the base `tx.Handler`. Each middleware can run pre-and-post-processing logic around its next middleware, as described in the section above. Conceptually, as an example, given the middlewares `A`, `B`, and `C` and the base `tx.Handler` `H` the stack looks like: ```text A.pre diff --git a/docs/build/architecture/adr-046-module-params.md b/docs/build/architecture/adr-046-module-params.md index 369cd043d..10bb65cde 100644 --- a/docs/build/architecture/adr-046-module-params.md +++ b/docs/build/architecture/adr-046-module-params.md @@ -142,8 +142,8 @@ and writing parameters from and to state, especially if a specific set of parame are read on a consistent basis. However, this methodology will require developers to implement more types and -Msg service metohds which can become burdensome if many parameters exist. In addition, -developers are required to implement persistance logics of module parameters. +Msg service methods which can become burdensome if many parameters exist. In addition, +developers are required to implement persistence logics of module parameters. However, this should be trivial. ### Backwards Compatibility @@ -162,7 +162,7 @@ module may be removed entirely in a future release. ### Negative -* Module parameters becomes slightly more burdensome for module developers: +* Module parameters become slightly more burdensome for module developers: * Modules are now responsible for persisting and retrieving parameter state * Modules are now required to have unique message handlers to handle parameter changes per unique parameter data structure. diff --git a/docs/build/architecture/adr-047-extend-upgrade-plan.md b/docs/build/architecture/adr-047-extend-upgrade-plan.md index 3500bb334..610feccc9 100644 --- a/docs/build/architecture/adr-047-extend-upgrade-plan.md +++ b/docs/build/architecture/adr-047-extend-upgrade-plan.md @@ -59,7 +59,7 @@ The current upgrade process has this timeline: We will update the `x/upgrade.Plan` message for providing upgrade instructions. The upgrade instructions will contain a list of artifacts available for each platform. It allows for the definition of a pre-run and post-run commands. -These commands are not consensus guaranteed; they will be executed by Cosmosvisor (or other) during its upgrade handling. +These commands are not consensus guaranteed; they will be executed by Cosmovisor (or other) during its upgrade handling. ```protobuf message Plan { @@ -88,13 +88,14 @@ All fields in the `UpgradeInstructions` are optional. This command MUST behave the same as the current [pre-upgrade](https://github.com/cosmos/cosmos-sdk/blob/v0.44.5/docs/migrations/pre-upgrade.md) command. It does not take in any command-line arguments and is expected to terminate with the following exit codes: - | Exit status code | How it is handled in Cosmosvisor | + | Exit status code | How it is handled in Cosmovisor | |------------------|---------------------------------------------------------------------------------------------------------------------| | `0` | Assumes `pre-upgrade` command executed successfully and continues the upgrade. | | `1` | Default exit code when `pre-upgrade` command has not been implemented. | | `30` | `pre-upgrade` command was executed but failed. This fails the entire upgrade. | | `31` | `pre-upgrade` command was executed but failed. But the command is retried until exit code `1` or `30` are returned. | If defined, then the app supervisors (e.g. Cosmovisor) MUST NOT run `app pre-run`. + * `post_run` is a command to run after the upgraded chain has been started. If defined, this command MUST be only executed at most once by an upgrading node. The output and exit code SHOULD be logged but SHOULD NOT affect the running of the upgraded chain. The working directory this command runs from MUST be `{DAEMON_HOME}/cosmovisor/{upgrade name}`. @@ -125,7 +126,7 @@ message Artifact { It is not required, but is recommended. If provided, it MUST be a hex encoded checksum string. Tools utilizing these `UpgradeInstructions` MUST fail if a `checksum` is provided but is different from the checksum of the result returned by the `url`. -* `checksum_algo` is a string identify the algorithm used to generate the `checksum`. +* `checksum_algo` is a string identifying the algorithm used to generate the `checksum`. Recommended algorithms: `sha256`, `sha512`. Algorithms also supported (but not recommended): `sha1`, `md5`. If a `checksum` is provided, a `checksum_algo` MUST also be provided. diff --git a/docs/build/architecture/adr-048-consensus-fees.md b/docs/build/architecture/adr-048-consensus-fees.md index f1c6065cd..6fbaeef6e 100644 --- a/docs/build/architecture/adr-048-consensus-fees.md +++ b/docs/build/architecture/adr-048-consensus-fees.md @@ -1,4 +1,4 @@ -# ADR 048: Multi Tire Gas Price System +# ADR 048: Multi Tier Gas Price System ## Changelog @@ -26,7 +26,7 @@ We propose a multi-tier price system on consensus to provide maximum flexibility * Tier 2: a dynamic gas price which is adjusted according to previous block load. * Tier 3: a dynamic gas price which is adjusted according to previous block load at a higher speed. -The gas price of higher tier should bigger than the lower tier. +The gas price of higher tier should be bigger than the lower tier. The transaction fees are charged with the exact gas price calculated on consensus. @@ -72,7 +72,7 @@ This mechanism can be easily composed with prioritization mechanisms: * we can add extra tiers out of a user control: * Example 1: user can set tier 0, 10 or 20, but the protocol will create tiers 0, 1, 2 ... 29. For example IBC transactions will go to tier `user_tier + 5`: if user selected tier 1, then the transaction will go to tier 15. * Example 2: we can reserve tier 4, 5, ... only for special transaction types. For example, tier 5 is reserved for evidence tx. So if submits a bank.Send transaction and set tier 5, it will be delegated to tier 3 (the max tier level available for any transaction). - * Example 3: we can enforce that all transactions of a sepecific type will go to specific tier. For example, tier 100 will be reserved for evidence transactions and all evidence transactions will always go to that tier. + * Example 3: we can enforce that all transactions of a specific type will go to specific tier. For example, tier 100 will be reserved for evidence transactions and all evidence transactions will always go to that tier. ### `min-gas-prices` diff --git a/docs/build/architecture/adr-049-state-sync-hooks.md b/docs/build/architecture/adr-049-state-sync-hooks.md index c7353aa3b..8b039d66f 100644 --- a/docs/build/architecture/adr-049-state-sync-hooks.md +++ b/docs/build/architecture/adr-049-state-sync-hooks.md @@ -31,13 +31,13 @@ acting as a delimiter between extensions. As the chunk hashes should be able to a delimiter to mark the end of the snapshot stream. Besides, we provide `Snapshotter` and `ExtensionSnapshotter` interface for modules to implement snapshotters, which will handle both taking -snapshot and the restoration. Each module could have mutiple snapshotters, and for modules with additional state, they should +snapshot and the restoration. Each module could have multiple snapshotters, and for modules with additional state, they should implement `ExtensionSnapshotter` as extension snapshotters. When setting up the application, the snapshot `Manager` should call `RegisterExtensions([]ExtensionSnapshotter…)` to register all the extension snapshotters. ```protobuf // SnapshotItem is an item contained in a rootmulti.Store snapshot. -// On top of the exsiting SnapshotStoreItem and SnapshotIAVLItem, we add two new options for the item. +// On top of the existing SnapshotStoreItem and SnapshotIAVLItem, we add two new options for the item. message SnapshotItem { // item is the specific type of snapshot item. oneof item { @@ -139,14 +139,14 @@ type ExtensionSnapshotter interface { ## Consequences -As a result of this implementation, we are able to create snapshots of binary chunk stream for the state that we maintain outside of the IAVL Tree, CosmWasm blobs for example. And new clients are able to fetch sanpshots of state for all modules that have implemented the corresponding interface from peer nodes. +As a result of this implementation, we are able to create snapshots of binary chunk stream for the state that we maintain outside of the IAVL Tree, CosmWasm blobs for example. And new clients are able to fetch snapshots of state for all modules that have implemented the corresponding interface from peer nodes. ### Backwards Compatibility -This ADR introduces new proto message types, add an `extensions` field in snapshot `Manager`, and add new `ExtensionSnapshotter` interface, so this is not backwards compatible if we have extensions. +This ADR introduces new proto message types, adds an `extensions` field in snapshot `Manager`, and add new `ExtensionSnapshotter` interface, so this is not backwards compatible if we have extensions. -But for applications that does not have the state data outside of the IAVL tree for any module, the snapshot stream is backwards-compatible. +But for applications that do not have the state data outside of the IAVL tree for any module, the snapshot stream is backwards-compatible. ### Positive diff --git a/docs/build/architecture/adr-050-sign-mode-textual-annex1.md b/docs/build/architecture/adr-050-sign-mode-textual-annex1.md index ff3acc8c5..96e0d0942 100644 --- a/docs/build/architecture/adr-050-sign-mode-textual-annex1.md +++ b/docs/build/architecture/adr-050-sign-mode-textual-annex1.md @@ -51,7 +51,7 @@ Value Renderers describe how values of different Protobuf types should be encode ### `coins` -* an array of `coin` is display as the concatenation of each `coin` encoded as the specification above, the joined together with the delimiter `", "` (a comma and a space, no quotes around). +* an array of `coin` is display as the concatenation of each `coin` encoded as the specification above, then joined together with the delimiter `", "` (a comma and a space, no quotes around). * the list of coins is ordered by unicode code point of the display denom: `A-Z` < `a-z`. For example, the string `aAbBcC` would be sorted `ABCabc`. * if the coins list had 0 items in it then it'll be rendered as `zero` @@ -195,6 +195,7 @@ Messages that have a custom encoding, including `google.protobuf.Timestamp`, `go #### Examples Message header screen is stripped, one-level of indentation removed: + ``` /cosmos.gov.v1.Vote > Proposal id: 4 @@ -210,6 +211,7 @@ Message header screen is stripped, one-level of indentation removed: ``` Message with custom encoding: + ``` /cosmos.base.v1beta1.Coin > 10uatom @@ -271,11 +273,12 @@ Examples: * The hexadecimal string is finally separated into groups of 4 digits, with a space `' '` as separator. If the bytes length is odd, the 2 remaining hexadecimal characters are at the end. The number 35 was chosen because it is the longest length where the hashed-and-prefixed representation is longer than the original data directly formatted, using the 3 rules above. More specifically: -- a 35-byte array will have 70 hex characters, plus 17 space characters, resulting in 87 characters. -- byte arrays starting from length 36 will be be hashed to 32 bytes, which is 64 hex characters plus 15 spaces, and with the `SHA-256=` prefix, it takes 87 characters. + +* a 35-byte array will have 70 hex characters, plus 17 space characters, resulting in 87 characters. +* byte arrays starting from length 36 will be hashed to 32 bytes, which is 64 hex characters plus 15 spaces, and with the `SHA-256=` prefix, it takes 87 characters. Also, secp256k1 public keys have length 33, so their Textual representation is not their hashed value, which we would like to avoid. -Note: Data longer than 35 bytes are not rendered in a way that can be inverted. See ADR-050's [section about invertability](./adr-050-sign-mode-textual.md#invertible-rendering) for a discussion. +Note: Data longer than 35 bytes are not rendered in a way that can be inverted. See ADR-050's [section about invertibility](./adr-050-sign-mode-textual.md#invertible-rendering) for a discussion. #### Examples @@ -346,7 +349,7 @@ message MsgSend { * `cosmos.gov.v1.MsgVote` -> `governance v1 vote` -#### Best Pratices +#### Best Practices We recommend to use this option only for `Msg`s whose Protobuf fully qualified name can be hard to understand. As such, the two examples above (`MsgSend` and `MsgVote`) are not good examples to be used with `msg_title`. We still allow `msg_title` for chains who might have `Msg`s with complex or non-obvious names. diff --git a/docs/build/architecture/adr-050-sign-mode-textual-annex2.md b/docs/build/architecture/adr-050-sign-mode-textual-annex2.md index 9bd0f3f47..3a44001fb 100644 --- a/docs/build/architecture/adr-050-sign-mode-textual-annex2.md +++ b/docs/build/architecture/adr-050-sign-mode-textual-annex2.md @@ -25,7 +25,7 @@ Unicode text within the transaction. `SIGN_MODE_TEXTUAL` renders to an abstract representation, leaving it up to device-specific software how to present this representation given the -capabilities, limitations, and conventions of the deivce. +capabilities, limitations, and conventions of the device. We offer the following normative guidance: @@ -77,7 +77,7 @@ in many languages: * All other ASCII control characters, plus non-ASCII Unicode code points, are shown as either: - * `\u` followed by 4 uppercase hex chacters for code points + * `\u` followed by 4 uppercase hex characters for code points in the basic multilingual plane (BMP). * `\U` followed by 8 uppercase hex characters for other code points. diff --git a/docs/build/architecture/adr-050-sign-mode-textual.md b/docs/build/architecture/adr-050-sign-mode-textual.md index c5b51b223..531859685 100644 --- a/docs/build/architecture/adr-050-sign-mode-textual.md +++ b/docs/build/architecture/adr-050-sign-mode-textual.md @@ -11,7 +11,7 @@ * Nov 23, 2022: Specify CBOR encoding. * Dec 01, 2022: Link to examples in separate JSON file. * Dec 06, 2022: Re-ordering of envelope screens. -* Dec 14, 2022: Mention exceptions for invertability. +* Dec 14, 2022: Mention exceptions for invertibility. * Jan 23, 2023: Switch Screen.Text to Title+Content. * Mar 07, 2023: Change SignDoc from array to struct containing array. * Mar 20, 2023: Introduce a spec version initialized to 0. @@ -24,7 +24,7 @@ Spec version: 0. ## Abstract -This ADR specifies SIGN_MODE_TEXTUAL, a new string-based sign mode that is targetted at signing with hardware devices. +This ADR specifies SIGN_MODE_TEXTUAL, a new string-based sign mode that is targeted at signing with hardware devices. ## Context @@ -72,7 +72,7 @@ or needs to be present only for signature integrity (see below). We require that the rendering of the transaction be invertible: there must be a parsing function such that for every transaction, when rendered to the textual representation, -parsing that representation yeilds a proto message equivalent +parsing that representation yields a proto message equivalent to the original under proto equality. Note that this inverse function does not need to perform correct @@ -145,7 +145,7 @@ type SignDocTextual struct { ``` We do not plan to use protobuf serialization to form the sequence of bytes -that will be tranmitted and signed, in order to keep the decoder simple. +that will be transmitted and signed, in order to keep the decoder simple. We will use [CBOR](https://cbor.io) ([RFC 8949](https://www.rfc-editor.org/rfc/rfc8949.html)) instead. The encoding is defined by the following CDDL ([RFC 8610](https://www.rfc-editor.org/rfc/rfc8610)): @@ -205,7 +205,7 @@ Memo: // Skipped if no mem Fee: // See value renderers for coins rendering. *Fee payer: // Skipped if no fee_payer set. *Fee granter: // Skipped if no fee_granter set. -Tip: // Skippted if no tip. +Tip: // Skipped if no tip. Tipper: *Gas Limit: *Timeout Height: // Skipped if no timeout_height set. @@ -226,7 +226,7 @@ Tipper: Transaction Body is the `Tx.TxBody.Messages` field, which is an array of `Any`s, where each `Any` packs a `sdk.Msg`. Since `sdk.Msg`s are widely used, they have a slightly different encoding than usual array of `Any`s (Protobuf: `repeated google.protobuf.Any`) described in Annex 1. ``` -This transaction has message: // Optional 's' for "message" if there's is >1 sdk.Msgs. +This transaction has message: // Optional 's' for "message" if there's >1 sdk.Msgs. // For each Msg, print the following 2 lines: Msg (/): // E.g. Msg (1/2): bank v1beta1 send coins @@ -285,7 +285,7 @@ Moreover, the renderer must provide 2 functions: one for formatting from Protobu ### Require signing over the `TxBody` and `AuthInfo` raw bytes -Recall that the transaction bytes merklelized on chain are the Protobuf binary serialization of [TxRaw](hhttps://buf.build/cosmos/cosmos-sdk/docs/main:cosmos.tx.v1beta1#cosmos.tx.v1beta1.TxRaw), which contains the `body_bytes` and `auth_info_bytes`. Moreover, the transaction hash is defined as the SHA256 hash of the `TxRaw` bytes. We require that the user signs over these bytes in SIGN_MODE_TEXTUAL, more specifically over the following string: +Recall that the transaction bytes merkleized on chain are the Protobuf binary serialization of [TxRaw](https://buf.build/cosmos/cosmos-sdk/docs/main:cosmos.tx.v1beta1#cosmos.tx.v1beta1.TxRaw), which contains the `body_bytes` and `auth_info_bytes`. Moreover, the transaction hash is defined as the SHA256 hash of the `TxRaw` bytes. We require that the user signs over these bytes in SIGN_MODE_TEXTUAL, more specifically over the following string: ``` *Hash of raw bytes: @@ -297,7 +297,7 @@ where: * `HEX` is the hexadecimal representation of the bytes, all in capital letters, no `0x` prefix, * and `len()` is encoded as a Big-Endian uint64. -This is to prevent transaction hash malleability. The point #1 about invertiblity assures that transaction `body` and `auth_info` values are not malleable, but the transaction hash still might be malleable with point #1 only, because the SIGN_MODE_TEXTUAL strings don't follow the byte ordering defined in `body_bytes` and `auth_info_bytes`. Without this hash, a malicious validator or exchange could intercept a transaction, modify its transaction hash _after_ the user signed it using SIGN_MODE_TEXTUAL (by tweaking the byte ordering inside `body_bytes` or `auth_info_bytes`), and then submit it to Tendermint. +This is to prevent transaction hash malleability. The point #1 about invertibility assures that transaction `body` and `auth_info` values are not malleable, but the transaction hash still might be malleable with point #1 only, because the SIGN_MODE_TEXTUAL strings don't follow the byte ordering defined in `body_bytes` and `auth_info_bytes`. Without this hash, a malicious validator or exchange could intercept a transaction, modify its transaction hash _after_ the user signed it using SIGN_MODE_TEXTUAL (by tweaking the byte ordering inside `body_bytes` or `auth_info_bytes`), and then submit it to Tendermint. By including this hash in the SIGN_MODE_TEXTUAL signing payload, we keep the same level of guarantees as [SIGN_MODE_DIRECT](./adr-020-protobuf-transaction-encoding.md). @@ -310,9 +310,9 @@ The current specification is not set in stone, and future iterations are to be e 1. Updates that require changes of the hardware device embedded application. 2. Updates that only modify the envelope and the value renderers. -Updates in the 1st category include changes of the `Screen` struct or its corresponding CBOR encoding. This type of updates require a modification of the hardware signer application, to be able to decode and parse the new types. Backwards-compatibility must also be guaranteed, so that the new hardware application works with existing versions of the SDK. These updates require the coordination of multiple parties: SDK developers, hardware application developers (currently: Zondax), and client-side developers (e.g. CosmJS). Furthermore, a new submission of the hardware device application may be necessary, which, dependending on the vendor, can take some time. As such, we recommend to avoid this type of updates as much as possible. +Updates in the 1st category include changes of the `Screen` struct or its corresponding CBOR encoding. This type of updates require a modification of the hardware signer application, to be able to decode and parse the new types. Backwards-compatibility must also be guaranteed, so that the new hardware application works with existing versions of the SDK. These updates require the coordination of multiple parties: SDK developers, hardware application developers (currently: Zondax), and client-side developers (e.g. CosmJS). Furthermore, a new submission of the hardware device application may be necessary, which, depending on the vendor, can take some time. As such, we recommend to avoid this type of updates as much as possible. -Updates in the 2nd category include changes to any of the value renderers or to the transaction envelope. For example, the ordering of fields in the envelope can be swapped, or the timestamp formatting can be modified. Since SIGN_MODE_TEXTUAL sends `Screen`s to the hardware device, this type of change do not need a hardware wallet application update. They are however state-machine-breaking, and must be documented as such. They require the coordination of SDK developers with client-side developers (e.g. CosmJS), so that the updates are released on both sides close to each other in time. +Updates in the 2nd category include changes to any of the value renderers or to the transaction envelope. For example, the ordering of fields in the envelope can be swapped, or the timestamp formatting can be modified. Since SIGN_MODE_TEXTUAL sends `Screen`s to the hardware device, this type of change does not need a hardware wallet application update. They are however state-machine-breaking, and must be documented as such. They require the coordination of SDK developers with client-side developers (e.g. CosmJS), so that the updates are released on both sides close to each other in time. We define a spec version, which is an integer that must be incremented on each update of either category. This spec version will be exposed by the SDK's implementation, and can be communicated to clients. For example, SDK v0.50 might use the spec version 1, and SDK v0.51 might use 2; thanks to this versioning, clients can know how to craft SIGN_MODE_TEXTUAL transactions based on the target SDK version. diff --git a/docs/build/architecture/adr-053-go-module-refactoring.md b/docs/build/architecture/adr-053-go-module-refactoring.md index d15c39019..a6a87ab21 100644 --- a/docs/build/architecture/adr-053-go-module-refactoring.md +++ b/docs/build/architecture/adr-053-go-module-refactoring.md @@ -23,7 +23,7 @@ increase which technically creates a new go module (with a v2, v3, etc. suffix). [Keeping modules API compatible](https://go.dev/blog/module-compatibility) in -this way requires a fair amount of fair thought and discipline. +this way requires a fair amount of thought and discipline. The Cosmos SDK is a fairly large project which originated before go modules came into existence and has always been under a v0.x release even though @@ -96,7 +96,7 @@ per-project, although most of these will hopefully be indirect ## Further Discussions -Further discussions are occurring in primarily in +Further discussions are occurring primarily in https://github.com/cosmos/cosmos-sdk/discussions/10582 and within the Cosmos SDK Framework Working Group. diff --git a/docs/build/architecture/adr-054-semver-compatible-modules.md b/docs/build/architecture/adr-054-semver-compatible-modules.md index be63e8dbd..2152e1a95 100644 --- a/docs/build/architecture/adr-054-semver-compatible-modules.md +++ b/docs/build/architecture/adr-054-semver-compatible-modules.md @@ -347,7 +347,7 @@ approach described in approach A. Either way, types implementing interfaces woul with an `InterfaceRegistry` as they are now because there would be no way to retrieve them via the global registry. In order to simplify access to other modules using ADR 033, a public API module (maybe even one -[remotely generated by Buf](https://docs.buf.build/bsr/remote-generation/go)) could be used by client modules instead +[remotely generated by Buf](https://buf.build/docs/bsr/generated-sdks/go/)) could be used by client modules instead of requiring to generate all client types internally. The big downsides of this approach are that it requires big changes to how people use protobuf types and would be a @@ -424,6 +424,7 @@ way that requires duplication and differing sets of design principles (protobuf while golang APIs would forbid it). Other downsides to this approach are: + * no clear roadmap to supporting modules in other languages like Rust * doesn't get us any closer to proper object capability security (one of the goals of ADR 033) * ADR 033 needs to be done properly anyway for the set of use cases which do need it @@ -447,6 +448,7 @@ languages, possibly executed within a WASM VM. To declare minor API revisions of proto files, we propose the following guidelines (which were already documented in [cosmos.app.v1alpha module options](../proto/cosmos/app/v1alpha1/module.proto)): + * proto packages which are revised from their initial version (considered revision `0`) should include a `package` * comment in some .proto file containing the test `Revision N` at the start of a comment line where `N` is the current revision number. @@ -469,7 +471,7 @@ to `cosmossdk.io/core/intermodule.Client`: ServiceRevision(ctx context.Context, serviceName string) uint64 ``` -Modules could all this using the service name statically generated by the go grpc code generator: +Modules could call this using the service name statically generated by the go grpc code generator: ```go intermoduleClient.ServiceRevision(ctx, bankv1beta1.Msg_ServiceDesc.ServiceName) @@ -522,6 +524,7 @@ func ProtoImage(protoImage []byte) Option {} ``` This approach allows us to support several ways protobuf files might be generated: + * proto files generated internally to a module (use `ProtoFiles`) * the API module approach with pinned file descriptors (use `ProtoImage`) * gogo proto (use `GzippedProtoFiles`) @@ -641,7 +644,7 @@ type IntegrationTestConfig struct { } // Run runs the test function for all combinations of dependency modules. -func (cfg IntegationTestConfig) Run(t *testing.T, f func (t *testing.T, f IntegrationTestFixture)) { +func (cfg IntegrationTestConfig) Run(t *testing.T, f func (t *testing.T, f IntegrationTestFixture)) { // ... } ``` diff --git a/docs/build/architecture/adr-055-orm.md b/docs/build/architecture/adr-055-orm.md index be7255f09..6d5974e54 100644 --- a/docs/build/architecture/adr-055-orm.md +++ b/docs/build/architecture/adr-055-orm.md @@ -64,6 +64,7 @@ A code generator is included with the ORM which creates type safe wrappers aroun implementation and is the recommended way for modules to use the ORM. The ORM tests provide a simplified bank module demonstration which illustrates: + * [ORM proto options](https://github.com/cosmos/cosmos-sdk/blob/0d846ae2f0424b2eb640f6679a703b52d407813d/orm/internal/testpb/bank.proto) * [Generated Code](https://github.com/cosmos/cosmos-sdk/blob/0d846ae2f0424b2eb640f6679a703b52d407813d/orm/internal/testpb/bank.cosmos_orm.go) * [Example Usage in a Module Keeper](https://github.com/cosmos/cosmos-sdk/blob/0d846ae2f0424b2eb640f6679a703b52d407813d/orm/model/ormdb/module_test.go) diff --git a/docs/build/architecture/adr-057-app-wiring.md b/docs/build/architecture/adr-057-app-wiring.md index 5ccd9c2a0..824403fb0 100644 --- a/docs/build/architecture/adr-057-app-wiring.md +++ b/docs/build/architecture/adr-057-app-wiring.md @@ -38,7 +38,7 @@ In order to improve the current situation, a new "app wiring" paradigm has been involves: * declaration configuration of the modules in an app which can be serialized to JSON or YAML -* a dependency-injection (DI) framework for instantiating apps from the that configuration +* a dependency-injection (DI) framework for instantiating apps from the configuration ### Dependency Injection @@ -250,8 +250,6 @@ defined here are described in [ADR 063: Core Module API](./adr-063-core-module-a ### Registration of Inter-Module Hooks -### Registration of Inter-Module Hooks - Some modules define a hooks interface (ex. `StakingHooks`) which allows one module to call back into another module when certain events happen. @@ -303,15 +301,17 @@ Code generation requires that all providers and invokers and their parameters ar When we start creating semantically versioned SDK modules that are in standalone go modules, a state machine breaking change to a module should be handled as follows: -- the semantic major version should be incremented, and -- a new semantically versioned module config protobuf type should be created. + +* the semantic major version should be incremented, and +* a new semantically versioned module config protobuf type should be created. For instance, if we have the SDK module for bank in the go module `github.com/cosmos/cosmos-sdk/x/bank` with the module config type `cosmos.bank.module.v1.Module`, and we want to make a state machine breaking change to the module, we would: -- create a new go module `github.com/cosmos/cosmos-sdk/x/bank/v2`, -- with the module config protobuf type `cosmos.bank.module.v2.Module`. -This _does not_ mean that we need to increment the protobuf API version for bank. Both modules can support +* create a new go module `github.com/cosmos/cosmos-sdk/x/bank/v2`, +* with the module config protobuf type `cosmos.bank.module.v2.Module`. + +This *does not* mean that we need to increment the protobuf API version for bank. Both modules can support `cosmos.bank.v1`, but `github.com/cosmos/cosmos-sdk/x/bank/v2` will be a separate go module with a separate module config type. This practice will eventually allow us to use appconfig to load new versions of a module via a configuration change. @@ -320,7 +320,7 @@ Effectively, there should be a 1:1 correspondence between a semantically version versioned module config protobuf type, and major versioning bumps should occur whenever state machine breaking changes are made to a module. -NOTE: SDK modules that are standalone go modules _should not_ adopt semantic versioning until the concerns described in +NOTE: SDK modules that are standalone go modules *should not* adopt semantic versioning until the concerns described in [ADR 054: Module Semantic Versioning](./adr-054-semver-compatible-modules.md) are addressed. The short-term solution for this issue was left somewhat unresolved. However, the easiest tactic is likely to use a standalone API go module and follow the guidelines described in this comment: https://github.com/cosmos/cosmos-sdk/pull/11802#issuecomment-1406815181. For the time-being, it is recommended that diff --git a/docs/build/architecture/adr-058-auto-generated-cli.md b/docs/build/architecture/adr-058-auto-generated-cli.md index b295ff4b2..8dc78920a 100644 --- a/docs/build/architecture/adr-058-auto-generated-cli.md +++ b/docs/build/architecture/adr-058-auto-generated-cli.md @@ -81,7 +81,7 @@ We would like to be able to customize: * which fields are positional parameters rather than flags It is an [open discussion](https://github.com/cosmos/cosmos-sdk/pull/11725#issuecomment-1108676129) -as to whether these customizations options should line in: +as to whether these customizations options should lie in: * the .proto files themselves, * separate config files (ex. YAML), or diff --git a/docs/build/architecture/adr-059-test-scopes.md b/docs/build/architecture/adr-059-test-scopes.md index 060344593..6fa387c20 100644 --- a/docs/build/architecture/adr-059-test-scopes.md +++ b/docs/build/architecture/adr-059-test-scopes.md @@ -56,7 +56,7 @@ Tests which exercise a whole module's function with dependencies mocked, are *jo These are almost like integration tests in that they exercise many things together but still use mocks. -Example 1 journey vs illustrative tests - [depinject's BDD style tests](https://github.com/cosmos/cosmos-sdk/blob/main/depinject/features/bindings.feature), show how we can +Example 1 journey vs illustrative tests - [depinject's BDD style tests](https://github.com/cosmos/cosmos-sdk/blob/main/depinject/binding_test.go), show how we can rapidly build up many illustrative cases demonstrating behavioral rules without [very much code](https://github.com/cosmos/cosmos-sdk/blob/main/depinject/binding_test.go) while maintaining high level readability. Example 2 [depinject table driven tests](https://github.com/cosmos/cosmos-sdk/blob/main/depinject/provider_desc_test.go) @@ -148,12 +148,12 @@ to a production environment as is practical. Presently these tests are located a [tests/e2e](https://github.com/cosmos/cosmos-sdk/tree/main/tests/e2e) and rely on [testutil/network](https://github.com/cosmos/cosmos-sdk/tree/main/testutil/network) to start up an in-process Tendermint node. An application should be built as minimally as possible to exercise the desired functionality. -The SDK uses an application will only the required modules for the tests. The application developer is adviced to use its own application for e2e tests. +The SDK uses an application will only the required modules for the tests. The application developer is advised to use its own application for e2e tests. #### Limitations In general the limitations of end to end tests are orchestration and compute cost. -Scaffolding is required to start up and run a prod-like environment and the this +Scaffolding is required to start up and run a prod-like environment and this process takes much longer to start and run than unit or integration tests. Global locks present in Tendermint code cause stateful starting/stopping to sometimes hang @@ -242,7 +242,7 @@ demonstrated in [PR#12706](https://github.com/cosmos/cosmos-sdk/pull/12706). It may be useful if test suites could be run in integration mode (with mocked tendermint) or with e2e fixtures (with real tendermint and many nodes). Integration fixtures could be used -for quicker runs, e2e fixures could be used for more battle hardening. +for quicker runs, e2e fixtures could be used for more battle hardening. A PoC `x/gov` was completed in PR [#12847](https://github.com/cosmos/cosmos-sdk/pull/12847) is in progress for unit tests demonstrating BDD [Rejected]. diff --git a/docs/build/architecture/adr-060-abci-1.0.md b/docs/build/architecture/adr-060-abci-1.0.md index 3f29be784..41e2230bc 100644 --- a/docs/build/architecture/adr-060-abci-1.0.md +++ b/docs/build/architecture/adr-060-abci-1.0.md @@ -84,7 +84,7 @@ type Mempool interface { // Select returns an Iterator over the app-side mempool. If txs are specified, // then they shall be incorporated into the Iterator. The Iterator must - // closed by the caller. + // be closed by the caller. Select(sdk.Context, [][]byte) Iterator // CountTx returns the number of transactions currently in the mempool. @@ -169,7 +169,7 @@ Instead, we will define an additional ABCI interface method on the existing or `EndBlock`. This new interface method will be defined as follows: ```go -ProcessProposal(sdk.Context, abci.RequestProcessProposal) error {} +ProcessProposal(sdk.Context, abci.ProcessProposalRequest) error {} ``` Note, we must call `ProcessProposal` with a new internal branched state on the diff --git a/docs/build/architecture/adr-061-liquid-staking.md b/docs/build/architecture/adr-061-liquid-staking.md index fcfeda0d3..a1be7e768 100644 --- a/docs/build/architecture/adr-061-liquid-staking.md +++ b/docs/build/architecture/adr-061-liquid-staking.md @@ -1,4 +1,4 @@ -# ADR ADR-061: Liquid Staking +# ADR-061: Liquid Staking ## Changelog @@ -20,7 +20,7 @@ As both Proof of Stake and blockchain use cases have matured, this design has ag The most important deficiency of the legacy staking design is that it composes poorly with on chain protocols for trading, lending, derivatives that are referred to collectively as DeFi. The legacy staking implementation starves these applications of liquidity by increasing the risk free rate adaptively. It basically makes DeFi and staking security somewhat incompatible. -The Osmosis team has adopted the idea of Superfluid and Interfluid staking where assets that are participating in DeFi appliactions can also be used in proof of stake. This requires tight integration with an enshrined set of DeFi applications and thus is unsuitable for the Cosmos SDK. +The Osmosis team has adopted the idea of Superfluid and Interfluid staking where assets that are participating in DeFi applications can also be used in proof of stake. This requires tight integration with an enshrined set of DeFi applications and thus is unsuitable for the Cosmos SDK. It's also important to note that Interchain Accounts are available in the default IBC implementation and can be used to [rehypothecate](https://www.investopedia.com/terms/h/hypothecation.asp#toc-what-is-rehypothecation) delegations. Thus liquid staking is already possible and these changes merely improve the UX of liquid staking. Centralized exchanges also rehypothecate staked assets, posing challenges for decentralization. This ADR takes the position that adoption of in-protocol liquid staking is the preferable outcome and provides new levers to incentivize decentralization of stake. diff --git a/docs/build/architecture/adr-062-collections-state-layer.md b/docs/build/architecture/adr-062-collections-state-layer.md index 8ebaddda7..db71cef0d 100644 --- a/docs/build/architecture/adr-062-collections-state-layer.md +++ b/docs/build/architecture/adr-062-collections-state-layer.md @@ -1,4 +1,4 @@ -# ADR 062: Collections, a simplified storage layer for cosmos-sdk modules. +# ADR 062: Collections, a simplified storage layer for cosmos-sdk modules ## Changelog @@ -11,37 +11,39 @@ PROPOSED - Implemented ## Abstract We propose a simplified module storage layer which leverages golang generics to allow module developers to handle module -storage in a simple and straightforward manner, whilst offering safety, extensibility and standardisation. +storage in a simple and straightforward manner, whilst offering safety, extensibility and standardization. ## Context Module developers are forced into manually implementing storage functionalities in their modules, those functionalities include but are not limited to: -- Defining key to bytes formats. -- Defining value to bytes formats. -- Defining secondary indexes. -- Defining query methods to expose outside to deal with storage. -- Defining local methods to deal with storage writing. -- Dealing with genesis imports and exports. -- Writing tests for all the above. +* Defining key to bytes formats. +* Defining value to bytes formats. +* Defining secondary indexes. +* Defining query methods to expose outside to deal with storage. +* Defining local methods to deal with storage writing. +* Dealing with genesis imports and exports. +* Writing tests for all the above. This brings in a lot of problems: -- It blocks developers from focusing on the most important part: writing business logic. -- Key to bytes formats are complex and their definition is error-prone, for example: - - how do I format time to bytes in such a way that bytes are sorted? - - how do I ensure when I don't have namespace collisions when dealing with secondary indexes? -- The lack of standardisation makes life hard for clients, and the problem is exacerbated when it comes to providing proofs for objects present in state. Clients are forced to maintain a list of object paths to gather proofs. + +* It blocks developers from focusing on the most important part: writing business logic. +* Key to bytes formats are complex and their definition is error-prone, for example: + * how do I format time to bytes in such a way that bytes are sorted? + * how do I ensure when I don't have namespace collisions when dealing with secondary indexes? +* The lack of standardization makes life hard for clients, and the problem is exacerbated when it comes to providing proofs for objects present in state. Clients are forced to maintain a list of object paths to gather proofs. ### Current Solution: ORM The current SDK proposed solution to this problem is [ORM](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-055-orm.md). Whilst ORM offers a lot of good functionality aimed at solving these specific problems, it has some downsides: -- It requires migrations. -- It uses the newest protobuf golang API, whilst the SDK still mainly uses gogoproto. -- Integrating ORM into a module would require the developer to deal with two different golang frameworks (golang protobuf + gogoproto) representing the same API objects. -- It has a high learning curve, even for simple storage layers as it requires developers to have knowledge around protobuf options, custom cosmos-sdk storage extensions, and tooling download. Then after this they still need to learn the code-generated API. + +* It requires migrations. +* It uses the newest protobuf golang API, whilst the SDK still mainly uses gogoproto. +* Integrating ORM into a module would require the developer to deal with two different golang frameworks (golang protobuf + gogoproto) representing the same API objects. +* It has a high learning curve, even for simple storage layers as it requires developers to have knowledge around protobuf options, custom cosmos-sdk storage extensions, and tooling download. Then after this they still need to learn the code-generated API. ### CosmWasm Solution: cw-storage-plus @@ -56,30 +58,31 @@ We propose to port the `collections` API, whose implementation lives in [NibiruC Collections implements four different storage handlers types: -- `Map`: which deals with simple `key=>object` mappings. -- `KeySet`: which acts as a `Set` and only retains keys and no object (usecase: allow-lists). -- `Item`: which always contains only one object (usecase: Params) -- `Sequence`: which implements a simple always increasing number (usecase: Nonces) -- `IndexedMap`: builds on top of `Map` and `KeySet` and allows to create relationships with `Objects` and `Objects` secondary keys. +* `Map`: which deals with simple `key=>object` mappings. +* `KeySet`: which acts as a `Set` and only retains keys and no object (usecase: allow-lists). +* `Item`: which always contains only one object (usecase: Params) +* `Sequence`: which implements a simple always increasing number (usecase: Nonces) +* `IndexedMap`: builds on top of `Map` and `KeySet` and allows to create relationships with `Objects` and `Objects` secondary keys. All the collection APIs build on top of the simple `Map` type. Collections is fully generic, meaning that anything can be used as `Key` and `Value`. It can be a protobuf object or not. -Collections types, in fact, delegate the duty of serialisation of keys and values to a secondary collections API component called `ValueEncoders` and `KeyEncoders`. +Collections types, in fact, delegate the duty of serialization of keys and values to a secondary collections API component called `ValueEncoders` and `KeyEncoders`. `ValueEncoders` take care of converting a value to bytes (relevant only for `Map`). And offers a plug and play layer which allows us to change how we encode objects, -which is relevant for swapping serialisation frameworks and enhancing performance. +which is relevant for swapping serialization frameworks and enhancing performance. `Collections` already comes in with default `ValueEncoders`, specifically for: protobuf objects, special SDK types (sdk.Int, sdk.Dec). -`KeyEncoders` take care of converting keys to bytes, `collections` already comes in with some default `KeyEncoders` for some privimite golang types +`KeyEncoders` take care of converting keys to bytes, `collections` already comes in with some default `KeyEncoders` for some primitive golang types (uint64, string, time.Time, ...) and some widely used sdk types (sdk.Acc/Val/ConsAddress, sdk.Int/Dec, ...). These default implementations also offer safety around proper lexicographic ordering and namespace-collision. Examples of the collections API can be found here: -- introduction: https://github.com/NibiruChain/collections/tree/main/examples -- usage in nibiru: [x/oracle](https://github.com/NibiruChain/nibiru/blob/master/x/oracle/keeper/keeper.go#L32), [x/perp](https://github.com/NibiruChain/nibiru/blob/master/x/perp/keeper/keeper.go#L31) -- cosmos-sdk's x/staking migrated: https://github.com/testinginprod/cosmos-sdk/pull/22 + +* introduction: https://github.com/NibiruChain/collections/tree/main/examples +* usage in nibiru: [x/oracle](https://github.com/NibiruChain/nibiru/blob/master/x/oracle/keeper/keeper.go#L32), [x/perp](https://github.com/NibiruChain/nibiru/blob/master/x/perp/keeper/keeper.go#L31) +* cosmos-sdk's x/staking migrated: https://github.com/testinginprod/cosmos-sdk/pull/22 ## Consequences @@ -92,17 +95,17 @@ the upgrade to the new storage layer non-state breaking. ### Positive -- ADR aimed at removing code from the SDK rather than adding it. Migrating just `x/staking` to collections would yield to a net decrease in LOC (even considering the addition of collections itself). -- Simplifies and standardises storage layers across modules in the SDK. -- Does not require to have to deal with protobuf. -- It's pure golang code. -- Generalisation over `KeyEncoders` and `ValueEncoders` allows us to not tie ourself to the data serialisation framework. -- `KeyEncoders` and `ValueEncoders` can be extended to provide schema reflection. +* ADR aimed at removing code from the SDK rather than adding it. Migrating just `x/staking` to collections would yield to a net decrease in LOC (even considering the addition of collections itself). +* Simplifies and standardizes storage layers across modules in the SDK. +* Does not require to have to deal with protobuf. +* It's pure golang code. +* Generalization over `KeyEncoders` and `ValueEncoders` allows us to not tie ourself to the data serialization framework. +* `KeyEncoders` and `ValueEncoders` can be extended to provide schema reflection. ### Negative -- Golang generics are not as battle-tested as other Golang features, despite being used in production right now. -- Collection types instantiation needs to be improved. +* Golang generics are not as battle-tested as other Golang features, despite being used in production right now. +* Collection types instantiation needs to be improved. ### Neutral @@ -110,8 +113,8 @@ the upgrade to the new storage layer non-state breaking. ## Further Discussions -- Automatic genesis import/export (not implemented because of API breakage) -- Schema reflection +* Automatic genesis import/export (not implemented because of API breakage) +* Schema reflection ## References diff --git a/docs/build/architecture/adr-063-core-module-api.md b/docs/build/architecture/adr-063-core-module-api.md index 743dd5fee..cb5bb02b3 100644 --- a/docs/build/architecture/adr-063-core-module-api.md +++ b/docs/build/architecture/adr-063-core-module-api.md @@ -199,7 +199,7 @@ func NewKeeper(logger log.Logger) Keeper { Modules will provide their core services to the runtime module via extension interfaces built on top of the `cosmossdk.io/core/appmodule.AppModule` tag interface. This tag interface requires only two empty methods which -allow `depinject` to identify implementors as `depinject.OnePerModule` types and as app module implementations: +allow `depinject` to identify implementers as `depinject.OnePerModule` types and as app module implementations: ```go type AppModule interface { @@ -226,7 +226,7 @@ type HasServices interface { ``` -Because of the `cosmos.msg.v1.service` protobuf option, required for `Msg` services, the same `ServiceRegitrar` can be +Because of the `cosmos.msg.v1.service` protobuf option, required for `Msg` services, the same `ServiceRegistrar` can be used to register both `Msg` and query services. #### Genesis @@ -282,7 +282,7 @@ type HasGenesis interface { #### Pre Blockers -Modules that have functionality that runs before BeginBlock and should implement the has `HasPreBlocker` interfaces: +Modules that have functionality that runs before BeginBlock and should implement the `HasPreBlocker` interfaces: ```go type HasPreBlocker interface { @@ -388,7 +388,7 @@ Additional `AppModule` extension interfaces either inside or outside of core wil these concerns. In the case of gogo proto and amino interfaces, the registration of these generally should happen as early -as possible during initialization and in [ADR 057: App Wiring](./adr-057-app-wiring-1.md), protobuf type registration +as possible during initialization and in [ADR 057: App Wiring](./adr-057-app-wiring.md), protobuf type registration happens before dependency injection (although this could alternatively be done dedicated DI providers). gRPC gateway registration should probably be handled by the runtime module, but the core API shouldn't depend on gRPC @@ -408,7 +408,7 @@ which modules can return in a provider: ```go func ProvideGrpcGateway() GrpcGatewayInfo { - return GrpcGatewayinfo { + return GrpcGatewayInfo { Handlers: []Handler {types.RegisterQueryHandlerClient} } } @@ -463,10 +463,11 @@ module manager and follow the Cosmos SDK's existing [0-based versioning](https:/ versioning as well as runtime modularity, new officially supported runtime modules will be created under the `cosmossdk.io/runtime` prefix. For each supported consensus engine a semantically-versioned go module should be created with a runtime implementation for that consensus engine. For example: -- `cosmossdk.io/runtime/comet` -- `cosmossdk.io/runtime/comet/v2` -- `cosmossdk.io/runtime/rollkit` -- etc. + +* `cosmossdk.io/runtime/comet` +* `cosmossdk.io/runtime/comet/v2` +* `cosmossdk.io/runtime/rollkit` +* etc. These runtime modules should attempt to be semantically versioned even if the underlying consensus engine is not. Also, because a runtime module is also a first class Cosmos SDK module, it should have a protobuf module config type. @@ -495,7 +496,7 @@ a dependency on `github.com/cosmos/cosmos-sdk` would no longer be required. In short, modules would depend primarily on `cosmossdk.io/core`, and each `cosmossdk.io/runtime/{consensus-engine}` would implement the `cosmossdk.io/core` functionality for that consensus engine. -On additional piece that would need to be resolved as part of this architecture is how runtimes relate to the server. +One additional piece that would need to be resolved as part of this architecture is how runtimes relate to the server. Likely it would make sense to modularize the current server architecture so that it can be used with any runtime even if that is based on a consensus engine besides Comet. This means that eventually the Comet runtime would need to encapsulate the logic for starting Comet and the ABCI app. @@ -557,7 +558,7 @@ as by providing service implementations by wrapping `sdk.Context`. ## References * [ADR 033: Protobuf-based Inter-Module Communication](./adr-033-protobuf-inter-module-comm.md) -* [ADR 057: App Wiring](./adr-057-app-wiring-1.md) +* [ADR 057: App Wiring](./adr-057-app-wiring.md) * [ADR 055: ORM](./adr-055-orm.md) * [ADR 028: Public Key Addresses](./adr-028-public-key-addresses.md) * [Keeping Your Modules Compatible](https://go.dev/blog/module-compatibility) diff --git a/docs/build/architecture/adr-064-abci-2.0.md b/docs/build/architecture/adr-064-abci-2.0.md index c0dc7f746..476896276 100644 --- a/docs/build/architecture/adr-064-abci-2.0.md +++ b/docs/build/architecture/adr-064-abci-2.0.md @@ -25,7 +25,7 @@ includes `ExtendVote`, `VerifyVoteExtension` and `FinalizeBlock`. ABCI 2.0 continues the promised updates from ABCI++, specifically three additional ABCI methods that the application can implement in order to gain further control, insight and customization of the consensus process, unlocking many novel use-cases -that previously not possible. We describe these three new methods below: +that were previously not possible. We describe these three new methods below: ### `ExtendVote` @@ -103,8 +103,8 @@ vote extensions. We propose the following new handlers for applications to implement: ```go -type ExtendVoteHandler func(sdk.Context, abci.RequestExtendVote) abci.ResponseExtendVote -type VerifyVoteExtensionHandler func(sdk.Context, abci.RequestVerifyVoteExtension) abci.ResponseVerifyVoteExtension +type ExtendVoteHandler func(sdk.Context, abci.ExtendVoteRequest) abci.ExtendVoteResponse +type VerifyVoteExtensionHandler func(sdk.Context, abci.VerifyVoteExtensionRequest) abci.VerifyVoteExtensionResponse ``` An ephemeral context and state will be supplied to both handlers. The @@ -120,7 +120,7 @@ Recall, an implementation of `ExtendVoteHandler` does NOT need to be determinist however, given a set of vote extensions, `VerifyVoteExtensionHandler` must be deterministic, otherwise the chain may suffer from liveness faults. In addition, recall CometBFT proceeds in rounds for each height, so if a decision cannot be -made about about a block proposal at a given height, CometBFT will proceed to the +made about a block proposal at a given height, CometBFT will proceed to the next round and thus will execute `ExtendVote` and `VerifyVoteExtension` again for the new round for each validator until 2/3 valid pre-commits can be obtained. @@ -144,7 +144,7 @@ type VoteExtensionHandler struct { // ExtendVoteHandler can do something with h.mk and possibly h.state to create // a vote extension, such as fetching a series of prices for supported assets. -func (h VoteExtensionHandler) ExtendVoteHandler(ctx sdk.Context, req abci.RequestExtendVote) abci.ResponseExtendVote { +func (h VoteExtensionHandler) ExtendVoteHandler(ctx sdk.Context, req abci.ExtendVoteRequest) abci.ExtendVoteResponse { prices := GetPrices(ctx, h.mk.Assets()) bz, err := EncodePrices(h.cdc, prices) if err != nil { @@ -156,22 +156,22 @@ func (h VoteExtensionHandler) ExtendVoteHandler(ctx sdk.Context, req abci.Reques // NOTE: Vote extensions can be overridden since we can timeout in a round. SetPrices(h.state, req, bz) - return abci.ResponseExtendVote{VoteExtension: bz} + return abci.ExtendVoteResponse{VoteExtension: bz} } // VerifyVoteExtensionHandler can do something with h.state and req to verify // the req.VoteExtension field, such as ensuring the provided oracle prices are // within some valid range of our prices. -func (h VoteExtensionHandler) VerifyVoteExtensionHandler(ctx sdk.Context, req abci.RequestVerifyVoteExtension) abci.ResponseVerifyVoteExtension { +func (h VoteExtensionHandler) VerifyVoteExtensionHandler(ctx sdk.Context, req abci.VerifyVoteExtensionRequest) abci.VerifyVoteExtensionResponse { prices, err := DecodePrices(h.cdc, req.VoteExtension) if err != nil { log("failed to decode vote extension", "err", err) - return abci.ResponseVerifyVoteExtension{Status: REJECT} + return abci.VerifyVoteExtensionResponse{Status: REJECT} } if err := ValidatePrices(h.state, req, prices); err != nil { log("failed to validate vote extension", "prices", prices, "err", err) - return abci.ResponseVerifyVoteExtension{Status: REJECT} + return abci.VerifyVoteExtensionResponse{Status: REJECT} } // store updated vote extensions at the given height @@ -179,7 +179,7 @@ func (h VoteExtensionHandler) VerifyVoteExtensionHandler(ctx sdk.Context, req ab // NOTE: Vote extensions can be overridden since we can timeout in a round. SetPrices(h.state, req, req.VoteExtension) - return abci.ResponseVerifyVoteExtension{Status: ACCEPT} + return abci.VerifyVoteExtensionResponse{Status: ACCEPT} } ``` @@ -301,7 +301,7 @@ during `ProcessProposal` because during replay, CometBFT will NOT call `ProcessP which would result in an incomplete state view. ```go -func (a MyApp) PreBlocker(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { +func (a MyApp) PreBlocker(ctx sdk.Context, req *abci.FinalizeBlockRequest) error { voteExts := GetVoteExtensions(ctx, req.Txs) // Process and perform some compute on vote extensions, storing any resulting @@ -350,7 +350,7 @@ legacy ABCI types, e.g. `LegacyBeginBlockRequest` and `LegacyEndBlockRequest`. O we can come up with new types and names altogether. ```go -func (app *BaseApp) FinalizeBlock(req abci.RequestFinalizeBlock) (*abci.ResponseFinalizeBlock, error) { +func (app *BaseApp) FinalizeBlock(req abci.FinalizeBlockRequest) (*abci.FinalizeBlockResponse, error) { ctx := ... if app.preBlocker != nil { @@ -375,7 +375,7 @@ func (app *BaseApp) FinalizeBlock(req abci.RequestFinalizeBlock) (*abci.Response endBlockResp, err := app.endBlock(app.finalizeBlockState.ctx) appendBlockEventAttr(beginBlockResp.Events, "end_block") - return abci.ResponseFinalizeBlock{ + return abci.FinalizeBlockResponse{ TxResults: txExecResults, Events: joinEvents(beginBlockResp.Events, endBlockResp.Events), ValidatorUpdates: endBlockResp.ValidatorUpdates, @@ -396,7 +396,7 @@ and rely on existing events, especially since applications will still define In order to facilitate existing event functionality, we propose that all `BeginBlock` and `EndBlock` events have a dedicated `EventAttribute` with `key=block` and `value=begin_block|end_block`. The `EventAttribute` will be appended to each event -in both `BeginBlock` and `EndBlock` events`. +in both `BeginBlock` and `EndBlock` events. ### Upgrading diff --git a/docs/build/architecture/adr-065-store-v2.md b/docs/build/architecture/adr-065-store-v2.md index 8faed0463..babf0eb70 100644 --- a/docs/build/architecture/adr-065-store-v2.md +++ b/docs/build/architecture/adr-065-store-v2.md @@ -21,7 +21,7 @@ shortcomings and flaws have been exposed in the state and storage primitives of the Cosmos SDK. In order to keep up with the evolving demands and needs of both clients and developers, -a major overhaul to these primitives are necessary. +a major overhaul to these primitives is necessary. ## Context @@ -35,7 +35,7 @@ application state. This data structure is the base layer `KVStore`. In addition, the SDK provides abstractions on top of this Merkle data structure. Namely, a root multi-store (RMS) is a collection of each module's `KVStore`. Through the RMS, the application can serve queries and provide proofs to clients -in addition to provide a module access to its own unique `KVStore` though the use +in addition to providing a module access to its own unique `KVStore` through the use of `StoreKey`, which is an OCAP primitive. There are further layers of abstraction that sit between the RMS and the underlying @@ -65,11 +65,11 @@ See the [Storage Discussion](https://github.com/cosmos/cosmos-sdk/discussions/13 ## Alternatives There was a previous attempt to refactor the storage layer described in [ADR-040](./adr-040-storage-and-smt-state-commitments.md). -However, this approach mainly stems on the short comings of IAVL and various performance +However, this approach mainly stems from the shortcomings of IAVL and various performance issues around it. While there was a (partial) implementation of [ADR-040](./adr-040-storage-and-smt-state-commitments.md), it was never adopted for a variety of reasons, such as the reliance on using an SMT, which was more in a research phase, and some design choices that couldn't -be fully agreed upon, such as the snap-shotting mechanism that would result in +be fully agreed upon, such as the snapshotting mechanism that would result in massive state bloat. ## Decision @@ -192,7 +192,7 @@ Since the SS layer is naturally a storage layer only, without any commitments to (key, value) pairs, it cannot provide Merkle proofs to clients during queries. Since the pruning strategy against the SC layer is configured by the operator, -we can therefore have the RMS route the query SC layer if the version exists and +we can therefore have the RMS route the query to the SC layer if the version exists and `prove: true`. Otherwise, the query will fall back to the SS layer without a proof. We could explore the idea of using state snapshots to rebuild an in-memory IAVL diff --git a/docs/build/architecture/adr-068-preblock.md b/docs/build/architecture/adr-068-preblock.md index 86692c412..6b50cf0cc 100644 --- a/docs/build/architecture/adr-068-preblock.md +++ b/docs/build/architecture/adr-068-preblock.md @@ -10,12 +10,12 @@ DRAFT ## Abstract -Introduce `PreBlock`, which runs before begin blocker other modules, and allows to modify consensus parameters, and the changes are visible to the following state machine logics. +Introduce `PreBlock`, which runs before the begin blocker of other modules, and allows modifying consensus parameters, and the changes are visible to the following state machine logics. ## Context When upgrading to sdk 0.47, the storage format for consensus parameters changed, but in the migration block, `ctx.ConsensusParams()` is always `nil`, because it fails to load the old format using new code, it's supposed to be migrated by the `x/upgrade` module first, but unfortunately, the migration happens in `BeginBlocker` handler, which runs after the `ctx` is initialized. -When we try to solve this, we find the `x/upgrade` module can't modify the context to make the consensus parameters visible for the other modules, the context is passed by value, and sdk team want to keep it that way, that's good for isolations between modules. +When we try to solve this, we find the `x/upgrade` module can't modify the context to make the consensus parameters visible for the other modules, the context is passed by value, and sdk team want to keep it that way, that's good for isolation between modules. ## Alternatives @@ -29,10 +29,11 @@ Suggested this new lifecycle method. There are two semantics around the new lifecycle method: -- It runs before the `BeginBlocker` of all modules -- It can modify consensus parameters in storage, and signal the caller through the return value. +* It runs before the `BeginBlocker` of all modules +* It can modify consensus parameters in storage, and signal the caller through the return value. + +When it returns `ConsensusParamsChanged=true`, the caller must refresh the consensus parameters in the finalize context: -When it returns `ConsensusParamsChanged=true`, the caller must refresh the consensus parameter in the finalize context: ``` app.finalizeBlockState.ctx = app.finalizeBlockState.ctx.WithConsensusParams(app.GetConsensusParams()) ``` @@ -55,6 +56,7 @@ The new ctx must be passed to all the other lifecycle methods. ## Test Cases ## References + * [1] https://github.com/cosmos/cosmos-sdk/issues/16494 * [2] https://github.com/cosmos/cosmos-sdk/pull/16583 * [3] https://github.com/cosmos/cosmos-sdk/pull/17421 diff --git a/docs/build/architecture/adr-070-unordered-account.md b/docs/build/architecture/adr-070-unordered-account.md index d4c228d69..767d40d5c 100644 --- a/docs/build/architecture/adr-070-unordered-account.md +++ b/docs/build/architecture/adr-070-unordered-account.md @@ -2,10 +2,10 @@ ## Changelog -- Dec 4, 2023: Initial Draft (@yihuang, @tac0turtle, @alexanderbez) -- Jan 30, 2024: Include section on deterministic transaction encoding -- Mar 18, 2025: Revise implementation to use Cosmos SDK KV Store and require unique timeouts per-address (@technicallyty) -- Apr 25, 2025: Add note about rejecting unordered txs with sequence values. +* Dec 4, 2023: Initial Draft (@yihuang, @tac0turtle, @alexanderbez) +* Jan 30, 2024: Include section on deterministic transaction encoding +* Mar 18, 2025: Revise implementation to use Cosmos SDK KV Store and require unique timeouts per-address (@technicallyty) +* Apr 25, 2025: Add note about rejecting unordered txs with sequence values. ## Status @@ -19,7 +19,7 @@ the use of a time-based, ephemeral sequence. ## Context -Account sequence values serve to prevent replay attacks and ensure transactions from the same sender are included into blocks and executed +Account sequence values serve to prevent replay attacks and ensure transactions from the same sender are included in blocks and executed in sequential order. Unfortunately, this makes it difficult to reliably send many concurrent transactions from the same sender. Victims of such limitations include IBC relayers and crypto exchanges. @@ -39,8 +39,8 @@ will be recorded to state. New transactions will be checked against the state to prevent duplicate submissions. To prevent the state from growing indefinitely, we propose the following: -- Define an upper bound for the value of `timeout_timestamp` (i.e. 10 minutes). -- Add PreBlocker method x/auth that removes state entries with a `timeout_timestamp` earlier than the current block time. +* Define an upper bound for the value of `timeout_timestamp` (i.e. 10 minutes). +* Add PreBlocker method to x/auth that removes state entries with a `timeout_timestamp` earlier than the current block time. ### Transaction Format @@ -49,7 +49,7 @@ message TxBody { ... bool unordered = 4; - google.protobuf.Timestamp timeout_timestamp = 5 + google.protobuf.Timestamp timeout_timestamp = 5; } ``` @@ -300,7 +300,7 @@ The storage of unordered sequences will be facilitated using the Cosmos SDK's KV The previous iteration of unordered transactions worked by using an ad-hoc state-management system that posed severe risks and a vector for duplicated tx processing. It relied on graceful app closure which would flush the current state -of the unordered sequence mapping. If the 2/3's of the network crashed, and the graceful closure did not trigger, +of the unordered sequence mapping. If 2/3 of the network crashed, and the graceful closure did not trigger, the system would lose track of all sequences in the mapping, allowing those transactions to be replayed. The implementation proposed in the updated version of this ADR solves this by writing directly to the Cosmos KV Store. While this is less performant, for the initial implementation, we opted to choose a safer path and postpone performance optimizations until we have more data on real-world impacts and a more battle-tested approach to optimization. @@ -319,7 +319,7 @@ single-use unordered nonces, instead of deriving nonces from bytes in the transa * Requires additional storage overhead. * Requirement of unique timestamps per transaction causes a small amount of additional overhead for clients. Clients must ensure each transaction's timeout timestamp is different. However, nanosecond differentials suffice. -* Usage of Cosmos SDK KV store is slower in comparison to using a non-merklized store or ad-hoc methods, and block times may slow down as a result. +* Usage of Cosmos SDK KV store is slower in comparison to using a non-merkleized store or ad-hoc methods, and block times may slow down as a result. ## References diff --git a/docs/build/architecture/adr-076-tx-malleability.md b/docs/build/architecture/adr-076-tx-malleability.md index 49625d9d0..9843b17fa 100644 --- a/docs/build/architecture/adr-076-tx-malleability.md +++ b/docs/build/architecture/adr-076-tx-malleability.md @@ -25,6 +25,7 @@ This document attempts to enumerate the various potential transaction "malleabil ### Risks Associated with Malleability The malleability of transactions poses the following potential risks to end users: + * unsigned data could get added to transactions and be processed by state machines * clients often rely on transaction hashes for checking transaction status, but whether or not submitted transaction hashes match processed transaction hashes depends primarily on good network actors rather than fundamental protocol guarantees * transactions could potentially get executed more than once (faulty replay protection) @@ -49,13 +50,15 @@ increasing account sequence number. #### Non-deterministic Protobuf Encoding Cosmos SDK transactions are encoded using protobuf binary encoding when they are submitted to the network. Protobuf binary is not inherently a deterministic encoding meaning that the same logical payload could have several valid bytes representations. In a basic sense, this means that protobuf in general can be decoded and re-encoded to produce a different byte stream (and thus different hash) without changing the logical meaning of the bytes. [ADR 027: Deterministic Protobuf Serialization](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-027-deterministic-protobuf-serialization.md) describes in detail what needs to be done to produce what we consider to be a "canonical", deterministic protobuf serialization. Briefly, the following sources of malleability at the encoding level have been identified and are addressed by this specification: + * fields can be emitted in any order * default field values can be included or omitted, and this doesn't change meaning unless `optional` is used * `repeated` fields of scalars may use packed or "regular" encoding * `varint`s can include extra ignored bits -* extra fields may be added and are usually simply ignored by decoders. [ADR 020](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-020-protobuf-transaction-encoding.md#unknown-field-filtering) specifies that in general such extra fields should cause messages and transactions to be rejected) +* extra fields may be added and are usually simply ignored by decoders. [ADR 020](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-020-protobuf-transaction-encoding.md#unknown-field-filtering) specifies that in general such extra fields should cause messages and transactions to be rejected When using `SIGN_MODE_DIRECT` none of the above malleabilities will be tolerated because: + * signatures of messages and extensions must be done over the raw encoded bytes of those fields * the outer tx envelope (`TxRaw`) must follow ADR 027 rules or be rejected @@ -69,7 +72,7 @@ In addition to being aware of the general non-determinism of protobuf binary, de In addition to the non-determinism present in protobuf binary itself, some protobuf field data is encoded using a micro-format which itself may not be deterministic. Consider for instance integer or decimal encoding. Some decoders may allow for the presence of leading or trailing zeros without changing the logical meaning, ex. `00100` vs `100` or `100.00` vs `100`. So if a sign mode encodes numbers deterministically, but decoders accept multiple representations, a user may sign over the value `100` while `0100` gets encoded. This would be possible with Amino JSON to the extent that the integer decoder accepts leading zeros. I believe the current `Int` implementation will reject this, however, it is -probably possible to encode a octal or hexadecimal representation in the transaction whereas the user signs over a decimal integer. +probably possible to encode an octal or hexadecimal representation in the transaction whereas the user signs over a decimal integer. #### Signature Encoding @@ -85,8 +88,8 @@ representation. #### Fields not covered by Amino JSON -Another area that needs to be addressed carefully is the discrepancy between `AminoSignDoc`(see [`aminojson.proto`](../../x/tx/signing/aminojson/internal/aminojsonpb/aminojson.proto)) used for `SIGN_MODE_LEGACY_AMINO_JSON` and the actual contents of `TxBody` and `AuthInfo` (see [`tx.proto`](../../proto/cosmos/tx/v1beta1/tx.proto)). -If fields get added to `TxBody` or `AuthInfo`, they must either have a corresponding representing in `AminoSignDoc` or Amino JSON signatures must be rejected when those new fields are set. Making sure that this is done is a +Another area that needs to be addressed carefully is the discrepancy between `AminoSignDoc` (see [`aminojson.proto`](../../x/tx/signing/aminojson/internal/aminojsonpb/aminojson.proto)) used for `SIGN_MODE_LEGACY_AMINO_JSON` and the actual contents of `TxBody` and `AuthInfo` (see [`tx.proto`](../../proto/cosmos/tx/v1beta1/tx.proto)). +If fields get added to `TxBody` or `AuthInfo`, they must either have a corresponding representation in `AminoSignDoc` or Amino JSON signatures must be rejected when those new fields are set. Making sure that this is done is a highly manual process, and developers could easily make the mistake of updating `TxBody` or `AuthInfo` without paying any attention to the implementation of `GetSignBytes` for Amino JSON. This is a critical vulnerability in which unsigned content can now get into the transaction and signature verification will @@ -114,6 +117,7 @@ For the known malleability of the `Multisignature` type, we should make sure tha were encoded following canonical ADR 027 rules when doing signature verification. `SIGN_MODE_DIRECT_AUX` provides the same level of safety as `SIGN_MODE_DIRECT` because + * the raw encoded `TxBody` bytes are signed over in `SignDocDirectAux`, and * a transaction using `SIGN_MODE_DIRECT_AUX` still requires the primary signer to sign the transaction with `SIGN_MODE_DIRECT` @@ -123,8 +127,9 @@ were encoded following canonical ADR 027 rules when doing signature verification Unfortunately, the vast majority of unaddressed malleability risks affect `SIGN_MODE_LEGACY_AMINO_JSON` and this sign mode is still commonly used. It is recommended that the following improvements be made to Amino JSON signing: -* hashes of `TxBody` and `AuthInfo` should be added to `AminoSignDoc` so that encoding-level malleablity is addressed -* when constructing `AminoSignDoc`, [protoreflect](https://pkg.go.dev/google.golang.org/protobuf/reflect/protoreflect) API should be used to ensure that there no fields in `TxBody` or `AuthInfo` which do not have a mapping in `AminoSignDoc` have been set + +* hashes of `TxBody` and `AuthInfo` should be added to `AminoSignDoc` so that encoding-level malleability is addressed +* when constructing `AminoSignDoc`, [protoreflect](https://pkg.go.dev/google.golang.org/protobuf/reflect/protoreflect) API should be used to ensure that there are no fields in `TxBody` or `AuthInfo` which do not have a mapping in `AminoSignDoc` have been set * fields present in `TxBody` or `AuthInfo` that are not present in `AminoSignDoc` (such as extension options) should be added to `AminoSignDoc` if possible @@ -133,12 +138,13 @@ be added to `AminoSignDoc` if possible To test that transactions are resistant to malleability, we can develop a test suite to run against all sign modes that attempts to manipulate transaction bytes in the following ways: -- changing protobuf encoding by - - reordering fields - - setting default values - - adding extra bits to varints, or - - setting new unknown fields -- modifying integer and decimal values encoded as strings with leading or trailing zeros + +* changing protobuf encoding by + * reordering fields + * setting default values + * adding extra bits to varints, or + * setting new unknown fields +* modifying integer and decimal values encoded as strings with leading or trailing zeros Whenever any of these manipulations is done, we should observe that the sign doc bytes for the sign mode being tested also change, meaning that the corresponding signatures will also have to change. @@ -147,8 +153,9 @@ In the case of Amino JSON, we should also develop tests which ensure that if any field not supported by Amino's `AminoSignDoc` is set that signing fails. In the general case of transaction decoding, we should have unit tests to ensure that -- any `TxRaw` bytes which do not follow ADR 027 canonical encoding cause decoding to fail, and -- any top-level transaction elements including `TxBody`, `AuthInfo`, public keys, and messages which + +* any `TxRaw` bytes which do not follow ADR 027 canonical encoding cause decoding to fail, and +* any top-level transaction elements including `TxBody`, `AuthInfo`, public keys, and messages which have unknown fields set cause the transaction to be rejected (this ensures that ADR 020 unknown field filtering is properly applied) diff --git a/docs/build/architecture/adr-template.md b/docs/build/architecture/adr-template.md index 04b0450c6..7a2c15496 100644 --- a/docs/build/architecture/adr-template.md +++ b/docs/build/architecture/adr-template.md @@ -15,7 +15,7 @@ > "If you can't explain it simply, you don't understand it well enough." Provide > a simplified and layman-accessible explanation of the ADR. -> A short (~200 word) description of the issue being addressed. +> A short (~200 words) description of the issue being addressed. ## Context diff --git a/docs/build/build.md b/docs/build/build.md index 60fe4c3b0..b3c64a6e9 100644 --- a/docs/build/build.md +++ b/docs/build/build.md @@ -5,7 +5,7 @@ sidebar_position: 0 # Build * [Building Apps](./building-apps/00-app-go.md) - The documentation in this section will guide you through the process of developing your dApp using the Cosmos SDK framework. -* [Modules](./modules/README.md) - Information about the various modules available in the Cosmos SDK: Auth, Authz, Bank, Circuit, Consensus, Distribution, Epochs, Evidence, Feegrant, Governance, Group, Mint, NFT, Protocolpool, Slashing, Staking, Upgrade, Genutil. +* [Modules](../../../x/README.md) - Information about the various modules available in the Cosmos SDK: Auth, Authz, Bank, Circuit, Consensus, Distribution, Epochs, Evidence, Feegrant, Governance, Group, Mint, NFT, Protocolpool, Slashing, Staking, Upgrade, Genutil. * [Migrations](./migrations/01-intro.md) - See what has been updated in each release the process of the transition between versions. * [Packages](./packages/README.md) - Explore a curated collection of pre-built modules and functionalities, streamlining the development process. * [Tooling](./tooling/README.md) - A suite of utilities designed to enhance the development workflow, optimizing the efficiency of Cosmos SDK-based projects. diff --git a/docs/build/building-apps/01-app-go-di.md b/docs/build/building-apps/01-app-go-di.md index 34b27da51..00ab7883d 100644 --- a/docs/build/building-apps/01-app-go-di.md +++ b/docs/build/building-apps/01-app-go-di.md @@ -6,8 +6,8 @@ sidebar_position: 1 :::note Synopsis -The Cosmos SDK allows much easier wiring of an `app.go` thanks to [runtime](./00-runtime.md) and app wiring. -Learn more about the rationale of App Wiring in [ADR-057](../architecture/adr-057-app-wiring.md). +The Cosmos SDK makes wiring of an `app.go` much easier thanks to [runtime](./00-runtime.md) and app wiring. +Learn more about the rationale of App Wiring in [ADR-057](../../../architecture/adr-057-app-wiring.md). ::: @@ -16,7 +16,7 @@ Learn more about the rationale of App Wiring in [ADR-057](../architecture/adr-05 * [What is `runtime`?](./00-runtime.md) * [Depinject documentation](../packages/01-depinject.md) * [Modules depinject-ready](../building-modules/15-depinject.md) -* [ADR 057: App Wiring](../architecture/adr-057-app-wiring.md) +* [ADR 057: App Wiring](../../../architecture/adr-057-app-wiring.md) ::: @@ -40,7 +40,7 @@ The `app_config.go` file is the single place to configure all modules parameters 2. Configure the `runtime` module: - In this configuration, the order at which the modules are defined in PreBlockers, BeginBlocks, and EndBlockers is important. + In this configuration, the order in which the modules are defined in PreBlockers, BeginBlocks, and EndBlockers is important. They are named in the order they should be executed by the module manager. ```go reference @@ -67,7 +67,7 @@ See the complete `app_config.go` file for `SimApp` [here](https://github.com/cos :::tip The example above shows how to create an `AppConfig` using Go. However, it is also possible to create an `AppConfig` using YAML, or JSON. -The configuration can then be embed with `go:embed` and read with [`appconfig.LoadYAML`](https://pkg.go.dev/cosmossdk.io/core/appconfig#LoadYAML), or [`appconfig.LoadJSON`](https://pkg.go.dev/cosmossdk.io/core/appconfig#LoadJSON), in `app_di.go`. +The configuration can then be embedded with `go:embed` and read with [`appconfig.LoadYAML`](https://pkg.go.dev/cosmossdk.io/core/appconfig#LoadYAML), or [`appconfig.LoadJSON`](https://pkg.go.dev/cosmossdk.io/core/appconfig#LoadJSON), in `app_di.go`. ```go //go:embed app_config.yaml diff --git a/docs/build/building-apps/02-app-mempool.md b/docs/build/building-apps/02-app-mempool.md index c2256edff..dbe6783ca 100644 --- a/docs/build/building-apps/02-app-mempool.md +++ b/docs/build/building-apps/02-app-mempool.md @@ -48,7 +48,7 @@ which is FIFO-ordered by default. ### Sender Nonce Mempool -The nonce mempool is a mempool that keeps transactions from an sorted by nonce in order to avoid the issues with nonces. +The nonce mempool is a mempool that keeps transactions from a sender sorted by nonce in order to avoid the issues with nonces. It works by storing the transaction in a list sorted by the transaction nonce. When the proposer asks for transactions to be included in a block it randomly selects a sender and gets the first transaction in the list. It repeats this until the mempool is empty or the block is full. It is configurable with the following parameters: @@ -59,7 +59,7 @@ It is an integer value that sets the mempool in one of three modes, *bounded*, * * **negative**: Disabled, mempool does not insert new transaction and return early. * **zero**: Unbounded mempool has no transaction limit and will never fail with `ErrMempoolTxMaxCapacity`. -* **positive**: Bounded, it fails with `ErrMempoolTxMaxCapacity` when `maxTx` value is the same as `CountTx()` +* **positive**: Bounded, it fails with `ErrMempoolTxMaxCapacity` when the `maxTx` value is the same as `CountTx()` #### Seed @@ -82,13 +82,13 @@ It is an integer value that sets the mempool in one of three modes, *bounded*, * * **negative**: Disabled, mempool does not insert new transaction and return early. * **zero**: Unbounded mempool has no transaction limit and will never fail with `ErrMempoolTxMaxCapacity`. -* **positive**: Bounded, it fails with `ErrMempoolTxMaxCapacity` when `maxTx` value is the same as `CountTx()` +* **positive**: Bounded, it fails with `ErrMempoolTxMaxCapacity` when the `maxTx` value is the same as `CountTx()` #### Callback -The priority nonce mempool provides mempool options allowing the application sets callback(s). +The priority nonce mempool provides mempool options allowing the application to set callback(s). * **OnRead**: Set a callback to be called when a transaction is read from the mempool. -* **TxReplacement**: Sets a callback to be called when duplicated transaction nonce detected during mempool insert. Application can define a transaction replacement rule based on tx priority or certain transaction fields. +* **TxReplacement**: Sets a callback to be called when duplicate transaction nonce detected during mempool insert. Application can define a transaction replacement rule based on tx priority or certain transaction fields. More information on the SDK mempool implementation can be found in the [godocs](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/types/mempool). diff --git a/docs/build/building-apps/03-app-upgrade.md b/docs/build/building-apps/03-app-upgrade.md index bafe968de..541530a14 100644 --- a/docs/build/building-apps/03-app-upgrade.md +++ b/docs/build/building-apps/03-app-upgrade.md @@ -22,13 +22,13 @@ This section is currently incomplete. Track the progress of this document [here] Let's assume we are running v0.38.0 of our software in our testnet and want to upgrade to v0.40.0. How would this look in practice? First, we want to finalize the v0.40.0 release candidate -and then install a specially named upgrade handler (eg. "testnet-v2" or even "v0.40.0"). An upgrade +and then install a specially named upgrade handler (e.g. "testnet-v2" or even "v0.40.0"). An upgrade handler should be defined in a new version of the software to define what migrations to run to migrate from the older version of the software. Naturally, this is app-specific rather -than module specific, and must be defined in `app.go`, even if it imports logic from various +than module-specific, and must be defined in `app.go`, even if it imports logic from various modules to perform the actions. You can register them with `upgradeKeeper.SetUpgradeHandler` during the app initialization (before starting the abci server), and they serve not only to -perform a migration, but also to identify if this is the old or new version (eg. presence of +perform a migration, but also to identify if this is the old or new version (e.g. presence of a handler registered for the named upgrade). Once the release candidate along with an appropriate upgrade handler is frozen, @@ -56,7 +56,7 @@ be a matter of minutes and not even require them to be awake at that time. The following is not required for users using `depinject`, this is abstracted for them. ::: -In addition to basic module wiring, setup the upgrade Keeper for the app and then define a `PreBlocker` that calls the upgrade +In addition to basic module wiring, set up the upgrade Keeper for the app and then define a `PreBlocker` that calls the upgrade keeper's PreBlocker method: ```go @@ -94,7 +94,7 @@ Here is a sample code to set store migrations with an upgrade: ```go // this configures a no-op upgrade handler for the "my-fancy-upgrade" upgrade -app.UpgradeKeeper.SetUpgradeHandler("my-fancy-upgrade", func(ctx context.Context, plan upgrade.Plan) { +app.UpgradeKeeper.SetUpgradeHandler("my-fancy-upgrade", func(ctx context.Context, plan upgrade.Plan) { // upgrade changes here }) upgradeInfo, err := app.UpgradeKeeper.ReadUpgradeInfoFromDisk() diff --git a/docs/build/building-apps/04-vote-extensions.md b/docs/build/building-apps/04-vote-extensions.md index d2f33aa07..f20ebde66 100644 --- a/docs/build/building-apps/04-vote-extensions.md +++ b/docs/build/building-apps/04-vote-extensions.md @@ -16,7 +16,7 @@ process does NOT have to be deterministic, and the data returned can be unique t validator process. The Cosmos SDK defines `baseapp.ExtendVoteHandler`: ```go -type ExtendVoteHandler func(Context, *abci.RequestExtendVote) (*abci.ResponseExtendVote, error) +type ExtendVoteHandler func(Context, *abci.ExtendVoteRequest) (*abci.ExtendVoteResponse, error) ``` An application can set this handler in `app.go` via the `baseapp.SetExtendVoteHandler` @@ -74,10 +74,10 @@ hook to allow applications to recover vote extensions, perform any necessary computation on them, and then store the results in the cached store. These results will be available to the application during the subsequent `FinalizeBlock` call. -An example of how a pre-FinalizeBlock hook could look like is shown below: +An example of how a pre-FinalizeBlock hook could look is shown below: ```go -app.SetPreBlocker(func(ctx sdk.Context, req *abci.RequestFinalizeBlock) error { +app.SetPreBlocker(func(ctx sdk.Context, req *abci.FinalizeBlockRequest) error { allVEs := []VE{} // store all parsed vote extensions here for _, tx := range req.Txs { // define a custom function that tries to parse the tx as a vote extension diff --git a/docs/build/building-apps/05-app-testnet.md b/docs/build/building-apps/05-app-testnet.md index f79ae5519..a9fe93d90 100644 --- a/docs/build/building-apps/05-app-testnet.md +++ b/docs/build/building-apps/05-app-testnet.md @@ -25,7 +25,7 @@ We will be breaking down the steps to create a testnet from mainnet state. #### Staking -When creating a testnet the important part is migrate the validator set from many validators to one or a few. This allows developers to spin up the chain without needing to replace validator keys. +When creating a testnet the important part is to migrate the validator set from many validators to one or a few. This allows developers to spin up the chain without needing to replace validator keys. ```go ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{}) diff --git a/docs/build/building-modules/00-intro.md b/docs/build/building-modules/00-intro.md index ab28445cd..a0475ac3b 100644 --- a/docs/build/building-modules/00-intro.md +++ b/docs/build/building-modules/00-intro.md @@ -56,7 +56,7 @@ https://github.com/cosmos/cosmos-sdk/blob/61da5d1c29c16a1eb5bb5488719fde604ec07b While there are no definitive guidelines for writing modules, here are some important design principles developers should keep in mind when building them: * **Composability**: Cosmos SDK applications are almost always composed of multiple modules. This means developers need to carefully consider the integration of their module not only with the core of the Cosmos SDK, but also with other modules. The former is achieved by following standard design patterns outlined [here](#main-components-of-cosmos-sdk-modules), while the latter is achieved by properly exposing the store(s) of the module via the [`keeper`](./06-keeper.md). -* **Specialization**: A direct consequence of the **composability** feature is that modules should be **specialized**. Developers should carefully establish the scope of their module and not batch multiple functionalities into the same module. This separation of concerns enables modules to be re-used in other projects and improves the upgradability of the application. **Specialization** also plays an important role in the [object-capabilities model](../../learn/advanced/10-ocap.md) of the Cosmos SDK. +* **Specialization**: A direct consequence of the **composability** feature is that modules should be **specialized**. Developers should carefully establish the scope of their module and not batch multiple functionalities into the same module. This separation of concerns enables modules to be re-used in other projects and improves the upgradability of the application. **Specialization** also plays an important role in the [object-capabilities model](../../docs/learn/advanced/10-ocap.md) of the Cosmos SDK. * **Capabilities**: Most modules need to read and/or write to the store(s) of other modules. However, in an open-source environment, it is possible for some modules to be malicious. That is why module developers need to carefully think not only about how their module interacts with other modules, but also about how to give access to the module's store(s). The Cosmos SDK takes a capabilities-oriented approach to inter-module security. This means that each store defined by a module is accessed by a `key`, which is held by the module's [`keeper`](./06-keeper.md). This `keeper` defines how to access the store(s) and under what conditions. Access to the module's store(s) is done by passing a reference to the module's `keeper`. ## Main Components of Cosmos SDK Modules diff --git a/docs/build/building-modules/01-module-manager.md b/docs/build/building-modules/01-module-manager.md index 02d7520af..ee2a83a80 100644 --- a/docs/build/building-modules/01-module-manager.md +++ b/docs/build/building-modules/01-module-manager.md @@ -5,7 +5,7 @@ sidebar_position: 1 # Module Manager :::note Synopsis -Cosmos SDK modules need to implement the [`AppModule` interfaces](#application-module-interfaces), in order to be managed by the application's [module manager](#module-manager). The module manager plays an important role in [`message` and `query` routing](../../learn/advanced/00-baseapp.md#routing), and allows application developers to set the order of execution of a variety of functions like [`PreBlocker`](../../learn/beginner/00-app-anatomy#preblocker) and [`BeginBlocker` and `EndBlocker`](../../learn/beginner/00-app-anatomy.md#begingblocker-and-endblocker). +Cosmos SDK modules need to implement the [`AppModule` interfaces](#application-module-interfaces), in order to be managed by the application's [module manager](#module-manager). The module manager plays an important role in [`message` and `query` routing](../../learn/advanced/00-baseapp.md#routing), and allows application developers to set the order of execution of a variety of functions like [`PreBlocker`](../../learn/beginner/00-app-anatomy.md#preblocker) and [`BeginBlocker` and `EndBlocker`](../../learn/beginner/00-app-anatomy.md#beginblocker-and-endblocker). ::: :::note Pre-requisite Readings @@ -29,7 +29,7 @@ There are 2 main application module interfaces: * [`appmodule.AppModule` / `module.AppModule`](#appmodule) for inter-dependent module functionalities (except genesis-related functionalities). * (legacy) [`module.AppModuleBasic`](#appmodulebasic) for independent module functionalities. New modules can use `module.CoreAppModuleBasicAdaptor` instead. -The above interfaces are mostly embedding smaller interfaces (extension interfaces), that defines specific functionalities: +The above interfaces are mostly embedding smaller interfaces (extension interfaces), that define specific functionalities: * (legacy) `module.HasName`: Allows the module to provide its own name for legacy purposes. * (legacy) [`module.HasGenesisBasics`](#modulehasgenesisbasics): The legacy interface for stateless genesis methods. @@ -144,7 +144,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L199-L2 ### `HasInvariants` -This interface defines one method. It allows to checks if a module can register invariants. +This interface defines one method. It allows checking if a module can register invariants. ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L211-L214 @@ -154,7 +154,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L211-L2 ### `HasServices` -This interface defines one method. It allows to checks if a module can register invariants. +This interface defines one method. It allows checking if a module can register services. #### `appmodule.HasService` @@ -196,7 +196,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/core/appmodule/module.go#L73-L ### `HasEndBlocker` -The `HasEndBlocker` is an extension interface from `appmodule.AppModule`. All modules that have an `EndBlock` method implement this interface. If a module need to return validator set updates (staking), they can use `HasABCIEndBlock` +The `HasEndBlocker` is an extension interface from `appmodule.AppModule`. All modules that have an `EndBlock` method implement this interface. If a module needs to return validator set updates (staking), they can use `HasABCIEndBlock` ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/core/appmodule/module.go#L83-L89 @@ -271,7 +271,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/types/module/module.go#L77 It implements the following methods: * `NewBasicManager(modules ...AppModuleBasic)`: Constructor function. It takes a list of the application's `AppModuleBasic` and builds a new `BasicManager`. This function is generally called in the `init()` function of [`app.go`](../../learn/beginner/00-app-anatomy.md#core-application-file) to quickly initialize the independent elements of the application's modules (click [here](https://github.com/cosmos/gaia/blob/main/app/app.go#L59-L74) to see an example). -* `NewBasicManagerFromManager(manager *Manager, customModuleBasics map[string]AppModuleBasic)`: Contructor function. It creates a new `BasicManager` from a `Manager`. The `BasicManager` will contain all `AppModuleBasic` from the `AppModule` manager using `CoreAppModuleBasicAdaptor` whenever possible. Module's `AppModuleBasic` can be overridden by passing a custom AppModuleBasic map +* `NewBasicManagerFromManager(manager *Manager, customModuleBasics map[string]AppModuleBasic)`: Constructor function. It creates a new `BasicManager` from a `Manager`. The `BasicManager` will contain all `AppModuleBasic` from the `AppModule` manager using `CoreAppModuleBasicAdaptor` whenever possible. Module's `AppModuleBasic` can be overridden by passing a custom AppModuleBasic map * `RegisterLegacyAminoCodec(cdc *codec.LegacyAmino)`: Registers the [`codec.LegacyAmino`s](../../learn/advanced/05-encoding.md#amino) of each of the application's `AppModuleBasic`. This function is usually called early on in the [application's construction](../../learn/beginner/00-app-anatomy.md#constructor). * `RegisterInterfaces(registry codectypes.InterfaceRegistry)`: Registers interface types and implementations of each of the application's `AppModuleBasic`. * `DefaultGenesis(cdc codec.JSONCodec)`: Provides default genesis information for modules in the application by calling the [`DefaultGenesis(cdc codec.JSONCodec)`](./08-genesis.md#defaultgenesis) function of each module. It only calls the modules that implements the `HasGenesisBasics` interfaces. @@ -302,7 +302,7 @@ The module manager is used throughout the application whenever an action on a co * `SetOrderMigrations(moduleNames ...string)`: Sets the order of migrations to be run. If not set then migrations will be run with an order defined in `DefaultMigrationsOrder`. * `RegisterInvariants(ir sdk.InvariantRegistry)`: Registers the [invariants](./07-invariants.md) of module implementing the `HasInvariants` interface. * `RegisterServices(cfg Configurator)`: Registers the services of modules implementing the `HasServices` interface. -* `InitGenesis(ctx context.Context, cdc codec.JSONCodec, genesisData map[string]json.RawMessage)`: Calls the [`InitGenesis`](./08-genesis.md#initgenesis) function of each module when the application is first started, in the order defined in `OrderInitGenesis`. Returns an `abci.ResponseInitChain` to the underlying consensus engine, which can contain validator updates. +* `InitGenesis(ctx context.Context, cdc codec.JSONCodec, genesisData map[string]json.RawMessage)`: Calls the [`InitGenesis`](./08-genesis.md#initgenesis) function of each module when the application is first started, in the order defined in `OrderInitGenesis`. Returns an `abci.InitChainResponse` to the underlying consensus engine, which can contain validator updates. * `ExportGenesis(ctx context.Context, cdc codec.JSONCodec)`: Calls the [`ExportGenesis`](./08-genesis.md#exportgenesis) function of each module, in the order defined in `OrderExportGenesis`. The export constructs a genesis file from a previously existing state, and is mainly used when a hard-fork upgrade of the chain is required. * `ExportGenesisForModules(ctx context.Context, cdc codec.JSONCodec, modulesToExport []string)`: Behaves the same as `ExportGenesis`, except takes a list of modules to export. * `BeginBlock(ctx context.Context) error`: At the beginning of each block, this function is called from [`BaseApp`](../../learn/advanced/00-baseapp.md#beginblock) and, in turn, calls the [`BeginBlock`](./06-beginblock-endblock.md) function of each modules implementing the `appmodule.HasBeginBlocker` interface, in the order defined in `OrderBeginBlockers`. It creates a child [context](../../learn/advanced/02-context.md) with an event manager to aggregate [events](../../learn/advanced/08-events.md) emitted from each modules. diff --git a/docs/build/building-modules/02-messages-and-queries.md b/docs/build/building-modules/02-messages-and-queries.md index 573c35cd7..e6048c313 100644 --- a/docs/build/building-modules/02-messages-and-queries.md +++ b/docs/build/building-modules/02-messages-and-queries.md @@ -39,15 +39,15 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/proto/cosmos/bank/v1be ### `sdk.Msg` Interface -`sdk.Msg` is a alias of `proto.Message`. +`sdk.Msg` is an alias of `proto.Message`. -To attach a `ValidateBasic()` method to a message then you must add methods to the type adhereing to the `HasValidateBasic`. +To attach a `ValidateBasic()` method to a message then you must add methods to the type adhering to the `HasValidateBasic`. ```go reference https://github.com/cosmos/cosmos-sdk/blob/9c1e8b247cd47b5d3decda6e86fbc3bc996ee5d7/types/tx_msg.go#L84-L88 ``` -In 0.50+ signers from the `GetSigners()` call is automated via a protobuf annotation. +In 0.50+ signers from the `GetSigners()` call are automated via a protobuf annotation. Read more about the signer field [here](./05-protobuf-annotations.md). @@ -120,7 +120,7 @@ where: * `queryType` is used by the module's [`querier`](./04-query-services.md#legacy-queriers) to map the `query` to the appropriate `querier function` within the module. * `args` are the actual arguments needed to process the `query`. They are filled out by the end-user. Note that for bigger queries, you might prefer passing arguments in the `Data` field of the request `req` instead of the `path`. -The `path` for each `query` must be defined by the module developer in the module's [command-line interface file](./09-module-interfaces.md#query-commands).Overall, there are 3 mains components module developers need to implement in order to make the subset of the state defined by their module queryable: +The `path` for each `query` must be defined by the module developer in the module's [command-line interface file](./09-module-interfaces.md#query-commands). Overall, there are 3 mains components module developers need to implement in order to make the subset of the state defined by their module queryable: * A [`querier`](./04-query-services.md#legacy-queriers), to process the `query` once it has been [routed to the module](../../learn/advanced/00-baseapp.md#query-routing). * [Query commands](./09-module-interfaces.md#query-commands) in the module's CLI file, where the `path` for each `query` is specified. @@ -128,7 +128,7 @@ The `path` for each `query` must be defined by the module developer in the modul ### Store Queries -Store queries query directly for store keys. They use `clientCtx.QueryABCI(req abci.RequestQuery)` to return the full `abci.ResponseQuery` with inclusion Merkle proofs. +Store queries access store keys directly. They use `clientCtx.QueryABCI(req abci.QueryRequest)` to return the full `abci.QueryResponse` with inclusion Merkle proofs. See following examples: diff --git a/docs/build/building-modules/03-msg-services.md b/docs/build/building-modules/03-msg-services.md index 421e53dec..910d6f88d 100644 --- a/docs/build/building-modules/03-msg-services.md +++ b/docs/build/building-modules/03-msg-services.md @@ -19,7 +19,7 @@ A Protobuf `Msg` service processes [messages](./02-messages-and-queries.md#messa Each module should define a Protobuf `Msg` service, which will be responsible for processing requests (implementing `sdk.Msg`) and returning responses. -As further described in [ADR 031](../architecture/adr-031-msg-service.md), this approach has the advantage of clearly specifying return types and generating server and client code. +As further described in [ADR 031](../../../architecture/adr-031-msg-service.md), this approach has the advantage of clearly specifying return types and generating server and client code. Protobuf generates a `MsgServer` interface based on a definition of `Msg` service. It is the role of the module developer to implement this interface, by implementing the state transition logic that should happen upon receival of each `sdk.Msg`. As an example, here is the generated `MsgServer` interface for `x/bank`, which exposes two `sdk.Msg`s: @@ -33,7 +33,7 @@ When possible, the existing module's [`Keeper`](./06-keeper.md) should implement https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/keeper/msg_server.go#L17-L19 ``` -`msgServer` methods can retrieve the `context.Context` from the `context.Context` parameter method using the `sdk.UnwrapSDKContext`: +`msgServer` methods can retrieve the `sdk.Context` from the `context.Context` parameter using the `sdk.UnwrapSDKContext` method: ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/keeper/msg_server.go#L56 @@ -53,10 +53,10 @@ It is recommended to implement all validation checks in a separate function that ```go ValidateMsgA(msg MsgA, now Time, gm GasMeter) error { if now.Before(msg.Expire) { - return sdkerrrors.ErrInvalidRequest.Wrap("msg expired") + return sdkerrors.ErrInvalidRequest.Wrap("msg expired") } gm.ConsumeGas(1000, "signature verification") - return signatureVerificaton(msg.Prover, msg.Data) + return signatureVerification(msg.Prover, msg.Data) } ``` @@ -75,7 +75,7 @@ Before returning, `msgServer` methods generally emit one or more [events](../../ ```go ctx.EventManager().EmitTypedEvent( - &group.EventABC{Key1: Value1, Key2, Value2}) + &group.EventABC{Key1: Value1, Key2: Value2}) ``` or the older `EmitEvent` function: diff --git a/docs/build/building-modules/05-protobuf-annotations.md b/docs/build/building-modules/05-protobuf-annotations.md index 5240112e9..942b9a892 100644 --- a/docs/build/building-modules/05-protobuf-annotations.md +++ b/docs/build/building-modules/05-protobuf-annotations.md @@ -56,7 +56,7 @@ There are a few options for what can be provided as a scalar: `cosmos.AddressStr ## Implements_Interface -Implement interface is used to provide information to client tooling like [telescope](https://github.com/cosmology-tech/telescope) on how to encode and decode protobuf messages. +`Implements_Interface` is used to provide information to client tooling like [telescope](https://github.com/cosmology-tech/telescope) on how to encode and decode protobuf messages. ```proto option (cosmos_proto.implements_interface) = "cosmos.auth.v1beta1.AccountI"; @@ -64,9 +64,9 @@ option (cosmos_proto.implements_interface) = "cosmos.auth.v1beta1.AccountI"; ## Method,Field,Message Added In -`method_added_in`, `field_added_in` and `message_added_in` are annotations to denotate to clients that a field has been supported in a later version. This is useful when new methods or fields are added in later versions and that the client needs to be aware of what it can call. +`method_added_in`, `field_added_in` and `message_added_in` are annotations to denote to clients that a field has been supported in a later version. This is useful when new methods or fields are added in later versions and that the client needs to be aware of what it can call. -The annotation should be worded as follow: +The annotation should be worded as follows: ```proto option (cosmos_proto.method_added_in) = "cosmos-sdk v0.50.1"; @@ -76,17 +76,15 @@ option (cosmos_proto.method_added_in) = "simapp v24.0.0"; ## Amino -The amino codec was removed in `v0.50+`, this means there is not a need register `legacyAminoCodec`. To replace the amino codec, Amino protobuf annotations are used to provide information to the amino codec on how to encode and decode protobuf messages. +The amino codec was removed in `v0.50+`, this means there is no need to register `legacyAminoCodec`. To replace the amino codec, Amino protobuf annotations are used to provide information to the amino codec on how to encode and decode protobuf messages. -:::note -Amino annotations are only used for backwards compatibility with amino. New modules are not required use amino annotations. -::: +Amino annotations are only used for backwards compatibility with amino. New modules are not required to use amino annotations. The below annotations are used to provide information to the amino codec on how to encode and decode protobuf messages in a backwards compatible manner. ### Name -Name specifies the amino name that would show up for the user in order for them see which message they are signing. +Name specifies the amino name that would show up for the user in order for them to see which message they are signing. ```proto option (amino.name) = "cosmos-sdk/BaseAccount"; @@ -98,7 +96,7 @@ https://github.com/cosmos/cosmos-sdk/blob/e8f28bf5db18b8d6b7e0d94b542ce4cf48fed9 ### Field_Name -Field name specifies the amino name that would show up for the user in order for them see which field they are signing. +Field name specifies the amino name that would show up for the user in order for them to see which field they are signing. ```proto uint64 height = 1 [(amino.field_name) = "public_key"]; diff --git a/docs/build/building-modules/06-beginblock-endblock.md b/docs/build/building-modules/06-beginblock-endblock.md index a8eafdf67..93e07a54f 100644 --- a/docs/build/building-modules/06-beginblock-endblock.md +++ b/docs/build/building-modules/06-beginblock-endblock.md @@ -18,11 +18,11 @@ sidebar_position: 1 `BeginBlocker` and `EndBlocker` are a way for module developers to add automatic execution of logic to their module. This is a powerful tool that should be used carefully, as complex automatic functions can slow down or even halt the chain. -In 0.47.0, Prepare and Process Proposal were added that allow app developers to do arbitrary work at those phases, but they do not influence the work that will be done in BeginBlock. If an application required `BeginBlock` to execute prior to any sort of work is done then this is not possible today (0.50.0). +In 0.47.0, Prepare and Process Proposal were added that allow app developers to do arbitrary work at those phases, but they do not influence the work that will be done in BeginBlock. If an application requires `BeginBlock` to execute prior to any sort of work is done then this is not possible today (0.50.0). When needed, `BeginBlocker` and `EndBlocker` are implemented as part of the [`HasBeginBlocker`, `HasABCIEndBlocker` and `EndBlocker` interfaces](./01-module-manager.md#appmodule). This means either can be left-out if not required. The `BeginBlock` and `EndBlock` methods of the interface implemented in `module.go` generally defer to `BeginBlocker` and `EndBlocker` methods respectively, which are usually implemented in `abci.go`. -The actual implementation of `BeginBlocker` and `EndBlocker` in `abci.go` are very similar to that of a [`Msg` service](./03-msg-services.md): +The actual implementation of `BeginBlocker` and `EndBlocker` in `abci.go` is very similar to that of a [`Msg` service](./03-msg-services.md): * They generally use the [`keeper`](./06-keeper.md) and [`ctx`](../../learn/advanced/02-context.md) to retrieve information about the latest state. * If needed, they use the `keeper` and `ctx` to trigger state-transitions. diff --git a/docs/build/building-modules/06-keeper.md b/docs/build/building-modules/06-keeper.md index 399ec648c..f942750e5 100644 --- a/docs/build/building-modules/06-keeper.md +++ b/docs/build/building-modules/06-keeper.md @@ -16,9 +16,9 @@ sidebar_position: 1 ## Motivation -The Cosmos SDK is a framework that makes it easy for developers to build complex decentralized applications from scratch, mainly by composing modules together. As the ecosystem of open-source modules for the Cosmos SDK expands, it will become increasingly likely that some of these modules contain vulnerabilities, as a result of the negligence or malice of their developer. +The Cosmos SDK is a framework that makes it easy for developers to build complex decentralized applications from scratch, mainly by composing modules together. As the ecosystem of open-source modules for the Cosmos SDK expands, it will become increasingly likely that some of these modules contain vulnerabilities, as a result of the negligence or malice of their developers. -The Cosmos SDK adopts an [object-capabilities-based approach](../../learn/advanced/10-ocap.md) to help developers better protect their application from unwanted inter-module interactions, and `keeper`s are at the core of this approach. A `keeper` can be considered quite literally to be the gatekeeper of a module's store(s). Each store (typically an [`IAVL` Store](../../learn/advanced/04-store.md#iavl-store)) defined within a module comes with a `storeKey`, which grants unlimited access to it. The module's `keeper` holds this `storeKey` (which should otherwise remain unexposed), and defines [methods](#implementing-methods) for reading and writing to the store(s). +The Cosmos SDK adopts an [object-capabilities-based approach](../../docs/learn/advanced/10-ocap.md) to help developers better protect their application from unwanted inter-module interactions, and `keeper`s are at the core of this approach. A `keeper` can be considered quite literally to be the gatekeeper of a module's store(s). Each store (typically an [`IAVL` Store](../../learn/advanced/04-store.md#iavl-store)) defined within a module comes with a `storeKey`, which grants unlimited access to it. The module's `keeper` holds this `storeKey` (which should otherwise remain unexposed), and defines [methods](#implementing-methods) for reading and writing to the store(s). The core idea behind the object-capabilities approach is to only reveal what is necessary to get the work done. In practice, this means that instead of handling permissions of modules through access-control lists, module `keeper`s are passed a reference to the specific instance of the other modules' `keeper`s that they need to access (this is done in the [application's constructor function](../../learn/beginner/00-app-anatomy.md#constructor-function)). As a consequence, a module can only interact with the subset of state defined in another module via the methods exposed by the instance of the other module's `keeper`. This is a great way for developers to control the interactions that their own module can have with modules developed by external developers. diff --git a/docs/build/building-modules/08-genesis.md b/docs/build/building-modules/08-genesis.md index 7abb21fb6..28ff911ba 100644 --- a/docs/build/building-modules/08-genesis.md +++ b/docs/build/building-modules/08-genesis.md @@ -17,7 +17,7 @@ Modules generally handle a subset of the state and, as such, they need to define ## Type Definition -The subset of the genesis state defined from a given module is generally defined in a `genesis.proto` file ([more info](../../learn/advanced/05-encoding.md#gogoproto) on how to define protobuf messages). The struct defining the module's subset of the genesis state is usually called `GenesisState` and contains all the module-related values that need to be initialized during the genesis process. +The subset of the genesis state defined by a given module is generally defined in a `genesis.proto` file ([more info](../../learn/advanced/05-encoding.md#gogoproto) on how to define protobuf messages). The struct defining the module's subset of the genesis state is usually called `GenesisState` and contains all the module-related values that need to be initialized during the genesis process. See an example of `GenesisState` protobuf message definition from the `auth` module: @@ -29,7 +29,7 @@ Next we present the main genesis-related methods that need to be implemented by ### `DefaultGenesis` -The `DefaultGenesis()` method is a simple method that calls the constructor function for `GenesisState` with the default value for each parameter. See an example from the `auth` module: +The `DefaultGenesis()` method is a simple function that calls the constructor function for `GenesisState` with the default value for each parameter. See an example from the `auth` module: ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/auth/module.go#L63-L67 diff --git a/docs/build/building-modules/09-module-interfaces.md b/docs/build/building-modules/09-module-interfaces.md index 4552baef2..63a939d02 100644 --- a/docs/build/building-modules/09-module-interfaces.md +++ b/docs/build/building-modules/09-module-interfaces.md @@ -132,7 +132,8 @@ Since `AddTxFlagsToCmd(cmd *cobra.Command)` includes all of the basic flags requ Similarly, there is a `AddQueryFlagsToCmd(cmd *cobra.Command)` to add common flags to a module query command. ```go reference -https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/client/flags/flags.go#L95-L106``` +https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/client/flags/flags.go#L95-L106 +``` --> ## gRPC @@ -159,6 +160,6 @@ Modules that want to expose REST queries should add `google.api.http` annotation https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/proto/cosmos/auth/v1beta1/query.proto#L14-L89 ``` -gRPC gateway is started in-process along with the application and CometBFT. It can be enabled or disabled by setting gRPC Configuration `enable` in [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml). +gRPC gateway is started in-process along with the application and CometBFT. It can be enabled or disabled by setting gRPC Configuration `enable` in [`app.toml`](../../user/run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml). -The Cosmos SDK provides a command for generating [Swagger](https://swagger.io/) documentation (`protoc-gen-swagger`). Setting `swagger` in [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml) defines if swagger documentation should be automatically registered. +The Cosmos SDK provides a command for generating [Swagger](https://swagger.io/) documentation (`protoc-gen-swagger`). Setting `swagger` in [`app.toml`](../../user/run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml) defines if swagger documentation should be automatically registered. diff --git a/docs/build/building-modules/11-structure.md b/docs/build/building-modules/11-structure.md index 71a5b3cc2..a36b9a498 100644 --- a/docs/build/building-modules/11-structure.md +++ b/docs/build/building-modules/11-structure.md @@ -82,7 +82,7 @@ x/{module_name} * `abci.go`: The module's `BeginBlocker` and `EndBlocker` implementations (this file is only required if `BeginBlocker` and/or `EndBlocker` need to be defined). * `autocli.go`: The module [autocli](https://docs.cosmos.network/main/core/autocli) options. * `simulation/`: The module's [simulation](./14-simulator.md) package defines functions used by the blockchain simulator application (`simapp`). -* `REAMDE.md`: The module's specification documents outlining important concepts, state storage structure, and message and event type definitions. Learn more how to write module specs in the [spec guidelines](../spec/SPEC_MODULE.md). +* `README.md`: The module's specification documents outlining important concepts, state storage structure, and message and event type definitions. Learn more about how to write module specs in the [spec guidelines](../../../spec/SPEC_MODULE.md). * The root directory includes type definitions for messages, events, and genesis state, including the type definitions generated by Protocol Buffers. * `codec.go`: The module's registry methods for interface types. * `errors.go`: The module's sentinel errors. diff --git a/docs/build/building-modules/13-upgrade.md b/docs/build/building-modules/13-upgrade.md index 908a6a06e..20c02e9f2 100644 --- a/docs/build/building-modules/13-upgrade.md +++ b/docs/build/building-modules/13-upgrade.md @@ -60,4 +60,4 @@ func (m Migrator) Migrate1to2(ctx sdk.Context) error { } ``` -To see example code of changes that were implemented in a migration of balance keys, check out [migrateBalanceKeys](https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/migrations/v2/store.go#L55-L76). For context, this code introduced migrations of the bank store that updated addresses to be prefixed by their length in bytes as outlined in [ADR-028](../architecture/adr-028-public-key-addresses.md). +To see example code of changes that were implemented in a migration of balance keys, check out [migrateBalanceKeys](https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/x/bank/migrations/v2/store.go#L55-L76). For context, this code introduced migrations of the bank store that updated addresses to be prefixed by their length in bytes as outlined in [ADR-028](../../../architecture/adr-028-public-key-addresses.md). diff --git a/docs/build/building-modules/14-simulator.md b/docs/build/building-modules/14-simulator.md index 78a186bc2..a97637158 100644 --- a/docs/build/building-modules/14-simulator.md +++ b/docs/build/building-modules/14-simulator.md @@ -18,11 +18,11 @@ Simulations are useful for testing edge cases in module implementations. * [Simulation Package](#simulation-package) * [Simulation App Module](#simulation-app-module) * [SimsX](#simsx) - * [Example Implementations](#example-implementations) + * [Example Implementations](#example-implementations) * [Store decoders](#store-decoders) * [Randomized genesis](#randomized-genesis) * [Random weighted operations](#random-weighted-operations) - * [Using Simsx](#using-simsx) + * [Using Simsx](#using-simsx) * [App Simulator manager](#app-simulator-manager) * [Running Simulations](#running-simulations) @@ -47,6 +47,7 @@ See an example implementation of these methods from `x/distribution` [here](http Cosmos SDK v0.53.0 introduced a new package, `simsx`, providing improved DevX for writing simulation code. It exposes the following extension interfaces that modules may implement to integrate with the new `simsx` runner. + ```go reference https://github.com/cosmos/cosmos-sdk/blob/main/testutil/simsx/runner.go#L223-L234 ``` @@ -62,15 +63,15 @@ If the module does **not** have message handlers or governance proposal handlers ### Example Implementations -- `HasWeightedOperationsXWithProposals`: [x/gov](https://github.com/cosmos/cosmos-sdk/blob/main/x/gov/module.go#L242-L261) -- `HasWeightedOperationsX`: [x/bank](https://github.com/cosmos/cosmos-sdk/blob/main/x/bank/module.go#L199-L203) -- `HasProposalMsgsX`: [x/bank](https://github.com/cosmos/cosmos-sdk/blob/main/x/bank/module.go#L194-L197) +* `HasWeightedOperationsXWithProposals`: [x/gov](https://github.com/cosmos/cosmos-sdk/blob/main/x/gov/module.go#L242-L261) +* `HasWeightedOperationsX`: [x/bank](https://github.com/cosmos/cosmos-sdk/blob/main/x/bank/module.go#L199-L203) +* `HasProposalMsgsX`: [x/bank](https://github.com/cosmos/cosmos-sdk/blob/main/x/bank/module.go#L194-L197) ## Store decoders Registering the store decoders is required for the `AppImportExport` simulation. This allows for the key-value pairs from the stores to be decoded to their corresponding types. -In particular, it matches the key to a concrete type and then unmarshalls the value from the `KVPair` to the type provided. +In particular, it matches the key to a concrete type and then unmarshals the value from the `KVPair` to the type provided. Modules using [collections](https://github.com/cosmos/cosmos-sdk/blob/main/collections/README.md) can use the `NewStoreDecoderFuncFromCollectionsSchema` function that builds the decoder for you: @@ -173,4 +174,4 @@ Example: ```go reference https://github.com/cosmos/cosmos-sdk/blob/main/simapp/sim_test.go#L53-L65 -``` \ No newline at end of file +``` diff --git a/docs/build/building-modules/15-depinject.md b/docs/build/building-modules/15-depinject.md index 316036383..64aa3711e 100644 --- a/docs/build/building-modules/15-depinject.md +++ b/docs/build/building-modules/15-depinject.md @@ -36,7 +36,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/proto/cosmos/group/mod * `go_import` must point to the Go package of the custom module. * Message fields define the module configuration. That configuration can be set in the `app_config.go` / `app.yaml` file for a chain developer to configure the module. - Taking `group` as example, a chain developer is able to decide, thanks to `uint64 max_metadata_len`, what the maximum metadata length allowed for a group proposal is. + Taking `group` as an example, a chain developer is able to decide, thanks to `uint64 max_metadata_len`, what the maximum metadata length allowed for a group proposal is. ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/simapp/app_config.go#L228-L234 diff --git a/docs/build/building-modules/16-testing.md b/docs/build/building-modules/16-testing.md index 3dc4c3419..43a79b8e3 100644 --- a/docs/build/building-modules/16-testing.md +++ b/docs/build/building-modules/16-testing.md @@ -6,8 +6,8 @@ sidebar_position: 1 The Cosmos SDK contains different types of [tests](https://martinfowler.com/articles/practical-test-pyramid.html). These tests have different goals and are used at different stages of the development cycle. -We advice, as a general rule, to use tests at all stages of the development cycle. -It is adviced, as a chain developer, to test your application and modules in a similar way than the SDK. +We advise, as a general rule, to use tests at all stages of the development cycle. +It is advised, as a chain developer, to test your application and modules in a similar way to the SDK. The rationale behind testing can be found in [ADR-59](https://docs.cosmos.network/main/build/architecture/adr-059-test-scopes). @@ -46,7 +46,7 @@ This allows us to test the `x/gov` module without having to import other modules https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/gov/keeper/keeper_test.go#L3-L42 ``` -We can test then create unit tests using the newly created `Keeper` instance. +We can then create unit tests using the newly created `Keeper` instance. ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/gov/keeper/keeper_test.go#L83-L107 @@ -59,7 +59,7 @@ In the SDK, we locate our integration tests under [`/tests/integrations`](https: The goal of these integration tests is to test how a component interacts with other dependencies. Compared to unit tests, integration tests do not mock dependencies. Instead, they use the direct dependencies of the component. This differs as well from end-to-end tests, which test the component with a full application. -Integration tests interact with the tested module via the defined `Msg` and `Query` services. The result of the test can be verified by checking the state of the application, by checking the emitted events or the response. It is adviced to combine two of these methods to verify the result of the test. +Integration tests interact with the tested module via the defined `Msg` and `Query` services. The result of the test can be verified by checking the state of the application, by checking the emitted events or the response. It is advised to combine two of these methods to verify the result of the test. The SDK provides small helpers for quickly setting up an integration tests. These helpers can be found at . @@ -116,9 +116,9 @@ Here are some examples: * Osmosis E2E tests: . :::note warning -The SDK is in the process of creating its E2E tests, as defined in [ADR-59](https://docs.cosmos.network/main/architecture/adr-059-test-scopes.html). This page will eventually be updated with better examples. +The SDK is in the process of creating its E2E tests, as defined in [ADR-59](https://docs.cosmos.network/main/build/architecture/adr-059-test-scopes). This page will eventually be updated with better examples. ::: ## Learn More -Learn more about testing scope in [ADR-59](https://docs.cosmos.network/main/architecture/adr-059-test-scopes.html). +Learn more about testing scope in [ADR-59](https://docs.cosmos.network/main/build/architecture/adr-059-test-scopes). diff --git a/docs/build/building-modules/17-preblock.md b/docs/build/building-modules/17-preblock.md index a79646bd4..437224979 100644 --- a/docs/build/building-modules/17-preblock.md +++ b/docs/build/building-modules/17-preblock.md @@ -5,7 +5,7 @@ sidebar_position: 1 # PreBlocker :::note Synopsis -`PreBlocker` is optional method module developers can implement in their module. They will be triggered before [`BeginBlock`](../../learn/advanced/00-baseapp.md#beginblock). +`PreBlocker` is an optional method module developers can implement in their module. They will be triggered before [`BeginBlock`](../../learn/advanced/00-baseapp.md#beginblock). ::: :::note Pre-requisite Readings @@ -18,10 +18,11 @@ sidebar_position: 1 There are two semantics around the new lifecycle method: -- It runs before the `BeginBlocker` of all modules -- It can modify consensus parameters in storage, and signal the caller through the return value. +* It runs before the `BeginBlocker` of all modules +* It can modify consensus parameters in storage, and signal the caller through the return value. + +When it returns `ConsensusParamsChanged=true`, the caller must refresh the consensus parameters in the deliver context: -When it returns `ConsensusParamsChanged=true`, the caller must refresh the consensus parameter in the deliver context: ``` app.finalizeBlockState.ctx = app.finalizeBlockState.ctx.WithConsensusParams(app.GetConsensusParams()) ``` diff --git a/docs/build/migrations/01-intro.md b/docs/build/migrations/01-intro.md index 47c5c245a..e3146856d 100644 --- a/docs/build/migrations/01-intro.md +++ b/docs/build/migrations/01-intro.md @@ -12,4 +12,4 @@ Additionally, the SDK includes in-place migrations for its core modules. These i Migration from a version older than the last two major releases is not supported. -When migrating from a previous version, refer to the [`UPGRADING.md`](./02-upgrading.md) and the `CHANGELOG.md` of the version you are migrating to. +When migrating from a previous version, refer to the [`UPGRADING.md`](../../../../UPGRADING.md) and the `CHANGELOG.md` of the version you are migrating to. diff --git a/docs/build/migrations/02-upgrade-reference.md b/docs/build/migrations/02-upgrade-reference.md index 598dd5190..aaefe25ff 100644 --- a/docs/build/migrations/02-upgrade-reference.md +++ b/docs/build/migrations/02-upgrade-reference.md @@ -1,227 +1,26 @@ # Upgrade Reference -This document provides a quick reference for the upgrades from `v0.50.x` to `v0.53.x` of Cosmos SDK. +This document provides a quick reference for the upgrades from `v0.53.x` to `v0.54.x` of Cosmos SDK. Note, always read the **App Wiring Changes** section for more information on application wiring updates. -🚨Upgrading to v0.53.x will require a **coordinated** chain upgrade.🚨 +🚨Upgrading to v0.54.x will require a **coordinated** chain upgrade.🚨 -### TLDR; +### TLDR -Unordered transactions, `x/protocolpool`, and `x/epoch` are the major new features added in v0.53.x. +**The only major feature in Cosmos SDK v0.54.x is the upgrade from CometBFT v0.x.x to CometBFT v2.** -We also added the ability to add a `CheckTx` handler and enabled ed25519 signature verification. +For a full list of changes, see the [Changelog](https://github.com/cosmos/cosmos-sdk/blob/release/v0.54.x/CHANGELOG.md). -For a full list of changes, see the [Changelog](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/CHANGELOG.md). +#### Deprecation of `TimeoutCommit` -### Unordered Transactions +CometBFT v2 has deprecated the use of `TimeoutCommit` for a new field, `NextBlockDelay`, that is part of the +`FinalizeBlockResponse` ABCI message that is returned to CometBFT via the SDK baseapp. More information from +the CometBFT repo can be found [here](https://github.com/cometbft/cometbft/blob/88ef3d267de491db98a654be0af6d791e8724ed0/spec/abci/abci%2B%2B_methods.md?plain=1#L689). -The Cosmos SDK now supports unordered transactions. _This is an opt-in feature_. +For SDK application developers and node runners, this means that the `timeout_commit` value in the `config.toml` file +is still used if `NextBlockDelay` is 0 (its default value). This means that when upgrading to Cosmos SDK v0.54.x, if +the existing `timout_commit` values that validators have been using will be maintained and have the same behavior. -Clients that use this feature may now submit their transactions in a fire-and-forget manner to chains that enabled unordered transactions. - -To submit an unordered transaction, clients must set the `unordered` flag to -`true` and ensure a reasonable `timeout_timestamp` is set. The `timeout_timestamp` is -used as a TTL for the transaction and provides replay protection. Each transaction's `timeout_timestamp` must be -unique to the account; however, the difference may be as small as a nanosecond. See [ADR-070](https://github.com/cosmos/cosmos-sdk/blob/main/docs/architecture/adr-070-unordered-transactions.md) for more details. - -Note that unordered transactions require sequence values to be zero, and will **FAIL** if a non-zero sequence value is set. -Please ensure no sequence value is set when submitting an unordered transaction. -Services that rely on prior assumptions about sequence values should be updated to handle unordered transactions. -Services should be aware that when the transaction is unordered, the transaction sequence will always be zero. - -#### Enabling Unordered Transactions - -To enable unordered transactions, supply the `WithUnorderedTransactions` option to the `x/auth` keeper: - -```go - app.AccountKeeper = authkeeper.NewAccountKeeper( - appCodec, - runtime.NewKVStoreService(keys[authtypes.StoreKey]), - authtypes.ProtoBaseAccount, - maccPerms, - authcodec.NewBech32Codec(sdk.Bech32MainPrefix), - sdk.Bech32MainPrefix, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - authkeeper.WithUnorderedTransactions(true), // new option! - ) -``` - -If using dependency injection, update the auth module config. - -```go - { - Name: authtypes.ModuleName, - Config: appconfig.WrapAny(&authmodulev1.Module{ - Bech32Prefix: "cosmos", - ModuleAccountPermissions: moduleAccPerms, - EnableUnorderedTransactions: true, // remove this line if you do not want unordered transactions. - }), - }, -``` - -By default, unordered transactions use a transaction timeout duration of 10 minutes and a default gas charge of 2240 gas units. -To modify these default values, pass in the corresponding options to the new `SigVerifyOptions` field in `x/auth's` `ante.HandlerOptions`. - -```go -options := ante.HandlerOptions{ - SigVerifyOptions: []ante.SigVerificationDecoratorOption{ - // change below as needed. - ante.WithUnorderedTxGasCost(ante.DefaultUnorderedTxGasCost), - ante.WithMaxUnorderedTxTimeoutDuration(ante.DefaultMaxTimoutDuration), - }, -} -``` - -```go -anteDecorators := []sdk.AnteDecorator{ - // ... other decorators ... - ante.NewSigVerificationDecorator(options.AccountKeeper, options.SignModeHandler, options.SigVerifyOptions...), // supply new options -} -``` - -### App Wiring Changes - -In this section, we describe the required app wiring changes to run a v0.53.x Cosmos SDK application. - -**These changes are directly applicable to your application wiring.** - -The `x/auth` module now contains a `PreBlocker` that _must_ be set in the module manager's `SetOrderPreBlockers` method. - -```go -app.ModuleManager.SetOrderPreBlockers( - upgradetypes.ModuleName, - authtypes.ModuleName, // NEW -) -``` - -That's it. - -### New Modules - -Below are some **optional** new modules you can include in your chain. -To see a full example of wiring these modules, please check out the [SimApp](https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/simapp/app.go). - -#### Epochs - -⚠️Adding this module requires a `StoreUpgrade`⚠️ - -The new, supplemental `x/epochs` module provides Cosmos SDK modules functionality to register and execute custom logic at fixed time-intervals. - -Required wiring: -- Keeper Instantiation -- StoreKey addition -- Hooks Registration -- App Module Registration -- entry in SetOrderBeginBlockers -- entry in SetGenesisModuleOrder -- entry in SetExportModuleOrder - -#### ProtocolPool - -:::warning - -Using `protocolpool` will cause the following `x/distribution` handlers to return an error: - - -**QueryService** - -- `CommunityPool` - -**MsgService** - -- `CommunityPoolSpend` -- `FundCommunityPool` - -If you have services that rely on this functionality from `x/distribution`, please update them to use the `x/protocolpool` equivalents. - -::: - -⚠️Adding this module requires a `StoreUpgrade`⚠️ - -The new, supplemental `x/protocolpool` module provides extended functionality for managing and distributing block reward revenue. - -Required wiring: -- Module Account Permissions - - protocolpooltypes.ModuleName (nil) - - protocolpooltypes.ProtocolPoolEscrowAccount (nil) -- Keeper Instantiation -- StoreKey addition -- Passing the keeper to the Distribution Keeper - - `distrkeeper.WithExternalCommunityPool(app.ProtocolPoolKeeper)` -- App Module Registration -- entry in SetOrderBeginBlockers -- entry in SetOrderEndBlockers -- entry in SetGenesisModuleOrder -- entry in SetExportModuleOrder **before `x/bank`** - -## Custom Minting Function in `x/mint` - -This release introduces the ability to configure a custom mint function in `x/mint`. The minting logic is now abstracted as a `MintFn` with a default implementation that can be overridden. - -### What’s New - -- **Configurable Mint Function:** - A new `MintFn` abstraction is introduced. By default, the module uses `DefaultMintFn`, but you can supply your own implementation. - -- **Deprecated InflationCalculationFn Parameter:** - The `InflationCalculationFn` argument previously provided to `mint.NewAppModule()` is now ignored and must be `nil`. To customize the default minter’s inflation behavior, wrap your custom function with `mintkeeper.DefaultMintFn` and pass it via the `WithMintFn` option: - -```go - mintkeeper.WithMintFn(mintkeeper.DefaultMintFn(customInflationFn)) -``` - -### How to Upgrade - -1. **Using the Default Minting Function** - - No action is needed if you’re happy with the default behavior. Make sure your application wiring initializes the MintKeeper like this: - -```go - mintKeeper := mintkeeper.NewKeeper( - appCodec, - storeService, - stakingKeeper, - accountKeeper, - bankKeeper, - authtypes.FeeCollectorName, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - ) -``` - -2. **Using a Custom Minting Function** - - To use a custom minting function, define it as follows and pass it you your mintKeeper when constructing it: - -```go -func myCustomMintFunc(ctx sdk.Context, k *mintkeeper.Keeper) { - // do minting... -} - -// ... - mintKeeper := mintkeeper.NewKeeper( - appCodec, - storeService, - stakingKeeper, - accountKeeper, - bankKeeper, - authtypes.FeeCollectorName, - authtypes.NewModuleAddress(govtypes.ModuleName).String(), - mintkeeper.WithMintFn(myCustomMintFunc), // Use custom minting function - ) -``` - -### Misc Changes - -#### Testnet's init-files Command - -Some changes were made to `testnet`'s `init-files` command to support our new testing framework, `Systemtest`. - -##### Flag Changes - -- The flag for validator count was changed from `--v` to `--validator-count`(shorthand: `-v`). - -##### Flag Additions -- `--staking-denom` allows changing the default stake denom, `stake`. -- `--commit-timeout` enables changing the commit timeout of the chain. -- `--single-host` enables running a multi-node network on a single host. This bumps each subsequent node's network addresses by 1. For example, node1's gRPC address will be 9090, node2's 9091, etc... \ No newline at end of file +For setting the field in your application, there is a new `baseapp` option, `SetNextBlockDelay` which can be passed to your application upon +initialization in `app.go`. Setting this value to any non-zero value will override anything that is set in validators' `config.toml`. diff --git a/docs/build/migrations/02-upgrading.md b/docs/build/migrations/02-upgrading.md index f44270ea6..c63f249d3 100644 --- a/docs/build/migrations/02-upgrading.md +++ b/docs/build/migrations/02-upgrading.md @@ -429,7 +429,25 @@ For ante handler construction via `ante.NewAnteHandler`, the field `ante.Handler #### `x/capability` -Capability has been moved to [IBC Go](https://github.com/cosmos/ibc-go). IBC v8 will contain the necessary changes to incorporate the new module location. +The capability module has been moved to [cosmos/ibc-go](https://github.com/cosmos/ibc-go). IBC v8 will contain the necessary changes to incorporate the new module location. In your `app.go`, you must import the capability module from the new location: + +```diff ++ "github.com/cosmos/ibc-go/modules/capability" ++ capabilitykeeper "github.com/cosmos/ibc-go/modules/capability/keeper" ++ capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" +- "github.com/cosmos/cosmos-sdk/x/capability/types" +- capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" +- capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" +``` + +Similar to previous versions, your module manager must include the capability module. + +```go +app.ModuleManager = module.NewManager( + capability.NewAppModule(encodingConfig.Codec, *app.CapabilityKeeper, true), + // remaining modules +) +``` #### `x/genutil` diff --git a/docs/build/migrations/03-upgrade-guide.md b/docs/build/migrations/03-upgrade-guide.md index 84ec6e7e0..057911c64 100644 --- a/docs/build/migrations/03-upgrade-guide.md +++ b/docs/build/migrations/03-upgrade-guide.md @@ -6,21 +6,21 @@ This guide includes one **required** change and three **optional** features. After completing this guide, applications will have: -- The `x/protocolpool` module -- The `x/epochs` module -- Unordered Transaction support +* The `x/protocolpool` module +* The `x/epochs` module +* Unordered Transaction support ## Table of Contents -- [App Wiring Changes (REQUIRED)](#app-wiring-changes-required) -- [Adding ProtocolPool Module (OPTIONAL)](#adding-protocolpool-module-optional) - - [ProtocolPool Manual Wiring](#protocolpool-manual-wiring) - - [ProtocolPool DI Wiring](#protocolpool-di-wiring) -- [Adding Epochs Module (OPTIONAL)](#adding-epochs-module-optional) - - [Epochs Manual Wiring](#epochs-manual-wiring) - - [Epochs DI Wiring](#epochs-di-wiring) -- [Enable Unordered Transactions (OPTIONAL)](#enable-unordered-transactions-optional) -- [Upgrade Handler](#upgrade-handler) +* [App Wiring Changes (REQUIRED)](#app-wiring-changes-required) +* [Adding ProtocolPool Module (OPTIONAL)](#adding-protocolpool-module-optional) + * [ProtocolPool Manual Wiring](#protocolpool-manual-wiring) + * [ProtocolPool DI Wiring](#protocolpool-di-wiring) +* [Adding Epochs Module (OPTIONAL)](#adding-epochs-module-optional) + * [Epochs Manual Wiring](#epochs-manual-wiring) + * [Epochs DI Wiring](#epochs-di-wiring) +* [Enable Unordered Transactions (OPTIONAL)](#enable-unordered-transactions-optional) +* [Upgrade Handler](#upgrade-handler) ## App Wiring Changes **REQUIRED** @@ -41,12 +41,12 @@ Using an external community pool such as `x/protocolpool` will cause the followi **QueryService** -- `CommunityPool` +* `CommunityPool` **MsgService** -- `CommunityPoolSpend` -- `FundCommunityPool` +* `CommunityPoolSpend` +* `FundCommunityPool` If your services depend on this functionality from `x/distribution`, please update them to use either `x/protocolpool` or your custom external community pool alternatives. @@ -449,7 +449,7 @@ options := ante.HandlerOptions{ SigVerifyOptions: []ante.SigVerificationDecoratorOption{ // change below as needed. ante.WithUnorderedTxGasCost(ante.DefaultUnorderedTxGasCost), - ante.WithMaxUnorderedTxTimeoutDuration(ante.DefaultMaxTimoutDuration), + ante.WithMaxUnorderedTxTimeoutDuration(ante.DefaultMaxTimeoutDuration), }, } ``` @@ -500,4 +500,4 @@ func (app SimApp) RegisterUpgradeHandlers() { app.SetStoreLoader(upgradetypes.UpgradeStoreLoader(upgradeInfo.Height, &storeUpgrades)) } } -``` \ No newline at end of file +``` diff --git a/docs/build/modules/README.md b/docs/build/modules/README.md index 61bc071b1..12a128c3a 100644 --- a/docs/build/modules/README.md +++ b/docs/build/modules/README.md @@ -41,10 +41,10 @@ capabilities of your blockchain or further specialize it. The following modules are deprecated. They will no longer be maintained and eventually will be removed in an upcoming release of the Cosmos SDK per our [release process](https://github.com/cosmos/cosmos-sdk/blob/main/RELEASE_PROCESS.md). -* [Crisis](./crisis/README.md) - *Deprecated* halting the blockchain under certain circumstances (e.g. if an invariant is broken). -* [Params](./params/README.md) - *Deprecated* Globally available parameter store. -* [NFT](./nft/README.md) - *Deprecated* NFT module implemented based on [ADR43](https://docs.cosmos.network/main/architecture/adr-043-nft-module.html). This module will be moved to the `cosmos-sdk-legacy` repo for use. -* [Group](./group/README.md) - *Deprecated* Allows for the creation and management of on-chain multisig accounts. This module will be moved to the `cosmos-sdk-legacy` repo for legacy use. +* [Crisis](./crisis/README.md) - _Deprecated_ halting the blockchain under certain circumstances (e.g. if an invariant is broken). +* [Params](./params/README.md) - _Deprecated_ Globally available parameter store. +* [NFT](./nft/README.md) - _Deprecated_ NFT module implemented based on [ADR43](https://docs.cosmos.network/main/build/architecture/adr-043-nft-module). This module will be moved to the `cosmos-sdk-legacy` repo for use. +* [Group](./group/README.md) - _Deprecated_ Allows for the creation and management of on-chain multisig accounts. This module will be moved to the `cosmos-sdk-legacy` repo for legacy use. To learn more about the process of building modules, visit the [building modules reference documentation](https://docs.cosmos.network/main/building-modules/intro). diff --git a/docs/build/modules/auth/1-vesting.md b/docs/build/modules/auth/1-vesting.md index 892013065..924580671 100644 --- a/docs/build/modules/auth/1-vesting.md +++ b/docs/build/modules/auth/1-vesting.md @@ -35,13 +35,13 @@ This specification defines the vesting account implementation that is used by th For all vesting accounts, the owner of the vesting account is able to delegate and undelegate from validators, however they cannot transfer coins to another account until those coins are vested. This specification allows for four different kinds of vesting: * Delayed vesting, where all coins are vested once `ET` is reached. -* Continous vesting, where coins begin to vest at `ST` and vest linearly with respect to time until `ET` is reached -* Periodic vesting, where coins begin to vest at `ST` and vest periodically according to number of periods and the vesting amount per period. The number of periods, length per period, and amount per period are configurable. A periodic vesting account is distinguished from a continuous vesting account in that coins can be released in staggered tranches. For example, a periodic vesting account could be used for vesting arrangements where coins are relased quarterly, yearly, or over any other function of tokens over time. +* Continuous vesting, where coins begin to vest at `ST` and vest linearly with respect to time until `ET` is reached +* Periodic vesting, where coins begin to vest at `ST` and vest periodically according to number of periods and the vesting amount per period. The number of periods, length per period, and amount per period are configurable. A periodic vesting account is distinguished from a continuous vesting account in that coins can be released in staggered tranches. For example, a periodic vesting account could be used for vesting arrangements where coins are released quarterly, yearly, or over any other function of tokens over time. * Permanent locked vesting, where coins are locked forever. Coins in this account can still be used for delegating and for governance votes even while locked. ## Note -Vesting accounts can be initialized with some vesting and non-vesting coins. The non-vesting coins would be immediately transferable. DelayedVesting ContinuousVesting, PeriodicVesting and PermenantVesting accounts can be created with normal messages after genesis. Other types of vesting accounts must be created at genesis, or as part of a manual network upgrade. The current specification only allows for _unconditional_ vesting (ie. there is no possibility of reaching `ET` and +Vesting accounts can be initialized with some vesting and non-vesting coins. The non-vesting coins would be immediately transferable. DelayedVesting ContinuousVesting, PeriodicVesting and PermanentVesting accounts can be created with normal messages after genesis. Other types of vesting accounts must be created at genesis, or as part of a manual network upgrade. The current specification only allows for _unconditional_ vesting (ie. there is no possibility of reaching `ET` and having coins fail to vest). ## Vesting Account Types @@ -543,7 +543,7 @@ V' = 0 V' = 25 ``` -3. During vesting period 2, 5 coins are transfered and 5 coins are delegated +3. During vesting period 2, 5 coins are transferred and 5 coins are delegated ```text DV = 5 @@ -591,7 +591,7 @@ simd tx vesting --help #### create-periodic-vesting-account -The `create-periodic-vesting-account` command creates a new vesting account funded with an allocation of tokens, where a sequence of coins and period length in seconds. Periods are sequential, in that the duration of of a period only starts at the end of the previous period. The duration of the first period starts upon account creation. +The `create-periodic-vesting-account` command creates a new vesting account funded with an allocation of tokens, where a sequence of coins and period length in seconds. Periods are sequential, in that the duration of a period only starts at the end of the previous period. The duration of the first period starts upon account creation. ```bash simd tx vesting create-periodic-vesting-account [to_address] [periods_json_file] [flags] @@ -605,7 +605,7 @@ simd tx vesting create-periodic-vesting-account cosmos1.. periods.json #### create-vesting-account -The `create-vesting-account` command creates a new vesting account funded with an allocation of tokens. The account can either be a delayed or continuous vesting account, which is determined by the '--delayed' flag. All vesting accouts created will have their start time set by the committed block's time. The end_time must be provided as a UNIX epoch timestamp. +The `create-vesting-account` command creates a new vesting account funded with an allocation of tokens. The account can either be a delayed or continuous vesting account, which is determined by the '--delayed' flag. All vesting accounts created will have their start time set by the committed block's time. The end_time must be provided as a UNIX epoch timestamp. ```bash simd tx vesting create-vesting-account [to_address] [amount] [end_time] [flags] diff --git a/docs/build/modules/auth/2-tx.md b/docs/build/modules/auth/2-tx.md index 378b60e55..78da05035 100644 --- a/docs/build/modules/auth/2-tx.md +++ b/docs/build/modules/auth/2-tx.md @@ -111,12 +111,12 @@ simd query blocks --query 'message.sender=cosmos...' --page 1 --limit 30 #### Transactions -The `x/auth/tx` module provides a convinient CLI command for decoding and encoding transactions. +The `x/auth/tx` module provides a convenient CLI command for decoding and encoding transactions. #### `encode` The `encode` command encodes a transaction created with the `--generate-only` flag or signed with the sign command. -The transaction is seralized it to Protobuf and returned as base64. +The transaction is serialized it to Protobuf and returned as base64. ```bash $ simd tx encode tx.json diff --git a/docs/build/modules/auth/README.md b/docs/build/modules/auth/README.md index c51d10634..bd9f18a37 100644 --- a/docs/build/modules/auth/README.md +++ b/docs/build/modules/auth/README.md @@ -32,7 +32,7 @@ This module is used in the Cosmos Hub. ## Concepts -**Note:** The auth module is different from the [authz module](../modules/authz/). +**Note:** The auth module is different from the [authz module](../authz/). The differences are: diff --git a/docs/build/modules/authz/README.md b/docs/build/modules/authz/README.md index a863472ac..fc7123825 100644 --- a/docs/build/modules/authz/README.md +++ b/docs/build/modules/authz/README.md @@ -38,7 +38,7 @@ on behalf of one account to other accounts. The design is defined in the [ADR 03 A *grant* is an allowance to execute a Msg by the grantee on behalf of the granter. Authorization is an interface that must be implemented by a concrete authorization logic to validate and execute grants. Authorizations are extensible and can be defined for any Msg service method even outside of the module where the Msg method is defined. See the `SendAuthorization` example in the next section for more details. -**Note:** The authz module is different from the [auth (authentication)](../modules/auth/) module that is responsible for specifying the base transaction and account types. +**Note:** The authz module is different from the [auth (authentication)](../auth/) module that is responsible for specifying the base transaction and account types. ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/authz/authorizations.go#L11-L25 @@ -96,7 +96,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/staking/types/authz.go#L In order to prevent DoS attacks, granting `StakeAuthorization`s with `x/authz` incurs gas. `StakeAuthorization` allows you to authorize another account to delegate, undelegate, or redelegate to validators. The authorizer can define a list of validators they allow or deny delegations to. The Cosmos SDK iterates over these lists and charge 10 gas for each validator in both of the lists. -Since the state maintaining a list for granter, grantee pair with same expiration, we are iterating over the list to remove the grant (incase of any revoke of paritcular `msgType`) from the list and we are charging 20 gas per iteration. +Since the state maintaining a list for granter, grantee pair with same expiration, we are iterating over the list to remove the grant (incase of any revoke of particular `msgType`) from the list and we are charging 20 gas per iteration. ## State @@ -122,7 +122,7 @@ In `EndBlock` (which runs for every block) we continuously check and prune the e https://github.com/cosmos/cosmos-sdk/blob/5f4ddc6f80f9707320eec42182184207fff3833a/x/authz/keeper/keeper.go#L378-L403 ``` -* GrantQueue: `0x02 | expiration_bytes | granter_address_len (1 byte) | granter_address_bytes | grantee_address_len (1 byte) | grantee_address_bytes -> ProtocalBuffer(GrantQueueItem)` +* GrantQueue: `0x02 | expiration_bytes | granter_address_len (1 byte) | granter_address_bytes | grantee_address_len (1 byte) | grantee_address_bytes -> ProtocolBuffer(GrantQueueItem)` The `expiration_bytes` are the expiration date in UTC with the format `"2006-01-02T15:04:05.000000000"`. @@ -255,22 +255,27 @@ The `grant` command allows a granter to grant an authorization to a grantee. ```bash simd tx authz grant --from [flags] ``` -- The `send` authorization_type refers to the built-in `SendAuthorization` type. The custom flags available are `spend-limit` (required) and `allow-list` (optional) , documented [here](#SendAuthorization) + +* The `send` authorization_type refers to the built-in `SendAuthorization` type. The custom flags available are `spend-limit` (required) and `allow-list` (optional) , documented [here](#sendauthorization) Example: ```bash simd tx authz grant cosmos1.. send --spend-limit=100stake --allow-list=cosmos1...,cosmos2... --from=cosmos1.. ``` -- The `generic` authorization_type refers to the built-in `GenericAuthorization` type. The custom flag available is `msg-type` ( required) documented [here](#GenericAuthorization). + +* The `generic` authorization_type refers to the built-in `GenericAuthorization` type. The custom flag available is `msg-type` (required) documented [here](#genericauthorization). > Note: `msg-type` is any valid Cosmos SDK `Msg` type url. Example: + ```bash simd tx authz grant cosmos1.. generic --msg-type=/cosmos.bank.v1beta1.MsgSend --from=cosmos1.. ``` -- The `delegate`,`unbond`,`redelegate` authorization_types refer to the built-in `StakeAuthorization` type. The custom flags available are `spend-limit` (optional), `allowed-validators` (optional) and `deny-validators` (optional) documented [here](#StakeAuthorization). + +* The `delegate`,`unbond`,`redelegate` authorization_types refer to the built-in `StakeAuthorization` type. The custom flags available are `spend-limit` (optional), `allowed-validators` (optional) and `deny-validators` (optional) documented [here](#stakeauthorization). + > Note: `allowed-validators` and `deny-validators` cannot both be empty. `spend-limit` represents the `MaxTokens` Example: diff --git a/docs/build/modules/bank/README.md b/docs/build/modules/bank/README.md index 6f0a701bc..62a781da6 100644 --- a/docs/build/modules/bank/README.md +++ b/docs/build/modules/bank/README.md @@ -1002,7 +1002,7 @@ Example Output: ### SendEnabled -The `SendEnabled` enpoints allows users to query the SendEnabled entries of the `bank` module. +The `SendEnabled` endpoints allows users to query the SendEnabled entries of the `bank` module. Any denominations NOT returned, use the `Params.DefaultSendEnabled` value. diff --git a/docs/build/modules/circuit/README.md b/docs/build/modules/circuit/README.md index f3b753896..253ca497d 100644 --- a/docs/build/modules/circuit/README.md +++ b/docs/build/modules/circuit/README.md @@ -21,7 +21,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.50.1/baseapp/msg_service_router.go# ``` :::note -The `CircuitBreakerDecorator` works for most use cases, but [does not check the inner messages of a transaction](https://docs.cosmos.network/main/learn/beginner/tx-lifecycle#antehandler). This some transactions (such as `x/authz` transactions or some `x/gov` transactions) may pass the ante handler. **This does not affect the circuit breaker** as the message router check will still fail the transaction. +The `CircuitBreakerDecorator` works for most use cases, but [does not check the inner messages of a transaction](https://docs.cosmos.network/main/learn/beginner/tx-lifecycle#antehandler). This means some transactions (such as `x/authz` transactions or some `x/gov` transactions) may pass the ante handler. **This does not affect the circuit breaker** as the message router check will still fail the transaction. This tradeoff is to avoid introducing more dependencies in the `x/circuit` module. Chains can re-define the `CircuitBreakerDecorator` to check for inner messages if they wish to do so. ::: @@ -91,7 +91,7 @@ Reset is called by an authorized account to enable execution for a specific msgU ```protobuf // ResetCircuitBreaker resumes processing of Msg's in the state machine that - // have been been paused using TripCircuitBreaker. + // have been paused using TripCircuitBreaker. rpc ResetCircuitBreaker(MsgResetCircuitBreaker) returns (MsgResetCircuitBreakerResponse); ``` @@ -168,3 +168,92 @@ The circuit module emits the following events: * `DisableListPrefix` - `0x02` ## Client - list and describe CLI commands and gRPC and REST endpoints + +## Examples: Using Circuit Breaker CLI Commands + +This section provides practical examples for using the Circuit Breaker module through the command-line interface (CLI). These examples demonstrate how to authorize accounts, disable (trip) specific message types, and re-enable (reset) them when needed. + +### Querying Circuit Breaker Permissions + +Check an account's current circuit breaker permissions: + +```bash +# Query permissions for a specific account + query circuit account-permissions + +# Example: +simd query circuit account-permissions cosmos1... +``` + +Check which message types are currently disabled: + +```bash +# Query all disabled message types + query circuit disabled-list + +# Example: +simd query circuit disabled-list +``` + +### Authorizing an Account as Circuit Breaker + +Only a super-admin or the module authority (typically the governance module account) can grant circuit breaker permissions to other accounts: + +```bash +# Grant LEVEL_ALL_MSGS permission (can disable any message type) + tx circuit authorize --level=ALL_MSGS --from= --gas=auto --gas-adjustment=1.5 + +# Grant LEVEL_SOME_MSGS permission (can only disable specific message types) + tx circuit authorize --level=SOME_MSGS --limit-type-urls="/cosmos.bank.v1beta1.MsgSend,/cosmos.staking.v1beta1.MsgDelegate" --from= --gas=auto --gas-adjustment=1.5 + +# Grant LEVEL_SUPER_ADMIN permission (can disable messages and authorize other accounts) + tx circuit authorize --level=SUPER_ADMIN --from= --gas=auto --gas-adjustment=1.5 +``` + +### Disabling Message Processing (Trip) + +Disable specific message types to prevent their execution (requires authorization): + +```bash +# Disable a single message type + tx circuit trip --type-urls="/cosmos.bank.v1beta1.MsgSend" --from= --gas=auto --gas-adjustment=1.5 + +# Disable multiple message types + tx circuit trip --type-urls="/cosmos.bank.v1beta1.MsgSend,/cosmos.staking.v1beta1.MsgDelegate" --from= --gas=auto --gas-adjustment=1.5 + +# Disable all message types (emergency measure) + tx circuit trip --from= --gas=auto --gas-adjustment=1.5 +``` + +### Re-enabling Message Processing (Reset) + +Re-enable previously disabled message types (requires authorization): + +```bash +# Re-enable a single message type + tx circuit reset --type-urls="/cosmos.bank.v1beta1.MsgSend" --from= --gas=auto --gas-adjustment=1.5 + +# Re-enable multiple message types + tx circuit reset --type-urls="/cosmos.bank.v1beta1.MsgSend,/cosmos.staking.v1beta1.MsgDelegate" --from= --gas=auto --gas-adjustment=1.5 + +# Re-enable all disabled message types + tx circuit reset --from= --gas=auto --gas-adjustment=1.5 +``` + +### Usage in Emergency Scenarios + +In case of a critical vulnerability in a specific message type: + +1. Quickly disable the vulnerable message type: + + ```bash + tx circuit trip --type-urls="/cosmos.vulnerable.v1beta1.MsgVulnerable" --from= --gas=auto --gas-adjustment=1.5 + ``` + +2. After a fix is deployed, re-enable the message type: + + ```bash + tx circuit reset --type-urls="/cosmos.vulnerable.v1beta1.MsgVulnerable" --from= --gas=auto --gas-adjustment=1.5 + ``` + +This allows chains to surgically disable problematic functionality without halting the entire chain, providing time for developers to implement and deploy fixes. diff --git a/docs/build/modules/crisis/README.md b/docs/build/modules/crisis/README.md index b75a5ab6b..631f9d857 100644 --- a/docs/build/modules/crisis/README.md +++ b/docs/build/modules/crisis/README.md @@ -66,7 +66,7 @@ The crisis module emits the following events: ### Handlers -#### MsgVerifyInvariance +#### MsgVerifyInvariant | Type | Attribute Key | Attribute Value | |-----------|---------------|------------------| diff --git a/docs/build/modules/distribution/README.md b/docs/build/modules/distribution/README.md index 8259b60e0..0563c5d72 100644 --- a/docs/build/modules/distribution/README.md +++ b/docs/build/modules/distribution/README.md @@ -291,12 +291,12 @@ When using an external community pool with `x/distribution`, the following handl **QueryService** -- `CommunityPool` +* `CommunityPool` **MsgService** -- `CommunityPoolSpend` -- `FundCommunityPool` +* `CommunityPoolSpend` +* `FundCommunityPool` If you have services that rely on this functionality from `x/distribution`, please update them to use the `x/protocolpool` equivalents. diff --git a/docs/build/modules/epochs/README.md b/docs/build/modules/epochs/README.md index 7b0b0b285..d56970668 100644 --- a/docs/build/modules/epochs/README.md +++ b/docs/build/modules/epochs/README.md @@ -6,7 +6,7 @@ sidebar_position: 1 ## Abstract -Often in the SDK, we would like to run certain code every-so often. The +Often in the SDK, we would like to run certain code every so often. The purpose of `epochs` module is to allow other modules to set that they would like to be signaled once every period. So another module can specify it wants to execute code once a week, starting at UTC-time = x. diff --git a/docs/build/modules/evidence/README.md b/docs/build/modules/evidence/README.md index 00c4abf41..aba2e10e6 100644 --- a/docs/build/modules/evidence/README.md +++ b/docs/build/modules/evidence/README.md @@ -271,7 +271,7 @@ The `evidence` command allows users to list all evidence or evidence by hash. Usage: ```bash -simd query evidence evidence [flags] +simd query evidence [flags] ``` To query evidence by hash diff --git a/docs/build/modules/feegrant/README.md b/docs/build/modules/feegrant/README.md index 07524449a..0ac1c2985 100644 --- a/docs/build/modules/feegrant/README.md +++ b/docs/build/modules/feegrant/README.md @@ -152,7 +152,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.47.0-rc1/x/feegrant/feegrant.pb.go# ### FeeAllowanceQueue -Fee Allowances queue items are identified by combining the `FeeAllowancePrefixQueue` (i.e., 0x01), `expiration`, `grantee` (the account address of fee allowance grantee), `granter` (the account address of fee allowance granter). Endblocker checks `FeeAllowanceQueue` state for the expired grants and prunes them from `FeeAllowance` if there are any found. +Fee Allowances queue items are identified by combining the `FeeAllowancePrefixQueue` (i.e., 0x01), `expiration`, `grantee` (the account address of fee allowance grantee), `granter` (the account address of fee allowance granter). Endblocker checks `FeeAllowanceQueue` state for the expired grants and prunes them from `FeeAllowance` if there are any found. Fee allowance queue keys are stored in the state as follows: diff --git a/docs/build/modules/genutil/README.md b/docs/build/modules/genutil/README.md index 45cb45355..34bc79d5c 100644 --- a/docs/build/modules/genutil/README.md +++ b/docs/build/modules/genutil/README.md @@ -16,7 +16,7 @@ The `genutil` package contains a variety of genesis utility functionalities for ## Genesis Genutil contains the data structure that defines an application genesis. -An application genesis consist of a consensus genesis (g.e. CometBFT genesis) and application related genesis data. +An application genesis consists of a consensus genesis (g.e. CometBFT genesis) and application related genesis data. ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-rc.0/x/genutil/types/genesis.go#L24-L34 diff --git a/docs/build/modules/gov/README.md b/docs/build/modules/gov/README.md index 66979627e..7b10700c1 100644 --- a/docs/build/modules/gov/README.md +++ b/docs/build/modules/gov/README.md @@ -191,9 +191,9 @@ https://github.com/cosmos/cosmos-sdk/blob/main/x/gov/keeper/tally.go#L15-L24 This gives developers a more expressive way to handle governance on their appchains. Developers can now build systems with: -- Quadratic Voting -- Time-weighted Voting -- Reputation-Based voting +* Quadratic Voting +* Time-weighted Voting +* Reputation-Based voting ##### Example @@ -284,7 +284,7 @@ There are three parameters that define if the deposit of a proposal should be bu ### Constitution -`Constitution` is found in the genesis state. It is a string field intended to be used to descibe the purpose of a particular blockchain, and its expected norms. A few examples of how the constitution field can be used: +`Constitution` is found in the genesis state. It is a string field intended to be used to describe the purpose of a particular blockchain, and its expected norms. A few examples of how the constitution field can be used: * define the purpose of the chain, laying a foundation for its future development * set expectations for delegators @@ -299,9 +299,9 @@ Since this is more of a social feature than a technical feature, we'll now get i * In the event of an economic emergency, what should validators do? * Terra crash of May, 2022, saw validators choose to run a new binary with code that had not been approved by governance, because the governance token had been inflated to nothing. * What is the purpose of the chain, specifically? - * best example of this is the Cosmos hub, where different founding groups, have different interpertations of the purpose of the network. + * best example of this is the Cosmos hub, where different founding groups, have different interpretations of the purpose of the network. -This genesis entry, "constitution" hasn't been designed for existing chains, who should likely just ratify a constitution using their governance system. Instead, this is for new chains. It will allow for validators to have a much clearer idea of purpose and the expecations placed on them while operating thier nodes. Likewise, for community members, the constitution will give them some idea of what to expect from both the "chain team" and the validators, respectively. +This genesis entry, "constitution" hasn't been designed for existing chains, who should likely just ratify a constitution using their governance system. Instead, this is for new chains. It will allow for validators to have a much clearer idea of purpose and the expectations placed on them while operating their nodes. Likewise, for community members, the constitution will give them some idea of what to expect from both the "chain team" and the validators, respectively. This constitution is designed to be immutable, and placed only in genesis, though that could change over time by a pull request to the cosmos-sdk that allows for the constitution to be changed by governance. Communities whishing to make amendments to their original constitution should use the governance mechanism and a "signaling proposal" to do exactly that. @@ -313,7 +313,7 @@ As a chain developer, you decide that you'd like to provide clarity to your key * token holders * developers (yourself) -You use the constitution to immutably store some Markdown in genesis, so that when difficult questions come up, the constutituon can provide guidance to the community. +You use the constitution to immutably store some Markdown in genesis, so that when difficult questions come up, the constitution can provide guidance to the community. ### Proposals @@ -401,7 +401,7 @@ const ( VoteAbstain = 0x4 ) -type ProposalType string +type ProposalType string const ( ProposalTypePlainText = "Text" @@ -719,7 +719,7 @@ simd query gov --help The `deposit` command allows users to query a deposit for a given proposal from a given depositor. ```bash -simd query gov deposit [proposal-id] [depositer-addr] [flags] +simd query gov deposit [proposal-id] [depositor-addr] [flags] ``` Example: @@ -1092,7 +1092,7 @@ where `proposal.json` contains: "messages": [ { "@type": "/cosmos.bank.v1beta1.MsgSend", - "from_address": "cosmos1...", // The gov module module address + "from_address": "cosmos1...", // The gov module address "to_address": "cosmos1...", "amount":[{"denom": "stake","amount": "10"}] } @@ -1149,7 +1149,7 @@ simd tx gov submit-legacy-proposal param-change proposal.json --from cosmos1.. #### cancel-proposal -Once proposal is canceled, from the deposits of proposal `deposits * proposal_cancel_ratio` will be burned or sent to `ProposalCancelDest` address , if `ProposalCancelDest` is empty then deposits will be burned. The `remaining deposits` will be sent to depositers. +Once proposal is canceled, from the deposits of proposal `deposits * proposal_cancel_ratio` will be burned or sent to `ProposalCancelDest` address , if `ProposalCancelDest` is empty then deposits will be burned. The `remaining deposits` will be sent to depositors. ```bash simd tx gov cancel-proposal [proposal-id] [flags] @@ -2528,7 +2528,7 @@ Example Output: ## Metadata -The gov module has two locations for metadata where users can provide further context about the on-chain actions they are taking. By default all metadata fields have a 255 character length field where metadata can be stored in json format, either on-chain or off-chain depending on the amount of data required. Here we provide a recommendation for the json structure and where the data should be stored. There are two important factors in making these recommendations. First, that the gov and group modules are consistent with one another, note the number of proposals made by all groups may be quite large. Second, that client applications such as block explorers and governance interfaces have confidence in the consistency of metadata structure accross chains. +The gov module has two locations for metadata where users can provide further context about the on-chain actions they are taking. By default all metadata fields have a 255 character length field where metadata can be stored in json format, either on-chain or off-chain depending on the amount of data required. Here we provide a recommendation for the json structure and where the data should be stored. There are two important factors in making these recommendations. First, that the gov and group modules are consistent with one another, note the number of proposals made by all groups may be quite large. Second, that client applications such as block explorers and governance interfaces have confidence in the consistency of metadata structure across chains. ### Proposal diff --git a/docs/build/modules/group/README.md b/docs/build/modules/group/README.md index ace764f33..98fd7ba91 100644 --- a/docs/build/modules/group/README.md +++ b/docs/build/modules/group/README.md @@ -87,7 +87,7 @@ A decision policy is the mechanism by which members of a group can vote on proposals, as well as the rules that dictate whether a proposal should pass or not based on its tally outcome. -All decision policies generally would have a mininum execution period and a +All decision policies generally would have a minimum execution period and a maximum voting window. The minimum execution period is the minimum amount of time that must pass after submission in order for a proposal to potentially be executed, and it may be set to 0. The maximum voting window is the maximum time after submission that a proposal may @@ -212,7 +212,7 @@ Proposals and votes are automatically pruned to avoid state bloat. Votes are pruned: * either after a successful tally, i.e. a tally whose result passes the decision - policy's rules, which can be trigged by a `Msg/Exec` or a + policy's rules, which can be triggered by a `Msg/Exec` or a `Msg/{SubmitProposal,Vote}` with the `Exec` field set, * or on `EndBlock` right after the proposal's voting period end. This applies to proposals with status `aborted` or `withdrawn` too. diff --git a/docs/build/modules/params/README.md b/docs/build/modules/params/README.md index 372f0ce6e..10b47da44 100644 --- a/docs/build/modules/params/README.md +++ b/docs/build/modules/params/README.md @@ -76,4 +76,4 @@ Modules often define parameters as a proto message. The generated struct can imp * `KeyTable.RegisterParamSet()`: registers all parameters in the struct * `Subspace.{Get, Set}ParamSet()`: Get to & Set from the struct -The implementor should be a pointer in order to use `GetParamSet()`. +The implementer should be a pointer in order to use `GetParamSet()`. diff --git a/docs/build/modules/protocolpool/README.md b/docs/build/modules/protocolpool/README.md index c7e379d67..d88b1ee12 100644 --- a/docs/build/modules/protocolpool/README.md +++ b/docs/build/modules/protocolpool/README.md @@ -10,7 +10,7 @@ sidebar_position: 1 This module is `supplemental`; it is not required to run a Cosmos SDK chain. `x/protocolpool` enhances the community pool functionality provided by `x/distribution` and enables custom modules to further extend the community pool. -Note: _as long as an external commmunity pool keeper (here, `x/protocolpool`) is wired in DI configs, `x/distribution` will automatically use it for its external pool._ +Note: _as long as an external community pool keeper (here, `x/protocolpool`) is wired in DI configs, `x/distribution` will automatically use it for its external pool._ ## Usage Limitations @@ -18,12 +18,12 @@ The following `x/distribution` handlers will now return an error when the `proto **QueryService** -- `CommunityPool` +* `CommunityPool` **MsgService** -- `CommunityPoolSpend` -- `FundCommunityPool` +* `CommunityPoolSpend` +* `FundCommunityPool` If you have services that rely on this functionality from `x/distribution`, please update them to use the `x/protocolpool` equivalents. @@ -124,9 +124,9 @@ https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/proto/cosmos/protocolp The message will fail under the following conditions: -- The recipient address is empty or restricted. -- The percentage is zero/negative/greater than one. -- The Expiry time is less than the current block time. +* The recipient address is empty or restricted. +* The percentage is zero/negative/greater than one. +* The Expiry time is less than the current block time. :::warning If two continuous fund proposals to the same address are created, the previous ContinuousFund will be updated with the new ContinuousFund. @@ -146,8 +146,8 @@ https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/x/protocolpool/proto/c The message will fail under the following conditions: -- The recipient address is empty or restricted. -- The ContinuousFund for the recipient does not exist. +* The recipient address is empty or restricted. +* The ContinuousFund for the recipient does not exist. ```go reference https://github.com/cosmos/cosmos-sdk/blob/release/v0.53.x/x/protocolpool/keeper/msg_server.go#L188-L226 diff --git a/docs/build/modules/slashing/README.md b/docs/build/modules/slashing/README.md index 591a9a73a..5bf95b80f 100644 --- a/docs/build/modules/slashing/README.md +++ b/docs/build/modules/slashing/README.md @@ -53,7 +53,7 @@ blocks. Validators who are _bonded_ are _at stake_, meaning that part or all of their stake and their delegators' stake is at risk if they commit a protocol fault. For each of these validators we keep a `ValidatorSigningInfo` record that contains -information partaining to validator's liveness and other infraction related +information pertaining to validator's liveness and other infraction related attributes. ### Tombstone Caps @@ -62,7 +62,7 @@ In order to mitigate the impact of initially likely categories of non-malicious protocol faults, the Cosmos Hub implements for each validator a _tombstone_ cap, which only allows a validator to be slashed once for a double sign fault. For example, if you misconfigure your HSM and double-sign a bunch of -old blocks, you'll only be punished for the first double-sign (and then immediately tombstombed). This will still be quite expensive and desirable to avoid, but tombstone caps +old blocks, you'll only be punished for the first double-sign (and then immediately tombstoned). This will still be quite expensive and desirable to avoid, but tombstone caps somewhat blunt the economic impact of unintentional misconfiguration. Liveness faults do not have caps, as they can't stack upon each other. Liveness bugs are "detected" as soon as the infraction occurs, and the validators are immediately put in jail, so it is not possible for them to commit multiple liveness faults without unjailing in between. @@ -226,7 +226,7 @@ greater than `minHeight` and the validator's `MissedBlocksCounter` is greater th for `DowntimeJailDuration`, and have the following values reset: `MissedBlocksBitArray`, `MissedBlocksCounter`, and `IndexOffset`. -**Note**: Liveness slashes do **NOT** lead to a tombstombing. +**Note**: Liveness slashes do **NOT** lead to a tombstoning. ```go height := block.Height @@ -234,7 +234,7 @@ height := block.Height for vote in block.LastCommitInfo.Votes { signInfo := GetValidatorSigningInfo(vote.Validator.Address) - // This is a relative index, so we counts blocks the validator SHOULD have + // This is a relative index, so we count blocks the validator SHOULD have // signed. We use the 0-value default signing info if not present, except for // start height. index := signInfo.IndexOffset % SignedBlocksWindow() @@ -331,7 +331,7 @@ onValidatorBonded(address sdk.ValAddress) IndexOffset : 0, JailedUntil : time.Unix(0, 0), Tombstone : false, - MissedBloskCounter : 0 + MissedBlockCounter : 0 } else { signingInfo.StartHeight = CurrentHeight } diff --git a/docs/build/modules/staking/README.md b/docs/build/modules/staking/README.md index c011a593d..afed4beef 100644 --- a/docs/build/modules/staking/README.md +++ b/docs/build/modules/staking/README.md @@ -464,15 +464,15 @@ When a Validator is slashed, the following occurs: * The total `slashAmount` is calculated as the `slashFactor` (a chain parameter) \* `TokensFromConsensusPower`, the total number of tokens bonded to the validator at the time of the infraction. -* Every unbonding delegation and pseudo-unbonding redelegation such that the infraction occured before the unbonding or +* Every unbonding delegation and pseudo-unbonding redelegation such that the infraction occurred before the unbonding or redelegation began from the validator are slashed by the `slashFactor` percentage of the initialBalance. * Each amount slashed from redelegations and unbonding delegations is subtracted from the total slash amount. -* The `remaingSlashAmount` is then slashed from the validator's tokens in the `BondedPool` or +* The `remainingSlashAmount` is then slashed from the validator's tokens in the `BondedPool` or `NonBondedPool` depending on the validator's status. This reduces the total supply of tokens. In the case of a slash due to any infraction that requires evidence to submitted (for example double-sign), the slash -occurs at the block where the evidence is included, not at the block where the infraction occured. +occurs at the block where the evidence is included, not at the block where the infraction occurred. Put otherwise, validators are not slashed retroactively, only when they are caught. #### Slash Unbonding Delegation @@ -1631,7 +1631,7 @@ simd tx staking edit-validator [flags] Example: ```bash -simd tx staking edit-validator --moniker "new_moniker_name" --website "new_webiste_url" --from mykey +simd tx staking edit-validator --moniker "new_moniker_name" --website "new_website_url" --from mykey ``` ##### redelegate @@ -2312,7 +2312,7 @@ A user can query the `staking` module using REST endpoints. #### DelegatorDelegations -The `DelegtaorDelegations` REST endpoint queries all delegations of a given delegator address. +The `DelegatorDelegations` REST endpoint queries all delegations of a given delegator address. ```bash /cosmos/staking/v1beta1/delegations/{delegatorAddr} diff --git a/docs/build/modules/upgrade/README.md b/docs/build/modules/upgrade/README.md index 46e4061a7..396b8fb1d 100644 --- a/docs/build/modules/upgrade/README.md +++ b/docs/build/modules/upgrade/README.md @@ -22,9 +22,9 @@ recover from. * [State](#state) * [Events](#events) * [Client](#client) - * [CLI](#cli) - * [REST](#rest) - * [gRPC](#grpc) + * [CLI](#cli) + * [REST](#rest) + * [gRPC](#grpc) * [Resources](#resources) ## Concepts @@ -90,7 +90,7 @@ func UpgradeStoreLoader (upgradeHeight int64, storeUpgrades *store.StoreUpgrades If there's a planned upgrade and the upgrade height is reached, the old binary writes `Plan` to the disk before panicking. This information is critical to ensure the `StoreUpgrades` happens smoothly at correct height and -expected upgrade. It eliminiates the chances for the new binary to execute `StoreUpgrades` multiple +expected upgrade. It eliminates the chances for the new binary to execute `StoreUpgrades` multiple times everytime on restart. Also if there are multiple upgrades planned on same height, the `Name` will ensure these `StoreUpgrades` takes place only in planned upgrade handler. diff --git a/docs/build/packages/02-collections.md b/docs/build/packages/02-collections.md index b8d8a62f1..d8f9c17e2 100644 --- a/docs/build/packages/02-collections.md +++ b/docs/build/packages/02-collections.md @@ -423,7 +423,7 @@ The third type of collection is the `collections.Item`. It stores only one single item, it's useful for example for parameters, there's only one instance of parameters in state always. -#### implementation curiosity +### implementation curiosity A `collections.Item` is just a `collections.Map` with no key but just a value. The key is the prefix of the collection! @@ -683,7 +683,7 @@ func NewKeeper(storeKey *storetypes.KVStoreKey) Keeper { } ``` -#### The Map Key definition +### The Map Key definition First of all we can see that in order to define a composite key of two elements we use the `collections.Pair` type: diff --git a/docs/build/packages/README.md b/docs/build/packages/README.md index 65324dc59..e6dbeeb2e 100644 --- a/docs/build/packages/README.md +++ b/docs/build/packages/README.md @@ -4,7 +4,7 @@ sidebar_position: 0 # Packages -The Cosmos SDK is a collection of Go modules. This section provides documentation on various packages that can used when developing a Cosmos SDK chain. +The Cosmos SDK is a collection of Go modules. This section provides documentation on various packages that can be used when developing a Cosmos SDK chain. It lists all standalone Go modules that are part of the Cosmos SDK. :::tip diff --git a/docs/build/rfc/rfc/PROCESS.md b/docs/build/rfc/rfc/PROCESS.md index a34af2269..20f08a6e0 100644 --- a/docs/build/rfc/rfc/PROCESS.md +++ b/docs/build/rfc/rfc/PROCESS.md @@ -10,11 +10,11 @@ An RFC is a sort of async whiteboarding session. It is meant to replace the need for a distributed team to come together to make a decision. Currently, the Cosmos SDK team and contributors are distributed around the world. The team conducts working groups to have a synchronous discussion and an RFC can be used to capture the discussion for a wider audience to better understand the changes that are coming to the software. -The main difference the Cosmos SDK is defining as a differentiation between RFC and ADRs is that one is to come to consensus and circulate information about a potential change or feature. An ADR is used if there is already consensus on a feature or change and there is not a need to articulate the change coming to the software. An ADR will articulate the changes and have a lower amount of communication . +The main difference the Cosmos SDK is defining as a differentiation between RFC and ADRs is that one is to come to consensus and circulate information about a potential change or feature. An ADR is used if there is already consensus on a feature or change and there is not a need to articulate the change coming to the software. An ADR will articulate the changes and have a lower amount of communication. ## RFC life cycle -RFC creation is an **iterative** process. An RFC is meant as a distributed colloboration session, it may have many comments and is usually the bi-product of no working group or synchornous communication +RFC creation is an **iterative** process. An RFC is meant as a distributed collaboration session, it may have many comments and is usually the by-product of no working group or synchronous communication 1. Proposals could start with a new GitHub Issue, be a result of existing Issues or a discussion. @@ -28,7 +28,7 @@ RFC creation is an **iterative** process. An RFC is meant as a distributed collo 6. If there is consensus and enough feedback then the RFC can be accepted. -> Note: An RFC is written when there is no working group or team session on the problem. RFC's are meant as a distributed white boarding session. If there is a working group on the proposal there is no need to have an RFC as there is synchornous whiteboarding going on. +> Note: An RFC is written when there is no working group or team session on the problem. RFC's are meant as a distributed white boarding session. If there is a working group on the proposal there is no need to have an RFC as there is synchronous whiteboarding going on. ### RFC status @@ -53,7 +53,7 @@ DRAFT -> PROPOSED -> LAST CALL yyyy-mm-dd -> ACCEPTED | REJECTED -> SUPERSEDED b * `LAST CALL `: [optional] clear notify that we are close to accept updates. Changing a status to `LAST CALL` means that social consensus (of Cosmos SDK maintainers) has been reached and we still want to give it a time to let the community react or analyze. * `ACCEPTED`: ADR which will represent a currently implemented or to be implemented architecture design. * `REJECTED`: ADR can go from PROPOSED or ACCEPTED to rejected if the consensus among project stakeholders will decide so. -* `SUPERSEEDED by ADR-xxx`: ADR which has been superseded by a new ADR. +* `SUPERSEDED by ADR-xxx`: ADR which has been superseded by a new ADR. * `ABANDONED`: the ADR is no longer pursued by the original authors. ## Language used in RFC diff --git a/docs/build/rfc/rfc/rfc-001-tx-validation.md b/docs/build/rfc/rfc/rfc-001-tx-validation.md index 923e1c720..80dc8e1f2 100644 --- a/docs/build/rfc/rfc/rfc-001-tx-validation.md +++ b/docs/build/rfc/rfc/rfc-001-tx-validation.md @@ -6,7 +6,7 @@ ## Background -Transation Validation is crucial to a functioning state machine. Within the Cosmos SDK there are two validation flows, one is outside the message server and the other within. The flow outside of the message server is the `ValidateBasic` function. It is called in the antehandler on both `CheckTx` and `DeliverTx`. There is an overhead and sometimes duplication of validation within these two flows. This extra validation provides an additional check before entering the mempool. +Transaction Validation is crucial to a functioning state machine. Within the Cosmos SDK there are two validation flows, one is outside the message server and the other within. The flow outside of the message server is the `ValidateBasic` function. It is called in the antehandler on both `CheckTx` and `DeliverTx`. There is an overhead and sometimes duplication of validation within these two flows. This extra validation provides an additional check before entering the mempool. With the deprecation of [`GetSigners`](https://github.com/cosmos/cosmos-sdk/issues/11275) we have the optionality to remove [sdk.Msg](https://github.com/cosmos/cosmos-sdk/blob/16a5404f8e00ddcf8857c8a55dca2f7c109c29bc/types/tx_msg.go#L16) and the `ValidateBasic` function. @@ -16,10 +16,10 @@ With the separation of CometBFT and Cosmos-SDK, there is a lack of control of wh The acceptance of this RFC would move validation within `ValidateBasic` to the message server in modules, update tutorials and docs to remove mention of using `ValidateBasic` in favour of handling all validation for a message where it is executed. -We can and will still support the `Validatebasic` function for users and provide an extension interface of the function once `sdk.Msg` is depreacted. +We can and will still support the `ValidateBasic` function for users and provide an extension interface of the function once `sdk.Msg` is deprecated. > Note: This is how messages are handled in VMs like Ethereum and CosmWasm. ### Consequences -The consequence of updating the transaction flow is that transaction that may have failed before with the `ValidateBasic` flow will now be included in a block and fees charged. +The consequence of updating the transaction flow is that transaction that may have failed before with the `ValidateBasic` flow will now be included in a block and the fees charged. diff --git a/docs/build/rfc/rfc/rfc-template.md b/docs/build/rfc/rfc/rfc-template.md index 417a795d0..f4e79fbb4 100644 --- a/docs/build/rfc/rfc/rfc-template.md +++ b/docs/build/rfc/rfc/rfc-template.md @@ -32,7 +32,7 @@ > path and fall into the same pitfalls that we've since matured from. Abandoned ideas are a way to recognize that path > and explain the pitfalls and why they were abandoned. -## Descision +## Decision > This section describes alternative designs to the chosen design. This section > is important and if an adr does not have any alternatives then it should be diff --git a/docs/build/spec/README.md b/docs/build/spec/README.md index 91f347a8e..cca186ade 100644 --- a/docs/build/spec/README.md +++ b/docs/build/spec/README.md @@ -17,7 +17,7 @@ block. ## Modules specifications -Go the [module directory](https://docs.cosmos.network/main/modules) +Go to the [module directory](https://docs.cosmos.network/main/modules) ## CometBFT diff --git a/docs/build/spec/addresses/bech32.md b/docs/build/spec/addresses/bech32.md index 626dfd11d..dcf8349bb 100644 --- a/docs/build/spec/addresses/bech32.md +++ b/docs/build/spec/addresses/bech32.md @@ -18,4 +18,4 @@ While all user facing interfaces to Cosmos software should exposed Bech32 interf To convert between other binary representation of addresses and keys, it is important to first apply the Amino encoding process before Bech32 encoding. -A complete implementation of the Amino serialization format is unnecessary in most cases. Simply prepending bytes from this [table](https://github.com/cometbft/cometbft/blob/main/spec/blockchain/encoding.md) to the byte string payload before Bech32 encoding will sufficient for compatible representation. +A complete implementation of the Amino serialization format is unnecessary in most cases. Simply prepending bytes from this [table](https://github.com/cometbft/cometbft/blob/main/spec/blockchain/encoding.md) to the byte string payload before Bech32 encoding will be sufficient for compatible representation. diff --git a/docs/build/spec/fee_distribution/f1_fee_distr.tex b/docs/build/spec/fee_distribution/f1_fee_distr.tex index 22e861026..658c3be41 100644 --- a/docs/build/spec/fee_distribution/f1_fee_distr.tex +++ b/docs/build/spec/fee_distribution/f1_fee_distr.tex @@ -78,7 +78,7 @@ \subsection{Base algorithm} This variable is incremented at every block by however much fees this validator received that block. On the update to the validators power, this variable is used to create the entry in state at $f$, and is then reset to 0. -This fee distribution proposal is agnostic to how all of the blocks fees are divied up between validators. +This fee distribution proposal is agnostic to how all of the blocks fees are divided up between validators. This creates many nice properties, for example it is possible to only rewarding validators who signed that block. \section{Additional add-ons} @@ -237,7 +237,7 @@ \section{TO DOs} \item Mention storage optimization for how to prune slashing entries in the uniform inflation and iteration over slashing case \item Add equation numbers \item perhaps re-organize so that the no iteration - \item Section on decimal precision considerations (would unums help?), and mitigating errors in calculation with floats and decimals. -- This probably belongs in a corrollary markdown file in the implementation + \item Section on decimal precision considerations (would unums help?), and mitigating errors in calculation with floats and decimals. -- This probably belongs in a corollary markdown file in the implementation \item Consider indicating that the withdraw action need not be a tx type and could instead happen 'transparently' when more coins are needed, if a chain desired this for UX / p2p efficiency. \end{itemize} diff --git a/docs/build/spec/store/README.md b/docs/build/spec/store/README.md index c53d69c67..3bf8b0e34 100644 --- a/docs/build/spec/store/README.md +++ b/docs/build/spec/store/README.md @@ -42,7 +42,7 @@ until `Commit()` is called on the `CommitMultiStore`. ### `CommitMultiStore` -The `CommitMultiStore` interface exposes the the top-level interface that is used +The `CommitMultiStore` interface exposes the top-level interface that is used to manage state commitment and storage by an SDK application and abstracts the concept of multiple `KVStore`s which are used by multiple modules. Specifically, it supports the following high-level primitives: @@ -53,7 +53,7 @@ it supports the following high-level primitives: * Allows for loading state storage at a particular height/version in the past to provide current head and historical queries. * Provides the ability to rollback state to a previous height/version. -* Provides the ability to to load state storage at a particular height/version +* Provides the ability to load state storage at a particular height/version while also performing store upgrades, which are used during live hard-fork application state migrations. * Provides the ability to commit all current accumulated state to disk and performs @@ -103,7 +103,7 @@ responsibility of the caller to ensure that concurrent access to the store is not performed. The main issue with concurrent use is when data is written at the same time as -it's being iterated over. Doing so will cause a irrecoverable fatal error because +it's being iterated over. Doing so will cause an irrecoverable fatal error because of concurrent reads and writes to an internal map. Although it's not recommended, you can iterate through values while writing to @@ -156,7 +156,7 @@ state from each `KVStore` to disk and returning an application state Merkle root Queries can be performed to return state data along with associated state commitment proofs for both previous heights/versions and the current state root. Queries are routed based on store name, i.e. a module, along with other parameters -which are defined in `abci.RequestQuery`. +which are defined in `abci.QueryRequest`. The `rootmulti.Store` also provides primitives for pruning data at a given height/version from state storage. When a height is committed, the `rootmulti.Store` diff --git a/docs/build/tooling/00-protobuf.md b/docs/build/tooling/00-protobuf.md index 7f9e33159..128970c0c 100644 --- a/docs/build/tooling/00-protobuf.md +++ b/docs/build/tooling/00-protobuf.md @@ -6,7 +6,7 @@ sidebar_position: 1 It is known that Cosmos SDK uses protocol buffers extensively, this document is meant to provide a guide on how it is used in the cosmos-sdk. -To generate the proto file, the Cosmos SDK uses a docker image, this image is provided to all to use as well. The latest version is `ghcr.io/cosmos/proto-builder:0.12.x` +To generate the proto file, the Cosmos SDK uses a docker image, this image is provided to all to use as well. The latest version is `ghcr.io/cosmos/proto-builder:0.17.0` Below is the example of the Cosmos SDK's commands for generating, linting, and formatting protobuf files that can be reused in any applications makefile. @@ -22,7 +22,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.50.0-alpha.0/scripts/protocgen.sh ## Buf -[Buf](https://buf.build) is a protobuf tool that abstracts the needs to use the complicated `protoc` toolchain on top of various other things that ensure you are using protobuf in accordance with the majority of the ecosystem. Within the cosmos-sdk repository there are a few files that have a buf prefix. Lets start with the top level and then dive into the various directories. +[Buf](https://buf.build) is a protobuf tool that abstracts the need to use the complicated `protoc` toolchain on top of various other things that ensure you are using protobuf in accordance with the majority of the ecosystem. Within the cosmos-sdk repository there are a few files that have a buf prefix. Lets start with the top level and then dive into the various directories. ### Workspace @@ -50,7 +50,7 @@ Next is the `proto/` directory where all of our protobuf files live. In here the └── tendermint ``` -The above diagram all the files and directories within the Cosmos SDK `proto/` directory. +The above diagram shows all the files and directories within the Cosmos SDK `proto/` directory. #### `buf.gen.gogo.yaml` @@ -61,7 +61,7 @@ https://github.com/cosmos/cosmos-sdk/blob/main/proto/buf.gen.gogo.yaml#L1-L9 ``` :::tip -Example of how to define `gen` files can be found [here](https://docs.buf.build/tour/generate-go-code) +Example of how to define `gen` files can be found [here](https://docs.buf.build/generate/overview) ::: #### `buf.gen.pulsar.yaml` @@ -73,24 +73,24 @@ https://github.com/cosmos/cosmos-sdk/blob/main/proto/buf.gen.pulsar.yaml#L1-L18 ``` :::tip -Example of how to define `gen` files can be found [here](https://docs.buf.build/tour/generate-go-code) +Example of how to define `gen` files can be found [here](https://docs.buf.build/generate/overview) ::: #### `buf.gen.swagger.yaml` -`buf.gen.swagger.yaml` generates the swagger documentation for the query and messages of the chain. This will only define the REST API end points that were defined in the query and msg servers. You can find examples of this [here](https://github.com/cosmos/cosmos-sdk/blob/main/proto/cosmos/bank/v1beta1/query.proto#L19) +`buf.gen.swagger.yaml` generates the swagger documentation for the query and messages of the chain. This will only define the REST API endpoints that were defined in the query and msg servers. You can find examples of this [here](https://github.com/cosmos/cosmos-sdk/blob/main/proto/cosmos/bank/v1beta1/query.proto#L19) ```go reference https://github.com/cosmos/cosmos-sdk/blob/main/proto/buf.gen.swagger.yaml#L1-L6 ``` :::tip -Example of how to define `gen` files can be found [here](https://docs.buf.build/tour/generate-go-code) +Example of how to define `gen` files can be found [here](https://docs.buf.build/generate/overview) ::: #### `buf.lock` -This is an autogenerated file based off the dependencies required by the `.gen` files. There is no need to copy the current one. If you depend on cosmos-sdk proto definitions a new entry for the Cosmos SDK will need to be provided. The dependency you will need to use is `buf.build/cosmos/cosmos-sdk`. +This is an autogenerated file based on the dependencies required by the `.gen` files. There is no need to copy the current one. If you depend on cosmos-sdk proto definitions a new entry for the Cosmos SDK will need to be provided. The dependency you will need to use is `buf.build/cosmos/cosmos-sdk`. ```go reference https://github.com/cosmos/cosmos-sdk/blob/main/proto/buf.lock#L1-L16 @@ -98,7 +98,7 @@ https://github.com/cosmos/cosmos-sdk/blob/main/proto/buf.lock#L1-L16 #### `buf.yaml` -`buf.yaml` defines the [name of your package](https://github.com/cosmos/cosmos-sdk/blob/main/proto/buf.yaml#L3), which [breakage checker](https://docs.buf.build/tour/detect-breaking-changes) to use and how to [lint your protobuf files](https://buf.build/docs/tutorials/getting-started-with-buf-cli#lint-your-api). +`buf.yaml` defines the [name of your package](https://github.com/cosmos/cosmos-sdk/blob/main/proto/buf.yaml#L3), which [breakage checker](https://docs.buf.build/breaking/overview) to use and how to [lint your protobuf files](https://buf.build/docs/tutorials/getting-started-with-buf-cli#lint-your-api). ```go reference https://github.com/cosmos/cosmos-sdk/blob/main/proto/buf.yaml#L1-L24 diff --git a/docs/build/tooling/01-cosmovisor.md b/docs/build/tooling/01-cosmovisor.md index 3b5f722c5..7c70611ff 100644 --- a/docs/build/tooling/01-cosmovisor.md +++ b/docs/build/tooling/01-cosmovisor.md @@ -188,7 +188,7 @@ When the upgrade mechanism is triggered, `cosmovisor` will: `cosmovisor` has an `add-upgrade` command that allows to easily link a binary to an upgrade. It creates a new folder in `cosmovisor/upgrades/` and copies the provided executable file to `cosmovisor/upgrades//bin/`. -Using the `--upgrade-height` flag allows to specify at which height the binary should be switched, without going via a gorvernance proposal. +Using the `--upgrade-height` flag allows to specify at which height the binary should be switched, without going via a governance proposal. This enables support for an emergency coordinated upgrades where the binary must be switched at a specific height, but there is no time to go through a governance proposal. :::warning diff --git a/docs/build/tooling/README.md b/docs/build/tooling/README.md index 853fd9a25..230918c21 100644 --- a/docs/build/tooling/README.md +++ b/docs/build/tooling/README.md @@ -9,8 +9,8 @@ This includes tools for development, operating a node, and ease of use of a Cosm ## CLI Tools -* [Cosmovisor](./01-cosmovisor.md) -* [Confix](./02-confix.md) +* [Cosmovisor](../../../tools/cosmovisor/README.md) +* [Confix](../../../tools/confix/README.md) ## Other Tools diff --git a/docs/learn/advanced/00-baseapp.md b/docs/learn/advanced/00-baseapp.md index 7c6bf2ac9..b24a570d7 100644 --- a/docs/learn/advanced/00-baseapp.md +++ b/docs/learn/advanced/00-baseapp.md @@ -166,7 +166,7 @@ which encodes and validates each transaction and from there the `AnteHandler` is If successful, valid transactions are returned inclusive of the events, tags, and data generated during the execution of the proposal. The described behavior is that of the default handler, applications have the flexibility to define their own -[custom mempool handlers](https://docs.cosmos.network/main/building-apps/app-mempool#custom-mempool-handlers). +[custom mempool handlers](https://docs.cosmos.network/main/build/building-apps/app-mempool). ![ProcessProposal](./baseapp_state-prepareproposal.png) @@ -177,7 +177,7 @@ from the root store and is used to process a signed proposal received from a val In this state, `runTx` is called and the `AnteHandler` is executed and the context used in this state is built with information from the header and the main state, including the minimum gas prices, which are also set. Again we want to highlight that the described behavior is that of the default handler and applications have the flexibility to define their own -[custom mempool handlers](https://docs.cosmos.network/main/building-apps/app-mempool#custom-mempool-handlers). +[custom mempool handlers](https://docs.cosmos.network/main/build/building-apps/app-mempool). ![ProcessProposal](./baseapp_state-processproposal.png) @@ -264,7 +264,7 @@ Note that, unlike `CheckTx()`, `PrepareProposal` process `sdk.Msg`s, so it can d It's important to note that `PrepareProposal` complements the `ProcessProposal` method which is executed after this method. The combination of these two methods means that it is possible to guarantee that no invalid transactions are ever committed. Furthermore, such a setup can give rise to other interesting use cases such as Oracles, threshold decryption and more. -`PrepareProposal` returns a response to the underlying consensus engine of type [`abci.ResponseCheckTx`](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_methods.md#processproposal). The response contains: +`PrepareProposal` returns a response to the underlying consensus engine of type [`abci.CheckTxResponse`](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_methods.md#processproposal). The response contains: * `Code (uint32)`: Response Code. `0` if successful. * `Data ([]byte)`: Result bytes, if any. @@ -291,7 +291,7 @@ CometBFT calls it when it receives a proposal and the CometBFT algorithm has not However, developers must exercise greater caution when using these methods. Incorrectly coding these methods could affect liveness as CometBFT is unable to receive 2/3 valid precommits to finalize a block. -`ProcessProposal` returns a response to the underlying consensus engine of type [`abci.ResponseCheckTx`](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_methods.md#processproposal). The response contains: +`ProcessProposal` returns a response to the underlying consensus engine of type [`abci.CheckTxResponse`](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_methods.md#processproposal). The response contains: * `Code (uint32)`: Response Code. `0` if successful. * `Data ([]byte)`: Result bytes, if any. @@ -338,7 +338,7 @@ be rejected. In any case, the sender's account will not actually pay the fees un is actually included in a block, because `checkState` never gets committed to the main state. The `checkState` is reset to the latest state of the main state each time a blocks gets [committed](#commit). -`CheckTx` returns a response to the underlying consensus engine of type [`abci.ResponseCheckTx`](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_methods.md#checktx). +`CheckTx` returns a response to the underlying consensus engine of type [`abci.CheckTxResponse`](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_methods.md#checktx). The response contains: * `Code (uint32)`: Response Code. `0` if successful. @@ -396,7 +396,7 @@ The `AnteHandler` is theoretically optional, but still a very important componen * Be a primary line of defense against spam and second line of defense (the first one being the mempool) against transaction replay with fees deduction and [`sequence`](./01-transactions.md#transaction-generation) checking. * Perform preliminary _stateful_ validity checks like ensuring signatures are valid or that the sender has enough funds to pay for fees. -* Play a role in the incentivisation of stakeholders via the collection of transaction fees. +* Play a role in the incentivization of stakeholders via the collection of transaction fees. `BaseApp` holds an `anteHandler` as parameter that is initialized in the [application's constructor](../beginner/00-app-anatomy.md#application-constructor). The most widely used `anteHandler` is the [`auth` module](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/x/auth/ante/ante.go). @@ -432,7 +432,7 @@ The [`InitChain` ABCI message](https://github.com/cometbft/cometbft/blob/v0.37.x * [`checkState` and `finalizeBlockState`](#state-updates) via `setState`. * The [block gas meter](../beginner/04-gas-fees.md#block-gas-meter), with infinite gas to process genesis transactions. -Finally, the `InitChain(req abci.RequestInitChain)` method of `BaseApp` calls the [`initChainer()`](../beginner/00-app-anatomy.md#initchainer) of the application in order to initialize the main state of the application from the `genesis file` and, if defined, call the [`InitGenesis`](../../build/building-modules/08-genesis.md#initgenesis) function of each of the application's modules. +Finally, the `InitChain(req abci.InitChainRequest)` method of `BaseApp` calls the [`initChainer()`](../beginner/00-app-anatomy.md#initchainer) of the application in order to initialize the main state of the application from the `genesis file` and, if defined, call the [`InitGenesis`](../../build/building-modules/08-genesis.md#initgenesis) function of each of the application's modules. ### FinalizeBlock @@ -450,7 +450,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/abci.go#L869 #### BeginBlock -* Initialize [`finalizeBlockState`](#state-updates) with the latest header using the `req abci.RequestFinalizeBlock` passed as parameter via the `setState` function. +* Initialize [`finalizeBlockState`](#state-updates) with the latest header using the `req abci.FinalizeBlockRequest` passed as parameter via the `setState` function. ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/baseapp.go#L746-L770 @@ -469,12 +469,12 @@ When the underlying consensus engine receives a block proposal, each transaction Before the first transaction of a given block is processed, a [volatile state](#state-updates) called `finalizeBlockState` is initialized during FinalizeBlock. This state is updated each time a transaction is processed via `FinalizeBlock`, and committed to the [main state](#main-state) when the block is [committed](#commit), after what it is set to `nil`. ```go reference -https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/baseapp.go#LL772-L807 +https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/baseapp.go#L772-L807 ``` Transaction execution within `FinalizeBlock` performs the **exact same steps as `CheckTx`**, with a little caveat at step 3 and the addition of a fifth step: -1. The `AnteHandler` does **not** check that the transaction's `gas-prices` is sufficient. That is because the `min-gas-prices` value `gas-prices` is checked against is local to the node, and therefore what is enough for one full-node might not be for another. This means that the proposer can potentially include transactions for free, although they are not incentivised to do so, as they earn a bonus on the total fee of the block they propose. +1. The `AnteHandler` does **not** check that the transaction's `gas-prices` is sufficient. That is because the `min-gas-prices` value `gas-prices` is checked against is local to the node, and therefore what is enough for one full-node might not be for another. This means that the proposer can potentially include transactions for free, although they are not incentivized to do so, as they earn a bonus on the total fee of the block they propose. 2. For each `sdk.Msg` in the transaction, route to the appropriate module's Protobuf [`Msg` service](../../build/building-modules/03-msg-services.md). Additional _stateful_ checks are performed, and the branched multistore held in `finalizeBlockState`'s `context` is updated by the module's `keeper`. If the `Msg` service returns successfully, the branched multistore held in `context` is written to `finalizeBlockState` `CacheMultiStore`. During the additional fifth step outlined in (2), each read/write to the store increases the value of `GasConsumed`. You can find the default cost of each operation: @@ -506,7 +506,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/baseapp/baseapp.go#L811-L833 ### Commit -The [`Commit` ABCI message](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_basic_concepts.md#method-overview) is sent from the underlying CometBFT engine after the full-node has received _precommits_ from 2/3+ of validators (weighted by voting power). On the `BaseApp` end, the `Commit(res abci.ResponseCommit)` function is implemented to commit all the valid state transitions that occurred during `FinalizeBlock` and to reset state for the next block. +The [`Commit` ABCI message](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_basic_concepts.md#method-overview) is sent from the underlying CometBFT engine after the full-node has received _precommits_ from 2/3+ of validators (weighted by voting power). On the `BaseApp` end, the `Commit(res abci.CommitResponse)` function is implemented to commit all the valid state transitions that occurred during `FinalizeBlock` and to reset state for the next block. To commit state-transitions, the `Commit` function calls the `Write()` function on `finalizeBlockState.ms`, where `finalizeBlockState.ms` is a branched multistore of the main store `app.cms`. Then, the `Commit` function sets `checkState` to the latest header (obtained from `finalizeBlockState.ctx.BlockHeader`) and `finalizeBlockState` to `nil`. @@ -514,13 +514,13 @@ Finally, `Commit` returns the hash of the commitment of `app.cms` back to the un ### Info -The [`Info` ABCI message](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_basic_concepts.md#info-methods) is a simple query from the underlying consensus engine, notably used to sync the latter with the application during a handshake that happens on startup. When called, the `Info(res abci.ResponseInfo)` function from `BaseApp` will return the application's name, version and the hash of the last commit of `app.cms`. +The [`Info` ABCI message](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_basic_concepts.md#info-methods) is a simple query from the underlying consensus engine, notably used to sync the latter with the application during a handshake that happens on startup. When called, the `Info(res abci.InfoResponse)` function from `BaseApp` will return the application's name, version and the hash of the last commit of `app.cms`. ### Query The [`Query` ABCI message](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_basic_concepts.md#info-methods) is used to serve queries received from the underlying consensus engine, including queries received via RPC like CometBFT RPC. It used to be the main entrypoint to build interfaces with the application, but with the introduction of [gRPC queries](../../build/building-modules/04-query-services.md) in Cosmos SDK v0.40, its usage is more limited. The application must respect a few rules when implementing the `Query` method, which are outlined [here](https://github.com/cometbft/cometbft/blob/v0.37.x/spec/abci/abci++_app_requirements.md#query). -Each CometBFT `query` comes with a `path`, which is a `string` which denotes what to query. If the `path` matches a gRPC fully-qualified service method, then `BaseApp` will defer the query to the `grpcQueryRouter` and let it handle it like explained [above](#grpc-query-router). Otherwise, the `path` represents a query that is not (yet) handled by the gRPC router. `BaseApp` splits the `path` string with the `/` delimiter. By convention, the first element of the split string (`split[0]`) contains the category of `query` (`app`, `p2p`, `store` or `custom` ). The `BaseApp` implementation of the `Query(req abci.RequestQuery)` method is a simple dispatcher serving these 4 main categories of queries: +Each CometBFT `query` comes with a `path`, which is a `string` which denotes what to query. If the `path` matches a gRPC fully-qualified service method, then `BaseApp` will defer the query to the `grpcQueryRouter` and let it handle it like explained [above](#grpc-query-router). Otherwise, the `path` represents a query that is not (yet) handled by the gRPC router. `BaseApp` splits the `path` string with the `/` delimiter. By convention, the first element of the split string (`split[0]`) contains the category of `query` (`app`, `p2p`, `store` or `custom` ). The `BaseApp` implementation of the `Query(req abci.QueryRequest)` method is a simple dispatcher serving these 4 main categories of queries: * Application-related queries like querying the application's version, which are served via the `handleQueryApp` method. * Direct queries to the multistore, which are served by the `handlerQueryStore` method. These direct queries are different from custom queries which go through `app.queryRouter`, and are mainly used by third-party service provider like block explorers. diff --git a/docs/learn/advanced/01-transactions.md b/docs/learn/advanced/01-transactions.md index cc8b862d0..725755637 100644 --- a/docs/learn/advanced/01-transactions.md +++ b/docs/learn/advanced/01-transactions.md @@ -76,7 +76,7 @@ The Cosmos SDK also provides a couple of other sign modes for particular use cas #### `SIGN_MODE_DIRECT_AUX` -`SIGN_MODE_DIRECT_AUX` is a sign mode released in the Cosmos SDK v0.46 which targets transactions with multiple signers. Whereas `SIGN_MODE_DIRECT` expects each signer to sign over both `TxBody` and `AuthInfo` (which includes all other signers' signer infos, i.e. their account sequence, public key and mode info), `SIGN_MODE_DIRECT_AUX` allows N-1 signers to only sign over `TxBody` and _their own_ signer info. Morever, each auxiliary signer (i.e. a signer using `SIGN_MODE_DIRECT_AUX`) doesn't +`SIGN_MODE_DIRECT_AUX` is a sign mode released in the Cosmos SDK v0.46 which targets transactions with multiple signers. Whereas `SIGN_MODE_DIRECT` expects each signer to sign over both `TxBody` and `AuthInfo` (which includes all other signers' signer infos, i.e. their account sequence, public key and mode info), `SIGN_MODE_DIRECT_AUX` allows N-1 signers to only sign over `TxBody` and _their own_ signer info. Moreover, each auxiliary signer (i.e. a signer using `SIGN_MODE_DIRECT_AUX`) doesn't need to sign over the fees: ```protobuf reference @@ -99,7 +99,7 @@ If you wish to learn more, please refer to [ADR-050](../../build/architecture/ad #### Custom Sign modes -There is the opportunity to add your own custom sign mode to the Cosmos-SDK. While we can not accept the implementation of the sign mode to the repository, we can accept a pull request to add the custom signmode to the SignMode enum located [here](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/proto/cosmos/tx/signing/v1beta1/signing.proto#L17) +There is an opportunity to add your own custom sign mode to the Cosmos-SDK. While we can not accept the implementation of the sign mode to the repository, we can accept a pull request to add the custom signmode to the SignMode enum located [here](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/proto/cosmos/tx/signing/v1beta1/signing.proto#L17) ## Transaction Process diff --git a/docs/learn/advanced/02-context.md b/docs/learn/advanced/02-context.md index 312a4fd9a..578bb1f1b 100644 --- a/docs/learn/advanced/02-context.md +++ b/docs/learn/advanced/02-context.md @@ -30,16 +30,16 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/types/context.go#L40-L67 * **Chain ID:** The unique identification number of the blockchain a block pertains to. * **Transaction Bytes:** The `[]byte` representation of a transaction being processed using the context. Every transaction is processed by various parts of the Cosmos SDK and consensus engine (e.g. CometBFT) throughout its [lifecycle](../beginner/01-tx-lifecycle.md), some of which do not have any understanding of transaction types. Thus, transactions are marshaled into the generic `[]byte` type using some kind of [encoding format](./05-encoding.md) such as [Amino](./05-encoding.md). * **Logger:** A `logger` from the CometBFT libraries. Learn more about logs [here](https://docs.cometbft.com/v0.37/core/configuration). Modules call this method to create their own unique module-specific logger. -* **VoteInfo:** A list of the ABCI type [`VoteInfo`](https://docs.cometbft.com/master/spec/abci/abci.html#voteinfo), which includes the name of a validator and a boolean indicating whether they have signed the block. +* **VoteInfo:** A list of the ABCI type [`VoteInfo`](https://docs.cometbft.com/main/spec/abci/abci++_methods.html#voteinfo), which includes the name of a validator and a boolean indicating whether they have signed the block. * **Gas Meters:** Specifically, a [`gasMeter`](../beginner/04-gas-fees.md#main-gas-meter) for the transaction currently being processed using the context and a [`blockGasMeter`](../beginner/04-gas-fees.md#block-gas-meter) for the entire block it belongs to. Users specify how much in fees they wish to pay for the execution of their transaction; these gas meters keep track of how much [gas](../beginner/04-gas-fees.md) has been used in the transaction or block so far. If the gas meter runs out, execution halts. * **CheckTx Mode:** A boolean value indicating whether a transaction should be processed in `CheckTx` or `DeliverTx` mode. * **Min Gas Price:** The minimum [gas](../beginner/04-gas-fees.md) price a node is willing to take in order to include a transaction in its block. This price is a local value configured by each node individually, and should therefore **not be used in any functions used in sequences leading to state-transitions**. -* **Consensus Params:** The ABCI type [Consensus Parameters](https://docs.cometbft.com/master/spec/abci/apps.html#consensus-parameters), which specify certain limits for the blockchain, such as maximum gas for a block. +* **Consensus Params:** The ABCI type [Consensus Parameters](https://docs.cometbft.com/v0.37/spec/abci/abci++_app_requirements#consensus-parameters), which specify certain limits for the blockchain, such as maximum gas for a block. * **Event Manager:** The event manager allows any caller with access to a `Context` to emit [`Events`](./08-events.md). Modules may define module specific `Events` by defining various `Types` and `Attributes` or use the common definitions found in `types/`. Clients can subscribe or query for these `Events`. These `Events` are collected throughout `FinalizeBlock` and are returned to CometBFT for indexing. * **Priority:** The transaction priority, only relevant in `CheckTx`. * **KV `GasConfig`:** Enables applications to set a custom `GasConfig` for the `KVStore`. -* **Transient KV `GasConfig`:** Enables applications to set a custom `GasConfig` for the transiant `KVStore`. +* **Transient KV `GasConfig`:** Enables applications to set a custom `GasConfig` for the transient `KVStore`. * **StreamingManager:** The streamingManager field provides access to the streaming manager, which allows modules to subscribe to state changes emitted by the blockchain. The streaming manager is used by the state listening API, which is described in [ADR 038](https://docs.cosmos.network/main/architecture/adr-038-state-listening). * **CometInfo:** A lightweight field that contains information about the current block, such as the block height, time, and hash. This information can be used for validating evidence, providing historical data, and enhancing the user experience. For further details see [here](https://github.com/cosmos/cosmos-sdk/blob/main/core/comet/service.go#L14). * **HeaderInfo:** The `headerInfo` field contains information about the current block header, such as the chain ID, gas limit, and timestamp. For further details see [here](https://github.com/cosmos/cosmos-sdk/blob/main/core/header/service.go#L14). @@ -71,7 +71,7 @@ goes wrong. The pattern of usage for a Context is as follows: 1. A process receives a Context `ctx` from its parent process, which provides information needed to perform the process. -2. The `ctx.ms` is a **branched store**, i.e. a branch of the [multistore](./04-store.md#multistore) is made so that the process can make changes to the state as it executes, without changing the original`ctx.ms`. This is useful to protect the underlying multistore in case the changes need to be reverted at some point in the execution. +2. The `ctx.ms` is a **branched store**, i.e. a branch of the [multistore](./04-store.md#multistore) is made so that the process can make changes to the state as it executes, without changing the original `ctx.ms`. This is useful to protect the underlying multistore in case the changes need to be reverted at some point in the execution. 3. The process may read and write from `ctx` as it is executing. It may call a subprocess and pass `ctx` to it as needed. 4. When a subprocess returns, it checks if the result is a success or failure. If a failure, nothing diff --git a/docs/learn/advanced/04-store.md b/docs/learn/advanced/04-store.md index 8bebc3ba1..860bb3d02 100644 --- a/docs/learn/advanced/04-store.md +++ b/docs/learn/advanced/04-store.md @@ -220,7 +220,7 @@ This is the type used whenever an IAVL Store needs to be branched to create an i #### `Iterator` -`Store.Iterator()` have to traverse on both cached items and the original items. In `Store.iterator()`, two iterators are generated for each of them, and merged. `memIterator` is essentially a slice of the `KVPairs`, used for cached items. `mergeIterator` is a combination of two iterators, where traverse happens ordered on both iterators. +`Store.Iterator()` has to traverse on both cached items and the original items. In `Store.iterator()`, two iterators are generated for each of them, and merged. `memIterator` is essentially a slice of the `KVPairs`, used for cached items. `mergeIterator` is a combination of two iterators, where traverse happens ordered on both iterators. ### `GasKv` Store diff --git a/docs/learn/advanced/05-encoding.md b/docs/learn/advanced/05-encoding.md index 7698b150d..3c7307417 100644 --- a/docs/learn/advanced/05-encoding.md +++ b/docs/learn/advanced/05-encoding.md @@ -57,7 +57,7 @@ Modules are encouraged to utilize Protobuf encoding for their respective types. In addition to [following official Protocol Buffer guidelines](https://developers.google.com/protocol-buffers/docs/proto3#simple), we recommend using these annotations in .proto files when dealing with interfaces: -* use `cosmos_proto.accepts_interface` to annote `Any` fields that accept interfaces +* use `cosmos_proto.accepts_interface` to annotate `Any` fields that accept interfaces * pass the same fully qualified name as `protoName` to `InterfaceRegistry.RegisterInterface` * example: `(cosmos_proto.accepts_interface) = "cosmos.gov.v1beta1.Content"` (and not just `Content`) * annotate interface implementations with `cosmos_proto.implements_interface` @@ -268,7 +268,7 @@ message MsgSubmitEvidence { } ``` -The Cosmos SDK `codec.Codec` interface provides support methods `MarshalInterface` and `UnmarshalInterface` to easy encoding of state to `Any`. +The Cosmos SDK `codec.Codec` interface provides support methods `MarshalInterface` and `UnmarshalInterface` for easy encoding of state to `Any`. Module should register interfaces using `InterfaceRegistry` which provides a mechanism for registering interfaces: `RegisterInterface(protoName string, iface interface{}, impls ...proto.Message)` and implementations: `RegisterImplementations(iface interface{}, impls ...proto.Message)` that can be safely unpacked from Any, similarly to type registration with Amino: diff --git a/docs/learn/advanced/06-grpc_rest.md b/docs/learn/advanced/06-grpc_rest.md index e10bda099..d3ab827a7 100644 --- a/docs/learn/advanced/06-grpc_rest.md +++ b/docs/learn/advanced/06-grpc_rest.md @@ -26,7 +26,7 @@ All endpoints are defaulted to localhost and must be modified to be exposed to t ## gRPC Server -In the Cosmos SDK, Protobuf is the main [encoding](./encoding) library. This brings a wide range of Protobuf-based tools that can be plugged into the Cosmos SDK. One such tool is [gRPC](https://grpc.io), a modern open-source high performance RPC framework that has decent client support in several languages. +In the Cosmos SDK, Protobuf is the main [encoding](./05-encoding.md) library. This brings a wide range of Protobuf-based tools that can be plugged into the Cosmos SDK. One such tool is [gRPC](https://grpc.io), a modern open-source high performance RPC framework that has decent client support in several languages. Each module exposes a [Protobuf `Query` service](../../build/building-modules/02-messages-and-queries.md#queries) that defines state queries. The `Query` services and a transaction service used to broadcast transactions are hooked up to the gRPC server via the following function inside the application: diff --git a/docs/learn/advanced/07-cli.md b/docs/learn/advanced/07-cli.md index ca97594d0..cd9e34ded 100644 --- a/docs/learn/advanced/07-cli.md +++ b/docs/learn/advanced/07-cli.md @@ -71,7 +71,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/simd/cmd/root_v2.go#L47 :::tip Use the `EnhanceRootCommand()` from the AutoCLI options to automatically add auto-generated commands from the modules to the root command. -Additionnally it adds all manually defined modules commands (`tx` and `query`) as well. +Additionally it adds all manually defined modules commands (`tx` and `query`) as well. Read more about [AutoCLI](https://docs.cosmos.network/main/core/autocli) in its dedicated section. ::: @@ -153,7 +153,7 @@ Flags are added to commands directly (generally in the [module's CLI file](../.. ## Environment variables -Each flag is bound to its respective named environment variable. Then name of the environment variable consist of two parts - capital case `basename` followed by flag name of the flag. `-` must be substituted with `_`. For example flag `--node` for application with basename `GAIA` is bound to `GAIA_NODE`. It allows reducing the amount of flags typed for routine operations. For example instead of: +Each flag is bound to its respective named environment variable. The name of the environment variable consist of two parts - capital case `basename` followed by flag name of the flag. `-` must be substituted with `_`. For example flag `--node` for application with basename `GAIA` is bound to `GAIA_NODE`. It allows reducing the amount of flags typed for routine operations. For example instead of: ```shell gaia --home=./ --node= --chain-id="testchain-1" --keyring-backend=test tx ... --from= diff --git a/docs/learn/advanced/08-events.md b/docs/learn/advanced/08-events.md index 290615e4a..52d026416 100644 --- a/docs/learn/advanced/08-events.md +++ b/docs/learn/advanced/08-events.md @@ -33,7 +33,7 @@ An Event contains: To parse the attribute values as strings, make sure to add `'` (single quotes) around each attribute value. ::: -_Typed Events_ are Protobuf-defined [messages](../../build/architecture/adr-032-typed-events.md) used by the Cosmos SDK +_Typed Events_ are Protobuf-defined [messages](../../../architecture/adr-032-typed-events.md) used by the Cosmos SDK for emitting and querying Events. They are defined in a `event.proto` file, on a **per-module basis** and are read as `proto.Message`. _Legacy Events_ are defined on a **per-module basis** in the module's `/types/events.go` file. They are triggered from the module's Protobuf [`Msg` service](../../build/building-modules/03-msg-services.md) @@ -57,7 +57,7 @@ The following examples show how to query Events using the Cosmos SDK. | `tx.height=23` | Query all transactions at height 23 | | `message.action='/cosmos.bank.v1beta1.Msg/Send'` | Query all transactions containing a x/bank `Send` [Service `Msg`](../../build/building-modules/03-msg-services.md). Note the `'`s around the value. | | `message.module='bank'` | Query all transactions containing messages from the x/bank module. Note the `'`s around the value. | -| `create_validator.validator='cosmosval1...'` | x/staking-specific Event, see [x/staking SPEC](../../build/modules/staking/README.md). | +| `create_validator.validator='cosmosval1...'` | x/staking-specific Event, see [x/staking SPEC](../../../../x/staking/README.md). | ## EventManager diff --git a/docs/learn/advanced/09-telemetry.md b/docs/learn/advanced/09-telemetry.md index fb16da782..14d1aa7c4 100644 --- a/docs/learn/advanced/09-telemetry.md +++ b/docs/learn/advanced/09-telemetry.md @@ -9,7 +9,7 @@ Gather relevant insights about your application and modules with custom metrics ::: The Cosmos SDK enables operators and developers to gain insight into the performance and behavior of -their application through the use of the `telemetry` package. To enable telemetrics, set `telemetry.enabled = true` in the app.toml config file. +their application through the use of the `telemetry` package. To enable telemetry, set `telemetry.enabled = true` in the app.toml config file. The Cosmos SDK currently supports enabling in-memory and prometheus as telemetry sinks. In-memory sink is always attached (when the telemetry is enabled) with 10 second interval and 1 minute retention. This means that metrics will be aggregated over 10 seconds, and metrics will be kept alive for 1 minute. @@ -91,7 +91,7 @@ The following examples expose too much cardinality and may not even prove to be | `tx_msg_withdraw_commission` | The total amount of tokens withdrawn in a `MsgWithdrawValidatorCommission` (per denom) | token | gauge | | `tx_msg_delegate` | The total amount of tokens delegated in a `MsgDelegate` | token | gauge | | `tx_msg_begin_unbonding` | The total amount of tokens undelegated in a `MsgUndelegate` | token | gauge | -| `tx_msg_begin_begin_redelegate` | The total amount of tokens redelegated in a `MsgBeginRedelegate` | token | gauge | +| `tx_msg_begin_redelegate` | The total amount of tokens redelegated in a `MsgBeginRedelegate` | token | gauge | | `tx_msg_ibc_transfer` | The total amount of tokens transferred via IBC in a `MsgTransfer` (source or sink chain) | token | gauge | | `ibc_transfer_packet_receive` | The total amount of tokens received in a `FungibleTokenPacketData` (source or sink chain) | token | gauge | | `new_account` | Total number of new accounts created | account | counter | diff --git a/docs/learn/advanced/11-runtx_middleware.md b/docs/learn/advanced/11-runtx_middleware.md index b88c4c509..bb8c04aad 100644 --- a/docs/learn/advanced/11-runtx_middleware.md +++ b/docs/learn/advanced/11-runtx_middleware.md @@ -4,7 +4,7 @@ sidebar_position: 1 # RunTx recovery middleware -`BaseApp.runTx()` function handles Go panics that might occur during transactions execution, for example, keeper has faced an invalid state and paniced. +`BaseApp.runTx()` function handles Go panics that might occur during transactions execution, for example, keeper has faced an invalid state and panicked. Depending on the panic type different handler is used, for instance the default one prints an error log message. Recovery middleware is used to add custom panic recovery for Cosmos SDK application developers. @@ -16,7 +16,7 @@ More context can found in the corresponding [ADR-022](../../build/architecture/a https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/baseapp/recovery.go#L14-L17 ``` -`recoveryObj` is a return value for `recover()` function from the `buildin` Go package. +`recoveryObj` is a return value for `recover()` function from the `building` Go package. **Contract:** @@ -45,7 +45,7 @@ func (k FooKeeper) Do(obj interface{}) { } ``` -By default that panic would be recovered and an error message will be printed to log. To override that behaviour we should register a custom RecoveryHandler: +By default that panic would be recovered and an error message will be printed to log. To override that behavior we should register a custom RecoveryHandler: ```go // Cosmos SDK application constructor diff --git a/docs/learn/advanced/15-upgrade.md b/docs/learn/advanced/15-upgrade.md index 5d56f2b59..e2332bd1c 100644 --- a/docs/learn/advanced/15-upgrade.md +++ b/docs/learn/advanced/15-upgrade.md @@ -103,7 +103,7 @@ if upgradeInfo.Name == "my-plan" && !app.UpgradeKeeper.IsSkipHeight(upgradeInfo. When starting a new chain, the consensus version of each module MUST be saved to state during the application's genesis. To save the consensus version, add the following line to the `InitChainer` method in `app.go`: ```diff -func (app *MyApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { +func (app *MyApp) InitChainer(ctx sdk.Context, req abci.InitChainRequest) abci.InitChainResponse { ... + app.UpgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap()) ... @@ -159,4 +159,4 @@ You can sync a full node to an existing blockchain which has been upgraded using To successfully sync, you must start with the initial binary that the blockchain started with at genesis. If all Software Upgrade Plans contain binary instruction, then you can run Cosmovisor with auto-download option to automatically handle downloading and switching to the binaries associated with each sequential upgrade. Otherwise, you need to manually provide all binaries to Cosmovisor. -To learn more about Cosmovisor, see the [Cosmovisor Quick Start](../../build/tooling/01-cosmovisor.md). +To learn more about Cosmovisor, see the [Cosmovisor Quick Start](../../../../tools/cosmovisor/README.md). diff --git a/docs/learn/advanced/17-autocli.md b/docs/learn/advanced/17-autocli.md index 24bc5ee57..416883091 100644 --- a/docs/learn/advanced/17-autocli.md +++ b/docs/learn/advanced/17-autocli.md @@ -92,7 +92,7 @@ The keyring is then converted to the `client/v2/autocli/keyring` interface. If no keyring is provided, the `autocli` generated command will not be able to sign transactions, but will still be able to query the chain. :::tip -The Cosmos SDK keyring and Hubl keyring both implement the `client/v2/autocli/keyring` interface, thanks to the following wrapper: +The Cosmos SDK keyring implements the `client/v2/autocli/keyring` interface, thanks to the following wrapper: ```go keyring.NewAutoCLIKeyring(kb) @@ -255,8 +255,4 @@ https://github.com/cosmos/cosmos-sdk/blob/client/v2.0.0-beta.1/client/grpc/cmtse ## Summary -`autocli` let you generate CLI to your Cosmos SDK-based applications without any cobra boilerplate. It allows you to easily generate CLI commands and flags from your protobuf messages, and provides many options for customising the behavior of your CLI application. - -To further enhance your CLI experience with Cosmos SDK-based blockchains, you can use `hubl`. `hubl` is a tool that allows you to query any Cosmos SDK-based blockchain using the new AutoCLI feature of the Cosmos SDK. With `hubl`, you can easily configure a new chain and query modules with just a few simple commands. - -For more information on `hubl`, including how to configure a new chain and query a module, see the [Hubl documentation](https://docs.cosmos.network/main/tooling/hubl). +`autocli` lets you generate CLI for your Cosmos SDK-based applications without any cobra boilerplate. It allows you to easily generate CLI commands and flags from your protobuf messages, and provides many options for customising the behavior of your CLI application. diff --git a/docs/learn/beginner/00-app-anatomy.md b/docs/learn/beginner/00-app-anatomy.md index e2314e782..988c7242a 100644 --- a/docs/learn/beginner/00-app-anatomy.md +++ b/docs/learn/beginner/00-app-anatomy.md @@ -50,10 +50,10 @@ In general, the core of the state-machine is defined in a file called `app.go`. The first thing defined in `app.go` is the `type` of the application. It is generally comprised of the following parts: -* **Embeding [runtime.App](../../build/building-apps/00-runtime.md)** The runtime package manages the application's core components and modules through dependency injection. It provides declarative configuration for module management, state storage, and ABCI handling. +* **Embedding [runtime.App](../../build/building-apps/00-runtime.md)** The runtime package manages the application's core components and modules through dependency injection. It provides declarative configuration for module management, state storage, and ABCI handling. * `Runtime` wraps `BaseApp`, meaning when a transaction is relayed by CometBFT to the application, `app` uses `runtime`'s methods to route them to the appropriate module. `BaseApp` implements all the [ABCI methods](https://docs.cometbft.com/v0.38/spec/abci/) and the [routing logic](../advanced/00-baseapp.md#service-routers). * It automatically configures the **[module manager](../../build/building-modules/01-module-manager.md#manager)** based on the app wiring configuration. The module manager facilitates operations related to these modules, like registering their [`Msg` service](../../build/building-modules/03-msg-services.md) and [gRPC `Query` service](#grpc-query-services), or setting the order of execution between modules for various functions like [`InitChainer`](#initchainer), [`PreBlocker`](#preblocker) and [`BeginBlocker` and `EndBlocker`](#beginblocker-and-endblocker). -* [**An App Wiring configuration file**](../../build/building-apps/00-runtime.md) The app wiring configuration file contains the list of application's modules that `runtime` must instantiate. The instantiation of the modules are done using `depinject`. It also contains the order in which all module's `InitGenesis` and `Pre/Begin/EndBlocker` methods should be executed. +* [**An App Wiring configuration file**](../../build/building-apps/00-runtime.md) The app wiring configuration file contains the list of application's modules that `runtime` must instantiate. The instantiation of the modules is done using `depinject`. It also contains the order in which all modules' `InitGenesis` and `Pre/Begin/EndBlocker` methods should be executed. * **A reference to an [`appCodec`](../advanced/05-encoding.md).** The application's `appCodec` is used to serialize and deserialize data structures in order to store them, as stores can only persist `[]bytes`. The default codec is [Protocol Buffers](../advanced/05-encoding.md). * **A reference to a [`legacyAmino`](../advanced/05-encoding.md) codec.** Some parts of the Cosmos SDK have not been migrated to use the `appCodec` above, and are still hardcoded to use Amino. Other parts explicitly use Amino for backwards compatibility. For these reasons, the application still holds a reference to the legacy Amino codec. Please note that the Amino codec will be removed from the SDK in the upcoming releases. @@ -100,7 +100,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app.go#L190-L708 The `InitChainer` is a function that initializes the state of the application from a genesis file (i.e. token balances of genesis accounts). It is called when the application receives the `InitChain` message from the CometBFT engine, which happens when the node is started at `appBlockHeight == 0` (i.e. on genesis). The application must set the `InitChainer` in its [constructor](#constructor-function) via the [`SetInitChainer`](https://pkg.go.dev/github.com/cosmos/cosmos-sdk/baseapp#BaseApp.SetInitChainer) method. -In general, the `InitChainer` is mostly composed of the [`InitGenesis`](../../build/building-modules/08-genesis.md#initgenesis) function of each of the application's modules. This is done by calling the `InitGenesis` function of the module manager, which in turn calls the `InitGenesis` function of each of the modules it contains. Note that the order in which the modules' `InitGenesis` functions must be called has to be set in the module manager using the [module manager's](../../build/building-modules/01-module-manager.md) `SetOrderInitGenesis` method. This is done in the [application's constructor](#application-constructor), and the `SetOrderInitGenesis` has to be called before the `SetInitChainer`. +In general, the `InitChainer` is mostly composed of the [`InitGenesis`](../../build/building-modules/08-genesis.md#initgenesis) function of each of the application's modules. This is done by calling the `InitGenesis` function of the module manager, which in turn calls the `InitGenesis` function of each of the modules it contains. Note that the order in which the modules' `InitGenesis` functions must be called has to be set in the module manager using the [module manager's](../../build/building-modules/01-module-manager.md) `SetOrderInitGenesis` method. This is done in the [application's constructor](#constructor-function), and the `SetOrderInitGenesis` has to be called before the `SetInitChainer`. See an example of an `InitChainer` from `simapp`: @@ -131,7 +131,7 @@ In general, the `BeginBlocker` and `EndBlocker` functions are mostly composed of As a sidenote, it is important to remember that application-specific blockchains are deterministic. Developers must be careful not to introduce non-determinism in `BeginBlocker` or `EndBlocker`, and must also be careful not to make them too computationally expensive, as [gas](./04-gas-fees.md) does not constrain the cost of `BeginBlocker` and `EndBlocker` execution. -See an example of `BeginBlocker` and `EndBlocker` functions from `simapp` +See an example of `BeginBlocker` and `EndBlocker` functions from `simapp`: ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/simapp/app.go#L752-L759 @@ -179,7 +179,7 @@ Note that `sdk.Msg`s are bundled in [transactions](../advanced/01-transactions.m When a valid block of transactions is received by the full-node, CometBFT relays each one to the application via [`DeliverTx`](https://docs.cometbft.com/v0.37/spec/abci/abci++_app_requirements#specifics-of-responsedelivertx). Then, the application handles the transaction: -1. Upon receiving the transaction, the application first unmarshalls it from `[]byte`. +1. Upon receiving the transaction, the application first unmarshals it from `[]byte`. 2. Then, it verifies a few things about the transaction like [fee payment and signatures](./04-gas-fees.md#antehandler) before extracting the `Msg`(s) contained in the transaction. 3. `sdk.Msg`s are encoded using Protobuf [`Any`s](#register-codec). By analyzing each `Any`'s `type_url`, baseapp's `msgServiceRouter` routes the `sdk.Msg` to the corresponding module's `Msg` service. 4. If the message is successfully processed, the state is updated. diff --git a/docs/learn/beginner/01-tx-lifecycle.md b/docs/learn/beginner/01-tx-lifecycle.md index b2e821e9f..b004b355b 100644 --- a/docs/learn/beginner/01-tx-lifecycle.md +++ b/docs/learn/beginner/01-tx-lifecycle.md @@ -71,9 +71,9 @@ The command-line is an easy way to interact with an application, but `Tx` can al ## Addition to Mempool -Each full-node (running CometBFT) that receives a `Tx` sends an [ABCI message](https://docs.cometbft.com/v0.37/spec/p2p/messages/), -`CheckTx`, to the application layer to check for validity, and receives an `abci.ResponseCheckTx`. If the `Tx` passes the checks, it is held in the node's -[**Mempool**](https://docs.cometbft.com/v0.37/spec/p2p/messages/mempool/), an in-memory pool of transactions unique to each node, pending inclusion in a block - honest nodes discard a `Tx` if it is found to be invalid. Prior to consensus, nodes continuously check incoming transactions and gossip them to their peers. +Each full-node (running CometBFT) that receives a `Tx` sends an [ABCI message](https://docs.cometbft.com/v0.37/spec/p2p/legacy-docs/messages/), +`CheckTx`, to the application layer to check for validity, and receives an `abci.CheckTxResponse`. If the `Tx` passes the checks, it is held in the node's +[**Mempool**](https://docs.cometbft.com/v0.37/spec/p2p/legacy-docs/messages/mempool), an in-memory pool of transactions unique to each node, pending inclusion in a block - honest nodes discard a `Tx` if it is found to be invalid. Prior to consensus, nodes continuously check incoming transactions and gossip them to their peers. ### Types of Checks @@ -98,7 +98,7 @@ through several steps, beginning with decoding `Tx`. ### Decoding -When `Tx` is received by the application from the underlying consensus engine (e.g. CometBFT ), it is still in its [encoded](../advanced/05-encoding.md) `[]byte` form and needs to be unmarshaled in order to be processed. Then, the [`runTx`](../advanced/00-baseapp.md#runtx-antehandler-runmsgs-posthandler) function is called to run in `runTxModeCheck` mode, meaning the function runs all checks but exits before executing messages and writing state changes. +When `Tx` is received by the application from the underlying consensus engine (e.g. CometBFT), it is still in its [encoded](../advanced/05-encoding.md) `[]byte` form and needs to be unmarshaled in order to be processed. Then, the [`runTx`](../advanced/00-baseapp.md#runtx-antehandler-runmsgs-posthandler) function is called to run in `runTxModeCheck` mode, meaning the function runs all checks but exits before executing messages and writing state changes. ### ValidateBasic (deprecated) @@ -113,7 +113,7 @@ Read [RFC 001](https://docs.cosmos.network/main/rfc/rfc-001-tx-validation) for m ::: :::note -`BaseApp` still calls `ValidateBasic` on messages that implements that method for backwards compatibility. +`BaseApp` still calls `ValidateBasic` on messages that implement that method for backwards compatibility. ::: #### Guideline @@ -126,10 +126,10 @@ Read [RFC 001](https://docs.cosmos.network/main/rfc/rfc-001-tx-validation) for m A copy of the cached context is provided to the `AnteHandler`, which performs limited checks specified for the transaction type. Using a copy allows the `AnteHandler` to do stateful checks for `Tx` without modifying the last committed state, and revert back to the original if the execution fails. -For example, the [`auth`](https://github.com/cosmos/cosmos-sdk/tree/main/x/auth/spec) module `AnteHandler` checks and increments sequence numbers, checks signatures and account numbers, and deducts fees from the first signer of the transaction - all state changes are made using the `checkState`. +For example, the [`auth`](https://github.com/cosmos/cosmos-sdk/blob/main/x/auth/README.md) module `AnteHandler` checks and increments sequence numbers, checks signatures and account numbers, and deducts fees from the first signer of the transaction - all state changes are made using the `checkState`. :::warning -Ante handlers only run on a transaction. If a transaction embed multiple messages (like some x/authz, x/gov transactions for instance), the ante handlers only have awareness of the outer message. Inner messages are mostly directly routed to the [message router](https://docs.cosmos.network/main/learn/advanced/baseapp#msg-service-router) and will skip the chain of ante handlers. Keep that in mind when designing your own ante handler. +Ante handlers only run on a transaction. If a transaction embeds multiple messages (like some x/authz, x/gov transactions for instance), the ante handlers only have awareness of the outer message. Inner messages are mostly directly routed to the [message router](https://docs.cosmos.network/main/learn/advanced/baseapp#msg-service-router) and will skip the chain of ante handlers. Keep that in mind when designing your own ante handler. ::: ### Gas @@ -230,7 +230,7 @@ to during consensus. Under the hood, transaction execution is almost identical t Instead of using their `checkState`, full-nodes use `finalizeblock`: * **Decoding:** Since `FinalizeBlock` is an ABCI call, `Tx` is received in the encoded `[]byte` form. - Nodes first unmarshal the transaction, using the [`TxConfig`](./app-anatomy#register-codec) defined in the app, then call `runTx` in `execModeFinalize`, which is very similar to `CheckTx` but also executes and writes state changes. + Nodes first unmarshal the transaction, using the [`TxConfig`](./00-app-anatomy.md#register-codec) defined in the app, then call `runTx` in `execModeFinalize`, which is very similar to `CheckTx` but also executes and writes state changes. * **Checks and `AnteHandler`:** Full-nodes call `validateBasicMsgs` and `AnteHandler` again. This second check happens because they may not have seen the same transactions during the addition to Mempool stage diff --git a/docs/learn/beginner/02-query-lifecycle.md b/docs/learn/beginner/02-query-lifecycle.md index c3d7eb1cc..4b11bfed6 100644 --- a/docs/learn/beginner/02-query-lifecycle.md +++ b/docs/learn/beginner/02-query-lifecycle.md @@ -17,7 +17,7 @@ This document describes the lifecycle of a query in a Cosmos SDK application, fr A [**query**](../../build/building-modules/02-messages-and-queries.md#queries) is a request for information made by end-users of applications through an interface and processed by a full-node. Users can query information about the network, the application itself, and application state directly from the application's stores or modules. Note that queries are different from [transactions](../advanced/01-transactions.md) (view the lifecycle [here](./01-tx-lifecycle.md)), particularly in that they do not require consensus to be processed (as they do not trigger state-transitions); they can be fully handled by one full-node. -For the purpose of explaining the query lifecycle, let's say the query, `MyQuery`, is requesting a list of delegations made by a certain delegator address in the application called `simapp`. As is to be expected, the [`staking`](../../build/modules/staking/README.md) module handles this query. But first, there are a few ways `MyQuery` can be created by users. +For the purpose of explaining the query lifecycle, let's say the query, `MyQuery`, is requesting a list of delegations made by a certain delegator address in the application called `simapp`. As is to be expected, the [`staking`](../../../../x/staking/README.md) module handles this query. But first, there are a few ways `MyQuery` can be created by users. ### CLI @@ -27,7 +27,7 @@ The main interface for an application is the command-line interface. Users conne simd query staking delegations ``` -This query command was defined by the [`staking`](../../build/modules/staking/README.md) module developer and added to the list of subcommands by the application developer when creating the CLI. +This query command was defined by the [`staking`](../../../../x/staking/README.md) module developer and added to the list of subcommands by the application developer when creating the CLI. Note that the general format is as follows: @@ -47,7 +47,7 @@ One such tool is [grpcurl](https://github.com/fullstorydev/grpcurl), and a gRPC ```bash grpcurl \ - -plaintext # We want results in plain test + -plaintext # We want results in plain text -import-path ./proto \ # Import these .proto files -proto ./proto/cosmos/staking/v1beta1/query.proto \ # Look into this .proto file for the Query protobuf service -d '{"address":"$MY_DELEGATOR"}' \ # Query arguments @@ -74,9 +74,9 @@ The preceding examples show how an external user can interact with a node by que The first thing that is created in the execution of a CLI command is a `client.Context`. A `client.Context` is an object that stores all the data needed to process a request on the user side. In particular, a `client.Context` stores the following: * **Codec**: The [encoder/decoder](../advanced/05-encoding.md) used by the application, used to marshal the parameters and query before making the CometBFT RPC request and unmarshal the returned response into a JSON object. The default codec used by the CLI is Protobuf. -* **Account Decoder**: The account decoder from the [`auth`](../../build/modules/auth/README.md) module, which translates `[]byte`s into accounts. +* **Account Decoder**: The account decoder from the [`auth`](../../../../x/auth/README.md) module, which translates `[]byte`s into accounts. * **RPC Client**: The CometBFT RPC Client, or node, to which requests are relayed. -* **Keyring**: A [Key Manager]../beginner/03-accounts.md#keyring) used to sign transactions and handle other operations with keys. +* **Keyring**: A [Key Manager](../beginner/03-accounts.md#keyring) used to sign transactions and handle other operations with keys. * **Output Writer**: A [Writer](https://pkg.go.dev/io/#Writer) used to output the response. * **Configurations**: The flags configured by the user for this command, including `--height`, specifying the height of the blockchain to query, and `--indent`, which indicates to add an indent to the JSON response. @@ -134,7 +134,7 @@ Once a result is received from the querier, `baseapp` begins the process of retu ## Response -Since `Query()` is an ABCI function, `baseapp` returns the response as an [`abci.ResponseQuery`](https://docs.cometbft.com/master/spec/abci/abci.html#query-2) type. The `client.Context` `Query()` routine receives the response and. +Since `Query()` is an ABCI function, `baseapp` returns the response as an [`abci.QueryResponse`](https://docs.cometbft.com/main/spec/abci/abci++_methods#query) type. The `client.Context` `Query()` routine receives the response and processes it. ### CLI Response diff --git a/docs/learn/beginner/03-accounts.md b/docs/learn/beginner/03-accounts.md index 80f787d32..150436b9d 100644 --- a/docs/learn/beginner/03-accounts.md +++ b/docs/learn/beginner/03-accounts.md @@ -72,7 +72,7 @@ In the node, all data is stored using Protocol Buffers serialization. The Cosmos SDK supports the following digital key schemes for creating digital signatures: * `secp256k1`, as implemented in the [Cosmos SDK's `crypto/keys/secp256k1` package](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/keys/secp256k1/secp256k1.go). -* `secp256r1`, as implemented in the [Cosmos SDK's `crypto/keys/secp256r1` package](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/keys/secp256r1/pubkey.go), +* `secp256r1`, as implemented in the [Cosmos SDK's `crypto/keys/secp256r1` package](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/keys/secp256r1/pubkey.go). * `tm-ed25519`, as implemented in the [Cosmos SDK `crypto/keys/ed25519` package](https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/keys/ed25519/ed25519.go). This scheme is supported only for the consensus validation. | | Address length in bytes | Public key length in bytes | Used for transaction authentication | Used for consensus (cometbft) | @@ -173,7 +173,7 @@ To create a new key type for using in keyring, `keyring.SignatureAlgo` interface https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/keyring/signing_algorithms.go#L11-L16 ``` -The interface consists in three methods where `Name()` returns the name of the algorithm as a `hd.PubKeyType` and `Derive()` and `Generate()` must return the following functions respectively: +The interface consists of three methods where `Name()` returns the name of the algorithm as a `hd.PubKeyType` and `Derive()` and `Generate()` must return the following functions respectively: ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.53.0/crypto/hd/algo.go#L28-L31 diff --git a/docs/learn/beginner/04-gas-fees.md b/docs/learn/beginner/04-gas-fees.md index a502bc8e5..5aea1238b 100644 --- a/docs/learn/beginner/04-gas-fees.md +++ b/docs/learn/beginner/04-gas-fees.md @@ -23,7 +23,7 @@ In the Cosmos SDK, `gas` is a special unit that is used to track the consumption ## Gas Meter -In the Cosmos SDK, `gas` is a simple alias for `uint64`, and is managed by an object called a _gas meter_. Gas meters implement the `GasMeter` interface +In the Cosmos SDK, `gas` is a simple alias for `uint64`, and is managed by an object called a _gas meter_. Gas meters implement the `GasMeter` interface: ```go reference https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/store/types/gas.go#L40-L51 @@ -32,7 +32,7 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/store/types/gas.go#L40-L5 where: * `GasConsumed()` returns the amount of gas that was consumed by the gas meter instance. -* `GasConsumedToLimit()` returns the amount of gas that was consumed by gas meter instance, or the limit if it is reached. +* `GasConsumedToLimit()` returns the amount of gas that was consumed by the gas meter instance, or the limit if it is reached. * `GasRemaining()` returns the gas left in the GasMeter. * `Limit()` returns the limit of the gas meter instance. `0` if the gas meter is infinite. * `ConsumeGas(amount Gas, descriptor string)` consumes the amount of `gas` provided. If the `gas` overflows, it panics with the `descriptor` message. If the gas meter is not infinite, it panics if `gas` consumed goes above the limit. @@ -46,7 +46,7 @@ The gas meter is generally held in [`ctx`](../advanced/02-context.md), and consu ctx.GasMeter().ConsumeGas(amount, "description") ``` -By default, the Cosmos SDK makes use of two different gas meters, the [main gas meter](#main-gas-metter) and the [block gas meter](#block-gas-meter). +By default, the Cosmos SDK makes use of two different gas meters, the [main gas meter](#main-gas-meter) and the [block gas meter](#block-gas-meter). ### Main Gas Meter @@ -58,22 +58,22 @@ Gas consumption can be done manually, generally by the module developer in the [ `ctx.BlockGasMeter()` is the gas meter used to track gas consumption per block and make sure it does not go above a certain limit. -During the genesis phase, gas consumption is unlimited to accommodate initialisation transactions. +During the genesis phase, gas consumption is unlimited to accommodate initialization transactions. ```go app.finalizeBlockState.SetContext(app.finalizeBlockState.Context().WithBlockGasMeter(storetypes.NewInfiniteGasMeter())) ``` -Following the genesis block, the block gas meter is set to a finite value by the SDK. This transition is facilitated by the consensus engine (e.g., CometBFT) calling the `RequestFinalizeBlock` function, which in turn triggers the SDK's `FinalizeBlock` method. Within `FinalizeBlock`, `internalFinalizeBlock` is executed, performing necessary state updates and function executions. The block gas meter, initialised each with a finite limit, is then incorporated into the context for transaction execution, ensuring gas consumption does not exceed the block's gas limit and is reset at the end of each block. +Following the genesis block, the block gas meter is set to a finite value by the SDK. This transition is facilitated by the consensus engine (e.g., CometBFT) calling the `RequestFinalizeBlock` function, which in turn triggers the SDK's `FinalizeBlock` method. Within `FinalizeBlock`, `internalFinalizeBlock` is executed, performing necessary state updates and function executions. The block gas meter, initialized each with a finite limit, is then incorporated into the context for transaction execution, ensuring gas consumption does not exceed the block's gas limit and is reset at the end of each block. -Modules within the Cosmos SDK can consume block gas at any point during their execution by utilising the `ctx`. This gas consumption primarily occurs during state read/write operations and transaction processing. The block gas meter, accessible via `ctx.BlockGasMeter()`, monitors the total gas usage within a block, enforcing the gas limit to prevent excessive computation. This ensures that gas limits are adhered to on a per-block basis, starting from the first block post-genesis. +Modules within the Cosmos SDK can consume block gas at any point during their execution by utilizing the `ctx`. This gas consumption primarily occurs during state read/write operations and transaction processing. The block gas meter, accessible via `ctx.BlockGasMeter()`, monitors the total gas usage within a block, enforcing the gas limit to prevent excessive computation. This ensures that gas limits are adhered to on a per-block basis, starting from the first block post-genesis. ```go gasMeter := app.getBlockGasMeter(app.finalizeBlockState.Context()) app.finalizeBlockState.SetContext(app.finalizeBlockState.Context().WithBlockGasMeter(gasMeter)) ``` -This above shows the general mechanism for setting the block gas meter with a finite limit based on the block's consensus parameters. +The above shows the general mechanism for setting the block gas meter with a finite limit based on the block's consensus parameters. ## AnteHandler @@ -94,8 +94,8 @@ https://github.com/cosmos/cosmos-sdk/blob/v0.53.0-rc.2/proto/cosmos/tx/v1beta1/t ``` * Verify signatures for each [`message`](../../build/building-modules/02-messages-and-queries.md#messages) contained in the transaction. Each `message` should be signed by one or multiple sender(s), and these signatures must be verified in the `anteHandler`. -* During `CheckTx`, verify that the gas prices provided with the transaction is greater than the local `min-gas-prices` (as a reminder, gas-prices can be deducted from the following equation: `fees = gas * gas-prices`). `min-gas-prices` is a parameter local to each full-node and used during `CheckTx` to discard transactions that do not provide a minimum amount of fees. This ensures that the mempool cannot be spammed with garbage transactions. +* During `CheckTx`, verify that the gas prices provided with the transaction are greater than the local `min-gas-prices` (as a reminder, gas-prices can be deducted from the following equation: `fees = gas * gas-prices`). `min-gas-prices` is a parameter local to each full-node and used during `CheckTx` to discard transactions that do not provide a minimum amount of fees. This ensures that the mempool cannot be spammed with garbage transactions. * Verify that the sender of the transaction has enough funds to cover for the `fees`. When the end-user generates a transaction, they must indicate 2 of the 3 following parameters (the third one being implicit): `fees`, `gas` and `gas-prices`. This signals how much they are willing to pay for nodes to execute their transaction. The provided `gas` value is stored in a parameter called `GasWanted` for later use. -* Set `newCtx.GasMeter` to 0, with a limit of `GasWanted`. **This step is crucial**, as it not only makes sure the transaction cannot consume infinite gas, but also that `ctx.GasMeter` is reset in-between each transaction (`ctx` is set to `newCtx` after `anteHandler` is run, and the `anteHandler` is run each time a transactions executes). +* Set `newCtx.GasMeter` to 0, with a limit of `GasWanted`. **This step is crucial**, as it not only makes sure the transaction cannot consume infinite gas, but also that `ctx.GasMeter` is reset in-between each transaction (`ctx` is set to `newCtx` after `anteHandler` is run, and the `anteHandler` is run each time a transaction executes). As explained above, the `anteHandler` returns a maximum limit of `gas` the transaction can consume during execution called `GasWanted`. The actual amount consumed in the end is denominated `GasUsed`, and we must therefore have `GasUsed =< GasWanted`. Both `GasWanted` and `GasUsed` are relayed to the underlying consensus engine when [`FinalizeBlock`](../advanced/00-baseapp.md#finalizeblock) returns. diff --git a/docs/learn/intro/00-overview.md b/docs/learn/intro/00-overview.md index a424dfdfe..f1e896f39 100644 --- a/docs/learn/intro/00-overview.md +++ b/docs/learn/intro/00-overview.md @@ -32,7 +32,7 @@ Today there is a lot of talk around modularity and discussions between monolithi The Cosmos SDK is the most advanced framework for building custom modular application-specific blockchains today. Here are a few reasons why you might want to consider building your decentralized application with the Cosmos SDK: * It allows you to plug and play and customize your consensus layer. As above you can use Rollkit and Celestia as your consensus and data availability layer. This offers a lot of flexibility and customisation. -* Previously the default consensus engine available within the Cosmos SDK is [CometBFT](https://github.com/cometbft/cometbft). CometBFT is the most (and only) mature BFT consensus engine in existence. It is widely used across the industry and is considered the gold standard consensus engine for building Proof-of-Stake systems. +* Previously the default consensus engine available within the Cosmos SDK is [CometBFT](https://github.com/cometbft/cometbft). CometBFT is the most mature BFT consensus engine in existence. It is widely used across the industry and is considered the gold standard consensus engine for building Proof-of-Stake systems. * The Cosmos SDK is open-source and designed to make it easy to build blockchains out of composable [modules](../../build/modules). As the ecosystem of open-source Cosmos SDK modules grows, it will become increasingly easier to build complex decentralized platforms with it. * The Cosmos SDK is inspired by capabilities-based security, and informed by years of wrestling with blockchain state-machines. This makes the Cosmos SDK a very secure environment to build blockchains. * Most importantly, the Cosmos SDK has already been used to build many application-specific blockchains that are already in production. Among others, we can cite [Cosmos Hub](https://hub.cosmos.network), [IRIS Hub](https://irisnet.org), [Binance Chain](https://docs.binance.org/), [Terra](https://terra.money/) or [Kava](https://www.kava.io/). [Many more](https://cosmos.network/ecosystem) are building on the Cosmos SDK. diff --git a/docs/learn/intro/01-why-app-specific.md b/docs/learn/intro/01-why-app-specific.md index 0f0c1c64e..df16c19af 100644 --- a/docs/learn/intro/01-why-app-specific.md +++ b/docs/learn/intro/01-why-app-specific.md @@ -60,7 +60,7 @@ The list above contains a few examples that show how much flexibility applicatio Decentralized applications built with Smart Contracts are inherently capped in performance by the underlying environment. For a decentralized application to optimise performance, it needs to be built as an application-specific blockchain. Next are some of the benefits an application-specific blockchain brings in terms of performance: -* Developers of application-specific blockchains can choose to operate with a novel consensus engine such as CometBFT BFT. Compared to Proof-of-Work (used by most virtual-machine blockchains today), it offers significant gains in throughput. +* Developers of application-specific blockchains can choose to operate with a novel consensus engine such as CometBFT. Compared to Proof-of-Work (used by most virtual-machine blockchains today), it offers significant gains in throughput. * An application-specific blockchain only operates a single application, so that the application does not compete with others for computation and storage. This is the opposite of most non-sharded virtual-machine blockchains today, where smart contracts all compete for computation and storage. * Even if a virtual-machine blockchain offered application-based sharding coupled with an efficient consensus algorithm, performance would still be limited by the virtual-machine itself. The real throughput bottleneck is the state-machine, and requiring transactions to be interpreted by a virtual-machine significantly increases the computational complexity of processing them. @@ -74,6 +74,6 @@ Security is hard to quantify, and greatly varies from platform to platform. That ### Sovereignty -One of the major benefits of application-specific blockchains is sovereignty. A decentralized application is an ecosystem that involves many actors: users, developers, third-party services, and more. When developers build on virtual-machine blockchain where many decentralized applications coexist, the community of the application is different than the community of the underlying blockchain, and the latter supersedes the former in the governance process. If there is a bug or if a new feature is needed, stakeholders of the application have very little leeway to upgrade the code. If the community of the underlying blockchain refuses to act, nothing can happen. +One of the major benefits of application-specific blockchains is sovereignty. A decentralized application is an ecosystem that involves many actors: users, developers, third-party services, and more. When developers build on a virtual-machine blockchain where many decentralized applications coexist, the community of the application is different than the community of the underlying blockchain, and the latter supersedes the former in the governance process. If there is a bug or if a new feature is needed, stakeholders of the application have very little leeway to upgrade the code. If the community of the underlying blockchain refuses to act, nothing can happen. The fundamental issue here is that the governance of the application and the governance of the network are not aligned. This issue is solved by application-specific blockchains. Because application-specific blockchains specialize to operate a single application, stakeholders of the application have full control over the entire chain. This ensures that the community will not be stuck if a bug is discovered, and that it has the freedom to choose how it is going to evolve. diff --git a/docs/learn/intro/02-sdk-app-architecture.md b/docs/learn/intro/02-sdk-app-architecture.md index c2ff7bbf6..532c27437 100644 --- a/docs/learn/intro/02-sdk-app-architecture.md +++ b/docs/learn/intro/02-sdk-app-architecture.md @@ -84,7 +84,7 @@ Note that **CometBFT only handles transaction bytes**. It has no knowledge of wh Here are the most important messages of the ABCI: -* `CheckTx`: When a transaction is received by CometBFT, it is passed to the application to check if a few basic requirements are met. `CheckTx` is used to protect the mempool of full-nodes against spam transactions. . A special handler called the [`AnteHandler`](../beginner/04-gas-fees.md#antehandler) is used to execute a series of validation steps such as checking for sufficient fees and validating the signatures. If the checks are valid, the transaction is added to the [mempool](https://docs.cometbft.com/v0.37/spec/p2p/legacy-docs/messages/mempool) and relayed to peer nodes. Note that transactions are not processed (i.e. no modification of the state occurs) with `CheckTx` since they have not been included in a block yet. +* `CheckTx`: When a transaction is received by CometBFT, it is passed to the application to check if a few basic requirements are met. `CheckTx` is used to protect the mempool of full-nodes against spam transactions. A special handler called the [`AnteHandler`](../beginner/04-gas-fees.md#antehandler) is used to execute a series of validation steps such as checking for sufficient fees and validating the signatures. If the checks are valid, the transaction is added to the [mempool](https://docs.cometbft.com/v0.37/spec/p2p/legacy-docs/messages/mempool) and relayed to peer nodes. Note that transactions are not processed (i.e. no modification of the state occurs) with `CheckTx` since they have not been included in a block yet. * `DeliverTx`: When a [valid block](https://docs.cometbft.com/v0.37/spec/core/data_structures#block) is received by CometBFT, each transaction in the block is passed to the application via `DeliverTx` in order to be processed. It is during this stage that the state transitions occur. The `AnteHandler` executes again, along with the actual [`Msg` service](../../build/building-modules/03-msg-services.md) RPC for each message in the transaction. * `BeginBlock`/`EndBlock`: These messages are executed at the beginning and the end of each block, whether the block contains transactions or not. It is useful to trigger automatic execution of logic. Proceed with caution though, as computationally expensive loops could slow down your blockchain, or even freeze it if the loop is infinite. diff --git a/docs/learn/learn.md b/docs/learn/learn.md index 01eea6187..ff14d7269 100644 --- a/docs/learn/learn.md +++ b/docs/learn/learn.md @@ -3,7 +3,7 @@ sidebar_position: 0 --- # Learn -* [Introduction](./intro/00-overview.md) - Dive into the fundamentals of Cosmos SDK with an insightful introduction, +* [Introduction](./intro/00-overview.md) - Dive into the fundamentals of Cosmos SDK with an insightful introduction, laying the groundwork for understanding blockchain development. In this section we provide a High-Level Overview of the SDK, then dive deeper into Core concepts such as Application-Specific Blockchains, Blockchain Architecture, and finally we begin to explore the main components of the SDK. * [Beginner](./beginner/00-app-anatomy.md) - Start your journey with beginner-friendly resources in the Cosmos SDK's "Learn" section, providing a gentle entry point for newcomers to blockchain development. Here we focus on a little more detail, covering the Anatomy of a Cosmos SDK Application, Transaction Lifecycles, Accounts and lastly, Gas and Fees. diff --git a/docs/user/run-node/00-keyring.md b/docs/user/run-node/00-keyring.md index e46ba5745..95f754d91 100644 --- a/docs/user/run-node/00-keyring.md +++ b/docs/user/run-node/00-keyring.md @@ -22,7 +22,7 @@ all operating systems. The `os` backend relies on operating system-specific defaults to handle key storage securely. Typically, an operating system's credential subsystem handles password prompts, private keys storage, and user sessions according to the user's password policies. Here -is a list of the most popular operating systems and their respective passwords manager: +is a list of the most popular operating systems and their respective password managers: * macOS: [Keychain](https://support.apple.com/en-gb/guide/keychain-access/welcome/mac) * Windows: [Credentials Management API](https://docs.microsoft.com/en-us/windows/win32/secauthn/credentials-management) @@ -35,7 +35,7 @@ GNU/Linux distributions that use GNOME as the default desktop environment typica [Seahorse](https://wiki.gnome.org/Apps/Seahorse). Users of KDE based distributions are commonly provided with [KDE Wallet Manager](https://userbase.kde.org/KDE_Wallet_Manager). Whilst the former is in fact a `libsecret` convenient frontend, the latter is a `kwallet` -client. `keyctl` is a secure backend that leverages the Linux's kernel security key management system +client. `keyctl` is a secure backend that leverages the Linux kernel security key management system to store cryptographic keys securely in memory. `os` is the default option since operating system's default credentials managers are @@ -91,8 +91,8 @@ one you may want to use specifically to encrypt the password store. ### The `kwallet` backend The `kwallet` backend uses `KDE Wallet Manager`, which comes installed by default on the -GNU/Linux distributions that ships KDE as default desktop environment. Please refer to -[KWallet Handbook](https://docs.kde.org/stable5/en/kdeutils/kwallet5/index.html) for more +GNU/Linux distributions that ship KDE as the default desktop environment. Please refer to +[KWallet API documentation](https://api.kde.org/frameworks/kwallet/html/index.html) for more information. ### The `keyctl` backend @@ -117,7 +117,7 @@ The `memory` backend stores keys in memory. The keys are immediately deleted aft **Provided for testing purposes only. The `memory` backend is not recommended for use in production environments**. -### Setting backend using the env variable +### Setting backend using an env variable You can set the keyring-backend using env variable: `BINNAME_KEYRING_BACKEND`. For example, if your binary name is `gaia-v5` then set: `export GAIA_V5_KEYRING_BACKEND=pass` diff --git a/docs/user/run-node/01-run-node.md b/docs/user/run-node/01-run-node.md index cf7e3b840..88aa38f2b 100644 --- a/docs/user/run-node/01-run-node.md +++ b/docs/user/run-node/01-run-node.md @@ -50,7 +50,7 @@ The `~/.simapp` folder has the following structure: ## Updating Some Default Settings -If you want to change any field values in configuration files (for ex: genesis.json) you can use `jq` ([installation](https://stedolan.github.io/jq/download/) & [docs](https://stedolan.github.io/jq/manual/#Assignment)) & `sed` commands to do that. Few examples are listed here. +If you want to change any field values in configuration files (for ex: genesis.json) you can use `jq` ([installation](https://stedolan.github.io/jq/download/) & [docs](https://stedolan.github.io/jq/manual/#Assignment)) & `sed` commands to do that. A few examples are listed here. ```bash # to change the chain-id @@ -68,7 +68,7 @@ jq '.app_state.mint.minter.inflation = "0.300000000000000000"' genesis.json > te ### Client Interaction -When instantiating a node, GRPC and REST are defaulted to localhost to avoid unknown exposure of your node to the public. It is recommended to not expose these endpoints without a proxy that can handle load balancing or authentication is set up between your node and the public. +When instantiating a node, GRPC and REST are defaulted to localhost to avoid unknown exposure of your node to the public. It is recommended not to expose these endpoints without a proxy that can handle load balancing or authentication set up between your node and the public. :::tip A commonly used tool for this is [nginx](https://nginx.org). diff --git a/docs/user/run-node/02-interact-node.md b/docs/user/run-node/02-interact-node.md index a511aec41..1a76f02fc 100644 --- a/docs/user/run-node/02-interact-node.md +++ b/docs/user/run-node/02-interact-node.md @@ -54,7 +54,7 @@ You should see two delegations, the first one made from the `gentx`, and the sec ## Using gRPC -The Protobuf ecosystem developed tools for different use cases, including code-generation from `*.proto` files into various languages. These tools allow the building of clients easily. Often, the client connection (i.e. the transport) can be plugged and replaced very easily. Let's explore one of the most popular transport: [gRPC](../../learn/advanced/06-grpc_rest.md). +The Protobuf ecosystem developed tools for different use cases, including code-generation from `*.proto` files into various languages. These tools allow the building of clients easily. Often, the client connection (i.e. the transport) can be plugged and replaced very easily. Let's explore one of the most popular transports: [gRPC](../../learn/advanced/06-grpc_rest.md). Since the code generation library largely depends on your own tech stack, we will only present three alternatives: @@ -66,7 +66,7 @@ Since the code generation library largely depends on your own tech stack, we wil [grpcurl](https://github.com/fullstorydev/grpcurl) is like `curl` but for gRPC. It is also available as a Go library, but we will use it only as a CLI command for debugging and testing purposes. Follow the instructions in the previous link to install it. -Assuming you have a local node running (either a localnet, or connected a live network), you should be able to run the following command to list the Protobuf services available (you can replace `localhost:9000` by the gRPC server endpoint of another node, which is configured under the `grpc.address` field inside [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml)): +Assuming you have a local node running (either a localnet, or connected to a live network), you should be able to run the following command to list the Protobuf services available (you can replace `localhost:9000` by the gRPC server endpoint of another node, which is configured under the `grpc.address` field inside [`app.toml`](../../user/run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml)): ```bash grpcurl -plaintext localhost:9090 list @@ -244,13 +244,13 @@ func main() { ### CosmJS -CosmJS documentation can be found at [https://cosmos.github.io/cosmjs](https://cosmos.github.io/cosmjs). As of January 2021, CosmJS documentation is still work in progress. +CosmJS documentation can be found at [https://cosmos.github.io/cosmjs](https://cosmos.github.io/cosmjs). As of January 2021, CosmJS documentation is still a work in progress. ## Using the REST Endpoints As described in the [gRPC guide](../../learn/advanced/06-grpc_rest.md), all gRPC services on the Cosmos SDK are made available for more convenient REST-based queries through gRPC-gateway. The format of the URL path is based on the Protobuf service method's full-qualified name, but may contain small customizations so that final URLs look more idiomatic. For example, the REST endpoint for the `cosmos.bank.v1beta1.Query/AllBalances` method is `GET /cosmos/bank/v1beta1/balances/{address}`. Request arguments are passed as query parameters. -Note that the REST endpoints are not enabled by default. To enable them, edit the `api` section of your `~/.simapp/config/app.toml` file: +Note that the REST endpoints are not enabled by default. To enable them, edit the `api` section of your `~/.simapp/config/app.toml` file: ```toml # Enable defines if the API server should be enabled. @@ -268,7 +268,7 @@ curl \ Make sure to replace `localhost:1317` with the REST endpoint of your node, configured under the `api.address` field. -The list of all available REST endpoints is available as a Swagger specification file, it can be viewed at `localhost:1317/swagger`. Make sure that the `api.swagger` field is set to true in your [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml) file. +The list of all available REST endpoints is available as a Swagger specification file, it can be viewed at `localhost:1317/swagger`. Make sure that the `api.swagger` field is set to true in your [`app.toml`](../../user/run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml) file. ### Query for historical state using REST @@ -286,4 +286,4 @@ Assuming the state at that block has not yet been pruned by the node, this query ### Cross-Origin Resource Sharing (CORS) -[CORS policies](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) are not enabled by default to help with security. If you would like to use the rest-server in a public environment we recommend you provide a reverse proxy, this can be done with [nginx](https://www.nginx.com/). For testing and development purposes there is an `enabled-unsafe-cors` field inside [`app.toml`](../run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml). +[CORS policies](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) are not enabled by default to help with security. If you would like to use the rest-server in a public environment we recommend you provide a reverse proxy, this can be done with [nginx](https://www.nginx.com/). For testing and development purposes there is an `enabled-unsafe-cors` field inside [`app.toml`](../../user/run-node/01-run-node.md#configuring-the-node-using-apptoml-and-configtoml). diff --git a/docs/user/run-node/03-txs.md b/docs/user/run-node/03-txs.md index d6a343885..93f81055b 100644 --- a/docs/user/run-node/03-txs.md +++ b/docs/user/run-node/03-txs.md @@ -161,7 +161,7 @@ func sendTx() error { // Define two x/bank MsgSend messages: // - from addr1 to addr3, // - from addr2 to addr3. - // This means that the transactions needs two signers: addr1 and addr2. + // This means that the transaction needs two signers: addr1 and addr2. msg1 := banktypes.NewMsgSend(addr1, addr3, types.NewCoins(types.NewInt64Coin("atom", 12))) msg2 := banktypes.NewMsgSend(addr2, addr3, types.NewCoins(types.NewInt64Coin("atom", 34))) @@ -420,10 +420,10 @@ Broadcasting a transaction using the REST endpoint (served by `gRPC-gateway`) ca ```bash curl -X POST \ -H "Content-Type: application/json" \ - -d'{"tx_bytes":"{{txBytes}}","mode":"BROADCAST_MODE_SYNC"}' \ + -d' {"tx_bytes":"{{txBytes}}","mode":"BROADCAST_MODE_SYNC"}' \ localhost:1317/cosmos/tx/v1beta1/txs ``` ## Using CosmJS (JavaScript & TypeScript) -CosmJS aims to build client libraries in JavaScript that can be embedded in web applications. Please see [https://cosmos.github.io/cosmjs](https://cosmos.github.io/cosmjs) for more information. As of January 2021, CosmJS documentation is still work in progress. +CosmJS aims to build client libraries in JavaScript that can be embedded in web applications. Please see [https://cosmos.github.io/cosmjs](https://cosmos.github.io/cosmjs) for more information. As of January 2021, CosmJS documentation is still a work in progress. diff --git a/docs/user/run-node/06-run-production.md b/docs/user/run-node/06-run-production.md index dd9d9d114..6eee48087 100644 --- a/docs/user/run-node/06-run-production.md +++ b/docs/user/run-node/06-run-production.md @@ -18,7 +18,7 @@ There are many different ways to secure a server and your node, the described st This walkthrough assumes the underlying operating system is Ubuntu. ::: -## Sever Setup +## Server Setup ### User @@ -196,13 +196,13 @@ tmkms softsign import $HOME/tmkms/config/secrets/priv_validator_key.json $HOME/t At this point, it is necessary to delete the `priv_validator_key.json` from the validator node and the tmkms node. Since the key has been imported into tmkms (above) it is no longer necessary on the nodes. The key can be safely stored offline. -4. Modifiy the `tmkms.toml`. +4. Modify the `tmkms.toml`. ```bash vim $HOME/tmkms/config/tmkms.toml ``` -This example shows a configuration that could be used for soft signing. The example has an IP of `123.456.12.345` with a port of `26659` a chain_id of `test-chain-waSDSe`. These are items that most be modified for the usecase of tmkms and the network. +This example shows a configuration that could be used for soft signing. The example has an IP of `123.456.12.345` with a port of `26659` a chain_id of `test-chain-waSDSe`. These are items that must be modified for the usecase of tmkms and the network. ```toml # CometBFT KMS configuration file diff --git a/docs/user/user.md b/docs/user/user.md index 14fc78e92..5429e8ad6 100644 --- a/docs/user/user.md +++ b/docs/user/user.md @@ -7,4 +7,4 @@ This section is designed for developers who are using the Cosmos SDK to build ap * [Setting up keys](./run-node/00-keyring.md) - Learn how to set up secure key management using the Cosmos SDK's keyring feature. This guide provides a streamlined approach to cryptographic key handling, which is crucial for securing your application. * [Running a node](./run-node/01-run-node.md) - This guide provides step-by-step instructions to deploy and manage a node in the Cosmos network. It ensures a smooth and reliable operation of your blockchain application by covering all the necessary setup and maintenance steps. -* [CLI](./run-node/02-interact-node.md) - Discover how to navigate and interact with the Cosmos SDK using the Command Line Interface (CLI). This section covers efficient and powerful command-based operations that can help you manage your application effectively. \ No newline at end of file +* [CLI](./run-node/02-interact-node.md) - Discover how to navigate and interact with the Cosmos SDK using the Command Line Interface (CLI). This section covers efficient and powerful command-based operations that can help you manage your application effectively. diff --git a/versioned_docs/version-0.5/build/migrations/02-upgrading.md b/versioned_docs/version-0.5/build/migrations/02-upgrading.md index f44270ea6..c63f249d3 100644 --- a/versioned_docs/version-0.5/build/migrations/02-upgrading.md +++ b/versioned_docs/version-0.5/build/migrations/02-upgrading.md @@ -429,7 +429,25 @@ For ante handler construction via `ante.NewAnteHandler`, the field `ante.Handler #### `x/capability` -Capability has been moved to [IBC Go](https://github.com/cosmos/ibc-go). IBC v8 will contain the necessary changes to incorporate the new module location. +The capability module has been moved to [cosmos/ibc-go](https://github.com/cosmos/ibc-go). IBC v8 will contain the necessary changes to incorporate the new module location. In your `app.go`, you must import the capability module from the new location: + +```diff ++ "github.com/cosmos/ibc-go/modules/capability" ++ capabilitykeeper "github.com/cosmos/ibc-go/modules/capability/keeper" ++ capabilitytypes "github.com/cosmos/ibc-go/modules/capability/types" +- "github.com/cosmos/cosmos-sdk/x/capability/types" +- capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" +- capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" +``` + +Similar to previous versions, your module manager must include the capability module. + +```go +app.ModuleManager = module.NewManager( + capability.NewAppModule(encodingConfig.Codec, *app.CapabilityKeeper, true), + // remaining modules +) +``` #### `x/genutil` diff --git a/versioned_docs/version-0.53/build/modules/circuit/README.md b/versioned_docs/version-0.53/build/modules/circuit/README.md index f3b753896..f0cbe5746 100644 --- a/versioned_docs/version-0.53/build/modules/circuit/README.md +++ b/versioned_docs/version-0.53/build/modules/circuit/README.md @@ -168,3 +168,90 @@ The circuit module emits the following events: * `DisableListPrefix` - `0x02` ## Client - list and describe CLI commands and gRPC and REST endpoints + +## Examples: Using Circuit Breaker CLI Commands + +This section provides practical examples for using the Circuit Breaker module through the command-line interface (CLI). These examples demonstrate how to authorize accounts, disable (trip) specific message types, and re-enable (reset) them when needed. + +### Querying Circuit Breaker Permissions + +Check an account's current circuit breaker permissions: + +```bash +# Query permissions for a specific account + query circuit account-permissions + +# Example: +simd query circuit account-permissions cosmos1... +``` + +Check which message types are currently disabled: + +```bash +# Query all disabled message types + query circuit disabled-list + +# Example: +simd query circuit disabled-list +``` + +### Authorizing an Account as Circuit Breaker + +Only a super-admin or the module authority (typically the governance module account) can grant circuit breaker permissions to other accounts: + +```bash +# Grant LEVEL_ALL_MSGS permission (can disable any message type) + tx circuit authorize --level=ALL_MSGS --from= --gas=auto --gas-adjustment=1.5 + +# Grant LEVEL_SOME_MSGS permission (can only disable specific message types) + tx circuit authorize --level=SOME_MSGS --limit-type-urls="/cosmos.bank.v1beta1.MsgSend,/cosmos.staking.v1beta1.MsgDelegate" --from= --gas=auto --gas-adjustment=1.5 + +# Grant LEVEL_SUPER_ADMIN permission (can disable messages and authorize other accounts) + tx circuit authorize --level=SUPER_ADMIN --from= --gas=auto --gas-adjustment=1.5 +``` + +### Disabling Message Processing (Trip) + +Disable specific message types to prevent their execution (requires authorization): + +```bash +# Disable a single message type + tx circuit trip --type-urls="/cosmos.bank.v1beta1.MsgSend" --from= --gas=auto --gas-adjustment=1.5 + +# Disable multiple message types + tx circuit trip --type-urls="/cosmos.bank.v1beta1.MsgSend,/cosmos.staking.v1beta1.MsgDelegate" --from= --gas=auto --gas-adjustment=1.5 + +# Disable all message types (emergency measure) + tx circuit trip --from= --gas=auto --gas-adjustment=1.5 +``` + +### Re-enabling Message Processing (Reset) + +Re-enable previously disabled message types (requires authorization): + +```bash +# Re-enable a single message type + tx circuit reset --type-urls="/cosmos.bank.v1beta1.MsgSend" --from= --gas=auto --gas-adjustment=1.5 + +# Re-enable multiple message types + tx circuit reset --type-urls="/cosmos.bank.v1beta1.MsgSend,/cosmos.staking.v1beta1.MsgDelegate" --from= --gas=auto --gas-adjustment=1.5 + +# Re-enable all disabled message types + tx circuit reset --from= --gas=auto --gas-adjustment=1.5 +``` + +### Usage in Emergency Scenarios + +In case of a critical vulnerability in a specific message type: + +1. Quickly disable the vulnerable message type: + ```bash + tx circuit trip --type-urls="/cosmos.vulnerable.v1beta1.MsgVulnerable" --from= --gas=auto --gas-adjustment=1.5 + ``` + +2. After a fix is deployed, re-enable the message type: + ```bash + tx circuit reset --type-urls="/cosmos.vulnerable.v1beta1.MsgVulnerable" --from= --gas=auto --gas-adjustment=1.5 + ``` + +This allows chains to surgically disable problematic functionality without halting the entire chain, providing time for developers to implement and deploy fixes. diff --git a/versioned_docs/version-0.53/build/modules/staking/README.md b/versioned_docs/version-0.53/build/modules/staking/README.md index c011a593d..dd3c6d56b 100644 --- a/versioned_docs/version-0.53/build/modules/staking/README.md +++ b/versioned_docs/version-0.53/build/modules/staking/README.md @@ -464,7 +464,7 @@ When a Validator is slashed, the following occurs: * The total `slashAmount` is calculated as the `slashFactor` (a chain parameter) \* `TokensFromConsensusPower`, the total number of tokens bonded to the validator at the time of the infraction. -* Every unbonding delegation and pseudo-unbonding redelegation such that the infraction occured before the unbonding or +* Every unbonding delegation and pseudo-unbonding redelegation such that the infraction occurred before the unbonding or redelegation began from the validator are slashed by the `slashFactor` percentage of the initialBalance. * Each amount slashed from redelegations and unbonding delegations is subtracted from the total slash amount. @@ -472,7 +472,7 @@ When a Validator is slashed, the following occurs: `NonBondedPool` depending on the validator's status. This reduces the total supply of tokens. In the case of a slash due to any infraction that requires evidence to submitted (for example double-sign), the slash -occurs at the block where the evidence is included, not at the block where the infraction occured. +occurs at the block where the evidence is included, not at the block where the infraction occurred. Put otherwise, validators are not slashed retroactively, only when they are caught. #### Slash Unbonding Delegation