Merge branch 'master' into gov_split_vote_weighted_vote

This commit is contained in:
Sunny Aggarwal 2021-01-12 13:51:36 -05:00 committed by GitHub
commit a517c6bdf7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
349 changed files with 33989 additions and 3093 deletions

View File

@ -11,7 +11,7 @@ set -ue
# - DEBUG
# Source builder's functions library
. /usr/local/share/cosmos-sdk/buildlib.sh
. /usr/local/share/tendermint/buildlib.sh
# These variables are now available
# - BASEDIR

View File

@ -7,6 +7,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- uses: gaurav-nelson/github-action-markdown-link-check@1.0.8
- uses: gaurav-nelson/github-action-markdown-link-check@1.0.12
with:
folder-path: "docs"

View File

@ -152,7 +152,7 @@ jobs:
sed -i.bak "/$(echo $filename | sed 's/\//\\\//g')/d" coverage.txt
done
if: env.GIT_DIFF
- uses: codecov/codecov-action@v1.0.15
- uses: codecov/codecov-action@v1.2.1
with:
file: ./coverage.txt
if: env.GIT_DIFF

View File

@ -36,124 +36,15 @@ Ref: https://keepachangelog.com/en/1.0.0/
## [Unreleased]
### Improvements
* (logging) [\#8072](https://github.com/cosmos/cosmos-sdk/pull/8072) Refactor logging:
* Use [zerolog](https://github.com/rs/zerolog) over Tendermint's go-kit logging wrapper.
* Introduce Tendermint's `--log_format=plain|json` flag. Using format `json` allows for emitting structured JSON
logs which can be consumed by an external logging facility (e.g. Loggly). Both formats log to STDERR.
* The existing `--log_level` flag and it's default value now solely relates to the global logging
level (e.g. `info`, `debug`, etc...) instead of `<module>:<level>`.
* (crypto) [\#7987](https://github.com/cosmos/cosmos-sdk/pull/7987) Fix the inconsistency of CryptoCdc, only use `codec/legacy.Cdc`.
* (SDK) [\#7925](https://github.com/cosmos/cosmos-sdk/pull/7925) Updated dependencies to use gRPC v1.33.2
* Updated gRPC dependency to v1.33.2
* Updated iavl dependency to v0.15-rc2
* (version) [\#7848](https://github.com/cosmos/cosmos-sdk/pull/7848) [\#7941](https://github.com/cosmos/cosmos-sdk/pull/7941) `version --long` output now shows the list of build dependencies and replaced build dependencies.
### State Machine Breaking Changes
* (x/upgrade) [\#7979](https://github.com/cosmos/cosmos-sdk/pull/7979) keeper pubkey storage serialization migration from bech32 to protobuf.
### Bug Fixes
* (crypto) [\#7966](https://github.com/cosmos/cosmos-sdk/issues/7966) `Bip44Params` `String()` function now correctly returns the absolute HD path by adding the `m/` prefix.
* (x/auth) [\#8287](https://github.com/cosmos/cosmos-sdk/pull/8287) Fix `tx sign --signature-only` to return correct sequence value in signature.
## [v0.40.0-rc3](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.40.0-rc3) - 2020-11-06
### Client Breaking
* (crypto) [\#7419](https://github.com/cosmos/cosmos-sdk/pull/7419) The SDK doesn't use Tendermint's `crypto.PubKey` interface anymore, and uses instead it's own `PubKey` interface, defined in `crypto/types`. Replace all instances of `crypto.PubKey` by `cryptotypes.Pubkey`.
* (x/staking) [\#7419](https://github.com/cosmos/cosmos-sdk/pull/7419) The `TmConsPubKey` method on ValidatorI has been removed and replaced instead by `ConsPubKey` (which returns a SDK `cryptotypes.PubKey`) and `TmConsPublicKey` (which returns a Tendermint proto PublicKey).
### Improvements
* (tendermint) [\#7828](https://github.com/cosmos/cosmos-sdk/pull/7828) Update tendermint dependency to v0.34.0-rc6
## [v0.40.0-rc2](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.40.0-rc2) - 2020-11-02
### Client Breaking
* (x/upgrade) [#7697](https://github.com/cosmos/cosmos-sdk/pull/7697) Rename flag name "--time" to "--upgrade-time", "--info" to "--upgrade-info", to keep it consistent with help message.
* (x/auth) [#7788](https://github.com/cosmos/cosmos-sdk/pull/7788) Remove `tx auth` subcommands, all auth subcommands exist as `tx <subcommand>`
### API Breaking
* (x/staking/types) [\#7447](https://github.com/cosmos/cosmos-sdk/issues/7447) Remove bech32 PubKey support:
* `ValidatorI` interface update. `GetConsPubKey` renamed to `TmConsPubKey` (consensus public key must be a tendermint key). `TmConsPubKey`, `GetConsAddr` methods return error.
* `Validator` update. Methods changed in `ValidatorI` (as described above) and `ToTmValidator` return error.
* `Validator.ConsensusPubkey` type changed from `string` to `codectypes.Any`.
* `MsgCreateValidator.Pubkey` type changed from `string` to `codectypes.Any`.
* Deprecating and renaming `MakeEncodingConfig` to `MakeTestEncodingConfig` (both in `simapp` and `simapp/params` packages).
* (tx) [\#7688](https://github.com/cosmos/cosmos-sdk/pull/7688) The gRPC simulate service method has been moved from `cosmos.base.v1beta1.simulate` to `cosmos.tx.v1beta1`, as a method in the Tx service.
* [#7764](https://github.com/cosmos/cosmos-sdk/pull/7764) Added module initialization options:
* `server/types.AppExporter` requires extra argument: `AppOptions`.
* `server.AddCommands` requires extra argument: `addStartFlags types.ModuleInitFlags`
* `x/crisis.NewAppModule` has a new attribute: `skipGenesisInvariants`. [PR](https://github.com/cosmos/cosmos-sdk/pull/7764)
* [#7918](https://github.com/cosmos/cosmos-sdk/pull/7918) Add x/capability safety checks:
* All outward facing APIs will now check that capability is not nil and name is not empty before performing any state-machine changes
* `SetIndex` has been renamed to `InitializeIndex`
### Features
* (tx) [\#7688](https://github.com/cosmos/cosmos-sdk/pull/7688) Add a new Tx gRPC service with methods `Simulate` and `GetTx` (by hash).
* __Modules__
* `x/crisis` has a new function: `AddModuleInitFlags`, which will register optional crisis module flags for the start command.
### Bug Fixes
* (client) [\#7699](https://github.com/cosmos/cosmos-sdk/pull/7699) Fix panic in context when setting invalid nodeURI. `WithNodeURI` does not set the `Client` in the context.
* (x/gov) [#7641](https://github.com/cosmos/cosmos-sdk/pull/7641) Fix tally calculation precision error.
### Improvements
* (rest) [#7649](https://github.com/cosmos/cosmos-sdk/pull/7649) Return an unsigned tx in legacy GET /tx endpoint when signature conversion fails
* (cli) [#7764](https://github.com/cosmos/cosmos-sdk/pull/7764) Update x/banking and x/crisis InitChain to improve node startup time
## [v0.40.0-rc1](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.40.0-rc1) - 2020-10-19
### Client Breaking Changes
* __Modules__
* (x/staking) [\#7499](https://github.com/cosmos/cosmos-sdk/pull/7499) `BondStatus` is now a protobuf `enum` instead
of an `int32`, and JSON serialized using its protobuf name, so expect names like `BOND_STATUS_UNBONDING` as opposed
to `Unbonding`.
* (x/staking) [\#7556](https://github.com/cosmos/cosmos-sdk/pull/7556) The ABCI's `Result.Data` field for
`MsgBeginRedelegate` and `MsgUndelegate` responses does not contain custom binary marshaled `completionTime`, but the
protobuf encoded `MsgBeginRedelegateResponse` and `MsgUndelegateResponse` structs respectively
* (x/evidence) [\#7538](https://github.com/cosmos/cosmos-sdk/pull/7538) The ABCI's `Result.Data` field for
`MsgSubmitEvidence` responses does not contain the raw evidence's hash, but the protobuf encoded
`MsgSubmitEvidenceResponse` struct.
* (x/gov) [\#7533](https://github.com/cosmos/cosmos-sdk/pull/7533) The ABCI's `Result.Data` field for
`MsgSubmitProposal` responses does not contain a raw binary encoding of the `proposalID`, but the protobuf encoded
`MsgSubmitSubmitProposalResponse` struct.
### API Breaking
* (AppModule) [\#7518](https://github.com/cosmos/cosmos-sdk/pull/7518) [\#7584](https://github.com/cosmos/cosmos-sdk/pull/7584) Rename `AppModule.RegisterQueryServices` to `AppModule.RegisterServices`, as this method now registers multiple services (the gRPC query service and the protobuf Msg service). A `Configurator` struct is used to hold the different services.
### Features
* (modules) [\#7540](https://github.com/cosmos/cosmos-sdk/issues/7540) Protobuf service definitions can now be used for
packing `Msg`s in transactions as defined in [ADR 031](./docs/architecture/adr-031-msg-service.md). All modules now
define a `Msg` protobuf service.
* (codec) [\#7519](https://github.com/cosmos/cosmos-sdk/pull/7519) `InterfaceRegistry` now inherits `jsonpb.AnyResolver`, and has a `RegisterCustomTypeURL` method to support ADR 031 packing of `Any`s. `AnyResolver` is now a required parameter to `RejectUnknownFields`.
* (baseapp) [\#7519](https://github.com/cosmos/cosmos-sdk/pull/7519) Add `ServiceMsgRouter` to BaseApp to handle routing of protobuf service `Msg`s. The two new types defined in ADR 031, `sdk.ServiceMsg` and `sdk.MsgRequest` are introduced with this router.
* (cli) [\#7221](https://github.com/cosmos/cosmos-sdk/pull/7221) Add the option of emitting amino encoded json from the CLI
### Bug Fixes
* (kvstore) [\#7415](https://github.com/cosmos/cosmos-sdk/pull/7415) Allow new stores to be registered during on-chain upgrades.
* (rest) [\#7730](https://github.com/cosmos/cosmos-sdk/pull/7730) Fix fetch txs by height on legacy REST endpoint
### Improvements
* (tendermint) [\#7527](https://github.com/cosmos/cosmos-sdk/pull/7527) Update sdk to tendermint 0.34-rc5
* (iavl) [\#7549](https://github.com/cosmos/cosmos-sdk/pull/7549) Update sdk to IAVL 0.15.0-rc4
## [v0.40.0-rc0](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.40.0-rc0) - 2020-10-13
## [v0.40.0](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.40.0) - 2021-01-08
v0.40.0, known as the Stargate release of the Cosmos SDK, is one of the largest releases
of the Cosmos SDK since launch. Please read through this changelog and [release notes](./RELEASE_NOTES.md) to make sure you are aware of any relevant breaking changes.
of the Cosmos SDK since launch. Please read through this changelog and [release notes](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0/RELEASE_NOTES.md) to make
sure you are aware of any relevant breaking changes.
### Client Breaking Changes
@ -161,8 +52,10 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* (client/keys) [\#5889](https://github.com/cosmos/cosmos-sdk/pull/5889) remove `keys update` command.
* (x/auth) [\#5844](https://github.com/cosmos/cosmos-sdk/pull/5844) `tx sign` command now returns an error when signing is attempted with offline/multisig keys.
* (x/auth) [\#6108](https://github.com/cosmos/cosmos-sdk/pull/6108) `tx sign` command's `--validate-signatures` flag is migrated into a `tx validate-signatures` standalone command.
* (x/auth) [#7788](https://github.com/cosmos/cosmos-sdk/pull/7788) Remove `tx auth` subcommands, all auth subcommands exist as `tx <subcommand>`
* (x/genutil) [\#6651](https://github.com/cosmos/cosmos-sdk/pull/6651) The `gentx` command has been improved. No longer are `--from` and `--name` flags required. Instead, a single argument, `name`, is required which refers to the key pair in the Keyring. In addition, an optional
`--moniker` flag can be provided to override the moniker found in `config.toml`.
* (x/upgrade) [#7697](https://github.com/cosmos/cosmos-sdk/pull/7697) Rename flag name "--time" to "--upgrade-time", "--info" to "--upgrade-info", to keep it consistent with help message.
* __REST / Queriers__
* (api) [\#6426](https://github.com/cosmos/cosmos-sdk/pull/6426) The ability to start an out-of-process API REST server has now been removed. Instead, the API server is now started in-process along with the application and Tendermint. Configuration options have been added to `app.toml` to enable/disable the API server along with additional HTTP server options.
* (client) [\#7246](https://github.com/cosmos/cosmos-sdk/pull/7246) The rest server endpoint `/swagger-ui/` is replaced by `/swagger/`, and contains swagger documentation for gRPC Gateway routes in addition to legacy REST routes. Swagger API is exposed only if set in `app.toml`.
@ -173,6 +66,9 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* __General__
* (baseapp) [\#6384](https://github.com/cosmos/cosmos-sdk/pull/6384) The `Result.Data` is now a Protocol Buffer encoded binary blob of type `TxData`. The `TxData` contains `Data` which contains a list of Protocol Buffer encoded message data and the corresponding message type.
* (client) [\#5783](https://github.com/cosmos/cosmos-sdk/issues/5783) Unify all coins representations on JSON client requests for governance proposals.
* (crypto) [\#7419](https://github.com/cosmos/cosmos-sdk/pull/7419) The SDK doesn't use Tendermint's `crypto.PubKey`
interface anymore, and uses instead it's own `PubKey` interface, defined in `crypto/types`. Replace all instances of
`crypto.PubKey` by `cryptotypes.Pubkey`.
* (store/rootmulti) [\#6390](https://github.com/cosmos/cosmos-sdk/pull/6390) Proofs of empty stores are no longer supported.
* (store/types) [\#5730](https://github.com/cosmos/cosmos-sdk/pull/5730) store.types.Cp() is removed in favour of types.CopyBytes().
* (x/auth) [\#6054](https://github.com/cosmos/cosmos-sdk/pull/6054) Remove custom JSON marshaling for base accounts as multsigs cannot be bech32 decoded.
@ -180,14 +76,29 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* (x/bank) [\#5785](https://github.com/cosmos/cosmos-sdk/issues/5785) In x/bank errors, JSON strings coerced to valid UTF-8 bytes at JSON marshalling time
are now replaced by human-readable expressions. This change can potentially break compatibility with all those client side tools
that parse log messages.
* (x/evidence) [\#7538](https://github.com/cosmos/cosmos-sdk/pull/7538) The ABCI's `Result.Data` field for
`MsgSubmitEvidence` responses does not contain the raw evidence's hash, but the protobuf encoded
`MsgSubmitEvidenceResponse` struct.
* (x/gov) [\#7533](https://github.com/cosmos/cosmos-sdk/pull/7533) The ABCI's `Result.Data` field for
`MsgSubmitProposal` responses does not contain a raw binary encoding of the `proposalID`, but the protobuf encoded
`MsgSubmitSubmitProposalResponse` struct.
* (x/gov) [\#6859](https://github.com/cosmos/cosmos-sdk/pull/6859) `ProposalStatus` and `VoteOption` are now JSON serialized using its protobuf name, so expect names like `PROPOSAL_STATUS_DEPOSIT_PERIOD` as opposed to `DepositPeriod`.
* (x/staking) [\#7499](https://github.com/cosmos/cosmos-sdk/pull/7499) `BondStatus` is now a protobuf `enum` instead
of an `int32`, and JSON serialized using its protobuf name, so expect names like `BOND_STATUS_UNBONDING` as opposed
to `Unbonding`.
* (x/staking) [\#7556](https://github.com/cosmos/cosmos-sdk/pull/7556) The ABCI's `Result.Data` field for
`MsgBeginRedelegate` and `MsgUndelegate` responses does not contain custom binary marshaled `completionTime`, but the
protobuf encoded `MsgBeginRedelegateResponse` and `MsgUndelegateResponse` structs respectively
### API Breaking Changes
* __Baseapp / Client__
* (AppModule) [\#7518](https://github.com/cosmos/cosmos-sdk/pull/7518) [\#7584](https://github.com/cosmos/cosmos-sdk/pull/7584) Rename `AppModule.RegisterQueryServices` to `AppModule.RegisterServices`, as this method now registers multiple services (the gRPC query service and the protobuf Msg service). A `Configurator` struct is used to hold the different services.
* (baseapp) [\#5865](https://github.com/cosmos/cosmos-sdk/pull/5865) The `SimulationResponse` returned from tx simulation is now JSON encoded instead of Amino binary.
* (client) [\#6290](https://github.com/cosmos/cosmos-sdk/pull/6290) `CLIContext` is renamed to `Context`. `Context` and all related methods have been moved from package context to client.
* (client) [\#6525](https://github.com/cosmos/cosmos-sdk/pull/6525) Removed support for `indent` in JSON responses. Clients should consider piping to an external tool such as `jq`.
* (client) [\#8107](https://github.com/cosmos/cosmos-sdk/pull/8107) Renamed `PrintOutput` and `PrintOutputLegacy`
methods of the `context.Client` object to `PrintProto` and `PrintObjectLegacy`.
* (client/flags) [\#6632](https://github.com/cosmos/cosmos-sdk/pull/6632) Remove NewCompletionCmd(), the function is now available in tendermint.
* (client/input) [\#5904](https://github.com/cosmos/cosmos-sdk/pull/5904) Removal of unnecessary `GetCheckPassword`, `PrintPrefixed` functions.
* (client/keys) [\#5889](https://github.com/cosmos/cosmos-sdk/pull/5889) Rename `NewKeyBaseFromDir()` -> `NewLegacyKeyBaseFromDir()`.
@ -195,6 +106,10 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* (client/rpc) [\#6290](https://github.com/cosmos/cosmos-sdk/pull/6290) `client` package and subdirs reorganization.
* (client/lcd) [\#6290](https://github.com/cosmos/cosmos-sdk/pull/6290) `CliCtx` of struct `RestServer` in package client/lcd has been renamed to `ClientCtx`.
* (codec) [\#6330](https://github.com/cosmos/cosmos-sdk/pull/6330) `codec.RegisterCrypto` has been moved to the `crypto/codec` package and the global `codec.Cdc` Amino instance has been deprecated and moved to the `codec/legacy_global` package.
* (codec) [\#8080](https://github.com/cosmos/cosmos-sdk/pull/8080) Updated the `codec.Marshaler` interface
* Moved `MarshalAny` and `UnmarshalAny` helper functions to `codec.Marshaler` and renamed to `MarshalInterface` and
`UnmarshalInterface` respectively. These functions must take interface as a parameter (not a concrete type nor `Any`
object). Underneath they use `Any` wrapping for correct protobuf serialization.
* (crypto) [\#6780](https://github.com/cosmos/cosmos-sdk/issues/6780) Move ledger code to its own package.
* (crypto/types/multisig) [\#6373](https://github.com/cosmos/cosmos-sdk/pull/6373) `multisig.Multisignature` has been renamed to `AminoMultisignature`
* (codec) `*codec.LegacyAmino` is now a wrapper around Amino which provides backwards compatibility with protobuf `Any`. ALL legacy code should use `*codec.LegacyAmino` instead of `*amino.Codec` directly
@ -209,6 +124,7 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
information on how to implement the new `Keyring` interface.
* [\#5858](https://github.com/cosmos/cosmos-sdk/pull/5858) Make Keyring store keys by name and address's hexbytes representation.
* (export) [\#5952](https://github.com/cosmos/cosmos-sdk/pull/5952) `AppExporter` now returns ABCI consensus parameters to be included in marshaled exported state. These parameters must be returned from the application via the `BaseApp`.
* (simapp) Deprecating and renaming `MakeEncodingConfig` to `MakeTestEncodingConfig` (both in `simapp` and `simapp/params` packages).
* (store) [\#5803](https://github.com/cosmos/cosmos-sdk/pull/5803) The `store.CommitMultiStore` interface now includes the new `snapshots.Snapshotter` interface as well.
* (types) [\#5579](https://github.com/cosmos/cosmos-sdk/pull/5579) The `keepRecent` field has been removed from the `PruningOptions` type.
The `PruningOptions` type now only includes fields `KeepEvery` and `SnapshotEvery`, where `KeepEvery`
@ -233,16 +149,46 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* (modules) [\#6447](https://github.com/cosmos/cosmos-sdk/issues/6447) Rename `blacklistedAddrs` to `blockedAddrs`.
* (modules) [\#6834](https://github.com/cosmos/cosmos-sdk/issues/6834) Add `RegisterInterfaces` method to `AppModuleBasic` to support registration of protobuf interface types.
* (modules) [\#6734](https://github.com/cosmos/cosmos-sdk/issues/6834) Add `TxEncodingConfig` parameter to `AppModuleBasic.ValidateGenesis` command to support JSON tx decoding in `genutil`.
* (modules) [#7764](https://github.com/cosmos/cosmos-sdk/pull/7764) Added module initialization options:
* `server/types.AppExporter` requires extra argument: `AppOptions`.
* `server.AddCommands` requires extra argument: `addStartFlags types.ModuleInitFlags`
* `x/crisis.NewAppModule` has a new attribute: `skipGenesisInvariants`. [PR](https://github.com/cosmos/cosmos-sdk/pull/7764)
* (types) [\#6327](https://github.com/cosmos/cosmos-sdk/pull/6327) `sdk.Msg` now inherits `proto.Message`, as a result all `sdk.Msg` types now use pointer semantics.
* (types) [\#7032](https://github.com/cosmos/cosmos-sdk/pull/7032) All types ending with `ID` (e.g. `ProposalID`) now end with `Id` (e.g. `ProposalId`), to match default Protobuf generated format. Also see [\#7033](https://github.com/cosmos/cosmos-sdk/pull/7033) for more details.
* (x/auth) [\#6029](https://github.com/cosmos/cosmos-sdk/pull/6029) Module accounts have been moved from `x/supply` to `x/auth`.
* (x/auth) [\#6443](https://github.com/cosmos/cosmos-sdk/issues/6443) Move `FeeTx` and `TxWithMemo` interfaces from `x/auth/ante` to `types`.
* (x/auth) [\#7006](https://github.com/cosmos/cosmos-sdk/pull/7006) All `AccountRetriever` methods now take `client.Context` as a parameter instead of as a struct member.
* (x/auth) [\#6270](https://github.com/cosmos/cosmos-sdk/pull/6270) The passphrase argument has been removed from the signature of the following functions and methods: `BuildAndSign`, ` MakeSignature`, ` SignStdTx`, `TxBuilder.BuildAndSign`, `TxBuilder.Sign`, `TxBuilder.SignStdTx`
* (x/auth) [\#6428](https://github.com/cosmos/cosmos-sdk/issues/6428):
* `NewAnteHandler` and `NewSigVerificationDecorator` both now take a `SignModeHandler` parameter.
* `SignatureVerificationGasConsumer` now has the signature: `func(meter sdk.GasMeter, sig signing.SignatureV2, params types.Params) error`.
* The `SigVerifiableTx` interface now has a `GetSignaturesV2() ([]signing.SignatureV2, error)` method and no longer has the `GetSignBytes` method.
* (x/auth/tx) [\#8106](https://github.com/cosmos/cosmos-sdk/pull/8106) change related to missing append functionality in
client transaction signing
+ added `overwriteSig` argument to `x/auth/client.SignTx` and `client/tx.Sign` functions.
+ removed `x/auth/tx.go:wrapper.GetSignatures`. The `wrapper` provides `TxBuilder` functionality, and it's a private
structure. That function was not used at all and it's not exposed through the `TxBuilder` interface.
* (x/bank) [\#7327](https://github.com/cosmos/cosmos-sdk/pull/7327) AddCoins and SubtractCoins no longer return a resultingValue and will only return an error.
* (x/capability) [#7918](https://github.com/cosmos/cosmos-sdk/pull/7918) Add x/capability safety checks:
* All outward facing APIs will now check that capability is not nil and name is not empty before performing any state-machine changes
* `SetIndex` has been renamed to `InitializeIndex`
* (x/evidence) [\#7251](https://github.com/cosmos/cosmos-sdk/pull/7251) New evidence types and light client evidence handling. The module function names changed.
* (x/evidence) [\#5952](https://github.com/cosmos/cosmos-sdk/pull/5952) Remove APIs for getting and setting `x/evidence` parameters. `BaseApp` now uses a `ParamStore` to manage Tendermint consensus parameters which is managed via the `x/params` `Substore` type.
* (x/gov) [\#6147](https://github.com/cosmos/cosmos-sdk/pull/6147) The `Content` field on `Proposal` and `MsgSubmitProposal`
is now `Any` in concordance with [ADR 019](docs/architecture/adr-019-protobuf-state-encoding.md) and `GetContent` should now
be used to retrieve the actual proposal `Content`. Also the `NewMsgSubmitProposal` constructor now may return an `error`
* (x/ibc) [\#6374](https://github.com/cosmos/cosmos-sdk/pull/6374) `VerifyMembership` and `VerifyNonMembership` now take a `specs []string` argument to specify the proof format used for verification. Most SDK chains can simply use `commitmenttypes.GetSDKSpecs()` for this argument.
* (x/params) [\#5619](https://github.com/cosmos/cosmos-sdk/pull/5619) The `x/params` keeper now accepts a `codec.Marshaller` instead of
a reference to an amino codec. Amino is still used for JSON serialization.
* (x/staking) [\#6451](https://github.com/cosmos/cosmos-sdk/pull/6451) `DefaultParamspace` and `ParamKeyTable` in staking module are moved from keeper to types to enforce consistency.
* (x/staking) [\#7419](https://github.com/cosmos/cosmos-sdk/pull/7419) The `TmConsPubKey` method on ValidatorI has been
removed and replaced instead by `ConsPubKey` (which returns a SDK `cryptotypes.PubKey`) and `TmConsPublicKey` (which
returns a Tendermint proto PublicKey).
* (x/staking/types) [\#7447](https://github.com/cosmos/cosmos-sdk/issues/7447) Remove bech32 PubKey support:
* `ValidatorI` interface update. `GetConsPubKey` renamed to `TmConsPubKey` (consensus public key must be a tendermint key). `TmConsPubKey`, `GetConsAddr` methods return error.
* `Validator` update. Methods changed in `ValidatorI` (as described above) and `ToTmValidator` return error.
* `Validator.ConsensusPubkey` type changed from `string` to `codectypes.Any`.
* `MsgCreateValidator.Pubkey` type changed from `string` to `codectypes.Any`.
* (x/supply) [\#6010](https://github.com/cosmos/cosmos-sdk/pull/6010) All `x/supply` types and APIs have been moved to `x/bank`.
* [\#6409](https://github.com/cosmos/cosmos-sdk/pull/6409) Rename all IsEmpty methods to Empty across the codebase and enforce consistency.
* [\#6231](https://github.com/cosmos/cosmos-sdk/pull/6231) Simplify `AppModule` interface, `Route` and `NewHandler` methods become only `Route`
@ -250,16 +196,7 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* (x/slashing) [\#6212](https://github.com/cosmos/cosmos-sdk/pull/6212) Remove `Get*` prefixes from key construction functions
* (server) [\#6079](https://github.com/cosmos/cosmos-sdk/pull/6079) Remove `UpgradeOldPrivValFile` (deprecated in Tendermint Core v0.28).
* [\#5719](https://github.com/cosmos/cosmos-sdk/pull/5719) Bump Go requirement to 1.14+
* (x/evidence) [\#5952](https://github.com/cosmos/cosmos-sdk/pull/5952) Remove APIs for getting and setting `x/evidence` parameters. `BaseApp` now uses a `ParamStore` to manage Tendermint consensus parameters which is managed via the `x/params` `Substore` type.
* (x/gov) [\#6147](https://github.com/cosmos/cosmos-sdk/pull/6147) The `Content` field on `Proposal` and `MsgSubmitProposal`
is now `Any` in concordance with [ADR 019](docs/architecture/adr-019-protobuf-state-encoding.md) and `GetContent` should now
be used to retrieve the actual proposal `Content`. Also the `NewMsgSubmitProposal` constructor now may return an `error`
* (x/auth) [\#7006](https://github.com/cosmos/cosmos-sdk/pull/7006) All `AccountRetriever` methods now take `client.Context` as a parameter instead of as a struct member.
* (x/auth) [\#6270](https://github.com/cosmos/cosmos-sdk/pull/6270) The passphrase argument has been removed from the signature of the following functions and methods: `BuildAndSign`, ` MakeSignature`, ` SignStdTx`, `TxBuilder.BuildAndSign`, `TxBuilder.Sign`, `TxBuilder.SignStdTx`
* (x/auth) [\#6428](https://github.com/cosmos/cosmos-sdk/issues/6428):
* `NewAnteHandler` and `NewSigVerificationDecorator` both now take a `SignModeHandler` parameter.
* `SignatureVerificationGasConsumer` now has the signature: `func(meter sdk.GasMeter, sig signing.SignatureV2, params types.Params) error`.
* The `SigVerifiableTx` interface now has a `GetSignaturesV2() ([]signing.SignatureV2, error)` method and no longer has the `GetSignBytes` method.
### State Machine Breaking
@ -328,6 +265,8 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* Every reference of `crypto.Pubkey` in context of a `Validator` is now of type string. `GetPubKeyFromBech32` must be used to get the `crypto.Pubkey`.
* The `Keeper` constructor now takes a `codec.Marshaler` instead of a concrete Amino codec. This exact type
provided is specified by `ModuleCdc`.
* (x/staking) [\#7979](https://github.com/cosmos/cosmos-sdk/pull/7979) keeper pubkey storage serialization migration
from bech32 to protobuf.
* (x/supply) [\#6010](https://github.com/cosmos/cosmos-sdk/pull/6010) Removed the `x/supply` module by merging the existing types and APIs into the `x/bank` module.
* (x/supply) [\#5533](https://github.com/cosmos/cosmos-sdk/pull/5533) Migrate the `x/supply` module to use Protocol Buffers for state
serialization instead of Amino.
@ -347,8 +286,11 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* (x/auth) [\#6213](https://github.com/cosmos/cosmos-sdk/issues/6213) Introduce new protobuf based path for transaction signing, see [ADR020](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-020-protobuf-transaction-encoding.md) for more details
* (x/auth) [\#6350](https://github.com/cosmos/cosmos-sdk/pull/6350) New sign-batch command to sign StdTx batch files.
* (baseapp) [\#5803](https://github.com/cosmos/cosmos-sdk/pull/5803) Added support for taking state snapshots at regular height intervals, via options `snapshot-interval` and `snapshot-keep-recent`.
* (baseapp) [\#7519](https://github.com/cosmos/cosmos-sdk/pull/7519) Add `ServiceMsgRouter` to BaseApp to handle routing of protobuf service `Msg`s. The two new types defined in ADR 031, `sdk.ServiceMsg` and `sdk.MsgRequest` are introduced with this router.
* (client) [\#5921](https://github.com/cosmos/cosmos-sdk/issues/5921) Introduce new gRPC and gRPC Gateway based APIs for querying app & module data. See [ADR021](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-021-protobuf-query-encoding.md) for more details
* (cli) [\#7485](https://github.com/cosmos/cosmos-sdk/pull/7485) Introduce a new optional `--keyring-dir` flag that allows clients to specify a Keyring directory if it does not reside in the directory specified by `--home`.
* (cli) [\#7221](https://github.com/cosmos/cosmos-sdk/pull/7221) Add the option of emitting amino encoded json from the CLI
* (codec) [\#7519](https://github.com/cosmos/cosmos-sdk/pull/7519) `InterfaceRegistry` now inherits `jsonpb.AnyResolver`, and has a `RegisterCustomTypeURL` method to support ADR 031 packing of `Any`s. `AnyResolver` is now a required parameter to `RejectUnknownFields`.
* (coin) [\#6755](https://github.com/cosmos/cosmos-sdk/pull/6755) Add custom regex validation for `Coin` denom by overwriting `CoinDenomRegex` when using `/types/coin.go`.
* (config) [\#7265](https://github.com/cosmos/cosmos-sdk/pull/7265) Support Tendermint block pruning through a new `min-retain-blocks` configuration that can be set in either `app.toml` or via the CLI. This parameter is used in conjunction with other criteria to determine the height at which Tendermint should prune blocks.
* (events) [\#7121](https://github.com/cosmos/cosmos-sdk/pull/7121) The application now derives what events are indexed by Tendermint via the `index-events` configuration in `app.toml`, which is a list of events taking the form `{eventType}.{attributeKey}`.
@ -357,7 +299,13 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* (genesis) [\#7089](https://github.com/cosmos/cosmos-sdk/pull/7089) The `export` command now adds a `initial_height` field in the exported JSON. Baseapp's `CommitMultiStore` now also has a `SetInitialVersion` setter, so it can set the initial store version inside `InitChain` and start a new chain from a given height.
* __General__
* (crypto/multisig) [\#6241](https://github.com/cosmos/cosmos-sdk/pull/6241) Add Multisig type directly to the repo. Previously this was in tendermint.
* (codec/types) [\#8106](https://github.com/cosmos/cosmos-sdk/pull/8106) Adding `NewAnyWithCustomTypeURL` to correctly
marshal Messages in TxBuilder.
* (tests) [\#6489](https://github.com/cosmos/cosmos-sdk/pull/6489) Introduce package `testutil`, new in-process testing network framework for use in integration and unit tests.
* (tx) Add new auth/tx gRPC & gRPC-Gateway endpoints for basic querying & broadcasting support
* [\#7842](https://github.com/cosmos/cosmos-sdk/pull/7842) Add TxsByEvent gRPC endpoint
* [\#7852](https://github.com/cosmos/cosmos-sdk/pull/7852) Add tx broadcast gRPC endpoint
* (tx) [\#7688](https://github.com/cosmos/cosmos-sdk/pull/7688) Add a new Tx gRPC service with methods `Simulate` and `GetTx` (by hash).
* (store) [\#5803](https://github.com/cosmos/cosmos-sdk/pull/5803) Added `rootmulti.Store` methods for taking and restoring snapshots, based on `iavl.Store` export/import.
* (store) [\#6324](https://github.com/cosmos/cosmos-sdk/pull/6324) IAVL store query proofs now return CommitmentOp which wraps an ics23 CommitmentProof
* (store) [\#6390](https://github.com/cosmos/cosmos-sdk/pull/6390) `RootMulti` store query proofs now return `CommitmentOp` which wraps `CommitmentProofs`
@ -365,8 +313,12 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* `ProofRuntime` only decodes and verifies `ics23.CommitmentProof`
* __Modules__
* (modules) [\#5921](https://github.com/cosmos/cosmos-sdk/issues/5921) Introduction of Query gRPC service definitions along with REST annotations for gRPC Gateway for each module
* (modules) [\#7540](https://github.com/cosmos/cosmos-sdk/issues/7540) Protobuf service definitions can now be used for
packing `Msg`s in transactions as defined in [ADR 031](./docs/architecture/adr-031-msg-service.md). All modules now
define a `Msg` protobuf service.
* (x/auth/vesting) [\#7209](https://github.com/cosmos/cosmos-sdk/pull/7209) Create new `MsgCreateVestingAccount` message type along with CLI handler that allows for the creation of delayed and continuous vesting types.
* (x/capability) [\#5828](https://github.com/cosmos/cosmos-sdk/pull/5828) Capability module integration as outlined in [ADR 3 - Dynamic Capability Store](https://github.com/cosmos/tree/master/docs/architecture/adr-003-dynamic-capability-store.md).
* (x/crisis) `x/crisis` has a new function: `AddModuleInitFlags`, which will register optional crisis module flags for the start command.
* (x/ibc) [\#5277](https://github.com/cosmos/cosmos-sdk/pull/5277) `x/ibc` changes from IBC alpha. For more details check the the [`x/ibc/core/spec`](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/spec) directory, or the ICS specs below:
* [ICS 002 - Client Semantics](https://github.com/cosmos/ics/tree/master/spec/ics-002-client-semantics) subpackage
* [ICS 003 - Connection Semantics](https://github.com/cosmos/ics/blob/master/spec/ics-003-connection-semantics) subpackage
@ -386,10 +338,14 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* __Baseapp / Client / REST__
* (client) [\#5964](https://github.com/cosmos/cosmos-sdk/issues/5964) `--trust-node` is now false by default - for real. Users must ensure it is set to true if they don't want to enable the verifier.
* (client) [\#6402](https://github.com/cosmos/cosmos-sdk/issues/6402) Fix `keys add` `--algo` flag which only worked for Tendermint's `secp256k1` default key signing algorithm.
* (client) [\#7699](https://github.com/cosmos/cosmos-sdk/pull/7699) Fix panic in context when setting invalid nodeURI. `WithNodeURI` does not set the `Client` in the context.
* (export) [\#6510](https://github.com/cosmos/cosmos-sdk/pull/6510/) Field TimeIotaMs now is included in genesis file while exporting.
* (rest) [\#5906](https://github.com/cosmos/cosmos-sdk/pull/5906) Fix an issue that make some REST calls panic when sending invalid or incomplete requests.
* (crypto) [\#7966](https://github.com/cosmos/cosmos-sdk/issues/7966) `Bip44Params` `String()` function now correctly
returns the absolute HD path by adding the `m/` prefix.
* (crypto/keyring) [\#5844](https://github.com/cosmos/cosmos-sdk/pull/5844) `Keyring.Sign()` methods no longer decode amino signatures when method receivers
are offline/multisig keys.
* (store) [\#7415](https://github.com/cosmos/cosmos-sdk/pull/7415) Allow new stores to be registered during on-chain upgrades.
* __Modules__
* (modules) [\#5569](https://github.com/cosmos/cosmos-sdk/issues/5569) `InitGenesis`, for the relevant modules, now ensures module accounts exist.
* (x/auth) [\#5892](https://github.com/cosmos/cosmos-sdk/pull/5892) Add `RegisterKeyTypeCodec` to register new
@ -397,6 +353,8 @@ of the Cosmos SDK since launch. Please read through this changelog and [release
* (x/bank) [\#6536](https://github.com/cosmos/cosmos-sdk/pull/6536) Fix bug in `WriteGeneratedTxResponse` function used by multiple
REST endpoints. Now it writes a Tx in StdTx format.
* (x/genutil) [\#5938](https://github.com/cosmos/cosmos-sdk/pull/5938) Fix `InitializeNodeValidatorFiles` error handling.
* (x/gentx) [\#8183](https://github.com/cosmos/cosmos-sdk/pull/8183) change gentx cmd amount to arg from flag
* (x/gov) [#7641](https://github.com/cosmos/cosmos-sdk/pull/7641) Fix tally calculation precision error.
* (x/staking) [\#6529](https://github.com/cosmos/cosmos-sdk/pull/6529) Export validator addresses (previously was empty).
* (x/staking) [\#5949](https://github.com/cosmos/cosmos-sdk/pull/5949) Skip staking `HistoricalInfoKey` in simulations as headers are not exported.
* (x/staking) [\#6061](https://github.com/cosmos/cosmos-sdk/pull/6061) Allow a validator to immediately unjail when no signing info is present due to
@ -415,8 +373,13 @@ falling below their minimum self-delegation and never having been bonded. The va
internet connection. Previously, `--generate-only` served this purpose in addition to only allowing txs to be generated. Now, `--generate-only` solely
allows txs to be generated without being broadcasted and disallows Keybase use and `--offline` allows the use of Keybase but does not allow any
functionality that requires an online connection.
* (cli) [#7764](https://github.com/cosmos/cosmos-sdk/pull/7764) Update x/banking and x/crisis InitChain to improve node startup time
* (client) [\#5856](https://github.com/cosmos/cosmos-sdk/pull/5856) Added the possibility to set `--offline` flag with config command.
* (client) [\#5895](https://github.com/cosmos/cosmos-sdk/issues/5895) show config options in the config command's help screen.
* (client/keys) [\#8043](https://github.com/cosmos/cosmos-sdk/pull/8043) Add support for export of unarmored private key
* (client/tx) [\#7801](https://github.com/cosmos/cosmos-sdk/pull/7801) Update sign-batch multisig to work online
* (x/genutil) [\#8099](https://github.com/cosmos/cosmos-sdk/pull/8099) `init` now supports a `--recover` flag to recover
the private validator key from a given mnemonic
* __Modules__
* (x/auth) [\#5702](https://github.com/cosmos/cosmos-sdk/pull/5702) Add parameter querying support for `x/auth`.
* (x/auth/ante) [\#6040](https://github.com/cosmos/cosmos-sdk/pull/6040) `AccountKeeper` interface used for `NewAnteHandler` and handler's decorators to add support of using custom `AccountKeeper` implementations.
@ -428,11 +391,23 @@ falling below their minimum self-delegation and never having been bonded. The va
* (x/staking) [\#5584](https://github.com/cosmos/cosmos-sdk/pull/5584) Add util function `ToTmValidator` that converts a `staking.Validator` type to `*tmtypes.Validator`.
* (x/staking) [\#6163](https://github.com/cosmos/cosmos-sdk/pull/6163) CLI and REST call to unbonding delegations and delegations now accept
pagination.
* (x/staking) [\#8178](https://github.com/cosmos/cosmos-sdk/pull/8178) Update default historical header number for stargate
* __General__
* (tendermint) [\#6365](https://github.com/cosmos/cosmos-sdk/issues/6365) Update tendermint version to v0.34, and make necessary upgrades to the SDK
* (crypto) [\#7987](https://github.com/cosmos/cosmos-sdk/pull/7987) Fix the inconsistency of CryptoCdc, only use
`codec/legacy.Cdc`.
* (logging) [\#8072](https://github.com/cosmos/cosmos-sdk/pull/8072) Refactor logging:
* Use [zerolog](https://github.com/rs/zerolog) over Tendermint's go-kit logging wrapper.
* Introduce Tendermint's `--log_format=plain|json` flag. Using format `json` allows for emitting structured JSON
logs which can be consumed by an external logging facility (e.g. Loggly). Both formats log to STDERR.
* The existing `--log_level` flag and it's default value now solely relates to the global logging
level (e.g. `info`, `debug`, etc...) instead of `<module>:<level>`.
* (rest) [#7649](https://github.com/cosmos/cosmos-sdk/pull/7649) Return an unsigned tx in legacy GET /tx endpoint when signature conversion fails
* (simulation) [\#6002](https://github.com/cosmos/cosmos-sdk/pull/6002) Add randomized consensus params into simulation.
* (store) [\#6481](https://github.com/cosmos/cosmos-sdk/pull/6481) Move `SimpleProofsFromMap` from Tendermint into the SDK.
* (store) [\#6719](https://github.com/cosmos/cosmos-sdk/6754) Add validity checks to stores for nil and empty keys.
* (SDK) Updated dependencies
* Updated iavl dependency to v0.15.3
* Update tendermint to v0.34.1
* (types) [\#7027](https://github.com/cosmos/cosmos-sdk/pull/7027) `Coin(s)` and `DecCoin(s)` updates:
* Bump denomination max length to 128
* Allow uppercase letters and numbers in denominations to support [ADR 001](./docs/architecture/adr-001-coin-source-tracing.md)
@ -446,6 +421,8 @@ falling below their minimum self-delegation and never having been bonded. The va
* (types) [\#6128](https://github.com/cosmos/cosmos-sdk/pull/6137) Add `String()` method to `GasMeter`.
* (types) [\#6195](https://github.com/cosmos/cosmos-sdk/pull/6195) Add codespace to broadcast(sync/async) response.
* (types) \#6897 Add KV type from tendermint to `types` directory.
* (version) [\#7848](https://github.com/cosmos/cosmos-sdk/pull/7848) [\#7941](https://github.com/cosmos/cosmos-sdk/pull/7941)
`version --long` output now shows the list of build dependencies and replaced build dependencies.
## [v0.39.1](https://github.com/cosmos/cosmos-sdk/releases/tag/v0.39.1) - 2020-08-11
@ -738,7 +715,7 @@ generalized genesis accounts through the `GenesisAccount` interface.
* (sdk) [\#4758](https://github.com/cosmos/cosmos-sdk/issues/4758) update `x/genaccounts` to match module spec
* (simulation) [\#4824](https://github.com/cosmos/cosmos-sdk/issues/4824) `PrintAllInvariants` flag will print all failed invariants
* (simulation) [\#4490](https://github.com/cosmos/cosmos-sdk/issues/4490) add `InitialBlockHeight` flag to resume a simulation from a given block
* Support exporting the simulation stats to a given JSON file
* (simulation) [\#4847](https://github.com/cosmos/cosmos-sdk/issues/4847), [\#4838](https://github.com/cosmos/cosmos-sdk/pull/4838) and [\#4869](https://github.com/cosmos/cosmos-sdk/pull/4869) `SimApp` and simulation refactors:
* Implement `SimulationManager` for executing modules' simulation functionalities in a modularized way
@ -1052,7 +1029,7 @@ that error is that the account doesn't exist.
* (simulation) PrintAllInvariants flag will print all failed invariants
* (simulation) Add `InitialBlockHeight` flag to resume a simulation from a given block
* (simulation) [\#4670](https://github.com/cosmos/cosmos-sdk/issues/4670) Update simulation statistics to JSON format
- Support exporting the simulation stats to a given JSON file
* [\#4775](https://github.com/cosmos/cosmos-sdk/issues/4775) Refactor CI config
* Upgrade IAVL to v0.12.4
@ -1658,9 +1635,9 @@ BREAKING CHANGES
FEATURES
* Gaia REST API
* [\#2358](https://github.com/cosmos/cosmos-sdk/issues/2358) Add distribution module REST interface
* Gaia CLI (`gaiacli`)
* [\#3429](https://github.com/cosmos/cosmos-sdk/issues/3429) Support querying
for all delegator distribution rewards.

View File

@ -218,7 +218,7 @@ only pull requests targeted directly against master.
### Development Procedure
- the latest state of development is on `master`
- `master` must never fail `make test` or `make test_cli`
- `master` must never fail `make lint test test-race`
- `master` should not fail `make lint`
- no `--force` onto `master` (except when reverting a broken commit, which should seldom happen)
- create a development branch either on github.com/cosmos/cosmos-sdk, or your fork (using `git remote add origin`)
@ -227,7 +227,7 @@ only pull requests targeted directly against master.
### Pull Merge Procedure
- ensure pull branch is rebased on `master`
- run `make test` and `make test_cli` to ensure that all tests pass
- run `make test` to ensure that all tests pass
- merge pull request
### Release Procedure
@ -306,9 +306,11 @@ new code owners is as follows: On a bi-monthly basis (or more frequently if
agreeable) all the existing code owners will privately convene to discuss
potential new candidates as well as the potential for existing code-owners to
exit or "pass on the torch". This private meeting is to be a held as a
phone/video meeting. Subsequently at the end of the meeting, one of the existing
code owners should open a PR modifying the `CODEOWNERS` file. The other code
owners should then all approve this PR to publicly display their support.
phone/video meeting.
Subsequently after the meeting, and pending final approval from the ICF,
one of the existing code owners should open a PR modifying the `CODEOWNERS` file.
The other code owners should then all approve this PR to publicly display their support.
Only if unanimous consensus is reached among all the existing code-owners will
an invitation be extended to a new potential-member. Likewise, when an existing
@ -318,6 +320,95 @@ should be taken. If however, a code-owner is demonstrably shown to intentionally
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
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
* Release committee not yet defined as there is already a roadmap that can be used for the time being
### Concept Approval
* Architecture Decision Records (ADRs) may be proposed by any contributors or maintainers of the Cosmos SDK,
and should follow the guidelines outlined in the
[ADR Creation Process](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/PROCESS.md)
* After proposal, a time bound period for Request for Comment (RFC) on ADRs commences
* ADRs are intended to be iterative, and may be merged into `master` while still in a `Proposed` status
**Time Bound Period**
* Once a PR for an ADR is opened, reviewers are expected to perform a first
review within 1 week of pull request being open
* Time bound period for individual ADR Pull Requests to be merged should not exceed 2 weeks
* Total time bound period for an ADR to reach a decision (`ABANDONED | ACCEPTED | REJECTED`) should not exceed 4 weeks
If an individual Pull Request for an ADR needs more time than 2 weeks to reach resolution, it should be merged
in current state (`Draft` or `Proposed`), with its contents updated to summarize
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
**Approval Committee & Decision Making**
In absense of general consensus, decision making requires ⅔ vote from the three members
of the **Concept Approval Committee**.
**Committee Members**
* Core Members: **Aaron** (Regen), **Bez** (Fission), **Alessio** (AiB)
* Secondary pool of candidates to replace / substitute:
* **Chris Goes** (IG), **Sunny** (Sikka)
**Committee Criteria**
Members must:
* Participate in all or almost all ADR discussions, both on Github as well as in bi-weekly Architecture Review
meetings
* Be active contributors to the SDK, and furthermore should be continuously making substantial contributions
to the project's codebase, review process, documentation and ADRs
* Have stake in the Cosmos SDK project, represented by:
* Being a client / user of the Comsos SDK
* "[giving back](https://www.debian.org/social_contract)" to the software
* Delegate representation in case of vacation or absence
Code owners need to maintain participation in the process, ideally as members of **Concept Approval Committee**
members, but at the very least as active participants in ADR discussions
Removal criteria:
* Missing 3 meetings results in ICF evaluating whether the member should be removed / replaced
* Violation of Code of Conduct
### Implementation & Release Approval
The following process should be adhered to both for implementation PRs corresponding to ADRs, as
well as for PRs made as part of a release process:
* Code reviewers should ensure the PR does exactly what the ADR said it should
* Code reviewers should have more senior engineering capability
* ⅔ approval is required from the **primary repo maintainers** in `CODEOWNERS`
* Secondary pool of candidates to replace / substitute are listed as **secondary repo maintainers** in `CODEOWNERS`
*Note: For any major or minor release series denoted as a "Stable Release" (e.g. v0.39 "Launchpad"), a separate release
committee is often established. Stable Releases, and their corresponding release committees are documented
separately in [STABLE_RELEASES.md](./STABLE_RELEASES.md)*

View File

@ -176,6 +176,16 @@ go.sum: go.mod
### Documentation ###
###############################################################################
update-swagger-docs: statik
$(BINDIR)/statik -src=client/docs/swagger-ui -dest=client/docs -f -m
@if [ -n "$(git status --porcelain)" ]; then \
echo "\033[91mSwagger docs are out of sync!!!\033[0m";\
exit 1;\
else \
echo "\033[92mSwagger docs are in sync\033[0m";\
fi
.PHONY: update-swagger-docs
godocs:
@echo "--> Wait a few seconds and visit http://localhost:6060/pkg/github.com/cosmos/cosmos-sdk/types"
godoc -http=:6060

View File

@ -286,7 +286,7 @@ func (app *BaseApp) Commit() (res abci.ResponseCommit) {
header := app.deliverState.ctx.BlockHeader()
retainHeight := app.GetBlockRetentionHeight(header.Height)
// Write the DeliverTx state which is cache-wrapped and commit the MultiStore.
// Write the DeliverTx state into branched storage and commit the MultiStore.
// The write to the DeliverTx state writes all state transitions to the root
// MultiStore (app.cms) so when Commit() is called is persists those values.
app.deliverState.ms.Write()
@ -629,7 +629,7 @@ func (app *BaseApp) createQueryContext(height int64, prove bool) (sdk.Context, e
)
}
// cache wrap the commit-multistore for safety
// branch the commit-multistore for safety
ctx := sdk.NewContext(
cacheMS, app.checkState.ctx.BlockHeader(), true, app.logger,
).WithMinGasPrices(app.minGasPrices)

View File

@ -357,8 +357,8 @@ func (app *BaseApp) Seal() { app.sealed = true }
// IsSealed returns true if the BaseApp is sealed and false otherwise.
func (app *BaseApp) IsSealed() bool { return app.sealed }
// setCheckState sets the BaseApp's checkState with a cache-wrapped multi-store
// (i.e. a CacheMultiStore) and a new Context with the cache-wrapped multi-store,
// setCheckState sets the BaseApp's checkState with a branched multi-store
// (i.e. a CacheMultiStore) and a new Context with the same multi-store branch,
// provided header, and minimum gas prices set. It is set on InitChain and reset
// on Commit.
func (app *BaseApp) setCheckState(header tmproto.Header) {
@ -369,8 +369,8 @@ func (app *BaseApp) setCheckState(header tmproto.Header) {
}
}
// setDeliverState sets the BaseApp's deliverState with a cache-wrapped multi-store
// (i.e. a CacheMultiStore) and a new Context with the cache-wrapped multi-store,
// setDeliverState sets the BaseApp's deliverState with a branched multi-store
// (i.e. a CacheMultiStore) and a new Context with the same multi-store branch,
// and provided header. It is set on InitChain and BeginBlock and set to nil on
// Commit.
func (app *BaseApp) setDeliverState(header tmproto.Header) {
@ -532,7 +532,7 @@ func (app *BaseApp) getContextForTx(mode runTxMode, txBytes []byte) sdk.Context
}
// cacheTxContext returns a new context based off of the provided context with
// a cache wrapped multi-store.
// a branched multi-store.
func (app *BaseApp) cacheTxContext(ctx sdk.Context, txBytes []byte) (sdk.Context, sdk.CacheMultiStore) {
ms := ctx.MultiStore()
// TODO: https://github.com/cosmos/cosmos-sdk/issues/2824
@ -620,7 +620,7 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte) (gInfo sdk.GasInfo, re
msCache sdk.CacheMultiStore
)
// Cache wrap context before AnteHandler call in case it aborts.
// Branch context before AnteHandler call in case it aborts.
// This is required for both CheckTx and DeliverTx.
// Ref: https://github.com/cosmos/cosmos-sdk/issues/2772
//
@ -632,9 +632,8 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte) (gInfo sdk.GasInfo, re
newCtx, err := app.anteHandler(anteCtx, tx, mode == runTxModeSimulate)
if !newCtx.IsZero() {
// At this point, newCtx.MultiStore() is cache-wrapped, or something else
// replaced by the AnteHandler. We want the original multistore, not one
// which was cache-wrapped for the AnteHandler.
// At this point, newCtx.MultiStore() is a store branch, or something else
// replaced by the AnteHandler. We want the original multistore.
//
// Also, in the case of the tx aborting, we need to track gas consumed via
// the instantiated gas meter in the AnteHandler, so we update the context
@ -654,9 +653,9 @@ func (app *BaseApp) runTx(mode runTxMode, txBytes []byte) (gInfo sdk.GasInfo, re
msCache.Write()
}
// Create a new Context based off of the existing Context with a cache-wrapped
// MultiStore in case message processing fails. At this point, the MultiStore
// is doubly cached-wrapped.
// Create a new Context based off of the existing Context with a MultiStore branch
// in case message processing fails. At this point, the MultiStore
// is a branch of a branch.
runMsgCtx, msCache := app.cacheTxContext(ctx, txBytes)
// Attempt to execute all messages and only update state if all messages pass

View File

@ -64,7 +64,7 @@ func ValidateEvidenceParams(i interface{}) error {
}
if v.MaxBytes < 0 {
return fmt.Errorf("maximum evidence bytes must be positive: %v", v.MaxBytes)
return fmt.Errorf("maximum evidence bytes must be non-negative: %v", v.MaxBytes)
}
return nil

View File

@ -37,7 +37,10 @@ func TestValidateEvidenceParams(t *testing.T) {
{&tmproto.EvidenceParams{}, true},
{tmproto.EvidenceParams{}, true},
{tmproto.EvidenceParams{MaxAgeNumBlocks: -1, MaxAgeDuration: 18004000, MaxBytes: 5000000}, true},
{tmproto.EvidenceParams{MaxAgeNumBlocks: 360000, MaxAgeDuration: -1, MaxBytes: 5000000}, true},
{tmproto.EvidenceParams{MaxAgeNumBlocks: 360000, MaxAgeDuration: 18004000, MaxBytes: -1}, true},
{tmproto.EvidenceParams{MaxAgeNumBlocks: 360000, MaxAgeDuration: 18004000, MaxBytes: 5000000}, false},
{tmproto.EvidenceParams{MaxAgeNumBlocks: 360000, MaxAgeDuration: 18004000, MaxBytes: 0}, false},
}
for _, tc := range testCases {

View File

@ -95,23 +95,14 @@ func (ctx Context) BroadcastTxCommit(txBytes []byte) (*sdk.TxResponse, error) {
}
res, err := node.BroadcastTxCommit(context.Background(), txBytes)
if err != nil {
if errRes := CheckTendermintError(err, txBytes); errRes != nil {
return errRes, nil
}
return sdk.NewResponseFormatBroadcastTxCommit(res), err
}
if !res.CheckTx.IsOK() {
if err == nil {
return sdk.NewResponseFormatBroadcastTxCommit(res), nil
}
if !res.DeliverTx.IsOK() {
return sdk.NewResponseFormatBroadcastTxCommit(res), nil
if errRes := CheckTendermintError(err, txBytes); errRes != nil {
return errRes, nil
}
return sdk.NewResponseFormatBroadcastTxCommit(res), nil
return sdk.NewResponseFormatBroadcastTxCommit(res), err
}
// BroadcastTxSync broadcasts transaction bytes to a Tendermint node

View File

@ -11,6 +11,7 @@ import (
rpchttp "github.com/tendermint/tendermint/rpc/client/http"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdk "github.com/cosmos/cosmos-sdk/types"
)
@ -145,7 +146,7 @@ func ReadPersistentCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Cont
return clientCtx, nil
}
// ReadQueryCommandFlags returns an updated Context with fields set based on flags
// readQueryCommandFlags returns an updated Context with fields set based on flags
// defined in AddQueryFlagsToCmd. An error is returned if any flag query fails.
//
// Note, the provided clientCtx may have field pre-populated. The following order
@ -155,7 +156,7 @@ func ReadPersistentCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Cont
// - client.Context field not pre-populated & flag set: uses set flag value
// - client.Context field pre-populated & flag not set: uses pre-populated value
// - client.Context field pre-populated & flag set: uses set flag value
func ReadQueryCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, error) {
func readQueryCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, error) {
if clientCtx.Height == 0 || flagSet.Changed(flags.FlagHeight) {
height, _ := flagSet.GetInt64(flags.FlagHeight)
clientCtx = clientCtx.WithHeight(height)
@ -169,7 +170,7 @@ func ReadQueryCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context,
return ReadPersistentCommandFlags(clientCtx, flagSet)
}
// ReadTxCommandFlags returns an updated Context with fields set based on flags
// readTxCommandFlags returns an updated Context with fields set based on flags
// defined in AddTxFlagsToCmd. An error is returned if any flag query fails.
//
// Note, the provided clientCtx may have field pre-populated. The following order
@ -179,7 +180,7 @@ func ReadQueryCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context,
// - client.Context field not pre-populated & flag set: uses set flag value
// - client.Context field pre-populated & flag not set: uses pre-populated value
// - client.Context field pre-populated & flag set: uses set flag value
func ReadTxCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, error) {
func readTxCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, error) {
clientCtx, err := ReadPersistentCommandFlags(clientCtx, flagSet)
if err != nil {
return clientCtx, err
@ -215,19 +216,56 @@ func ReadTxCommandFlags(clientCtx Context, flagSet *pflag.FlagSet) (Context, err
clientCtx = clientCtx.WithSkipConfirmation(skipConfirm)
}
if clientCtx.SignModeStr == "" || flagSet.Changed(flags.FlagSignMode) {
signModeStr, _ := flagSet.GetString(flags.FlagSignMode)
clientCtx = clientCtx.WithSignModeStr(signModeStr)
}
if clientCtx.From == "" || flagSet.Changed(flags.FlagFrom) {
from, _ := flagSet.GetString(flags.FlagFrom)
fromAddr, fromName, err := GetFromFields(clientCtx.Keyring, from, clientCtx.GenerateOnly)
fromAddr, fromName, keyType, err := GetFromFields(clientCtx.Keyring, from, clientCtx.GenerateOnly)
if err != nil {
return clientCtx, err
}
clientCtx = clientCtx.WithFrom(from).WithFromAddress(fromAddr).WithFromName(fromName)
// If the `from` signer account is a ledger key, we need to use
// SIGN_MODE_AMINO_JSON, because ledger doesn't support proto yet.
// ref: https://github.com/cosmos/cosmos-sdk/issues/8109
if keyType == keyring.TypeLedger && clientCtx.SignModeStr != flags.SignModeLegacyAminoJSON {
fmt.Println("Default sign-mode 'direct' not supported by Ledger, using sign-mode 'amino-json'.")
clientCtx = clientCtx.WithSignModeStr(flags.SignModeLegacyAminoJSON)
}
}
return clientCtx, nil
}
// GetClientQueryContext returns a Context from a command with fields set based on flags
// defined in AddQueryFlagsToCmd. An error is returned if any flag query fails.
//
// - client.Context field not pre-populated & flag not set: uses default flag value
// - client.Context field not pre-populated & flag set: uses set flag value
// - client.Context field pre-populated & flag not set: uses pre-populated value
// - client.Context field pre-populated & flag set: uses set flag value
func GetClientQueryContext(cmd *cobra.Command) (Context, error) {
ctx := GetClientContextFromCmd(cmd)
return readQueryCommandFlags(ctx, cmd.Flags())
}
// GetClientTxContext returns a Context from a command with fields set based on flags
// defined in AddTxFlagsToCmd. An error is returned if any flag query fails.
//
// - client.Context field not pre-populated & flag not set: uses default flag value
// - client.Context field not pre-populated & flag set: uses set flag value
// - client.Context field pre-populated & flag not set: uses pre-populated value
// - client.Context field pre-populated & flag set: uses set flag value
func GetClientTxContext(cmd *cobra.Command) (Context, error) {
ctx := GetClientContextFromCmd(cmd)
return readTxCommandFlags(ctx, cmd.Flags())
}
// GetClientContextFromCmd returns a Context from a command or an empty Context
// if it has not been set.
func GetClientContextFromCmd(cmd *cobra.Command) Context {

View File

@ -64,13 +64,8 @@ func TestSetCmdClientContextHandler(t *testing.T) {
return client.SetCmdClientContextHandler(initClientCtx, cmd)
},
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)
_, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags())
if err != nil {
return err
}
return nil
_, err := client.GetClientTxContext(cmd)
return err
},
}

View File

@ -35,6 +35,7 @@ type Context struct {
From string
BroadcastMode string
FromName string
SignModeStr string
UseLedger bool
Simulate bool
GenerateOnly bool
@ -172,6 +173,13 @@ func (ctx Context) WithBroadcastMode(mode string) Context {
return ctx
}
// WithSignModeStr returns a copy of the context with an updated SignMode
// value.
func (ctx Context) WithSignModeStr(signModeStr string) Context {
ctx.SignModeStr = signModeStr
return ctx
}
// WithSkipConfirmation returns a copy of the context with an updated SkipConfirm
// value.
func (ctx Context) WithSkipConfirmation(skip bool) Context {
@ -197,21 +205,27 @@ func (ctx Context) WithInterfaceRegistry(interfaceRegistry codectypes.InterfaceR
return ctx
}
// PrintString prints the raw string to ctx.Output or os.Stdout
// PrintString prints the raw string to ctx.Output if it's defined, otherwise to os.Stdout
func (ctx Context) PrintString(str string) error {
return ctx.PrintBytes([]byte(str))
}
// PrintBytes prints the raw bytes to ctx.Output if it's defined, otherwise to os.Stdout.
// NOTE: for printing a complex state object, you should use ctx.PrintOutput
func (ctx Context) PrintBytes(o []byte) error {
writer := ctx.Output
if writer == nil {
writer = os.Stdout
}
_, err := writer.Write([]byte(str))
_, err := writer.Write(o)
return err
}
// PrintOutput outputs toPrint to the ctx.Output based on ctx.OutputFormat which is
// PrintProto outputs toPrint to the ctx.Output based on ctx.OutputFormat which is
// either text or json. If text, toPrint will be YAML encoded. Otherwise, toPrint
// will be JSON encoded using ctx.JSONMarshaler. An error is returned upon failure.
func (ctx Context) PrintOutput(toPrint proto.Message) error {
func (ctx Context) PrintProto(toPrint proto.Message) error {
// always serialize JSON initially because proto json can't be directly YAML encoded
out, err := ctx.JSONMarshaler.MarshalJSON(toPrint)
if err != nil {
@ -220,9 +234,10 @@ func (ctx Context) PrintOutput(toPrint proto.Message) error {
return ctx.printOutput(out)
}
// PrintOutputLegacy is a variant of PrintOutput that doesn't require a proto type
// and uses amino JSON encoding. It will be removed in the near future!
func (ctx Context) PrintOutputLegacy(toPrint interface{}) error {
// PrintObjectLegacy is a variant of PrintProto that doesn't require a proto.Message type
// and uses amino JSON encoding.
// Deprecated: It will be removed in the near future!
func (ctx Context) PrintObjectLegacy(toPrint interface{}) error {
out, err := ctx.LegacyAmino.MarshalJSON(toPrint)
if err != nil {
return err
@ -267,37 +282,37 @@ func (ctx Context) printOutput(out []byte) error {
return nil
}
// GetFromFields returns a from account address and Keybase name given either
// GetFromFields returns a from account address, account name and keyring type, given either
// an address or key name. If genOnly is true, only a valid Bech32 cosmos
// address is returned.
func GetFromFields(kr keyring.Keyring, from string, genOnly bool) (sdk.AccAddress, string, error) {
func GetFromFields(kr keyring.Keyring, from string, genOnly bool) (sdk.AccAddress, string, keyring.KeyType, error) {
if from == "" {
return nil, "", nil
return nil, "", 0, nil
}
if genOnly {
addr, err := sdk.AccAddressFromBech32(from)
if err != nil {
return nil, "", errors.Wrap(err, "must provide a valid Bech32 address in generate-only mode")
return nil, "", 0, errors.Wrap(err, "must provide a valid Bech32 address in generate-only mode")
}
return addr, "", nil
return addr, "", 0, nil
}
var info keyring.Info
if addr, err := sdk.AccAddressFromBech32(from); err == nil {
info, err = kr.KeyByAddress(addr)
if err != nil {
return nil, "", err
return nil, "", 0, err
}
} else {
info, err = kr.Key(from)
if err != nil {
return nil, "", err
return nil, "", 0, err
}
}
return info.GetAddress(), info.GetName(), nil
return info.GetAddress(), info.GetName(), info.GetType(), nil
}
func newKeyringFromFlags(ctx Context, backend string) (keyring.Keyring, error) {

View File

@ -23,7 +23,7 @@ func TestMain(m *testing.M) {
os.Exit(m.Run())
}
func TestContext_PrintOutput(t *testing.T) {
func TestContext_PrintObject(t *testing.T) {
ctx := client.Context{}
animal := &testdata.Dog{
@ -47,7 +47,7 @@ func TestContext_PrintOutput(t *testing.T) {
buf := &bytes.Buffer{}
ctx = ctx.WithOutput(buf)
ctx.OutputFormat = "json"
err = ctx.PrintOutput(hasAnimal)
err = ctx.PrintProto(hasAnimal)
require.NoError(t, err)
require.Equal(t,
`{"animal":{"@type":"/testdata.Dog","size":"big","name":"Spot"},"x":"10"}
@ -57,7 +57,7 @@ func TestContext_PrintOutput(t *testing.T) {
buf = &bytes.Buffer{}
ctx = ctx.WithOutput(buf)
ctx.OutputFormat = "text"
err = ctx.PrintOutput(hasAnimal)
err = ctx.PrintProto(hasAnimal)
require.NoError(t, err)
require.Equal(t,
`animal:
@ -77,7 +77,7 @@ x: "10"
buf = &bytes.Buffer{}
ctx = ctx.WithOutput(buf)
ctx.OutputFormat = "json"
err = ctx.PrintOutputLegacy(hasAnimal)
err = ctx.PrintObjectLegacy(hasAnimal)
require.NoError(t, err)
require.Equal(t,
`{"type":"testdata/HasAnimal","value":{"animal":{"type":"testdata/Dog","value":{"size":"big","name":"Spot"}},"x":"10"}}
@ -87,7 +87,7 @@ x: "10"
buf = &bytes.Buffer{}
ctx = ctx.WithOutput(buf)
ctx.OutputFormat = "text"
err = ctx.PrintOutputLegacy(hasAnimal)
err = ctx.PrintObjectLegacy(hasAnimal)
require.NoError(t, err)
require.Equal(t,
`type: testdata/HasAnimal

View File

@ -28,6 +28,14 @@
}
}
},
{
"url": "./tmp-swagger-gen/cosmos/base/tendermint/v1beta1/query.swagger.json",
"operationIds": {
"rename": {
"Params": "BaseParams"
}
}
},
{
"url": "./tmp-swagger-gen/cosmos/distribution/v1beta1/query.swagger.json",
"operationIds": {
@ -85,6 +93,12 @@
}
}
},
{
"url": "./tmp-swagger-gen/cosmos/tx/v1beta1/service.swagger.json",
"dereference": {
"circular": "ignore"
}
},
{
"url": "./tmp-swagger-gen/cosmos/upgrade/v1beta1/query.swagger.json",
"operationIds": {

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -30,6 +30,11 @@ const (
// BroadcastAsync defines a tx broadcasting mode where the client returns
// immediately.
BroadcastAsync = "async"
// SignModeDirect is the value of the --sign-mode flag for SIGN_MODE_DIRECT
SignModeDirect = "direct"
// SignModeLegacyAminoJSON is the value of the --sign-mode flag for SIGN_MODE_LEGACY_AMINO_JSON
SignModeLegacyAminoJSON = "amino-json"
)
// List of CLI flags

View File

@ -866,74 +866,74 @@ func init() {
}
var fileDescriptor_40c93fb3ef485c5d = []byte{
// 1059 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x56, 0xcf, 0x6f, 0xdc, 0xc4,
0x17, 0x8f, 0xb3, 0x6d, 0x36, 0x79, 0xfb, 0xd5, 0x97, 0x64, 0x12, 0x1a, 0xc7, 0x4a, 0xb7, 0xc1,
0x87, 0x36, 0x21, 0x8a, 0xad, 0xdd, 0x10, 0x0a, 0xe2, 0x97, 0x08, 0x81, 0x34, 0x6a, 0xa9, 0x22,
0x07, 0x71, 0x40, 0x48, 0x96, 0x77, 0x3d, 0x71, 0x46, 0xd9, 0xf5, 0x4c, 0x3d, 0xe3, 0xa0, 0x15,
0xaa, 0x40, 0xfd, 0x0b, 0x90, 0xf8, 0x17, 0x7a, 0xe1, 0x1f, 0xe0, 0x88, 0x38, 0x72, 0xa3, 0x12,
0x12, 0xf4, 0x88, 0x12, 0xfe, 0x0a, 0x4e, 0xc8, 0x33, 0xe3, 0x5d, 0xbb, 0x49, 0xba, 0xbb, 0x39,
0x20, 0x71, 0xf2, 0xcc, 0xfb, 0x35, 0x9f, 0xcf, 0x9b, 0xf7, 0x9e, 0x07, 0x5e, 0x6f, 0x53, 0xde,
0xa5, 0xdc, 0x6d, 0x05, 0x1c, 0xbb, 0x02, 0xc7, 0x21, 0x4e, 0xba, 0x24, 0x16, 0xee, 0x49, 0xa3,
0x85, 0x45, 0xd0, 0x70, 0x1f, 0xa5, 0x38, 0xe9, 0x39, 0x2c, 0xa1, 0x82, 0xa2, 0xba, 0xb2, 0x75,
0x32, 0x5b, 0x67, 0x60, 0xeb, 0x68, 0x5b, 0x6b, 0x21, 0xa2, 0x11, 0x95, 0xa6, 0x6e, 0xb6, 0x52,
0x5e, 0xd6, 0x52, 0x44, 0x69, 0xd4, 0xc1, 0xae, 0xdc, 0xb5, 0xd2, 0x43, 0x37, 0x88, 0x75, 0x40,
0x6b, 0x59, 0xab, 0x02, 0x46, 0xdc, 0x20, 0x8e, 0xa9, 0x08, 0x04, 0xa1, 0x31, 0xd7, 0x5a, 0xab,
0x00, 0x87, 0x35, 0x99, 0x2b, 0x7a, 0x0c, 0xe7, 0xba, 0xe5, 0x82, 0x4e, 0xca, 0xdd, 0x56, 0x87,
0xb6, 0x8f, 0x2f, 0xd5, 0x16, 0x7d, 0x4b, 0x94, 0x25, 0xbf, 0x3e, 0x5b, 0x16, 0x44, 0x24, 0x96,
0x20, 0x94, 0xad, 0xfd, 0xad, 0x01, 0xf5, 0x5d, 0x2c, 0x3e, 0x0f, 0x3a, 0x24, 0x0c, 0x04, 0x4d,
0x0e, 0xb0, 0xd8, 0xee, 0xdd, 0xc3, 0x24, 0x3a, 0x12, 0x1e, 0x7e, 0x94, 0x62, 0x2e, 0xd0, 0x0d,
0x98, 0x3a, 0x92, 0x02, 0xd3, 0x58, 0x31, 0x56, 0x2b, 0x9e, 0xde, 0xa1, 0x4f, 0x00, 0x06, 0xe1,
0xcc, 0xc9, 0x15, 0x63, 0xb5, 0xd6, 0xbc, 0xed, 0x14, 0x53, 0xa8, 0x72, 0xab, 0xcf, 0x76, 0xf6,
0x83, 0x08, 0xeb, 0x98, 0x5e, 0xc1, 0xd3, 0x7e, 0x6e, 0xc0, 0xad, 0x4b, 0x21, 0x70, 0x46, 0x63,
0x8e, 0xd1, 0x6b, 0xf0, 0x3f, 0xc9, 0xdf, 0x2f, 0x21, 0xa9, 0x49, 0x99, 0x32, 0x45, 0x7b, 0x00,
0x27, 0x79, 0x08, 0x6e, 0x4e, 0xae, 0x54, 0x56, 0x6b, 0xcd, 0x35, 0xe7, 0xe5, 0x37, 0xea, 0xf4,
0x0f, 0xf5, 0x0a, 0xce, 0x68, 0xb7, 0xc4, 0xac, 0x22, 0x99, 0xdd, 0x19, 0xca, 0x4c, 0x41, 0x2d,
0x51, 0x3b, 0x84, 0xe5, 0x5d, 0x2c, 0x1e, 0x04, 0x02, 0xf3, 0x12, 0xbf, 0x3c, 0xb5, 0xe5, 0x14,
0x1a, 0x57, 0x4e, 0xe1, 0xef, 0x06, 0xdc, 0xbc, 0xe4, 0xa0, 0xff, 0x76, 0x02, 0x9f, 0x1a, 0x30,
0xd3, 0x3f, 0x02, 0x99, 0x50, 0x0d, 0xc2, 0x30, 0xc1, 0x9c, 0x4b, 0xfc, 0x33, 0x5e, 0xbe, 0x45,
0x1b, 0x50, 0x65, 0x69, 0xcb, 0x3f, 0xc6, 0x3d, 0x5d, 0x88, 0x0b, 0x8e, 0x6a, 0x3d, 0x27, 0xef,
0x4a, 0xe7, 0xc3, 0xb8, 0xe7, 0x4d, 0xb1, 0xb4, 0x75, 0x1f, 0xf7, 0xb2, 0x6c, 0x9c, 0x50, 0x41,
0xe2, 0xc8, 0x67, 0xf4, 0x2b, 0x9c, 0x48, 0x84, 0x15, 0xaf, 0xa6, 0x64, 0xfb, 0x99, 0x08, 0xad,
0xc3, 0x1c, 0x4b, 0x28, 0xa3, 0x1c, 0x27, 0x3e, 0x4b, 0x08, 0x4d, 0x88, 0xe8, 0x99, 0xd7, 0xa4,
0xdd, 0x6c, 0xae, 0xd8, 0xd7, 0x72, 0xbb, 0x01, 0x8b, 0xbb, 0x58, 0x6c, 0x67, 0xc9, 0x1c, 0xb1,
0x7b, 0xec, 0x6f, 0xc0, 0x3c, 0xef, 0xa2, 0x2f, 0xeb, 0x0d, 0x98, 0x56, 0x97, 0x45, 0x42, 0x5d,
0x14, 0x4b, 0xc5, 0xdc, 0xab, 0x5e, 0x97, 0xae, 0x7b, 0x3b, 0x5e, 0x55, 0x9a, 0xee, 0x85, 0x68,
0x03, 0xae, 0xcb, 0xa5, 0xce, 0xc0, 0xe2, 0x25, 0x2e, 0x9e, 0xb2, 0xb2, 0x17, 0xe1, 0xd5, 0x7e,
0xc9, 0x28, 0x85, 0x42, 0x6c, 0x3f, 0x86, 0x1b, 0x2f, 0x2a, 0xfe, 0x4d, 0x5c, 0xf3, 0x30, 0xb7,
0x8b, 0xc5, 0x41, 0x2f, 0x6e, 0x93, 0x38, 0xca, 0x31, 0x39, 0x80, 0x8a, 0x42, 0x8d, 0xc7, 0x84,
0x2a, 0x57, 0x22, 0x09, 0x67, 0xda, 0xcb, 0xb7, 0xf6, 0x82, 0xb4, 0x7f, 0x48, 0x43, 0xbc, 0x17,
0x1f, 0xd2, 0x3c, 0xca, 0xcf, 0x06, 0xcc, 0x97, 0xc4, 0x3a, 0xce, 0x7d, 0x98, 0x0b, 0xf1, 0x61,
0x90, 0x76, 0x84, 0x1f, 0xd3, 0x10, 0xfb, 0x24, 0x3e, 0xa4, 0x9a, 0xe0, 0xad, 0x22, 0x5a, 0xd6,
0x64, 0xce, 0x8e, 0x32, 0xec, 0xc7, 0x78, 0x25, 0x2c, 0x0b, 0xd0, 0x97, 0x30, 0x1f, 0x30, 0xd6,
0x21, 0x6d, 0x59, 0xc1, 0xfe, 0x09, 0x4e, 0xf8, 0x60, 0x3e, 0xae, 0x0f, 0xed, 0x27, 0x65, 0x2e,
0x43, 0xa3, 0x42, 0x1c, 0x2d, 0xb7, 0xff, 0x36, 0xa0, 0x56, 0xb0, 0x41, 0x08, 0xae, 0xc5, 0x41,
0x17, 0xeb, 0x7e, 0x90, 0x6b, 0xb4, 0x04, 0xd3, 0x01, 0x63, 0xbe, 0x94, 0x4f, 0xea, 0x3e, 0x61,
0xec, 0x61, 0xa6, 0x32, 0xa1, 0x9a, 0x03, 0xaa, 0x28, 0x8d, 0xde, 0xa2, 0x9b, 0x00, 0x11, 0x11,
0x7e, 0x9b, 0x76, 0xbb, 0x44, 0xc8, 0x42, 0x9f, 0xf1, 0x66, 0x22, 0x22, 0x3e, 0x92, 0x82, 0x4c,
0xdd, 0x4a, 0x49, 0x27, 0xf4, 0x45, 0x10, 0x71, 0xf3, 0xba, 0x52, 0x4b, 0xc9, 0x67, 0x41, 0xc4,
0xa5, 0x37, 0xed, 0x73, 0x9d, 0xd2, 0xde, 0x54, 0x23, 0x45, 0x1f, 0xe7, 0xde, 0x21, 0x66, 0xdc,
0xac, 0xca, 0xd1, 0x72, 0x7b, 0x58, 0x2a, 0x3e, 0xa5, 0x61, 0xda, 0xc1, 0xfa, 0x94, 0x1d, 0xcc,
0xb8, 0x7d, 0x0f, 0xa6, 0x94, 0x30, 0xa3, 0xcd, 0x02, 0x71, 0x94, 0xd3, 0xce, 0xd6, 0x45, 0x6e,
0x93, 0x65, 0x6e, 0xb3, 0x50, 0xe1, 0x69, 0x57, 0x33, 0xce, 0x96, 0xcd, 0x27, 0x33, 0x50, 0x3d,
0xc0, 0xc9, 0x09, 0x69, 0x63, 0xf4, 0x83, 0x01, 0xb5, 0x42, 0x55, 0xa0, 0xe6, 0x30, 0x60, 0xe7,
0x2b, 0xcb, 0xda, 0x1c, 0xcb, 0x47, 0x95, 0x9d, 0xdd, 0x78, 0xf2, 0xdb, 0x5f, 0xdf, 0x4f, 0xae,
0xa3, 0x35, 0x77, 0xc8, 0x1b, 0xa5, 0x5f, 0x94, 0xe8, 0xa9, 0x01, 0x30, 0x68, 0x04, 0xd4, 0x18,
0xe1, 0xd8, 0x72, 0x27, 0x59, 0xcd, 0x71, 0x5c, 0x34, 0x50, 0x57, 0x02, 0x5d, 0x43, 0x77, 0x86,
0x01, 0xd5, 0xed, 0x87, 0x7e, 0x34, 0xe0, 0xff, 0xe5, 0x19, 0x82, 0xb6, 0x46, 0x38, 0xf7, 0xfc,
0x30, 0xb2, 0xde, 0x1c, 0xd7, 0x4d, 0x43, 0xde, 0x92, 0x90, 0x5d, 0xb4, 0x31, 0x0c, 0xb2, 0x1c,
0x3a, 0xdc, 0xed, 0xc8, 0x18, 0xe8, 0x27, 0x03, 0x66, 0x5f, 0x1c, 0xcb, 0xe8, 0xee, 0x08, 0x18,
0x2e, 0x9a, 0xfd, 0xd6, 0x5b, 0xe3, 0x3b, 0x6a, 0xf8, 0x77, 0x25, 0xfc, 0x06, 0x72, 0x47, 0x84,
0xff, 0xb5, 0xfa, 0xab, 0x3c, 0x46, 0xbf, 0x1a, 0x85, 0xb1, 0x5e, 0x7c, 0x09, 0xa0, 0x77, 0x47,
0xce, 0xe4, 0x05, 0x2f, 0x15, 0xeb, 0xbd, 0x2b, 0x7a, 0x6b, 0x3e, 0x6f, 0x4b, 0x3e, 0x9b, 0xa8,
0x31, 0x8c, 0xcf, 0xe0, 0x11, 0x91, 0x5f, 0xc9, 0x1f, 0x86, 0xfc, 0xb9, 0x5e, 0xf4, 0x3c, 0x44,
0xef, 0x8f, 0x80, 0xea, 0x25, 0x4f, 0x5b, 0xeb, 0x83, 0x2b, 0xfb, 0x6b, 0x5e, 0xef, 0x48, 0x5e,
0x5b, 0x68, 0x73, 0x0c, 0x5e, 0xf9, 0x5d, 0x6d, 0x3f, 0xf8, 0xe5, 0xb4, 0x6e, 0x3c, 0x3b, 0xad,
0x1b, 0x7f, 0x9e, 0xd6, 0x8d, 0xef, 0xce, 0xea, 0x13, 0xcf, 0xce, 0xea, 0x13, 0xcf, 0xcf, 0xea,
0x13, 0x5f, 0x34, 0x23, 0x22, 0x8e, 0xd2, 0x96, 0xd3, 0xa6, 0xdd, 0x3c, 0xb0, 0xfa, 0x6c, 0xf0,
0xf0, 0xd8, 0x6d, 0x77, 0x08, 0x8e, 0x85, 0x1b, 0x25, 0xac, 0xed, 0x8a, 0x2e, 0x57, 0x63, 0xac,
0x35, 0x25, 0x5f, 0x3a, 0x9b, 0xff, 0x04, 0x00, 0x00, 0xff, 0xff, 0xf6, 0xf3, 0x0e, 0x76, 0xf1,
0x0c, 0x00, 0x00,
// 1060 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x56, 0x4f, 0x6f, 0xdc, 0x44,
0x14, 0xaf, 0xb3, 0x6d, 0x36, 0x79, 0x8b, 0x20, 0x99, 0x84, 0xc6, 0xb1, 0xd2, 0x6d, 0xf0, 0xa1,
0x4d, 0x88, 0x62, 0x6b, 0xb7, 0x6d, 0xda, 0x43, 0x29, 0x22, 0x04, 0xd2, 0xa8, 0xa5, 0x8a, 0x1c,
0xc4, 0x01, 0x21, 0x59, 0xde, 0xf5, 0xc4, 0x19, 0x65, 0xd7, 0x33, 0xf5, 0x8c, 0x83, 0x56, 0xa8,
0x02, 0x71, 0xe2, 0x88, 0xc4, 0x57, 0xe8, 0x85, 0x2f, 0xc0, 0x11, 0x71, 0xe4, 0x58, 0x81, 0x84,
0x2a, 0x4e, 0x28, 0xe1, 0x53, 0x70, 0x42, 0x9e, 0x19, 0xef, 0xda, 0x4d, 0xd2, 0xdd, 0xcd, 0x01,
0x89, 0x93, 0x67, 0xde, 0xbf, 0xf9, 0xfd, 0xde, 0xbc, 0xf7, 0x3c, 0xf0, 0x6e, 0x9b, 0xf2, 0x2e,
0xe5, 0x6e, 0x2b, 0xe0, 0xd8, 0x15, 0x38, 0x0e, 0x71, 0xd2, 0x25, 0xb1, 0x70, 0x8f, 0x1a, 0x2d,
0x2c, 0x82, 0x86, 0xfb, 0x34, 0xc5, 0x49, 0xcf, 0x61, 0x09, 0x15, 0x14, 0xd5, 0x95, 0xad, 0x93,
0xd9, 0x3a, 0x03, 0x5b, 0x47, 0xdb, 0x5a, 0xf3, 0x11, 0x8d, 0xa8, 0x34, 0x75, 0xb3, 0x95, 0xf2,
0xb2, 0x16, 0x23, 0x4a, 0xa3, 0x0e, 0x76, 0xe5, 0xae, 0x95, 0xee, 0xbb, 0x41, 0xac, 0x03, 0x5a,
0x4b, 0x5a, 0x15, 0x30, 0xe2, 0x06, 0x71, 0x4c, 0x45, 0x20, 0x08, 0x8d, 0xb9, 0xd6, 0x5a, 0x05,
0x38, 0xac, 0xc9, 0x5c, 0xd1, 0x63, 0x38, 0xd7, 0x2d, 0x15, 0x74, 0x52, 0xee, 0xb6, 0x3a, 0xb4,
0x7d, 0x78, 0xae, 0xb6, 0xe8, 0x5b, 0xa2, 0x2c, 0xf9, 0xf5, 0xd9, 0xb2, 0x20, 0x22, 0xb1, 0x04,
0xa1, 0x6c, 0xed, 0x6f, 0x0c, 0xa8, 0x6f, 0x63, 0xf1, 0x59, 0xd0, 0x21, 0x61, 0x20, 0x68, 0xb2,
0x87, 0xc5, 0x66, 0xef, 0x21, 0x26, 0xd1, 0x81, 0xf0, 0xf0, 0xd3, 0x14, 0x73, 0x81, 0xae, 0xc2,
0xe4, 0x81, 0x14, 0x98, 0xc6, 0xb2, 0xb1, 0x52, 0xf1, 0xf4, 0x0e, 0x7d, 0x0c, 0x30, 0x08, 0x67,
0x4e, 0x2c, 0x1b, 0x2b, 0xb5, 0xe6, 0x0d, 0xa7, 0x98, 0x42, 0x95, 0x5b, 0x7d, 0xb6, 0xb3, 0x1b,
0x44, 0x58, 0xc7, 0xf4, 0x0a, 0x9e, 0xf6, 0x4b, 0x03, 0xae, 0x9f, 0x0b, 0x81, 0x33, 0x1a, 0x73,
0x8c, 0xde, 0x81, 0x37, 0x24, 0x7f, 0xbf, 0x84, 0xa4, 0x26, 0x65, 0xca, 0x14, 0xed, 0x00, 0x1c,
0xe5, 0x21, 0xb8, 0x39, 0xb1, 0x5c, 0x59, 0xa9, 0x35, 0x57, 0x9d, 0xd7, 0xdf, 0xa8, 0xd3, 0x3f,
0xd4, 0x2b, 0x38, 0xa3, 0xed, 0x12, 0xb3, 0x8a, 0x64, 0x76, 0x73, 0x28, 0x33, 0x05, 0xb5, 0x44,
0x6d, 0x1f, 0x96, 0xb6, 0xb1, 0x78, 0x1c, 0x08, 0xcc, 0x4b, 0xfc, 0xf2, 0xd4, 0x96, 0x53, 0x68,
0x5c, 0x38, 0x85, 0x7f, 0x18, 0x70, 0xed, 0x9c, 0x83, 0xfe, 0xdf, 0x09, 0x7c, 0x6e, 0xc0, 0x74,
0xff, 0x08, 0x64, 0x42, 0x35, 0x08, 0xc3, 0x04, 0x73, 0x2e, 0xf1, 0x4f, 0x7b, 0xf9, 0x16, 0xad,
0x43, 0x95, 0xa5, 0x2d, 0xff, 0x10, 0xf7, 0x74, 0x21, 0xce, 0x3b, 0xaa, 0xf5, 0x9c, 0xbc, 0x2b,
0x9d, 0x0f, 0xe2, 0x9e, 0x37, 0xc9, 0xd2, 0xd6, 0x23, 0xdc, 0xcb, 0xb2, 0x71, 0x44, 0x05, 0x89,
0x23, 0x9f, 0xd1, 0x2f, 0x71, 0x22, 0x11, 0x56, 0xbc, 0x9a, 0x92, 0xed, 0x66, 0x22, 0xb4, 0x06,
0xb3, 0x2c, 0xa1, 0x8c, 0x72, 0x9c, 0xf8, 0x2c, 0x21, 0x34, 0x21, 0xa2, 0x67, 0x5e, 0x96, 0x76,
0x33, 0xb9, 0x62, 0x57, 0xcb, 0xed, 0x06, 0x2c, 0x6c, 0x63, 0xb1, 0x99, 0x25, 0x73, 0xc4, 0xee,
0xb1, 0xbf, 0x06, 0xf3, 0xb4, 0x8b, 0xbe, 0xac, 0xdb, 0x30, 0xa5, 0x2e, 0x8b, 0x84, 0xba, 0x28,
0x16, 0x8b, 0xb9, 0x57, 0xbd, 0x2e, 0x5d, 0x77, 0xb6, 0xbc, 0xaa, 0x34, 0xdd, 0x09, 0xd1, 0x3a,
0x5c, 0x91, 0x4b, 0x9d, 0x81, 0x85, 0x73, 0x5c, 0x3c, 0x65, 0x65, 0x2f, 0xc0, 0xdb, 0xfd, 0x92,
0x51, 0x0a, 0x85, 0xd8, 0x7e, 0x06, 0x57, 0x5f, 0x55, 0xfc, 0x97, 0xb8, 0xe6, 0x60, 0x76, 0x1b,
0x8b, 0xbd, 0x5e, 0xdc, 0x26, 0x71, 0x94, 0x63, 0x72, 0x00, 0x15, 0x85, 0x1a, 0x8f, 0x09, 0x55,
0xae, 0x44, 0x12, 0xce, 0x94, 0x97, 0x6f, 0xed, 0x79, 0x69, 0xff, 0x84, 0x86, 0x78, 0x27, 0xde,
0xa7, 0x79, 0x94, 0x5f, 0x0c, 0x98, 0x2b, 0x89, 0x75, 0x9c, 0x47, 0x30, 0x1b, 0xe2, 0xfd, 0x20,
0xed, 0x08, 0x3f, 0xa6, 0x21, 0xf6, 0x49, 0xbc, 0x4f, 0x35, 0xc1, 0xeb, 0x45, 0xb4, 0xac, 0xc9,
0x9c, 0x2d, 0x65, 0xd8, 0x8f, 0xf1, 0x56, 0x58, 0x16, 0xa0, 0x2f, 0x60, 0x2e, 0x60, 0xac, 0x43,
0xda, 0xb2, 0x82, 0xfd, 0x23, 0x9c, 0xf0, 0xc1, 0x7c, 0x5c, 0x1b, 0xda, 0x4f, 0xca, 0x5c, 0x86,
0x46, 0x85, 0x38, 0x5a, 0x6e, 0xff, 0x63, 0x40, 0xad, 0x60, 0x83, 0x10, 0x5c, 0x8e, 0x83, 0x2e,
0xd6, 0xfd, 0x20, 0xd7, 0x68, 0x11, 0xa6, 0x02, 0xc6, 0x7c, 0x29, 0x9f, 0xd0, 0x7d, 0xc2, 0xd8,
0x93, 0x4c, 0x65, 0x42, 0x35, 0x07, 0x54, 0x51, 0x1a, 0xbd, 0x45, 0xd7, 0x00, 0x22, 0x22, 0xfc,
0x36, 0xed, 0x76, 0x89, 0x90, 0x85, 0x3e, 0xed, 0x4d, 0x47, 0x44, 0x7c, 0x28, 0x05, 0x99, 0xba,
0x95, 0x92, 0x4e, 0xe8, 0x8b, 0x20, 0xe2, 0xe6, 0x15, 0xa5, 0x96, 0x92, 0x4f, 0x83, 0x88, 0x4b,
0x6f, 0xda, 0xe7, 0x3a, 0xa9, 0xbd, 0xa9, 0x46, 0x8a, 0x3e, 0xca, 0xbd, 0x43, 0xcc, 0xb8, 0x59,
0x95, 0xa3, 0xe5, 0xc6, 0xb0, 0x54, 0x7c, 0x42, 0xc3, 0xb4, 0x83, 0xf5, 0x29, 0x5b, 0x98, 0x71,
0xfb, 0x21, 0x4c, 0x2a, 0x61, 0x46, 0x9b, 0x05, 0xe2, 0x20, 0xa7, 0x9d, 0xad, 0x8b, 0xdc, 0x26,
0xca, 0xdc, 0x66, 0xa0, 0xc2, 0xd3, 0xae, 0x66, 0x9c, 0x2d, 0x9b, 0xdf, 0x4d, 0x43, 0x75, 0x0f,
0x27, 0x47, 0xa4, 0x8d, 0xd1, 0x8f, 0x06, 0xd4, 0x0a, 0x55, 0x81, 0x9a, 0xc3, 0x80, 0x9d, 0xae,
0x2c, 0xeb, 0xd6, 0x58, 0x3e, 0xaa, 0xec, 0xec, 0xc6, 0xb7, 0xbf, 0xff, 0xfd, 0xc3, 0xc4, 0x1a,
0x5a, 0x75, 0x87, 0xbc, 0x51, 0xfa, 0x45, 0x89, 0x9e, 0x1b, 0x00, 0x83, 0x46, 0x40, 0x8d, 0x11,
0x8e, 0x2d, 0x77, 0x92, 0xd5, 0x1c, 0xc7, 0x45, 0x03, 0x75, 0x25, 0xd0, 0x55, 0x74, 0x73, 0x18,
0x50, 0xdd, 0x7e, 0xe8, 0x27, 0x03, 0xde, 0x2c, 0xcf, 0x10, 0x74, 0x67, 0x84, 0x73, 0x4f, 0x0f,
0x23, 0x6b, 0x63, 0x5c, 0x37, 0x0d, 0xf9, 0x8e, 0x84, 0xec, 0xa2, 0xf5, 0x61, 0x90, 0xe5, 0xd0,
0xe1, 0x6e, 0x47, 0xc6, 0x40, 0x3f, 0x1b, 0x30, 0xf3, 0xea, 0x58, 0x46, 0x77, 0x47, 0xc0, 0x70,
0xd6, 0xec, 0xb7, 0xee, 0x8d, 0xef, 0xa8, 0xe1, 0xdf, 0x95, 0xf0, 0x1b, 0xc8, 0x1d, 0x11, 0xfe,
0x57, 0xea, 0xaf, 0xf2, 0x0c, 0xfd, 0x66, 0x14, 0xc6, 0x7a, 0xf1, 0x25, 0x80, 0xee, 0x8f, 0x9c,
0xc9, 0x33, 0x5e, 0x2a, 0xd6, 0x7b, 0x17, 0xf4, 0xd6, 0x7c, 0xee, 0x4b, 0x3e, 0x1b, 0xe8, 0xf6,
0x30, 0x3e, 0x83, 0x47, 0x04, 0x16, 0xfd, 0x5b, 0xf9, 0xd3, 0x90, 0xff, 0xd7, 0xb3, 0x5e, 0x88,
0xe8, 0xc1, 0x08, 0xc0, 0x5e, 0xf3, 0xba, 0xb5, 0xde, 0xbf, 0xb0, 0xbf, 0xa6, 0xf6, 0x40, 0x52,
0xbb, 0x87, 0x36, 0xc6, 0xa3, 0x96, 0xdf, 0xd8, 0xe6, 0xe3, 0x5f, 0x8f, 0xeb, 0xc6, 0x8b, 0xe3,
0xba, 0xf1, 0xd7, 0x71, 0xdd, 0xf8, 0xfe, 0xa4, 0x7e, 0xe9, 0xc5, 0x49, 0xfd, 0xd2, 0xcb, 0x93,
0xfa, 0xa5, 0xcf, 0x9b, 0x11, 0x11, 0x07, 0x69, 0xcb, 0x69, 0xd3, 0x6e, 0x1e, 0x5b, 0x7d, 0xd6,
0x79, 0x78, 0xe8, 0xb6, 0x3b, 0x04, 0xc7, 0xc2, 0x8d, 0x12, 0xd6, 0x76, 0x45, 0x97, 0xab, 0x61,
0xd6, 0x9a, 0x94, 0xef, 0x9d, 0x5b, 0xff, 0x06, 0x00, 0x00, 0xff, 0xff, 0x08, 0x32, 0x9c, 0x36,
0xf7, 0x0c, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.

View File

@ -546,9 +546,9 @@ var (
pattern_Service_GetBlockByHeight_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"cosmos", "base", "tendermint", "v1beta1", "blocks", "height"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_Service_GetLatestValidatorSet_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 2, 5}, []string{"cosmos", "base", "tendermint", "v1beta1", "validators", "latest"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_Service_GetLatestValidatorSet_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 2, 5}, []string{"cosmos", "base", "tendermint", "v1beta1", "validatorsets", "latest"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_Service_GetValidatorSetByHeight_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"cosmos", "base", "tendermint", "v1beta1", "validators", "height"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_Service_GetValidatorSetByHeight_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"cosmos", "base", "tendermint", "v1beta1", "validatorsets", "height"}, "", runtime.AssumeColonVerbOpt(true)))
)
var (

View File

@ -117,11 +117,11 @@ func (s IntegrationTestSuite) TestQueryLatestValidatorSet() {
s.Require().NoError(err)
// rest request without pagination
_, err = rest.GetRequest(fmt.Sprintf("%s/cosmos/base/tendermint/v1beta1/validators/latest", val.APIAddress))
_, err = rest.GetRequest(fmt.Sprintf("%s/cosmos/base/tendermint/v1beta1/validatorsets/latest", val.APIAddress))
s.Require().NoError(err)
// rest request with pagination
restRes, err := rest.GetRequest(fmt.Sprintf("%s/cosmos/base/tendermint/v1beta1/validators/latest?pagination.offset=%d&pagination.limit=%d", val.APIAddress, 0, 1))
restRes, err := rest.GetRequest(fmt.Sprintf("%s/cosmos/base/tendermint/v1beta1/validatorsets/latest?pagination.offset=%d&pagination.limit=%d", val.APIAddress, 0, 1))
s.Require().NoError(err)
var validatorSetRes tmservice.GetLatestValidatorSetResponse
s.Require().NoError(val.ClientCtx.JSONMarshaler.UnmarshalJSON(restRes, &validatorSetRes))
@ -150,11 +150,11 @@ func (s IntegrationTestSuite) TestQueryValidatorSetByHeight() {
s.Require().NoError(err)
// no pagination rest
_, err = rest.GetRequest(fmt.Sprintf("%s/cosmos/base/tendermint/v1beta1/validators/%d", val.APIAddress, 1))
_, err = rest.GetRequest(fmt.Sprintf("%s/cosmos/base/tendermint/v1beta1/validatorsets/%d", val.APIAddress, 1))
s.Require().NoError(err)
// rest query with pagination
restRes, err := rest.GetRequest(fmt.Sprintf("%s/cosmos/base/tendermint/v1beta1/validators/%d?pagination.offset=%d&pagination.limit=%d", val.APIAddress, 1, 0, 1))
restRes, err := rest.GetRequest(fmt.Sprintf("%s/cosmos/base/tendermint/v1beta1/validatorsets/%d?pagination.offset=%d&pagination.limit=%d", val.APIAddress, 1, 0, 1))
var validatorSetRes tmservice.GetValidatorSetByHeightResponse
s.Require().NoError(val.ClientCtx.JSONMarshaler.UnmarshalJSON(restRes, &validatorSetRes))
}

View File

@ -85,12 +85,12 @@ the flag --nosort is set.
func runAddCmd(cmd *cobra.Command, args []string) error {
buf := bufio.NewReader(cmd.InOrStdin())
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
var (
kr keyring.Keyring
err error
)
var kr keyring.Keyring
dryRun, _ := cmd.Flags().GetBool(flags.FlagDryRun)
if dryRun {

View File

@ -29,7 +29,10 @@ private keys stored in a ledger device cannot be deleted with the CLI.
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
buf := bufio.NewReader(cmd.InOrStdin())
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
for _, name := range args {
info, err := clientCtx.Keyring.Key(name)

View File

@ -32,7 +32,10 @@ and export your keys in ASCII-armored encrypted format.`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
buf := bufio.NewReader(cmd.InOrStdin())
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
unarmored, _ := cmd.Flags().GetBool(flagUnarmoredHex)
unsafe, _ := cmd.Flags().GetBool(flagUnsafe)

View File

@ -19,7 +19,10 @@ func ImportKeyCommand() *cobra.Command {
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
buf := bufio.NewReader(cmd.InOrStdin())
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
bz, err := ioutil.ReadFile(args[1])
if err != nil {

View File

@ -24,7 +24,10 @@ along with their associated name and address.`,
}
func runListCmd(cmd *cobra.Command, _ []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
infos, err := clientCtx.Keyring.List()
if err != nil {

View File

@ -53,7 +53,10 @@ consisting of all the keys provided by name and multisig threshold.`,
func runShowCmd(cmd *cobra.Command, args []string) (err error) {
var info keyring.Info
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
if len(args) == 1 {
info, err = fetchKey(clientCtx.Keyring, args[0])

View File

@ -11,6 +11,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec/legacy"
"github.com/cosmos/cosmos-sdk/types/rest"
)
@ -21,8 +22,10 @@ func BlockCommand() *cobra.Command {
Short: "Get verified data for a the block at given height",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
var height *int64
// optional height
@ -67,7 +70,7 @@ func getBlock(clientCtx client.Context, height *int64) ([]byte, error) {
return nil, err
}
return clientCtx.LegacyAmino.MarshalJSON(res)
return legacy.Cdc.MarshalJSON(res)
}
// get the current blockchain height

View File

@ -5,10 +5,13 @@ import (
"testing"
"github.com/stretchr/testify/suite"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/codec/legacy"
clitestutil "github.com/cosmos/cosmos-sdk/testutil/cli"
"github.com/cosmos/cosmos-sdk/testutil/network"
"github.com/cosmos/cosmos-sdk/types/rest"
)
type IntegrationTestSuite struct {
@ -42,6 +45,17 @@ func (s *IntegrationTestSuite) TestStatusCommand() {
s.Require().Contains(out.String(), fmt.Sprintf("\"moniker\":\"%s\"", val0.Moniker))
}
func (s *IntegrationTestSuite) TestLatestBlocks() {
val0 := s.network.Validators[0]
res, err := rest.GetRequest(fmt.Sprintf("%s/blocks/latest", val0.APIAddress))
s.Require().NoError(err)
var result ctypes.ResultBlock
err = legacy.Cdc.UnmarshalJSON(res, &result)
s.Require().NoError(err)
}
func TestIntegrationTestSuite(t *testing.T) {
suite.Run(t, new(IntegrationTestSuite))
}

View File

@ -40,7 +40,10 @@ func StatusCommand() *cobra.Command {
Use: "status",
Short: "Query remote node for status",
RunE: func(cmd *cobra.Command, _ []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
status, err := getNodeStatus(clientCtx)
if err != nil {

View File

@ -29,8 +29,10 @@ func ValidatorCommand() *cobra.Command {
Short: "Get the full tendermint validator set at given height",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
var height *int64
// optional height
@ -53,7 +55,7 @@ func ValidatorCommand() *cobra.Command {
return err
}
return clientCtx.PrintOutputLegacy(result)
return clientCtx.PrintObjectLegacy(result)
},
}

View File

@ -29,19 +29,15 @@ type Factory struct {
simulateAndExecute bool
}
const (
signModeDirect = "direct"
signModeAminoJSON = "amino-json"
)
// NewFactoryCLI creates a new Factory.
func NewFactoryCLI(clientCtx client.Context, flagSet *pflag.FlagSet) Factory {
signModeStr, _ := flagSet.GetString(flags.FlagSignMode)
signModeStr := clientCtx.SignModeStr
signMode := signing.SignMode_SIGN_MODE_UNSPECIFIED
switch signModeStr {
case signModeDirect:
case flags.SignModeDirect:
signMode = signing.SignMode_SIGN_MODE_DIRECT
case signModeAminoJSON:
case flags.SignModeLegacyAminoJSON:
signMode = signing.SignMode_SIGN_MODE_LEGACY_AMINO_JSON
}

View File

@ -12,7 +12,6 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/input"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -21,6 +20,7 @@ import (
"github.com/cosmos/cosmos-sdk/types/tx"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
authsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
)
// GenerateOrBroadcastTxCLI will either generate and print and unsigned transaction
@ -117,7 +117,7 @@ func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error {
}
}
err = Sign(txf, clientCtx.GetFromName(), tx)
err = Sign(txf, clientCtx.GetFromName(), tx, true)
if err != nil {
return err
}
@ -133,7 +133,7 @@ func BroadcastTx(clientCtx client.Context, txf Factory, msgs ...sdk.Msg) error {
return err
}
return clientCtx.PrintOutput(res)
return clientCtx.PrintProto(res)
}
// WriteGeneratedTxResponse writes a generated unsigned transaction to the
@ -263,22 +263,15 @@ func BuildSimTx(txf Factory, msgs ...sdk.Msg) ([]byte, error) {
},
Sequence: txf.Sequence(),
}
if err := txb.SetSignatures(sig); err != nil {
return nil, err
}
any, ok := txb.(codectypes.IntoAny)
if !ok {
return nil, fmt.Errorf("cannot simulate tx that cannot be wrapped into any")
}
cached := any.AsAny().GetCachedValue()
protoTx, ok := cached.(*tx.Tx)
protoProvider, ok := txb.(authtx.ProtoTxProvider)
if !ok {
return nil, fmt.Errorf("cannot simulate amino tx")
}
simReq := tx.SimulateRequest{Tx: protoTx}
simReq := tx.SimulateRequest{Tx: protoProvider.GetProtoTx()}
return simReq.Marshal()
}
@ -375,10 +368,21 @@ func SignWithPrivKey(
return sigV2, nil
}
// Sign signs a given tx with the provided name and passphrase. The bytes signed
// over are canconical. The resulting signature will be set on the transaction.
func checkMultipleSigners(mode signing.SignMode, tx authsigning.Tx) error {
if mode == signing.SignMode_SIGN_MODE_DIRECT &&
len(tx.GetSigners()) > 1 {
return sdkerrors.Wrap(sdkerrors.ErrNotSupported, "Signing in DIRECT mode is only supported for transactions with one signer only")
}
return nil
}
// Sign signs a given tx with a named key. The bytes signed over are canconical.
// The resulting signature will be added to the transaction builder overwriting the previous
// ones if overwrite=true (otherwise, the signature will be appended).
// Signing a transaction with mutltiple signers in the DIRECT mode is not supprted and will
// return an error.
// An error is returned upon failure.
func Sign(txf Factory, name string, txBuilder client.TxBuilder) error {
func Sign(txf Factory, name string, txBuilder client.TxBuilder, overwriteSig bool) error {
if txf.keybase == nil {
return errors.New("keybase must be set prior to signing a transaction")
}
@ -388,12 +392,14 @@ func Sign(txf Factory, name string, txBuilder client.TxBuilder) error {
// use the SignModeHandler's default mode if unspecified
signMode = txf.txConfig.SignModeHandler().DefaultMode()
}
if err := checkMultipleSigners(signMode, txBuilder.GetTx()); err != nil {
return err
}
key, err := txf.keybase.Key(name)
if err != nil {
return err
}
pubKey := key.GetPubKey()
signerData := authsigning.SignerData{
ChainID: txf.chainID,
@ -418,18 +424,25 @@ func Sign(txf Factory, name string, txBuilder client.TxBuilder) error {
Data: &sigData,
Sequence: txf.Sequence(),
}
var prevSignatures []signing.SignatureV2
if !overwriteSig {
prevSignatures, err = txBuilder.GetTx().GetSignaturesV2()
if err != nil {
return err
}
}
if err := txBuilder.SetSignatures(sig); err != nil {
return err
}
// Generate the bytes to be signed.
signBytes, err := txf.txConfig.SignModeHandler().GetSignBytes(signMode, signerData, txBuilder.GetTx())
bytesToSign, err := txf.txConfig.SignModeHandler().GetSignBytes(signMode, signerData, txBuilder.GetTx())
if err != nil {
return err
}
// Sign those bytes
sigBytes, _, err := txf.keybase.Sign(name, signBytes)
sigBytes, _, err := txf.keybase.Sign(name, bytesToSign)
if err != nil {
return err
}
@ -445,8 +458,11 @@ func Sign(txf Factory, name string, txBuilder client.TxBuilder) error {
Sequence: txf.Sequence(),
}
// And here the tx is populated with the signature
return txBuilder.SetSignatures(sig)
if overwriteSig {
return txBuilder.SetSignatures(sig)
}
prevSignatures = append(prevSignatures, sig)
return txBuilder.SetSignatures(prevSignatures...)
}
// GasEstimateResponse defines a response definition for tx gas estimation.

View File

@ -10,9 +10,11 @@ import (
"github.com/cosmos/cosmos-sdk/client/tx"
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
signingtypes "github.com/cosmos/cosmos-sdk/types/tx/signing"
"github.com/cosmos/cosmos-sdk/x/auth/signing"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
)
@ -121,49 +123,110 @@ func TestBuildUnsignedTx(t *testing.T) {
}
func TestSign(t *testing.T) {
requireT := require.New(t)
path := hd.CreateHDPath(118, 0, 0).String()
kr, err := keyring.New(t.Name(), "test", t.TempDir(), nil)
require.NoError(t, err)
requireT.NoError(err)
var from = "test_sign"
var from1 = "test_key1"
var from2 = "test_key2"
_, seed, err := kr.NewMnemonic(from, keyring.English, path, hd.Secp256k1)
require.NoError(t, err)
require.NoError(t, kr.Delete(from))
// create a new key using a mnemonic generator and test if we can reuse seed to recreate that account
_, seed, err := kr.NewMnemonic(from1, keyring.English, path, hd.Secp256k1)
requireT.NoError(err)
requireT.NoError(kr.Delete(from1))
info1, _, err := kr.NewMnemonic(from1, keyring.English, path, hd.Secp256k1)
requireT.NoError(err)
info, err := kr.NewAccount(from, seed, "", path, hd.Secp256k1)
require.NoError(t, err)
info2, err := kr.NewAccount(from2, seed, "", path, hd.Secp256k1)
requireT.NoError(err)
txf := tx.Factory{}.
pubKey1 := info1.GetPubKey()
pubKey2 := info2.GetPubKey()
requireT.NotEqual(pubKey1.Bytes(), pubKey2.Bytes())
t.Log("Pub keys:", pubKey1, pubKey2)
txfNoKeybase := tx.Factory{}.
WithTxConfig(NewTestTxConfig()).
WithAccountNumber(50).
WithSequence(23).
WithFees("50stake").
WithMemo("memo").
WithChainID("test-chain")
msg := banktypes.NewMsgSend(info.GetAddress(), sdk.AccAddress("to"), nil)
txn, err := tx.BuildUnsignedTx(txf, msg)
require.NoError(t, err)
t.Log("should failed if txf without keyring")
err = tx.Sign(txf, from, txn)
require.Error(t, err)
txf = tx.Factory{}.
txfDirect := txfNoKeybase.
WithKeybase(kr).
WithTxConfig(NewTestTxConfig()).
WithAccountNumber(50).
WithSequence(23).
WithFees("50stake").
WithMemo("memo").
WithChainID("test-chain")
WithSignMode(signingtypes.SignMode_SIGN_MODE_DIRECT)
txfAmino := txfDirect.
WithSignMode(signingtypes.SignMode_SIGN_MODE_LEGACY_AMINO_JSON)
msg1 := banktypes.NewMsgSend(info1.GetAddress(), sdk.AccAddress("to"), nil)
msg2 := banktypes.NewMsgSend(info2.GetAddress(), sdk.AccAddress("to"), nil)
txb, err := tx.BuildUnsignedTx(txfNoKeybase, msg1, msg2)
requireT.NoError(err)
txb2, err := tx.BuildUnsignedTx(txfNoKeybase, msg1, msg2)
requireT.NoError(err)
txbSimple, err := tx.BuildUnsignedTx(txfNoKeybase, msg2)
requireT.NoError(err)
t.Log("should succeed if txf with keyring")
err = tx.Sign(txf, from, txn)
require.NoError(t, err)
testCases := []struct {
name string
txf tx.Factory
txb client.TxBuilder
from string
overwrite bool
expectedPKs []cryptotypes.PubKey
matchingSigs []int // if not nil, check matching signature against old ones.
}{
{"should fail if txf without keyring",
txfNoKeybase, txb, from1, true, nil, nil},
{"should fail for non existing key",
txfAmino, txb, "unknown", true, nil, nil},
{"amino: should succeed with keyring",
txfAmino, txbSimple, from1, true, []cryptotypes.PubKey{pubKey1}, nil},
{"direct: should succeed with keyring",
txfDirect, txbSimple, from1, true, []cryptotypes.PubKey{pubKey1}, nil},
t.Log("should fail for non existing key")
err = tx.Sign(txf, "non_existing_key", txn)
require.Error(t, err)
/**** test double sign Amino mode ****/
{"amino: should sign multi-signers tx",
txfAmino, txb, from1, true, []cryptotypes.PubKey{pubKey1}, nil},
{"amino: should append a second signature and not overwrite",
txfAmino, txb, from2, false, []cryptotypes.PubKey{pubKey1, pubKey2}, []int{0, 0}},
{"amino: should overwrite a signature",
txfAmino, txb, from2, true, []cryptotypes.PubKey{pubKey2}, []int{1, 0}},
/**** test double sign Direct mode
signing transaction with more than 2 signers should fail in DIRECT mode ****/
{"direct: should fail to append a signature with different mode",
txfDirect, txb, from1, false, []cryptotypes.PubKey{}, nil},
{"direct: should fail to sign multi-signers tx",
txfDirect, txb2, from1, false, []cryptotypes.PubKey{}, nil},
{"direct: should fail to overwrite multi-signers tx",
txfDirect, txb2, from1, true, []cryptotypes.PubKey{}, nil},
}
var prevSigs []signingtypes.SignatureV2
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
err = tx.Sign(tc.txf, tc.from, tc.txb, tc.overwrite)
if len(tc.expectedPKs) == 0 {
requireT.Error(err)
} else {
requireT.NoError(err)
sigs := testSigners(requireT, tc.txb.GetTx(), tc.expectedPKs...)
if tc.matchingSigs != nil {
requireT.Equal(prevSigs[tc.matchingSigs[0]], sigs[tc.matchingSigs[1]])
}
prevSigs = sigs
}
})
}
}
func testSigners(require *require.Assertions, tr signing.Tx, pks ...cryptotypes.PubKey) []signingtypes.SignatureV2 {
sigs, err := tr.GetSignaturesV2()
require.Len(sigs, len(pks))
require.NoError(err)
require.Len(sigs, len(pks))
for i := range pks {
require.True(sigs[i].PubKey.Equals(pks[i]), "Signature is signed with a wrong pubkey. Got: %s, expected: %s", sigs[i].PubKey, pks[i])
}
return sigs
}

View File

@ -1,6 +1,8 @@
package codec
import "github.com/gogo/protobuf/proto"
import (
"github.com/gogo/protobuf/proto"
)
// AminoCodec defines a codec that utilizes Codec for both binary and JSON
// encoding.
@ -78,3 +80,45 @@ func (ac *AminoCodec) UnmarshalJSON(bz []byte, ptr proto.Message) error {
func (ac *AminoCodec) MustUnmarshalJSON(bz []byte, ptr proto.Message) {
ac.LegacyAmino.MustUnmarshalJSON(bz, ptr)
}
// MarshalInterface is a convenience function for amino marshaling interfaces.
// The `i` must be an interface.
// NOTE: to marshal a concrete type, you should use MarshalBinaryBare instead
func (ac *AminoCodec) MarshalInterface(i proto.Message) ([]byte, error) {
if err := assertNotNil(i); err != nil {
return nil, err
}
return ac.LegacyAmino.MarshalBinaryBare(i)
}
// UnmarshalInterface is a convenience function for amino unmarshaling interfaces.
// `ptr` must be a pointer to an interface.
// NOTE: to unmarshal a concrete type, you should use UnmarshalBinaryBare instead
//
// Example:
// var x MyInterface
// err := cdc.UnmarshalInterface(bz, &x)
func (ac *AminoCodec) UnmarshalInterface(bz []byte, ptr interface{}) error {
return ac.LegacyAmino.UnmarshalBinaryBare(bz, ptr)
}
// MarshalInterfaceJSON is a convenience function for amino marshaling interfaces.
// The `i` must be an interface.
// NOTE: to marshal a concrete type, you should use MarshalJSON instead
func (ac *AminoCodec) MarshalInterfaceJSON(i proto.Message) ([]byte, error) {
if err := assertNotNil(i); err != nil {
return nil, err
}
return ac.LegacyAmino.MarshalJSON(i)
}
// UnmarshalInterfaceJSON is a convenience function for amino unmarshaling interfaces.
// `ptr` must be a pointer to an interface.
// NOTE: to unmarshal a concrete type, you should use UnmarshalJSON instead
//
// Example:
// var x MyInterface
// err := cdc.UnmarshalInterfaceJSON(bz, &x)
func (ac *AminoCodec) UnmarshalInterfaceJSON(bz []byte, ptr interface{}) error {
return ac.LegacyAmino.UnmarshalJSON(bz, ptr)
}

View File

@ -5,131 +5,38 @@ import (
"errors"
"testing"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/simapp"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
"github.com/cosmos/cosmos-sdk/x/auth/client/rest"
"github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx"
)
func createTestCodec() *codec.LegacyAmino {
cdc := codec.NewLegacyAmino()
cdc.RegisterInterface((*testdata.Animal)(nil), nil)
cdc.RegisterConcrete(testdata.Dog{}, "testdata/Dog", nil)
cdc.RegisterConcrete(testdata.Cat{}, "testdata/Cat", nil)
// NOTE: since we unmarshal interface using pointers, we need to register a pointer
// types here.
cdc.RegisterConcrete(&testdata.Dog{}, "testdata/Dog", nil)
cdc.RegisterConcrete(&testdata.Cat{}, "testdata/Cat", nil)
return cdc
}
func TestAminoMarsharlInterface(t *testing.T) {
cdc := codec.NewAminoCodec(createTestCodec())
m := interfaceMarshaler{cdc.MarshalInterface, cdc.UnmarshalInterface}
testInterfaceMarshaling(require.New(t), m, true)
m = interfaceMarshaler{cdc.MarshalInterfaceJSON, cdc.UnmarshalInterfaceJSON}
testInterfaceMarshaling(require.New(t), m, false)
}
func TestAminoCodec(t *testing.T) {
any, err := types.NewAnyWithValue(&testdata.Dog{Name: "rufus"})
require.NoError(t, err)
testCases := []struct {
name string
codec *codec.AminoCodec
input codec.ProtoMarshaler
recv codec.ProtoMarshaler
marshalErr bool
unmarshalErr bool
}{
{
"valid encoding and decoding",
codec.NewAminoCodec(createTestCodec()),
&testdata.Dog{Name: "rufus"},
&testdata.Dog{},
false,
false,
},
{
"invalid decode type",
codec.NewAminoCodec(createTestCodec()),
&testdata.Dog{Name: "rufus"},
&testdata.Cat{},
false,
true,
},
{
"any marshaling",
codec.NewAminoCodec(createTestCodec()),
&testdata.HasAnimal{Animal: any},
&testdata.HasAnimal{Animal: any},
false,
false,
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
bz, err := tc.codec.MarshalBinaryBare(tc.input)
if tc.marshalErr {
require.Error(t, err)
require.Panics(t, func() { tc.codec.MustMarshalBinaryBare(tc.input) })
} else {
var bz2 []byte
require.NoError(t, err)
require.NotPanics(t, func() { bz2 = tc.codec.MustMarshalBinaryBare(tc.input) })
require.Equal(t, bz, bz2)
err := tc.codec.UnmarshalBinaryBare(bz, tc.recv)
if tc.unmarshalErr {
require.Error(t, err)
require.Panics(t, func() { tc.codec.MustUnmarshalBinaryBare(bz, tc.recv) })
} else {
require.NoError(t, err)
require.NotPanics(t, func() { tc.codec.MustUnmarshalBinaryBare(bz, tc.recv) })
require.Equal(t, tc.input, tc.recv)
}
}
bz, err = tc.codec.MarshalBinaryLengthPrefixed(tc.input)
if tc.marshalErr {
require.Error(t, err)
require.Panics(t, func() { tc.codec.MustMarshalBinaryLengthPrefixed(tc.input) })
} else {
var bz2 []byte
require.NoError(t, err)
require.NotPanics(t, func() { bz2 = tc.codec.MustMarshalBinaryLengthPrefixed(tc.input) })
require.Equal(t, bz, bz2)
err := tc.codec.UnmarshalBinaryLengthPrefixed(bz, tc.recv)
if tc.unmarshalErr {
require.Error(t, err)
require.Panics(t, func() { tc.codec.MustUnmarshalBinaryLengthPrefixed(bz, tc.recv) })
} else {
require.NoError(t, err)
require.NotPanics(t, func() { tc.codec.MustUnmarshalBinaryLengthPrefixed(bz, tc.recv) })
require.Equal(t, tc.input, tc.recv)
}
}
bz, err = tc.codec.MarshalJSON(tc.input)
if tc.marshalErr {
require.Error(t, err)
require.Panics(t, func() { tc.codec.MustMarshalJSON(tc.input) })
} else {
var bz2 []byte
require.NoError(t, err)
require.NotPanics(t, func() { bz2 = tc.codec.MustMarshalJSON(tc.input) })
require.Equal(t, bz, bz2)
err := tc.codec.UnmarshalJSON(bz, tc.recv)
if tc.unmarshalErr {
require.Error(t, err)
require.Panics(t, func() { tc.codec.MustUnmarshalJSON(bz, tc.recv) })
} else {
require.NoError(t, err)
require.NotPanics(t, func() { tc.codec.MustUnmarshalJSON(bz, tc.recv) })
require.Equal(t, tc.input, tc.recv)
}
}
})
}
testMarshaling(t, codec.NewAminoCodec(createTestCodec()))
}
func TestAminoCodecMarshalJSONIndent(t *testing.T) {
@ -210,3 +117,25 @@ func TestAminoCodecUnpackAnyFails(t *testing.T) {
require.Error(t, err)
require.Equal(t, err, errors.New("AminoCodec can't handle unpack protobuf Any's"))
}
func TestAminoCodecFullDecodeAndEncode(t *testing.T) {
// This tx comes from https://github.com/cosmos/cosmos-sdk/issues/8117.
txSigned := `{"type":"cosmos-sdk/StdTx","value":{"msg":[{"type":"cosmos-sdk/MsgCreateValidator","value":{"description":{"moniker":"fulltest","identity":"satoshi","website":"example.com","details":"example inc"},"commission":{"rate":"0.500000000000000000","max_rate":"1.000000000000000000","max_change_rate":"0.200000000000000000"},"min_self_delegation":"1000000","delegator_address":"cosmos14pt0q5cwf38zt08uu0n6yrstf3rndzr5057jys","validator_address":"cosmosvaloper14pt0q5cwf38zt08uu0n6yrstf3rndzr52q28gr","pubkey":{"type":"tendermint/PubKeyEd25519","value":"CYrOiM3HtS7uv1B1OAkknZnFYSRpQYSYII8AtMMtev0="},"value":{"denom":"umuon","amount":"700000000"}}}],"fee":{"amount":[{"denom":"umuon","amount":"6000"}],"gas":"160000"},"signatures":[{"pub_key":{"type":"tendermint/PubKeySecp256k1","value":"AwAOXeWgNf1FjMaayrSnrOOKz+Fivr6DiI/i0x0sZCHw"},"signature":"RcnfS/u2yl7uIShTrSUlDWvsXo2p2dYu6WJC8VDVHMBLEQZWc8bsINSCjOnlsIVkUNNe1q/WCA9n3Gy1+0zhYA=="}],"memo":"","timeout_height":"0"}}`
var legacyCdc = simapp.MakeTestEncodingConfig().Amino
var tx legacytx.StdTx
err := legacyCdc.UnmarshalJSON([]byte(txSigned), &tx)
require.NoError(t, err)
// Marshalling/unmarshalling the tx should work.
marshaledTx, err := legacyCdc.MarshalJSON(tx)
require.NoError(t, err)
require.Equal(t, string(marshaledTx), txSigned)
// Marshalling/unmarshalling the tx wrapped in a struct should work.
txRequest := &rest.BroadcastReq{
Mode: "block",
Tx: tx,
}
_, err = legacyCdc.MarshalJSON(txRequest)
require.NoError(t, err)
}

View File

@ -1,44 +0,0 @@
package codec
import (
"fmt"
"github.com/gogo/protobuf/proto"
"github.com/cosmos/cosmos-sdk/codec/types"
)
// MarshalAny is a convenience function for packing the provided value in an
// Any and then proto marshaling it to bytes
func MarshalAny(m BinaryMarshaler, x interface{}) ([]byte, error) {
msg, ok := x.(proto.Message)
if !ok {
return nil, fmt.Errorf("can't proto marshal %T", x)
}
any := &types.Any{}
err := any.Pack(msg)
if err != nil {
return nil, err
}
return m.MarshalBinaryBare(any)
}
// UnmarshalAny is a convenience function for proto unmarshaling an Any from
// bz and then unpacking it to the interface pointer passed in as iface using
// the provided AnyUnpacker or returning an error
//
// Ex:
// var x MyInterface
// err := UnmarshalAny(unpacker, &x, bz)
func UnmarshalAny(m BinaryMarshaler, iface interface{}, bz []byte) error {
any := &types.Any{}
err := m.UnmarshalBinaryBare(bz, any)
if err != nil {
return err
}
return m.UnpackAny(any, iface)
}

View File

@ -1,7 +1,6 @@
package codec_test
import (
"errors"
"testing"
"github.com/stretchr/testify/require"
@ -28,38 +27,29 @@ func TestMarshalAny(t *testing.T) {
cdc := codec.NewProtoCodec(registry)
kitty := &testdata.Cat{Moniker: "Kitty"}
bz, err := codec.MarshalAny(cdc, kitty)
bz, err := cdc.MarshalInterface(kitty)
require.NoError(t, err)
var animal testdata.Animal
// empty registry should fail
err = codec.UnmarshalAny(cdc, &animal, bz)
err = cdc.UnmarshalInterface(bz, &animal)
require.Error(t, err)
// wrong type registration should fail
registry.RegisterImplementations((*testdata.Animal)(nil), &testdata.Dog{})
err = codec.UnmarshalAny(cdc, &animal, bz)
err = cdc.UnmarshalInterface(bz, &animal)
require.Error(t, err)
// should pass
registry = NewTestInterfaceRegistry()
cdc = codec.NewProtoCodec(registry)
err = codec.UnmarshalAny(cdc, &animal, bz)
err = cdc.UnmarshalInterface(bz, &animal)
require.NoError(t, err)
require.Equal(t, kitty, animal)
// nil should fail
registry = NewTestInterfaceRegistry()
err = codec.UnmarshalAny(cdc, nil, bz)
err = cdc.UnmarshalInterface(bz, nil)
require.Error(t, err)
}
func TestMarshalAnyNonProtoErrors(t *testing.T) {
registry := types.NewInterfaceRegistry()
cdc := codec.NewProtoCodec(registry)
_, err := codec.MarshalAny(cdc, 29)
require.Error(t, err)
require.Equal(t, err, errors.New("can't proto marshal int"))
}

View File

@ -32,12 +32,17 @@ type (
UnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler) error
MustUnmarshalBinaryLengthPrefixed(bz []byte, ptr ProtoMarshaler)
MarshalInterface(i proto.Message) ([]byte, error)
UnmarshalInterface(bz []byte, ptr interface{}) error
types.AnyUnpacker
}
JSONMarshaler interface {
MarshalJSON(o proto.Message) ([]byte, error)
MustMarshalJSON(o proto.Message) []byte
MarshalInterfaceJSON(i proto.Message) ([]byte, error)
UnmarshalInterfaceJSON(bz []byte, ptr interface{}) error
UnmarshalJSON(bz []byte, ptr proto.Message) error
MustUnmarshalJSON(bz []byte, ptr proto.Message)

135
codec/codec_common_test.go Normal file
View File

@ -0,0 +1,135 @@
package codec_test
import (
"testing"
"github.com/gogo/protobuf/proto"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
)
type interfaceMarshaler struct {
marshal func(i proto.Message) ([]byte, error)
unmarshal func(bz []byte, ptr interface{}) error
}
func testInterfaceMarshaling(require *require.Assertions, cdc interfaceMarshaler, isAminoBin bool) {
_, err := cdc.marshal(nil)
require.Error(err, "can't marshal a nil value")
dog := &testdata.Dog{Name: "rufus"}
var dogI testdata.Animal = dog
bz, err := cdc.marshal(dogI)
require.NoError(err)
var animal testdata.Animal
if isAminoBin {
require.PanicsWithValue("Unmarshal expects a pointer", func() {
cdc.unmarshal(bz, animal)
})
} else {
err = cdc.unmarshal(bz, animal)
require.Error(err)
require.Contains(err.Error(), "expects a pointer")
}
require.NoError(cdc.unmarshal(bz, &animal))
require.Equal(dog, animal)
// Amino doesn't wrap into Any, so it doesn't need to register self type
if isAminoBin {
var dog2 testdata.Dog
require.NoError(cdc.unmarshal(bz, &dog2))
require.Equal(*dog, dog2)
}
var cat testdata.Cat
require.Error(cdc.unmarshal(bz, &cat))
}
type mustMarshaler struct {
marshal func(i codec.ProtoMarshaler) ([]byte, error)
mustMarshal func(i codec.ProtoMarshaler) []byte
unmarshal func(bz []byte, ptr codec.ProtoMarshaler) error
mustUnmarshal func(bz []byte, ptr codec.ProtoMarshaler)
}
type testCase struct {
name string
input codec.ProtoMarshaler
recv codec.ProtoMarshaler
marshalErr bool
unmarshalErr bool
}
func testMarshalingTestCase(require *require.Assertions, tc testCase, m mustMarshaler) {
bz, err := m.marshal(tc.input)
if tc.marshalErr {
require.Error(err)
require.Panics(func() { m.mustMarshal(tc.input) })
} else {
var bz2 []byte
require.NoError(err)
require.NotPanics(func() { bz2 = m.mustMarshal(tc.input) })
require.Equal(bz, bz2)
err := m.unmarshal(bz, tc.recv)
if tc.unmarshalErr {
require.Error(err)
require.Panics(func() { m.mustUnmarshal(bz, tc.recv) })
} else {
require.NoError(err)
require.NotPanics(func() { m.mustUnmarshal(bz, tc.recv) })
require.Equal(tc.input, tc.recv)
}
}
}
func testMarshaling(t *testing.T, cdc codec.Marshaler) {
any, err := types.NewAnyWithValue(&testdata.Dog{Name: "rufus"})
require.NoError(t, err)
testCases := []testCase{
{
"valid encoding and decoding",
&testdata.Dog{Name: "rufus"},
&testdata.Dog{},
false,
false,
}, {
"invalid decode type",
&testdata.Dog{Name: "rufus"},
&testdata.Cat{},
false,
true,
}}
if _, ok := cdc.(*codec.AminoCodec); ok {
testCases = append(testCases, testCase{
"any marshaling",
&testdata.HasAnimal{Animal: any},
&testdata.HasAnimal{Animal: any},
false,
false,
})
}
for _, tc := range testCases {
tc := tc
m1 := mustMarshaler{cdc.MarshalBinaryBare, cdc.MustMarshalBinaryBare, cdc.UnmarshalBinaryBare, cdc.MustUnmarshalBinaryBare}
m2 := mustMarshaler{cdc.MarshalBinaryLengthPrefixed, cdc.MustMarshalBinaryLengthPrefixed, cdc.UnmarshalBinaryLengthPrefixed, cdc.MustUnmarshalBinaryLengthPrefixed}
m3 := mustMarshaler{
func(i codec.ProtoMarshaler) ([]byte, error) { return cdc.MarshalJSON(i) },
func(i codec.ProtoMarshaler) []byte { return cdc.MustMarshalJSON(i) },
func(bz []byte, ptr codec.ProtoMarshaler) error { return cdc.UnmarshalJSON(bz, ptr) },
func(bz []byte, ptr codec.ProtoMarshaler) { cdc.MustUnmarshalJSON(bz, ptr) }}
t.Run(tc.name+"_BinaryBare",
func(t *testing.T) { testMarshalingTestCase(require.New(t), tc, m1) })
t.Run(tc.name+"_BinaryLengthPrefixed",
func(t *testing.T) { testMarshalingTestCase(require.New(t), tc, m2) })
t.Run(tc.name+"_JSON",
func(t *testing.T) { testMarshalingTestCase(require.New(t), tc, m3) })
}
}

View File

@ -2,13 +2,14 @@ package codec
import (
"encoding/binary"
"errors"
"fmt"
"strings"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/gogo/protobuf/jsonpb"
"github.com/gogo/protobuf/proto"
"github.com/cosmos/cosmos-sdk/codec/types"
)
// ProtoCodecMarshaler defines an interface for codecs that utilize Protobuf for both
@ -160,6 +161,67 @@ func (pc *ProtoCodec) MustUnmarshalJSON(bz []byte, ptr proto.Message) {
}
}
// MarshalInterface is a convenience function for proto marshalling interfaces. It packs
// the provided value, which must be an interface, in an Any and then marshals it to bytes.
// NOTE: to marshal a concrete type, you should use MarshalBinaryBare instead
func (pc *ProtoCodec) MarshalInterface(i proto.Message) ([]byte, error) {
if err := assertNotNil(i); err != nil {
return nil, err
}
any, err := types.NewAnyWithValue(i)
if err != nil {
return nil, err
}
return pc.MarshalBinaryBare(any)
}
// UnmarshalInterface is a convenience function for proto unmarshaling interfaces. It
// unmarshals an Any from bz bytes and then unpacks it to the `ptr`, which must
// be a pointer to a non empty interface with registered implementations.
// NOTE: to unmarshal a concrete type, you should use UnmarshalBinaryBare instead
//
// Example:
// var x MyInterface
// err := cdc.UnmarshalInterface(bz, &x)
func (pc *ProtoCodec) UnmarshalInterface(bz []byte, ptr interface{}) error {
any := &types.Any{}
err := pc.UnmarshalBinaryBare(bz, any)
if err != nil {
return err
}
return pc.UnpackAny(any, ptr)
}
// MarshalInterfaceJSON is a convenience function for proto marshalling interfaces. It
// packs the provided value in an Any and then marshals it to bytes.
// NOTE: to marshal a concrete type, you should use MarshalJSON instead
func (pc *ProtoCodec) MarshalInterfaceJSON(x proto.Message) ([]byte, error) {
any, err := types.NewAnyWithValue(x)
if err != nil {
return nil, err
}
return pc.MarshalJSON(any)
}
// UnmarshalInterfaceJSON is a convenience function for proto unmarshaling interfaces.
// It unmarshals an Any from bz bytes and then unpacks it to the `iface`, which must
// be a pointer to a non empty interface, implementing proto.Message with registered implementations.
// NOTE: to unmarshal a concrete type, you should use UnmarshalJSON instead
//
// Example:
// var x MyInterface // must implement proto.Message
// err := cdc.UnmarshalInterfaceJSON(&x, bz)
func (pc *ProtoCodec) UnmarshalInterfaceJSON(bz []byte, iface interface{}) error {
any := &types.Any{}
err := pc.UnmarshalJSON(bz, any)
if err != nil {
return err
}
return pc.UnpackAny(any, iface)
}
// UnpackAny implements AnyUnpacker.UnpackAny method,
// it unpacks the value in any to the interface pointer passed in as
// iface.
@ -170,3 +232,10 @@ func (pc *ProtoCodec) UnpackAny(any *types.Any, iface interface{}) error {
func (pc *ProtoCodec) InterfaceRegistry() types.InterfaceRegistry {
return pc.interfaceRegistry
}
func assertNotNil(i interface{}) error {
if i == nil {
return errors.New("can't marshal <nil> value")
}
return nil
}

View File

@ -24,102 +24,17 @@ func createTestInterfaceRegistry() types.InterfaceRegistry {
return interfaceRegistry
}
func TestProtoMarsharlInterface(t *testing.T) {
cdc := codec.NewProtoCodec(createTestInterfaceRegistry())
m := interfaceMarshaler{cdc.MarshalInterface, cdc.UnmarshalInterface}
testInterfaceMarshaling(require.New(t), m, false)
m = interfaceMarshaler{cdc.MarshalInterfaceJSON, cdc.UnmarshalInterfaceJSON}
testInterfaceMarshaling(require.New(t), m, false)
}
func TestProtoCodec(t *testing.T) {
testCases := []struct {
name string
codec codec.Marshaler
input codec.ProtoMarshaler
recv codec.ProtoMarshaler
marshalErr bool
unmarshalErr bool
}{
{
"valid encoding and decoding",
codec.NewProtoCodec(createTestInterfaceRegistry()),
&testdata.Dog{Name: "rufus"},
&testdata.Dog{},
false,
false,
},
{
"invalid decode type",
codec.NewProtoCodec(createTestInterfaceRegistry()),
&testdata.Dog{Name: "rufus"},
&testdata.Cat{},
false,
true,
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
bz, err := tc.codec.MarshalBinaryBare(tc.input)
if tc.marshalErr {
require.Error(t, err)
require.Panics(t, func() { tc.codec.MustMarshalBinaryBare(tc.input) })
} else {
var bz2 []byte
require.NoError(t, err)
require.NotPanics(t, func() { bz2 = tc.codec.MustMarshalBinaryBare(tc.input) })
require.Equal(t, bz, bz2)
err := tc.codec.UnmarshalBinaryBare(bz, tc.recv)
if tc.unmarshalErr {
require.Error(t, err)
require.Panics(t, func() { tc.codec.MustUnmarshalBinaryBare(bz, tc.recv) })
} else {
require.NoError(t, err)
require.NotPanics(t, func() { tc.codec.MustUnmarshalBinaryBare(bz, tc.recv) })
require.Equal(t, tc.input, tc.recv)
}
}
bz, err = tc.codec.MarshalBinaryLengthPrefixed(tc.input)
if tc.marshalErr {
require.Error(t, err)
require.Panics(t, func() { tc.codec.MustMarshalBinaryLengthPrefixed(tc.input) })
} else {
var bz2 []byte
require.NoError(t, err)
require.NotPanics(t, func() { bz2 = tc.codec.MustMarshalBinaryLengthPrefixed(tc.input) })
require.Equal(t, bz, bz2)
err := tc.codec.UnmarshalBinaryLengthPrefixed(bz, tc.recv)
if tc.unmarshalErr {
require.Error(t, err)
require.Panics(t, func() { tc.codec.MustUnmarshalBinaryLengthPrefixed(bz, tc.recv) })
} else {
require.NoError(t, err)
require.NotPanics(t, func() { tc.codec.MustUnmarshalBinaryLengthPrefixed(bz, tc.recv) })
require.Equal(t, tc.input, tc.recv)
}
}
bz, err = tc.codec.MarshalJSON(tc.input)
if tc.marshalErr {
require.Error(t, err)
require.Panics(t, func() { tc.codec.MustMarshalJSON(tc.input) })
} else {
var bz2 []byte
require.NoError(t, err)
require.NotPanics(t, func() { bz2 = tc.codec.MustMarshalJSON(tc.input) })
require.Equal(t, bz, bz2)
err := tc.codec.UnmarshalJSON(bz, tc.recv)
if tc.unmarshalErr {
require.Error(t, err)
require.Panics(t, func() { tc.codec.MustUnmarshalJSON(bz, tc.recv) })
} else {
require.NoError(t, err)
require.NotPanics(t, func() { tc.codec.MustUnmarshalJSON(bz, tc.recv) })
require.Equal(t, tc.input, tc.recv)
}
}
})
}
cdc := codec.NewProtoCodec(createTestInterfaceRegistry())
testMarshaling(t, cdc)
}
type lyingProtoMarshaler struct {

View File

@ -58,31 +58,24 @@ type Any struct {
// returns an error if that value couldn't be packed. This also caches
// the packed value so that it can be retrieved from GetCachedValue without
// unmarshaling
func NewAnyWithValue(value proto.Message) (*Any, error) {
any := &Any{}
err := any.Pack(value)
if err != nil {
return nil, err
func NewAnyWithValue(v proto.Message) (*Any, error) {
if v == nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrPackAny, "Expecting non nil value to create a new Any")
}
return any, nil
return NewAnyWithCustomTypeURL(v, "/"+proto.MessageName(v))
}
// Pack packs the value x in the Any or returns an error. This also caches
// the packed value so that it can be retrieved from GetCachedValue without
// unmarshaling
func (any *Any) Pack(x proto.Message) error {
any.TypeUrl = "/" + proto.MessageName(x)
bz, err := proto.Marshal(x)
if err != nil {
return err
}
any.Value = bz
any.cachedValue = x
return nil
// NewAnyWithCustomTypeURL same as NewAnyWithValue, but sets a custom type url, instead
// using the one from proto.Message.
// NOTE: This functions should be only used for types with additional logic bundled
// into the protobuf Any serialization. For simple marshaling you should use NewAnyWithValue.
func NewAnyWithCustomTypeURL(v proto.Message, typeURL string) (*Any, error) {
bz, err := proto.Marshal(v)
return &Any{
TypeUrl: typeURL,
Value: bz,
cachedValue: v,
}, err
}
// UnsafePackAny packs the value x in the Any and instead of returning the error
@ -100,21 +93,20 @@ func UnsafePackAny(x interface{}) *Any {
return &Any{cachedValue: x}
}
// PackAny is a checked and safe version of UnsafePackAny. It assures that
// `x` implements the proto.Message interface and uses it to serialize `x`.
// [DEPRECATED]: should be moved away: https://github.com/cosmos/cosmos-sdk/issues/7479
func PackAny(x interface{}) (*Any, error) {
if x == nil {
return nil, nil
// pack packs the value x in the Any or returns an error. This also caches
// the packed value so that it can be retrieved from GetCachedValue without
// unmarshaling
func (any *Any) pack(x proto.Message) error {
any.TypeUrl = "/" + proto.MessageName(x)
bz, err := proto.Marshal(x)
if err != nil {
return err
}
if intoany, ok := x.(IntoAny); ok {
return intoany.AsAny(), nil
}
protoMsg, ok := x.(proto.Message)
if !ok {
return nil, sdkerrors.Wrapf(sdkerrors.ErrInvalidType, "Expecting %T to implement proto.Message", x)
}
return NewAnyWithValue(protoMsg)
any.Value = bz
any.cachedValue = x
return nil
}
// GetCachedValue returns the cached value from the Any if present
@ -126,8 +118,3 @@ func (any *Any) GetCachedValue() interface{} {
func (any *Any) ClearCachedValue() {
any.cachedValue = nil
}
// IntoAny represents a type that can be wrapped into an Any.
type IntoAny interface {
AsAny() *Any
}

View File

@ -89,8 +89,7 @@ func (a AminoUnpacker) UnpackAny(any *Any, iface interface{}) error {
return err
}
if m, ok := val.(proto.Message); ok {
err := any.Pack(m)
if err != nil {
if err = any.pack(m); err != nil {
return err
}
} else {
@ -148,8 +147,7 @@ func (a AminoJSONUnpacker) UnpackAny(any *Any, iface interface{}) error {
return err
}
if m, ok := val.(proto.Message); ok {
err := any.Pack(m)
if err != nil {
if err = any.pack(m); err != nil {
return err
}
} else {

View File

@ -22,24 +22,19 @@ func TestPackUnpack(t *testing.T) {
registry := testdata.NewTestInterfaceRegistry()
spot := &testdata.Dog{Name: "Spot"}
any := types.Any{}
err := any.Pack(spot)
require.NoError(t, err)
require.Equal(t, spot, any.GetCachedValue())
// without cache
any.ClearCachedValue()
var animal testdata.Animal
err = registry.UnpackAny(&any, &animal)
// with cache
any, err := types.NewAnyWithValue(spot)
require.NoError(t, err)
require.Equal(t, spot, any.GetCachedValue())
err = registry.UnpackAny(any, &animal)
require.NoError(t, err)
require.Equal(t, spot, animal)
// with cache
err = any.Pack(spot)
require.Equal(t, spot, any.GetCachedValue())
require.NoError(t, err)
err = registry.UnpackAny(&any, &animal)
// without cache
any.ClearCachedValue()
err = registry.UnpackAny(any, &animal)
require.NoError(t, err)
require.Equal(t, spot, animal)
}

View File

@ -25,7 +25,7 @@ f_check_cmds
if [[ $STAGED_GO_FILES != "" ]]; then
f_echo_stderr "[pre-commit] fmt'ing staged files..."
for file in $STAGED_GO_FILES; do
if [[ $file =~ vendor/ ]] || [[ $file =~ client/lcd/statik/ ]] || [[ $file =~ tests/mocks/ ]] || [[ $file =~ \.pb\.go ]]; then
if [[ $file =~ vendor/ ]] || [[ $file =~ client/docs/statik/ ]] || [[ $file =~ tests/mocks/ ]] || [[ $file =~ \.pb\.go ]]; then
continue
fi

View File

@ -37,6 +37,16 @@ module.exports = {
key: "ac317234e6a42074175369b2f42e9754",
index: "cosmos-sdk"
},
versions: [
{
"label": "v0.39",
"key": "v0.39"
},
{
"label": "master",
"key": "master"
}
],
topbar: {
banner: true
},

View File

@ -48,7 +48,7 @@ aside: false
## Get Started
- **[SDK Intro](./intro/overview.md)**: High-level overview of the Cosmos SDK.
- **[Quick Start Guide](./using-the-sdk/quick-start.md)**: Scaffold a standard Cosmos SDK app and run a node.
- **[Quick Start Guide](./using-the-sdk/quick-start.md)**: Scaffold a standard Cosmos SDK app and run a node.
- **[SDK Application Tutorial](https://github.com/cosmos/sdk-application-tutorial)**: A tutorial that showcases how to build an SDK-based blockchain from scratch and explains the basic principles of the SDK in the process.
## Reference
@ -56,7 +56,9 @@ aside: false
- **[Basics](./basics/)**: Documentation on the basic concepts of the Cosmos SDK, like the standard anatomy of an application, the transaction lifecycle and accounts management.
- **[Core](./core/)**: Documentation on the core concepts of the Cosmos SDK, like `baseapp`, the `store` or the `server`.
- **[Building Modules](./building-modules/)**: Important concepts for module developers like `message`s, `keeper`s, `handler`s and `querier`s.
- **[Interfaces](./interfaces/)**: Documentation on building interfaces for Cosmos SDK applications.
- **[IBC](./ibc/)**: Documentation for the IBC protocol integration and concepts.
- **[Running a Node, API, CLI](./run-node/)**: Documentation on how to run a node, and how to interact with it using the CLI and the API.
- **[Migrations](./migrations/)**: Migration guides for updating to Stargate.
## Other Resources

View File

@ -6,6 +6,7 @@
- 2020 Feb 24: Updates to handle messages with interface fields
- 2020 Apr 27: Convert usages of `oneof` for interfaces to `Any`
- 2020 May 15: Describe `cosmos_proto` extensions and amino compatibility
- 2020 Dec 4: Move and rename `MarshalAny` and `UnmarshalAny` into the `codec.Marshaler` interface.
## Status
@ -221,23 +222,20 @@ every module that implements it in order to populate the `InterfaceRegistry`.
### Using `Any` to encode state
The SDK will provide support methods `MarshalAny` and `UnmarshalAny` to allow
easy encoding of state to `Any` in `Codec` implementations. Ex:
The SDK will provide support methods `MarshalInterface` and `UnmarshalInterface` to hide a complexity of wrapping interface types into `Any` and allow easy serialization.
```go
import "github.com/cosmos/cosmos-sdk/codec"
func (c *Codec) MarshalEvidence(evidenceI eviexported.Evidence) ([]byte, error) {
return codec.MarshalAny(evidenceI)
// note: eviexported.Evidence is an interface type
func MarshalEvidence(cdc codec.BinaryMarshaler, e eviexported.Evidence) ([]byte, error) {
return cdc.MarshalInterface(e)
}
func (c *Codec) UnmarshalEvidence(bz []byte) (eviexported.Evidence, error) {
func UnmarshalEvidence(cdc codec.BinaryMarshaler, bz []byte) (eviexported.Evidence, error) {
var evi eviexported.Evidence
err := codec.UnmarshalAny(c.interfaceContext, &evi, bz)
if err != nil {
return nil, err
}
return evi, nil
err := cdc.UnmarshalInterface(&evi, bz)
return err, nil
}
```
@ -375,4 +373,3 @@ seamless.
1. https://github.com/cosmos/cosmos-sdk/issues/4977
2. https://github.com/cosmos/cosmos-sdk/issues/5444

View File

@ -53,6 +53,12 @@
{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.

View File

@ -113,17 +113,19 @@ The `EncodingConfig` structure is the last important part of the `app.go` file.
Here are descriptions of what each of the four fields means:
- `InterfaceRegistry`: The `InterfaceRegistry` is used by the Protobuf codec to handle interfaces, which are encoded and decoded (we also say "unpacked") using [`google.protobuf.Any`](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/any.proto). `Any` could be thought as a struct which contains a `type_url` (the concrete type of the interface) and a `value` (its encoded bytes). `InterfaceRegistry` provides a mechanism for registering interfaces and implementations that can be safely unpacked from `Any`. Each of the application's modules implements the `RegisterInterfaces` method, which can be used to register the module's own interfaces and implementations.
- `InterfaceRegistry`: The `InterfaceRegistry` is used by the Protobuf codec to handle interfaces, which are encoded and decoded (we also say "unpacked") using [`google.protobuf.Any`](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/any.proto). `Any` could be thought as a struct which contains a `type_url` (name of a concrete type implementing the interface) and a `value` (its encoded bytes). `InterfaceRegistry` provides a mechanism for registering interfaces and implementations that can be safely unpacked from `Any`. Each of the application's modules implements the `RegisterInterfaces` method, which can be used to register the module's own interfaces and implementations.
- You can read more about Any in [ADR-19](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-019-protobuf-state-encoding.md#usage-of-any-to-encode-interfaces).
- To go more into details, the SDK uses an implementation of the Protobuf specification called [`gogoprotobuf`](https://github.com/gogo/protobuf). By default, the [gogo protobuf implementation of `Any`](https://godoc.org/github.com/gogo/protobuf/types) uses [global type registration](https://github.com/gogo/protobuf/blob/master/proto/properties.go#L540) to decode values packed in `Any` into concrete Go types. This introduces a vulnerability where any malicious module in the dependency tree could registry a type with the global protobuf registry and cause it to be loaded and unmarshaled by a transaction that referenced it in the `type_url` field. For more information, please refer to [ADR-019](../architecture/adr-019-protobuf-state-encoding.md).
- `Marshaler`: The `Marshaler` is the default codec used throughout the SDK. It is composed of a `BinaryMarshaler` used to encode and decode state, and a `JSONMarshaler` used to output data to the users (for example in the [CLI](#cli)). By default, the SDK uses Protobuf as `Marshaler`.
- `Marshaler`: the default codec used throughout the SDK. It is composed of a `BinaryMarshaler` used to encode and decode state, and a `JSONMarshaler` used to output data to the users (for example in the [CLI](#cli)). By default, the SDK uses Protobuf as `Marshaler`.
- `TxConfig`: `TxConfig` defines an interface a client can utilize to generate an application-defined concrete transaction type. Currently, the SDK handles two transaction types: `SIGN_MODE_DIRECT` (which uses Protobuf binary as over-the-wire encoding) and `SIGN_MODE_LEGACY_AMINO_JSON` (which depends on Amino). Read more about transactions [here](../core/transactions.md).
- `Amino`: Some legacy parts of the SDK still use Amino for backwards-compatibility. Each module exposes a `RegisterLegacyAmino` method to register the module's specific types within Amino. This `Amino` codec should not be used by app developers anymore, and will be removed in future releases.
The SDK exposes a `MakeCodecs` function used to create a `EncodingConfig`. It uses Protobuf as default `Marshaler`, and passes it down to the app's `appCodec` field. It also instantiates a legacy `Amino` codec inside the app's `legacyAmino` field.
The SDK exposes a `MakeTestEncodingConfig` function used to create a `EncodingConfig` for the app constructor (`NewApp`). It uses Protobuf as a default `Marshaler`.
NOTE: this function is marked deprecated and should only be used to create an app or in tests. We are working on refactoring codec management in a post Stargate release.
See an example of a `MakeCodecs` from `simapp`:
See an example of a `MakeTestEncodingConfig` from `simapp`:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/simapp/app.go#L429-L435
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/simapp/simd/cmd/root.go#L179-196
## Modules

View File

@ -56,7 +56,7 @@ This query returns the account at a given address. The getter function does the
- The function should first initialize a new client [`Context`](../interfaces/query-lifecycle.md#context) as described in the [previous section](#transaction-commands)
- If applicable, the `Context` is used to retrieve any parameters (e.g. the query originator's address to be used in the query) and marshal them with the query parameter type, in preparation to be relayed to a node. There are no `Context` parameters in this case because the query does not involve any information about the user.
- A new `queryClient` should be initialized using `NewQueryClient(clientCtx)`, this method being generated from `query.proto`. Then it can be used to call the appropriate [query](./messages-and-queries.md#grpc-queries).
- The `clientCtx.PrintOutput` method is used to print the output back to the user.
- The `clientCtx.PrintProto` method is used to format a `proto.Message` object and print it back to the user.
- **Flags.** Add any [flags](#flags) to the command.
Finally, the module also needs a `GetQueryCmd`, which aggregates all of the query commands of the module. Application developers wishing to include the module's queries will call this function to add them as subcommands in their CLI. Its structure is identical to the `GetTxCmd` command shown above.

View File

@ -67,7 +67,7 @@ Here is the typical structure of a `handler` function:
Let us break it down:
- The [`Msg`](./messages-and-queries.md#messages) is the actual object being processed.
- The [`Context`](../core/context.md) contains all the necessary information needed to process the `msg`, as well as a cache-wrapped copy of the latest state. If the `msg` is succesfully processed, the modified version of the temporary state contained in the `ctx` will be written to the main state.
- The [`Context`](../core/context.md) contains all the necessary information needed to process the `msg`, as well as a branch of the latest state. If the `msg` is successfully processed, the branched version of the state contained in the `ctx` will be written to the main state (branch).
- The [`*Result`] returned to `BaseApp` contains (among other things) information on the execution of the `handler` and [events](../core/events.md).
Module `handler`s are typically implemented in a `./handler.go` file inside the module's folder. The [module manager](./module-manager.md) is used to add the module's `handler`s to the

View File

@ -21,7 +21,7 @@ Let us break it down:
- The `path` is an array of `string`s that contains the type of the query, and that can also contain `query` arguments. See [`queries`](./messages-and-queries.md#queries) for more information.
- The `req` itself is primarily used to retrieve arguments if they are too large to fit in the `path`. This is done using the `Data` field of `req`.
- The [`Context`](../core/context.md) contains all the necessary information needed to process the `query`, as well as a cache-wrapped copy of the latest state. It is primarily used by the [`keeper`](./keeper.md) to access the state.
- The [`Context`](../core/context.md) contains all the necessary information needed to process the `query`, as well as a branch of the latest state. It is primarily used by the [`keeper`](./keeper.md) to access the state.
- The result `res` returned to `BaseApp`, marshalled using the application's [`codec`](../core/encoding.md).
## Implementation of a module query service

View File

@ -14,10 +14,12 @@ This repository contains reference documentation on the core concepts of the Cos
4. [Node Client](./node.md)
5. [Store](./store.md)
6. [Encoding](./encoding.md)
7. [Events](./events.md)
8. [Telemetry](./telemetry.md)
9. [Object-Capabilities](./ocap.md)
10. [RunTx recovery middleware](./runtx_middleware.md)
7. [gRPC, REST and Tendermint Endpoints](./grpc_rest.md)
8. [Events](./events.md)
9. [Telemetry](./telemetry.md)
10. [Object-Capabilities](./ocap.md)
11. [RunTx recovery middleware](./runtx_middleware.md)
12. [Protobuf documentation](./proto-docs.md)
After reading about the core concepts, check the [IBC documentation](../ibc/README.md) to learn more
about the IBC core concepts and how to integrate it to you application.

View File

@ -126,15 +126,16 @@ is the canonical state of the application and the volatile states, `checkState`
are used to handle state transitions in-between the main state made during [`Commit`](#commit).
Internally, there is only a single `CommitMultiStore` which we refer to as the main or root state.
From this root state, we derive two volatile state through a mechanism called cache-wrapping. The
types can be illustrated as follows:
From this root state, we derive two volatile state through a mechanism called _store branching_ (performed by `CacheWrap` function).
The types can be illustrated as follows:
![Types](./baseapp_state_types.png)
### InitChain State Updates
During `InitChain`, the two volatile states, `checkState` and `deliverState` are set by cache-wrapping
the root `CommitMultiStore`. Any subsequent reads and writes happen on cached versions of the `CommitMultiStore`.
During `InitChain`, the two volatile states, `checkState` and `deliverState` are set by branching
the root `CommitMultiStore`. Any subsequent reads and writes happen on branched versions of the `CommitMultiStore`.
To avoid unnecessary roundtrip to the main state, all reads to the branched store are cached.
![InitChain](./baseapp_state-initchain.png)
@ -142,8 +143,8 @@ the root `CommitMultiStore`. Any subsequent reads and writes happen on cached ve
During `CheckTx`, the `checkState`, which is based off of the last committed state from the root
store, is used for any reads and writes. Here we only execute the `AnteHandler` and verify a service router
exists for every message in the transaction. Note, when we execute the `AnteHandler`, we cache-wrap
the already cache-wrapped `checkState`. This has the side effect that if the `AnteHandler` fails,
exists for every message in the transaction. Note, when we execute the `AnteHandler`, we branch
the already branched `checkState`. This has the side effect that if the `AnteHandler` fails,
the state transitions won't be reflected in the `checkState` -- i.e. `checkState` is only updated on
success.
@ -152,7 +153,7 @@ success.
### BeginBlock State Updates
During `BeginBlock`, the `deliverState` is set for use in subsequent `DeliverTx` ABCI messages. The
`deliverState` is based off of the last committed state from the root store and is cache-wrapped.
`deliverState` is based off of the last committed state from the root store and is branched.
Note, the `deliverState` is set to `nil` on [`Commit`](#commit).
![BeginBlock](./baseapp_state-begin_block.png)
@ -161,7 +162,7 @@ Note, the `deliverState` is set to `nil` on [`Commit`](#commit).
The state flow for `DeliverTx` is nearly identical to `CheckTx` except state transitions occur on
the `deliverState` and messages in a transaction are executed. Similarly to `CheckTx`, state transitions
occur on a doubly cache-wrapped state -- `deliverState`. Successful message execution results in
occur on a doubly branched state -- `deliverState`. Successful message execution results in
writes being committed to `deliverState`. Note, if message execution fails, state transitions from
the AnteHandler are persisted.
@ -283,7 +284,7 @@ Before the first transaction of a given block is processed, a [volatile state](#
`DeliverTx` performs the **exact same steps as `CheckTx`**, with a little caveat at step 3 and the addition of a fifth step:
1. The `AnteHandler` does **not** check that the transaction's `gas-prices` is sufficient. That is because the `min-gas-prices` value `gas-prices` is checked against is local to the node, and therefore what is enough for one full-node might not be for another. This means that the proposer can potentially include transactions for free, although they are not incentivised to do so, as they earn a bonus on the total fee of the block they propose.
2. For each `Msg` in the transaction, route to the appropriate module's [`Msg` service](../building-modules/msg-services.md). Additional _stateful_ checks are performed, and the cache-wrapped multistore held in `deliverState`'s `context` is updated by the module's `keeper`. If the `Msg` service returns successfully, the cache-wrapped multistore held in `context` is written to `deliverState` `CacheMultiStore`.
2. For each `Msg` in the transaction, route to the appropriate module's [`Msg` service](../building-modules/msg-services.md). Additional _stateful_ checks are performed, and the branched multistore held in `deliverState`'s `context` is updated by the module's `keeper`. If the `Msg` service returns successfully, the branched multistore held in `context` is written to `deliverState` `CacheMultiStore`.
During step 5., each read/write to the store increases the value of `GasConsumed`. You can find the default cost of each operation:
@ -308,17 +309,17 @@ At any point, if `GasConsumed > GasWanted`, the function returns with `Code != 0
`RunTx` is called from `CheckTx`/`DeliverTx` to handle the transaction, with `runTxModeCheck` or `runTxModeDeliver` as parameter to differentiate between the two modes of execution. Note that when `RunTx` receives a transaction, it has already been decoded.
The first thing `RunTx` does upon being called is to retrieve the `context`'s `CacheMultiStore` by calling the `getContextForTx()` function with the appropriate mode (either `runTxModeCheck` or `runTxModeDeliver`). This `CacheMultiStore` is a cached version of the main store instantiated during `BeginBlock` for `DeliverTx` and during the `Commit` of the previous block for `CheckTx`. After that, two `defer func()` are called for [`gas`](../basics/gas-fees.md) management. They are executed when `runTx` returns and make sure `gas` is actually consumed, and will throw errors, if any.
The first thing `RunTx` does upon being called is to retrieve the `context`'s `CacheMultiStore` by calling the `getContextForTx()` function with the appropriate mode (either `runTxModeCheck` or `runTxModeDeliver`). This `CacheMultiStore` is a branch of the main store, with cache functionality (for query requests), instantiated during `BeginBlock` for `DeliverTx` and during the `Commit` of the previous block for `CheckTx`. After that, two `defer func()` are called for [`gas`](../basics/gas-fees.md) management. They are executed when `runTx` returns and make sure `gas` is actually consumed, and will throw errors, if any.
After that, `RunTx()` calls `ValidateBasic()` on each `Msg`in the `Tx`, which runs preliminary _stateless_ validity checks. If any `Msg` fails to pass `ValidateBasic()`, `RunTx()` returns with an error.
Then, the [`anteHandler`](#antehandler) of the application is run (if it exists). In preparation of this step, both the `checkState`/`deliverState`'s `context` and `context`'s `CacheMultiStore` are cached-wrapped using the `cacheTxContext()` function.
Then, the [`anteHandler`](#antehandler) of the application is run (if it exists). In preparation of this step, both the `checkState`/`deliverState`'s `context` and `context`'s `CacheMultiStore` are branched using the `cacheTxContext()` function.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/baseapp/baseapp.go#L623-L630
This allows `RunTx` not to commit the changes made to the state during the execution of `anteHandler` if it ends up failing. It also prevents the module implementing the `anteHandler` from writing to state, which is an important part of the [object-capabilities](./ocap.md) of the Cosmos SDK.
Finally, the [`RunMsgs()`](#runmsgs) function is called to process the `Msg`s in the `Tx`. In preparation of this step, just like with the `anteHandler`, both the `checkState`/`deliverState`'s `context` and `context`'s `CacheMultiStore` are cached-wrapped using the `cacheTxContext()` function.
Finally, the [`RunMsgs()`](#runmsgs) function is called to process the `Msg`s in the `Tx`. In preparation of this step, just like with the `anteHandler`, both the `checkState`/`deliverState`'s `context` and `context`'s `CacheMultiStore` are branched using the `cacheTxContext()` function.
### AnteHandler
@ -373,7 +374,7 @@ The [`EndBlock` ABCI message](#https://tendermint.com/docs/app-dev/abci-spec.htm
The [`Commit` ABCI message](https://tendermint.com/docs/app-dev/abci-spec.html#commit) is sent from the underlying Tendermint engine after the full-node has received _precommits_ from 2/3+ of validators (weighted by voting power). On the `BaseApp` end, the `Commit(res abci.ResponseCommit)` function is implemented to commit all the valid state transitions that occured during `BeginBlock`, `DeliverTx` and `EndBlock` and to reset state for the next block.
To commit state-transitions, the `Commit` function calls the `Write()` function on `deliverState.ms`, where `deliverState.ms` is a cached multistore of the main store `app.cms`. Then, the `Commit` function sets `checkState` to the latest header (obtbained from `deliverState.ctx.BlockHeader`) and `deliverState` to `nil`.
To commit state-transitions, the `Commit` function calls the `Write()` function on `deliverState.ms`, where `deliverState.ms` is a branched multistore of the main store `app.cms`. Then, the `Commit` function sets `checkState` to the latest header (obtbained from `deliverState.ctx.BlockHeader`) and `deliverState` to `nil`.
Finally, `Commit` returns the hash of the commitment of `app.cms` back to the underlying consensus engine. This hash is used as a reference in the header of the next block.
@ -390,7 +391,7 @@ Each Tendermint `query` comes with a `path`, which is a `string` which denotes w
- Application-related queries like querying the application's version, which are served via the `handleQueryApp` method.
- Direct queries to the multistore, which are served by the `handlerQueryStore` method. These direct queryeis are different from custom queries which go through `app.queryRouter`, and are mainly used by third-party service provider like block explorers.
- P2P queries, which are served via the `handleQueryP2P` method. These queries return either `app.addrPeerFilter` or `app.ipPeerFilter` that contain the list of peers filtered by address or IP respectively. These lists are first initialized via `options` in `BaseApp`'s [constructor](#constructor).
- Custom queries, which encompass legacy queries (before the introduction of gRPC queries), are served via the `handleQueryCustom` method. The `handleQueryCustom` cache-wraps the multistore before using the `queryRoute` obtained from `app.queryRouter` to map the query to the appropriate module's [legacy `querier`](../building-modules/query-services.md#legacy-queriers).
- Custom queries, which encompass legacy queries (before the introduction of gRPC queries), are served via the `handleQueryCustom` method. The `handleQueryCustom` branches the multistore before using the `queryRoute` obtained from `app.queryRouter` to map the query to the appropriate module's [legacy `querier`](../building-modules/query-services.md#legacy-queriers).
## Next {hide}

View File

@ -4,7 +4,7 @@ order: 3
# Context
The `context` is a data structure intended to be passed from function to function that carries information about the current state of the application. It holds a cached copy of the entire state as well as useful objects and information like `gasMeter`, `block height`, `consensus parameters` and more. {synopsis}
The `context` is a data structure intended to be passed from function to function that carries information about the current state of the application. It provides an access to a branched storage (a safe branch of the entire state) as well as useful objects and information like `gasMeter`, `block height`, `consensus parameters` and more. {synopsis}
## Pre-requisites Readings
@ -54,21 +54,23 @@ childCtx = parentCtx.WithBlockHeader(header)
The [Golang Context Package](https://golang.org/pkg/context) documentation instructs developers to
explicitly pass a context `ctx` as the first argument of a process.
## Cache Wrapping
## Store branching
The `Context` contains a `MultiStore`, which allows for cache-wrapping functionality: a `CacheMultiStore`
where each `KVStore` is is wrapped with an ephemeral cache. Processes are free to write changes to
the `CacheMultiStore`, then write the changes back to the original state or disregard them if something
The `Context` contains a `MultiStore`, which allows for branchinig and caching functionality using `CacheMultiStore`
(queries in `CacheMultiStore` are cached to avoid future round trips).
Each `KVStore` is branched in a safe and isolated ephemeral storage. Processes are free to write changes to
the `CacheMultiStore`. If a state-transition sequence is performed without issue, the store branch can
be committed to the underlying store at the end of the sequence or disregard them if something
goes wrong. The pattern of usage for a Context is as follows:
1. A process receives a Context `ctx` from its parent process, which provides information needed to
perform the process.
2. The `ctx.ms` is **cache wrapped**, i.e. a cached copy of the [multistore](./store.md#multistore) is made so that the process can make changes to the state as it executes, without changing the original`ctx.ms`. This is useful to protect the underlying multistore in case the changes need to be reverted at some point in the execution.
2. The `ctx.ms` is a **branched store**, i.e. a branch of the [multistore](./store.md#multistore) is made so that the process can make changes to the state as it executes, without changing the original`ctx.ms`. This is useful to protect the underlying multistore in case the changes need to be reverted at some point in the execution.
3. The process may read and write from `ctx` as it is executing. It may call a subprocess and pass
`ctx` to it as needed.
4. When a subprocess returns, it checks if the result is a success or failure. If a failure, nothing
needs to be done - the cache wrapped `ctx` is simply discarded. If successful, the changes made to
the cache-wrapped `MultiStore` can be committed to the original `ctx.ms` via `Write()`.
needs to be done - the branch `ctx` is simply discarded. If successful, the changes made to
the `CacheMultiStore` can be committed to the original `ctx.ms` via `Write()`.
For example, here is a snippet from the [`runTx`](./baseapp.md#runtx-and-runmsgs) function in
[`baseapp`](./baseapp.md):
@ -90,12 +92,12 @@ if result.IsOK() {
Here is the process:
1. Prior to calling `runMsgs` on the message(s) in the transaction, it uses `app.cacheTxContext()`
to cache-wrap the context and multistore.
2. The cache-wrapped context, `runMsgCtx`, is used in `runMsgs` to return a result.
to branch and cache the context and multistore.
2. `runMsgCtx` - the context with branched store, is used in `runMsgs` to return a result.
3. If the process is running in [`checkTxMode`](./baseapp.md#checktx), there is no need to write the
changes - the result is returned immediately.
4. If the process is running in [`deliverTxMode`](./baseapp.md#delivertx) and the result indicates
a successful run over all the messages, the cached multistore is written back to the original.
a successful run over all the messages, the branched multistore is written back to the original.
## Next {hide}

View File

@ -78,11 +78,12 @@ Modules are encouraged to utilize Protobuf encoding for their respective types.
**Defining module types**
Protobuf types can be defined to encode:
- state
- [`Msg`s](../building-modules/messages-and-queries.md#messages)
- [Query services](../building-modules/query-services.md)
- [genesis](../building-modules/genesis.md)
- state
- [`Msg`s](../building-modules/messages-and-queries.md#messages)
- [Query services](../building-modules/query-services.md)
- [genesis](../building-modules/genesis.md)
**Naming and conventions**
We encourage developers to follow industry guidelines: [Protocol Buffers style guide](https://developers.google.com/protocol-buffers/docs/style)
@ -95,11 +96,9 @@ may simply migrate any existing types that
are encoded and persisted via their concrete Amino codec to Protobuf (see 1. for further guidelines) and accept a `Marshaler` as the codec which is implemented via the `ProtoCodec`
without any further customization.
However, if modules are to handle type interfaces, module-level .proto files should define messages which encode interfaces
using [`google.protobuf.Any`](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/any.proto).
However, if a module type composes an interface, it must wrap it in the `skd.Any` (from `/types` package) type. To do that, a module-level .proto file must use [`google.protobuf.Any`](https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/any.proto) for respective message type interface types.
For example, we can define `MsgSubmitEvidence` as follows where `Evidence` is
an interface:
For example, in the `x/evidence` module defines an `Evidence` interface, which is used by the `MsgSubmitEvidence`. The structure definition must use `sdk.Any` to wrap the evidence file. In the proto file we define it as follows:
```protobuf
// proto/cosmos/evidence/v1beta1/tx.proto
@ -110,12 +109,11 @@ message MsgSubmitEvidence {
}
```
The SDK provides support methods `MarshalAny` and `UnmarshalAny` to allow
easy encoding of state to `Any`.
The SDK `codec.Marshaler` interface provides support methods `MarshalInterface` and `UnmarshalInterface` to easy encoding of state to `Any`.
Module should register interfaces using `InterfaceRegistry` which provides a mechanism for registering interfaces: `RegisterInterface(protoName string, iface interface{})` and implementations: `RegisterImplementations(iface interface{}, impls ...proto.Message)` that can be safely unpacked from Any, similarly to type registration with Amino:
+++ https://github.com/cosmos/cosmos-sdk/blob/3d969a1ffdf9a80f9ee16db9c16b8a8aa1004af6/codec/types/interface_registry.go#L23-L52
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc4/codec/types/interface_registry.go#L25-L66
In addition, an `UnpackInterfaces` phase should be introduced to deserialization to unpack interfaces before they're needed. Protobuf types that contain a protobuf `Any` either directly or via one of their members should implement the `UnpackInterfacesMessage` interface:
@ -128,10 +126,11 @@ type UnpackInterfacesMessage interface {
#### Guidelines for protobuf message definitions
In addition to [following official guidelines](https://developers.google.com/protocol-buffers/docs/proto3#simple), we recommend to use these annotations in .proto files when dealing with interfaces:
* 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`
using the same full-qualified name passed as `protoName` to `InterfaceRegistry.RegisterInterface`
- 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`
using the same full-qualified name passed as `protoName` to `InterfaceRegistry.RegisterInterface`
#### Transaction Encoding
@ -142,14 +141,14 @@ other peers. Since the underlying consensus engine is agnostic to the applicatio
it only accepts transactions in the form of raw bytes. The encoding is done by an
object called `TxEncoder` and the decoding by an object called `TxDecoder`.
+++ https://github.com/cosmos/cosmos-sdk/blob/9ae17669d6715a84c20d52e10e2232be9f467360/types/tx_msg.go#L82-L86
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc4/types/tx_msg.go#L83-L87
A standard implementation of both these objects can be found in the [`auth` module](https://github.com/cosmos/cosmos-sdk/blob/master/x/auth):
+++ https://github.com/cosmos/cosmos-sdk/blob/9ae17669d6715a84c20d52e10e2232be9f467360/x/auth/tx/decoder.go
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc4/x/auth/tx/decoder.go
+++ https://github.com/cosmos/cosmos-sdk/blob/9ae17669d6715a84c20d52e10e2232be9f467360/x/auth/tx/encoder.go
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc4/x/auth/tx/encoder.go
## Next {hide}
Learn about [events](./events.md) {hide}
Learn about [gRPC, REST and other endpoints](./grpc_rest.md) {hide}

View File

@ -1,5 +1,5 @@
<!--
order: 7
order: 8
-->
# Events

101
docs/core/grpc_rest.md Normal file
View File

@ -0,0 +1,101 @@
<!--
order: 7
-->
# gRPC, REST, and Tendermint Endpoints
This document presents an overview of all the endpoints a node exposes: gRPC, REST as well as some other endpoints. {synopsis}
## An Overview of All Endpoints
Each node exposes the following endpoints for users to interact with a node, each endpoint is served on a different port. Details on how to configure each endpoint is provided in the endpoint's own section.
- the gRPC server (default port: `9090`),
- the REST server (default port: `1317`),
- the Tendermint RPC endpoint (default port: `26657`).
::: tip
The node also exposes some other endpoints, such as the Tendermint P2P endpoint, or the [Prometheus endpoint](https://docs.tendermint.com/master/nodes/metrics.html#metrics), which are not directly related to the Cosmos SDK. Please refer to the [Tendermint documentation](https://docs.tendermint.com/master/tendermint-core/using-tendermint.html#configuration) for more information about these endpoints.
:::
## gRPC Server
Cosmos SDK v0.40 introduced Protobuf as the main [encoding](./encoding) library, and this brings a wide range of Protobuf-based tools that can be plugged into the SDK. One such tool is [gRPC](https://grpc.io), a modern open source high performance RPC framework that has decent client support in several languages.
Each module exposes [`Msg` and `Query` Protobuf services](../building-modules/messages-and-queries.md) to define state transitions and state queries. These services are hooked up to gRPC via the following function inside the application:
https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc4/server/types/app.go#L39-L41
The `grpc.Server` is a concrete gRPC server, which spawns and serves any gRPC requests. This server can be configured inside `$TMHOME/config/app.toml`:
- `grpc.enable = true|false` field defines if the gRPC server should be enabled. Defaults to `true`.
- `grpc.address = {string}` field defines the address (really, the port, since the host should be kept at `0.0.0.0`) the server should bind to. Defaults to `0.0.0.0:9000`.
::tip
`$TMHOME` is the directory where the node's configuration and databases are stored. By default, it's set to `~/.{app_name}`.
::
Once the gRPC server is started, you can send requests to it using a gRPC client. Some examples are given in our [Interact with the Node](../run-node/interact-node.md#using-grpc) tutorial.
An overview of all available gRPC endpoints shipped with the Cosmos SDK is [Protobuf documention](./proto-docs.md).
## REST Server
In Cosmos SDK v0.40, the node continues to serve a REST server. However, the existing routes present in version v0.39 and earlier are now marked as deprecated, and new routes have been added via gRPC-gateway.
All routes are configured under the following fields in `$TMHOME/config/app.toml`:
- `api.enable = true|false` field defines if the REST server should be enabled. Defaults to `true`.
- `api.address = {string}` field defines the address (really, the port, since the host should be kept at `0.0.0.0`) the server should bind to. Defaults to `tcp://0.0.0.0:1317`.
- some additional API configuration options are defined in `$TMHOME/config/app.toml`, along with comments, please refer to that file directly.
### gRPC-gateway REST Routes
If, for various reasons, you cannot use gRPC (for example, you are building a web application, and browsers don't support HTTP2 on which gRPC is built), then the SDK offers REST routes via gRPC-gateway.
[gRPC-gateway](https://grpc-ecosystem.github.io/grpc-gateway/) is a tool to expose gRPC endpoints as REST endpoints. For each RPC endpoint defined in a Protobuf service, the SDK offers a REST equivalent. For instance, querying a balance could be done via the `/cosmos.bank.v1beta1.Query/AllBalances` gRPC endpoint, or alternatively via the gRPC-gateway `"/cosmos/bank/v1beta1/balances/{address}"` REST endpoint: both will return the same result. For each RPC method defined in a Protobuf service, the corresponding REST endpoint is defined as an option:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc4/proto/cosmos/bank/v1beta1/query.proto#L19-L22
For application developers, gRPC-gateway REST routes needs to be wired up to the REST server, this is done by calling the `RegisterGRPCGatewayRoutes` function on the ModuleManager.
### Legacy REST API Routes
The REST routes present in Cosmos SDK v0.39 and earlier are marked as deprecated via a [HTTP deprecation header](https://tools.ietf.org/id/draft-dalal-deprecation-header-01.html). They are still maintained to keep backwards compatibility, but will be removed in v0.41. For updating from Legacy REST routes to new gRPC-gateway REST routes, please refer to our [migration guide](../migrations/rest.md).
For application developers, Legacy REST API routes needs to be wired up to the REST server, this is done by calling the `RegisterRESTRoutes` function on the ModuleManager.
### Swagger
A [Swagger](https://swagger.io/) (or OpenAPIv2) specification file is exposed under the `/swagger` route on the API server. Swagger is an open specification describing the API endpoints a server serves, including description, input arguments, return types and much more about each endpoint.
Enabling the `/swagger` endpoint is configurable inside `$TMHOME/config/app.toml` via the `api.swagger` field, which is set to true by default.
For application developers, you may want to generate your own Swagger definitions based on your custom modules. The SDK's [Swagger generation script](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc4/scripts/protoc-swagger-gen.sh) is a good place to start.
## Tendermint RPC
Independently from the Cosmos SDK, Tendermint also exposes a RPC server. This RPC server can be configured by tuning parameters under the `rpc` table in the `$TMHOME/config/config.toml`, the default listening address is `tcp://0.0.0.0:26657`. An OpenAPI specification of all Tendermint RPC endpoints is available [here](https://docs.tendermint.com/master/rpc/).
Some Tendermint RPC endpoints are directly related to the Cosmos SDK:
- `/abci_query`: this endpoint will query the application for state. As the `path` parameter, you can send the following strings:
- any Protobuf fully-qualified service method, such as `/cosmos.bank.v1beta1.Query/AllBalances`. The `data` field should then include the method's request parameter(s) encoded as bytes using Protobuf.
- `/app/simulate`: this will simulate a transaction, and return some information such as gas used.
- `/app/version`: this will return the application's version.
- `/store/{path}`: this will query the store directly.
- `/p2p/filter/addr/{port}`: this will return a filtered list of the node's P2P peers by address port.
- `/p2p/filter/id/{id}`: this will return a filtered list of the node's P2P peers by ID.
- `/broadcast_tx_{aync,async,commit}`: these 3 endpoint will broadcast a transaction to other peers. CLI, gRPC and REST expose [a way to broadcast transations](./transactions.md#broadcasting-the-transaction), but they all use these 3 Tendermint RPCs under the hood.
## Comparison Table
| Name | Advantages | Disadvantages |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| gRPC | - can use code-generated stubs in various languages<br>- supports streaming and bidirectional communication (HTTP2)<br>- small wire binary sizes, faster transmission | - based on HTTP2, not available in browsers<br>- learning curve (mostly due to Protobuf) |
| REST | - ubiquitous<br>- client libraries in all languages, faster implementation<br> | - only supports unary request-response communication (HTTP1.1)<br>- bigger over-the-wire message sizes (JSON) |
| Tendermint RPC | - easy to use | - bigger over-the-wire message sizes (JSON) |
## Next {hide}
Learn about [events](./events.md) {hide}

View File

@ -69,7 +69,7 @@ Upon starting, the node will bootstrap its RPC and P2P server and start dialing
## Other commands
To discover how to concretely run a node and interact with it, please refer to our [Running a Node](../run-node/README.md) guide.
To discover how to concretely run a node and interact with it, please refer to our [Running a Node, API and CLI](../run-node/README.md) guide.
## Next {hide}

View File

@ -1,5 +1,5 @@
<!--
order: 9
order: 10
-->
# Object-Capability Model

9913
docs/core/proto-docs.md Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
<!--
order: 10
order: 11
-->
# RunTx recovery middleware

View File

@ -56,25 +56,25 @@ The Cosmos SDK comes with a large set of stores to persist the state of applicat
### Store Interface
At its very core, a Cosmos SDK `store` is an object that holds a `CacheWrapper` and implements a `GetStoreType()` method:
At its very core, a Cosmos SDK `store` is an object that holds a `CacheWrapper` and has a `GetStoreType()` method:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/types/store.go#L15-L18
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/types/store.go#L15-L18
The `GetStoreType` is a simple method that returns the type of store, whereas a `CacheWrapper` is a simple interface that specifies cache-wrapping and `Write` methods:
The `GetStoreType` is a simple method that returns the type of store, whereas a `CacheWrapper` is a simple interface that implements store read caching and write branching through `Write` method:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/types/store.go#L240-L264
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/types/store.go#L240-L264
Cache-wrapping is used ubiquitously in the Cosmos SDK and required to be implemented on every store type. A cache-wrapper creates a light snapshot of a store that can be passed around and updated without affecting the main underlying store. This is used to trigger temporary state-transitions that may be reverted later should an error occur. If a state-transition sequence is performed without issue, the cached store can be committed to the underlying store at the end of the sequence.
Branching and cache is used ubiquitously in the Cosmos SDK and required to be implemented on every store type. A storage branch creates an isolated, ephemeral branch of a store that can be passed around and updated without affecting the main underlying store. This is used to trigger temporary state-transitions that may be reverted later should an error occur. Read more about it in [context](./context.md#Store-branching)
### Commit Store
A commit store is a store that has the ability to commit changes made to the underlying tree or db. The Cosmos SDK differentiates simple stores from commit stores by extending the basic store interfaces with a `Committer`:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/types/store.go#L29-L33
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/types/store.go#L29-L33
The `Committer` is an interface that defines methods to persist changes to disk:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/types/store.go#L20-L27
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/types/store.go#L20-L27
The `CommitID` is a deterministic commit of the state tree. Its hash is returned to the underlying consensus engine and stored in the block header. Note that commit store interfaces exist for various purposes, one of which is to make sure not every object can commit the store. As part of the [object-capabilities model](./ocap.md) of the Cosmos SDK, only `baseapp` should have the ability to commit stores. For example, this is the reason why the `ctx.KVStore()` method by which modules typically access stores returns a `KVStore` and not a `CommitKVStore`.
@ -86,29 +86,29 @@ The Cosmos SDK comes with many types of stores, the most used being [`CommitMult
Each Cosmos SDK application holds a multistore at its root to persist its state. The multistore is a store of `KVStores` that follows the `Multistore` interface:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/types/store.go#L104-L133
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/types/store.go#L104-L133
If tracing is enabled, then cache-wrapping the multistore will wrap all the underlying `KVStore` in [`TraceKv.Store`](#tracekv-store) before caching them.
If tracing is enabled, then branching the multistore will firstly wrap all the underlying `KVStore` in [`TraceKv.Store`](#tracekv-store).
### CommitMultiStore
The main type of `Multistore` used in the Cosmos SDK is `CommitMultiStore`, which is an extension of the `Multistore` interface:
+++https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/types/store.go#L141-L184
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/types/store.go#L141-L184
As for concrete implementation, the [`rootMulti.Store`] is the go-to implementation of the `CommitMultiStore` interface.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/rootmulti/store.go#L43-L61
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/rootmulti/store.go#L43-L61
The `rootMulti.Store` is a base-layer multistore built around a `db` on top of which multiple `KVStores` can be mounted, and is the default multistore store used in [`baseapp`](./baseapp.md).
### CacheMultiStore
Whenever the `rootMulti.Store` needs to be cached-wrapped, a [`cachemulti.Store`](https://github.com/cosmos/cosmos-sdk/blob/master/store/cachemulti/store.go) is used.
Whenever the `rootMulti.Store` needs to be branched, a [`cachemulti.Store`](https://github.com/cosmos/cosmos-sdk/blob/master/store/cachemulti/store.go) is used.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/cachemulti/store.go#L17-L28
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/cachemulti/store.go#L17-L28
`cachemulti.Store` cache wraps all substores in its constructor and hold them in `Store.stores`. `Store.GetKVStore()` returns the store from `Store.stores`, and `Store.Write()` recursively calls `CacheWrap.Write()` on all the substores.
`cachemulti.Store` branches all substores (creates a virtual store for each substore) in its constructor and hold them in `Store.stores`. Moreover cachese all read queries. `Store.GetKVStore()` returns the store from `Store.stores`, and `Store.Write()` recursively calls `CacheWrap.Write()` on all the substores.
## Base-layer KVStores
@ -120,17 +120,17 @@ Individual `KVStore`s are used by modules to manage a subset of the global state
`CommitKVStore`s are declared by proxy of their respective `key` and mounted on the application's [multistore](#multistore) in the [main application file](../basics/app-anatomy.md#core-application-file). In the same file, the `key` is also passed to the module's `keeper` that is responsible for managing the store.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/types/store.go#L189-L219
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/types/store.go#L189-L219
Apart from the traditional `Get` and `Set` methods, a `KVStore` must provide an `Iterator(start, end)` method which returns an `Iterator` object. It is used to iterate over a range of keys, typically keys that share a common prefix. Below is an example from the bank's module keeper, used to iterate over all account balances:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/x/bank/keeper/view.go#L115-L134
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/x/bank/keeper/view.go#L115-L134
### `IAVL` Store
The default implementation of `KVStore` and `CommitKVStore` used in `baseapp` is the `iavl.Store`.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/iavl/store.go#L37-L40
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/iavl/store.go#L37-L40
`iavl` stores are based around an [IAVL Tree](https://github.com/tendermint/iavl), a self-balancing binary tree which guarantees that:
@ -144,7 +144,7 @@ The documentation on the IAVL Tree is located [here](https://github.com/cosmos/i
`dbadapter.Store` is a adapter for `dbm.DB` making it fulfilling the `KVStore` interface.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/dbadapter/store.go#L13-L16
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/dbadapter/store.go#L13-L16
`dbadapter.Store` embeds `dbm.DB`, meaning most of the `KVStore` interface functions are implemented. The other functions (mostly miscellaneous) are manually implemented. This store is primarily used within [Transient Stores](#transient-stores)
@ -152,17 +152,17 @@ The documentation on the IAVL Tree is located [here](https://github.com/cosmos/i
`Transient.Store` is a base-layer `KVStore` which is automatically discarded at the end of the block.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/transient/store.go#L13-L16
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/transient/store.go#L13-L16
`Transient.Store` is a `dbadapter.Store` with a `dbm.NewMemDB()`. All `KVStore` methods are reused. When `Store.Commit()` is called, a new `dbadapter.Store` is assigned, discarding previous reference and making it garbage collected.
This type of store is useful to persist information that is only relevant per-block. One example would be to store parameter changes (i.e. a bool set to `true` if a parameter changed in a block).
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/x/params/types/subspace.go#L20-L30
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/x/params/types/subspace.go#L20-L30
Transient stores are typically accessed via the [`context`](./context.md) via the `TransientStore()` method:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/types/context.go#L232-L235
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/types/context.go#L232-L235
## KVStore Wrappers
@ -170,45 +170,45 @@ Transient stores are typically accessed via the [`context`](./context.md) via th
`cachekv.Store` is a wrapper `KVStore` which provides buffered writing / cached reading functionalities over the underlying `KVStore`.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/cachekv/store.go#L27-L34
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/cachekv/store.go#L27-L34
This is the type used whenever an IAVL Store needs to be cache-wrapped (typically when setting value that might be reverted later).
This is the type used whenever an IAVL Store needs to be branched to create an isolated store (typically when we need to mutate a state that might be reverted later).
#### `Get`
`Store.Get()` checks `Store.cache` first in order to find if there is any cached value associated with the key. If the value exists, the function returns it. If not, the function calls `Store.parent.Get()`, sets the key-value pair to the `Store.cache`, and returns it.
`Store.Get()` firstly checks if `Store.cache` has an associated value with the key. If the value exists, the function returns it. If not, the function calls `Store.parent.Get()`, caches the result in `Store.cache`, and returns it.
#### `Set`
`Store.Set()` sets the key-value pair to the `Store.cache`. `cValue` has the field dirty bool which indicates whether the cached value is different from the underlying value. When `Store.Set()` cache new pair, the `cValue.dirty` is set `true` so when `Store.Write()` is called it can be written to the underlying store.
`Store.Set()` sets the key-value pair to the `Store.cache`. `cValue` has the field dirty bool which indicates whether the cached value is different from the underlying value. When `Store.Set()` cachees a new pair, the `cValue.dirty` is set `true` so when `Store.Write()` is called it can be written to the underlying store.
#### `Iterator`
`Store.Iterator()` have to traverse on both caches items and the original items. In `Store.iterator()`, two iterators are generated for each of them, and merged. `memIterator` is essentially a slice of the `KVPairs`, used for cached items. `mergeIterator` is a combination of two iterators, where traverse happens ordered on both iterators.
`Store.Iterator()` have to traverse on both cached items and the original items. In `Store.iterator()`, two iterators are generated for each of them, and merged. `memIterator` is essentially a slice of the `KVPairs`, used for cached items. `mergeIterator` is a combination of two iterators, where traverse happens ordered on both iterators.
### `GasKv` Store
Cosmos SDK applications use [`gas`](../basics/gas-fees.md) to track resources usage and prevent spam. [`GasKv.Store`](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/gaskv/store.go) is a `KVStore` wrapper that enables automatic gas consumption each time a read or write to the store is made. It is the solution of choice to track storage usage in Cosmos SDK applications.
Cosmos SDK applications use [`gas`](../basics/gas-fees.md) to track resources usage and prevent spam. [`GasKv.Store`](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/gaskv/store.go) is a `KVStore` wrapper that enables automatic gas consumption each time a read or write to the store is made. It is the solution of choice to track storage usage in Cosmos SDK applications.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/gaskv/store.go#L13-L19
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/gaskv/store.go#L13-L19
When methods of the parent `KVStore` are called, `GasKv.Store` automatically consumes appropriate amount of gas depending on the `Store.gasConfig`:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/types/gas.go#L153-L162
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/types/gas.go#L153-L162
By default, all `KVStores` are wrapped in `GasKv.Stores` when retrieved. This is done in the `KVStore()` method of the [`context`](./context.md):
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/types/context.go#L227-L230
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/types/context.go#L227-L230
In this case, the default gas configuration is used:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/types/gas.go#L164-L175
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/types/gas.go#L164-L175
### `TraceKv` Store
`tracekv.Store` is a wrapper `KVStore` which provides operation tracing functionalities over the underlying `KVStore`. It is applied automatically by the Cosmos SDK on all `KVStore` if tracing is enabled on the parent `MultiStore`.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/tracekv/store.go#L20-L43
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/tracekv/store.go#L20-L43
When each `KVStore` methods are called, `tracekv.Store` automatically logs `traceOperation` to the `Store.writer`. `traceOperation.Metadata` is filled with `Store.context` when it is not nil. `TraceContext` is a `map[string]interface{}`.
@ -216,7 +216,7 @@ When each `KVStore` methods are called, `tracekv.Store` automatically logs `trac
`prefix.Store` is a wrapper `KVStore` which provides automatic key-prefixing functionalities over the underlying `KVStore`.
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc3/store/prefix/store.go#L15-L21
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/store/prefix/store.go#L15-L21
When `Store.{Get, Set}()` is called, the store forwards the call to its parent, with the key prefixed with the `Store.prefix`.

View File

@ -1,5 +1,5 @@
<!--
order: 8
order: 9
-->
# Telemetry

View File

@ -141,13 +141,17 @@ simd tx send $MY_VALIDATOR_ADDRESS $RECIPIENT 1000stake
The `Tx` service exposes a handful of utility functions, such as simulating a transaction or querying a transaction, and also one method to broadcast transactions.
An example of broadcasting a transaction is shown in [TODO](https://github.com/cosmos/cosmos-sdk/issues/7657). Please note that the `BroadcastTx` endpoint takes `TxRaw`, not bytes.
Examples of broadcasting and simulating a transaction are shown [here](../run-node/txs.md#programmatically-with-go).
#### REST
Each gRPC method has its corresponding REST endpoint, generated using [gRPC-gateway](https://github.com/grpc-ecosystem/grpc-gateway). Therefore, instead of using gRPC, you can also use HTTP to broadcast the same transaction, on the `POST /cosmos/tx/v1beta1/broadcast_tx` endpoint.
Each gRPC method has its corresponding REST endpoint, generated using [gRPC-gateway](https://github.com/grpc-ecosystem/grpc-gateway). Therefore, instead of using gRPC, you can also use HTTP to broadcast the same transaction, on the `POST /cosmos/tx/v1beta1/txs` endpoint.
An example can be seen [here TODO](https://github.com/cosmos/cosmos-sdk/issues/7657)
An example can be seen [here](../run-node/txs.md#using-rest)
#### Tendermint RPC
The three methods presented above are actually higher abstractions over the Tendermint RPC `/broadcast_tx_{async,sync,commit}` endpoints, documented [here](https://docs.tendermint.com/master/rpc/#/Tx). This means that you can use the Tendermint RPC endpoints directly to broadcast the transaction, if you wish so.
## Next {hide}

View File

@ -49,7 +49,9 @@ func (k Keeper) OnChanOpenInit(ctx sdk.Context,
version string,
) error {
// OpenInit must claim the channelCapability that IBC passes into the callback
k.scopedKeeper.ClaimCapability(ctx, channelCap)
if err := k.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil {
return err
}
// ... do custom initialization logic
@ -72,9 +74,17 @@ OnChanOpenTry(
version,
counterpartyVersion string,
) error {
// OpenInit must claim the channelCapability that IBC passes into the callback
k.scopedKeeper.ClaimCapability(ctx, channelCap)
// Module may have already claimed capability in OnChanOpenInit in the case of crossing hellos
// (ie chainA and chainB both call ChanOpenInit before one of them calls ChanOpenTry)
// If the module can already authenticate the capability then the module already owns it so we don't need to claim
// Otherwise, module does not have channel capability and we must claim it from IBC
if !k.AuthenticateCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)) {
// Only claim channel capability passed back by IBC module if we do not already own it
if err := k.scopedKeeper.ClaimCapability(ctx, chanCap, host.ChannelCapabilityPath(portID, channelID)); err != nil {
return err
}
}
// ... do custom initialization logic
// Use above arguments to determine if we want to abort handshake
@ -285,7 +295,7 @@ invoked by the IBC module after the packet has been proved valid and correctly p
keepers. Thus, the `OnRecvPacket` callback only needs to worry about making the appropriate state
changes given the packet data without worrying about whether the packet is valid or not.
Modules must return an acknowledgement as a byte string and return it to the IBC handler.
Modules may return an acknowledgement as a byte string and return it to the IBC handler.
The IBC handler will then commit this acknowledgement of the packet so that a relayer may relay the
acknowledgement back to the sender module.
@ -331,8 +341,14 @@ acknowledgement. An example of this technique is in the `ibc-transfer` module's
### Acknowledgements
Modules must commit an acknowledgement upon receiving and processing a packet. This
acknowledgement can then be relayed back to the original sender chain, which can take action
Modules may commit an acknowledgement upon receiving and processing a packet in the case of synchronous packet processing.
In the case where a packet is processed at some later point after the packet has been received (asynchronous execution), the acknowledgement
will be written once the packet has been processed by the application which may be well after the packet receipt.
NOTE: Most blockchain modules will want to use the synchronous execution model in which the module processes and writes the acknowledgement
for a packet as soon as it has been received from the IBC module.
This acknowledgement can then be relayed back to the original sender chain, which can take action
depending on the contents of the acknowledgement.
Just as packet data was opaque to IBC, acknowledgements are similarly opaque. Modules must pass and
@ -344,12 +360,31 @@ example above. [ICS 04](https://github.com/cosmos/ics/tree/master/spec/ics-004-c
specifies a recommended format for acknowledgements. This acknowledgement type can be imported from
[channel types](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/04-channel/types).
While modules may choose arbitrary acknowledgement structs, a default acknowledgement types is provided by IBC [here](https://github.com/cosmos/cosmos-sdk/blob/master/proto/ibc/core/channel/v1/channel.proto):
```proto
// Acknowledgement is the recommended acknowledgement format to be used by
// app-specific protocols.
// NOTE: The field numbers 21 and 22 were explicitly chosen to avoid accidental
// conflicts with other protobuf message formats used for acknowledgements.
// The first byte of any message with this format will be the non-ASCII values
// `0xaa` (result) or `0xb2` (error). Implemented as defined by ICS:
// https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#acknowledgement-envelope
message Acknowledgement {
// response contains either a result or an error and must be non-empty
oneof response {
bytes result = 21;
string error = 22;
}
}
```
#### Acknowledging Packets
After a module writes an acknowledgement while receiving a packet. a relayer can relay back the acknowledgement to the sender module. The sender module can
After a module writes an acknowledgement, a relayer can relay back the acknowledgement to the sender module. The sender module can
then process the acknowledgement using the `OnAcknowledgementPacket` callback. The contents of the
acknowledgement is entirely upto the modules on the channel (just like the packet data); however, it
may often contain information on whether the packet was successfully received and processed along
may often contain information on whether the packet was successfully processed along
with some additional data that could be useful for remediation if the packet processing failed.
Since the modules are responsible for agreeing on an encoding/decoding standard for packet data and

View File

@ -141,6 +141,34 @@ Thus, packet data is completely opaque to IBC handlers. It is incumbent on a sen
their application-specific packet information into the `Data` field of packets, and the receiver
module to decode that `Data` back to the original application data.
### [Receipts and Timeouts](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/04-channel)
Since IBC works over a distributed network and relies on potentially faulty relayers to relay messages between ledgers,
IBC must handle the case where a packet does not get sent to its destination in a timely manner or at all. Thus, packets must
specify a timeout height or timeout timestamp after which a packet can no longer be successfully received on the destination chain.
If the timeout does get reached, then a proof of packet timeout can be submitted to the original chain which can then perform
application-specific logic to timeout the packet, perhaps by rolling back the packet send changes (refunding senders any locked funds, etc).
In ORDERED channels, a timeout of a single packet in the channel will cause the channel to close. If packet sequence `n` times out,
then no packet at sequence `k > n` can be successfully received without violating the contract of ORDERED channels that packets are processed in the order that they are sent. Since ORDERED channels enforce this invariant, a proof that sequence `n` hasn't been received on the destination chain by packet `n`'s specified timeout is sufficient to timeout packet `n` and close the channel.
In the UNORDERED case, packets may be received in any order. Thus, IBC will write a packet receipt for each sequence it has received in the UNORDERED channel. This receipt contains no information, it is simply a marker intended to signify that the UNORDERED channel has received a packet at the specified sequence. To timeout a packet on an UNORDERED channel, one must provide a proof that a packet receipt does not exist for the packet's sequence by the specified timeout. Of course, timing out a packet on an UNORDERED channel will simply trigger the application specific timeout logic for that packet, and will not close the channel.
For this reason, most modules should use UNORDERED channels as they require less liveness guarantees to function effectively for users of that channel.
### [Acknowledgements](https://github.com/cosmos/cosmos-sdk/tree/master/x/ibc/core/04-channel)
Modules may also choose to write application-specific acknowledgements upon processing a packet. This may either be done synchronously on `OnRecvPacket`, if the module processes packets as soon as they are received from IBC module. Or they may be done asynchronously if module processes packets at some later point after receiving the packet.
Regardless, this acknowledgement data is opaque to IBC much like the packet `Data` and will be treated by IBC as a simple byte string `[]byte`. It is incumbent on receiver modules to encode their acknowledgemnet in such a way that the sender module can decode it correctly. This should be decided through version negotiation during the channel handshake.
The acknowledgement may encode whether the packet processing succeeded or failed, along with additional information that will allow the sender module to take appropriate action.
Once the acknowledgement has been written by the receiving chain, a relayer will relay the acknowledgement back to the original sender module which will then execute application-specific acknowledgment logic using the contents of the acknowledgement. This may involve rolling back packet-send changes in the case of a failed acknowledgement (refunding senders).
Once an acknowledgement is received successfully on the original sender the chain, the IBC module deletes the corresponding packet commitment as it is no longer needed.
## Further Readings and Specs
If you want to learn more about IBC, check the following specifications:

View File

@ -1,10 +1,10 @@
<!--
order: false
parent:
order: 6
order: 7
-->
# Interfaces
# Interfaces (Deprecated)
This repository contains documentation on interfaces for Cosmos SDK applications.

13
docs/migrations/README.md Normal file
View File

@ -0,0 +1,13 @@
<!--
order: false
parent:
order: 6
-->
# Migrations
This folder contains all the migration guides to update your app and modules to Cosmos v0.40 Stargate.
1. [App and Modules Migration](./app_and_modules.md)
1. [Chain Upgrade Guide to v0.40](./chain-upgrade-guide-040.md)
1. [REST Endpoints Migration](./rest.md)

View File

@ -0,0 +1,239 @@
<!--
order: 1
-->
# App and Modules Migration
The following document describes the changes to update your app and modules from Cosmos SDK v0.39 to v0.40,
a.k.a. Stargate release. {synopsis}
## Update Tooling
Make sure to have the following dependencies before updating your app to v0.40:
- Go 1.15+
- Docker
- Node.js v12.0+ (optional, for generating Swagger docs)
In Cosmos-SDK we manage the project using Makefile. Your own app can use a similar Makefile to the [Cosmos SDK's one](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/Makefile). More specifically, below are some _make_ commands that might be useful for your own app, related to the introduction of Protocol Buffers:
- `proto-update-deps` - To download/update the required thirdparty `proto` definitions.
- `proto-gen` - To auto generate proto code.
- `proto-check-breaking` - To check proto breaking changes.
- `proto-format` - To format proto files.
## Updating Modules
This section outlines how to upgrade your module to v0.40. There is also a whole section about [building modules](../building-modules/README.md) from scratch, it might serve as a useful guide.
### Protocol Buffers
As outlined in our [encoding guide](../core/encoding.md), one of the most significant improvements introduced in Cosmos SDK v0.40 is Protobuf.
The rule of thumb is that any object that needs to be serialized (into binary or JSON) must implement `proto.Message` and must be serializable into Protobuf format. The easiest way to do it is to use Protobuf type definition and `protoc` compiler to generate the structures and functions for you. In practice, the three following categories of types must be converted to Protobuf messages:
- client-facing types: `Msg`s, query requests and responses. This is because client will send these types over the wire to your app.
- objects that are stored in state. This is because the SDK stores the binary representation of these types in state.
- genesis types. These are used when importing and exporting state snapshots during chain upgrades.
Let's have a look at [x/auth's](../../x/auth/spec/README.md) `BaseAccount` objects, which are stored in a state. The migration looks like:
```diff
// We were definining `MsgSend` as a Go struct in v0.39.
- // https://github.com/cosmos/cosmos-sdk/blob/v0.39.2/x/bank/internal/types/msgs.go#L12-L16
- type BaseAccount struct {
- Address sdk.AccAddress `json:"address" yaml:"address"`
- Coins sdk.Coins `json:"coins" yaml:"coins"`
- PubKey crypto.PubKey `json:"public_key" yaml:"public_key"`
- AccountNumber uint64 `json:"account_number" yaml:"account_number"`
- Sequence uint64 `json:"sequence" yaml:"sequence"`
- }
// And it should be converted to a Protobuf message in v0.40.
+ // https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/proto/cosmos/auth/v1beta1/auth.proto#L13-L25
+ message BaseAccount {
+ string address = 1;
+ google.protobuf.Any pub_key = 2
+ [(gogoproto.jsontag) = "public_key,omitempty", (gogoproto.moretags) = "yaml:\"public_key\""];
+ uint64 account_number = 3 [(gogoproto.moretags) = "yaml:\"account_number\""];
+ uint64 sequence = 4;
+ }
}
```
In general, we recommend to put all the Protobuf definitions in your module's subdirectory under a root `proto/` folder, as described in [ADR-023](../architecture/adr-023-protobuf-naming.md). This ADR also contains other useful information on naming conventions.
You might have noticed that the `PubKey` interface in v0.39's `BaseAccount` has been transformed into an `Any`. For storing interfaces, we use Protobuf's `Any` message, which is a struct that can hold arbitrary content. Please refer to the [encoding FAQ](../core/encoding.md#faq) to learn how to handle interfaces and `Any`s.
Once all your Protobuf messages are defined, use the `make proto-gen` command defined in the [tooling section](#tooling) to generate Go structs. These structs will be generated into `*.pb.go` files. As a quick example, here is the generated Go struct for the Protobuf BaseAccount we defined above:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/x/auth/types/auth.pb.go#L28-L36
There might be some back and forth removing old Go structs/interfaces and defining new Protobuf messages before your Go app compiles and your tests pass.
### Create `Msg` and `Query` Services
Cosmos SDK v0.40 uses Protobuf services to define state transitions (`Msg`s) and state queries, please read [the building modules guide on those services](../building-modules/messages-and-queries.md) for an overview.
#### `Msg` Service
For migrating `Msg`s, the handler pattern (inside the `handler.go` file) is deprecated. You may still keep it if you wish to support `Msg`s defined in older versions of the SDK. However, it is strongly recommended to add a `Msg` service to your Protobuf files, and each old `Msg` should be converted into a service method. Taking [x/bank's](../../x/bank/spec/README.md) `MsgSend` as an example, we have a corresponding `cosmos.bank.v1beta1.Msg/Send` service method:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/proto/cosmos/bank/v1beta1/tx.proto#L10-L31
A state transition is therefore modelized as a Protobuf service method, with a method request, and an (optionally empty) method response.
After defining your `Msg` service, run the `make proto-gen` script again to generate `Msg` server interfaces. The name of this interface is simply `MsgServer`. The implementation of this interface should follow exactly the implementation of the old `Msg` handlers, which, in most cases, defers the actual state transition logic to the [keeper](../building-modules/keeper.md). You may implement a `MsgServer` directly on the keeper, or you can do it using a new struct (e.g. called `msgServer`) that references the module's keeper.
For more information, please check our [`Msg` service guide](../building-modules/msg-services.md).
#### `Query` Service
For migrating state queries, the querier pattern (inside the `querier.go` file) is deprecated. You may still keep this file to support legacy queries, but it is strongly recommended to use a Protobuf `Query` service to handle state queries.
Each query endpoint is now defined as a separate service method in the `Query` service. Still taking `x/bank` as an example, here are the queries to fetch an account's balances:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/proto/cosmos/bank/v1beta1/query.proto#L12-L23
Each query has its own `Request` and `Response` types. Please also note the `google.api.http` option (coming from [`grpc-gateway`](https://github.com/grpc-ecosystem/grpc-gateway)) on each service method. `grpc-gateway` is a tool that exposes `Query` service methods as REST endpoints. Adding this annotation will expose these endpoints not only as gRPC endpoints, but also as REST endpoints. An overview of gRPC versus REST can be found [here](../core/grpc_rest.md).
After defining the `Query` Protobuf service, run the `make proto-gen` command to generate corresponding interfaces. The interface that needs to be implemented by your module is `QueryServer`. This interface can be implemented on the [keeper](../building-modules/keeper.md) directly, or on a struct (e.g. called `queryServer`) that references the module's keeper. The logic of the implementation, namely the logic that fetches data from the module's store and performs unmarshalling, can be deferred to the keeper.
Cosmos SDK v0.40 also comes with an efficient pagination, it now uses `Prefix` stores to make queries. There are 2 helpers for pagination, [`Paginate`](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/types/query/pagination.go#L40-L42), [`FilteredPaginate`](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/types/query/filtered_pagination.go#L9-L17).
For more information, please check our [`Query` service guide](../building-modules/query-services.md).
#### Wiring up `Msg` and `Query` Services
We added a new `RegisterServices` method that registers a module's `Msg` service and a `Query` service. It should be implemented by all modules, using a `Configurator` object:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/x/bank/module.go#L99-L103
If you wish to expose your `Query` endpoints as REST endpoints (as proposed in the [`Query` Services paragraph](#query-services)), make sure to also implement the `RegisterGRPCGatewayRoutes` method:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/x/bank/module.go#L69-L72
### Codec
If you still use Amino (which is deprecated since Stargate), you must register related types using the `RegisterLegacyAminoCodec(cdc *codec.LegacyAmino)` method (previously it was called `RegisterCodec(cdc *codec.Codec)`).
Moreover, a new `RegisterInterfaces` method has been added to the `AppModule` interface that all modules must implement. This method must register the interfaces that Protobuf messages implement, as well as the service `Msg`s used in the module. An example from x/bank is given below:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/x/bank/types/codec.go#L21-L34
### Keeper
The `Keeper` constructor now takes a `codec.Marshaler` instead of a concrete Amino codec. This `codec.Marshaler` is used to encode types as binary and save the bytes into the state. With an interface, you can define `codec.Marshaler` to be Amino or Protobuf on an app level, and keepers will use that encoding library to encode state. Please note that Amino is deprecated in v0.40, and we strongly recommend to use Protobuf. Internally, the SDK still uses Amino in a couple of places (legacy REST API, x/params, keyring...), but Amino is planned to be removed in a future release.
Keeping Amino for now can be useful if you wish to update to SDK v0.40 without doing a chain upgrade with a genesis migration. This will not require updating the stores, so you can migrate to Cosmos SDK v0.40 with less effort. However, as Amino will be removed in a future release, the chain migration with genesis export/import will need to be performed then.
Related to the keepers, each module's `AppModuleBasic` now also includes this `codec.Marshaler`:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/x/bank/module.go#L35-L38
### CLI
Each modules may optionally expose CLI commands, and some changes are needed in these commands.
First, `context.CLIContext` is renamed to `client.Context` and moved to `github.com/cosmos/cosmos-sdk/client`.
Second, the global `viper` usage is removed from client and is replaced with Cobra' `cmd.Flags()`. There are two helpers to read common flags for CLI txs and queries:
```go
clientCtx, err := client.GetClientQueryContext(cmd)
clientCtx, err := client.GetClientTxContext(cmd)
```
Some other flags helper functions are transformed: `flags.PostCommands(cmds ...*cobra.Command) []*cobra.Command` and `flags.GetCommands(...)` usage is now replaced by `flags.AddTxFlagsToCmd(cmd *cobra.Command)` and `flags.AddQueryFlagsToCmd(cmd *cobra.Command)` respectively.
Moreover, new CLI commands don't take any codec as input anymore. Instead, the `clientCtx` can be retrieved from the `cmd` itself using the `GetClient{Query,Tx}Context` function above, and the codec as `clientCtx.JSONMarshaler`.
```diff
// v0.39
- func SendTxCmd(cdc *codec.Codec) *cobra.Command {
- cdc.MarshalJSON(...)
- }
// v0.40
+ func NewSendTxCmd() *cobra.Command {
+ clientCtx, err := client.GetClientTxContext(cmd)
+ clientCtx.JSONMarshaler.MarshalJSON(...)
+}
```
Finally, once your [`Query` services](#query-service) are wired up, the CLI commands should preferably use gRPC to communicate with the node. The gist is to create a `Query` or `Msg` client using the command's `clientCtx`, and perform the request using Protobuf's generated code. An example for querying x/bank balances is given here:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/x/bank/client/cli/query.go#L66-L94
### Miscelleanous
A number of other smaller breaking changes are also noteworthy.
| Before | After | Comment |
| ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `alias.go` file | Removed | `alias` usage is removed, please see [#6311](https://github.com/cosmos/cosmos-sdk/issues/6311) for details. |
| `codec.New()` | `codec.NewLegacyAmino()` | Simple rename. |
| `DefaultGenesis()` | `DefaultGenesis(cdc codec.JSONMarshaler)` | `DefaultGenesis` takes a codec argument now |
| `ValidateGenesis()` | `ValidateGenesis(cdc codec.JSONMarshaler, config client.TxEncodingConfig, bz json.RawMessage)` | `ValidateGenesis` now requires `Marshaler`, `TxEncodingConfig`, `json.RawMessage` as input. |
| `Route() string` | `Route() sdk.Route` | For legacy handlers, return type of `Route()` method is changed from `string` to `"github.com/cosmos/cosmos-sdk/types".Route`. It should return a `NewRoute()` which includes `RouterKey` and `NewHandler` as params. |
| `QuerierHandler` | `LegacyQuerierHandler` | Simple rename. |
| `InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate` | InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate | `InitGenesis` now takes a codec input. |
| `ExportGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate` | ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate | `ExportGenesis` now takes a codec input. |
## Updating Your App
For a reference implementation used for demo purposes, you can refer to the SDK's [SimApp](https://github.com/cosmos/cosmos-sdk/tree/v0.40.0-rc6/simapp) for your app's migration. The most important changes are described in this section.
### Creating Codecs
With the introduction of Protobuf, each app needs to define the encoding library (Amino or Protobuf) to be used throughout the app. There is a central struct, [`EncodingConfig`](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/simapp/params/encoding.go#L9-L11), which defines all information necessary for codecs. In your app, an example `EncodingConfig` with Protobuf as default codec might look like:
```go
// MakeEncodingConfig creates an EncodingConfig
func MakeEncodingConfig() params.EncodingConfig {
amino := codec.NewLegacyAmino()
interfaceRegistry := types.NewInterfaceRegistry()
marshaler := codec.NewProtoCodec(interfaceRegistry)
txCfg := tx.NewTxConfig(marshaler, tx.DefaultSignModes)
encodingConfig := params.EncodingConfig{
InterfaceRegistry: interfaceRegistry,
Marshaler: marshaler,
TxConfig: txCfg,
Amino: amino,
}
std.RegisterLegacyAminoCodec(encodingConfig.Amino)
std.RegisterInterfaces(encodingConfig.InterfaceRegistry)
ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino)
ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry)
return encodingConfig
}
```
These codecs are used to populate the following fields on your app (again, we are using SimApp for demo purposes):
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/simapp/app.go#L146-L153
As explained in the [modules migration section](#updating-modules), some functions and structs in modules require an additional `codec.Marshaler` argument. You should pass `app.appCodec` in these cases, and this will be the default codec used throughout the app.
### Registering Non-Module Protobuf Services
We described in the [modules migration section](#updating-modules) `Query` and `Msg` services defined in each module. The SDK also exposes two more module-agnostic services:
- the [Tx Service](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/proto/cosmos/tx/v1beta1/service.proto), to perform operations on transactions,
- the [Tendermint service](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/proto/cosmos/base/tendermint/v1beta1/query.proto), to have a more idiomatic interface to the [Tendermint RPC](https://docs.tendermint.com/master/rpc/).
These services are optional, if you wish to use them, or if you wish to add more module-agnostic Protobuf services into your app, then you need to add them inside `app.go`:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/simapp/app.go#L577-L585
### Registering `grpc-gateway` Routes
The exising `RegisterAPIRoutes` method on the `app` only registers [Legacy API routes](../core/grpc_rest.md#legacy-rest-api-routes). If you are using `grpc-gateway` REST endpoints as described [above](#query-service), then these endpoints need to be wired up to a HTTP server:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/simapp/app.go#L555-L575
## Next {hide}
Learn how to perform a [chain upgrade](./chain-upgrade-guide-040.md) to 0.40.

View File

@ -0,0 +1,162 @@
<!--
order: 2
-->
# Chain Upgrade Guide to v0.40
This document explains how to perform a chain upgrade from v0.39 to v0.40. {synopsis}
## Risks
As a validator, performing the upgrade procedure on your consensus nodes carries a heightened risk of double-signing and
being slashed: if your validator node votes for a block, and, in the same block time, restarts the upgraded node, this may lead to double-voting on a block.
The riskiest thing a validator can do is to discover that they made a mistake and repeat the upgrade procedure again during
the network startup. If you discover a mistake in the process, the best thing to do is wait for the network to start
before correcting it. If the network is halted and you have started with a different genesis file than the expected one,
seek advice from the validator community.
## Recovery
- Prior to exporting the state, the validators are encouraged to take a full data snapshot at exported height. Exported
height will be determined by a governance proposal. Data backup is usually done by copying daemon home directory,
e.g.: `~/.simd`
**Note:** we use "simd" as our app throughout this doc, be sure to replace with the name of your own binary.
It is critically important to back-up the validator state file, e.g.: `~/.simd/data/priv_validator_state.json` file
after stopping your daemon process. This file is updated every block as your validator participates in a consensus
rounds. It is a critical file needed to prevent double-signing, in case the upgrade fails, and the previous chain needs
to be restarted.
In the event that the upgrade does not succeed, validators and operators must downgrade back to old version of the
software and restore to their latest snapshot before restarting their nodes.
## Upgrade procedure
1. The procedure is to export the state from the old binary, and import it with the new binary. First, verify your old binary version (which should use `github.com/cosmos/cosmos-sdk@0.39.*`) before exporting the state.
```shell
simd version --long
```
1. Export the state from existing chain using the old binary.
```shell
simd export --for-zero-height --height <height> > v039_exported_state.json
```
1. Verify the SHA256 of the (sorted) exported genesis file:
```shell
$ jq -S -c -M '' v039_exported_state.json | shasum -a 256
[SHASUM_PLACEHOLDER] v039_exported_state.json
```
1. Cross check the hash with other peers (other validators) in the chat rooms.
1. Install the latest binary (which uses `github.com/cosmos/cosmos-sdk@0.40.*`).
1. Migrate the exported state to `github.com/cosmos/cosmos-sdk@0.40.*` compatible genesis state.
```shell
simd migrate v0.40 v039_exported_state.json --chain-id <new_chain_id> --genesis-time <new_genesis_time_in_utc> > new_v040_genesis.json
```
**Note:** The migrate command takes an input genesis state and migrates it to a targeted version. New `genesis-time` will be as mentioned in the governance proposal.
1. All the necessary state changes are handled in the `simd migrate v0.40` migration command. However, Tendermint parameters are **not** handled in this command. You might need to update these parameters manually.
In the recent versions of Tendermint, the following changes have been made:
- `consensus_params.evidence.max_num` has been renamed to `consensus_params.evidence.max_bytes`.
- `consensus_params.evidence.max_age` has been removed, and replaced by `consensus_params.evidence.max_age_duration` and `consensus_params.evidence.max_age_num_blocks`.
Make sure that your genesis JSON files contains the correct values specific to your chain. If the `simd migrate` errors with a message saying that the genesis file cannot be parsed, these are the fields to check first.
1. Verify the SHA256 of the migrated genesis file with other validators to make sure there are no manual errors in the process.
```shell
$ jq -S -c -M '' new_v040_genesis.json | shasum -a 256
[SHASUM_PLACEHOLDER] new_v040_genesis.json
```
1. Make sure to update the genesis parameters in the new genesis if any. All these details will be generally present in
the governance proposal.
1) If your chain is using IBC, make sure to add IBC initial genesis state to the genesis file. You can use the following command to add IBC initial genesis state to the genesis file.
```shell
cat new_040_genesis.json | jq '.app_state |= . + {"ibc":{"client_genesis":{"clients":[],"clients_consensus":[],"create_localhost":false},"connection_genesis":{"connections":[],"client_connection_paths":[]},"channel_genesis":{"channels":[],"acknowledgements":[],"commitments":[],"receipts":[],"send_sequences":[],"recv_sequences":[],"ack_sequences":[]}},"transfer":{"port_id":"transfer","denom_traces":[],"params":{"send_enabled":false,"receive_enabled":false}},"capability":{"index":"1","owners":[]}}' > new_040_genesis.json
```
**Note:** This would add IBC state with IBC's `send_enabled: false` and `receive_enabled: false`. Make sure to update them to `true` in the above command if are planning to enable IBC transactions with chain upgrade. Otherwise you can do it via a governance proposal.
1) Reset the old state.
**Note:** Be sure you have a complete backed up state of your node before proceeding with this step.
See Recovery for details on how to proceed.
```shell
simd unsafe-reset-all
```
1) Move the new genesis.json to your daemon config directory. Ex
```shell
cp new_v040_genesis.json ~/.simd/config/genesis.json
```
1) Update `~/.simd/config/app.toml` to include latest app configurations. [Here is the link](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/server/config/toml.go#L11-L164) to the default template for v0.40's `app.toml`. Make sure to
update your custom configurations as per your validator design, e.g. `gas_price`.
Compared to v0.39, some notable updates to `app.toml` are:
- API server is now configured to run in-process with daemon, previously it was a separate process, invoked by running rest-server
command i.e., `gaiacli rest-server`. Now it is in-process with daemon and can be enabled/disabled by API configuration:
```yaml
[api]
# Enable defines if the API server should be enabled.
enable = false
# Swagger defines if swagger documentation should automatically be registered.
swagger = false
```
`swagger` setting refers to enabling/disabling swagger docs API, i.e, `/swagger/` API endpoint.
- gRPC Configuration
```yaml
[grpc]
# Enable defines if the gRPC server should be enabled.
enable = true
# Address defines the gRPC server address to bind to.
address = "0.0.0.0:9090"
```
- State Sync Configuration
```yaml
# State sync snapshots allow other nodes to rapidly join the network without replaying historical
# blocks, instead downloading and applying a snapshot of the application state at a given height.
[state-sync]
# snapshot-interval specifies the block interval at which local state sync snapshots are
# taken (0 to disable). Must be a multiple of pruning-keep-every.
snapshot-interval = 0
# snapshot-keep-recent specifies the number of recent snapshots to keep and serve (0 to keep all).
snapshot-keep-recent = 2
```
1) Kill if any external `rest-server` process is running.
1) All set now! You can (re)start your daemon to validate on the upgraded network. Make sure to check your binary version
before starting the daemon:
```
simd version --long
```
## Next {hide}
Once your chain is upgraded, make sure to [update your clients' REST endpoints](./rest.md).

View File

@ -1,3 +1,7 @@
<!--
order: 3
-->
# REST Endpoints Migration
Migrate your REST endpoints to the Stargate ones. {synopsis}
@ -30,7 +34,7 @@ Some important information concerning all legacy REST endpoints:
Thanks to the Protocol Buffers migration in v0.40 we are able to take advantage of a vast number of gRPC tools and solutions. For most of the legacy REST endpoints, Cosmos SDK v0.40 provides new REST endpoints generated from [gRPC `Query` services](../building-modules/query-services.md) using [grpc-gateway](https://grpc-ecosystem.github.io/grpc-gateway/). We usually call them _gGPC-gateway REST endpoints_.
Some modules expose legacy `POST` endpoints to generate unsigned transactions for their `Msg`s. These `POST` endpoints have been removed. We recommend to use [service `Msg`s](../building-modules/msg-services.md) directly, and use Protobuf to do client-side transaction generation. A guide can be found [here (TODO)](https://github.com/cosmos/cosmos-sdk/issues/7657).
Some modules expose legacy `POST` endpoints to generate unsigned transactions for their `Msg`s. These `POST` endpoints have been removed. We recommend to use [service `Msg`s](../building-modules/msg-services.md) directly, and use Protobuf to do client-side transaction generation. A guide can be found [here](../run-node/txs.md).
| Legacy REST Endpoint | Description | New gGPC-gateway REST Endpoint |
| ------------------------------------------------------------------------------- | ------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
@ -94,4 +98,4 @@ Some modules expose legacy `POST` endpoints to generate unsigned transactions fo
## Migrating to gRPC
Instead of hitting REST endpoints as described in the previous paragraph, the SDK also exposes a gRPC server. Any client can use gRPC instead of REST to interact with the node. An overview of different ways to communicate with a node can be found [here (TODO)](https://github.com/cosmos/cosmos-sdk/issues/7657), and a concrete tutorial for setting up a gRPC client [here (TODO)](https://github.com/cosmos/cosmos-sdk/issues/7657).
Instead of hitting REST endpoints as described in the previous paragraph, the SDK also exposes a gRPC server. Any client can use gRPC instead of REST to interact with the node. An overview of different ways to communicate with a node can be found [here](../core/grpc_rest.md), and a concrete tutorial for setting up a gRPC client [here](../run-node/txs.md#programmatically-with-go).

182
docs/package-lock.json generated
View File

@ -133,24 +133,23 @@
"integrity": "sha512-YaxPMGs/XIWtYqrdEOZOCPsVWfEoriXopnsz3/i7apYPXQ3698UFhS6dVT1KN5qOsWmVgw/FOrmQgpRaZayGsw=="
},
"@babel/core": {
"version": "7.12.9",
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.12.9.tgz",
"integrity": "sha512-gTXYh3M5wb7FRXQy+FErKFAv90BnlOuNn1QkCK2lREoPAjrQCO49+HVSrFoe5uakFAF5eenS75KbO2vQiLrTMQ==",
"version": "7.12.10",
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.12.10.tgz",
"integrity": "sha512-eTAlQKq65zHfkHZV0sIVODCPGVgoo1HdBlbSLi9CqOzuZanMv2ihzY+4paiKr1mH+XmYESMAmJ/dpZ68eN6d8w==",
"requires": {
"@babel/code-frame": "^7.10.4",
"@babel/generator": "^7.12.5",
"@babel/generator": "^7.12.10",
"@babel/helper-module-transforms": "^7.12.1",
"@babel/helpers": "^7.12.5",
"@babel/parser": "^7.12.7",
"@babel/parser": "^7.12.10",
"@babel/template": "^7.12.7",
"@babel/traverse": "^7.12.9",
"@babel/types": "^7.12.7",
"@babel/traverse": "^7.12.10",
"@babel/types": "^7.12.10",
"convert-source-map": "^1.7.0",
"debug": "^4.1.0",
"gensync": "^1.0.0-beta.1",
"json5": "^2.1.2",
"lodash": "^4.17.19",
"resolve": "^1.3.2",
"semver": "^5.4.1",
"source-map": "^0.5.0"
},
@ -189,11 +188,11 @@
}
},
"@babel/generator": {
"version": "7.12.5",
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.12.5.tgz",
"integrity": "sha512-m16TQQJ8hPt7E+OS/XVQg/7U184MLXtvuGbCdA7na61vha+ImkyyNM/9DDA0unYCVZn3ZOhng+qz48/KBOT96A==",
"version": "7.12.10",
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.12.10.tgz",
"integrity": "sha512-6mCdfhWgmqLdtTkhXjnIz0LcdVCd26wS2JXRtj2XY0u5klDsXBREA/pG5NVOuVnF2LUrBGNFtQkIqqTbblg0ww==",
"requires": {
"@babel/types": "^7.12.5",
"@babel/types": "^7.12.10",
"jsesc": "^2.5.1",
"source-map": "^0.5.0"
},
@ -206,11 +205,11 @@
}
},
"@babel/helper-annotate-as-pure": {
"version": "7.10.4",
"resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.10.4.tgz",
"integrity": "sha512-XQlqKQP4vXFB7BN8fEEerrmYvHp3fK/rBkRFz9jaJbzK0B1DSfej9Kc7ZzE8Z/OnId1jpJdNAZ3BFQjWG68rcA==",
"version": "7.12.10",
"resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.12.10.tgz",
"integrity": "sha512-XplmVbC1n+KY6jL8/fgLVXXUauDIB+lD5+GsQEh6F6GBF1dq1qy4DP4yXWzDKcoqXB3X58t61e85Fitoww4JVQ==",
"requires": {
"@babel/types": "^7.10.4"
"@babel/types": "^7.12.10"
}
},
"@babel/helper-builder-binary-assignment-operator-visitor": {
@ -290,11 +289,11 @@
}
},
"@babel/helper-get-function-arity": {
"version": "7.10.4",
"resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.10.4.tgz",
"integrity": "sha512-EkN3YDB+SRDgiIUnNgcmiD361ti+AVbL3f3Henf6dqqUyr5dMsorno0lJWJuLhDhkI5sYEpgj6y9kB8AOU1I2A==",
"version": "7.12.10",
"resolved": "https://registry.npmjs.org/@babel/helper-get-function-arity/-/helper-get-function-arity-7.12.10.tgz",
"integrity": "sha512-mm0n5BPjR06wh9mPQaDdXWDoll/j5UpCAPl1x8fS71GHm7HA6Ua2V4ylG1Ju8lvcTOietbPNNPaSilKj+pj+Ag==",
"requires": {
"@babel/types": "^7.10.4"
"@babel/types": "^7.12.10"
}
},
"@babel/helper-hoist-variables": {
@ -338,11 +337,11 @@
}
},
"@babel/helper-optimise-call-expression": {
"version": "7.12.7",
"resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.12.7.tgz",
"integrity": "sha512-I5xc9oSJ2h59OwyUqjv95HRyzxj53DAubUERgQMrpcCEYQyToeHA+NEcUEsVWB4j53RDeskeBJ0SgRAYHDBckw==",
"version": "7.12.10",
"resolved": "https://registry.npmjs.org/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.12.10.tgz",
"integrity": "sha512-4tpbU0SrSTjjt65UMWSrUOPZTsgvPgGG4S8QSTNHacKzpS51IVWGDj0yCwyeZND/i+LSN2g/O63jEXEWm49sYQ==",
"requires": {
"@babel/types": "^7.12.7"
"@babel/types": "^7.12.10"
}
},
"@babel/helper-plugin-utils": {
@ -437,9 +436,9 @@
}
},
"@babel/parser": {
"version": "7.12.7",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.12.7.tgz",
"integrity": "sha512-oWR02Ubp4xTLCAqPRiNIuMVgNO5Aif/xpXtabhzW2HWUD47XJsAB4Zd/Rg30+XeQA3juXigV7hlquOTmwqLiwg=="
"version": "7.12.10",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.12.10.tgz",
"integrity": "sha512-PJdRPwyoOqFAWfLytxrWwGrAxghCgh/yTNCYciOz8QgjflA7aZhECPZAa2VUedKg2+QMWkI0L9lynh2SNmNEgA=="
},
"@babel/plugin-proposal-async-generator-functions": {
"version": "7.12.1",
@ -907,13 +906,12 @@
}
},
"@babel/plugin-transform-runtime": {
"version": "7.12.1",
"resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.12.1.tgz",
"integrity": "sha512-Ac/H6G9FEIkS2tXsZjL4RAdS3L3WHxci0usAnz7laPWUmFiGtj7tIASChqKZMHTSQTQY6xDbOq+V1/vIq3QrWg==",
"version": "7.12.10",
"resolved": "https://registry.npmjs.org/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.12.10.tgz",
"integrity": "sha512-xOrUfzPxw7+WDm9igMgQCbO3cJKymX7dFdsgRr1eu9n3KjjyU4pptIXbXPseQDquw+W+RuJEJMHKHNsPNNm3CA==",
"requires": {
"@babel/helper-module-imports": "^7.12.1",
"@babel/helper-module-imports": "^7.12.5",
"@babel/helper-plugin-utils": "^7.10.4",
"resolve": "^1.8.1",
"semver": "^5.5.1"
},
"dependencies": {
@ -958,9 +956,9 @@
}
},
"@babel/plugin-transform-typeof-symbol": {
"version": "7.12.1",
"resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.12.1.tgz",
"integrity": "sha512-EPGgpGy+O5Kg5pJFNDKuxt9RdmTgj5sgrus2XVeMp/ZIbOESadgILUbm50SNpghOh3/6yrbsH+NB5+WJTmsA7Q==",
"version": "7.12.10",
"resolved": "https://registry.npmjs.org/@babel/plugin-transform-typeof-symbol/-/plugin-transform-typeof-symbol-7.12.10.tgz",
"integrity": "sha512-JQ6H8Rnsogh//ijxspCjc21YPd3VLVoYtAwv3zQmqAt8YGYUtdo5usNhdl4b9/Vir2kPFZl6n1h0PfUz4hJhaA==",
"requires": {
"@babel/helper-plugin-utils": "^7.10.4"
}
@ -983,9 +981,9 @@
}
},
"@babel/preset-env": {
"version": "7.12.7",
"resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.12.7.tgz",
"integrity": "sha512-OnNdfAr1FUQg7ksb7bmbKoby4qFOHw6DKWWUNB9KqnnCldxhxJlP+21dpyaWFmf2h0rTbOkXJtAGevY3XW1eew==",
"version": "7.12.10",
"resolved": "https://registry.npmjs.org/@babel/preset-env/-/preset-env-7.12.10.tgz",
"integrity": "sha512-Gz9hnBT/tGeTE2DBNDkD7BiWRELZt+8lSysHuDwmYXUIvtwZl0zI+D6mZgXZX0u8YBlLS4tmai9ONNY9tjRgRA==",
"requires": {
"@babel/compat-data": "^7.12.7",
"@babel/helper-compilation-targets": "^7.12.5",
@ -1046,12 +1044,12 @@
"@babel/plugin-transform-spread": "^7.12.1",
"@babel/plugin-transform-sticky-regex": "^7.12.7",
"@babel/plugin-transform-template-literals": "^7.12.1",
"@babel/plugin-transform-typeof-symbol": "^7.12.1",
"@babel/plugin-transform-typeof-symbol": "^7.12.10",
"@babel/plugin-transform-unicode-escapes": "^7.12.1",
"@babel/plugin-transform-unicode-regex": "^7.12.1",
"@babel/preset-modules": "^0.1.3",
"@babel/types": "^7.12.7",
"core-js-compat": "^3.7.0",
"@babel/types": "^7.12.10",
"core-js-compat": "^3.8.0",
"semver": "^5.5.0"
},
"dependencies": {
@ -1100,16 +1098,16 @@
}
},
"@babel/traverse": {
"version": "7.12.9",
"resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.12.9.tgz",
"integrity": "sha512-iX9ajqnLdoU1s1nHt36JDI9KG4k+vmI8WgjK5d+aDTwQbL2fUnzedNedssA645Ede3PM2ma1n8Q4h2ohwXgMXw==",
"version": "7.12.10",
"resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.12.10.tgz",
"integrity": "sha512-6aEtf0IeRgbYWzta29lePeYSk+YAFIC3kyqESeft8o5CkFlYIMX+EQDDWEiAQ9LHOA3d0oHdgrSsID/CKqXJlg==",
"requires": {
"@babel/code-frame": "^7.10.4",
"@babel/generator": "^7.12.5",
"@babel/generator": "^7.12.10",
"@babel/helper-function-name": "^7.10.4",
"@babel/helper-split-export-declaration": "^7.11.0",
"@babel/parser": "^7.12.7",
"@babel/types": "^7.12.7",
"@babel/parser": "^7.12.10",
"@babel/types": "^7.12.10",
"debug": "^4.1.0",
"globals": "^11.1.0",
"lodash": "^4.17.19"
@ -1131,9 +1129,9 @@
}
},
"@babel/types": {
"version": "7.12.7",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.12.7.tgz",
"integrity": "sha512-MNyI92qZq6jrQkXvtIiykvl4WtoRrVV9MPn+ZfsoEENjiWcBQ3ZSHrkxnJWgWtLX3XXqX5hrSQ+X69wkmesXuQ==",
"version": "7.12.10",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.12.10.tgz",
"integrity": "sha512-sf6wboJV5mGyip2hIpDSKsr80RszPinEFjsHTalMxZAZkoQ2/2yQzxlcFN52SJqsyPfLtPmenL4g2KB3KJXPDw==",
"requires": {
"@babel/helper-validator-identifier": "^7.10.4",
"lodash": "^4.17.19",
@ -1253,9 +1251,9 @@
"integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA=="
},
"@types/node": {
"version": "14.14.10",
"resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.10.tgz",
"integrity": "sha512-J32dgx2hw8vXrSbu4ZlVhn1Nm3GbeCFNw2FWL8S5QKucHGY0cyNwjdQdO+KMBZ4wpmC7KhLCiNsdk1RFRIYUQQ=="
"version": "14.14.12",
"resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.12.tgz",
"integrity": "sha512-ASH8OPHMNlkdjrEdmoILmzFfsJICvhBsFfAum4aKZ/9U4B6M6tTmTPh+f3ttWdD74CEGV5XvXWkbyfSdXaTd7g=="
},
"@types/q": {
"version": "1.5.4",
@ -1273,12 +1271,13 @@
"integrity": "sha512-1+7CwjQ0Kasml6rHoNQUmbISwqLNNfFVBUcZl6QBremUl296ZmLrVQPqJP5pyAAWjZke5bpI1hlj+LVVuT7Jcg=="
},
"@vue/babel-plugin-jsx": {
"version": "1.0.0-rc.3",
"resolved": "https://registry.npmjs.org/@vue/babel-plugin-jsx/-/babel-plugin-jsx-1.0.0-rc.3.tgz",
"integrity": "sha512-/Ibq0hoKsidnHWPhgRpjcjYhYcHpqEm2fiKVAPO88OXZNHGwaGgS4yXkC6TDEvlZep4mBDo+2S5T81wpbVh90Q==",
"version": "1.0.0-rc.4",
"resolved": "https://registry.npmjs.org/@vue/babel-plugin-jsx/-/babel-plugin-jsx-1.0.0-rc.4.tgz",
"integrity": "sha512-ifzYc0jfLqiQebfqzKrJGfmQFE1lIgFlE9Ive8hQMJS/GC9Y+mNtHpqmWyqljbFGsqmsxmMRNFdAUgz0HZN1rg==",
"requires": {
"@babel/helper-module-imports": "^7.0.0",
"@babel/plugin-syntax-jsx": "^7.0.0",
"@babel/template": "^7.0.0",
"@babel/traverse": "^7.0.0",
"@babel/types": "^7.0.0",
"@vue/babel-helper-vue-transform-on": "^1.0.0-rc.2",
@ -2554,13 +2553,13 @@
}
},
"browserslist": {
"version": "4.15.0",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.15.0.tgz",
"integrity": "sha512-IJ1iysdMkGmjjYeRlDU8PQejVwxvVO5QOfXH7ylW31GO6LwNRSmm/SgRXtNsEXqMLl2e+2H5eEJ7sfynF8TCaQ==",
"version": "4.16.0",
"resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.16.0.tgz",
"integrity": "sha512-/j6k8R0p3nxOC6kx5JGAxsnhc9ixaWJfYc+TNTzxg6+ARaESAvQGV7h0uNOB4t+pLQJZWzcrMxXOxjgsCj3dqQ==",
"requires": {
"caniuse-lite": "^1.0.30001164",
"caniuse-lite": "^1.0.30001165",
"colorette": "^1.2.1",
"electron-to-chromium": "^1.3.612",
"electron-to-chromium": "^1.3.621",
"escalade": "^3.1.1",
"node-releases": "^1.1.67"
}
@ -4182,9 +4181,9 @@
"integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0="
},
"electron-to-chromium": {
"version": "1.3.616",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.616.tgz",
"integrity": "sha512-CI8L38UN2BEnqXw3/oRIQTmde0LiSeqWSRlPA42ZTYgJQ8fYenzAM2Z3ni+jtILTcrs5aiXZCGJ96Pm+3/yGyQ=="
"version": "1.3.621",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.621.tgz",
"integrity": "sha512-FeIuBzArONbAmKmZIsZIFGu/Gc9AVGlVeVbhCq+G2YIl6QkT0TDn2HKN/FMf1btXEB9kEmIuQf3/lBTVAbmFOg=="
},
"elliptic": {
"version": "6.5.3",
@ -5576,9 +5575,9 @@
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
},
"ini": {
"version": "1.3.5",
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.5.tgz",
"integrity": "sha512-RZY5huIKCMRWDUqZlEi72f/lmXKMvuszcMBduliQ3nnWbx9X/ZBQO7DijMEYS9EhHBb2qacRUMtC7svLwe0lcw=="
"version": "1.3.7",
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.7.tgz",
"integrity": "sha512-iKpRpXP+CrP2jyrxvg1kMUpXDyRUFDWurxbnVT1vQPx+Wz9uCYsMIqYuSBLV+PAaZG/d7kRLKRFc9oDMsH+mFQ=="
},
"internal-ip": {
"version": "4.3.0",
@ -5961,9 +5960,9 @@
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="
},
"js-yaml": {
"version": "3.14.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.0.tgz",
"integrity": "sha512-/4IbIeHcD9VMHFqDR/gQ7EdZdLimOvW2DdcxFjdyyZ9NsbS+ccrXqVWDtab/lRl5AlUqmpBx8EhPaWR+OtY17A==",
"version": "3.14.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz",
"integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==",
"requires": {
"argparse": "^1.0.7",
"esprima": "^4.0.0"
@ -6256,12 +6255,12 @@
}
},
"markdown-it": {
"version": "12.0.2",
"resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-12.0.2.tgz",
"integrity": "sha512-4Lkvjbv2kK+moL9TbeV+6/NHx+1Q+R/NIdUlFlkqkkzUcTod4uiyTJRiBidKR9qXSdkNFkgv+AELY8KN9vSgVA==",
"version": "12.0.3",
"resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-12.0.3.tgz",
"integrity": "sha512-M57RsMv+QQmJHz1yCu0gTJRMx/LlxRPtrrw+2kb/CpDVK/graCmWO0qfNnz/SE1FCNdyq3pkMMZ+itTnyT/YGA==",
"requires": {
"argparse": "^2.0.1",
"entities": "~2.0.0",
"entities": "~2.1.0",
"linkify-it": "^3.0.1",
"mdurl": "^1.0.1",
"uc.micro": "^1.0.5"
@ -6272,11 +6271,6 @@
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="
},
"entities": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/entities/-/entities-2.0.3.tgz",
"integrity": "sha512-MyoZ0jgnLvB2X3Lg5HqpFmn1kybDiIfEQmKzTb5apr51Rb+T3KdmMiqa70T+bhGnyv7bQ6WMj2QMHpGMmlrUYQ=="
},
"linkify-it": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-3.0.2.tgz",
@ -7271,9 +7265,9 @@
}
},
"ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
}
}
},
@ -8020,9 +8014,9 @@
}
},
"pug-plain-loader": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/pug-plain-loader/-/pug-plain-loader-1.0.0.tgz",
"integrity": "sha512-mDfq/qvJJ0xdug38mZ1ObW0BQTx9kAHnKqotXC+C00XQkKmsWaMe90JUg/kN4lS6MU7tpVsMZ+rmcnBSPfDtHA==",
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/pug-plain-loader/-/pug-plain-loader-1.1.0.tgz",
"integrity": "sha512-1nYgIJLaahRuHJHhzSPODV44aZfb00bO7kiJiMkke6Hj4SVZftuvx6shZ4BOokk50dJc2RSFqNUBOlus0dniFQ==",
"requires": {
"loader-utils": "^1.1.0"
}
@ -8948,9 +8942,9 @@
}
},
"ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
}
}
},
@ -10385,6 +10379,11 @@
"markdown-it-container": "^2.0.0"
}
},
"vuepress-plugin-google-tag-manager": {
"version": "0.0.5",
"resolved": "https://registry.npmjs.org/vuepress-plugin-google-tag-manager/-/vuepress-plugin-google-tag-manager-0.0.5.tgz",
"integrity": "sha512-Hm1GNDdNmc4Vs9c3OMfTtHicB/oZWNCmzMFPdlOObVN1OjizIjImdm+LZIwiVKVndT2TQ4BPhMx7HQkovmD2Lg=="
},
"vuepress-plugin-sitemap": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/vuepress-plugin-sitemap/-/vuepress-plugin-sitemap-2.3.1.tgz",
@ -10402,9 +10401,9 @@
}
},
"vuepress-theme-cosmos": {
"version": "1.0.178",
"resolved": "https://registry.npmjs.org/vuepress-theme-cosmos/-/vuepress-theme-cosmos-1.0.178.tgz",
"integrity": "sha512-RkCO3BbS9WuS4VwZtu2e2EHJIHpP6dwyKr3OYbFvdBLwybk64TKHf3gwOiQ8Vfpm5pij5YCd0WKGQOHU8duMKQ==",
"version": "1.0.179",
"resolved": "https://registry.npmjs.org/vuepress-theme-cosmos/-/vuepress-theme-cosmos-1.0.179.tgz",
"integrity": "sha512-BJw/SGn7AmvaSU5Rw74BIRuAkmVZMuf1Gd1++7vpPudgNHEmWSKOHULpIdtkzn1WPXF8sgf4hZQ7+PhESk7JUQ==",
"requires": {
"@cosmos-ui/vue": "^0.35.0",
"@vuepress/plugin-google-analytics": "1.7.1",
@ -10427,6 +10426,7 @@
"tiny-cookie": "^2.3.2",
"v-runtime-template": "^1.10.0",
"vuepress": "^1.5.4",
"vuepress-plugin-google-tag-manager": "0.0.5",
"vuepress-plugin-sitemap": "^2.3.1"
}
},

View File

@ -14,6 +14,6 @@
"author": "",
"license": "ISC",
"dependencies": {
"vuepress-theme-cosmos": "^1.0.178"
"vuepress-theme-cosmos": "^1.0.179"
}
}

105
docs/protodoc-markdown.tmpl Normal file
View File

@ -0,0 +1,105 @@
<!-- This file is auto-generated. Please do not modify it yourself. -->
# Protobuf Documentation
<a name="top"></a>
## Table of Contents
{{range .Files}}
{{$file_name := .Name}}- [{{.Name}}](#{{.Name}})
{{- if .Messages }}
{{range .Messages}} - [{{.LongName}}](#{{.FullName}})
{{end}}
{{- end -}}
{{- if .Enums }}
{{range .Enums}} - [{{.LongName}}](#{{.FullName}})
{{end}}
{{- end -}}
{{- if .Extensions }}
{{range .Extensions}} - [File-level Extensions](#{{$file_name}}-extensions)
{{end}}
{{- end -}}
{{- if .Services }}
{{range .Services}} - [{{.Name}}](#{{.FullName}})
{{end}}
{{- end -}}
{{end}}
- [Scalar Value Types](#scalar-value-types)
{{range .Files}}
{{$file_name := .Name}}
<a name="{{.Name}}"></a>
<p align="right"><a href="#top">Top</a></p>
## {{.Name}}
{{.Description}}
{{range .Messages}}
<a name="{{.FullName}}"></a>
### {{.LongName}}
{{.Description}}
{{if .HasFields}}
| Field | Type | Label | Description |
| ----- | ---- | ----- | ----------- |
{{range .Fields -}}
| `{{.Name}}` | [{{.LongType}}](#{{.FullType}}) | {{.Label}} | {{if (index .Options "deprecated"|default false)}}**Deprecated.** {{end}}{{nobr .Description}}{{if .DefaultValue}} Default: {{.DefaultValue}}{{end}} |
{{end}}
{{end}}
{{if .HasExtensions}}
| Extension | Type | Base | Number | Description |
| --------- | ---- | ---- | ------ | ----------- |
{{range .Extensions -}}
| `{{.Name}}` | {{.LongType}} | {{.ContainingLongType}} | {{.Number}} | {{nobr .Description}}{{if .DefaultValue}} Default: {{.DefaultValue}}{{end}} |
{{end}}
{{end}}
{{end}} <!-- end messages -->
{{range .Enums}}
<a name="{{.FullName}}"></a>
### {{.LongName}}
{{.Description}}
| Name | Number | Description |
| ---- | ------ | ----------- |
{{range .Values -}}
| {{.Name}} | {{.Number}} | {{nobr .Description}} |
{{end}}
{{end}} <!-- end enums -->
{{if .HasExtensions}}
<a name="{{$file_name}}-extensions"></a>
### File-level Extensions
| Extension | Type | Base | Number | Description |
| --------- | ---- | ---- | ------ | ----------- |
{{range .Extensions -}}
| `{{.Name}}` | {{.LongType}} | {{.ContainingLongType}} | {{.Number}} | {{nobr .Description}}{{if .DefaultValue}} Default: `{{.DefaultValue}}`{{end}} |
{{end}}
{{end}} <!-- end HasExtensions -->
{{range .Services}}
<a name="{{.FullName}}"></a>
### {{.Name}}
{{.Description}}
| Method Name | Request Type | Response Type | Description | HTTP Verb | Endpoint |
| ----------- | ------------ | ------------- | ------------| ------- | -------- |
{{range .Methods -}}
| `{{.Name}}` | [{{.RequestLongType}}](#{{.RequestFullType}}){{if .RequestStreaming}} stream{{end}} | [{{.ResponseLongType}}](#{{.ResponseFullType}}){{if .ResponseStreaming}} stream{{end}} | {{nobr .Description}} | {{with (index .Options "google.api.http")}}{{range .Rules}}{{.Method}}|{{.Pattern}}{{end}}{{end}}|
{{end}}
{{end}} <!-- end services -->
{{end}}
## Scalar Value Types
| .proto Type | Notes | C++ | Java | Python | Go | C# | PHP | Ruby |
| ----------- | ----- | --- | ---- | ------ | -- | -- | --- | ---- |
{{range .Scalars -}}
| <a name="{{.ProtoType}}" /> {{.ProtoType}} | {{.Notes}} | {{.CppType}} | {{.JavaType}} | {{.PythonType}} | {{.GoType}} | {{.CSharp}} | {{.PhpType}} | {{.RubyType}} |
{{end}}

View File

@ -4,10 +4,11 @@ parent:
order: 5
-->
# Running a Node
# Running a Node, API and CLI
This folder contains documentation on how to run a node and interact with it.
1. [Setting up the keyring](./keyring.md)
2. [Running a Node](./run-node.md)
3. [Interacting with a Node](./interact-node.md)
1. [Running a Node](./run-node.md)
1. [Interacting with a Node](./interact-node.md)
1. [Generating, Signing and Broadcasting Transactions](./txs.md)

View File

@ -4,11 +4,14 @@ order: 3
# Interacting with the Node
There are multiple ways to interact with a node: using the CLI, using gRPC or using the REST endpoints. {synopsis}
## Pre-requisite Readings
- [gRPC, REST and Tendermint Endpoints](../core/grpc_rest.md) {prereq}
- [Running a Node](./run-node.md) {prereq}
## Via CLI
## Using the CLI
Now that your chain is running, it is time to try sending tokens from the first account you created to a second account. In a new terminal window, start by running the following query command:
@ -28,7 +31,7 @@ RECIPIENT=$(simd keys show recipient -a --keyring-backend test)
The command above creates a local key-pair that is not yet registered on the chain. An account is created the first time it receives tokens from another account. Now, run the following command to send tokens to the `recipient` account:
```bash
simd tx send $MY_VALIDATOR_ADDRESS $RECIPIENT 1000stake --chain-id my-test-chain
simd tx bank send $MY_VALIDATOR_ADDRESS $RECIPIENT 1000stake --chain-id my-test-chain
# Check that the recipient account did receive the tokens.
simd query account $RECIPIENT --chain-id my-test-chain
@ -44,3 +47,192 @@ simd query staking delegations-to $(simd keys show my_validator --bech val -a --
```
You should see two delegations, the first one made from the `gentx`, and the second one you just performed from the `recipient` account.
## Using gRPC
The Protobuf ecosystem developed tools for different use cases, including code-generation from `*.proto` files into various languages. These tools allow to build clients easily. Often, the client connection (i.e. the transport) can be plugged and replaced very easily. Let's explore one of the most popular transport: [gRPC](../core/grpc_rest.md).
Since the code generation library largely depends on your own tech stack, we will only present three alternatives:
- `grpcurl` for generic debugging and testing,
- programmatically via Go,
- CosmJS for JavaScript/TypeScript developers.
### grpcurl
[grpcurl])https://github.com/fullstorydev/grpcurl is like `curl` but for gRPC. It is also available as a Go library, but we will use it only as a CLI command for debugging and testing purposes. Follow the instructions in the previous link to install it.
Assuming you have a local node running (either a localnet, or connected a live network), you should be able to run the following command to list the Protobuf services available (you can replace `localhost:9000` by the gRPC server endpoint of another node, which is configured under the `grpc.address` field inside `app.toml`):
```bash
grpcurl -plaintext localhost:9090 list
```
You should see a list of gRPC services, like `cosmos.bank.v1beta1.Query`. This is called reflection, which is a Protobuf endpoint returning a description of all available endpoints. Each of these represents a different Protobuf service, and each service exposes multiple RPC methods you can query against.
In the Cosmos SDK, we use [gogoprotobuf](https://github.com/gogo/protobuf) for code generation, and [grpc-go](https://github.com/grpc/grpc-go) for creating the gRPC server. Unfortunately, these two don't play well together, and more in-depth reflection (such as using grpcurl's `describe`) is not possible. See [this issue](https://github.com/grpc/grpc-go/issues/1873) for more info.
Instead, we need to manually pass the reference to relevant `.proto` files. For example:
```bash
grpcurl \
-import-path ./proto \ # Import these proto files too
-import-path ./third_party/proto \ # Import these proto files too
-proto ./proto/cosmos/bank/v1beta1/query.proto \ # That's the proto file with the description of your service
localhost:9090 \
describe cosmos.bank.v1beta1.Query # Service we want to inspect
```
Once the Protobuf definitions are given, making a gRPC query is then straightforward, by calling the correct `Query` service RPC method, and by passing the request argument as data (`-d` flag):
```bash
grpcurl \
-plaintext
-import-path ./proto \
-import-path ./third_party/proto \
-proto ./proto/cosmos/bank/v1beta1/query.proto \
-d '{"address":"$MY_VALIDATOR"}' \
localhost:9090 \
cosmos.bank.v1beta1.Query/AllBalances
```
The list of all available gRPC query endpoints is [coming soon](https://github.com/cosmos/cosmos-sdk/issues/7786).
#### Query for historical state using grpcurl
You may also query for historical data by passing some [gRPC metadata](https://github.com/grpc/grpc-go/blob/master/Documentation/grpc-metadata.md) to the query: the `x-cosmos-block-height` metadata should contain the block to query. Using grpcurl as above, the command looks like:
```bash
grpcurl \
-plaintext
-import-path ./proto \
-import-path ./third_party/proto \
-proto ./proto/cosmos/bank/v1beta1/query.proto \
-H "x-cosmos-block-height: 279256" \
-d '{"address":"$MY_VALIDATOR"}' \
localhost:9090 \
cosmos.bank.v1beta1.Query/AllBalances
```
Assuming the state at that block has not yet been pruned by the node, this query should return a non-empty response.
### Programmatically via Go
The following snippet shows how to query the state using gRPC inside a Go program. The idea is to create a gRPC connection, and use the Protobuf-generated client code to query the gRPC server.
```go
import (
"context"
"fmt"
"google.golang.org/grpc"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/tx"
)
func queryState() error {
myAddress, err := sdk.AccAddressFromBech32("cosmos1...")
if err != nil {
return err
}
// Create a connection to the gRPC server.
grpcConn := grpc.Dial(
"127.0.0.1:9090", // Or your gRPC server address.
grpc.WithInsecure(), // The SDK doesn't support any transport security mechanism.
)
defer grpcConn.Close()
// This creates a gRPC client to query the x/bank service.
bankClient := banktypes.NewQueryClient(grpcConn)
bankRes, err := bankClient.Balance(
context.Background(),
&banktypes.QueryBalanceRequest{Address: myAddress, Denom: "atom"},
)
if err != nil {
return err
}
fmt.Println(bankRes.GetBalance()) // Prints the account balance
return nil
}
```
You can replace the query client (here we are using `x/bank`'s) with one generated from any other Protobuf service. The list of all available gRPC query endpoints is [coming soon](https://github.com/cosmos/cosmos-sdk/issues/7786).
#### Query for historical state using Go
Querying for historical blocks is done by adding the block height metadata in the gRPC request.
```go
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
grpctypes "github.com/cosmos/cosmos-sdk/types/grpc"
"github.com/cosmos/cosmos-sdk/types/tx"
)
func queryState() error {
// --snip--
var header metadata.MD
bankRes, err = bankClient.Balance(
metadata.AppendToOutgoingContext(context.Background(), grpctypes.GRPCBlockHeightHeader, "12"), // Add metadata to request
&banktypes.QueryBalanceRequest{Address: myAddress, Denom: denom},
grpc.Header(&header), // Retrieve header from response
)
if err != nil {
return err
}
blockHeight = header.Get(grpctypes.GRPCBlockHeightHeader)
fmt.Println(blockHeight) // Prints the block height (12)
return nil
}
```
### CosmJS
CosmJS documentation can be found at [https://cosmos.github.io/cosmjs](https://cosmos.github.io/cosmjs). As of January 2021, CosmJS documentation is still work in progress.
## Using the REST Endpoints
As described in the [gRPC guide](../core/grpc_rest.md), all gRPC services on the Cosmos SDK are made available for more convenient REST-based queries through gRPC-gateway. The format of the URL path is based on the Protobuf service method's full-qualified name, but may contain small customizations so that final URLs look more idiomatic. For example, the REST endpoint for the `cosmos.bank.v1beta1.Query/AllBalances` method is `GET /cosmos/bank/v1beta1/balances/{address}`. Request arguments are passed as query parameters.
As a concrete example, the `curl` command to make balances request is:
```bash
curl \
-X GET \
-H "Content-Type: application/json" \
http://localhost:1317/cosmos/bank/v1beta1/balances/$MY_VALIDATOR
```
Make sure to replace `localhost:1317` with the REST endpoint of your node, configured under the `api.address` field.
The list of all available REST endpoints is available as a Swagger specification file, it can be viewed at `localhost:1317/swagger`. Make sure that the `api.swagger` field is set to true in your `app.toml` file.
### Query for historical state using REST
Querying for historical state is done using the HTTP header `x-cosmos-block-height`. For example, a curl command would look like:
```bash
curl \
-X GET \
-H "Content-Type: application/json" \
-H "x-cosmos-block-height: 279256"
http://localhost:1317/cosmos/bank/v1beta1/balances/$MY_VALIDATOR
```
Assuming the state at that block has not yet been pruned by the node, this query should return a non-empty response.
## Next {hide}
Sending transactions using gRPC and REST requires some additional steps: generating the transaction, signing it, and finally broadcasting it. Read about [generating and signing transactions](./txs.md). {hide}

View File

@ -121,3 +121,7 @@ MY_VALIDATOR_ADDRESS=$(simd keys show my_validator -a --keyring-backend test)
This command generates a new 24-word mnemonic phrase, persists it to the relevant backend, and outputs information about the keypair. If this keypair will be used to hold value-bearing tokens, be sure to write down the mnemonic phrase somewhere safe!
By default, the keyring generates a `secp256k1` keypair. The keyring also supports `ed25519` keys, which may be created by passing the `--algo ed25519` flag. A keyring can of course hold both types of keys simultaneously, and the Cosmos SDK's `x/auth` module (in particular its [AnteHandlers](../core/baseapp.md#antehandler)) supports natively these two public key algorithms.
## Next {hide}
Read about [running a node](./run-node.md) {hide}

View File

@ -53,7 +53,7 @@ Now that your account has some tokens, you need to add a validator to your chain
```bash
# Create a gentx.
simd gentx my_validator --amount 100000stake --chain-id my-test-chain --keyring-backend test
simd gentx my_validator 100000stake --chain-id my-test-chain --keyring-backend test
# Add the gentx to the genesis file.
simd collect-gentxs

357
docs/run-node/txs.md Normal file
View File

@ -0,0 +1,357 @@
<!--
order: 4
-->
# Generating, Signing and Broadcasting Transactions
This document describes how to generate an (unsigned) transaction, signing it (with one or multiple keys), and broadcasting it to the network. {synopsis}
## Using the CLI
The easiest way to send transactions is using the CLI, as we have seen in the previous page when [interacting with a node](./interact-node.md#using-the-cli). For example, running the following command
```bash
simd tx bank send $MY_VALIDATOR_ADDRESS $RECIPIENT 1000stake --chain-id my-test-chain
```
will run the following steps:
- generate a transaction with one `Msg` (`x/bank`'s `MsgSend`), and print the generated transaction to the console.
- ask the user for confirmation to send the transaction from the `$MY_VALIDATOR_ADDRESS` account.
- fetch `$MY_VALIDATOR_ADDRESS` in the keyring. This is possible because we have [set up the CLI's keyring](./keyring.md) in a previous step.
- sign the generated transaction with the keyring's account.
- broadcast the signed transaction to the network. This is possible because the CLI connects to the node's Tendermint RPC endpoint.
The CLI bundles all the necessary steps into a simple-to-use user experience. However, it's possible to run all the steps individually too.
### Generating a Transaction
Generating a transaction can simply be done by appending the `--generate-only` flag on any `tx` command, e.g.:
```bash
simd tx bank send $MY_VALIDATOR_ADDRESS $RECIPIENT 1000stake --chain-id my-test-chain --generate-only
```
This will output the unsigned transaction as JSON in the console. We can also save the unsigned transaction to a file (to be passed around between signers more easily) by appending `> unsigned_tx.json` to the above command.
### Signing a Transaction
Signing a transaction using the CLI requires the unsigned transaction to be saved in a file. Let's assume the unsigned transaction is in a file called `unsigned_tx.json` in the current directory (see previous paragraph on how to do that). Then, simply run the following command:
```bash
simd tx sign unsigned_tx.json --chain-id my-test-chain --keyring-backend test --from $MY_VALIDATOR_ADDRESS
```
This command will decode the unsigned transaction and sign it with `SIGN_MODE_DIRECT` with `$MY_VALIDATOR_ADDRESS`'s key, which we already set up in the keyring. The signed transaction will be output as JSON to the console, and, as above, we can save it to a file by appending `> signed_tx.json`.
Some useful flags to consider in the `tx sign` command:
- `--sign-mode`: you may use `amino-json` to sign the transaction using `SIGN_MODE_LEGACY_AMINO_JSON`,
- `--offline`: sign in offline mode. This means that the `tx sign` command doesn't connect to the node to retrieve the signer's account number and sequence, both needed for signing. In this case, you must manually supply the `--account-number` and `--sequence` flags. This is useful for offline signing, i.e. signing in a secure environment which doesn't have access to the internet.
#### Signing with Multiple Signers
::: warning
Please note that signing a transaction with multiple signers or with a multisig account, where at least one signer uses `SIGN_MODE_DIRECT`, is not possible as of yet. You may follow [this Github issue](https://github.com/cosmos/cosmos-sdk/issues/8141) for more info.
:::
Signing with multiple signers is done with the `tx multisign` command. This command assumes that all signers use `SIGN_MODE_LEGACY_AMINO_JSON`. The flow is similar to the `tx sign` command flow, but instead of signing an unsigned transaction file, each signer signs the file signed by previous signer(s). The `tx multisign` command will append signatures to the existing transactions. It is important that signers sign the transaction **in the same order** as given by the transaction, which is retrievable using the `GetSigners()` method.
For example, starting with the `unsigned_tx.json`, and assuming the transaction has 4 signers, we would run:
```bash
# Let signer 1 sign the unsigned tx.
simd tx multisignsign unsigned_tx.json signer_key_1 --chain-id my-test-chain --keyring-backend test > partial_tx_1.json
# Signer 2 appends their signature.
simd tx multisignsign partial_tx_1.json signer_key_2 --chain-id my-test-chain --keyring-backend test > partial_tx_2.json
# Signer 3 appends their signature.
simd tx multisignsign partial_tx_2.json signer_key_3 --chain-id my-test-chain --keyring-backend test > partial_tx_3.json
# Signer 4 appends their signature. The final output is the fully signed tx.
simd tx multisignsign partial_tx_3.json signer_key_4 --chain-id my-test-chain --keyring-backend test > signed_tx.json
```
### Broadcasting a Transaction
Broadcasting a transaction is done using the following command:
```bash
simd tx broadcast tx_signed.json
```
You may optionally pass the `--broadcast-mode` flag to specify which response to receive from the node:
- `block`: the CLI waits for the tx to be committed in a block.
- `sync`: the CLI waits for a CheckTx execution response only.
- `async`: the CLI returns immediately (transaction might fail).
## Programmatically with Go
It is possible to manipulate transactions programmatically via Go using the Cosmos SDK's `TxBuilder` interface.
### Generating a Transaction
Before generating a transaction, a new instance of a `TxBuilder` needs to be created. Since the SDK supports both Amino and Protobuf transactions, the first step would be to decide which encoding scheme to use. All the subsequent steps remain unchanged, whether you're using Amino or Protobuf, as `TxBuilder` abstracts the encoding mechanisms. In the following snippet, we will use Protobuf.
```go
import (
"github.com/cosmos/cosmos-sdk/simapp"
)
func sendTx() error {
// Choose your codec: Amino or Protobuf. Here, we use Protobuf, given by the
// following function.
encCfg := simapp.MakeTestEncodingConfig()
// Create a new TxBuilder.
txBuilder := encCfg.TxConfig.NewTxBuilder()
// --snip--
}
```
We can also set up some keys and addresses that will send and receive the transactions. Here, for the purpose of the tutorial, we will be using some dummy data to create keys.
```go
import (
"github.com/cosmos/cosmos-sdk/testutil/testdata"
)
priv1, _, addr1 := testdata.KeyTestPubAddr()
priv2, _, addr2 := testdata.KeyTestPubAddr()
priv3, _, addr3 := testdata.KeyTestPubAddr()
```
Populating the `TxBuilder` can be done via its [methods](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/client/tx_config.go#L32-L45):
```go
import (
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
)
func sendTx() error {
// --snip--
// Define two x/bank MsgSend messages:
// - from addr1 to addr3,
// - from addr2 to addr3.
// This means that the transactions needs two signers: addr1 and addr2.
msg1 := banktypes.NewMsgSend(addr1, addr3, types.NewCoins(types.NewInt64Coin("atom", 12)))
msg2 := banktypes.NewMsgSend(addr2, addr3, types.NewCoins(types.NewInt64Coin("atom", 34)))
err := txBuilder.SetMsgs(msg1, msg2)
if err != nil {
return err
}
txBuilder.SetGasLimit(...)
txBuilder.SetFeeAmount(...)
txBuilder.SetMemo(...)
txBuilder.SetTimeoutHeight(...)
}
```
At this point, `TxBuilder`'s underlying transaction is ready to be signed.
### Signing a Transaction
We chose our encoding config to use Protobuf, which will use `SIGN_MODE_DIRECT` by default. As per [ADR-020](https://github.com/cosmos/cosmos-sdk/blob/v0.40.0-rc6/docs/architecture/adr-020-protobuf-transaction-encoding.md), each signer needs to sign the `SignerInfo`s of all other signers. This means that we need to perform two steps sequentially:
- for each signer, populate the signer's `SignerInfo` inside `TxBuilder`,
- once all `SignerInfo`s are populated, for each signer, sign the `SignDoc` (the payload to be signed).
In the current `TxBuilder`'s API, both steps are done using the same method: `SetSignatures()`. The current API requires us to first perform a round of `SetSignatures()` _with empty signatures_, only to populate `SignerInfo`s, and a second round of `SetSignatures()` to actually sign the correct payload.
```go
import (
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/types/tx/signing"
xauthsigning "github.com/cosmos/cosmos-sdk/x/auth/signing"
)
func sendTx() error {
// --snip--
privs := []cryptotypes.PrivKey{priv1, priv2}
accNums:= []uint64{..., ...} // The accounts' account numbers
accSeqs:= []uint64{..., ...} // The accounts' sequence numbers
// First round: we gather all the signer infos. We use the "set empty
// signature" hack to do that.
var sigsV2 []signing.SignatureV2
for i, priv := range privs {
sigV2 := signing.SignatureV2{
PubKey: priv.PubKey(),
Data: &signing.SingleSignatureData{
SignMode: encCfg.TxConfig.SignModeHandler().DefaultMode(),
Signature: nil,
},
Sequence: accSeqs[i],
}
sigsV2 = append(sigsV2, sigV2)
}
err := txBuilder.SetSignatures(sigsV2...)
if err != nil {
return err
}
// Second round: all signer infos are set, so each signer can sign.
sigsV2 = []signing.SignatureV2{}
for i, priv := range privs {
signerData := xauthsigning.SignerData{
ChainID: chainID,
AccountNumber: accNums[i],
Sequence: accSeqs[i],
}
sigV2, err := tx.SignWithPrivKey(
encCfg.TxConfig.SignModeHandler().DefaultMode(), signerData,
txBuilder, priv, encCfg.TxConfig, accSeqs[i])
if err != nil {
return nil, err
}
sigsV2 = append(sigsV2, sigV2)
}
err = txBuilder.SetSignatures(sigsV2...)
if err != nil {
return err
}
}
```
The `TxBuilder` is now correctly populated. To print it, you can use the `TxConfig` interface from the initial encoding config `encCfg`:
```go
func sendTx() error {
// --snip--
// Generated Protobuf-encoded bytes.
txBytes, err := encCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
if err != nil {
return err
}
// Generate a JSON string.
txJSONBytes, err := encCfg.TxConfig.TxJSONEncoder()(txBuilder.GetTx())
if err != nil {
return err
}
txJSON := string(txJSONBytes)
}
```
### Broadcasting a Transaction
The preferred way to broadcast a transaction is to use gRPC, though using REST (via `gRPC-gateway`) or the Tendermint RPC is also posible. An overview of the differences between these methods is exposed [here](../core/grpc_rest.md). For this tutorial, we will only describe the gRPC method.
```go
import (
"context"
"fmt"
"google.golang.org/grpc"
"github.com/cosmos/cosmos-sdk/types/tx"
)
func sendTx() error {
// --snip--
// Create a connection to the gRPC server.
grpcConn := grpc.Dial(
"127.0.0.1:9090", // Or your gRPC server address.
grpc.WithInsecure(), // The SDK doesn't support any transport security mechanism.
)
defer grpcConn.Close()
// Broadcast the tx via gRPC. We create a new client for the Protobuf Tx
// service.
txClient := tx.NewServiceClient(grpcConn)
// We then call the BroadcastTx method on this client.
grpcRes, err := txClient.BroadcastTx(
context.Background(),
&tx.BroadcastTxRequest{
Mode: tx.BroadcastMode_BROADCAST_MODE_SYNC,
TxBytes: txBytes, // Proto-binary of the signed transaction, see previous step.
},
)
if err != nil {
return err
}
fmt.Println(grpcRes.TxResponse.Code) // Should be `0` if the tx is successful
return nil
}
```
#### Simulating a Transaction
Before broadcasting a transaction, we sometimes may want to dry-run the transaction, to estimate some information about the transaction without actually committing it. This is called simulating a transaction, and can be done as follows:
```go
import (
"context"
"fmt"
"testing"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/types/tx"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
)
func simulateTx() error {
// --snip--
// Simulate the tx via gRPC. We create a new client for the Protobuf Tx
// service.
txClient := tx.NewServiceClient(grpcConn)
// We then call the BroadcastTx method on this client.
protoTx := txBuilderToProtoTx(txBuilder)
if err != nil {
return err
}
grpcRes, err := txClient.Simulate(
context.Background(),
&tx.SimulateRequest{
Tx: protoTx,
},
)
if err != nil {
return err
}
fmt.Println(grpcRes.GasInfo) // Prints estimated gas used.
return nil
}
// txBuilderToProtoTx converts a txBuilder into a proto tx.Tx.
func txBuilderToProtoTx(txBuilder client.TxBuilder) (*tx.Tx, error) { // nolint
protoProvider, ok := txBuilder.(authtx.ProtoTxProvider)
if !ok {
return nil, fmt.Errorf("expected proto tx builder, got %T", txBuilder)
}
return protoProvider.GetProtoTx(), nil
}
```
## Using REST
It is not possible to generate or sign a transaction using REST, only to broadcast one.
### Broadcasting a Transaction
Broadcasting a transaction using the REST endpoint (served by `gRPC-gateway`) can be done by sending a POST request as follows, where the `txBytes` are the protobuf-encoded bytes of a signed transaction:
```bash
curl -X POST \
-H "Content-Type: application/json"
-d'{"tx_bytes":"{{txBytes}}","mode":"BROADCAST_MODE_SYNC"}'
localhost:1317/cosmos/tx/v1beta1/txs
```
## Using CosmJS (JavaScript & TypeScript)
CosmJS aims to build client libraries in JavaScript that can be embedded in web applications. Please see [https://cosmos.github.io/cosmjs](https://cosmos.github.io/cosmjs) for more information. As of January 2021, CosmJS documentation is still work in progress.

View File

@ -103,7 +103,7 @@ rm -rf $HOME/.simapp
./build/simd keys --keyring-backend=test add validator
./build/simd init testing --chain-id test
./build/simd add-genesis-account --keyring-backend=test $(./build/simd keys --keyring-backend=test show validator -a) 1000000000stake,1000000000validatortoken
./build/simd gentx --keyring-backend test --chain-id test validator
./build/simd gentx --keyring-backend test --chain-id test validator 100000stake
./build/simd collect-gentxs
```

View File

@ -1,2 +1,3 @@
master master
launchpad/backports v0.39
release/v0.40.x v0.40

20
go.mod
View File

@ -5,19 +5,19 @@ module github.com/cosmos/cosmos-sdk
require (
github.com/99designs/keyring v1.1.6
github.com/DataDog/zstd v1.4.5 // indirect
github.com/armon/go-metrics v0.3.4
github.com/armon/go-metrics v0.3.6
github.com/bgentry/speakeasy v0.1.0
github.com/btcsuite/btcd v0.21.0-beta
github.com/btcsuite/btcutil v1.0.2
github.com/confio/ics23/go v0.6.3
github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d
github.com/cosmos/iavl v0.15.0-rc5
github.com/cosmos/go-bip39 v1.0.0
github.com/cosmos/iavl v0.15.3
github.com/cosmos/ledger-cosmos-go v0.11.1
github.com/dgraph-io/ristretto v0.0.3 // indirect
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/enigmampc/btcutil v1.0.3-0.20200723161021-e2fb6adb2a25
github.com/gogo/gateway v1.1.0
github.com/gogo/protobuf v1.3.1
github.com/gogo/protobuf v1.3.2
github.com/golang/mock v1.4.4
github.com/golang/protobuf v1.4.3
github.com/golang/snappy v0.0.2 // indirect
@ -28,7 +28,7 @@ require (
github.com/hashicorp/golang-lru v0.5.4
github.com/magiconair/properties v1.8.4
github.com/mattn/go-isatty v0.0.12
github.com/otiai10/copy v1.2.0
github.com/otiai10/copy v1.4.2
github.com/pelletier/go-toml v1.8.0 // indirect
github.com/pkg/errors v0.9.1
github.com/prometheus/client_golang v1.8.0
@ -36,7 +36,7 @@ require (
github.com/rakyll/statik v0.1.7
github.com/regen-network/cosmos-proto v0.3.0
github.com/rs/zerolog v1.20.0
github.com/spf13/afero v1.2.2 // indirect
github.com/spf13/afero v1.3.4 // indirect
github.com/spf13/cast v1.3.1
github.com/spf13/cobra v1.1.1
github.com/spf13/jwalterweatherman v1.1.0 // indirect; indirects
@ -46,14 +46,14 @@ require (
github.com/tendermint/btcd v0.1.1
github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15
github.com/tendermint/go-amino v0.16.0
github.com/tendermint/tendermint v0.34.0
github.com/tendermint/tendermint v0.34.1
github.com/tendermint/tm-db v0.6.3
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad
golang.org/x/net v0.0.0-20200930145003-4acb6c075d10 // indirect
google.golang.org/genproto v0.0.0-20201111145450-ac7456db90a6
google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d
google.golang.org/grpc v1.33.2
google.golang.org/protobuf v1.25.0
gopkg.in/yaml.v2 v2.3.0
gopkg.in/yaml.v2 v2.4.0
)
replace github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.2-alpha.regen.4

46
go.sum
View File

@ -44,8 +44,8 @@ github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-metrics v0.3.4 h1:Xqf+7f2Vhl9tsqDYmXhnXInUdcrtgpRNpIA15/uldSc=
github.com/armon/go-metrics v0.3.4/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc=
github.com/armon/go-metrics v0.3.6 h1:x/tmtOF9cDBoXH7XoAGOz2qqm1DknFD1590XmD/DUJ8=
github.com/armon/go-metrics v0.3.6/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A=
github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU=
@ -101,11 +101,13 @@ github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d h1:49RLWk1j44Xu4fjHb6JFYmeUnDORVwHNkDxaQ0ctCVU=
github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y=
github.com/cosmos/go-bip39 v1.0.0 h1:pcomnQdrdH22njcAatO0yWojsUnCO3y2tNoV1cb6hHY=
github.com/cosmos/go-bip39 v1.0.0/go.mod h1:RNJv0H/pOIVgxw6KS7QeX2a0Uo0aKUlfhZ4xuwvCdJw=
github.com/cosmos/iavl v0.15.0-rc3.0.20201009144442-230e9bdf52cd/go.mod h1:3xOIaNNX19p0QrX0VqWa6voPRoJRGGYtny+DH8NEPvE=
github.com/cosmos/iavl v0.15.0-rc5 h1:AMKgaAjXwGANWv56NL4q4hV+a0puSkLYD6cCQAv3i44=
github.com/cosmos/iavl v0.15.0-rc5/go.mod h1:WqoPL9yPTQ85QBMT45OOUzPxG/U/JcJoN7uMjgxke/I=
github.com/cosmos/iavl v0.15.3 h1:xE9r6HW8GeKeoYJN4zefpljZ1oukVScP/7M8oj6SUts=
github.com/cosmos/iavl v0.15.3/go.mod h1:OLjQiAQ4fGD2KDZooyJG9yz+p2ao2IAYSbke8mVvSA4=
github.com/cosmos/ledger-cosmos-go v0.11.1 h1:9JIYsGnXP613pb2vPjFeMMjBI5lEDsEaF6oYorTy6J4=
github.com/cosmos/ledger-cosmos-go v0.11.1/go.mod h1:J8//BsAGTo3OC/vDLjMRFLW6q0WAaXvHnVc7ZmE8iUY=
github.com/cosmos/ledger-go v0.9.2 h1:Nnao/dLwaVTk1Q5U9THldpUMMXU94BOTWPddSmVB6pI=
@ -147,6 +149,7 @@ github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4s
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0 h1:EQciDnbrYxy13PgWoY8AqoxGiPrpgBZ1R8UNe3ddc+A=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/facebookgo/ensure v0.0.0-20160127193407-b4ab57deab51 h1:0JZ+dUmQeA8IIVUMzysrX4/AKuQwWhV2dYQuPZdvdSQ=
github.com/facebookgo/ensure v0.0.0-20160127193407-b4ab57deab51/go.mod h1:Yg+htXGokKKdzcwhuNDwVvN+uBxDGXJ7G/VN1d8fa64=
@ -228,6 +231,7 @@ github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OI
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
@ -324,6 +328,7 @@ github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6
github.com/kkdai/bstream v1.0.0/go.mod h1:FDnDOHt5Yx4p3FaHcioFT0QjDOtgUpvjeZqAs+NVZZA=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
@ -403,14 +408,14 @@ github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxS
github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw=
github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4=
github.com/otiai10/copy v1.2.0 h1:HvG945u96iNadPoG2/Ja2+AUJeW5YuFQMixq9yirC+k=
github.com/otiai10/copy v1.2.0/go.mod h1:rrF5dJ5F0t/EWSYODDu4j9/vEeYHMkc8jt0zJChqQWw=
github.com/otiai10/copy v1.4.2 h1:RTiz2sol3eoXPLF4o+YWqEybwfUa/Q2Nkc4ZIUs3fwI=
github.com/otiai10/copy v1.4.2/go.mod h1:XWfuS3CrI0R6IE0FbgHsEazaXO8G0LpMp9o8tos0x4E=
github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE=
github.com/otiai10/curr v1.0.0 h1:TJIWdbX0B+kpNagQrjgq8bCMrbhiuX73M2XwgtDMoOI=
github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs=
github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo=
github.com/otiai10/mint v1.3.1 h1:BCmzIS3n71sGfHB5NMNDB3lHYPz8fWSkCAErHed//qc=
github.com/otiai10/mint v1.3.1/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc=
github.com/otiai10/mint v1.3.2 h1:VYWnrP5fXmz1MXvjuUvcBrXSjGE6xjON+axB/UrpO3E=
github.com/otiai10/mint v1.3.2/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc=
github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY=
@ -429,6 +434,7 @@ github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA=
github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
@ -506,8 +512,8 @@ github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasO
github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI=
github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc=
github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk=
github.com/spf13/afero v1.3.4 h1:8q6vk3hthlpb2SouZcnBVKboxWQWMDNF38bwholZrJc=
github.com/spf13/afero v1.3.4/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I=
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
@ -556,6 +562,8 @@ github.com/tendermint/tendermint v0.34.0-rc4/go.mod h1:yotsojf2C1QBOw4dZrTcxbyxm
github.com/tendermint/tendermint v0.34.0-rc6/go.mod h1:ugzyZO5foutZImv0Iyx/gOFCX6mjJTgbLHTwi17VDVg=
github.com/tendermint/tendermint v0.34.0 h1:eXCfMgoqVSzrjzOj6clI9GAejcHH0LvOlRjpCmMJksU=
github.com/tendermint/tendermint v0.34.0/go.mod h1:Aj3PIipBFSNO21r+Lq3TtzQ+uKESxkbA3yo/INM4QwQ=
github.com/tendermint/tendermint v0.34.1 h1:TsJXY8+1NThc/XIENMv1ENzazriHBJJjeP6hN3kpC8g=
github.com/tendermint/tendermint v0.34.1/go.mod h1:Aj3PIipBFSNO21r+Lq3TtzQ+uKESxkbA3yo/INM4QwQ=
github.com/tendermint/tm-db v0.6.2/go.mod h1:GYtQ67SUvATOcoY8/+x6ylk8Qo02BQyLrAs+yAcLvGI=
github.com/tendermint/tm-db v0.6.3 h1:ZkhQcKnB8/2jr5EaZwGndN4owkPsGezW2fSisS9zGbg=
github.com/tendermint/tm-db v0.6.3/go.mod h1:lfA1dL9/Y/Y8wwyPp2NMLyn5P5Ptr/gvDFNWtrCWSf8=
@ -596,15 +604,20 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 h1:pLI5jrR7OSLijeIDcmRxNmw2api+jEfxLoykJVice/E=
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20201117144127-c1f2f97bffc9 h1:phUcVbl53swtrUN8kQEXFhUxPlIlWyBfKmidCu7P95o=
golang.org/x/crypto v0.0.0-20201117144127-c1f2f97bffc9/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY=
golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@ -690,6 +703,7 @@ golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@ -704,6 +718,8 @@ golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211 h1:9UQO31fZ+0aKQOFldThf7BKPMJTiBfWycGh/u3UoO88=
golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221 h1:/ZHdbVpdR/jk3g30/d4yUL0JU9kksj8+F/bnQUVLGDM=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
@ -770,8 +786,11 @@ google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfG
google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20201111145450-ac7456db90a6 h1:iRN4+t0lvZX/l9gH14ARF9i58tsVa5a97k6aH95rC3Y=
google.golang.org/genproto v0.0.0-20201111145450-ac7456db90a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20201119123407-9b1e624d6bc4 h1:Rt0FRalMgdSlXAVJvX4pr65KfqaxHXSLkSJRD9pw6g0=
google.golang.org/genproto v0.0.0-20201119123407-9b1e624d6bc4/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d h1:HV9Z9qMhQEsdlvxNFELgQ11RkMzO3CMkjEySjCtuLes=
google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.19.1/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
@ -828,8 +847,9 @@ gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

View File

@ -32,11 +32,11 @@ service Service {
// GetLatestValidatorSet queries latest validator-set.
rpc GetLatestValidatorSet(GetLatestValidatorSetRequest) returns (GetLatestValidatorSetResponse) {
option (google.api.http).get = "/cosmos/base/tendermint/v1beta1/validators/latest";
option (google.api.http).get = "/cosmos/base/tendermint/v1beta1/validatorsets/latest";
}
// GetValidatorSetByHeight queries validator-set at a given height.
rpc GetValidatorSetByHeight(GetValidatorSetByHeightRequest) returns (GetValidatorSetByHeightResponse) {
option (google.api.http).get = "/cosmos/base/tendermint/v1beta1/validators/{height}";
option (google.api.http).get = "/cosmos/base/tendermint/v1beta1/validatorsets/{height}";
}
}
@ -84,8 +84,8 @@ message GetBlockByHeightRequest {
// GetBlockByHeightResponse is the response type for the Query/GetBlockByHeight RPC method.
message GetBlockByHeightResponse {
tendermint.types.BlockID block_id = 1;
tendermint.types.Block block = 2;
.tendermint.types.BlockID block_id = 1;
.tendermint.types.Block block = 2;
}
// GetLatestBlockRequest is the request type for the Query/GetLatestBlock RPC method.
@ -93,8 +93,8 @@ message GetLatestBlockRequest {}
// GetLatestBlockResponse is the response type for the Query/GetLatestBlock RPC method.
message GetLatestBlockResponse {
tendermint.types.BlockID block_id = 1;
tendermint.types.Block block = 2;
.tendermint.types.BlockID block_id = 1;
.tendermint.types.Block block = 2;
}
// GetSyncingRequest is the request type for the Query/GetSyncing RPC method.
@ -110,8 +110,8 @@ message GetNodeInfoRequest {}
// GetNodeInfoResponse is the request type for the Query/GetNodeInfo RPC method.
message GetNodeInfoResponse {
tendermint.p2p.DefaultNodeInfo default_node_info = 1;
VersionInfo application_version = 2;
.tendermint.p2p.DefaultNodeInfo default_node_info = 1;
VersionInfo application_version = 2;
}
// VersionInfo is the type for the GetNodeInfoResponse message.
@ -133,4 +133,4 @@ message Module {
string version = 2;
// checksum
string sum = 3;
}
}

View File

@ -64,7 +64,6 @@ message MsgEditValidator {
// We pass a reference to the new commission rate and min self delegation as
// it's not mandatory to update. If not updated, the deserialized rate will be
// zero with no way to distinguish if an update was intended.
//
// REF: #2373
string commission_rate = 3 [
(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",

View File

@ -69,7 +69,6 @@ message TxBody {
// those messages define the number and order of elements in AuthInfo's
// signer_infos and Tx's signatures. Each required signer address is added to
// the list only the first time it occurs.
//
// By convention, the first required signer (usually from the first message)
// is referred to as the primary signer and pays the fee for the whole
// transaction.

View File

@ -40,7 +40,6 @@ message Plan {
// previous version of the chain.
// This will allow IBC connections to persist smoothly across planned chain upgrades
google.protobuf.Any upgraded_client_state = 5 [(gogoproto.moretags) = "yaml:\"upgraded_client_state\""];
;
}
// SoftwareUpgradeProposal is a gov Content type for initiating a software

View File

@ -7,14 +7,14 @@ proto_dirs=$(find ./proto -path -prune -o -name '*.proto' -print0 | xargs -0 -n1
for dir in $proto_dirs; do
# generate swagger files (filter query files)
query_file=$(find "${dir}" -maxdepth 1 -name 'query.proto')
query_file=$(find "${dir}" -maxdepth 1 \( -name 'query.proto' -o -name 'service.proto' \))
if [[ ! -z "$query_file" ]]; then
protoc \
buf protoc \
-I "proto" \
-I "third_party/proto" \
"$query_file" \
--swagger_out ./tmp-swagger-gen \
--swagger_opt logtostderr=true --swagger_opt fqn_for_swagger_name=true --swagger_opt simple_operation_ids=true
--swagger_out=./tmp-swagger-gen \
--swagger_opt=logtostderr=true --swagger_opt=fqn_for_swagger_name=true --swagger_opt=simple_operation_ids=true
fi
done

View File

@ -11,7 +11,12 @@ protoc_gen_gocosmos() {
go get github.com/regen-network/cosmos-proto/protoc-gen-gocosmos 2>/dev/null
}
protoc_gen_doc() {
go get -u github.com/pseudomuto/protoc-gen-doc/cmd/protoc-gen-doc 2>/dev/null
}
protoc_gen_gocosmos
protoc_gen_doc
proto_dirs=$(find ./proto -path -prune -o -name '*.proto' -print0 | xargs -0 -n1 dirname | sort | uniq)
for dir in $proto_dirs; do
@ -31,6 +36,15 @@ Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types:. \
done
# command to generate docs using protoc-gen-doc
buf protoc \
-I "proto" \
-I "third_party/proto" \
--doc_out=./docs/core \
--doc_opt=./docs/protodoc-markdown.tmpl,proto-docs.md \
$(find "$(pwd)/proto" -maxdepth 5 -name '*.proto')
go mod tidy
# generate codec/testdata proto code
buf protoc -I "proto" -I "third_party/proto" -I "testutil/testdata" --gocosmos_out=plugins=interfacetype+grpc,\
Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types:. ./testutil/testdata/*.proto

View File

@ -1,20 +1,21 @@
# Server
The `server` package is responsible for providing the mechanisms necessary to
start an ABCI Tendermint application and providing the CLI framework necessary
to fully bootstrap an application. The package exposes two core commands, `StartCmd`
and `ExportCmd`.
start an ABCI Tendermint application and provides the CLI framework (based on [cobra](github.com/spf13/cobra))
necessary to fully bootstrap an application. The package exposes two core functions: `StartCmd`
and `ExportCmd` which creates commands to start the application and export state respectively.
## Preliminary
The root command of an application typically is constructed with three core
sub-commands, query commands, tx commands, and auxiliary commands such as genesis
utilities, and starting an application binary.
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.
It is vital that the root command of an application set the appropriate `PersistentPreRun(E)`
function so all child commands have access to the server and client contexts.
It is vital that the root command of an application uses `PersistentPreRun()` cobra command
property for executing the command, so all child commands have access to the server and client contexts.
These contexts are set as their default values initially and maybe modified,
scoped to the command, in their respective `PersistentPreRun(E)` functions. Note,
scoped to the command, in their respective `PersistentPreRun()` functions. Note that
the `client.Context` is typically pre-populated with "default" values that may be
useful for all commands to inherit and override if necessary.
@ -22,6 +23,8 @@ Example:
```go
var (
initClientCtx = client.Context{...}
rootCmd = &cobra.Command{
Use: "simd",
Short: "simulation app",
@ -33,16 +36,7 @@ var (
return server.InterceptConfigsPreRunHandler(cmd)
},
}
encodingConfig = simapp.MakeTestEncodingConfig()
initClientCtx = client.Context{}.
WithJSONMarshaler(encodingConfig.Marshaler).
WithTxConfig(encodingConfig.TxConfig).
WithCodec(encodingConfig.Amino).
WithInput(os.Stdin).
WithAccountRetriever(types.NewAccountRetriever(encodingConfig.Marshaler)).
WithBroadcastMode(flags.BroadcastBlock).
WithHomeDir(simapp.DefaultNodeHome)
// add root sub-commands ...
)
```

37
server/cmd/execute.go Normal file
View File

@ -0,0 +1,37 @@
package cmd
import (
"context"
"github.com/rs/zerolog"
"github.com/spf13/cobra"
tmcfg "github.com/tendermint/tendermint/config"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/server"
)
// Execute executes the root command of an application. It handles creating a
// server context object with the appropriate server and client objects injected
// into the underlying stdlib Context. It also handles adding core CLI flags,
// specifically the logging flags. It returns an error upon execution failure.
func Execute(rootCmd *cobra.Command, defaultHome string) error {
// Create and set a client.Context on the command's Context. During the pre-run
// of the root command, a default initialized client.Context is provided to
// seed child command execution with values such as AccountRetriver, Keyring,
// and a Tendermint RPC. This requires the use of a pointer reference when
// getting and setting the client.Context. Ideally, we utilize
// https://github.com/spf13/cobra/pull/1118.
srvCtx := server.NewDefaultContext()
ctx := context.Background()
ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{})
ctx = context.WithValue(ctx, server.ServerContextKey, srvCtx)
rootCmd.PersistentFlags().String(flags.FlagLogLevel, zerolog.InfoLevel.String(), "The logging level (trace|debug|info|warn|error|fatal|panic)")
rootCmd.PersistentFlags().String(flags.FlagLogFormat, tmcfg.LogFormatPlain, "The logging format (json|plain)")
executor := tmcli.PrepareBaseCmd(rootCmd, "", defaultHome)
return executor.ExecuteContext(ctx)
}

View File

@ -109,7 +109,8 @@ func ExportCmd(appExporter types.AppExporter, defaultNodeHome string) *cobra.Com
return nil
},
}
cmd.SetOut(cmd.OutOrStdout())
cmd.SetErr(cmd.ErrOrStderr())
cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
cmd.Flags().Int64(FlagHeight, -1, "Export state from a particular height (-1 means latest height)")
cmd.Flags().Bool(FlagForZeroHeight, false, "Export state to start at height zero (perform preproccessing)")

View File

@ -22,6 +22,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/simapp"
@ -135,7 +136,7 @@ func setupApp(t *testing.T, tempDir string) (*simapp.SimApp, context.Context, *t
serverCtx.Config.RootDir = tempDir
clientCtx := client.Context{}.WithJSONMarshaler(app.AppCodec())
genDoc := newDefaultGenesisDoc()
genDoc := newDefaultGenesisDoc(encCfg.Marshaler)
require.NoError(t, saveGenesisFile(genDoc, serverCtx.Config.GenesisFile()))
app.InitChain(
@ -176,8 +177,8 @@ func createConfigFolder(dir string) error {
return os.Mkdir(path.Join(dir, "config"), 0700)
}
func newDefaultGenesisDoc() *tmtypes.GenesisDoc {
genesisState := simapp.NewDefaultGenesisState()
func newDefaultGenesisDoc(cdc codec.Marshaler) *tmtypes.GenesisDoc {
genesisState := simapp.NewDefaultGenesisState(cdc)
stateBytes, err := json.MarshalIndent(genesisState, "", " ")
if err != nil {

View File

@ -154,7 +154,7 @@ func (s *IntegrationTestSuite) TestGRPCServer_BroadcastTx() {
WithSignMode(signing.SignMode_SIGN_MODE_DIRECT)
// Sign Tx.
err := authclient.SignTx(txFactory, val0.ClientCtx, val0.Moniker, txBuilder, false)
err := authclient.SignTx(txFactory, val0.ClientCtx, val0.Moniker, txBuilder, false, true)
s.Require().NoError(err)
txBytes, err := val0.ClientCtx.TxConfig.TxEncoder()(txBuilder.GetTx())

View File

@ -103,7 +103,10 @@ which accepts a path for the resulting pprof file.
},
RunE: func(cmd *cobra.Command, _ []string) error {
serverCtx := GetServerContextFromCmd(cmd)
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
withTM, _ := cmd.Flags().GetBool(flagWithTendermint)
if !withTM {
@ -114,8 +117,14 @@ which accepts a path for the resulting pprof file.
serverCtx.Logger.Info("starting ABCI with Tendermint")
// amino is needed here for backwards compatibility of REST routes
err := startInProcess(serverCtx, clientCtx, appCreator)
return err
err = startInProcess(serverCtx, clientCtx, appCreator)
errCode, ok := err.(ErrorCode)
if !ok {
return err
}
serverCtx.Logger.Debug(fmt.Sprintf("received quit signal: %d", errCode.Code))
return nil
},
}

View File

@ -203,7 +203,6 @@ func NewSimApp(
appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp),
) *SimApp {
// TODO: Remove cdc in favor of appCodec once all modules are migrated.
appCodec := encodingConfig.Marshaler
legacyAmino := encodingConfig.Amino
interfaceRegistry := encodingConfig.InterfaceRegistry
@ -441,14 +440,6 @@ func NewSimApp(
return app
}
// MakeCodecs constructs the *std.Codec and *codec.LegacyAmino instances used by
// simapp. It is useful for tests and clients who do not want to construct the
// full simapp
func MakeCodecs() (codec.Marshaler, *codec.LegacyAmino) {
config := MakeTestEncodingConfig()
return config.Marshaler, config.Amino
}
// Name returns the name of the App
func (app *SimApp) Name() string { return app.BaseApp.Name() }

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