chore: add markdownlint to lint commands (#9353)

* add markdownlint config

* update make lint commands

* update markdownlint config

* run make lint-fix

* fix empty link

* resuse docker container

* run lint-fix

* do not echo commands

Co-authored-by: ryanchrypto <12519942+ryanchrypto@users.noreply.github.com>
This commit is contained in:
Ryan Christoffersen 2021-05-27 08:31:04 -07:00 committed by GitHub
parent b56e1a164b
commit cb66c99eab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
147 changed files with 806 additions and 771 deletions

17
.markdownlint.json Normal file
View File

@ -0,0 +1,17 @@
{
"default": true,
"MD001": false,
"MD004": false,
"MD007": { "indent": 4 },
"MD013": false,
"MD024": { "siblings_only": true },
"MD025": false,
"MD026": { "punctuation": ".,;:" },
"MD029": false,
"MD033": false,
"MD034": false,
"MD036": false,
"MD040": false,
"MD041": false,
"no-hard-tabs": false
}

3
.markdownlintignore Normal file
View File

@ -0,0 +1,3 @@
CHANGELOG.md
docs/core/proto-docs.md
docs/node_modules

View File

@ -314,6 +314,7 @@ have had acted maliciously or grossly negligent, code-owner privileges may be
stripped with no prior warning or consent from the member in question.
Other potential removal criteria:
* Missing 3 scheduled meetings results in ICF evaluating whether the member should be
removed / replaced
* Violation of Code of Conduct
@ -322,14 +323,12 @@ Earning this privilege should be considered to be no small feat and is by no
means guaranteed by any quantifiable metric. It is a symbol of great trust of
the community of this project.
## Concept & Release Approval Process
The process for how Cosmos SDK maintainers take features and ADRs from concept to release
is broken up into three distinct stages: **Strategy Discovery**, **Concept Approval**, and
**Implementation & Release Approval**
### Strategy Discovery
* Develop long term priorities, strategy and roadmap for the SDK
@ -356,6 +355,7 @@ the current state of its discussion.
If an ADR is taking longer than 4 weeks to reach a final conclusion, the **Concept Approval Committee**
should convene to rectify the situation by either:
- unanimously setting a new time bound period for this ADR
- making changes to the Concept Approval Process (as outlined here)
- making changes to the members of the Concept Approval Committee

View File

@ -327,11 +327,18 @@ benchmark:
### Linting ###
###############################################################################
containerMarkdownLintImage=tmknom/markdownlint
containerMarkdownLint=cosmos-sdk-markdownlint
containerMarkdownLintFix=cosmos-sdk-markdownlint-fix
lint:
golangci-lint run --out-format=tab
@if docker ps -a --format '{{.Names}}' | grep -Eq "^${containerMarkdownLint}$$"; then docker start -a $(containerMarkdownLint); else docker run --name $(containerMarkdownLint) -i -v "$(CURDIR):/work" $(containerMarkdownLintImage); fi
lint-fix:
golangci-lint run --fix --out-format=tab --issues-exit-code=0
@if docker ps -a --format '{{.Names}}' | grep -Eq "^${containerMarkdownLintFix}$$"; then docker start -a $(containerMarkdownLintFix); else docker run --name $(containerMarkdownLintFix) -i -v "$(CURDIR):/work" $(containerMarkdownLintImage) . --fix; fi
.PHONY: lint lint-fix
format:

View File

@ -40,9 +40,6 @@ parent:
<img alt="Lint Satus" src="https://github.com/cosmos/cosmos-sdk/workflows/Lint/badge.svg" />
</div>
The Cosmos-SDK is a framework for building blockchain applications in Golang.
It is being used to build [`Gaia`](https://github.com/cosmos/gaia), the first implementation of the Cosmos Hub.

View File

@ -73,6 +73,7 @@ This process can take some time. Every effort is made to handle the bug in as ti
### Disclosure Communications
Communications to partners usually include the following details:
1. Affected version or versions
1. New release version
1. Impact on user funds
@ -81,6 +82,7 @@ Communications to partners usually include the following details:
1. Potential required actions if an adverse condition arises during the security release process
An example notice looks like:
```
Dear Cosmos SDK partners,

View File

@ -89,9 +89,11 @@ As rule of thumb, the following changes will **NOT** be automatically accepted i
1. Check that the bug is either fixed or not reproducible in `master`. It is, in general, not appropriate to release bug fixes for stable releases without first testing them in `master`. Please apply the label [0.42 «Stargate»](https://github.com/cosmos/cosmos-sdk/labels/0.42%20LTS%20%28Stargate%29) to the issue.
2. Add a comment to the issue and ensure it contains the following information (see the bug template below):
* **[Impact]** An explanation of the bug on users and justification for backporting the fix to the stable release.
* A **[Test Case]** section containing detailed instructions on how to reproduce the bug.
* A **[Regression Potential]** section with a clear assessment on how regressions are most likely to manifest as a result of the pull request that aims to fix the bug in the target stable release.
3. **Stable Release Managers** will review and discuss the PR. Once *consensus* surrounding the rationale has been reached and the technical review has successfully concluded, the pull request will be merged in the respective point-release target branch (e.g. `release/v0.42.x`) and the PR included in the point-release's respective milestone (e.g. `0.42.5`).
### Stable Release Exception - Bug template
@ -119,6 +121,7 @@ according to the [stable release policy](#stable-release-policy) and [release pr
Decisions are made by consensus.
Their responsibilites include:
* Driving the Stable Release Exception process.
* Approving/rejecting proposed changes to a stable release series.
* Executing the release process of stable point-releases in compliance with the [Point Release Procedure](CONTRIBUTING.md).

View File

@ -3,7 +3,7 @@
Installation:
```
$ git config core.hooksPath contrib/githooks
git config core.hooksPath contrib/githooks
```
## pre-commit
@ -14,8 +14,8 @@ that all the aforementioned commands are installed and available
in the user's search `$PATH` environment variable:
```
$ go get golang.org/x/tools/cmd/goimports
$ go get github.com/golangci/misspell/cmd/misspell@master
go get golang.org/x/tools/cmd/goimports
go get github.com/golangci/misspell/cmd/misspell@master
```
It also runs `go mod tidy` and `golangci-lint` if available.

View File

@ -5,6 +5,7 @@ This directory contains the files required to run the rosetta CI. It builds `sim
## docker-compose.yaml
Builds:
- cosmos-sdk simapp node, with prefixed data directory, keys etc. This is required to test historical balances.
- faucet is required so we can test construction API, it was literally impossible to put there a deterministic address to request funds for
- rosetta is the rosetta node used by rosetta-cli to interact with the cosmos-sdk app

View File

@ -66,6 +66,7 @@ directory layout:
## Usage
The system administrator admin is responsible for:
* installing the `cosmovisor` binary and configure the host's init system (e.g. `systemd`, `launchd`, etc) along with the environmental variables appropriately;
* installing the `genesis` folder manually;
* installing the `upgrades/<name>` folders manually.
@ -95,6 +96,7 @@ valid format to specify a download in such a message:
1. Store an os/architecture -> binary URI map in the upgrade plan info field
as JSON under the `"binaries"` key, eg:
```json
{
"binaries": {
@ -102,6 +104,7 @@ as JSON under the `"binaries"` key, eg:
}
}
```
2. Store a link to a file that contains all information in the above format (eg. if you want
to specify lots of binaries, changelog info, etc without filling up the blockchain).

View File

@ -8,6 +8,7 @@ Optimized C library for EC operations on curve secp256k1.
This library is a work in progress and is being used to research best practices. Use at your own risk.
Features:
* secp256k1 ECDSA signing/verification and key generation.
* Adding/multiplying private/public keys.
* Serialization/parsing of private keys, public keys, signatures.
@ -54,8 +55,8 @@ Build steps
libsecp256k1 is built using autotools:
$ ./autogen.sh
$ ./configure
$ make
$ ./tests
$ sudo make install # optional
./autogen.sh
./configure
make
./tests
sudo make install # optional

View File

@ -108,14 +108,17 @@ much as possible with its [counterpart in the Tendermint Core repo](https://gith
### Update and Build the RPC docs
1. Execute the following command at the root directory to install the swagger-ui generate tool.
```bash
make tools
```
2. Edit API docs
1. Directly Edit API docs manually: `client/lcd/swagger-ui/swagger.yaml`.
2. Edit API docs within the [Swagger Editor](https://editor.swagger.io/). Please refer to this [document](https://swagger.io/docs/specification/2-0/basic-structure/) for the correct structure in `.yaml`.
3. Download `swagger.yaml` and replace the old `swagger.yaml` under fold `client/lcd/swagger-ui`.
4. Compile gaiacli
```bash
make install
```

View File

@ -6,7 +6,6 @@
4. Add an entry to a list in the [README](./README.md) file.
5. Create a Pull Request to propose a new ADR.
## ADR life cycle
ADR creation is an **iterative** process. Instead of trying to solve all decisions in a single ADR pull request, we MUST firstly understand the problem and collect feedback through a GitHub Issue.
@ -23,7 +22,6 @@ ADR creation is an **iterative** process. Instead of trying to solve all decisio
6. Merged ADRs SHOULD NOT be pruned.
### ADR status
Status has two components:
@ -44,7 +42,6 @@ DRAFT -> PROPOSED -> LAST CALL yyyy-mm-dd -> ACCEPTED | REJECTED -> SUPERSEEDED
ABANDONED
```
+ `DRAFT`: [optional] an ADR which is work in progress, not being ready for a general review. This is to present an early work and get an 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 agreed yet.
+ `LAST CALL <date for the 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.
@ -53,7 +50,6 @@ DRAFT -> PROPOSED -> LAST CALL yyyy-mm-dd -> ACCEPTED | REJECTED -> SUPERSEEDED
+ `SUPERSEEDED 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 ADR
+ The context/background should be written in the present tense.

View File

@ -32,7 +32,6 @@ 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
Read about the [PROCESS](./PROCESS.md).

View File

@ -7,12 +7,10 @@
- 2020-01-14: Updates from review feedback
- 2020-01-30: Updates from implementation
### Glossary
* denom / denomination key -- unique token identifier.
## Context
With permissionless IBC, anyone will be able to send arbitrary denominations to any other account. Currently, all non-zero balances are stored along with the account in an `sdk.Coins` struct, which creates a potential denial-of-service concern, as too many denominations will become expensive to load & store each time the account is modified. See issues [5467](https://github.com/cosmos/cosmos-sdk/issues/5467) and [4982](https://github.com/cosmos/cosmos-sdk/issues/4982) for additional context.

View File

@ -17,15 +17,12 @@ All modern desktop computers OS (Ubuntu, Debian, MacOS, Windows) provide a built
We are seeking solution that provides a common abstraction layer to the many different backends and reasonable fallback for minimal platforms that dont provide a native secret store.
## Decision
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 users machine.
## Status
Accepted
@ -55,4 +52,3 @@ Running tests locally on a Mac require numerous repetitive password entries.
- #5097 Add keys migrate command [__MERGED__]
- #5180 Drop on-disk keybase in favor of keyring [_PENDING_REVIEW_]
- cosmos/gaia#164 Drop on-disk keybase in favor of keyring (gaia's changes) [_PENDING_REVIEW_]

View File

@ -21,7 +21,6 @@ code development etc. This type of community organization paves the way for
individual stakeholders to delegate votes by issue type, if in the future
governance proposals include a field for issue type.
## Decision
A specialization group can be broadly broken down into the following functions
@ -175,5 +174,4 @@ type SpecializationGroup interface {
## References
- (dCERT ADR)[./adr-008-dCERT-group.md]
- [dCERT ADR](./adr-008-dCERT-group.md)

View File

@ -34,6 +34,7 @@ vulnerability being patched on the live network.
The dCERT group is proposed to include an implementation of a `SpecializationGroup`
as defined in [ADR 007](./adr-007-specialization-groups.md). This will include the
implementation of:
- continuous voting
- slashing due to breach of soft contract
- revoking a member due to breach of soft contract
@ -42,6 +43,7 @@ implementation of:
governance
This system necessitates the following new parameters:
- blockly stipend allowance per dCERT member
- maximum number of dCERT members
- required staked slashable tokens for each dCERT member
@ -57,6 +59,7 @@ that governance may change them at any given point.
An `Electionator` object is to be implemented as continuous voting and with the
following specifications:
- All delegation addresses may submit votes at any point which updates their
preferred representation on the dCERT group.
- Preferred representation may be arbitrarily split between addresses (ex. 50%
@ -124,6 +127,7 @@ capable of shutting down the exploitable message routes.
### dCERT membership transactions
Active dCERT members
- change of the description of the dCERT group
- circuit break a message route
- vote to suspend a dCERT member.
@ -164,4 +168,4 @@ they should all be severely slashed.
## References
(Specialization Groups ADR)[./adr-007-specialization-groups.md]
[Specialization Groups ADR](./adr-007-specialization-groups.md)

View File

@ -17,10 +17,12 @@ For example, let's say a user wants to implement some custom signature verificat
One approach is to use the [ModuleManager](https://godoc.org/github.com/cosmos/cosmos-sdk/types/module) and have each module implement its own antehandler if it requires custom antehandler logic. The ModuleManager can then be passed in an AnteHandler order in the same way it has an order for BeginBlockers and EndBlockers. The ModuleManager returns a single AnteHandler function that will take in a tx and run each module's `AnteHandle` in the specified order. The module manager's AnteHandler is set as the baseapp's AnteHandler.
Pros:
1. Simple to implement
2. Utilizes the existing ModuleManager architecture
Cons:
1. Improves granularity but still cannot get more granular than a per-module basis. e.g. If auth's `AnteHandle` function is in charge of validating memo and signatures, users cannot swap the signature-checking functionality while keeping the rest of auth's `AnteHandle` functionality.
2. Module AnteHandler are run one after the other. There is no way for one AnteHandler to wrap or "decorate" another.
@ -53,10 +55,12 @@ func (example Decorator) Deliver(ctx Context, store KVStore, tx Tx, next Deliver
```
Pros:
1. Weave Decorators can wrap over the next decorator/handler in the chain. The ability to both pre-process and post-process may be useful in certain settings.
2. Provides a nested modular structure that isn't possible in the solution above, while also allowing for a linear one-after-the-other structure like the solution above.
Cons:
1. It is hard to understand at first glance the state updates that would occur after a Decorator runs given the `ctx`, `store`, and `tx`. A Decorator can have an arbitrary number of nested Decorators being called within its function body, each possibly doing some pre- and post-processing before calling the next decorator on the chain. Thus to understand what a Decorator is doing, one must also understand what every other decorator further along the chain is also doing. This can get quite complicated to understand. A linear, one-after-the-other approach while less powerful, may be much easier to reason about.
### Chained Micro-Functions
@ -71,11 +75,11 @@ Users can order the AnteHandlers easily by simply using the ModuleManager. The M
If however, users wish to change the order or add, modify, or delete ante micro-functions in anyway; they can always define their own ante micro-functions and add them explicitly to the list that gets passed into module manager.
#### Default Workflow:
#### Default Workflow
This is an example of a user's AnteHandler if they choose not to make any custom micro-functions.
##### SDK code:
##### SDK code
```go
// Chains together a list of AnteHandler micro-functions that get run one after the other.
@ -137,7 +141,7 @@ func (mm ModuleManager) GetAnteHandler() AnteHandler {
}
```
##### User Code:
##### User Code
```go
// Note: Since user is not making any custom modifications, we can just SetAnteHandlerOrder with the default AnteHandlers provided by each module in our preferred order
@ -166,11 +170,13 @@ moduleManager.SetAnteHandlerOrder([]AnteHandler(ValidateMemo, CustomSigVerify, D
```
Pros:
1. Allows for ante functionality to be as modular as possible.
2. For users that do not need custom ante-functionality, there is little difference between how antehandlers work and how BeginBlock and EndBlock work in ModuleManager.
3. Still easy to understand
Cons:
1. Cannot wrap antehandlers with decorators like you can with Weave.
### Simple Decorators

View File

@ -33,6 +33,7 @@ However in practice, we likely don't want a linear relation between amount of st
#### Parameterization
This requires parameterizing a logistic function. It is very well understood how to parameterize this. It has four parameters:
1) A minimum slashing factor
2) A maximum slashing factor
3) The inflection point of the S-curve (essentially where do you want to center the S)
@ -66,7 +67,6 @@ We then will iterate over all the SlashEvents in the queue, adding their `Valida
Once we have the `NewSlashPercent`, we then iterate over all the `SlashEvent`s in the queue once again, and if `NewSlashPercent > SlashedSoFar` for that SlashEvent, we call the `staking.Slash(slashEvent.Address, slashEvent.Power, Math.Min(Math.Max(minSlashPercent, NewSlashPercent - SlashedSoFar), maxSlashPercent)` (we pass in the power of the validator before any slashes occured, so that we slash the right amount of tokens). We then set `SlashEvent.SlashedSoFar` amount to `NewSlashPercent`.
## Status
Proposed

View File

@ -23,7 +23,6 @@ Also, it should be noted that this ADR includes only the simplest form of consen
- 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.
### Considerations
- consensus key mapping information management strategy
@ -50,7 +49,6 @@ Also, it should be noted that this ADR includes only the simplest form of consen
- `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)
### Workflow
1. The validator generates a new consensus keypair.
@ -99,6 +97,7 @@ Also, it should be noted that this ADR includes only the simplest form of consen
6. at `previousVotes` Iteration logic of `AllocateTokens`, `previousVote` using `OldConsPubKey` match up with `ConsPubKeyRotationHistory`, and replace validator for token allocation
7. Migrate `ValidatorSigningInfo` and `ValidatorMissedBlockBitArray` from `OldConsPubKey` to `NewConsPubKey`
- Note : All above features shall be implemented in `staking` module.
## Status

View File

@ -16,7 +16,7 @@ However, we would like to avoid the creation of an entire second voting process
Thus, we propose the following mechanism:
### Params:
### Params
- The current gov param `VotingPeriod` is to be replaced by a `MinVotingPeriod` param. This is the the default voting period that all governance proposal voting periods start with.
- There is a new gov param called `MaxVotingPeriodExtension`.

View File

@ -182,6 +182,7 @@ In addition to serving as a whitelist, `InterfaceRegistry` can also serve
to communicate the list of concrete types that satisfy an interface to clients.
In .proto files:
* fields which accept interfaces should be annotated with `cosmos_proto.accepts_interface`
using the same full-qualified name passed as `protoName` to `InterfaceRegistry.RegisterInterface`
* interface implementations should be annotated with `cosmos_proto.implements_interface`

View File

@ -52,7 +52,6 @@ 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.
A hypothetical example for the `gov` module would look something like:
```proto
@ -126,7 +125,6 @@ The signature for this method matches the existing
`RegisterServer` method on the GRPC `Server` type where `handler` is the custom
query server implementation described above.
GRPC-like requests are routed by the service name (ex. `cosmos_sdk.x.bank.v1.Query`)
and method name (ex. `QueryBalance`) combined with `/`s to form a full
method name (ex. `/cosmos_sdk.x.bank.v1.Query/QueryBalance`). This gets translated

View File

@ -13,6 +13,7 @@ the need to rewrite whole BaseApp. Also there's one special case for `sdk.ErrorO
might be handled in a "standard" way (middleware) alongside the others.
We propose middleware-solution, which could help developers implement the following cases:
* add external logging (let's say sending reports to external services like [Sentry](https://sentry.io));
* call panic for specific error cases;
@ -87,13 +88,14 @@ func newRecoveryMiddleware(handler RecoveryHandler, next recoveryMiddleware) rec
```
Function receives a `recoveryObj` object and returns:
* (next `recoveryMiddleware`, `nil`) if object wasn't handled (not a target type) by `RecoveryHandler`;
* (`nil`, not nil `error`) if input object was handled and other middlewares in the chain should not be executed;
* (`nil`, `nil`) in case of invalid behavior. Panic recovery might not have been properly handled;
this can be avoided by always using a `default` as a rightmost middleware in the chain (always returns an `error`');
`OutOfGas` middleware example:
```go
func newOutOfGasRecoveryMiddleware(gasWanted uint64, ctx sdk.Context, next recoveryMiddleware) recoveryMiddleware {
handler := func(recoveryObj interface{}) error {
@ -112,6 +114,7 @@ func newOutOfGasRecoveryMiddleware(gasWanted uint64, ctx sdk.Context, next recov
```
`Default` middleware example:
```go
func newDefaultRecoveryMiddleware() recoveryMiddleware {
handler := func(recoveryObj interface{}) error {

View File

@ -57,6 +57,7 @@ third-party modules.
As a starting point, we should adopt all of the [DEFAULT](https://buf.build/docs/lint-checkers#default)
checkers in [Buf's](https://buf.build) including [`PACKAGE_DIRECTORY_MATCH`](https://buf.build/docs/lint-checkers#file_layout),
except:
* [PACKAGE_VERSION_SUFFIX](https://buf.build/docs/lint-checkers#package_version_suffix)
* [SERVICE_SUFFIX](https://buf.build/docs/lint-checkers#service_suffix)
@ -118,6 +119,7 @@ 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
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
way to do this. In that case, there are really just two different, but similar modules with different APIs.
* we want to add a new revamped API for an existing module and it's just too cumbersome to add it to the existing package,
@ -127,6 +129,7 @@ so putting it in `v2` is cleaner for users. In this case, care should be made to
#### Guidelines on unstable (alpha and beta) package versions
The following guidelines are recommended for marking packages as alpha or beta:
* marking something as `alpha` or `beta` should be a last resort and just putting something in the
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
@ -140,6 +143,7 @@ Whenever code is released into the wild, especially on a blockchain, there is a
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:
* 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?
@ -151,6 +155,7 @@ and so if they actually went and changed the package to `grpc.reflection.v1`, so
they probably don't want to do that... So now the `v1alpha` package is more or less the de-facto `v1`. Let's not do that.
The following are guidelines for working with non-stable packages:
* [Buf's recommended version suffix](https://buf.build/docs/lint-checkers#package_version_suffix)
(ex. `v1alpha1`) _should_ be used for non-stable packages
* non-stable packages should generally be excluded from breaking change detection

View File

@ -71,7 +71,6 @@ malleability.
Among other sources of non-determinism, this ADR eliminates the possibility of
encoding malleability.
### Serialization rules
The serialization is based on the
@ -275,7 +274,6 @@ for all protobuf documents we need in the context of Cosmos SDK signing.
### Neutral
### Usage in SDK
For the reasons mentioned above ("Negative" section) we prefer to keep workarounds

View File

@ -18,14 +18,12 @@ This ADR defines an address format for all addressable SDK accounts. That includ
Issue [\#3685](https://github.com/cosmos/cosmos-sdk/issues/3685) identified that public key
address spaces are currently overlapping. We confirmed that it significantly decreases security of Cosmos SDK.
### 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:
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
@ -47,7 +45,6 @@ And explained how this approach should be sufficiently collision resistant:
This led to the first proposal (which we proved to be not good enough):
we concatenate a key type with a public key, hash it and take the first 20 bytes of that hash, summarized as `sha256(keyTypePrefix || keybytes)[:20]`.
### Review and Discussions
In [\#5694](https://github.com/cosmos/cosmos-sdk/issues/5694) we discussed various solutions.
@ -55,6 +52,7 @@ We agreed that 20 bytes it's not future proof, and extending the address length
This disqualifies the initial proposal.
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])`.
@ -65,13 +63,11 @@ In the issue we discussed various modifications:
+ Support currently used tools - we don't want to break an ecosystem, or add a long adaptation period. Ref: https://github.com/cosmos/cosmos-sdk/issues/8041
+ Try to keep the address length small - addresses are widely used in state, both as part of a key and object value.
### Scope
This ADR only defines a process for the generation of address bytes. For end-user interactions with addresses (through the API, or CLI, etc.), we still use bech32 to format these addresses as strings. This ADR doesn't change that.
Using Bech32 for string encoding gives us support for checksum error codes and handling of user typos.
## Decision
We define the following account types, for which we define the address function:
@ -81,7 +77,6 @@ We define the following account types, for which we define the address function:
3. composed accounts with a native address key (ie: bls, group module accounts)
4. module accounts: basically any accounts which cannot sign transactions and which are managed internally by modules
### Legacy Public Key Addresses Don't Change
Currently (Jan 2021), the only officially supported SDK user accounts are `secp256k1` basic accounts and legacy amino multisig.
@ -120,11 +115,12 @@ and it's more secure than [post-hash-prefix-proposal] (which uses the first 20 b
Moreover the cryptographer motivated the choice of adding `typ` in the hash to protect against a switch table attack.
We use the `address.Hash` function for generating addresses for all accounts represented by a single key:
* simple public keys: `address.Hash(keyType, pubkey)`
+ aggregated keys (eg: BLS): `address.Hash(keyType, aggregatedPubKey)`
+ modules: `address.Hash("module", moduleName)`
### Composed Addresses
For simple composed accounts (like new naive multisig), we generalize the `address.Hash`. The address is constructed by recursively creating addresses for the sub accounts, sorting the addresses and composing them into a single address. It ensures that the ordering of keys doesn't impact the resulting address.
@ -199,11 +195,13 @@ func Module(moduleName string, key []byte) []byte{
```
**Example** A lending BTC pool address would be:
```
btcPool := address.Module("lending", btc.Addrress()})
```
If we want to create an address for a module account depending on more than one key, we can concatenate them:
```
btcAtomAMM := address.Module("amm", btc.Addrress() + atom.Address()})
```
@ -221,11 +219,11 @@ func Derive(address []byte, derivationKey []byte) []byte {
Note: `Module` is a special case of the more general _derived_ address, where we set the `"module"` string for the _from address_.
**Example** For a cosmwasm smart-contract address we could use the following construction:
```
smartContractAddr := Derived(Module("cosmwasm", smartContractsNamespace), []{smartContractKey})
```
### Schema Types
A `typ` parameter used in `Hash` function SHOULD be unique for each account type.
@ -246,8 +244,6 @@ These names are derived directly from .proto files in a standardized way and use
in other places such as the type URL in `Any`s. We can easily obtain the name using
`proto.MessageName(msg)`.
## Consequences
### Backwards Compatibility
@ -272,19 +268,18 @@ This ADR is compatible with what was committed and directly supported in the SDK
- protobuf message names are used as key type prefixes
## 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.
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.
## Appendix: Consulting session
End of Dec 2020 we had a session with [Alan Szepieniec](https://scholar.google.be/citations?user=4LyZn8oAAAAJ&hl=en) to consult the approach presented above.
Alan general observations:
+ we dont 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
@ -292,11 +287,12 @@ Alan general observations:
+ sha2 mining can be use to breaking address pre-image
Hashing algorithm
+ any attack breaking blake3 will break blake2
+ Alan is pretty confident about the current security analysis of the blake hash algorithm. It was a finalist, and the author is well known in security analysis.
Algorithm:
+ Alan recommends to hash the prefix: `address(pub_key) = hash(hash(key_type) + pub_key)[:32]`, main benefits:
+ we are free to user arbitrary long prefix names
+ we still dont risk collisions
@ -305,24 +301,29 @@ Algorithm:
+ Aaron asked about post hash prefixes (`address(pub_key) = key_type + hash(pub_key)`) and differences. Alan noted that this approach has longer address space and its stronger.
Algorithm for complex / composed keys:
+ merging tree like addresses with same algorithm are fine
Module addresses: Should module addresses have 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)`
+ Aaron observation: we already need to deal with variable length (to not break secp256k1 keys).
Discssion about arithmetic hash function for ZKP
+ Posseidon / Rescue
+ Problem: much bigger risk because we dont know much techniques and history of crypto-analysis of arithmetic constructions. Its still a new ground and area of active research.
Post quantum signature size
+ Alan suggestion: Falcon: speed / size ration - 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 thats a lot of uncertainty. But there is magic happening with recurions / linking / simulation and that can speedup the progress.
Other ideas
+ Lets 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 its less secure but there are fixes.
### References
+ [Notes](https://hackmd.io/_NGWI4xZSbKzj1BkCqyZMw)

View File

@ -115,6 +115,7 @@ message MsgGrantAllowance {
```
In order to use allowances in transactions, we add a new field `granter` to the transaction `Fee` type:
```proto
package cosmos.tx.v1beta1;

View File

@ -19,6 +19,7 @@ on behalf of that account to other accounts.
## Context
The concrete use cases which motivated this module include:
- the desire to delegate the ability to vote on proposals to other accounts besides the account which one has
delegated stake
- "sub-keys" functionality, as originally proposed in [\#4480](https://github.com/cosmos/cosmos-sdk/issues/4480) which

View File

@ -182,6 +182,7 @@ This also allows us to change how we perform functional tests. Instead of mockin
Finally, closing a module to client API opens desirable OCAP patterns discussed in ADR-033. Since server implementation and interface is hidden, nobody can hold "keepers"/servers and will be forced to relay on the client interface, which will drive developers for correct encapsulation and software engineering patterns.
### Pros
- communicates return type clearly
- manual handler registration and return type marshaling is no longer needed, just implement the interface and register it
- communication interface is automatically generated, the developer can now focus only on the state transition methods - this would improve the UX of [\#7093](https://github.com/cosmos/cosmos-sdk/issues/7093) approach (1) if we chose to adopt that
@ -189,8 +190,8 @@ Finally, closing a module to client API opens desirable OCAP patterns discussed
- dramatically reduces and simplifies the code
### Cons
- using `service` definitions outside the context of gRPC could be confusing (but doesnt violate the proto3 spec)
- using `service` definitions outside the context of gRPC could be confusing (but doesnt violate the proto3 spec)
## References

View File

@ -165,7 +165,6 @@ Please see the below code sample for more detail on this flow looks for clients.
### Negative
## Detailed code example of publishing events
This ADR also proposes adding affordances to emit and consume these events. This way developers will only need to write
@ -315,5 +314,6 @@ func PublishChainTxEvents(ctx context.Context, client tmclient.EventsClient, bus
```
## References
- [Publish Custom Events via a bus](https://github.com/ovrclk/akash/blob/90d258caeb933b611d575355b8df281208a214f8/events/publish.go#L19-L58)
- [Consuming the events in `Client`](https://github.com/ovrclk/deploy/blob/bf6c633ab6c68f3026df59efd9982d6ca1bf0561/cmd/event-handlers.go#L57)

View File

@ -13,6 +13,7 @@ Proposed
This ADR introduces a system for permissioned inter-module communication leveraging the protobuf `Query` and `Msg`
service definitions defined in [ADR 021](./adr-021-protobuf-query-encoding.md) and
[ADR 031](./adr-031-msg-service.md) which provides:
- stable protobuf based module interfaces to potentially later replace the keeper paradigm
- stronger inter-module object capabilities (OCAPs) guarantees
- module accounts and sub-account authorization
@ -24,6 +25,7 @@ In the current Cosmos SDK documentation on the [Object-Capability Model](../core
> 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.
There is currently not a thriving ecosystem of Cosmos SDK modules. We hypothesize that this is in part due to:
1. lack of a stable v1.0 Cosmos SDK to build modules off of. Module interfaces are changing, sometimes dramatically, from
point release to point release, often for good reasons, but this does not create a stable foundation to build on.
2. lack of a properly implemented object capability or even object-oriented encapsulation system which makes refactors
@ -84,6 +86,7 @@ this ADR does not necessitate the creation of new protobuf definitions or servic
based service interfaces already used by clients for inter-module communication.
Using this `QueryClient`/`MsgClient` approach has the following key benefits over exposing keepers to external modules:
1. Protobuf types are checked for breaking changes using [buf](https://buf.build/docs/breaking-overview) and because of
the way protobuf is designed this will give us strong backwards compatibility guarantees while allowing for forward
evolution.
@ -95,6 +98,7 @@ enabling atomicy of operations ([currently a problem](https://github.com/cosmos/
transaction
This mechanism has the added benefits of:
- reducing boilerplate through code generation, and
- allowing for modules in other languages either via a VM like CosmWasm or sub-processes using gRPC
@ -116,6 +120,7 @@ For example, module `A` could use its `A.ModuleKey` to create `MsgSend` object f
will assure that the `from` account (`A.ModuleKey` in this case) is the signer.
Here's an example of a hypothetical module `foo` interacting with `x/bank`:
```go
package foo
@ -247,7 +252,6 @@ In [ADR 031](./adr-031-msg-service.md), the `AppModule.RegisterService(Configura
inter-module communication, we extend the `Configurator` interface to pass in the `ModuleKey` and to allow modules to
specify their dependencies on other modules using `RequireServer()`:
```go
type Configurator interface {
MsgServer() grpc.Server
@ -334,6 +338,7 @@ other modules. This will be addressed in separate ADRs or updates to this ADR.
### Future Work
Other future improvements may include:
* custom code generation that:
* simplifies interfaces (ex. generates code with `sdk.Context` instead of `context.Context`)
* optimizes inter-module calls - for instance caching resolved methods after first invocation

View File

@ -43,19 +43,15 @@ The MsgChangePubKey transaction needs to be signed by the existing pubkey in sta
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.
```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.
## Consequences
### Positive
@ -70,7 +66,6 @@ Breaks the current assumed relationship between address and pubkeys as H(pubkey)
* 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.

View File

@ -7,10 +7,10 @@
- Alessio Treglia (@alessio)
- Frojdy Dymylja (@fdymylja)
## Changelog
- 2021-05-12: the external library [cosmos-rosetta-gateway](https://github.com/tendermint/cosmos-rosetta-gateway) has been moved within the SDK.
## Context
[Rosetta API](https://www.rosetta-api.org/) is an open-source specification and set of tools developed by Coinbase to
@ -49,7 +49,6 @@ We will achieve these delivering on these principles by the following:
a. API shares the application process
b. API-specific process.
## Architecture
### The External Repo
@ -65,6 +64,7 @@ The constructor follows:
`func NewServer(settings Settings) (Server, error)`
`Settings`, which are used to construct a new server, are the following:
```go
// Settings define the rosetta server settings
type Settings struct {
@ -88,7 +88,6 @@ type Settings struct {
Package types uses a mixture of rosetta types and custom defined type wrappers, that the client must parse and return while executing operations.
##### Interfaces
Every SDK version uses a different format to connect (rpc, gRPC, etc), query and build transactions, we have abstracted this in what is the `Client` interface.
@ -180,6 +179,7 @@ type Msg interface {
```
Hence developers who want to extend the rosetta set of supported operations just need to extend their module's sdk.Msgs with the `ToOperations` and `FromOperations` methods.
### 3. API service invocation
As stated at the start, application developers will have two methods for invocation of the Rosetta API service:
@ -191,12 +191,10 @@ As stated at the start, application developers will have two methods for invocat
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).
#### Separate API service
Client application developers can write a new command to launch a Rosetta API server as a separate process too, using the rosetta command contained in the `/server/rosetta` package. Construction of the command depends on cosmos sdk version. Examples can be found inside `simd` for stargate, and `contrib/rosetta/simapp` for other release series.
## Status
Proposed

View File

@ -5,6 +5,7 @@
- 28/10/2020 - Initial draft
## Authors
- Antoine Herzog (@antoineherzog)
- Zaki Manian (@zmanian)
- Aleksandr Bezobchuk (alexanderbez) [1]
@ -19,6 +20,7 @@ Draft
Currently, in the 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.
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.
## 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.
@ -53,8 +55,8 @@ The first message added to the `offchain` package is `MsgSignData`.
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.
Proto definition:
```proto
// MsgSignData defines an arbitrary, general-purpose, off-chain message
message MsgSignData {
@ -64,7 +66,9 @@ message MsgSignData {
bytes Data = 2 [(gogoproto.jsontag) = "data"];
}
```
Signed MsgSignData json example:
```json
{
"type": "cosmos-sdk/StdTx",

View File

@ -36,6 +36,7 @@ type Vote struct {
```
And for backwards compatibility, we introduce `MsgVoteWeighted` while keeping `MsgVote`.
```
type MsgVote struct {
ProposalID int64
@ -51,6 +52,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
2. No Option is repeated
@ -69,11 +71,13 @@ tally() {
```
The CLI command for creating a multi-option vote would be as such:
```sh
simd tx gov vote 1 "yes=0.6,no=0.3,abstain=0.05,no_with_veto=0.05" --from mykey
```
To create a single-option vote a user can do either
```
simd tx gov vote 1 "yes=1" --from mykey
```
@ -86,19 +90,22 @@ simd tx gov vote 1 yes --from mykey
to maintain backwards compatibility.
## Consequences
### Backwards Compatibility
- Previous VoteMsg types will remain the same and so clients will not have to update their procedure unless they want to support the WeightedVoteMsg feature.
- When querying a Vote struct from state, its structure will be different, and so clients wanting to display all voters and their respective votes will have to handle the new format and the fact that a single voter can have split votes.
- The result of querying the tally function should have the same API for clients.
### Positive
- Can make the voting process more accurate for addresses representing multiple stakeholders, often some of the largest addresses.
### Negative
- Is more complex than simple voting, and so may be harder to explain to users. However, this is mostly mitigated because the feature is opt-in.
### Neutral
- Relatively minor change to governance tally function.

View File

@ -229,6 +229,7 @@ This service uses the same `StoreKVPairWriteListener` for every KVStore, writing
out to the same files, relying on the `StoreKey` field in the `StoreKVPair` protobuf message to later distinguish the source for each pair.
The file naming schema is as such:
* After every `BeginBlock` request a new file is created with the name `block-{N}-begin`, where N is the block number. All
subsequent state changes are written out to this file until the first `DeliverTx` request is received. At the head of these files,
the length-prefixed protobuf encoded `BeginBlock` request is written, and the response is written at the tail.
@ -398,7 +399,6 @@ func (app *BaseApp) RegisterHooks(s StreamingService) {
We will also modify the `BeginBlock`, `EndBlock`, and `DeliverTx` methods to pass ABCI requests and responses to any streaming service hooks registered
with the `BaseApp`.
```go
func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeginBlock) {
@ -544,7 +544,6 @@ func FileStreamingConstructor(opts servertypes.AppOptions, keys []sdk.StoreKey)
As a demonstration, we will implement the state watching features as part of SimApp.
For example, the below is a very rudimentary integration of the state listening features into the SimApp `AppCreator` function:
```go
func NewSimApp(
logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, skipUpgradeHeights map[int64]bool,

View File

@ -58,7 +58,6 @@ For threshold based cryptography in particular, we need a pipeline for epoch cha
This can be handled by making a parameter for the epoch pipeline length. This parameter should not be alterable except during hard forks, to mitigate implementation complexity of switching the pipeline length.
With pipeline length 1, if I redelegate during epoch N, then my redelegation is applied prior to the beginning of epoch N+1.
With pipeline length 2, if I redelegate during epoch N, then my redelegation is applied prior to the beginning of epoch N+2.
@ -79,6 +78,7 @@ __Step-1__: Implement buffering of all staking and slashing messages.
First we create a pool for storing tokens that are being bonded, but should be applied at the epoch boundary called the `EpochDelegationPool`. Then, we have two separate queues, one for staking, one for slashing. We describe what happens on each message being delivered below:
### 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.
- **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.
@ -86,15 +86,16 @@ First we create a pool for storing tokens that are being bonded, but should be a
- **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.
### Evidence Messages
- **MsgSubmitEvidence**: This gets executed immediately, and the validator gets jailed immediately. However in slashing, the actual slash event gets queued.
Then we add methods to the end blockers, to ensure that at the epoch boundary the queues are cleared and delegation updates are applied.
__Step-2__: Implement querying of queued staking txs.
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.

View File

@ -8,12 +8,10 @@
DRAFT Not Implemented
## Abstract
Sparse Merke Tree ([SMT](https://osf.io/8mcnh/)) is a version of a Merkle Tree with various storage and performance optimizations. This ADR defines a separation of state commitments from data storage and the SDK transition from IAVL to SMT.
## Context
Currently, Cosmos SDK uses IAVL for both state [commitments](https://cryptography.fandom.com/wiki/Commitment_scheme) and data storage.
@ -30,7 +28,6 @@ In the current design, IAVL is used for both data storage and as a Merkle Tree f
Moreover, the IAVL project lacks support and a maintainer and we already see better and well-established alternatives. Instead of optimizing the IAVL, we are looking into other solutions for both storage and state commitments.
## 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 [LazyLedgers' SMT](https://github.com/lazyledger/smt). LazyLedger 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.
@ -39,7 +36,6 @@ The storage model presented here doesn't deal with data structure nor serializat
### Decouple state commitment from storage
Separation of storage and commitment (by the SMT) will allow the optimization of different components according to their usage and access patterns.
`SS` (SMT) is used to commit to a data and compute merkle proofs. `SC` is used to directly access data. To avoid collisions, both `SS` and `SC` will use a separate storage namespace (they could use the same database underneath). `SC` will store each `(key, value)` pair directly (map key -> value).
@ -47,16 +43,17 @@ Separation of storage and commitment (by the SMT) will allow the optimization of
SMT is a merkle tree structure: we don't store keys directly. For every `(key, value)` pair, `hash(key)` is stored in a path (we hash a key to evenly distribute keys in the tree) and `hash(key, value)` in a leaf. Since we don't know a structure of a value (in particular if it contains the key) we hash both the key and the value in the `SC` leaf.
For data access we propose 2 additional KV buckets (namespaces for the key-value pairs, sometimes called [column family](https://github.com/facebook/rocksdb/wiki/Terminology)):
1. B1: `key → value`: the principal object storage, used by a state machine, behind the SDK `KVStore` interface: provides direct access by key and allows prefix iteration (KV DB backend must support it).
2. B2: `hash(key, value) → key`: a reverse index to get a key from an SMT path. Recall that SMT will store `(k, v)` as `(hash(k), hash(key, value))`. So, we can get an object value by composing `SMT_path → B2 → B1`.
3. we could use more buckets to optimize the app usage if needed.
Above, we propose to use a KV DB. However, for the state machine, we could use an RDBMS, which we discuss below.
### Requirements
State Storage requirements:
+ range queries
+ quick (key, value) access
+ creating a snapshot
@ -64,16 +61,15 @@ State Storage requirements:
+ pruning (garbage collection)
State Commitment requirements:
+ fast updates
+ tree path should be short
+ pruning (garbage collection)
### LazyLedger SMT for State Commitment
A Sparse Merkle tree is based on the idea of a complete Merkle tree of an intractable size. The assumption here is that as the size of the tree is intractable, there would only be a few leaf nodes with valid data blocks relative to the tree size, rendering a sparse tree.
### Snapshots for storage sync and state versioning
Below, with simple _snapshot_ we refer to a database snapshot mechanism, not to a _ABCI snapshot sync_. The latter will be referred as _snapshot sync_ (which will directly use DB snapshot as described below).
@ -93,7 +89,6 @@ Pruning old snapshots is effectively done by a database. Whenever we update a re
To manage the active snapshots we will either us a DB _max number of snapshots_ option (if available), or will remove snapshots in the `EndBlocker`. The latter option can be done efficiently by identifying snapshots with block height.
#### Accessing old state versions
One of the functional requirements is to access old state. This is done through `abci.Query` 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.Query` is configurable. Accessing an old state is done by using available snapshots.
@ -103,25 +98,20 @@ Moreover, SDK could provide a way to directly access the state. However, a state
We positively [validated](https://github.com/cosmos/cosmos-sdk/discussions/8297) a versioning and snapshot mechanism for querying old state with regards to the database we evaluated.
### State Proofs
For any object stored in State Store (SS), we have corresponding object in `SC`. A proof for object `V` identified by a key `K` is a branch of `SC`, where the path corresponds to the key `hash(K)`, and the leaf is `hash(K, V)`.
### Rollbacks
We need to be able to process transactions and roll-back state updates if a transaction fails. This can be done in the following way: during transaction processing, we keep all state change requests (writes) in a `CacheWrapper` abstraction (as it's done today). Once we finish the block processing, in the `Endblocker`, we commit a root store - at that time, all changes are written to the SMT and to the `SS` and a snapshot is created.
### Committing to an object without saving it
We identified use-cases, where modules will need to save an object commitment without storing an object itself. Sometimes clients are receiving complex objects, and they have no way to prove a correctness of that object without knowing the storage layout. For those use cases it would be easier to commit to the object without storing it directly.
## Consequences
### Backwards Compatibility
This ADR doesn't introduce any SDK level API changes.
@ -143,14 +133,12 @@ We change the storage layout of the state machine, a storage hard fork and netwo
+ Deprecating IAVL, which is one of the core proposals of Cosmos Whitepaper.
## Alternative designs.
## Alternative designs
Most of the alternative designs were evaluated in [state commitments and storage report](https://paper.dropbox.com/published/State-commitments-and-storage-review--BDvA1MLwRtOx55KRihJ5xxLbBw-KeEB7eOd11pNrZvVtqUgL3h).
Ethereum research published [Verkle Tire](https://notes.ethereum.org/_N1mutVERDKtqGIEYc-Flw#fnref1) - an idea of combining polynomial commitments with merkle tree in order to reduce the tree height. This concept has a very good potential, but we think it's too early to implement it. The current, SMT based design could be easily updated to the Verkle Tire once other research implement all necessary libraries. The main advantage of the design described in this ADR is the separation of state commitments from the data storage and designing a more powerful interface.
## Further Discussions
### Evaluated KV Databases
@ -165,7 +153,6 @@ Use of RDBMS instead of simple KV store for state. Use of RDBMS will require an
We were discussing use case where modules can use a support database, which is not automatically committed. Module will responsible for having a sound storage model and can optionally use the feature discussed in __Committing to an object without saving it_ section.
## References
+ [IAVL What's Next?](https://github.com/cosmos/cosmos-sdk/issues/7100)

View File

@ -84,6 +84,7 @@ We introduce a new prefix store in `x/upgrade`'s store. This store will track ea
```
0x2 | {bytes(module_name)} => BigEndian(module_consensus_version)
```
The initial state of the store is set from `app.go`'s `InitChainer` method.
The UpgradeHandler signature needs to be updated to take a `VersionMap`, as well as return an upgraded `VersionMap` and an error:

View File

@ -15,6 +15,7 @@ This ADR defines the `x/group` module which allows the creation and management o
## Context
The legacy amino multi-signature mechanism of the Cosmos SDK has certain limitations:
- Key rotation is not possible, although this can be solved with [account rekeying](adr-034-account-rekeying.md).
- Thresholds can't be changed.
- UX is cumbersome for non-technical users ([#5661](https://github.com/cosmos/cosmos-sdk/issues/5661)).
@ -185,6 +186,7 @@ A proposal consists of a set of `sdk.Msg`s that will be executed if the proposal
passes as well as any metadata associated with the proposal. These `sdk.Msg`s get validated as part of the `Msg/CreateProposal` request validation. They should also have their signer set as the group account.
Internally, a proposal also tracks:
- its current `Status`: submitted, closed or aborted
- its `Result`: unfinalized, accepted or rejected
- its `VoteState` in the form of a `Tally`, which is calculated on new votes and when executing the proposal.

View File

@ -11,35 +11,29 @@
> Please have a look at the [PROCESS](./PROCESS.md#adr-status) page.
> Use DRAFT if the ADR is in a draft stage (draft PR) or PROPOSED if it's in review.
## Abstract
> "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.
## Context
> This section describes the forces at play, including technological, political, social, and project local. These forces are probably in tension, and should be called out as such. The language in this section is value-neutral. It is simply describing facts. It should clearly explain the problem and motivation that the proposal aims to resolve.
> {context body}
## Decision
> This section describes our response to these forces. It is stated in full sentences, with active voice. "We will ..."
> {decision body}
## Consequences
> This section describes the resulting context, after applying the decision. All consequences should be listed here, not just the "positive" ones. A particular decision may have positive, negative, and neutral consequences, but all of them affect the team and project in the future.
### Backwards Compatibility
> All ADRs that introduce backwards incompatibilities must include a section describing these incompatibilities and their severity. The ADR must explain how the author proposes to deal with these incompatibilities. ADR submissions without a sufficient backwards compatibility treatise may be rejected outright.
### Positive
{positive consequences}
@ -52,18 +46,15 @@
{neutral consequences}
## Further Discussions
While an ADR is in the DRAFT or PROPOSED stage, this section should contain a summary of issues to be solved in future iterations (usually referencing comments from a pull-request discussion).
Later, this section can optionally list ideas or improvements the author or reviewers found during the analysis of this ADR.
## Test Cases [optional]
Test cases for an implementation are mandatory for ADRs that are affecting consensus changes. Other ADRs can choose to include links to test cases if applicable.
## References
- {reference link}

View File

@ -58,7 +58,6 @@ For HD key derivation the Cosmos SDK uses a standard called [BIP32](https://gith
In the Cosmos SDK, keys are stored and managed by using an object called a [`Keyring`](#keyring).
## Keys, accounts, addresses, and signatures
The principal way of authenticating a user is done using [digital signatures](https://en.wikipedia.org/wiki/Digital_signature). Users sign transactions using their own private key. Signature verification is done with the associated public key. For on-chain signature verification purposes, we store the public key in an `Account` object (alongside other data required for a proper transaction validation).
@ -71,7 +70,6 @@ The Cosmos SDK supports the following digital key schemes for creating digital s
- `secp256r1`, as implemented in the [SDK's `crypto/keys/secp256r1` package](https://github.com/cosmos/cosmos-sdk/blob/master/crypto/keys/secp256r1/pubkey.go),
- `tm-ed25519`, as implemented in the [SDK `crypto/keys/ed25519` package](https://github.com/cosmos/cosmos-sdk/blob/v0.42.1/crypto/keys/ed25519/ed25519.go). This scheme is supported only for the consensus validation.
| | Address length | Public key length | Used for transaction | Used for consensus |
| | in bytes | in bytes | authentication | (tendermint) |
|--------------+----------------+-------------------+----------------------+--------------------|
@ -79,8 +77,6 @@ The Cosmos SDK supports the following digital key schemes for creating digital s
| `secp256r1` | 32 | 33 | yes | no |
| `tm-ed25519` | -- not used -- | 32 | no | yes |
## Addresses
`Addresses` and `PubKey`s are both public information that identifies actors in the application. `Account` is used to store authentication information. The basic account implementation is provided by a `BaseAccount` object.
@ -108,14 +104,12 @@ For user interaction, addresses are formatted using [Bech32](https://en.bitcoin.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.42.1/types/address.go#L230-L244
| | Address Bech32 Prefix |
| ------------------ | --------------------- |
| Accounts | cosmos |
| Validator Operator | cosmosvaloper |
| Consensus Nodes | cosmosvalcons |
### Public Keys
Public keys in Cosmos SDK are defined by `cryptotypes.PubKey` interface. Since public keys are saved in a store, `cryptotypes.PubKey` extends the `proto.Message` interface:
@ -123,6 +117,7 @@ Public keys in Cosmos SDK are defined by `cryptotypes.PubKey` interface. Since p
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.42.1/crypto/types/types.go#L8-L17
A compressed format is used for `secp256k1` and `secp256r1` serialization.
- The first byte is a `0x02` byte if the `y`-coordinate is the lexicographically largest of the two associated with the `x`-coordinate.
- Otherwise the first byte is a `0x03`.
@ -133,7 +128,6 @@ For user interactions, `PubKey` is formatted using Protobufs JSON ([ProtoMarshal
+++ https://github.com/cosmos/cosmos-sdk/blob/7568b66/crypto/keyring/output.go#L23-L39
## Keyring
A `Keyring` is an object that stores and manages accounts. In the Cosmos SDK, a `Keyring` implementation follows the `Keyring` interface:
@ -154,7 +148,6 @@ A few notes on the `Keyring` methods:
- `ExportPrivKeyArmor(uid, encryptPassphrase string) (armor string, err error)` exports a private key in ASCII-armored encrypted format using the given passphrase. You can then either import the private key again into the keyring using the `ImportPrivKey(uid, armor, passphrase string)` function or decrypt it into a raw private key using the `UnarmorDecryptPrivKey(armorStr string, passphrase string)` function.
## Next {hide}
Learn about [gas and fees](./gas-fees.md) {hide}

View File

@ -255,7 +255,7 @@ This section is optional, as developers are free to choose their dependency mana
+++ https://github.com/cosmos/sdk-tutorials/blob/c6754a1e313eb1ed973c5c91dcc606f2fd288811/go.mod#L1-L18
For building the application, a [Makefile](https://en.wikipedia.org/wiki/Makefile) is generally used. The Makefile primarily ensures that the `go.mod` is run before building the two entrypoints to the application, [`appd`](#node-client) and [`appd`](#application-interface). See an example of Makefile from the [nameservice tutorial]()
For building the application, a [Makefile](https://en.wikipedia.org/wiki/Makefile) is generally used. The Makefile primarily ensures that the `go.mod` is run before building the two entrypoints to the application, [`appd`](#node-client) and [`appd`](#application-interface). See an example of Makefile from the [nameservice tutorial](https://tutorials.cosmos.network/nameservice/tutorial/00-intro.html)
+++ https://github.com/cosmos/sdk-tutorials/blob/86a27321cf89cc637581762e953d0c07f8c78ece/nameservice/Makefile

View File

@ -51,7 +51,6 @@ func AllInvariants(k Keeper) sdk.Invariant {
Finally, module developers need to implement the `RegisterInvariants` method as part of the [`AppModule` interface](./module-manager.md#appmodule). Indeed, the `RegisterInvariants` method of the module, implemented in the `module/module.go` file, typically only defers the call to a `RegisterInvariants` method implemented in the `keeper/invariants.go` file. The `RegisterInvariants` method registers a route for each `Invariant` function in the [`InvariantRegistry`](#invariant-registry):
```go
// RegisterInvariants registers all staking invariants
func RegisterInvariants(ir sdk.InvariantRegistry, k Keeper) {

View File

@ -25,14 +25,15 @@ See an example of a `Msg` service definition from `x/bank` module:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc1/proto/cosmos/bank/v1beta1/tx.proto#L10-L17
Each `Msg` service method must have exactly one argument, which must implement the `sdk.Msg` interface, and a Protobuf response. The naming convention is to call the RPC argument `Msg<service-rpc-name>` and the RPC response `Msg<service-rpc-name>Response`. For example:
```
rpc Send(MsgSend) returns (MsgSendResponse);
```
`sdk.Msg` interface is a simplified version of the Amino `LegacyMsg` interface described [below](#legacy-amino-msgs) with only `ValidateBasic()` and `GetSigners()` methods. For backwards compatibility with [Amino `LegacyMsg`s](#legacy-amino-msgs), existing `LegacyMsg` types should be used as the request parameter for `service` RPC definitions. Newer `sdk.Msg` types, which only support `service` definitions, should use canonical `Msg...` name.
Cosmos SDK uses Protobuf definitions to generate client and server code:
* `MsgServer` interface defines the server API for the `Msg` service and its implementation is described as part of the [`Msg` services](./msg-services.md) documentation.
* Structures are generated for all RPC request and response types.

View File

@ -76,7 +76,6 @@ Let us go through the methods of `AppModule`:
- `BeginBlock(sdk.Context, abci.RequestBeginBlock)`: This method gives module developers the option to implement logic that is automatically triggered at the beginning of each block. Implement empty if no logic needs to be triggered at the beginning of each block for this module.
- `EndBlock(sdk.Context, abci.RequestEndBlock)`: This method gives module developers the option to implement logic that is automatically triggered at the end of each block. This is also where the module can inform the underlying consensus engine of validator set changes (e.g. the `staking` module). Implement empty if no logic needs to be triggered at the end of each block for this module.
### Implementing the Application Module Interfaces
Typically, the various application module interfaces are implemented in a file called `module.go`, located in the module's folder (e.g. `./x/module/module.go`).

View File

@ -1,6 +1,7 @@
<!--
order: 4
-->
# `Msg` Services
A Protobuf `Msg` service processes [messages](./messages-and-queries.md#messages). Protobuf `Msg` services are specific to the module in which they are defined, and only process messages defined within the said module. They are called from `BaseApp` during [`DeliverTx`](../core/baseapp.md#delivertx). {synopsis}
@ -92,7 +93,6 @@ Then, a simple switch calls the appropriate `handler` based on the `LegacyMsg` t
In this regard, `handler`s functions need to be implemented for each module `LegacyMsg`. This will also involve manual handler registration of `LegacyMsg` types.
`handler`s functions should return a `*Result` and an `error`.
## Telemetry
New [telemetry metrics](../core/telemetry.md) can be created from `msgServer` methods when handling messages.

View File

@ -10,7 +10,6 @@ parent:
This documentation is not complete and it's outdated. Please use the English version.
:::
## 开始
- **[SDK 介绍](./intro/README.md)**Cosmos SDK 的总体概览

View File

@ -5,7 +5,6 @@
This documentation is not complete and it's outdated. Please use the English version.
:::
此目录包含对 cosmos sdk 的基础概念介绍
1. [SDK 应用解析](./app-anatomy.md)

View File

@ -111,10 +111,13 @@ Flags are added to commands directly (generally in the [module's CLI file](../bu
## Environment variables
Each flag is bound to it's respecteve 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 `--home` for application with basename `GAIA` is bound to `GAIA_HOME`. It allows to reduce amount of flags typed for routine operations. For example instead of:
```sh
gaia --home=./ --node=<node address> --chain-id="testchain-1" --keyring-backend=test tx ... --from=<key name>
```
this will be more convinient:
```sh
# define env variables in .env, .envrc etc
GAIA_HOME=<path to home>

View File

@ -16,14 +16,12 @@ The Cosmos SDK uses two methods to perform upgrades.
- Version v0.43 and later can perform upgrades in place to significantly decrease the upgrade time for chains with a larger state. Use the [Migration Upgrade Guide](../building-modules/upgrade.md) guide to set up your application modules to take advantage of in-place upgrades.
This document provides steps to use the In-Place Store Migrations upgrade method.
## Tracking Module Versions
Each module gets assigned a consensus version by the module developer. The consensus version serves as the breaking change version of the module. The SDK keeps track of all module consensus versions in the x/upgrade `VersionMap` store. During an upgrade, the difference between the old `VersionMap` stored in state and the new `VersionMap` is calculated by the Cosmos SDK. For each identified difference, the module-specific migrations are run and the respective consensus version of each upgraded module is incremented.
## Genesis State
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`:
@ -39,9 +37,11 @@ func (app *MyApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.R
This information is used by the Cosmos SDK to detect when modules with newer versions are introduced to the app.
### Consensus Version
The consensus version is defined on each app module by the module developer and serves as the breaking change version of the module. The consensus version informs the SDK on which modules need to be upgraded. For example, if the bank module was version 2 and an upgrade introduces bank module 3, the SDK upgrades the bank module and runs the "version 2 to 3" migration script.
### Version Map
The version map is a mapping of module names to consensus versions. The map is persisted to x/upgrade's state for use during in-place migrations. When migrations finish, the updated version map is persisted to state.
## Upgrade Handlers

View File

@ -38,7 +38,6 @@ The Cosmos SDK gives developers maximum flexibility to define the state of their
Thanks to the Cosmos SDK, developers just have to define the state machine, and [*Tendermint*](https://tendermint.com/docs/introduction/what-is-tendermint.html) will handle replication over the network for them.
```
^ +-------------------------------+ ^
| | | | Built with Cosmos SDK
@ -55,7 +54,6 @@ Blockchain node | | Consensus | |
v +-------------------------------+ v
```
[Tendermint](https://docs.tendermint.com/v0.34/introduction/what-is-tendermint.html) is an application-agnostic engine that is responsible for handling the *networking* and *consensus* layers of a blockchain. In practice, this means that Tendermint is responsible for propagating and ordering transaction bytes. Tendermint Core relies on an eponymous Byzantine-Fault-Tolerant (BFT) algorithm to reach consensus on the order of transactions.
The Tendermint [consensus algorithm](https://docs.tendermint.com/v0.34/introduction/what-is-tendermint.html#consensus-overview) works with a set of special nodes called *Validators*. Validators are responsible for adding blocks of transactions to the blockchain. At any given block, there is a validator set V. A validator in V is chosen by the algorithm to be the proposer of the next block. This block is considered valid if more than two thirds of V signed a *[prevote](https://docs.tendermint.com/v0.34/spec/consensus/consensus.html#prevote-step-height-h-round-r)* and a *[precommit](https://docs.tendermint.com/v0.34/spec/consensus/consensus.html#precommit-step-height-h-round-r)* on it, and if all the transactions that it contains are valid. The validator set can be changed by rules written in the state-machine.
@ -94,7 +92,6 @@ Find a more detailed view of the ABCI methods from the [Tendermint docs](https:/
Any application built on Tendermint needs to implement the ABCI interface in order to communicate with the underlying local Tendermint engine. Fortunately, you do not have to implement the ABCI interface. The Cosmos SDK provides a boilerplate implementation of it in the form of [baseapp](./sdk-design.md#baseapp).
## Next {hide}
Read about the [high-level design principles of the SDK](./sdk-design.md) {hide}

View File

@ -2,7 +2,6 @@
REST 서버를 가동하기 위해서는 다음과 같은 파라미터 값을 정의해야 합니다:
| 파라미터 | 형태 | 기본 값 | 필수/선택 | 설명 |
| ----------- | --------- | ----------------------- | -------- | ---------------------------------------------------- |
| chain-id | string | null | 필수 | 연결할 체인의 chain-id |

View File

@ -54,7 +54,6 @@ type KeyExistsProof struct {
존재 증거의 데이터 형식은 위와 같이 나열되어 있습니다. 존재 증거를 생성하고 검증하는 방식은 다음과 같습니다:
![Exist Proof](./pics/existProof.png)
증거 생성 절차:
@ -129,7 +128,6 @@ type KeyAbsentProof struct {
IAVL 증거를 검증했다면 substore 증거와 AppHash를 비교하여 검증할 수 있습니다. 우선 MultiStoreCommitInfo를 반복(iterate)하여 proof StoreName을 이용해 서브스토어의 commitID를 찾을 수 있습니다. 여기에서 commitID의 해시가 RootHash의 proof와 동일하다는 것을 검증합니다. 만약 동일하지 않을 경우, 증거는 유효하지 않습니다. 이후 서브스토어 commitInfo 어레이를 서브스토어 이름의 해시 값으로 정렬합니다. 마지막으로, 모든 서브스토어 commitInfo 어레이를 기반으로 단순 머클 트리(simple Merkle tree)를 빌드하여 머클 루트 해시가 앱 해시와 동일한지 검증합니다.
![substore proof](./pics/substoreProof.png)
```go

View File

@ -36,7 +36,6 @@ gaiacli keys add <your_key_name>
이후 해당 키페어에 대한 비밀번호(최소 8글지)를 생성할 것을 요청받습니다. 커맨드는 다음 4개 정보를 리턴합니다:
- `NAME`: 키 이름
- `ADDRESS`: 주소 (토큰 전송을 받을때 이용)
- `PUBKEY`: 퍼블릭 키 (검증인들이 사용합니다)
@ -67,6 +66,7 @@ gaiacli send --amount=10faucetToken --chain-id=<name_of_testnet_chain> --from=<k
```
플래그:
- `--amount`: `<value|coinName>` 포맷의 코인 이름/코인 수량입니다.
- `--chain-id`: 이 플래그는 특정 체인의 ID를 설정할 수 있게 합니다. 앞으로 테스트넷 체인과 메인넷 체인은 각자 다른 아이디를 보유하게 됩니다.
- `--from`: 전송하는 계정의 키 이름.
@ -93,10 +93,10 @@ gaiacli advanced rest-server --node=<full_node_address:full_node_port>
```
플래그:
- `--node`: 플노드의 주소와 포트를 입력하시면 됩니다. 만약 풀노드와 REST 서버가 동일한 머신에서 운영될 경우 주소 값은 `tcp://localhost:26657`로 설정하시면 됩니다.
- `--laddr`: REST 서버의 주소와 포트를 정하는 플래그입니다(기본 값 `1317`). 대다수의 경우에는 포트를 정하기 위해서 사용됩니다, 이 경우 주소는 "localhost"로 입력하시면 됩니다. 포맷은 <rest_server_address:port>입니다.
### 트랜잭션 수신 모니터링
추천하는 수신 트랜잭션을 모니터링하는 방식은 LCD의 다음 엔드포인트를 정기적으로 쿼리하는 것입니다:

View File

@ -39,15 +39,19 @@
`CheckTx``DeliverTx` 외에도 베이스앱은 다음과 같은 ABCI 메시지를 처리합니다.
### Info
TODO complete description (추후 업데이트 예정)
### SetOption
TODO complete description (추후 업데이트 예정)
### Query
TODO complete description (추후 업데이트 예정)
### InitChain
TODO complete description (추후 업데이트 예정)
체인 시동(chain initialization) 단계에서 `InitChain``CommitMultiStore`에 직접적으로 할당되어 있는 시동 로직을 실행합니다. check state와 deliver state는 정의된 ChainID로 시작됩니다.
@ -55,14 +59,16 @@ TODO complete description (추후 업데이트 예정)
참고할 것은 InitChain 이후에 커밋을 실행하지 않습니다. 그렇기 때문에 블록 1의 BeginBlock은 InitChain이 시작한대로 deliver state에서 시작됩니다.
### BeginBlock
TODO complete description (추후 업데이트 예정)
### EndBlock
TODO complete description (추후 업데이트 예정)
### Commit
TODO complete description (추후 업데이트 예정)
TODO complete description (추후 업데이트 예정)
## 가스 관리(Gas Management)
@ -72,7 +78,6 @@ InitChain 실행 단계에서 블록 가스 미터는 제네시스 트랜잭션
또한, InitChain의 리퀘스트 메시지에는 genesis.json 파일이 정의하는 ConsensusParams가 포함되어있습니다.
### 가스: BeginBlock
블록 가스 미터는 BeginBlock의 deliver state에서 리셋됩니다. 만약 베이스앱에서 최대 블록 가스가 설정되어있지 않은 경우, 가스 미터는 무한으로 설정됩니다. 최대 블록 가스가 설정되었을 경우, 가스 미터는 `ConsensusParam.BlockSize.MaxGas`를 통해 설정됩니다.
@ -82,4 +87,3 @@ InitChain 실행 단계에서 블록 가스 미터는 제네시스 트랜잭션
특정 트랜잭션이 실행되기 전, `BlockGasMeter`를 우선 확인하여 남은 가스가 있는지 확인합니다. 만약 남은 가스가 없다면 `DeliverTx`는 즉시 에러를 리턴합니다.
트랜잭션이 처리된 후, 사용된 가스는 (설정된 가스 리밋에 따라) `BlockGasMeter`에서 차감됩니다. 만약 잔류 가스가 가스 미터의 한도를 초과할 경우, `DeliverTx`는 에러를 리턴하고 해당 트랜잭션은 커밋되지 않습니다.

View File

@ -15,6 +15,7 @@
> 그렇기 때문에, 악의적인 코드가 포함되있을 확률이 있는 새로운 오브젝트가 소개되더라도 보안적 속성은 지켜질 수 있습니다.
>
> 이런 구조적 속성은 해당 오브젝트를 통치하는 두가지 법칙에 의해 지켜질 수 있습니다:
>
> 1. 오브젝트 'A'는 'B'에 대한 레퍼런스를 보유하고 있을 경우에만 메시지를 전송할 수 있다.
> 2. 오브젝트 'A'가 'C'에 대한 레퍼런스를 가지고 싶다면 오브젝트 'A'는 'C'에 대한 레퍼런스가 포함된 메시지를 수신해야 한다.
>
@ -64,5 +65,3 @@ app.Router().
AddRoute(slashing.RouterKey, slashing.NewHandler(app.slashingKeeper)).
AddRoute(gov.RouterKey, gov.NewHandler(app.govKeeper))
```

View File

@ -2,7 +2,6 @@
order: 3
-->
# SDK 애플리케이션 아키텍쳐
## 상태 기계 (state machine)
@ -40,7 +39,6 @@ order: 3
개발자는 코스모스 SDK를 사용하여 상태 기계만을 정의하면 되며, 해당 상태를 네트워크에 복제하는 기능은 [*텐더민트*](https://tendermint.com/docs/introduction/introduction.html)가 제공합니다.
```
^ +-------------------------------+ ^
| | | | 코스모스 SDK로 개발

View File

@ -6,7 +6,6 @@ Documentation has been translated for **reference use only** and may contain typ
Please refer to the official english version of the documentation for the latest and accurate information.
## 코스모스 SDK 도큐멘테이션 번역 (한국어)
이 문서는 코스모스 공식 문서의 번역 작업 트래킹을 위한 문서입니다.
@ -15,25 +14,28 @@ Please refer to the official english version of the documentation for the latest
코스모스 관련 가장 정확한 정보를 확인하시기 위해서는 영어 원문을 참고하시기 바랍니다.
## Progress by directory
### [`concepts`](../concepts/)
- Synced until commit [14ebc65](https://github.com/cosmos/cosmos-sdk/commit/14ebc65daffd63e1adf17995c103aac9380207ef#diff-f874f370376bf359320af0543de53fcf)
### [`spec`](../spec/)
- Redacted from until completion
### [`gaia`](../gaia/)
- Synced until commit [288df6f](https://github.com/cosmos/cosmos-sdk/commit/288df6fe69dcef8fa95aca022039f92ba1e98c11#diff-3302fe357e01f0996ddb0f10adec85f0)
### [`intro`](../intro/)
- Synced until commit [0043912](https://github.com/cosmos/cosmos-sdk/commit/0043912548808b4cfd6ab84ec49ba73bd5f65b5b#diff-e518eaec0d99787e6f75682d54751821)
### [`modules`](../modules/)
- Synced until commit [78a2135](https://github.com/cosmos/cosmos-sdk/commit/78a21353da978d6c2a9b711f29b3874ff9ca14ae#diff-449cc65858e8929d15f4a170950e7758)
### [`clients`](../clients/)
- Synced until Commit [857a65d](https://github.com/cosmos/cosmos-sdk/commit/857a65dc610cd736a47980b5d4778e5123206a3d#diff-93dd988c16d20a1bce170b86ad89425a)
- Synced until Commit [857a65d](https://github.com/cosmos/cosmos-sdk/commit/857a65dc610cd736a47980b5d4778e5123206a3d#diff-93dd988c16d20a1bce170b86ad89425a)

View File

@ -12,7 +12,6 @@
관련 스펙은 [여기](https://github.com/cosmos/cosmos-sdk/tree/master/docs/spec/staking)에서 확인하실 수 있습니다.
# Slashing
`x/slashing` 모듈은 코스모스 위임형 지분증명(Delegated-Proof-of-Stake) 시스템에서 사용됩니다.

View File

@ -1,6 +1,7 @@
<!--
order: 4
-->
# Keyring Migrate Quick Start
`keyring` is the Cosmos SDK mechanism to manage the public/private keypair. Cosmos SDK v0.42 (Stargate) introduced breaking changes in the keyring.
@ -21,6 +22,7 @@ The migration process moves key information from the legacy db-based Keybase to
You can migrate or skip the migration for each key entry found in the specified `old_home_dir` directory. Each key migration requires a valid passphrase. If an invalid passphrase is entered, the command exits. Run the command again to restart the keyring migration.
The `migrate` command takes the following flags:
- `--dry-run` boolean
- true - run the migration but do not persist changes to the new Keybase.

View File

@ -21,6 +21,7 @@ order: 3
```
На практике транзакции сгруппированы в блоки, что позволяет сделать процесс более эффективным. Принимая в качестве входа состояние `S` и блок транзакций `B`, автомат вернет новое состояние `S'`.
```
+--------+ +--------+
| | | |

View File

@ -38,7 +38,6 @@ Cosmos SDK - это фреймворк, который облегчает раз
Вот упрощенное представление о том, как транзакция обрабатывается приложением каждого полной ноды, когда она получена в валидном блоке:
```
+
|
@ -96,5 +95,4 @@ Cosmos SDK - это фреймворк, который облегчает раз
В дополнение к уже существующим модулям в `x/`, которые каждый может использовать в своем приложении, SDK позволяет [создавать собственные модули](https://cosmos.network/docs/tutorial/keeper.html).
### Далее, узнайте больше о модели безопасности Cosmos SDK, [ocap](./ocap.md)

View File

@ -67,6 +67,7 @@ directory layout:
## Usage
The system administrator admin is responsible for:
* installing the `cosmovisor` binary and configure the host's init system (e.g. `systemd`, `launchd`, etc) along with the environmental variables appropriately;
* installing the `genesis` folder manually;
* installing the `upgrades/<name>` folders manually.
@ -96,6 +97,7 @@ valid format to specify a download in such a message:
1. Store an os/architecture -> binary URI map in the upgrade plan info field
as JSON under the `"binaries"` key, eg:
```json
{
"binaries": {
@ -103,6 +105,7 @@ as JSON under the `"binaries"` key, eg:
}
}
```
2. Store a link to a file that contains all information in the above format (eg. if you want
to specify lots of binaries, changelog info, etc without filling up the blockchain).

View File

@ -78,7 +78,7 @@ passphrase expiration.
The password store must be set up prior to first use:
```sh
$ pass init <GPG_KEY_ID>
pass init <GPG_KEY_ID>
```
Replace `<GPG_KEY_ID>` with your GPG key ID. You can use your personal GPG key or an alternative

View File

@ -16,6 +16,7 @@ Examples on how to do so can be found in the staking types such as `MsgDelegate`
In case more customization is required, it's possible to embed the Client type and override the methods which require customizations.
Example:
```go
package custom_client
import (

View File

@ -154,7 +154,6 @@ know exactly what they are signing (opposed to signing a bunch of arbitrary byte
Thus, in the future, the Cosmos signing message specification will be expected
to expand upon it's canonical JSON structure to include such functionality.
## API
Application developers and designers should formalize a standard set of APIs that

View File

@ -14,4 +14,3 @@ The circuit breaker is intended to be enabled through either:
The basic pause state of any module simply disables all message routes to
that module. Beyond that, it may be a appropriate for different modules to
process begin-block/end-block in an altered "safe" way.

View File

@ -2,4 +2,3 @@ TODO
The reserve pool is the pool of collected funds for use by governance taken via the `CommunityTax`.
Currently with the SDK, tokens collected by the CommunityTax are accounted for but unspendable.

View File

@ -8,6 +8,7 @@ and `ExportCmd` which creates commands to start the application and export state
## Preliminary
The root command of an application typically is constructed with:
+ command to start an application binary
+ three meta commands: `query`, `tx`, and a few auxiliary commands such as `genesis`.
utilities.

View File

@ -72,7 +72,6 @@ type Store struct {
When each `KVStore` methods are called, `gaskv.Store` automatically consumes appropriate amount of gas depending on the `Store.gasConfig`.
## Prefix
`prefix.Store` is a wrapper `KVStore` which provides automatic key-prefixing functionalities over the underlying `KVStore`.

View File

@ -166,19 +166,19 @@ the module itself are defined below:
1. Query an account.
```shell
$ app q auth account [address] [...flags]
app q auth account [address] [...flags]
```
2. Sign an unsigned transaction using a single signature.
```shell
$ app tx auth sign [file]
app tx auth sign [file]
```
3. Sign an unsigned transaction using a multisig.
```shell
$ app tx auth multisign [file] [name] [[signature]...]
app tx auth multisign [file] [name] [[signature]...]
```
### REST

View File

@ -89,16 +89,21 @@ type VestingAccount interface {
GetEndTime() int64
}
```
### BaseVestingAccount
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/vesting/v1beta1/vesting.proto#L10-L33
### ContinuousVestingAccount
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/vesting/v1beta1/vesting.proto#L35-L43
### DelayedVestingAccount
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/vesting/v1beta1/vesting.proto#L45-L53
### Period
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/vesting/v1beta1/vesting.proto#L56-L62
```go
@ -108,6 +113,7 @@ type Periods []Period
```
### PeriodicVestingAccount
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/vesting/v1beta1/vesting.proto#L64-L73
In order to facilitate less ad-hoc type checking and assertions and to support

View File

@ -5,6 +5,7 @@ order: 1
# Concepts
## Authorization and Grant
`x/authz` module defines interfaces and messages grant authorizations to perform actions
on behalf of one account to other accounts. The design is defined in the [ADR 030](../../../architecture/adr-030-authz-module.md).
@ -13,7 +14,6 @@ Authorization is an interface which must be implemented by a concrete authorizat
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.43.0-beta1/x/authz/authorizations.go#L11-L25
## Built-in Authorizations
Cosmos-SDK `x/authz` module comes with following authorization types
@ -28,7 +28,6 @@ Cosmos-SDK `x/authz` module comes with following authorization types
- `spent_limit` keeps track of how many coins are left in the authorization.
### GenericAuthorization
`GenericAuthorization` implements the `Authorization` interface, that gives unrestricted permission to execute the provided Msg on behalf of granter's account.

View File

@ -20,7 +20,6 @@ The message handling should fail if:
- provided `Grant.Authorization` is not implemented.
- `Authorization.MsgTypeURL()` is not defined in the router (there is no defined handler in the app router to handle that Msg types).
## MsgRevoke
A grant can be removed with the `MsgRevoke` message.

View File

@ -10,6 +10,7 @@ parent:
## Contents
## Abstract
`x/authz` is an implementation of a Cosmos SDK module, per [ADR 30](../../../architecture/adr-030-authz-module.md), that allows
granting arbitrary privileges from one account (the granter) to another account (the grantee). Authorizations must be granted for a particular Msg service method one by one using an implementation of the `Authorization` interface.

View File

@ -141,7 +141,7 @@ The `x/bank` supports the following transactional commands.
1. Send tokens via a `MsgSend` message.
```shell
$ app tx send [from_key_or_address] [to_address] [amount] [...flags]
app tx send [from_key_or_address] [to_address] [amount] [...flags]
```
Note, the `x/bank` module does not natively support constructing a `MsgMultiSend`

View File

@ -10,6 +10,7 @@ Send coins from one address to another.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/bank/v1beta1/tx.proto#L19-L28
The message will fail under the following conditions:
- The coins do not have sending enabled
- The `to` address is restricted
@ -19,8 +20,8 @@ Send coins from and to a series of different address. If any of the receiving ad
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/bank/v1beta1/tx.proto#L33-L39
The message will fail under the following conditions:
- Any of the coins do not have sending enabled
- Any of the `to` addresses are restricted
- Any of the coins are locked
- The inputs and outputs do not correctly correspond to one another

View File

@ -15,4 +15,3 @@ with the standard gas consumption method.
The ConstantFee param is held in the global params store.
- Params: `mint/params -> legacy_amino(sdk.Coin)`

View File

@ -14,6 +14,7 @@ Blockchain invariants can be checked using the `MsgVerifyInvariant` message.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc7/proto/cosmos/crisis/v1beta1/tx.proto#L14-L22
This message is expected to fail if:
- the sender does not have enough coins for the constant fee
- the invariant route is not registered

View File

@ -3,6 +3,7 @@ order: 1
-->
# Concepts
In Proof of Stake (PoS) blockchains, rewards gained from transaction fees are paid to validators. The fee distribution module fairly distributes the rewards to the validators' constituent delegators.
Rewards are calculated per period. The period is updated each time a validator's delegation changes, for example, when the validator receives a new delegation.

View File

@ -3,7 +3,9 @@ order: 5
-->
# Hooks
Available hooks that can be called by and from this module.
## Create or modify delegation distribution
- triggered-by: `staking.MsgDelegate`, `staking.MsgBeginRedelegate`, `staking.MsgUndelegate`

View File

@ -15,7 +15,9 @@ order: 1
+++ https://github.com/cosmos/cosmos-sdk/blob/691032b8be0f7539ec99f8882caecefc51f33d1f/x/feegrant/fees.go#L9-L32
## Fee Allowance types
There are two types of fee allowances present at the moment:
- `BasicAllowance`
- `PeriodicAllowance`
@ -23,7 +25,6 @@ There are two types of fee allowances present at the moment:
`BasicAllowance` is permission for `grantee` to use fee from a `granter`'s account. If any of the `spend_limit` or `expiration` reaches its limit, the grant will be removed from the state.
+++ https://github.com/cosmos/cosmos-sdk/blob/691032b8be0f7539ec99f8882caecefc51f33d1f/proto/cosmos/feegrant/v1beta1/feegrant.proto#L13-L26
- `spend_limit` is the limit of coins that are allowed to be used from the `granter` account. If it is empty, it assumes there's no spend limit, `grantee` can use any number of available tokens from `granter` account address before the expiration.
@ -61,14 +62,17 @@ There are two types of fee allowances present at the moment:
+++ https://github.com/cosmos/cosmos-sdk/blob/d97e7907f176777ed8a464006d360bb3e1a223e4/proto/cosmos/tx/v1beta1/tx.proto#L160-L181
Example cmd:
```go
./simd tx gov submit-proposal --title="Test Proposal" --description="My awesome proposal" --type="Text" --from validator-key --fee-account=cosmos1xh44hxt7spr67hqaa7nyx5gnutrz5fraw6grxn --chain-id=testnet --fees="10stake"
```
## Granted Fee Deductions
Fees are deducted from grants in the `x/auth` ante handler. To learn more about how ante handlers work, read the [Auth Module AnteHandlers Guide](../../auth/spec/03_antehandlers.md).
## Gas
In order to prevent DoS attacks, using a filtered `x/feegrant` incurs gas. The SDK must assure that the `grantee`'s transactions all conform to the filter set by the `granter`. The SDK does this by iterating over the allowed messages in the filter and charging 10 gas per filtered message. The SDK will then iterate over the messages being sent by the `grantee` to ensure the messages adhere to the filter, also charging 10 gas per message. The SDK will stop iterating and fail the transaction if it finds a message that does not conform to the filter.
**WARNING**: The gas is charged against the granted allowance. Ensure your messages conform to the filter, if any, before sending transactions using your allowance.

View File

@ -30,4 +30,3 @@ This module allows accounts to grant fee allowances and to use fees from their a
- [MsgGrantAllowance](04_events.md#msggrantallowance)
- [MsgRevokeAllowance](04_events.md#msgrevokeallowance)
- [Exec fee allowance](04_events.md#exec-fee-allowance)

View File

@ -12,12 +12,15 @@ parameter set, either to modify a value or add/remove a parameter field, a new
parameter set has to be created and the previous one rendered inactive.
### DepositParams
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/gov/v1beta1/gov.proto#L127-L145
### VotingParams
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/gov/v1beta1/gov.proto#L147-L156
### TallyParams
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/proto/cosmos/gov/v1beta1/gov.proto#L158-L183
Parameters are stored in a global `GlobalParams` KVStore.

View File

@ -7,6 +7,7 @@ order: 0
## The Minting Mechanism
The minting mechanism was designed to:
- allow for a flexible inflation rate determined by market demand targeting a particular bonded-stake ratio
- effect a balance between market liquidity and staked supply
@ -18,6 +19,7 @@ adjust to further incentivize or disincentivize being bonded, respectively. Sett
which should help provide some liquidity.
It can be broken down in the following way:
- If the inflation rate is below the goal %-bonded the inflation rate will
increase until a maximum value is reached
- If the goal % bonded (67% in Cosmos-Hub) is maintained, then the inflation

View File

@ -20,4 +20,3 @@ parent:
4. **[Parameters](04_params.md)**
5. **[Events](05_events.md)**
- [BeginBlocker](05_events.md#beginblocker)

View File

@ -16,7 +16,6 @@ The following hooks impact the slashing state:
+ `AfterValidatorCreated` stores a validator's consensus key.
+ `AfterValidatorRemoved` removes a validator's consensus key.
## Validator Bonded
Upon successful first-time bonding of a new validator, we create a new `ValidatorSigningInfo` structure for the

View File

@ -15,7 +15,6 @@ The slashing module emits the following events/tags:
| message | module | slashing |
| message | sender | {validatorAddress} |
## Keeper
## BeginBlocker: HandleValidatorSignature
@ -35,14 +34,12 @@ The slashing module emits the following events/tags:
| liveness | missed_blocks | {missedBlocksCounter} |
| liveness | height | {blockHeight} |
### Slash
+ same as `"slash"` event from `HandleValidatorSignature`, but without the `jailed` attribute.
### Jail
| Type | Attribute Key | Attribute Value |
| ----- | ------------- | ------------------ |
| slash | jailed | {validatorAddress} |

View File

@ -60,6 +60,7 @@ this process may be also be reversed. the following operations occur:
- if unjailed add record to `ValidatorByPowerIndex`
Jailed validators are not present in any of the following stores:
- the power store (from consensus power to address)
## Delegations

View File

@ -57,7 +57,6 @@ or if the binary was upgraded too early, the node will gracefully panic and exit
## StoreLoader
The `x/upgrade` module also facilitates store migrations as part of the upgrade. The
`StoreLoader` sets the migrations that need to occur before the new binary can
successfully run the chain. This `StoreLoader` is also application specific and