Merge branch 'master' into jonathan/4875-staking-test-use-simapp

This commit is contained in:
Jonathan Gimeno 2020-02-25 15:48:13 +01:00
commit 13f2138989
323 changed files with 13669 additions and 2822 deletions

View File

@ -47,6 +47,7 @@ ignore:
- "*.md"
- "*.rst"
- "**/*.pb.go"
- "x/**/*.pb.go"
- "x/**/test_common.go"
- "scripts/"
- "contrib"

View File

@ -57,6 +57,12 @@ flushed to disk or kept as a snapshot. Note, `KeepRecent` is automatically infer
and provided directly the IAVL store.
* (modules) [\#5555](https://github.com/cosmos/cosmos-sdk/pull/5555) Move x/auth/client/utils/ types and functions to x/auth/client/.
* (modules) [\#5572](https://github.com/cosmos/cosmos-sdk/pull/5572) Move account balance logic and APIs from `x/auth` to `x/bank`.
* (types) [\#5533](https://github.com/cosmos/cosmos-sdk/pull/5533) Refactored `AppModuleBasic` and `AppModuleGenesis`
to now accept a `codec.JSONMarshaler` for modular serialization of genesis state.
### Features
* (x/ibc) [\#5588](https://github.com/cosmos/cosmos-sdk/pull/5588) Add [ICS 024 - Host State Machine Requirements](https://github.com/cosmos/ics/tree/master/spec/ics-024-host-requirements) subpackage to `x/ibc` module.
### Bug Fixes
@ -72,7 +78,7 @@ and provided directly the IAVL store.
* Callers to `NewBaseVestingAccount` are responsible for verifying account balance in relation to
the original vesting amount.
* The `SendKeeper` and `ViewKeeper` interfaces in `x/bank` have been modified to account for changes.
* (staking) [\#5600](https://github.com/cosmos/cosmos-sdk/pull/5600) Migrate the `x/staking` module to use Protocol Buffer for state
* (x/staking) [\#5600](https://github.com/cosmos/cosmos-sdk/pull/5600) Migrate the `x/staking` module to use Protocol Buffers for state
serialization instead of Amino. The exact codec used is `codec.HybridCodec` which utilizes Protobuf for binary encoding and Amino
for JSON encoding.
* `BondStatus` is now of type `int32` instead of `byte`.
@ -80,7 +86,12 @@ for JSON encoding.
* 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`.
* (distr) [\#5610](https://github.com/cosmos/cosmos-sdk/pull/5610) Migrate the `x/distribution` module to use Protocol Buffer for state
* (x/slashing) [\#5627](https://github.com/cosmos/cosmos-sdk/pull/5627) Migrate the `x/slashing` module to use Protocol Buffers for state
serialization instead of Amino. The exact codec used is `codec.HybridCodec` which utilizes Protobuf for binary encoding and Amino
for JSON encoding.
* The `Keeper` constructor now takes a `codec.Marshaler` instead of a concrete Amino codec. This exact type
provided is specified by `ModuleCdc`.
* (x/distribution) [\#5610](https://github.com/cosmos/cosmos-sdk/pull/5610) Migrate the `x/distribution` module to use Protocol Buffers for state
serialization instead of Amino. The exact codec used is `codec.HybridCodec` which utilizes Protobuf for binary encoding and Amino
for JSON encoding.
* `ValidatorHistoricalRewards.ReferenceCount` is now of types `uint32` instead of `uint16`.
@ -89,6 +100,36 @@ for JSON encoding.
* `ValidatorAccumulatedCommission` is now a struct with `commission`.
* The `Keeper` constructor now takes a `codec.Marshaler` instead of a concrete Amino codec. This exact type
provided is specified by `ModuleCdc`.
* (x/auth) [\#5533](https://github.com/cosmos/cosmos-sdk/pull/5533) Migrate the `x/auth` module to use Protocol Buffers for state
serialization instead of Amino.
* The `BaseAccount.PubKey` field is now represented as a Bech32 string instead of a `crypto.Pubkey`.
* `NewBaseAccountWithAddress` now returns a reference to a `BaseAccount`.
* The `x/auth` module now accepts a `Codec` interface which extends the `codec.Marshaler` interface by
requiring a concrete codec to know how to serialize accounts.
* The `AccountRetriever` type now accepts a `Codec` in its constructor in order to know how to
serialize accounts.
* (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.
* The `internal` sub-package has been removed in order to expose the types proto file.
* The `x/supply` module now accepts a `Codec` interface which extends the `codec.Marshaler` interface by
requiring a concrete codec to know how to serialize `SupplyI` types.
* The `SupplyI` interface has been modified to no longer return `SupplyI` on methods. Instead the
concrete type's receiver should modify the type.
* (x/mint) [\#5634](https://github.com/cosmos/cosmos-sdk/pull/5634) Migrate the `x/mint` module to use Protocol Buffers for state
serialization instead of Amino.
* The `internal` sub-package has been removed in order to expose the types proto file.
* (x/evidence) [\#5634](https://github.com/cosmos/cosmos-sdk/pull/5634) Migrate the `x/evidence` module to use Protocol Buffers for state
serialization instead of Amino.
* The `internal` sub-package has been removed in order to expose the types proto file.
* The module now accepts a `Codec` interface which extends the `codec.Marshaler` interface by
requiring a concrete codec to know how to serialize `Evidence` types.
* The `MsgSubmitEvidence` message has been removed in favor of `MsgSubmitEvidenceBase`. The application-level
codec must now define the concrete `MsgSubmitEvidence` type which must implement the module's `MsgSubmitEvidence`
interface.
* (x/upgrade) [\#5659](https://github.com/cosmos/cosmos-sdk/pull/5659) Migrate the `x/upgrade` module to use Protocol
Buffers for state serialization instead of Amino.
* The `internal` sub-package has been removed in order to expose the types proto file.
* The `x/upgrade` module now accepts a `codec.Marshaler` interface.
### Improvements

View File

@ -238,25 +238,37 @@ proto-lint:
proto-check-breaking:
@buf check breaking --against-input '.git#branch=master'
# Origin
# TODO: Update to the version of Tendermint that is being used in go.mod
version_branch = v0.33.0
tendermint = https://raw.githubusercontent.com/tendermint/tendermint/$(version_branch)
TM_URL = https://raw.githubusercontent.com/tendermint/tendermint/v0.33.1
GOGO_PROTO_URL = https://raw.githubusercontent.com/regen-network/protobuf/cosmos
COSMOS_PROTO_URL = https://raw.githubusercontent.com/regen-network/cosmos-proto/master
# Outputs
tmkv = third_party/proto/tendermint/libs/kv/types.proto
tmmerkle = third_party/proto/tendermint/crypto/merkle/merkle.proto
tmabci = third_party/proto/tendermint/abci/types/types.proto
TM_KV_TYPES = third_party/proto/tendermint/libs/kv
TM_MERKLE_TYPES = third_party/proto/tendermint/crypto/merkle
TM_ABCI_TYPES = third_party/proto/tendermint/abci/types
GOGO_PROTO_TYPES = third_party/proto/gogoproto
COSMOS_PROTO_TYPES = third_party/proto/cosmos-proto
SDK_PROTO_TYPES = third_party/proto/cosmos-sdk/types
AUTH_PROTO_TYPES = third_party/proto/cosmos-sdk/x/auth/types
VESTING_PROTO_TYPES = third_party/proto/cosmos-sdk/x/auth/vesting/types
SUPPLY_PROTO_TYPES = third_party/proto/cosmos-sdk/x/supply/types
# You *only* need to run this to rebuild protobufs from the tendermint source
proto-update-tendermint:
@curl $(tendermint)/abci/types/types.proto > $(tmabci)
sed -i '' '8,9 s|github.com/tendermint|third_party/proto|g' $(tmabci)
sed -i '' '7 s|github.com/gogo/protobuf|third_party/proto|' $(tmabci)
@curl $(tendermint)/libs/kv/types.proto > $(tmkv)
sed -i '' 's|github.com/gogo/protobuf|third_party/proto|' $(tmkv)
@curl $(tendermint)/crypto/merkle/merkle.proto > $(tmmerkle)
sed -i '' '7 s|github.com/gogo/protobuf|third_party/proto|' $(tmmerkle)
proto-update-deps:
@mkdir -p $(GOGO_PROTO_TYPES)
@curl -sSL $(GOGO_PROTO_URL)/gogoproto/gogo.proto > $(GOGO_PROTO_TYPES)/gogo.proto
@mkdir -p $(COSMOS_PROTO_TYPES)
@curl -sSL $(COSMOS_PROTO_URL)/cosmos.proto > $(COSMOS_PROTO_TYPES)/cosmos.proto
@mkdir -p $(TM_ABCI_TYPES)
@curl -sSL $(TM_URL)/abci/types/types.proto > $(TM_ABCI_TYPES)/types.proto
@sed -i '' '8 s|crypto/merkle/merkle.proto|third_party/proto/tendermint/crypto/merkle/merkle.proto|g' $(TM_ABCI_TYPES)/types.proto
@sed -i '' '9 s|libs/kv/types.proto|third_party/proto/tendermint/libs/kv/types.proto|g' $(TM_ABCI_TYPES)/types.proto
@mkdir -p $(TM_KV_TYPES)
@curl -sSL $(TM_URL)/libs/kv/types.proto > $(TM_KV_TYPES)/types.proto
@mkdir -p $(TM_MERKLE_TYPES)
@curl -sSL $(TM_URL)/crypto/merkle/merkle.proto > $(TM_MERKLE_TYPES)/merkle.proto
.PHONY: proto-all proto-gen proto-lint proto-check-breaking proto-update-tendermint
.PHONY: proto-all proto-gen proto-lint proto-check-breaking proto-update-deps

View File

@ -68,6 +68,7 @@ const (
FlagKeyringBackend = "keyring-backend"
FlagPage = "page"
FlagLimit = "limit"
FlagUnsafeCORS = "unsafe-cors"
)
// LineBreak can be included in a command list to provide a blank line
@ -141,6 +142,7 @@ func RegisterRestServerFlags(cmd *cobra.Command) *cobra.Command {
cmd.Flags().Uint(FlagMaxOpenConnections, 1000, "The number of maximum open connections")
cmd.Flags().Uint(FlagRPCReadTimeout, 10, "The RPC read timeout (in seconds)")
cmd.Flags().Uint(FlagRPCWriteTimeout, 10, "The RPC write timeout (in seconds)")
cmd.Flags().Bool(FlagUnsafeCORS, false, "Allows CORS requests from all domains. For development purposes only, use it at your own risk.")
return cmd
}

View File

@ -7,6 +7,7 @@ import (
"os"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/rakyll/statik/fs"
"github.com/spf13/cobra"
@ -46,7 +47,7 @@ func NewRestServer(cdc *codec.Codec) *RestServer {
}
// Start starts the rest server
func (rs *RestServer) Start(listenAddr string, maxOpen int, readTimeout, writeTimeout uint) (err error) {
func (rs *RestServer) Start(listenAddr string, maxOpen int, readTimeout, writeTimeout uint, cors bool) (err error) {
server.TrapSignal(func() {
err := rs.listener.Close()
rs.log.Error("error closing listener", "err", err)
@ -68,6 +69,11 @@ func (rs *RestServer) Start(listenAddr string, maxOpen int, readTimeout, writeTi
),
)
var h http.Handler = rs.Mux
if cors {
return rpcserver.StartHTTPServer(rs.listener, handlers.CORS()(h), rs.log, cfg)
}
return rpcserver.StartHTTPServer(rs.listener, rs.Mux, rs.log, cfg)
}
@ -90,6 +96,7 @@ func ServeCommand(cdc *codec.Codec, registerRoutesFn func(*RestServer)) *cobra.C
viper.GetInt(flags.FlagMaxOpenConnections),
uint(viper.GetInt(flags.FlagRPCReadTimeout)),
uint(viper.GetInt(flags.FlagRPCWriteTimeout)),
viper.GetBool(flags.FlagUnsafeCORS),
)
return err

View File

@ -3,6 +3,7 @@
## Changelog
- 2020 Feb 15: Initial Draft
- 2020 Feb 24: Updates to handle messages with interface fields
## Status
@ -143,19 +144,6 @@ message Account {
```go
// app/codec/codec.go
import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/supply"
authexported "github.com/cosmos/cosmos-sdk/x/auth/exported"
// ...
)
var (
_ auth.Codec = (*Codec)(nil)
// ...
)
type Codec struct {
codec.Marshaler
@ -192,10 +180,91 @@ about all the required types. Note, the use of `interface_type` allows us to avo
amount of code boilerplate when implementing the `Codec`.
A similar concept is to be applied for messages that contain interfaces fields. The module will
define a "base" concrete message type (e.g. `MsgSubmitProposalBase`) that the application-level codec
will extend via `oneof` (e.g. `MsgSubmitProposal`) that fulfills the required interface
(e.g. `MsgSubmitProposalI`). Note, however, the module's message handler must now switch on the
interface rather than the concrete type for this particular message.
define a "base" concrete message type that the application-level codec will extend via `oneof` that
fulfills the required message interface.
Example:
The `MsgSubmitEvidence` defined by the `x/evidence` module contains a field `Evidence` which is an
interface.
```go
type MsgSubmitEvidence struct {
Evidence exported.Evidence
Submitter sdk.AccAddress
}
```
Instead, we will implement a "base" message type and an interface which the concrete message type
must implement.
```protobuf
// x/evidence/types/types.proto
message MsgSubmitEvidenceBase {
bytes submitter = 1
[
(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"
];
}
```
```go
// x/evidence/exported/evidence.go
type MsgSubmitEvidence interface {
sdk.Msg
GetEvidence() Evidence
GetSubmitter() sdk.AccAddress
}
```
Notice the `MsgSubmitEvidence` interface extends `sdk.Msg` and allows for the `Evidence` interface
to be retrieved from the concrete message type.
Now, the application-level codec will define the concrete `MsgSubmitEvidence` type and will have it
fulfill the `MsgSubmitEvidence` interface defined by `x/evidence`.
```protobuf
// app/codec/codec.proto
message Evidence {
option (gogoproto.equal) = true;
option (cosmos_proto.interface_type) = "github.com/cosmos/cosmos-sdk/x/evidence/exported.Evidence";
oneof sum {
cosmos_sdk.x.evidence.v1.Equivocation equivocation = 1;
}
}
message MsgSubmitEvidence {
option (gogoproto.equal) = true;
option (gogoproto.goproto_getters) = false;
Evidence evidence = 1;
cosmos_sdk.x.evidence.v1.MsgSubmitEvidenceBase base = 2
[
(gogoproto.nullable) = false,
(gogoproto.embed) = true
];
}
```
```go
// app/codec/msgs.go
func (msg MsgSubmitEvidence) GetEvidence() eviexported.Evidence {
return msg.Evidence.GetEvidence()
}
func (msg MsgSubmitEvidence) GetSubmitter() sdk.AccAddress {
return msg.Submitter
}
```
Note, however, the module's message handler must now handle the interface `MsgSubmitEvidence` in
addition to any concrete types.
### Why Wasn't X Chosen Instead

View File

@ -19,3 +19,4 @@ This repository contains documentation on concepts developers need to know in or
9. [Genesis](./genesis.md)
10. [Module Interfaces](./module-interfaces.md)
11. [Standard Module Structure](./structure.md)
12. [Errors](./errors.md)

View File

@ -0,0 +1,53 @@
<!--
order: 13
synopsis: This document outlines the recommended usage and APIs for error handling in Cosmos SDK modules.
-->
# Errors
Modules are encouraged to define and register their own errors to provide better
context on failed message or handler execution. Typically, these errors should be
common or general errors which can be further wrapped to provide additional specific
execution context.
## Registration
Modules should define and register their custom errors in `x/{module}/types/errors.go`. Registration
of errors is handled via the `types/errors` package.
Example:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.38.1/x/distribution/types/errors.go#L1-L21
Each custom module error must provide the codespace, which is typically the module name
(e.g. "distribution") and is unique per module, and a uint32 code. Together, the codespace and code
provide a globally unique SDK error. Typically, the code is monotonically increasing but does not
necessarily have to be. The only restrictions on error codes are the following:
* Must be greater than one, as a code value of one is reserved for internal errors.
* Must be unique within the module.
Note, the SDK provides a core set of *common* errors. These errors are defined in `types/errors/errors.go`.
## Wrapping
The custom module errors can be returned as their concrete type as they already fulfill the `error`
interface. However, module errors can be wrapped to provide further context and meaning to failed
execution.
Example:
+++ https://github.com/cosmos/cosmos-sdk/blob/v0.38.1/x/distribution/keeper/querier.go#L62-L80
Regardless if an error is wrapped or not, the SDK's `errors` package provides an API to determine if
an error is of a particular kind via `Is`.
## ABCI
If a module error is registered, the SDK `errors` package allows ABCI information to be extracted
through the `ABCIInfo` API. The package also provides `ResponseCheckTx` and `ResponseDeliverTx` as
auxiliary APIs to automatically get `CheckTx` and `DeliverTx` responses from an error.
## Next {hide}
Learn about [interfaces](../interfaces/interfaces-intro.md) {hide}

View File

@ -85,9 +85,9 @@ allows for greater freedom of development while maintaining API stability.
- `module.go`: The module's implementation of the `AppModule` and `AppModuleBasic`
interfaces.
- `simulation/`: The module's simulation package defines all the required functions
used on the blockchain simulator: randomized genesis state, parameters, weigthed
used on the blockchain simulator: randomized genesis state, parameters, weighted
operations, proposal contents and types decoders.
## Next {hide}
Learn about [interfaces](../interfaces/interfaces-intro.md) {hide}
Learn about [Errors](./errors.md) {hide}

View File

@ -7,10 +7,10 @@ synopsis: "This document describes how to create a REST interface for an SDK **a
## Prerequisites {hide}
* [Query Lifecycle](./query-lifecycle.md) {prereq}
* [Application CLI](./cli.md) {prereq}
- [Query Lifecycle](./query-lifecycle.md) {prereq}
- [Application CLI](./cli.md) {prereq}
## Application REST Interface
## Application REST Interface
Building the REST Interface for an application is done by [aggregating REST Routes](#registering-routes) defined in the application's modules. This interface is served by a REST Server [REST server](#rest-server), which route requests and output responses in the application itself. The SDK comes with its own REST Server by default. To enable it, the `rest.ServeCommand` command needs to be added as a subcommand of the `rootCmd` in the `main()` function of the [CLI interface](./cli.md):
@ -24,19 +24,19 @@ Users will then be able to use the application CLI to start a new REST server, a
appcli rest-server --chain-id <chainID> --trust-node
```
Note that if `trust-node` is set to `false`, the REST server will verify the query proof against the merkle root (contained in the block header).
Note that if `trust-node` is set to `false`, the REST server will verify the query proof against the merkle root (contained in the block header).
## REST Server
A REST Server is used to receive and route HTTP Requests, obtain the results from the application, and return a response to the user. The REST Server defined by the SDK `rest` package contains the following:
* **Router:** A router for HTTP requests. A new router can be instantiated for an application and used to match routes based on path, request method, headers, etc. The SDK uses the [Gorilla Mux Router](https://github.com/gorilla/mux).
* **CLIContext:** A [`CLIContext`](./query-lifecycle.md#clicontext) created for a user interaction.
* **Keybase:** A [Keybase](../basics/accounts.md#keybase) is a key manager.
* **Logger:** A logger from Tendermint `Log`, a log package structured around key-value pairs that allows logging level to be set differently for different keys. The logger takes `Debug()`, `Info()`, and `Error()`s.
* **Listener:** A [listener](https://golang.org/pkg/net/#Listener) from the net package.
- **Router:** A router for HTTP requests. A new router can be instantiated for an application and used to match routes based on path, request method, headers, etc. The SDK uses the [Gorilla Mux Router](https://github.com/gorilla/mux).
- **CLIContext:** A [`CLIContext`](./query-lifecycle.md#clicontext) created for a user interaction.
- **Keybase:** A [Keybase](../basics/accounts.md#keybase) is a key manager.
- **Logger:** A logger from Tendermint `Log`, a log package structured around key-value pairs that allows logging level to be set differently for different keys. The logger takes `Debug()`, `Info()`, and `Error()`s.
- **Listener:** A [listener](https://golang.org/pkg/net/#Listener) from the net package.
Of the five, the only attribute that application developers need interact with is the `router`: they need to add routes to it so that the REST server can properly handle queries. See the next section for more information on registering routes.
Of the five, the only attribute that application developers need interact with is the `router`: they need to add routes to it so that the REST server can properly handle queries. See the next section for more information on registering routes.
In order to enable the REST Server in an SDK application, the `rest.ServeCommand` needs to be added to the application's command-line interface. See the [above section](#application-rest-interface) for more information.
@ -44,7 +44,7 @@ In order to enable the REST Server in an SDK application, the `rest.ServeCommand
To include routes for each module in an application, the CLI must have some kind of function to register routes in its REST Server. This function is called `RegisterRoutes()`, and is utilized by the `ServeCommand` and must include routes for each of the application's modules. Since each module used by an SDK application implements a [`RegisterRESTRoutes`](../building-modules/module-interfaces.md#rest) function, application developers simply use the [Module Manager](../building-modules/module-manager.md) to call this function for each module (this is done in the [application's constructor](../basics/app-anatomy.md#constructor-function)).
At the bare minimum, a `RegisterRoutes()` function should use the SDK client package `RegisterRoutes()` function to be able to route RPC calls, and instruct the application Module Manager to call `RegisterRESTRoutes()` for all of its modules. This is done in the `main.go` file of the CLI (typically located in `./cmd/appcli/main.go`).
At the bare minimum, a `RegisterRoutes()` function should use the SDK client package `RegisterRoutes()` function to be able to route RPC calls, and instruct the application Module Manager to call `RegisterRESTRoutes()` for all of its modules. This is done in the `main.go` file of the CLI (typically located in `./cmd/appcli/main.go`).
```go
func registerRoutes(rs *rest.RestServer) {
@ -58,3 +58,14 @@ This function is specific to the application and passed in to the `ServeCommand`
```go
rootCmd.AddCommand(rest.ServeCommand(cdc, registerRoutes))
```
## Cross-Origin Resource Sharing (CORS)
[CORS policies](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) are not enabled by default to help with security. If you would like to use the rest-server in a public environment we recommend you provide a reverse proxy, this can be done with [nginx](https://www.nginx.com/). For testing and development purposes there is an `unsafe_cors` flag that can be passed to the cmd to enable accepting cors from everyone.
```sh
gaiacli rest-server --chain-id=test \
--laddr=tcp://localhost:1317 \
--node tcp://localhost:26657 \
--trust-node=true --unsafe-cors
```

7
go.mod
View File

@ -10,19 +10,20 @@ require (
github.com/gogo/protobuf v1.3.1
github.com/golang/mock v1.3.1-0.20190508161146-9fa652df1129
github.com/golang/protobuf v1.3.3
github.com/gorilla/handlers v1.4.2
github.com/gorilla/mux v1.7.4
github.com/hashicorp/golang-lru v0.5.4
github.com/mattn/go-isatty v0.0.12
github.com/pelletier/go-toml v1.6.0
github.com/pkg/errors v0.9.1
github.com/rakyll/statik v0.1.6
github.com/regen-network/cosmos-proto v0.1.0
github.com/regen-network/cosmos-proto v0.1.1-0.20200213154359-02baa11ea7c2
github.com/spf13/afero v1.2.1 // indirect
github.com/spf13/cobra v0.0.5
github.com/spf13/cobra v0.0.6
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.6.2
github.com/stretchr/testify v1.4.0
github.com/stretchr/testify v1.5.1
github.com/tendermint/btcd v0.1.1
github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15
github.com/tendermint/go-amino v0.15.1

19
go.sum
View File

@ -46,6 +46,7 @@ github.com/cosmos/ledger-cosmos-go v0.11.1/go.mod h1:J8//BsAGTo3OC/vDLjMRFLW6q0W
github.com/cosmos/ledger-go v0.9.2 h1:Nnao/dLwaVTk1Q5U9THldpUMMXU94BOTWPddSmVB6pI=
github.com/cosmos/ledger-go v0.9.2/go.mod h1:oZJ2hHAZROdlHiwTg4t7kP+GKIIkBT+o6c9QWFanOyI=
github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/danieljoos/wincred v1.0.2 h1:zf4bhty2iLuwgjgpraD2E9UbvO+fe54XXGJbOwe23fU=
github.com/danieljoos/wincred v1.0.2/go.mod h1:SnuYRW9lp1oJrZX/dXJqr0cPK5gYXqx3EJbmjhLdK9U=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@ -91,7 +92,6 @@ github.com/golang/mock v1.3.1-0.20190508161146-9fa652df1129/go.mod h1:sBzyDLLjw3
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I=
github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw=
@ -105,6 +105,8 @@ github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/handlers v1.4.2 h1:0QniY0USkHQ1RGCLfKxeNHK9bkDHGRYGNDFBCS+YARg=
github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ=
github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc=
github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
@ -196,14 +198,16 @@ github.com/rakyll/statik v0.1.6 h1:uICcfUXpgqtw2VopbIncslhAmE5hwc4g20TEyEENBNs=
github.com/rakyll/statik v0.1.6/go.mod h1:OEi9wJV/fMUAGx1eNjq75DKDsJVuEv1U0oYdX6GX8Zs=
github.com/rcrowley/go-metrics v0.0.0-20180503174638-e2704e165165 h1:nkcn14uNmFEuGCb2mBZbBb24RdNRL08b/wb+xBOYpuk=
github.com/rcrowley/go-metrics v0.0.0-20180503174638-e2704e165165/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
github.com/regen-network/cosmos-proto v0.1.0 h1:gsV+YO2kMvY430zQn8ioPXRxEJgb/ms0iMPeWo3VEyY=
github.com/regen-network/cosmos-proto v0.1.0/go.mod h1:+r7jN10xXCypD4yBgzKOa+vgLz0riqYMHeDcKekxPvA=
github.com/regen-network/cosmos-proto v0.1.1-0.20200213154359-02baa11ea7c2 h1:jQK1YoH972Aptd22YKgtNu5jM2X2xMGkyIENOAc71to=
github.com/regen-network/cosmos-proto v0.1.1-0.20200213154359-02baa11ea7c2/go.mod h1:+r7jN10xXCypD4yBgzKOa+vgLz0riqYMHeDcKekxPvA=
github.com/regen-network/protobuf v1.3.2-alpha.regen.1 h1:YdeZbBS0lG1D13COb7b57+nM/RGgIs8WF9DwitU6EBM=
github.com/regen-network/protobuf v1.3.2-alpha.regen.1/go.mod h1:lye6mqhOn/GCw1zRl3uPD5VP8rC+LPMyTyPAyQV872U=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik=
github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU=
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
@ -220,6 +224,8 @@ github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkU
github.com/spf13/cobra v0.0.1/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
github.com/spf13/cobra v0.0.5 h1:f0B+LkLX6DtmRH1isoNA9VTtNUK9K8xYd28JNNfOv/s=
github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU=
github.com/spf13/cobra v0.0.6 h1:breEStsVwemnKh2/s6gMvSdMEkwW0sK8vGStnlVBMCs=
github.com/spf13/cobra v0.0.6/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk=
github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo=
@ -227,6 +233,7 @@ github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE=
github.com/spf13/viper v1.6.1/go.mod h1:t3iDnF5Jlj76alVNuyFBk5oUMCvsrkbvZK0WQdfDi5k=
github.com/spf13/viper v1.6.2 h1:7aKfF+e8/k68gda3LOjo5RxiUqddoFxVq4BKBPrxk5E=
github.com/spf13/viper v1.6.2/go.mod h1:t3iDnF5Jlj76alVNuyFBk5oUMCvsrkbvZK0WQdfDi5k=
@ -238,6 +245,10 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.5.0 h1:DMOzIV76tmoDNE9pX6RSN0aDtCYeCg5VueieJaAo1uw=
github.com/stretchr/testify v1.5.0/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d h1:gZZadD8H+fF+n9CmNhYL1Y0dJB+kLOmKd7FbPJLeGHs=
@ -253,7 +264,6 @@ github.com/tendermint/go-amino v0.15.1 h1:D2uk35eT4iTsvJd9jWIetzthE5C0/k2QmMFkCN
github.com/tendermint/go-amino v0.15.1/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME=
github.com/tendermint/iavl v0.13.0 h1:r2sINvNFlJsLlLhGoqlqPlREWYkuK26BvMfkBt+XQnA=
github.com/tendermint/iavl v0.13.0/go.mod h1:7nSUPdrsHEZ2nNZa+9gaIrcJciWd1jCQZXtcyARU82k=
github.com/tendermint/tendermint v0.33.0 h1:TW1g9sQs3YSqKM8o1+opL3/VmBy4Ke/VKV9MxYpqNbI=
github.com/tendermint/tendermint v0.33.0/go.mod h1:s5UoymnPIY+GcA3mMte4P9gpMP8vS7UH7HBXikT1pHI=
github.com/tendermint/tendermint v0.33.1 h1:8f68LUBz8yhISZvaLFP4siXXrLWsWeoYfelbdNtmvm4=
github.com/tendermint/tendermint v0.33.1/go.mod h1:fBOKyrlXOETqQ+heL8x/TZgSdmItON54csyabvktBp0=
@ -341,7 +351,6 @@ google.golang.org/genproto v0.0.0-20200108215221-bd8f9a0ef82f/go.mod h1:n3cpQtvx
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.26.0 h1:2dTRdpdFEEhJYQD8EMLB61nnrzSCTbG38PhqdhvOltg=
google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.27.1 h1:zvIju4sqAGvwKspUQOhwnpcqSbzi7/H6QomNNjTL4sk=
google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=

View File

@ -11,6 +11,7 @@ import (
bam "github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/codec"
simappcodec "github.com/cosmos/cosmos-sdk/simapp/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/version"
@ -25,6 +26,7 @@ import (
"github.com/cosmos/cosmos-sdk/x/mint"
"github.com/cosmos/cosmos-sdk/x/params"
paramsclient "github.com/cosmos/cosmos-sdk/x/params/client"
paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal"
"github.com/cosmos/cosmos-sdk/x/slashing"
"github.com/cosmos/cosmos-sdk/x/staking"
"github.com/cosmos/cosmos-sdk/x/supply"
@ -78,7 +80,6 @@ var (
}
)
// Verify app interface at compile time
var _ App = (*SimApp)(nil)
// SimApp extends an ABCI application, but with most of its parameters exported.
@ -124,10 +125,10 @@ func NewSimApp(
invCheckPeriod uint, baseAppOptions ...func(*bam.BaseApp),
) *SimApp {
appCodec := NewAppCodec()
// TODO: Remove cdc in favor of appCodec once all modules are migrated.
cdc := MakeCodec()
cdc := simappcodec.MakeCodec(ModuleBasics)
appCodec := simappcodec.NewAppCodec(cdc)
bApp := bam.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...)
bApp.SetCommitMultiStoreTracer(traceStore)
@ -150,7 +151,7 @@ func NewSimApp(
}
// init params keeper and subspaces
app.ParamsKeeper = params.NewKeeper(appCodec.Params, keys[params.StoreKey], tkeys[params.TStoreKey])
app.ParamsKeeper = params.NewKeeper(appCodec, keys[params.StoreKey], tkeys[params.TStoreKey])
app.subspaces[auth.ModuleName] = app.ParamsKeeper.Subspace(auth.DefaultParamspace)
app.subspaces[bank.ModuleName] = app.ParamsKeeper.Subspace(bank.DefaultParamspace)
app.subspaces[staking.ModuleName] = app.ParamsKeeper.Subspace(staking.DefaultParamspace)
@ -163,36 +164,36 @@ func NewSimApp(
// add keepers
app.AccountKeeper = auth.NewAccountKeeper(
app.cdc, keys[auth.StoreKey], app.subspaces[auth.ModuleName], auth.ProtoBaseAccount,
appCodec, keys[auth.StoreKey], app.subspaces[auth.ModuleName], auth.ProtoBaseAccount,
)
app.BankKeeper = bank.NewBaseKeeper(
app.cdc, keys[bank.StoreKey], app.AccountKeeper, app.subspaces[bank.ModuleName], app.BlacklistedAccAddrs(),
appCodec, keys[bank.StoreKey], app.AccountKeeper, app.subspaces[bank.ModuleName], app.BlacklistedAccAddrs(),
)
app.SupplyKeeper = supply.NewKeeper(
app.cdc, keys[supply.StoreKey], app.AccountKeeper, app.BankKeeper, maccPerms,
appCodec, keys[supply.StoreKey], app.AccountKeeper, app.BankKeeper, maccPerms,
)
stakingKeeper := staking.NewKeeper(
appCodec.Staking, keys[staking.StoreKey], app.BankKeeper, app.SupplyKeeper, app.subspaces[staking.ModuleName],
appCodec, keys[staking.StoreKey], app.BankKeeper, app.SupplyKeeper, app.subspaces[staking.ModuleName],
)
app.MintKeeper = mint.NewKeeper(
app.cdc, keys[mint.StoreKey], app.subspaces[mint.ModuleName], &stakingKeeper,
appCodec, keys[mint.StoreKey], app.subspaces[mint.ModuleName], &stakingKeeper,
app.SupplyKeeper, auth.FeeCollectorName,
)
app.DistrKeeper = distr.NewKeeper(
appCodec.Distribution, keys[distr.StoreKey], app.subspaces[distr.ModuleName], app.BankKeeper, &stakingKeeper,
appCodec, keys[distr.StoreKey], app.subspaces[distr.ModuleName], app.BankKeeper, &stakingKeeper,
app.SupplyKeeper, auth.FeeCollectorName, app.ModuleAccountAddrs(),
)
app.SlashingKeeper = slashing.NewKeeper(
app.cdc, keys[slashing.StoreKey], &stakingKeeper, app.subspaces[slashing.ModuleName],
appCodec, keys[slashing.StoreKey], &stakingKeeper, app.subspaces[slashing.ModuleName],
)
app.CrisisKeeper = crisis.NewKeeper(
app.subspaces[crisis.ModuleName], invCheckPeriod, app.SupplyKeeper, auth.FeeCollectorName,
)
app.UpgradeKeeper = upgrade.NewKeeper(skipUpgradeHeights, keys[upgrade.StoreKey], app.cdc)
app.UpgradeKeeper = upgrade.NewKeeper(skipUpgradeHeights, keys[upgrade.StoreKey], appCodec)
// create evidence keeper with router
evidenceKeeper := evidence.NewKeeper(
app.cdc, keys[evidence.StoreKey], app.subspaces[evidence.ModuleName], &app.StakingKeeper, app.SlashingKeeper,
appCodec, keys[evidence.StoreKey], app.subspaces[evidence.ModuleName], &app.StakingKeeper, app.SlashingKeeper,
)
evidenceRouter := evidence.NewRouter()
// TODO: Register evidence routes.
@ -202,7 +203,7 @@ func NewSimApp(
// register the proposal types
govRouter := gov.NewRouter()
govRouter.AddRoute(gov.RouterKey, gov.ProposalHandler).
AddRoute(params.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)).
AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)).
AddRoute(distr.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.DistrKeeper)).
AddRoute(upgrade.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.UpgradeKeeper))
app.GovKeeper = gov.NewKeeper(
@ -305,7 +306,7 @@ func (app *SimApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.Re
func (app *SimApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain {
var genesisState GenesisState
app.cdc.MustUnmarshalJSON(req.AppStateBytes, &genesisState)
return app.mm.InitGenesis(ctx, genesisState)
return app.mm.InitGenesis(ctx, app.cdc, genesisState)
}
// LoadHeight loads a particular height

View File

@ -1,46 +0,0 @@
package simapp
import (
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/vesting"
distr "github.com/cosmos/cosmos-sdk/x/distribution"
"github.com/cosmos/cosmos-sdk/x/params"
"github.com/cosmos/cosmos-sdk/x/staking"
)
// AppCodec defines the application-level codec. This codec contains all the
// required module-specific codecs that are to be provided upon initialization.
type AppCodec struct {
amino *codec.Codec
Params *params.Codec
Staking *staking.Codec
Distribution *distr.Codec
}
func NewAppCodec() *AppCodec {
amino := MakeCodec()
return &AppCodec{
amino: amino,
Params: params.NewCodec(amino),
Staking: staking.NewCodec(amino),
Distribution: distr.NewCodec(amino),
}
}
// MakeCodec creates and returns a reference to an Amino codec that has all the
// necessary types and interfaces registered. This codec is provided to all the
// modules the application depends on.
//
// NOTE: This codec will be deprecated in favor of AppCodec once all modules are
// migrated.
func MakeCodec() *codec.Codec {
var cdc = codec.New()
ModuleBasics.RegisterCodec(cdc)
vesting.RegisterCodec(cdc)
sdk.RegisterCodec(cdc)
codec.RegisterCrypto(cdc)
return cdc
}

169
simapp/codec/codec.go Normal file
View File

@ -0,0 +1,169 @@
package codec
import (
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/auth"
authexported "github.com/cosmos/cosmos-sdk/x/auth/exported"
"github.com/cosmos/cosmos-sdk/x/auth/vesting"
"github.com/cosmos/cosmos-sdk/x/evidence"
eviexported "github.com/cosmos/cosmos-sdk/x/evidence/exported"
"github.com/cosmos/cosmos-sdk/x/supply"
supplyexported "github.com/cosmos/cosmos-sdk/x/supply/exported"
)
var (
_ auth.Codec = (*Codec)(nil)
_ supply.Codec = (*Codec)(nil)
_ evidence.Codec = (*Codec)(nil)
)
// Codec defines the application-level codec. This codec contains all the
// required module-specific codecs that are to be provided upon initialization.
type Codec struct {
codec.Marshaler
// Keep reference to the amino codec to allow backwards compatibility along
// with type, and interface registration.
amino *codec.Codec
}
func NewAppCodec(amino *codec.Codec) *Codec {
return &Codec{Marshaler: codec.NewHybridCodec(amino), amino: amino}
}
// MarshalAccount marshals an Account interface. If the given type implements
// the Marshaler interface, it is treated as a Proto-defined message and
// serialized that way. Otherwise, it falls back on the internal Amino codec.
func (c *Codec) MarshalAccount(accI authexported.Account) ([]byte, error) {
acc := &Account{}
if err := acc.SetAccount(accI); err != nil {
return nil, err
}
return c.Marshaler.MarshalBinaryLengthPrefixed(acc)
}
// UnmarshalAccount returns an Account interface from raw encoded account bytes
// of a Proto-based Account type. An error is returned upon decoding failure.
func (c *Codec) UnmarshalAccount(bz []byte) (authexported.Account, error) {
acc := &Account{}
if err := c.Marshaler.UnmarshalBinaryLengthPrefixed(bz, acc); err != nil {
return nil, err
}
return acc.GetAccount(), nil
}
// MarshalAccountJSON JSON encodes an account object implementing the Account
// interface.
func (c *Codec) MarshalAccountJSON(acc authexported.Account) ([]byte, error) {
return c.Marshaler.MarshalJSON(acc)
}
// UnmarshalAccountJSON returns an Account from JSON encoded bytes.
func (c *Codec) UnmarshalAccountJSON(bz []byte) (authexported.Account, error) {
acc := &Account{}
if err := c.Marshaler.UnmarshalJSON(bz, acc); err != nil {
return nil, err
}
return acc.GetAccount(), nil
}
// MarshalSupply marshals a SupplyI interface. If the given type implements
// the Marshaler interface, it is treated as a Proto-defined message and
// serialized that way. Otherwise, it falls back on the internal Amino codec.
func (c *Codec) MarshalSupply(supplyI supplyexported.SupplyI) ([]byte, error) {
supply := &Supply{}
if err := supply.SetSupplyI(supplyI); err != nil {
return nil, err
}
return c.Marshaler.MarshalBinaryLengthPrefixed(supply)
}
// UnmarshalSupply returns a SupplyI interface from raw encoded account bytes
// of a Proto-based SupplyI type. An error is returned upon decoding failure.
func (c *Codec) UnmarshalSupply(bz []byte) (supplyexported.SupplyI, error) {
supply := &Supply{}
if err := c.Marshaler.UnmarshalBinaryLengthPrefixed(bz, supply); err != nil {
return nil, err
}
return supply.GetSupplyI(), nil
}
// MarshalSupplyJSON JSON encodes a supply object implementing the SupplyI
// interface.
func (c *Codec) MarshalSupplyJSON(supply supplyexported.SupplyI) ([]byte, error) {
return c.Marshaler.MarshalJSON(supply)
}
// UnmarshalSupplyJSON returns a SupplyI from JSON encoded bytes.
func (c *Codec) UnmarshalSupplyJSON(bz []byte) (supplyexported.SupplyI, error) {
supply := &Supply{}
if err := c.Marshaler.UnmarshalJSON(bz, supply); err != nil {
return nil, err
}
return supply.GetSupplyI(), nil
}
// MarshalEvidence marshals an Evidence interface. If the given type implements
// the Marshaler interface, it is treated as a Proto-defined message and
// serialized that way. Otherwise, it falls back on the internal Amino codec.
func (c *Codec) MarshalEvidence(evidenceI eviexported.Evidence) ([]byte, error) {
evidence := &Evidence{}
if err := evidence.SetEvidence(evidenceI); err != nil {
return nil, err
}
return c.Marshaler.MarshalBinaryLengthPrefixed(evidence)
}
// UnmarshalEvidence returns an Evidence interface from raw encoded evidence
// bytes of a Proto-based Evidence type. An error is returned upon decoding
// failure.
func (c *Codec) UnmarshalEvidence(bz []byte) (eviexported.Evidence, error) {
evidence := &Evidence{}
if err := c.Marshaler.UnmarshalBinaryLengthPrefixed(bz, evidence); err != nil {
return nil, err
}
return evidence.GetEvidence(), nil
}
// MarshalEvidenceJSON JSON encodes an evidence object implementing the Evidence
// interface.
func (c *Codec) MarshalEvidenceJSON(evidence eviexported.Evidence) ([]byte, error) {
return c.Marshaler.MarshalJSON(evidence)
}
// UnmarshalEvidenceJSON returns an Evidence from JSON encoded bytes
func (c *Codec) UnmarshalEvidenceJSON(bz []byte) (eviexported.Evidence, error) {
evidence := &Evidence{}
if err := c.Marshaler.UnmarshalJSON(bz, evidence); err != nil {
return nil, err
}
return evidence.GetEvidence(), nil
}
// ----------------------------------------------------------------------------
// necessary types and interfaces registered. This codec is provided to all the
// modules the application depends on.
//
// NOTE: This codec will be deprecated in favor of AppCodec once all modules are
// migrated.
func MakeCodec(bm module.BasicManager) *codec.Codec {
cdc := codec.New()
bm.RegisterCodec(cdc)
vesting.RegisterCodec(cdc)
sdk.RegisterCodec(cdc)
codec.RegisterCrypto(cdc)
return cdc
}

1676
simapp/codec/codec.pb.go Normal file

File diff suppressed because it is too large Load Diff

58
simapp/codec/codec.proto Normal file
View File

@ -0,0 +1,58 @@
syntax = "proto3";
package cosmos_sdk.simapp.codec.v1;
import "third_party/proto/cosmos-proto/cosmos.proto";
import "third_party/proto/gogoproto/gogo.proto";
import "x/auth/types/types.proto";
import "x/auth/vesting/types/types.proto";
import "x/supply/types/types.proto";
import "x/evidence/types/types.proto";
option go_package = "github.com/cosmos/cosmos-sdk/simapp/codec";
// Account defines the application-level Account type.
message Account {
option (cosmos_proto.interface_type) = "*github.com/cosmos/cosmos-sdk/x/auth/exported.Account";
// sum defines a list of all acceptable concrete Account implementations.
oneof sum {
cosmos_sdk.x.auth.v1.BaseAccount base_account = 1;
cosmos_sdk.x.auth.vesting.v1.ContinuousVestingAccount continuous_vesting_account = 2;
cosmos_sdk.x.auth.vesting.v1.DelayedVestingAccount delayed_vesting_account = 3;
cosmos_sdk.x.auth.vesting.v1.PeriodicVestingAccount periodic_vesting_account = 4;
cosmos_sdk.x.supply.v1.ModuleAccount module_account = 5;
}
}
// Supply defines the application-level Supply type.
message Supply {
option (gogoproto.equal) = true;
option (cosmos_proto.interface_type) = "*github.com/cosmos/cosmos-sdk/x/supply/exported.SupplyI";
// sum defines a set of all acceptable concrete Supply implementations.
oneof sum {
cosmos_sdk.x.supply.v1.Supply supply = 1;
}
}
// Evidence defines the application-level allowed Evidence to be submitted via a
// MsgSubmitEvidence message.
message Evidence {
option (gogoproto.equal) = true;
option (cosmos_proto.interface_type) = "github.com/cosmos/cosmos-sdk/x/evidence/exported.Evidence";
// sum defines a set of all acceptable concrete Evidence implementations.
oneof sum {
cosmos_sdk.x.evidence.v1.Equivocation equivocation = 1;
}
}
// MsgSubmitEvidence defines the application-level message type for handling
// evidence submission.
message MsgSubmitEvidence {
option (gogoproto.equal) = true;
option (gogoproto.goproto_getters) = false;
Evidence evidence = 1;
cosmos_sdk.x.evidence.v1.MsgSubmitEvidenceBase base = 2 [(gogoproto.nullable) = false, (gogoproto.embed) = true];
}

38
simapp/codec/msgs.go Normal file
View File

@ -0,0 +1,38 @@
package codec
import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/evidence"
eviexported "github.com/cosmos/cosmos-sdk/x/evidence/exported"
)
var _ eviexported.MsgSubmitEvidence = MsgSubmitEvidence{}
// NewMsgSubmitEvidence returns a new MsgSubmitEvidence.
func NewMsgSubmitEvidence(evidenceI eviexported.Evidence, s sdk.AccAddress) MsgSubmitEvidence {
e := &Evidence{}
e.SetEvidence(evidenceI)
return MsgSubmitEvidence{Evidence: e, MsgSubmitEvidenceBase: evidence.NewMsgSubmitEvidenceBase(s)}
}
// ValidateBasic performs basic (non-state-dependant) validation on a
// MsgSubmitEvidence.
func (msg MsgSubmitEvidence) ValidateBasic() error {
if err := msg.MsgSubmitEvidenceBase.ValidateBasic(); err != nil {
return nil
}
if msg.Evidence == nil {
return sdkerrors.Wrap(evidence.ErrInvalidEvidence, "missing evidence")
}
if err := msg.Evidence.GetEvidence().ValidateBasic(); err != nil {
return err
}
return nil
}
// nolint
func (msg MsgSubmitEvidence) GetEvidence() eviexported.Evidence { return msg.Evidence.GetEvidence() }
func (msg MsgSubmitEvidence) GetSubmitter() sdk.AccAddress { return msg.Submitter }

View File

@ -27,7 +27,7 @@ func (app *SimApp) ExportAppStateAndValidators(
app.prepForZeroHeightGenesis(ctx, jailWhiteList)
}
genState := app.mm.ExportGenesis(ctx)
genState := app.mm.ExportGenesis(ctx, app.cdc)
appState, err = codec.MarshalJSONIndent(app.cdc, genState)
if err != nil {
return nil, nil, err

View File

@ -2,6 +2,8 @@ package simapp
import (
"encoding/json"
simappcodec "github.com/cosmos/cosmos-sdk/simapp/codec"
)
// The genesis state of the blockchain is represented here as a map of raw json
@ -15,5 +17,7 @@ type GenesisState map[string]json.RawMessage
// NewDefaultGenesisState generates the default state for the application.
func NewDefaultGenesisState() GenesisState {
return ModuleBasics.DefaultGenesis()
cdc := simappcodec.MakeCodec(ModuleBasics)
return ModuleBasics.DefaultGenesis(cdc)
}

View File

@ -8,6 +8,7 @@ import (
"testing"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/log"
dbm "github.com/tendermint/tm-db"
@ -20,7 +21,7 @@ import (
distr "github.com/cosmos/cosmos-sdk/x/distribution"
"github.com/cosmos/cosmos-sdk/x/gov"
"github.com/cosmos/cosmos-sdk/x/mint"
"github.com/cosmos/cosmos-sdk/x/params"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/cosmos/cosmos-sdk/x/simulation"
"github.com/cosmos/cosmos-sdk/x/slashing"
"github.com/cosmos/cosmos-sdk/x/staking"
@ -137,7 +138,7 @@ func TestAppImportExport(t *testing.T) {
ctxA := app.NewContext(true, abci.Header{Height: app.LastBlockHeight()})
ctxB := newApp.NewContext(true, abci.Header{Height: app.LastBlockHeight()})
newApp.mm.InitGenesis(ctxB, genesisState)
newApp.mm.InitGenesis(ctxB, app.Codec(), genesisState)
fmt.Printf("comparing stores...\n")
@ -152,7 +153,7 @@ func TestAppImportExport(t *testing.T) {
{app.keys[mint.StoreKey], newApp.keys[mint.StoreKey], [][]byte{}},
{app.keys[distr.StoreKey], newApp.keys[distr.StoreKey], [][]byte{}},
{app.keys[supply.StoreKey], newApp.keys[supply.StoreKey], [][]byte{}},
{app.keys[params.StoreKey], newApp.keys[params.StoreKey], [][]byte{}},
{app.keys[paramtypes.StoreKey], newApp.keys[paramtypes.StoreKey], [][]byte{}},
{app.keys[gov.StoreKey], newApp.keys[gov.StoreKey], [][]byte{}},
}

View File

@ -8,12 +8,13 @@ import (
tmkv "github.com/tendermint/tendermint/libs/kv"
"github.com/cosmos/cosmos-sdk/codec"
simappcodec "github.com/cosmos/cosmos-sdk/simapp/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
)
func TestGetSimulationLog(t *testing.T) {
cdc := MakeCodec()
cdc := simappcodec.MakeCodec(ModuleBasics)
decoders := make(sdk.StoreDecoderRegistry)
decoders[auth.StoreKey] = func(cdc *codec.Codec, kvAs, kvBs tmkv.Pair) string { return "10" }

View File

@ -142,4 +142,4 @@ extend google.protobuf.FieldOptions {
optional bool wktpointer = 65012;
optional string castrepeated = 65013;
}
}

View File

@ -1,6 +1,6 @@
syntax = "proto3";
package tendermint.abci.types;
option go_package = "github.com/tendermint/tendermint/abci/types";
option go_package = "github.com/tendermint/tendermint/abci/types";
// For more information on gogo.proto, see:
// https://github.com/gogo/protobuf/blob/master/extensions.md
@ -14,31 +14,31 @@ import "google/protobuf/duration.proto";
// NOTE: When using custom types, mind the warnings.
// https://github.com/gogo/protobuf/blob/master/custom_types.md#warnings-and-issues
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
// Generate tests
option (gogoproto.populate_all) = true;
option (gogoproto.equal_all) = true;
option (gogoproto.testgen_all) = true;
option (gogoproto.equal_all) = true;
option (gogoproto.testgen_all) = true;
//----------------------------------------
// Request types
message Request {
oneof value {
RequestEcho echo = 2;
RequestFlush flush = 3;
RequestInfo info = 4;
RequestSetOption set_option = 5;
RequestInitChain init_chain = 6;
RequestQuery query = 7;
RequestEcho echo = 2;
RequestFlush flush = 3;
RequestInfo info = 4;
RequestSetOption set_option = 5;
RequestInitChain init_chain = 6;
RequestQuery query = 7;
RequestBeginBlock begin_block = 8;
RequestCheckTx check_tx = 9;
RequestDeliverTx deliver_tx = 19;
RequestEndBlock end_block = 11;
RequestCommit commit = 12;
RequestCheckTx check_tx = 9;
RequestDeliverTx deliver_tx = 19;
RequestEndBlock end_block = 11;
RequestCommit commit = 12;
}
}
@ -46,50 +46,49 @@ message RequestEcho {
string message = 1;
}
message RequestFlush {
}
message RequestFlush {}
message RequestInfo {
string version = 1;
string version = 1;
uint64 block_version = 2;
uint64 p2p_version = 3;
uint64 p2p_version = 3;
}
// nondeterministic
message RequestSetOption {
string key = 1;
string key = 1;
string value = 2;
}
message RequestInitChain {
google.protobuf.Timestamp time = 1 [(gogoproto.nullable)=false, (gogoproto.stdtime)=true];
string chain_id = 2;
ConsensusParams consensus_params = 3;
repeated ValidatorUpdate validators = 4 [(gogoproto.nullable)=false];
bytes app_state_bytes = 5;
google.protobuf.Timestamp time = 1 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true];
string chain_id = 2;
ConsensusParams consensus_params = 3;
repeated ValidatorUpdate validators = 4 [(gogoproto.nullable) = false];
bytes app_state_bytes = 5;
}
message RequestQuery {
bytes data = 1;
string path = 2;
int64 height = 3;
bool prove = 4;
bytes data = 1;
string path = 2;
int64 height = 3;
bool prove = 4;
}
message RequestBeginBlock {
bytes hash = 1;
Header header = 2 [(gogoproto.nullable)=false];
LastCommitInfo last_commit_info = 3 [(gogoproto.nullable)=false];
repeated Evidence byzantine_validators = 4 [(gogoproto.nullable)=false];
bytes hash = 1;
Header header = 2 [(gogoproto.nullable) = false];
LastCommitInfo last_commit_info = 3 [(gogoproto.nullable) = false];
repeated Evidence byzantine_validators = 4 [(gogoproto.nullable) = false];
}
enum CheckTxType {
New = 0;
New = 0;
Recheck = 1;
}
message RequestCheckTx {
bytes tx = 1;
bytes tx = 1;
CheckTxType type = 2;
}
@ -101,26 +100,25 @@ message RequestEndBlock {
int64 height = 1;
}
message RequestCommit {
}
message RequestCommit {}
//----------------------------------------
// Response types
message Response {
oneof value {
ResponseException exception = 1;
ResponseEcho echo = 2;
ResponseFlush flush = 3;
ResponseInfo info = 4;
ResponseSetOption set_option = 5;
ResponseInitChain init_chain = 6;
ResponseQuery query = 7;
ResponseException exception = 1;
ResponseEcho echo = 2;
ResponseFlush flush = 3;
ResponseInfo info = 4;
ResponseSetOption set_option = 5;
ResponseInitChain init_chain = 6;
ResponseQuery query = 7;
ResponseBeginBlock begin_block = 8;
ResponseCheckTx check_tx = 9;
ResponseDeliverTx deliver_tx = 10;
ResponseEndBlock end_block = 11;
ResponseCommit commit = 12;
ResponseCheckTx check_tx = 9;
ResponseDeliverTx deliver_tx = 10;
ResponseEndBlock end_block = 11;
ResponseCommit commit = 12;
}
}
@ -133,16 +131,15 @@ message ResponseEcho {
string message = 1;
}
message ResponseFlush {
}
message ResponseFlush {}
message ResponseInfo {
string data = 1;
string version = 2;
string version = 2;
uint64 app_version = 3;
int64 last_block_height = 4;
int64 last_block_height = 4;
bytes last_block_app_hash = 5;
}
@ -150,58 +147,62 @@ message ResponseInfo {
message ResponseSetOption {
uint32 code = 1;
// bytes data = 2;
string log = 3;
string log = 3;
string info = 4;
}
message ResponseInitChain {
ConsensusParams consensus_params = 1;
repeated ValidatorUpdate validators = 2 [(gogoproto.nullable)=false];
ConsensusParams consensus_params = 1;
repeated ValidatorUpdate validators = 2 [(gogoproto.nullable) = false];
}
message ResponseQuery {
uint32 code = 1;
// bytes data = 2; // use "value" instead.
string log = 3; // nondeterministic
string info = 4; // nondeterministic
int64 index = 5;
bytes key = 6;
bytes value = 7;
tendermint.crypto.merkle.Proof proof = 8;
int64 height = 9;
string codespace = 10;
string log = 3; // nondeterministic
string info = 4; // nondeterministic
int64 index = 5;
bytes key = 6;
bytes value = 7;
tendermint.crypto.merkle.Proof proof = 8;
int64 height = 9;
string codespace = 10;
}
message ResponseBeginBlock {
repeated Event events = 1 [(gogoproto.nullable)=false, (gogoproto.jsontag)="events,omitempty"];
repeated Event events = 1
[(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"];
}
message ResponseCheckTx {
uint32 code = 1;
bytes data = 2;
string log = 3; // nondeterministic
string info = 4; // nondeterministic
int64 gas_wanted = 5;
int64 gas_used = 6;
repeated Event events = 7 [(gogoproto.nullable)=false, (gogoproto.jsontag)="events,omitempty"];
uint32 code = 1;
bytes data = 2;
string log = 3; // nondeterministic
string info = 4; // nondeterministic
int64 gas_wanted = 5;
int64 gas_used = 6;
repeated Event events = 7
[(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"];
string codespace = 8;
}
message ResponseDeliverTx {
uint32 code = 1;
bytes data = 2;
string log = 3; // nondeterministic
string info = 4; // nondeterministic
int64 gas_wanted = 5;
int64 gas_used = 6;
repeated Event events = 7 [(gogoproto.nullable)=false, (gogoproto.jsontag)="events,omitempty"];
uint32 code = 1;
bytes data = 2;
string log = 3; // nondeterministic
string info = 4; // nondeterministic
int64 gas_wanted = 5;
int64 gas_used = 6;
repeated Event events = 7
[(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"];
string codespace = 8;
}
message ResponseEndBlock {
repeated ValidatorUpdate validator_updates = 1 [(gogoproto.nullable)=false];
ConsensusParams consensus_param_updates = 2;
repeated Event events = 3 [(gogoproto.nullable)=false, (gogoproto.jsontag)="events,omitempty"];
repeated ValidatorUpdate validator_updates = 1 [(gogoproto.nullable) = false];
ConsensusParams consensus_param_updates = 2;
repeated Event events = 3
[(gogoproto.nullable) = false, (gogoproto.jsontag) = "events,omitempty"];
}
message ResponseCommit {
@ -215,8 +216,8 @@ message ResponseCommit {
// ConsensusParams contains all consensus-relevant parameters
// that can be adjusted by the abci app
message ConsensusParams {
BlockParams block = 1;
EvidenceParams evidence = 2;
BlockParams block = 1;
EvidenceParams evidence = 2;
ValidatorParams validator = 3;
}
@ -230,8 +231,9 @@ message BlockParams {
message EvidenceParams {
// Note: must be greater than 0
int64 max_age_num_blocks = 1;
google.protobuf.Duration max_age_duration = 2 [(gogoproto.nullable)=false, (gogoproto.stdduration)=true];
int64 max_age_num_blocks = 1;
google.protobuf.Duration max_age_duration = 2
[(gogoproto.nullable) = false, (gogoproto.stdduration) = true];
}
// ValidatorParams contains limits on validators.
@ -240,13 +242,14 @@ message ValidatorParams {
}
message LastCommitInfo {
int32 round = 1;
repeated VoteInfo votes = 2 [(gogoproto.nullable)=false];
int32 round = 1;
repeated VoteInfo votes = 2 [(gogoproto.nullable) = false];
}
message Event {
string type = 1;
repeated tendermint.libs.kv.Pair attributes = 2 [(gogoproto.nullable)=false, (gogoproto.jsontag)="attributes,omitempty"];
string type = 1;
repeated tendermint.libs.kv.Pair attributes = 2
[(gogoproto.nullable) = false, (gogoproto.jsontag) = "attributes,omitempty"];
}
//----------------------------------------
@ -254,63 +257,62 @@ message Event {
message Header {
// basic block info
Version version = 1 [(gogoproto.nullable)=false];
string chain_id = 2 [(gogoproto.customname)="ChainID"];
int64 height = 3;
google.protobuf.Timestamp time = 4 [(gogoproto.nullable)=false, (gogoproto.stdtime)=true];
Version version = 1 [(gogoproto.nullable) = false];
string chain_id = 2 [(gogoproto.customname) = "ChainID"];
int64 height = 3;
google.protobuf.Timestamp time = 4 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true];
// prev block info
BlockID last_block_id = 5 [(gogoproto.nullable)=false];
BlockID last_block_id = 5 [(gogoproto.nullable) = false];
// hashes of block data
bytes last_commit_hash = 6; // commit from validators from the last block
bytes data_hash = 7; // transactions
bytes last_commit_hash = 6; // commit from validators from the last block
bytes data_hash = 7; // transactions
// hashes from the app output from the prev block
bytes validators_hash = 8; // validators for the current block
bytes validators_hash = 8; // validators for the current block
bytes next_validators_hash = 9; // validators for the next block
bytes consensus_hash = 10; // consensus params for current block
bytes app_hash = 11; // state after txs from the previous block
bytes last_results_hash = 12;// root hash of all results from the txs from the previous block
bytes consensus_hash = 10; // consensus params for current block
bytes app_hash = 11; // state after txs from the previous block
bytes last_results_hash = 12; // root hash of all results from the txs from the previous block
// consensus info
bytes evidence_hash = 13; // evidence included in the block
bytes proposer_address = 14; // original proposer of the block
bytes evidence_hash = 13; // evidence included in the block
bytes proposer_address = 14; // original proposer of the block
}
message Version {
uint64 Block = 1;
uint64 App = 2;
uint64 App = 2;
}
message BlockID {
bytes hash = 1;
PartSetHeader parts_header = 2 [(gogoproto.nullable)=false];
bytes hash = 1;
PartSetHeader parts_header = 2 [(gogoproto.nullable) = false];
}
message PartSetHeader {
int32 total = 1;
bytes hash = 2;
bytes hash = 2;
}
// Validator
message Validator {
bytes address = 1;
//PubKey pub_key = 2 [(gogoproto.nullable)=false];
// PubKey pub_key = 2 [(gogoproto.nullable)=false];
int64 power = 3;
}
// ValidatorUpdate
message ValidatorUpdate {
PubKey pub_key = 1 [(gogoproto.nullable)=false];
int64 power = 2;
PubKey pub_key = 1 [(gogoproto.nullable) = false];
int64 power = 2;
}
// VoteInfo
message VoteInfo {
Validator validator = 1 [(gogoproto.nullable)=false];
bool signed_last_block = 2;
Validator validator = 1 [(gogoproto.nullable) = false];
bool signed_last_block = 2;
}
message PubKey {
@ -319,18 +321,18 @@ message PubKey {
}
message Evidence {
string type = 1;
Validator validator = 2 [(gogoproto.nullable)=false];
int64 height = 3;
google.protobuf.Timestamp time = 4 [(gogoproto.nullable)=false, (gogoproto.stdtime)=true];
int64 total_voting_power = 5;
string type = 1;
Validator validator = 2 [(gogoproto.nullable) = false];
int64 height = 3;
google.protobuf.Timestamp time = 4 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true];
int64 total_voting_power = 5;
}
//----------------------------------------
// Service Definition
service ABCIApplication {
rpc Echo(RequestEcho) returns (ResponseEcho) ;
rpc Echo(RequestEcho) returns (ResponseEcho);
rpc Flush(RequestFlush) returns (ResponseFlush);
rpc Info(RequestInfo) returns (ResponseInfo);
rpc SetOption(RequestSetOption) returns (ResponseSetOption);

View File

@ -1,17 +1,17 @@
syntax = "proto3";
package tendermint.crypto.merkle;
option go_package = "github.com/tendermint/tendermint/crypto/merkle";
option go_package = "github.com/tendermint/tendermint/crypto/merkle";
// For more information on gogo.proto, see:
// https://github.com/gogo/protobuf/blob/master/extensions.md
import "third_party/proto/gogoproto/gogo.proto";
option (gogoproto.marshaler_all) = true;
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.populate_all) = true;
option (gogoproto.equal_all) = true;
option (gogoproto.equal_all) = true;
//----------------------------------------
// Message types
@ -21,11 +21,11 @@ option (gogoproto.equal_all) = true;
// for example neighbouring node hash
message ProofOp {
string type = 1;
bytes key = 2;
bytes data = 3;
bytes key = 2;
bytes data = 3;
}
// Proof is Merkle proof defined by the list of ProofOps
message Proof {
repeated ProofOp ops = 1 [(gogoproto.nullable)=false];
repeated ProofOp ops = 1 [(gogoproto.nullable) = false];
}

View File

@ -1,29 +1,29 @@
syntax = "proto3";
package tendermint.libs.kv;
option go_package = "github.com/tendermint/tendermint/libs/kv";
option go_package = "github.com/tendermint/tendermint/libs/kv";
import "third_party/proto/gogoproto/gogo.proto";
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.marshaler_all) = true;
option (gogoproto.unmarshaler_all) = true;
option (gogoproto.sizer_all) = true;
option (gogoproto.goproto_registration) = true;
// Generate tests
option (gogoproto.populate_all) = true;
option (gogoproto.equal_all) = true;
option (gogoproto.testgen_all) = true;
option (gogoproto.equal_all) = true;
option (gogoproto.testgen_all) = true;
//----------------------------------------
// Abstract types
// Define these here for compatibility but use tmlibs/common.KVPair.
// Define these here for compatibility but use tmlibs/kv.Pair.
message Pair {
bytes key = 1;
bytes key = 1;
bytes value = 2;
}
// Define these here for compatibility but use tmlibs/common.KI64Pair.
// Define these here for compatibility but use tmlibs/kv.KI64Pair.
message KI64Pair {
bytes key = 1;
bytes key = 1;
int64 value = 2;
}

View File

@ -154,10 +154,9 @@ func errIsNil(err error) bool {
return false
}
// Redact replace all errors that do not initialize with a weave error with a
// generic internal error instance. This function is supposed to hide
// implementation details errors and leave only those that weave framework
// originates.
// Redact replaces an error that is not initialized as an ABCI Error with a
// generic internal error instance. If the error is an ABCI Error, that error is
// simply returned.
func Redact(err error) error {
if ErrPanic.Is(err) {
return errors.New(internalABCILog)

View File

@ -48,9 +48,8 @@ type AppModuleBasic interface {
Name() string
RegisterCodec(*codec.Codec)
// genesis
DefaultGenesis() json.RawMessage
ValidateGenesis(json.RawMessage) error
DefaultGenesis(codec.JSONMarshaler) json.RawMessage
ValidateGenesis(codec.JSONMarshaler, json.RawMessage) error
// client functionality
RegisterRESTRoutes(context.CLIContext, *mux.Router)
@ -78,21 +77,23 @@ func (bm BasicManager) RegisterCodec(cdc *codec.Codec) {
}
// DefaultGenesis provides default genesis information for all modules
func (bm BasicManager) DefaultGenesis() map[string]json.RawMessage {
func (bm BasicManager) DefaultGenesis(cdc codec.JSONMarshaler) map[string]json.RawMessage {
genesis := make(map[string]json.RawMessage)
for _, b := range bm {
genesis[b.Name()] = b.DefaultGenesis()
genesis[b.Name()] = b.DefaultGenesis(cdc)
}
return genesis
}
// ValidateGenesis performs genesis state validation for all modules
func (bm BasicManager) ValidateGenesis(genesis map[string]json.RawMessage) error {
func (bm BasicManager) ValidateGenesis(cdc codec.JSONMarshaler, genesis map[string]json.RawMessage) error {
for _, b := range bm {
if err := b.ValidateGenesis(genesis[b.Name()]); err != nil {
if err := b.ValidateGenesis(cdc, genesis[b.Name()]); err != nil {
return err
}
}
return nil
}
@ -126,8 +127,9 @@ func (bm BasicManager) AddQueryCommands(rootQueryCmd *cobra.Command, cdc *codec.
// AppModuleGenesis is the standard form for an application module genesis functions
type AppModuleGenesis interface {
AppModuleBasic
InitGenesis(sdk.Context, json.RawMessage) []abci.ValidatorUpdate
ExportGenesis(sdk.Context) json.RawMessage
InitGenesis(sdk.Context, codec.JSONMarshaler, json.RawMessage) []abci.ValidatorUpdate
ExportGenesis(sdk.Context, codec.JSONMarshaler) json.RawMessage
}
// AppModule is the standard form for an application module
@ -256,13 +258,14 @@ func (m *Manager) RegisterRoutes(router sdk.Router, queryRouter sdk.QueryRouter)
}
// InitGenesis performs init genesis functionality for modules
func (m *Manager) InitGenesis(ctx sdk.Context, genesisData map[string]json.RawMessage) abci.ResponseInitChain {
func (m *Manager) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, genesisData map[string]json.RawMessage) abci.ResponseInitChain {
var validatorUpdates []abci.ValidatorUpdate
for _, moduleName := range m.OrderInitGenesis {
if genesisData[moduleName] == nil {
continue
}
moduleValUpdates := m.Modules[moduleName].InitGenesis(ctx, genesisData[moduleName])
moduleValUpdates := m.Modules[moduleName].InitGenesis(ctx, cdc, genesisData[moduleName])
// use these validator updates if provided, the module manager assumes
// only one module will update the validator set
@ -273,17 +276,19 @@ func (m *Manager) InitGenesis(ctx sdk.Context, genesisData map[string]json.RawMe
validatorUpdates = moduleValUpdates
}
}
return abci.ResponseInitChain{
Validators: validatorUpdates,
}
}
// ExportGenesis performs export genesis functionality for modules
func (m *Manager) ExportGenesis(ctx sdk.Context) map[string]json.RawMessage {
func (m *Manager) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) map[string]json.RawMessage {
genesisData := make(map[string]json.RawMessage)
for _, moduleName := range m.OrderExportGenesis {
genesisData[moduleName] = m.Modules[moduleName].ExportGenesis(ctx)
genesisData[moduleName] = m.Modules[moduleName].ExportGenesis(ctx, cdc)
}
return genesisData
}

View File

@ -1,7 +1,7 @@
package types
import (
_ "github.com/gogo/protobuf/gogoproto" // nolint
_ "github.com/gogo/protobuf/gogoproto" // nolint
_ "github.com/regen-network/cosmos-proto" // nolint
)

View File

@ -2,9 +2,27 @@ package types
import "regexp"
// IsAlphaNumeric defines a regular expression for matching against alpha-numeric
// values.
var IsAlphaNumeric = regexp.MustCompile(`^[a-zA-Z0-9]+$`).MatchString
var (
// IsAlphaNumeric defines a regular expression for matching against alpha-numeric
// values.
IsAlphaNumeric = regexp.MustCompile(`^[a-zA-Z0-9]+$`).MatchString
// IsAlphaLower defines regular expression to check if the string has lowercase
// alphabetic characters only.
IsAlphaLower = regexp.MustCompile(`^[a-z]+$`).MatchString
// IsAlphaUpper defines regular expression to check if the string has uppercase
// alphabetic characters only.
IsAlphaUpper = regexp.MustCompile(`^[A-Z]+$`).MatchString
// IsAlpha defines regular expression to check if the string has alphabetic
// characters only.
IsAlpha = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString
// IsNumeric defines regular expression to check if the string has numeric
// characters only.
IsNumeric = regexp.MustCompile(`^[0-9]+$`).MatchString
)
// Router provides handlers for each transaction type.
type Router interface {

View File

@ -250,28 +250,83 @@ func init() {
func init() { proto.RegisterFile("types/types.proto", fileDescriptor_2c0f90c600ad7e2e) }
var fileDescriptor_2c0f90c600ad7e2e = []byte{
// 298 bytes of a gzipped FileDescriptorProto
// 305 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x2c, 0xa9, 0x2c, 0x48,
0x2d, 0xd6, 0x07, 0x93, 0x7a, 0x05, 0x45, 0xf9, 0x25, 0xf9, 0x42, 0xbc, 0xc9, 0xf9, 0xc5, 0xb9,
0xf9, 0xc5, 0xf1, 0xc5, 0x29, 0xd9, 0x7a, 0x65, 0x86, 0x52, 0x6a, 0x25, 0x19, 0x99, 0x45, 0x29,
0xf1, 0x05, 0x89, 0x45, 0x25, 0x95, 0xfa, 0x60, 0x15, 0xfa, 0xe9, 0xf9, 0xe9, 0xf9, 0x08, 0x16,
0x44, 0x9b, 0x92, 0x23, 0x17, 0x8b, 0x73, 0x7e, 0x66, 0x9e, 0x90, 0x08, 0x17, 0x6b, 0x4a, 0x6a,
0x44, 0x9b, 0x92, 0x3b, 0x17, 0x8b, 0x73, 0x7e, 0x66, 0x9e, 0x90, 0x08, 0x17, 0x6b, 0x4a, 0x6a,
0x5e, 0x7e, 0xae, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x67, 0x10, 0x84, 0x23, 0xa4, 0xcc, 0xc5, 0x96,
0x98, 0x9b, 0x5f, 0x9a, 0x57, 0x22, 0xc1, 0x04, 0x12, 0x76, 0xe2, 0x3e, 0x71, 0x4f, 0x9e, 0xe1,
0xd6, 0x3d, 0x79, 0x66, 0xcf, 0xbc, 0x92, 0x20, 0xa8, 0x94, 0x92, 0x0b, 0x17, 0xbb, 0x4b, 0x6a,
0x32, 0x39, 0xa6, 0xb8, 0xa4, 0x26, 0xc3, 0x4d, 0xd1, 0xe4, 0xe2, 0xf0, 0xcc, 0x2b, 0x09, 0x00,
0xfb, 0x45, 0x96, 0x8b, 0x39, 0x33, 0xaf, 0x04, 0x62, 0x08, 0xaa, 0x9d, 0x20, 0x71, 0x90, 0x52,
0x97, 0xd4, 0x64, 0xb8, 0xd2, 0x94, 0xd4, 0x64, 0x74, 0xa5, 0x20, 0x83, 0x41, 0xe2, 0x4a, 0x4e,
0x5c, 0x3c, 0x61, 0x89, 0x39, 0x8e, 0x29, 0x29, 0x45, 0xa9, 0xc5, 0xc5, 0xa9, 0xc5, 0x42, 0x3a,
0x5c, 0x9c, 0x89, 0x30, 0x8e, 0x04, 0xa3, 0x02, 0xb3, 0x06, 0x8f, 0x13, 0xdf, 0xaf, 0x7b, 0xf2,
0x5c, 0x08, 0x45, 0x41, 0x08, 0x05, 0x56, 0x2c, 0x0d, 0x77, 0x14, 0x18, 0x9d, 0x5c, 0x6e, 0x3c,
0x94, 0x63, 0x68, 0x78, 0x24, 0xc7, 0x70, 0xe2, 0x91, 0x1c, 0xe3, 0x85, 0x47, 0x72, 0x8c, 0x0f,
0x1e, 0xc9, 0x31, 0x4e, 0x78, 0x2c, 0xc7, 0x70, 0xe1, 0xb1, 0x1c, 0xc3, 0x8d, 0xc7, 0x72, 0x0c,
0x51, 0x4a, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x90, 0x68, 0x80,
0x52, 0xba, 0xc5, 0x29, 0xd9, 0x90, 0x58, 0x4a, 0x62, 0x03, 0x87, 0xb7, 0x31, 0x20, 0x00, 0x00,
0xff, 0xff, 0xd6, 0x08, 0x09, 0x0f, 0xbb, 0x01, 0x00, 0x00,
0xd6, 0x3d, 0x79, 0x66, 0xcf, 0xbc, 0x92, 0x20, 0xa8, 0x94, 0x15, 0xcb, 0x8b, 0x05, 0xf2, 0x8c,
0x4a, 0x5e, 0x5c, 0xec, 0x2e, 0xa9, 0xc9, 0xe4, 0x98, 0xe5, 0x92, 0x9a, 0x8c, 0x66, 0x96, 0x26,
0x17, 0x87, 0x67, 0x5e, 0x49, 0x00, 0xd8, 0x5f, 0xb2, 0x5c, 0xcc, 0x99, 0x79, 0x25, 0x10, 0xa3,
0x50, 0xed, 0x07, 0x89, 0x83, 0x94, 0xba, 0xa4, 0x26, 0xc3, 0x95, 0xa6, 0xa4, 0x26, 0xa3, 0x2b,
0x05, 0x19, 0x0f, 0x12, 0x57, 0x72, 0xe2, 0xe2, 0x09, 0x4b, 0xcc, 0x71, 0x4c, 0x49, 0x29, 0x4a,
0x2d, 0x2e, 0x4e, 0x2d, 0x16, 0xd2, 0xe1, 0xe2, 0x4c, 0x84, 0x71, 0x24, 0x18, 0x15, 0x98, 0x35,
0x78, 0x9c, 0xf8, 0x7e, 0xdd, 0x93, 0xe7, 0x42, 0x28, 0x0a, 0x42, 0x28, 0xb0, 0x62, 0x69, 0xb8,
0xa3, 0xc0, 0xe8, 0xe4, 0x72, 0xe3, 0xa1, 0x1c, 0x43, 0xc3, 0x23, 0x39, 0x86, 0x13, 0x8f, 0xe4,
0x18, 0x2f, 0x3c, 0x92, 0x63, 0x7c, 0xf0, 0x48, 0x8e, 0x71, 0xc2, 0x63, 0x39, 0x86, 0x0b, 0x8f,
0xe5, 0x18, 0x6e, 0x3c, 0x96, 0x63, 0x88, 0x52, 0x4a, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b,
0xce, 0xcf, 0xd5, 0x87, 0x44, 0x09, 0x94, 0xd2, 0x2d, 0x4e, 0xc9, 0x86, 0xc4, 0x58, 0x12, 0x1b,
0x38, 0xec, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xa7, 0x40, 0xd2, 0x04, 0xc7, 0x01, 0x00,
0x00,
}
func (this *Coin) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*Coin)
if !ok {
that2, ok := that.(Coin)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.Denom != that1.Denom {
return false
}
if !this.Amount.Equal(that1.Amount) {
return false
}
return true
}
func (this *DecCoin) Equal(that interface{}) bool {
if that == nil {
return this == nil
}
that1, ok := that.(*DecCoin)
if !ok {
that2, ok := that.(DecCoin)
if ok {
that1 = &that2
} else {
return false
}
}
if that1 == nil {
return this == nil
} else if this == nil {
return false
}
if this.Denom != that1.Denom {
return false
}
if !this.Amount.Equal(that1.Amount) {
return false
}
return true
}
func (m *Coin) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)

View File

@ -3,18 +3,19 @@ package cosmos_sdk.v1;
import "third_party/proto/gogoproto/gogo.proto";
option go_package = "github.com/cosmos/cosmos-sdk/types";
option go_package = "github.com/cosmos/cosmos-sdk/types";
option (gogoproto.goproto_stringer_all) = false;
option (gogoproto.stringer_all) = false;
option (gogoproto.stringer_all) = false;
// Coin defines a token with a denomination and an amount.
//
// NOTE: The amount field is an Int which implements the custom method
// signatures required by gogoproto.
message Coin {
string denom = 1;
string amount = 2
[ (gogoproto.customtype) = "Int", (gogoproto.nullable) = false ];
option (gogoproto.equal) = true;
string denom = 1;
string amount = 2 [(gogoproto.customtype) = "Int", (gogoproto.nullable) = false];
}
// DecCoin defines a token with a denomination and a decimal amount.
@ -22,26 +23,25 @@ message Coin {
// NOTE: The amount field is an Dec which implements the custom method
// signatures required by gogoproto.
message DecCoin {
string denom = 1;
string amount = 2
[ (gogoproto.customtype) = "Dec", (gogoproto.nullable) = false ];
option (gogoproto.equal) = true;
string denom = 1;
string amount = 2 [(gogoproto.customtype) = "Dec", (gogoproto.nullable) = false];
}
// IntProto defines a Protobuf wrapper around an Int object.
message IntProto {
string int = 1
[ (gogoproto.customtype) = "Int", (gogoproto.nullable) = false ];
string int = 1 [(gogoproto.customtype) = "Int", (gogoproto.nullable) = false];
}
// DecProto defines a Protobuf wrapper around a Dec object.
message DecProto {
string dec = 1
[ (gogoproto.customtype) = "Dec", (gogoproto.nullable) = false ];
string dec = 1 [(gogoproto.customtype) = "Dec", (gogoproto.nullable) = false];
}
// ValAddresses defines a repeated set of validator addresses.
message ValAddresses {
option (gogoproto.stringer) = true;
repeated bytes addresses = 1 [ (gogoproto.casttype) = "ValAddress" ];
}
repeated bytes addresses = 1 [(gogoproto.casttype) = "ValAddress"];
}

View File

@ -1,9 +1,3 @@
// nolint
// autogenerated code using github.com/rigelrozanski/multitool
// aliases generated for the following subdirectories:
// ALIASGEN: github.com/cosmos/cosmos-sdk/x/auth/ante
// ALIASGEN: github.com/cosmos/cosmos-sdk/x/auth/keeper
// ALIASGEN: github.com/cosmos/cosmos-sdk/x/auth/types
package auth
import (
@ -12,6 +6,9 @@ import (
"github.com/cosmos/cosmos-sdk/x/auth/types"
)
// DONTCOVER
// nolint
const (
ModuleName = types.ModuleName
StoreKey = types.StoreKey
@ -40,7 +37,6 @@ var (
NewBaseAccountWithAddress = types.NewBaseAccountWithAddress
NewAccountRetriever = types.NewAccountRetriever
RegisterCodec = types.RegisterCodec
RegisterAccountTypeCodec = types.RegisterAccountTypeCodec
NewGenesisState = types.NewGenesisState
DefaultGenesisState = types.DefaultGenesisState
ValidateGenesis = types.ValidateGenesis
@ -89,4 +85,5 @@ type (
StdSignature = types.StdSignature
TxBuilder = types.TxBuilder
GenesisAccountIterator = types.GenesisAccountIterator
Codec = types.Codec
)

View File

@ -1,6 +1,7 @@
package ante
import (
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
err "github.com/cosmos/cosmos-sdk/types/errors"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
@ -112,21 +113,24 @@ func (cgts ConsumeTxSizeGasDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, sim
if sigs[i] != nil {
continue
}
acc := cgts.ak.GetAccount(ctx, signer)
var pubkey crypto.PubKey
acc := cgts.ak.GetAccount(ctx, signer)
// use placeholder simSecp256k1Pubkey if sig is nil
if acc == nil || acc.GetPubKey() == nil {
pubkey = simSecp256k1Pubkey
} else {
pubkey = acc.GetPubKey()
}
// use stdsignature to mock the size of a full signature
simSig := types.StdSignature{
Signature: simSecp256k1Sig[:],
PubKey: pubkey,
}
sigBz := types.ModuleCdc.MustMarshalBinaryLengthPrefixed(simSig)
sigBz := codec.Cdc.MustMarshalBinaryLengthPrefixed(simSig)
cost := sdk.Gas(len(sigBz) + 6)
// If the pubkey is a multi-signature pubkey, then we estimate for the maximum

View File

@ -299,6 +299,7 @@ func (vscd ValidateSigCountDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, sim
func DefaultSigVerificationGasConsumer(
meter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params types.Params,
) error {
switch pubkey := pubkey.(type) {
case ed25519.PubKeyEd25519:
meter.ConsumeGas(params.SigVerifyCostED25519, "ante verify: ed25519")
@ -321,11 +322,13 @@ func DefaultSigVerificationGasConsumer(
}
// ConsumeMultisignatureVerificationGas consumes gas from a GasMeter for verifying a multisig pubkey signature
func ConsumeMultisignatureVerificationGas(meter sdk.GasMeter,
sig multisig.Multisignature, pubkey multisig.PubKeyMultisigThreshold,
params types.Params) {
func ConsumeMultisignatureVerificationGas(
meter sdk.GasMeter, sig multisig.Multisignature, pubkey multisig.PubKeyMultisigThreshold, params types.Params,
) {
size := sig.BitArray.Size()
sigIndex := 0
for i := 0; i < size; i++ {
if sig.BitArray.GetIndex(i) {
DefaultSigVerificationGasConsumer(meter, sig.Sigs[sigIndex], pubkey.PubKeys[i], params)
@ -340,5 +343,6 @@ func GetSignerAcc(ctx sdk.Context, ak keeper.AccountKeeper, addr sdk.AccAddress)
if acc := ak.GetAccount(ctx, addr); acc != nil {
return acc, nil
}
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", addr)
}

View File

@ -50,7 +50,7 @@ func GetAccountCmd(cdc *codec.Codec) *cobra.Command {
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cliCtx := context.NewCLIContext().WithCodec(cdc)
accGetter := types.NewAccountRetriever(cliCtx)
accGetter := types.NewAccountRetriever(authclient.Codec, cliCtx)
key, err := sdk.AccAddressFromBech32(args[0])
if err != nil {

View File

@ -86,7 +86,7 @@ func makeMultiSignCmd(cdc *codec.Codec) func(cmd *cobra.Command, args []string)
txBldr := types.NewTxBuilderFromCLI(inBuf)
if !viper.GetBool(flagOffline) {
accnum, seq, err := types.NewAccountRetriever(cliCtx).GetAccountNumberSequence(multisigInfo.GetAddress())
accnum, seq, err := types.NewAccountRetriever(client.Codec, cliCtx).GetAccountNumberSequence(multisigInfo.GetAddress())
if err != nil {
return err
}

View File

@ -224,7 +224,7 @@ func printAndValidateSigs(
// Validate the actual signature over the transaction bytes since we can
// reach out to a full node to query accounts.
if !offline && success {
acc, err := types.NewAccountRetriever(cliCtx).GetAccount(sigAddr)
acc, err := types.NewAccountRetriever(client.Codec, cliCtx).GetAccount(sigAddr)
if err != nil {
fmt.Printf("failed to get account: %s\n", sigAddr)
return false

View File

@ -33,7 +33,7 @@ func QueryAccountRequestHandlerFn(storeName string, cliCtx context.CLIContext) h
return
}
accGetter := types.NewAccountRetriever(cliCtx)
accGetter := types.NewAccountRetriever(client.Codec, cliCtx)
account, height, err := accGetter.GetAccountWithHeight(addr)
if err != nil {

View File

@ -19,6 +19,15 @@ import (
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
)
// Codec defines the x/auth account codec to be used for use with the
// AccountRetriever. The application must be sure to set this to their respective
// codec that implements the Codec interface and must be the same codec that
// passed to the x/auth module.
//
// TODO:/XXX: Using a package-level global isn't ideal and we should consider
// refactoring the module manager to allow passing in the correct module codec.
var Codec authtypes.Codec
// GasEstimateResponse defines a response definition for tx gas estimation.
type GasEstimateResponse struct {
GasEstimate uint64 `json:"gas_estimate" yaml:"gas_estimate"`
@ -198,9 +207,10 @@ func SignStdTx(
// SignStdTxWithSignerAddress attaches a signature to a StdTx and returns a copy of a it.
// Don't perform online validation or lookups if offline is true, else
// populate account and sequence numbers from a foreign account.
func SignStdTxWithSignerAddress(txBldr authtypes.TxBuilder, cliCtx context.CLIContext,
addr sdk.AccAddress, name string, stdTx authtypes.StdTx,
offline bool) (signedStdTx authtypes.StdTx, err error) {
func SignStdTxWithSignerAddress(
txBldr authtypes.TxBuilder, cliCtx context.CLIContext,
addr sdk.AccAddress, name string, stdTx authtypes.StdTx, offline bool,
) (signedStdTx authtypes.StdTx, err error) {
// check whether the address is a signer
if !isTxSigner(addr, stdTx.GetSigners()) {
@ -242,7 +252,7 @@ func populateAccountFromState(
txBldr authtypes.TxBuilder, cliCtx context.CLIContext, addr sdk.AccAddress,
) (authtypes.TxBuilder, error) {
num, seq, err := authtypes.NewAccountRetriever(cliCtx).GetAccountNumberSequence(addr)
num, seq, err := authtypes.NewAccountRetriever(Codec, cliCtx).GetAccountNumberSequence(addr)
if err != nil {
return txBldr, err
}
@ -290,7 +300,7 @@ func parseQueryResponse(cdc *codec.Codec, rawRes []byte) (uint64, error) {
func PrepareTxBuilder(txBldr authtypes.TxBuilder, cliCtx context.CLIContext) (authtypes.TxBuilder, error) {
from := cliCtx.GetFromAddress()
accGetter := authtypes.NewAccountRetriever(cliCtx)
accGetter := authtypes.NewAccountRetriever(Codec, cliCtx)
if err := accGetter.EnsureExists(from); err != nil {
return txBldr, err
}
@ -299,7 +309,7 @@ func PrepareTxBuilder(txBldr authtypes.TxBuilder, cliCtx context.CLIContext) (au
// TODO: (ref #1903) Allow for user supplied account number without
// automatically doing a manual lookup.
if txbldrAccNum == 0 || txbldrAccSeq == 0 {
num, seq, err := authtypes.NewAccountRetriever(cliCtx).GetAccountNumberSequence(from)
num, seq, err := authtypes.NewAccountRetriever(Codec, cliCtx).GetAccountNumberSequence(from)
if err != nil {
return txBldr, err
}

View File

@ -13,6 +13,7 @@ func (ak AccountKeeper) NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddre
if err != nil {
panic(err)
}
return ak.NewAccount(ctx, acc)
}
@ -21,6 +22,7 @@ func (ak AccountKeeper) NewAccount(ctx sdk.Context, acc exported.Account) export
if err := acc.SetAccountNumber(ak.GetNextAccountNumber(ctx)); err != nil {
panic(err)
}
return acc
}
@ -31,17 +33,17 @@ func (ak AccountKeeper) GetAccount(ctx sdk.Context, addr sdk.AccAddress) exporte
if bz == nil {
return nil
}
acc := ak.decodeAccount(bz)
return acc
return ak.decodeAccount(bz)
}
// GetAllAccounts returns all accounts in the accountKeeper.
func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) (accounts []exported.Account) {
ak.IterateAccounts(ctx,
func(acc exported.Account) (stop bool) {
accounts = append(accounts, acc)
return false
})
ak.IterateAccounts(ctx, func(acc exported.Account) (stop bool) {
accounts = append(accounts, acc)
return false
})
return accounts
}
@ -49,10 +51,12 @@ func (ak AccountKeeper) GetAllAccounts(ctx sdk.Context) (accounts []exported.Acc
func (ak AccountKeeper) SetAccount(ctx sdk.Context, acc exported.Account) {
addr := acc.GetAddress()
store := ctx.KVStore(ak.key)
bz, err := ak.cdc.MarshalBinaryBare(acc)
bz, err := ak.cdc.MarshalAccount(acc)
if err != nil {
panic(err)
}
store.Set(types.AddressStoreKey(addr), bz)
}

View File

@ -3,37 +3,32 @@ package keeper
import (
"fmt"
gogotypes "github.com/gogo/protobuf/types"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/libs/log"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/auth/exported"
"github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/params/subspace"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
)
// AccountKeeper encodes/decodes accounts using the go-amino (binary)
// encoding/decoding library.
type AccountKeeper struct {
// The (unexposed) key used to access the store from the Context.
key sdk.StoreKey
key sdk.StoreKey
cdc types.Codec
paramSubspace paramtypes.Subspace
// The prototypical Account constructor.
proto func() exported.Account
// The codec codec for binary encoding/decoding of accounts.
cdc *codec.Codec
paramSubspace subspace.Subspace
}
// NewAccountKeeper returns a new sdk.AccountKeeper that uses go-amino to
// (binary) encode and decode concrete sdk.Accounts.
// nolint
func NewAccountKeeper(
cdc *codec.Codec, key sdk.StoreKey, paramstore subspace.Subspace, proto func() exported.Account,
cdc types.Codec, key sdk.StoreKey, paramstore paramtypes.Subspace, proto func() exported.Account,
) AccountKeeper {
return AccountKeeper{
@ -55,6 +50,7 @@ func (ak AccountKeeper) GetPubKey(ctx sdk.Context, addr sdk.AccAddress) (crypto.
if acc == nil {
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", addr)
}
return acc.GetPubKey(), nil
}
@ -64,6 +60,7 @@ func (ak AccountKeeper) GetSequence(ctx sdk.Context, addr sdk.AccAddress) (uint6
if acc == nil {
return 0, sdkerrors.Wrapf(sdkerrors.ErrUnknownAddress, "account %s does not exist", addr)
}
return acc.GetSequence(), nil
}
@ -72,30 +69,33 @@ func (ak AccountKeeper) GetSequence(ctx sdk.Context, addr sdk.AccAddress) (uint6
func (ak AccountKeeper) GetNextAccountNumber(ctx sdk.Context) uint64 {
var accNumber uint64
store := ctx.KVStore(ak.key)
bz := store.Get(types.GlobalAccountNumberKey)
if bz == nil {
// initialize the account numbers
accNumber = 0
} else {
err := ak.cdc.UnmarshalBinaryLengthPrefixed(bz, &accNumber)
val := gogotypes.UInt64Value{}
err := ak.cdc.UnmarshalBinaryLengthPrefixed(bz, &val)
if err != nil {
panic(err)
}
accNumber = val.GetValue()
}
bz = ak.cdc.MustMarshalBinaryLengthPrefixed(accNumber + 1)
bz = ak.cdc.MustMarshalBinaryLengthPrefixed(&gogotypes.UInt64Value{Value: accNumber + 1})
store.Set(types.GlobalAccountNumberKey, bz)
return accNumber
}
// -----------------------------------------------------------------------------
// Misc.
func (ak AccountKeeper) decodeAccount(bz []byte) (acc exported.Account) {
err := ak.cdc.UnmarshalBinaryBare(bz, &acc)
func (ak AccountKeeper) decodeAccount(bz []byte) exported.Account {
acc, err := ak.cdc.UnmarshalAccount(bz)
if err != nil {
panic(err)
}
return
return acc
}

View File

@ -41,14 +41,14 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {
// DefaultGenesis returns default genesis state as raw bytes for the auth
// module.
func (AppModuleBasic) DefaultGenesis() json.RawMessage {
return types.ModuleCdc.MustMarshalJSON(types.DefaultGenesisState())
func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage {
return cdc.MustMarshalJSON(types.DefaultGenesisState())
}
// ValidateGenesis performs genesis state validation for the auth module.
func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error {
func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessage) error {
var data types.GenesisState
if err := types.ModuleCdc.UnmarshalJSON(bz, &data); err != nil {
if err := cdc.UnmarshalJSON(bz, &data); err != nil {
return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err)
}
@ -113,18 +113,18 @@ func (am AppModule) NewQuerierHandler() sdk.Querier {
// InitGenesis performs genesis initialization for the auth module. It returns
// no validator updates.
func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate {
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate {
var genesisState GenesisState
types.ModuleCdc.MustUnmarshalJSON(data, &genesisState)
cdc.MustUnmarshalJSON(data, &genesisState)
InitGenesis(ctx, am.accountKeeper, genesisState)
return []abci.ValidatorUpdate{}
}
// ExportGenesis returns the exported genesis state as raw bytes for the auth
// module.
func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage {
func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage {
gs := ExportGenesis(ctx, am.accountKeeper)
return types.ModuleCdc.MustMarshalJSON(gs)
return cdc.MustMarshalJSON(gs)
}
// BeginBlock returns the begin blocker for the auth module.

View File

@ -19,11 +19,13 @@ func DecodeStore(cdc *codec.Codec, kvA, kvB tmkv.Pair) string {
cdc.MustUnmarshalBinaryBare(kvA.Value, &accA)
cdc.MustUnmarshalBinaryBare(kvB.Value, &accB)
return fmt.Sprintf("%v\n%v", accA, accB)
case bytes.Equal(kvA.Key, types.GlobalAccountNumberKey):
var globalAccNumberA, globalAccNumberB uint64
cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &globalAccNumberA)
cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &globalAccNumberB)
return fmt.Sprintf("GlobalAccNumberA: %d\nGlobalAccNumberB: %d", globalAccNumberA, globalAccNumberB)
default:
panic(fmt.Sprintf("invalid account key %X", kvA.Key))
}

View File

@ -98,7 +98,7 @@ func RandomizedGenState(simState *module.SimulationState) {
func RandomGenesisAccounts(simState *module.SimulationState) (genesisAccs exported.GenesisAccounts) {
for i, acc := range simState.Accounts {
bacc := types.NewBaseAccountWithAddress(acc.Address)
var gacc exported.GenesisAccount = &bacc
var gacc exported.GenesisAccount = bacc
// Only consider making a vesting account once the initial bonded validator
// set is exhausted due to needing to track DelegatedVesting.
@ -115,7 +115,7 @@ func RandomGenesisAccounts(simState *module.SimulationState) (genesisAccs export
endTime = int64(simulation.RandIntBetween(simState.Rand, int(startTime)+1, int(startTime+(60*60*12))))
}
bva := vestingtypes.NewBaseVestingAccount(&bacc, initialVesting, endTime)
bva := vestingtypes.NewBaseVestingAccount(bacc, initialVesting, endTime)
if simState.Rand.Intn(100) < 50 {
gacc = vestingtypes.NewContinuousVestingAccountRaw(bva, startTime)

View File

@ -2,41 +2,29 @@ package types
import (
"bytes"
"encoding/json"
"errors"
"github.com/tendermint/tendermint/crypto"
yaml "gopkg.in/yaml.v2"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/exported"
)
//-----------------------------------------------------------------------------
// BaseAccount
var _ exported.Account = (*BaseAccount)(nil)
var _ exported.GenesisAccount = (*BaseAccount)(nil)
// BaseAccount - a base account structure.
// This can be extended by embedding within in your AppAccount.
// However one doesn't have to use BaseAccount as long as your struct
// implements Account.
type BaseAccount struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
PubKey crypto.PubKey `json:"public_key" yaml:"public_key"`
AccountNumber uint64 `json:"account_number" yaml:"account_number"`
Sequence uint64 `json:"sequence" yaml:"sequence"`
}
// NewBaseAccount creates a new BaseAccount object
func NewBaseAccount(address sdk.AccAddress, pubKey crypto.PubKey, accountNumber, sequence uint64) *BaseAccount {
return &BaseAccount{
acc := &BaseAccount{
Address: address,
PubKey: pubKey,
AccountNumber: accountNumber,
Sequence: sequence,
}
acc.SetPubKey(pubKey)
return acc
}
// ProtoBaseAccount - a prototype function for BaseAccount
@ -45,8 +33,8 @@ func ProtoBaseAccount() exported.Account {
}
// NewBaseAccountWithAddress - returns a new base account with a given address
func NewBaseAccountWithAddress(addr sdk.AccAddress) BaseAccount {
return BaseAccount{
func NewBaseAccountWithAddress(addr sdk.AccAddress) *BaseAccount {
return &BaseAccount{
Address: addr,
}
}
@ -61,23 +49,34 @@ func (acc *BaseAccount) SetAddress(addr sdk.AccAddress) error {
if len(acc.Address) != 0 {
return errors.New("cannot override BaseAccount address")
}
acc.Address = addr
return nil
}
// GetPubKey - Implements sdk.Account.
func (acc BaseAccount) GetPubKey() crypto.PubKey {
return acc.PubKey
func (acc BaseAccount) GetPubKey() (pk crypto.PubKey) {
if len(acc.PubKey) == 0 {
return nil
}
codec.Cdc.MustUnmarshalBinaryBare(acc.PubKey, &pk)
return pk
}
// SetPubKey - Implements sdk.Account.
func (acc *BaseAccount) SetPubKey(pubKey crypto.PubKey) error {
acc.PubKey = pubKey
if pubKey == nil {
acc.PubKey = nil
} else {
acc.PubKey = pubKey.Bytes()
}
return nil
}
// GetAccountNumber - Implements Account
func (acc *BaseAccount) GetAccountNumber() uint64 {
func (acc BaseAccount) GetAccountNumber() uint64 {
return acc.AccountNumber
}
@ -88,7 +87,7 @@ func (acc *BaseAccount) SetAccountNumber(accNumber uint64) error {
}
// GetSequence - Implements sdk.Account.
func (acc *BaseAccount) GetSequence() uint64 {
func (acc BaseAccount) GetSequence() uint64 {
return acc.Sequence
}
@ -100,14 +99,19 @@ func (acc *BaseAccount) SetSequence(seq uint64) error {
// Validate checks for errors on the account fields
func (acc BaseAccount) Validate() error {
if acc.PubKey != nil && acc.Address != nil &&
!bytes.Equal(acc.PubKey.Address().Bytes(), acc.Address.Bytes()) {
return errors.New("pubkey and address pair is invalid")
if len(acc.PubKey) != 0 && acc.Address != nil &&
!bytes.Equal(acc.GetPubKey().Address().Bytes(), acc.Address.Bytes()) {
return errors.New("account address and pubkey address do not match")
}
return nil
}
func (acc BaseAccount) String() string {
out, _ := acc.MarshalYAML()
return out.(string)
}
type baseAccountPretty struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
PubKey string `json:"public_key" yaml:"public_key"`
@ -115,11 +119,6 @@ type baseAccountPretty struct {
Sequence uint64 `json:"sequence" yaml:"sequence"`
}
func (acc BaseAccount) String() string {
out, _ := acc.MarshalYAML()
return out.(string)
}
// MarshalYAML returns the YAML representation of an account.
func (acc BaseAccount) MarshalYAML() (interface{}, error) {
alias := baseAccountPretty{
@ -129,7 +128,7 @@ func (acc BaseAccount) MarshalYAML() (interface{}, error) {
}
if acc.PubKey != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, acc.PubKey)
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, acc.GetPubKey())
if err != nil {
return nil, err
}
@ -144,46 +143,3 @@ func (acc BaseAccount) MarshalYAML() (interface{}, error) {
return string(bz), err
}
// MarshalJSON returns the JSON representation of a BaseAccount.
func (acc BaseAccount) MarshalJSON() ([]byte, error) {
alias := baseAccountPretty{
Address: acc.Address,
AccountNumber: acc.AccountNumber,
Sequence: acc.Sequence,
}
if acc.PubKey != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, acc.PubKey)
if err != nil {
return nil, err
}
alias.PubKey = pks
}
return json.Marshal(alias)
}
// UnmarshalJSON unmarshals raw JSON bytes into a BaseAccount.
func (acc *BaseAccount) UnmarshalJSON(bz []byte) error {
var alias baseAccountPretty
if err := json.Unmarshal(bz, &alias); err != nil {
return err
}
if alias.PubKey != "" {
pk, err := sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeAccPub, alias.PubKey)
if err != nil {
return err
}
acc.PubKey = pk
}
acc.Address = alias.Address
acc.AccountNumber = alias.AccountNumber
acc.Sequence = alias.Sequence
return nil
}

View File

@ -18,12 +18,13 @@ type NodeQuerier interface {
// AccountRetriever defines the properties of a type that can be used to
// retrieve accounts.
type AccountRetriever struct {
codec Codec
querier NodeQuerier
}
// NewAccountRetriever initialises a new AccountRetriever instance.
func NewAccountRetriever(querier NodeQuerier) AccountRetriever {
return AccountRetriever{querier: querier}
func NewAccountRetriever(codec Codec, querier NodeQuerier) AccountRetriever {
return AccountRetriever{codec: codec, querier: querier}
}
// GetAccount queries for an account given an address and a block height. An
@ -37,18 +38,18 @@ func (ar AccountRetriever) GetAccount(addr sdk.AccAddress) (exported.Account, er
// height of the query with the account. An error is returned if the query
// or decoding fails.
func (ar AccountRetriever) GetAccountWithHeight(addr sdk.AccAddress) (exported.Account, int64, error) {
bs, err := ModuleCdc.MarshalJSON(NewQueryAccountParams(addr))
bs, err := ar.codec.MarshalJSON(NewQueryAccountParams(addr))
if err != nil {
return nil, 0, err
}
res, height, err := ar.querier.QueryWithData(fmt.Sprintf("custom/%s/%s", QuerierRoute, QueryAccount), bs)
bz, height, err := ar.querier.QueryWithData(fmt.Sprintf("custom/%s/%s", QuerierRoute, QueryAccount), bs)
if err != nil {
return nil, height, err
}
var account exported.Account
if err := ModuleCdc.UnmarshalJSON(res, &account); err != nil {
if err := ar.codec.UnmarshalJSON(bz, &account); err != nil {
return nil, height, err
}

View File

@ -1,4 +1,4 @@
package types
package types_test
import (
"errors"
@ -8,6 +8,7 @@ import (
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/tests/mocks"
"github.com/cosmos/cosmos-sdk/x/auth/types"
)
var errFoo = errors.New("dummy")
@ -17,9 +18,9 @@ func TestAccountRetriever(t *testing.T) {
defer mockCtrl.Finish()
mockNodeQuerier := mocks.NewMockNodeQuerier(mockCtrl)
accRetr := NewAccountRetriever(mockNodeQuerier)
accRetr := types.NewAccountRetriever(appCodec, mockNodeQuerier)
addr := []byte("test")
bs, err := ModuleCdc.MarshalJSON(NewQueryAccountParams(addr))
bs, err := appCodec.MarshalJSON(types.NewQueryAccountParams(addr))
require.NoError(t, err)
mockNodeQuerier.EXPECT().QueryWithData(gomock.Eq("custom/acc/account"),

View File

@ -1,22 +1,20 @@
package types
package types_test
import (
"encoding/json"
"errors"
"testing"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto/secp256k1"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/exported"
"github.com/cosmos/cosmos-sdk/x/auth/types"
)
func TestBaseAddressPubKey(t *testing.T) {
_, pub1, addr1 := KeyTestPubAddr()
_, pub2, addr2 := KeyTestPubAddr()
acc := NewBaseAccountWithAddress(addr1)
_, pub1, addr1 := types.KeyTestPubAddr()
_, pub2, addr2 := types.KeyTestPubAddr()
acc := types.NewBaseAccountWithAddress(addr1)
// check the address (set) and pubkey (not set)
require.EqualValues(t, addr1, acc.GetAddress())
@ -40,16 +38,15 @@ func TestBaseAddressPubKey(t *testing.T) {
//------------------------------------
// can set address on empty account
acc2 := BaseAccount{}
acc2 := types.BaseAccount{}
err = acc2.SetAddress(addr2)
require.Nil(t, err)
require.EqualValues(t, addr2, acc2.GetAddress())
}
func TestBaseAccountSequence(t *testing.T) {
_, _, addr := KeyTestPubAddr()
acc := NewBaseAccountWithAddress(addr)
_, _, addr := types.KeyTestPubAddr()
acc := types.NewBaseAccountWithAddress(addr)
seq := uint64(7)
err := acc.SetSequence(seq)
@ -58,9 +55,8 @@ func TestBaseAccountSequence(t *testing.T) {
}
func TestBaseAccountMarshal(t *testing.T) {
_, pub, addr := KeyTestPubAddr()
acc := NewBaseAccountWithAddress(addr)
_, pub, addr := types.KeyTestPubAddr()
acc := types.NewBaseAccountWithAddress(addr)
seq := uint64(7)
// set everything on the account
@ -69,73 +65,45 @@ func TestBaseAccountMarshal(t *testing.T) {
err = acc.SetSequence(seq)
require.Nil(t, err)
// need a codec for marshaling
cdc := codec.New()
codec.RegisterCrypto(cdc)
b, err := cdc.MarshalBinaryLengthPrefixed(acc)
bz, err := appCodec.MarshalAccount(acc)
require.Nil(t, err)
acc2 := BaseAccount{}
err = cdc.UnmarshalBinaryLengthPrefixed(b, &acc2)
acc2, err := appCodec.UnmarshalAccount(bz)
require.Nil(t, err)
require.Equal(t, acc, acc2)
// error on bad bytes
acc2 = BaseAccount{}
err = cdc.UnmarshalBinaryLengthPrefixed(b[:len(b)/2], &acc2)
_, err = appCodec.UnmarshalAccount(bz[:len(bz)/2])
require.NotNil(t, err)
}
func TestGenesisAccountValidate(t *testing.T) {
pubkey := secp256k1.GenPrivKey().PubKey()
addr := sdk.AccAddress(pubkey.Address())
baseAcc := NewBaseAccount(addr, pubkey, 0, 0)
baseAcc := types.NewBaseAccount(addr, pubkey, 0, 0)
tests := []struct {
name string
acc exported.GenesisAccount
expErr error
expErr bool
}{
{
"valid base account",
baseAcc,
nil,
false,
},
{
"invalid base valid account",
NewBaseAccount(addr, secp256k1.GenPrivKey().PubKey(), 0, 0),
errors.New("pubkey and address pair is invalid"),
types.NewBaseAccount(addr, secp256k1.GenPrivKey().PubKey(), 0, 0),
true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
err := tt.acc.Validate()
require.Equal(t, tt.expErr, err)
require.Equal(t, tt.expErr, tt.acc.Validate() != nil)
})
}
}
func TestBaseAccountJSON(t *testing.T) {
pubkey := secp256k1.GenPrivKey().PubKey()
addr := sdk.AccAddress(pubkey.Address())
baseAcc := NewBaseAccount(addr, pubkey, 10, 50)
bz, err := json.Marshal(baseAcc)
require.NoError(t, err)
bz1, err := baseAcc.MarshalJSON()
require.NoError(t, err)
require.Equal(t, string(bz1), string(bz))
var a BaseAccount
require.NoError(t, json.Unmarshal(bz, &a))
require.Equal(t, baseAcc.String(), a.String())
bz, err = ModuleCdc.MarshalJSON(baseAcc)
require.NoError(t, err)
var b BaseAccount
require.NoError(t, ModuleCdc.UnmarshalJSON(bz, &b))
require.Equal(t, baseAcc.String(), b.String())
}

View File

@ -5,10 +5,20 @@ import (
"github.com/cosmos/cosmos-sdk/x/auth/exported"
)
// ModuleCdc auth module wide codec
var ModuleCdc = codec.New()
// Codec defines the interface needed to serialize x/auth state. It must be
// aware of all concrete account types.
type Codec interface {
codec.Marshaler
// RegisterCodec registers concrete types on the codec
MarshalAccount(acc exported.Account) ([]byte, error)
UnmarshalAccount(bz []byte) (exported.Account, error)
MarshalAccountJSON(acc exported.Account) ([]byte, error)
UnmarshalAccountJSON(bz []byte) (exported.Account, error)
}
// RegisterCodec registers the account interfaces and concrete types on the
// provided Amino codec.
func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterInterface((*exported.GenesisAccount)(nil), nil)
cdc.RegisterInterface((*exported.Account)(nil), nil)
@ -16,13 +26,20 @@ func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(StdTx{}, "cosmos-sdk/StdTx", nil)
}
// RegisterAccountTypeCodec registers an external account type defined in
// another module for the internal ModuleCdc.
func RegisterAccountTypeCodec(o interface{}, name string) {
ModuleCdc.RegisterConcrete(o, name, nil)
}
var (
amino = codec.New()
// ModuleCdc references the global x/auth module codec. Note, the codec should
// ONLY be used in certain instances of tests and for JSON encoding as Amino is
// still used for that purpose.
//
// The actual codec used for serialization should be provided to x/auth and
// defined at the application level.
ModuleCdc = codec.NewHybridCodec(amino)
)
func init() {
RegisterCodec(ModuleCdc)
codec.RegisterCrypto(ModuleCdc)
RegisterCodec(amino)
codec.RegisterCrypto(amino)
amino.Seal()
}

View File

@ -0,0 +1,11 @@
package types_test
import (
"github.com/cosmos/cosmos-sdk/simapp"
simappcodec "github.com/cosmos/cosmos-sdk/simapp/codec"
)
var (
app = simapp.Setup(false)
appCodec = simappcodec.NewAppCodec(app.Codec())
)

View File

@ -1,8 +1,10 @@
package types
import "errors"
import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
var (
ErrorInvalidSigner = errors.New("tx intended signer does not match the given signer")
ErrorInvalidGasAdjustment = errors.New("invalid gas adjustment")
ErrorInvalidSigner = sdkerrors.Register(ModuleName, 2, "tx intended signer does not match the given signer")
ErrorInvalidGasAdjustment = sdkerrors.Register(ModuleName, 3, "invalid gas adjustment")
)

View File

@ -5,7 +5,6 @@ import (
"fmt"
"sort"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/x/auth/exported"
)
@ -30,7 +29,7 @@ func DefaultGenesisState() GenesisState {
// GetGenesisStateFromAppState returns x/auth GenesisState given raw application
// genesis state.
func GetGenesisStateFromAppState(cdc *codec.Codec, appState map[string]json.RawMessage) GenesisState {
func GetGenesisStateFromAppState(cdc Codec, appState map[string]json.RawMessage) GenesisState {
var genesisState GenesisState
if appState[ModuleName] != nil {
cdc.MustUnmarshalJSON(appState[ModuleName], &genesisState)
@ -86,7 +85,7 @@ type GenesisAccountIterator struct{}
// appGenesis and invokes a callback on each genesis account. If any call
// returns true, iteration stops.
func (GenesisAccountIterator) IterateGenesisAccounts(
cdc *codec.Codec, appGenesis map[string]json.RawMessage, cb func(exported.Account) (stop bool),
cdc Codec, appGenesis map[string]json.RawMessage, cb func(exported.Account) (stop bool),
) {
for _, genAcc := range GetGenesisStateFromAppState(cdc, appGenesis).Accounts {

View File

@ -1,4 +1,4 @@
package types
package types_test
import (
"encoding/json"
@ -9,21 +9,22 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth/exported"
"github.com/cosmos/cosmos-sdk/x/auth/types"
)
func TestSanitize(t *testing.T) {
addr1 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address())
authAcc1 := NewBaseAccountWithAddress(addr1)
authAcc1 := types.NewBaseAccountWithAddress(addr1)
authAcc1.SetAccountNumber(1)
addr2 := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address())
authAcc2 := NewBaseAccountWithAddress(addr2)
authAcc2 := types.NewBaseAccountWithAddress(addr2)
genAccs := exported.GenesisAccounts{&authAcc1, &authAcc2}
genAccs := exported.GenesisAccounts{authAcc1, authAcc2}
require.True(t, genAccs[0].GetAccountNumber() > genAccs[1].GetAccountNumber())
require.Equal(t, genAccs[1].GetAddress(), addr2)
genAccs = SanitizeGenesisAccounts(genAccs)
genAccs = types.SanitizeGenesisAccounts(genAccs)
require.False(t, genAccs[0].GetAccountNumber() > genAccs[1].GetAccountNumber())
require.Equal(t, genAccs[1].GetAddress(), addr1)
@ -38,34 +39,33 @@ var (
// require duplicate accounts fails validation
func TestValidateGenesisDuplicateAccounts(t *testing.T) {
acc1 := NewBaseAccountWithAddress(sdk.AccAddress(addr1))
acc1 := types.NewBaseAccountWithAddress(sdk.AccAddress(addr1))
genAccs := make(exported.GenesisAccounts, 2)
genAccs[0] = &acc1
genAccs[1] = &acc1
genAccs[0] = acc1
genAccs[1] = acc1
require.Error(t, ValidateGenAccounts(genAccs))
require.Error(t, types.ValidateGenAccounts(genAccs))
}
func TestGenesisAccountIterator(t *testing.T) {
acc1 := NewBaseAccountWithAddress(sdk.AccAddress(addr1))
acc1 := types.NewBaseAccountWithAddress(sdk.AccAddress(addr1))
acc2 := types.NewBaseAccountWithAddress(sdk.AccAddress(addr2))
acc2 := NewBaseAccountWithAddress(sdk.AccAddress(addr2))
genAccounts := exported.GenesisAccounts{acc1, acc2}
genAccounts := exported.GenesisAccounts{&acc1, &acc2}
authGenState := DefaultGenesisState()
authGenState := types.DefaultGenesisState()
authGenState.Accounts = genAccounts
appGenesis := make(map[string]json.RawMessage)
authGenStateBz, err := ModuleCdc.MarshalJSON(authGenState)
authGenStateBz, err := appCodec.MarshalJSON(authGenState)
require.NoError(t, err)
appGenesis[ModuleName] = authGenStateBz
appGenesis[types.ModuleName] = authGenStateBz
var addresses []sdk.AccAddress
GenesisAccountIterator{}.IterateGenesisAccounts(
ModuleCdc, appGenesis, func(acc exported.Account) (stop bool) {
types.GenesisAccountIterator{}.IterateGenesisAccounts(
appCodec, appGenesis, func(acc exported.Account) (stop bool) {
addresses = append(addresses, acc.GetAddress())
return false
},

View File

@ -1,12 +1,11 @@
package types
import (
"bytes"
"fmt"
"strings"
"github.com/cosmos/cosmos-sdk/x/params"
"github.com/cosmos/cosmos-sdk/x/params/subspace"
yaml "gopkg.in/yaml.v2"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
)
// DefaultParamspace defines the default auth module parameter subspace
@ -30,20 +29,12 @@ var (
KeySigVerifyCostSecp256k1 = []byte("SigVerifyCostSecp256k1")
)
var _ subspace.ParamSet = &Params{}
// Params defines the parameters for the auth module.
type Params struct {
MaxMemoCharacters uint64 `json:"max_memo_characters" yaml:"max_memo_characters"`
TxSigLimit uint64 `json:"tx_sig_limit" yaml:"tx_sig_limit"`
TxSizeCostPerByte uint64 `json:"tx_size_cost_per_byte" yaml:"tx_size_cost_per_byte"`
SigVerifyCostED25519 uint64 `json:"sig_verify_cost_ed25519" yaml:"sig_verify_cost_ed25519"`
SigVerifyCostSecp256k1 uint64 `json:"sig_verify_cost_secp256k1" yaml:"sig_verify_cost_secp256k1"`
}
var _ paramtypes.ParamSet = &Params{}
// NewParams creates a new Params object
func NewParams(maxMemoCharacters, txSigLimit, txSizeCostPerByte,
sigVerifyCostED25519, sigVerifyCostSecp256k1 uint64) Params {
func NewParams(
maxMemoCharacters, txSigLimit, txSizeCostPerByte, sigVerifyCostED25519, sigVerifyCostSecp256k1 uint64,
) Params {
return Params{
MaxMemoCharacters: maxMemoCharacters,
@ -55,30 +46,23 @@ func NewParams(maxMemoCharacters, txSigLimit, txSizeCostPerByte,
}
// ParamKeyTable for auth module
func ParamKeyTable() subspace.KeyTable {
return subspace.NewKeyTable().RegisterParamSet(&Params{})
func ParamKeyTable() paramtypes.KeyTable {
return paramtypes.NewKeyTable().RegisterParamSet(&Params{})
}
// ParamSetPairs implements the ParamSet interface and returns all the key/value pairs
// pairs of auth module's parameters.
// nolint
func (p *Params) ParamSetPairs() subspace.ParamSetPairs {
return subspace.ParamSetPairs{
params.NewParamSetPair(KeyMaxMemoCharacters, &p.MaxMemoCharacters, validateMaxMemoCharacters),
params.NewParamSetPair(KeyTxSigLimit, &p.TxSigLimit, validateTxSigLimit),
params.NewParamSetPair(KeyTxSizeCostPerByte, &p.TxSizeCostPerByte, validateTxSizeCostPerByte),
params.NewParamSetPair(KeySigVerifyCostED25519, &p.SigVerifyCostED25519, validateSigVerifyCostED25519),
params.NewParamSetPair(KeySigVerifyCostSecp256k1, &p.SigVerifyCostSecp256k1, validateSigVerifyCostSecp256k1),
func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs {
return paramtypes.ParamSetPairs{
paramtypes.NewParamSetPair(KeyMaxMemoCharacters, &p.MaxMemoCharacters, validateMaxMemoCharacters),
paramtypes.NewParamSetPair(KeyTxSigLimit, &p.TxSigLimit, validateTxSigLimit),
paramtypes.NewParamSetPair(KeyTxSizeCostPerByte, &p.TxSizeCostPerByte, validateTxSizeCostPerByte),
paramtypes.NewParamSetPair(KeySigVerifyCostED25519, &p.SigVerifyCostED25519, validateSigVerifyCostED25519),
paramtypes.NewParamSetPair(KeySigVerifyCostSecp256k1, &p.SigVerifyCostSecp256k1, validateSigVerifyCostSecp256k1),
}
}
// Equal returns a boolean determining if two Params types are identical.
func (p Params) Equal(p2 Params) bool {
bz1 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&p)
bz2 := ModuleCdc.MustMarshalBinaryLengthPrefixed(&p2)
return bytes.Equal(bz1, bz2)
}
// DefaultParams returns a default set of parameters.
func DefaultParams() Params {
return Params{
@ -92,14 +76,8 @@ func DefaultParams() Params {
// String implements the stringer interface.
func (p Params) String() string {
var sb strings.Builder
sb.WriteString("Params: \n")
sb.WriteString(fmt.Sprintf("MaxMemoCharacters: %d\n", p.MaxMemoCharacters))
sb.WriteString(fmt.Sprintf("TxSigLimit: %d\n", p.TxSigLimit))
sb.WriteString(fmt.Sprintf("TxSizeCostPerByte: %d\n", p.TxSizeCostPerByte))
sb.WriteString(fmt.Sprintf("SigVerifyCostED25519: %d\n", p.SigVerifyCostED25519))
sb.WriteString(fmt.Sprintf("SigVerifyCostSecp256k1: %d\n", p.SigVerifyCostSecp256k1))
return sb.String()
out, _ := yaml.Marshal(p)
return string(out)
}
func validateTxSigLimit(i interface{}) error {

View File

@ -163,16 +163,6 @@ func (tx StdTx) FeePayer() sdk.AccAddress {
return sdk.AccAddress{}
}
//__________________________________________________________
// StdFee includes the amount of coins paid in fees and the maximum
// gas to be used by the transaction. The ratio yields an effective "gasprice",
// which must be above some miminum to be accepted into the mempool.
type StdFee struct {
Amount sdk.Coins `json:"amount" yaml:"amount"`
Gas uint64 `json:"gas" yaml:"gas"`
}
// NewStdFee returns a new instance of StdFee
func NewStdFee(gas uint64, amount sdk.Coins) StdFee {
return StdFee{
@ -190,10 +180,12 @@ func (fee StdFee) Bytes() []byte {
if len(fee.Amount) == 0 {
fee.Amount = sdk.NewCoins()
}
bz, err := ModuleCdc.MarshalJSON(fee) // TODO
bz, err := codec.Cdc.MarshalJSON(fee) // TODO
if err != nil {
panic(err)
}
return bz
}
@ -228,7 +220,8 @@ func StdSignBytes(chainID string, accnum uint64, sequence uint64, fee StdFee, ms
for _, msg := range msgs {
msgsBytes = append(msgsBytes, json.RawMessage(msg.GetSignBytes()))
}
bz, err := ModuleCdc.MarshalJSON(StdSignDoc{
bz, err := codec.Cdc.MarshalJSON(StdSignDoc{
AccountNumber: accnum,
ChainID: chainID,
Fee: json.RawMessage(fee.Bytes()),
@ -236,9 +229,11 @@ func StdSignBytes(chainID string, accnum uint64, sequence uint64, fee StdFee, ms
Msgs: msgsBytes,
Sequence: sequence,
})
if err != nil {
panic(err)
}
return sdk.MustSortJSON(bz)
}

View File

@ -59,8 +59,8 @@ func NewTxBuilderFromCLI(input io.Reader) TxBuilder {
}
txbldr := TxBuilder{
keybase: kb,
accountNumber: uint64(viper.GetInt64(flags.FlagAccountNumber)),
sequence: uint64(viper.GetInt64(flags.FlagSequence)),
accountNumber: viper.GetUint64(flags.FlagAccountNumber),
sequence: viper.GetUint64(flags.FlagSequence),
gas: flags.GasFlagVar.Gas,
gasAdjustment: viper.GetFloat64(flags.FlagGasAdjustment),
simulateAndExecute: flags.GasFlagVar.Simulate,

1035
x/auth/types/types.pb.go Normal file

File diff suppressed because it is too large Load Diff

45
x/auth/types/types.proto Normal file
View File

@ -0,0 +1,45 @@
syntax = "proto3";
package cosmos_sdk.x.auth.v1;
import "third_party/proto/gogoproto/gogo.proto";
import "types/types.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/auth/types";
// BaseAccount defines a base account type. It contains all the necessary fields
// for basic account functionality. Any custom account type should extend this
// type for additional functionality (e.g. vesting).
message BaseAccount {
option (gogoproto.goproto_getters) = false;
option (gogoproto.goproto_stringer) = false;
bytes address = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"];
bytes pub_key = 2 [(gogoproto.moretags) = "yaml:\"public_key\""];
uint64 account_number = 3 [(gogoproto.moretags) = "yaml:\"account_number\""];
uint64 sequence = 4;
}
// StdFee includes the amount of coins paid in fees and the maximum
// gas to be used by the transaction. The ratio yields an effective "gasprice",
// which must be above some miminum to be accepted into the mempool.
message StdFee {
option (gogoproto.equal) = true;
repeated cosmos_sdk.v1.Coin amount = 1
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"];
uint64 gas = 2;
}
// Params defines the parameters for the auth module.
message Params {
option (gogoproto.equal) = true;
option (gogoproto.goproto_stringer) = false;
uint64 max_memo_characters = 1 [(gogoproto.moretags) = "yaml:\"max_memo_characters\""];
uint64 tx_sig_limit = 2 [(gogoproto.moretags) = "yaml:\"tx_sig_limit\""];
uint64 tx_size_cost_per_byte = 3 [(gogoproto.moretags) = "yaml:\"tx_size_cost_per_byte\""];
uint64 sig_verify_cost_ed25519 = 4
[(gogoproto.customname) = "SigVerifyCostED25519", (gogoproto.moretags) = "yaml:\"sig_verify_cost_ed25519\""];
uint64 sig_verify_cost_secp256k1 = 5
[(gogoproto.customname) = "SigVerifyCostSecp256k1", (gogoproto.moretags) = "yaml:\"sig_verify_cost_secp256k1\""];
}

View File

@ -1,15 +1,13 @@
// nolint
// autogenerated code using github.com/rigelrozanski/multitool
// aliases generated for the following subdirectories:
// ALIASGEN: github.com/cosmos/cosmos-sdk/x/auth/vesting/types/
package vesting
// DONTCOVER
// nolint
import (
"github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
)
var (
// functions aliases
RegisterCodec = types.RegisterCodec
NewBaseVestingAccount = types.NewBaseVestingAccount
NewContinuousVestingAccountRaw = types.NewContinuousVestingAccountRaw
@ -18,9 +16,6 @@ var (
NewPeriodicVestingAccount = types.NewPeriodicVestingAccount
NewDelayedVestingAccountRaw = types.NewDelayedVestingAccountRaw
NewDelayedVestingAccount = types.NewDelayedVestingAccount
// variable aliases
VestingCdc = types.VestingCdc
)
type (

View File

@ -5,7 +5,8 @@ import (
"github.com/cosmos/cosmos-sdk/x/auth/vesting/exported"
)
// RegisterCodec registers concrete types on the codec
// RegisterCodec registers the vesting interfaces and concrete types on the
// provided Amino codec.
func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterInterface((*exported.VestingAccount)(nil), nil)
cdc.RegisterConcrete(&BaseVestingAccount{}, "cosmos-sdk/BaseVestingAccount", nil)
@ -13,12 +14,3 @@ func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(&DelayedVestingAccount{}, "cosmos-sdk/DelayedVestingAccount", nil)
cdc.RegisterConcrete(&PeriodicVestingAccount{}, "cosmos-sdk/PeriodicVestingAccount", nil)
}
// VestingCdc module wide codec
var VestingCdc *codec.Codec
func init() {
VestingCdc = codec.New()
RegisterCodec(VestingCdc)
VestingCdc.Seal()
}

View File

@ -0,0 +1,11 @@
package types_test
import (
"github.com/cosmos/cosmos-sdk/simapp"
simappcodec "github.com/cosmos/cosmos-sdk/simapp/codec"
)
var (
app = simapp.Setup(false)
appCodec = simappcodec.NewAppCodec(app.Codec())
)

View File

@ -22,7 +22,7 @@ var (
func TestValidateGenesisInvalidAccounts(t *testing.T) {
acc1 := authtypes.NewBaseAccountWithAddress(sdk.AccAddress(addr1))
acc1Balance := sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 150))
baseVestingAcc := NewBaseVestingAccount(&acc1, acc1Balance, 1548775410)
baseVestingAcc := NewBaseVestingAccount(acc1, acc1Balance, 1548775410)
// invalid delegated vesting
baseVestingAcc.DelegatedVesting = acc1Balance.Add(acc1Balance...)
@ -32,7 +32,7 @@ func TestValidateGenesisInvalidAccounts(t *testing.T) {
genAccs := make([]exported.GenesisAccount, 2)
genAccs[0] = baseVestingAcc
genAccs[1] = &acc2
genAccs[1] = acc2
require.Error(t, authtypes.ValidateGenAccounts(genAccs))
baseVestingAcc.DelegatedVesting = acc1Balance

View File

@ -4,22 +4,16 @@ import (
"fmt"
"strings"
sdk "github.com/cosmos/cosmos-sdk/types"
"gopkg.in/yaml.v2"
)
// Period defines a length of time and amount of coins that will vest
type Period struct {
Length int64 `json:"length" yaml:"length"` // length of the period, in seconds
Amount sdk.Coins `json:"amount" yaml:"amount"` // amount of coins vesting during this period
}
// Periods stores all vesting periods passed as part of a PeriodicVestingAccount
type Periods []Period
// String Period implements stringer interface
func (p Period) String() string {
return fmt.Sprintf(`Length: %d
Amount: %s`, p.Length, p.Amount)
out, _ := yaml.Marshal(p)
return string(out)
}
// String Periods implements stringer interface
@ -28,6 +22,7 @@ func (vp Periods) String() string {
for _, period := range vp {
periodsListString = append(periodsListString, period.String())
}
return strings.TrimSpace(fmt.Sprintf(`Vesting Periods:
%s`, strings.Join(periodsListString, ", ")))
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,76 @@
syntax = "proto3";
package cosmos_sdk.x.auth.vesting.v1;
import "third_party/proto/gogoproto/gogo.proto";
import "types/types.proto";
import "x/auth/types/types.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/auth/vesting/types";
// BaseVestingAccount implements the VestingAccount interface. It contains all
// the necessary fields needed for any vesting account implementation.
message BaseVestingAccount {
option (gogoproto.goproto_getters) = false;
option (gogoproto.goproto_stringer) = false;
cosmos_sdk.x.auth.v1.BaseAccount base_account = 1 [(gogoproto.embed) = true];
repeated cosmos_sdk.v1.Coin original_vesting = 2 [
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins",
(gogoproto.moretags) = "yaml:\"original_vesting\""
];
repeated cosmos_sdk.v1.Coin delegated_free = 3 [
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins",
(gogoproto.moretags) = "yaml:\"delegated_free\""
];
repeated cosmos_sdk.v1.Coin delegated_vesting = 4 [
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins",
(gogoproto.moretags) = "yaml:\"delegated_vesting\""
];
int64 end_time = 5 [(gogoproto.moretags) = "yaml:\"end_time\""];
}
// ContinuousVestingAccount implements the VestingAccount interface. It
// continuously vests by unlocking coins linearly with respect to time.
message ContinuousVestingAccount {
option (gogoproto.goproto_getters) = false;
option (gogoproto.goproto_stringer) = false;
BaseVestingAccount base_vesting_account = 1 [(gogoproto.embed) = true];
int64 start_time = 2 [(gogoproto.moretags) = "yaml:\"start_time\""];
}
// DelayedVestingAccount implements the VestingAccount interface. It vests all
// coins after a specific time, but non prior. In other words, it keeps them
// locked until a specified time.
message DelayedVestingAccount {
option (gogoproto.goproto_getters) = false;
option (gogoproto.goproto_stringer) = false;
BaseVestingAccount base_vesting_account = 1 [(gogoproto.embed) = true];
}
// Period defines a length of time and amount of coins that will vest
message Period {
option (gogoproto.goproto_stringer) = false;
int64 length = 1;
repeated cosmos_sdk.v1.Coin amount = 2 [
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
}
// PeriodicVestingAccount implements the VestingAccount interface. It
// periodically vests by unlocking coins during each specified period
message PeriodicVestingAccount {
option (gogoproto.goproto_getters) = false;
option (gogoproto.goproto_stringer) = false;
BaseVestingAccount base_vesting_account = 1 [(gogoproto.embed) = true];
int64 start_time = 2 [(gogoproto.moretags) = "yaml:\"start_time\""];
repeated Period vesting_periods = 3
[(gogoproto.moretags) = "yaml:\"vesting_periods\"", (gogoproto.nullable) = false];
}

View File

@ -1,10 +1,10 @@
package types
import (
"encoding/json"
"errors"
"time"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
authexported "github.com/cosmos/cosmos-sdk/x/auth/exported"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
@ -22,24 +22,8 @@ var (
_ vestexported.VestingAccount = (*DelayedVestingAccount)(nil)
)
// Register the vesting account types on the auth module codec
func init() {
authtypes.RegisterAccountTypeCodec(&BaseVestingAccount{}, "cosmos-sdk/BaseVestingAccount")
authtypes.RegisterAccountTypeCodec(&ContinuousVestingAccount{}, "cosmos-sdk/ContinuousVestingAccount")
authtypes.RegisterAccountTypeCodec(&DelayedVestingAccount{}, "cosmos-sdk/DelayedVestingAccount")
authtypes.RegisterAccountTypeCodec(&PeriodicVestingAccount{}, "cosmos-sdk/PeriodicVestingAccount")
}
// BaseVestingAccount implements the VestingAccount interface. It contains all
// the necessary fields needed for any vesting account implementation.
type BaseVestingAccount struct {
*authtypes.BaseAccount
OriginalVesting sdk.Coins `json:"original_vesting" yaml:"original_vesting"` // coins in account upon initialization
DelegatedFree sdk.Coins `json:"delegated_free" yaml:"delegated_free"` // coins that are vested and delegated
DelegatedVesting sdk.Coins `json:"delegated_vesting" yaml:"delegated_vesting"` // coins that vesting and delegated
EndTime int64 `json:"end_time" yaml:"end_time"` // when the coins become unlocked
}
//-----------------------------------------------------------------------------
// Base Vesting Account
// NewBaseVestingAccount creates a new BaseVestingAccount object. It is the
// callers responsibility to ensure the base account has sufficient funds with
@ -180,7 +164,7 @@ func (bva BaseVestingAccount) Validate() error {
return bva.BaseAccount.Validate()
}
type vestingAccountPretty struct {
type vestingAccountYAML struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
PubKey string `json:"public_key" yaml:"public_key"`
AccountNumber uint64 `json:"account_number" yaml:"account_number"`
@ -195,6 +179,21 @@ type vestingAccountPretty struct {
VestingPeriods Periods `json:"vesting_periods,omitempty" yaml:"vesting_periods,omitempty"`
}
type vestingAccountJSON struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
PubKey crypto.PubKey `json:"public_key" yaml:"public_key"`
AccountNumber uint64 `json:"account_number" yaml:"account_number"`
Sequence uint64 `json:"sequence" yaml:"sequence"`
OriginalVesting sdk.Coins `json:"original_vesting" yaml:"original_vesting"`
DelegatedFree sdk.Coins `json:"delegated_free" yaml:"delegated_free"`
DelegatedVesting sdk.Coins `json:"delegated_vesting" yaml:"delegated_vesting"`
EndTime int64 `json:"end_time" yaml:"end_time"`
// custom fields based on concrete vesting type which can be omitted
StartTime int64 `json:"start_time,omitempty" yaml:"start_time,omitempty"`
VestingPeriods Periods `json:"vesting_periods,omitempty" yaml:"vesting_periods,omitempty"`
}
func (bva BaseVestingAccount) String() string {
out, _ := bva.MarshalYAML()
return out.(string)
@ -202,7 +201,7 @@ func (bva BaseVestingAccount) String() string {
// MarshalYAML returns the YAML representation of a BaseVestingAccount.
func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {
alias := vestingAccountPretty{
alias := vestingAccountYAML{
Address: bva.Address,
AccountNumber: bva.AccountNumber,
Sequence: bva.Sequence,
@ -212,8 +211,9 @@ func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {
EndTime: bva.EndTime,
}
if bva.PubKey != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, bva.PubKey)
pk := bva.GetPubKey()
if pk != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pk)
if err != nil {
return nil, err
}
@ -231,8 +231,9 @@ func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {
// MarshalJSON returns the JSON representation of a BaseVestingAccount.
func (bva BaseVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountPretty{
alias := vestingAccountJSON{
Address: bva.Address,
PubKey: bva.GetPubKey(),
AccountNumber: bva.AccountNumber,
Sequence: bva.Sequence,
OriginalVesting: bva.OriginalVesting,
@ -241,38 +242,17 @@ func (bva BaseVestingAccount) MarshalJSON() ([]byte, error) {
EndTime: bva.EndTime,
}
if bva.PubKey != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, bva.PubKey)
if err != nil {
return nil, err
}
alias.PubKey = pks
}
return json.Marshal(alias)
return codec.Cdc.MarshalJSON(alias)
}
// UnmarshalJSON unmarshals raw JSON bytes into a BaseVestingAccount.
func (bva *BaseVestingAccount) UnmarshalJSON(bz []byte) error {
var alias vestingAccountPretty
if err := json.Unmarshal(bz, &alias); err != nil {
var alias vestingAccountJSON
if err := codec.Cdc.UnmarshalJSON(bz, &alias); err != nil {
return err
}
var (
pk crypto.PubKey
err error
)
if alias.PubKey != "" {
pk, err = sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeAccPub, alias.PubKey)
if err != nil {
return err
}
}
bva.BaseAccount = authtypes.NewBaseAccount(alias.Address, pk, alias.AccountNumber, alias.Sequence)
bva.BaseAccount = authtypes.NewBaseAccount(alias.Address, alias.PubKey, alias.AccountNumber, alias.Sequence)
bva.OriginalVesting = alias.OriginalVesting
bva.DelegatedFree = alias.DelegatedFree
bva.DelegatedVesting = alias.DelegatedVesting
@ -287,14 +267,6 @@ func (bva *BaseVestingAccount) UnmarshalJSON(bz []byte) error {
var _ vestexported.VestingAccount = (*ContinuousVestingAccount)(nil)
var _ authexported.GenesisAccount = (*ContinuousVestingAccount)(nil)
// ContinuousVestingAccount implements the VestingAccount interface. It
// continuously vests by unlocking coins linearly with respect to time.
type ContinuousVestingAccount struct {
*BaseVestingAccount
StartTime int64 `json:"start_time" yaml:"start_time"` // when the coins start to vest
}
// NewContinuousVestingAccountRaw creates a new ContinuousVestingAccount object from BaseVestingAccount
func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount {
return &ContinuousVestingAccount{
@ -384,7 +356,7 @@ func (cva ContinuousVestingAccount) String() string {
// MarshalYAML returns the YAML representation of a ContinuousVestingAccount.
func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {
alias := vestingAccountPretty{
alias := vestingAccountYAML{
Address: cva.Address,
AccountNumber: cva.AccountNumber,
Sequence: cva.Sequence,
@ -395,8 +367,9 @@ func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {
StartTime: cva.StartTime,
}
if cva.PubKey != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, cva.PubKey)
pk := cva.GetPubKey()
if pk != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pk)
if err != nil {
return nil, err
}
@ -414,8 +387,9 @@ func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {
// MarshalJSON returns the JSON representation of a ContinuousVestingAccount.
func (cva ContinuousVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountPretty{
alias := vestingAccountJSON{
Address: cva.Address,
PubKey: cva.GetPubKey(),
AccountNumber: cva.AccountNumber,
Sequence: cva.Sequence,
OriginalVesting: cva.OriginalVesting,
@ -425,39 +399,18 @@ func (cva ContinuousVestingAccount) MarshalJSON() ([]byte, error) {
StartTime: cva.StartTime,
}
if cva.PubKey != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, cva.PubKey)
if err != nil {
return nil, err
}
alias.PubKey = pks
}
return json.Marshal(alias)
return codec.Cdc.MarshalJSON(alias)
}
// UnmarshalJSON unmarshals raw JSON bytes into a ContinuousVestingAccount.
func (cva *ContinuousVestingAccount) UnmarshalJSON(bz []byte) error {
var alias vestingAccountPretty
if err := json.Unmarshal(bz, &alias); err != nil {
var alias vestingAccountJSON
if err := codec.Cdc.UnmarshalJSON(bz, &alias); err != nil {
return err
}
var (
pk crypto.PubKey
err error
)
if alias.PubKey != "" {
pk, err = sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeAccPub, alias.PubKey)
if err != nil {
return err
}
}
cva.BaseVestingAccount = &BaseVestingAccount{
BaseAccount: authtypes.NewBaseAccount(alias.Address, pk, alias.AccountNumber, alias.Sequence),
BaseAccount: authtypes.NewBaseAccount(alias.Address, alias.PubKey, alias.AccountNumber, alias.Sequence),
OriginalVesting: alias.OriginalVesting,
DelegatedFree: alias.DelegatedFree,
DelegatedVesting: alias.DelegatedVesting,
@ -474,14 +427,6 @@ func (cva *ContinuousVestingAccount) UnmarshalJSON(bz []byte) error {
var _ vestexported.VestingAccount = (*PeriodicVestingAccount)(nil)
var _ authexported.GenesisAccount = (*PeriodicVestingAccount)(nil)
// PeriodicVestingAccount implements the VestingAccount interface. It
// periodically vests by unlocking coins during each specified period
type PeriodicVestingAccount struct {
*BaseVestingAccount
StartTime int64 `json:"start_time" yaml:"start_time"` // when the coins start to vest
VestingPeriods Periods `json:"vesting_periods" yaml:"vesting_periods"` // the vesting schedule
}
// NewPeriodicVestingAccountRaw creates a new PeriodicVestingAccount object from BaseVestingAccount
func NewPeriodicVestingAccountRaw(bva *BaseVestingAccount, startTime int64, periods Periods) *PeriodicVestingAccount {
return &PeriodicVestingAccount{
@ -600,7 +545,7 @@ func (pva PeriodicVestingAccount) String() string {
// MarshalYAML returns the YAML representation of a PeriodicVestingAccount.
func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {
alias := vestingAccountPretty{
alias := vestingAccountYAML{
Address: pva.Address,
AccountNumber: pva.AccountNumber,
Sequence: pva.Sequence,
@ -612,8 +557,9 @@ func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {
VestingPeriods: pva.VestingPeriods,
}
if pva.PubKey != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pva.PubKey)
pk := pva.GetPubKey()
if pk != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pk)
if err != nil {
return nil, err
}
@ -631,8 +577,9 @@ func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {
// MarshalJSON returns the JSON representation of a PeriodicVestingAccount.
func (pva PeriodicVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountPretty{
alias := vestingAccountJSON{
Address: pva.Address,
PubKey: pva.GetPubKey(),
AccountNumber: pva.AccountNumber,
Sequence: pva.Sequence,
OriginalVesting: pva.OriginalVesting,
@ -643,39 +590,18 @@ func (pva PeriodicVestingAccount) MarshalJSON() ([]byte, error) {
VestingPeriods: pva.VestingPeriods,
}
if pva.PubKey != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pva.PubKey)
if err != nil {
return nil, err
}
alias.PubKey = pks
}
return json.Marshal(alias)
return codec.Cdc.MarshalJSON(alias)
}
// UnmarshalJSON unmarshals raw JSON bytes into a PeriodicVestingAccount.
func (pva *PeriodicVestingAccount) UnmarshalJSON(bz []byte) error {
var alias vestingAccountPretty
if err := json.Unmarshal(bz, &alias); err != nil {
var alias vestingAccountJSON
if err := codec.Cdc.UnmarshalJSON(bz, &alias); err != nil {
return err
}
var (
pk crypto.PubKey
err error
)
if alias.PubKey != "" {
pk, err = sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeAccPub, alias.PubKey)
if err != nil {
return err
}
}
pva.BaseVestingAccount = &BaseVestingAccount{
BaseAccount: authtypes.NewBaseAccount(alias.Address, pk, alias.AccountNumber, alias.Sequence),
BaseAccount: authtypes.NewBaseAccount(alias.Address, alias.PubKey, alias.AccountNumber, alias.Sequence),
OriginalVesting: alias.OriginalVesting,
DelegatedFree: alias.DelegatedFree,
DelegatedVesting: alias.DelegatedVesting,
@ -693,13 +619,6 @@ func (pva *PeriodicVestingAccount) UnmarshalJSON(bz []byte) error {
var _ vestexported.VestingAccount = (*DelayedVestingAccount)(nil)
var _ authexported.GenesisAccount = (*DelayedVestingAccount)(nil)
// DelayedVestingAccount implements the VestingAccount interface. It vests all
// coins after a specific time, but non prior. In other words, it keeps them
// locked until a specified time.
type DelayedVestingAccount struct {
*BaseVestingAccount
}
// NewDelayedVestingAccountRaw creates a new DelayedVestingAccount object from BaseVestingAccount
func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount {
return &DelayedVestingAccount{
@ -756,10 +675,16 @@ func (dva DelayedVestingAccount) Validate() error {
return dva.BaseVestingAccount.Validate()
}
func (dva DelayedVestingAccount) String() string {
out, _ := dva.MarshalYAML()
return out.(string)
}
// MarshalJSON returns the JSON representation of a DelayedVestingAccount.
func (dva DelayedVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountPretty{
alias := vestingAccountJSON{
Address: dva.Address,
PubKey: dva.GetPubKey(),
AccountNumber: dva.AccountNumber,
Sequence: dva.Sequence,
OriginalVesting: dva.OriginalVesting,
@ -768,39 +693,18 @@ func (dva DelayedVestingAccount) MarshalJSON() ([]byte, error) {
EndTime: dva.EndTime,
}
if dva.PubKey != nil {
pks, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, dva.PubKey)
if err != nil {
return nil, err
}
alias.PubKey = pks
}
return json.Marshal(alias)
return codec.Cdc.MarshalJSON(alias)
}
// UnmarshalJSON unmarshals raw JSON bytes into a DelayedVestingAccount.
func (dva *DelayedVestingAccount) UnmarshalJSON(bz []byte) error {
var alias vestingAccountPretty
if err := json.Unmarshal(bz, &alias); err != nil {
var alias vestingAccountJSON
if err := codec.Cdc.UnmarshalJSON(bz, &alias); err != nil {
return err
}
var (
pk crypto.PubKey
err error
)
if alias.PubKey != "" {
pk, err = sdk.GetPubKeyFromBech32(sdk.Bech32PubKeyTypeAccPub, alias.PubKey)
if err != nil {
return err
}
}
dva.BaseVestingAccount = &BaseVestingAccount{
BaseAccount: authtypes.NewBaseAccount(alias.Address, pk, alias.AccountNumber, alias.Sequence),
BaseAccount: authtypes.NewBaseAccount(alias.Address, alias.PubKey, alias.AccountNumber, alias.Sequence),
OriginalVesting: alias.OriginalVesting,
DelegatedFree: alias.DelegatedFree,
DelegatedVesting: alias.DelegatedVesting,

View File

@ -1,8 +1,7 @@
package types
package types_test
import (
"encoding/json"
"errors"
"testing"
"time"
@ -13,6 +12,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
authexported "github.com/cosmos/cosmos-sdk/x/auth/exported"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
)
var (
@ -24,10 +24,10 @@ func TestGetVestedCoinsContVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
cva := NewContinuousVestingAccount(&bacc, origCoins, now.Unix(), endTime.Unix())
cva := types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix())
// require no coins vested in the very beginning of the vesting schedule
vestedCoins := cva.GetVestedCoins(now)
@ -50,10 +50,10 @@ func TestGetVestingCoinsContVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
cva := NewContinuousVestingAccount(&bacc, origCoins, now.Unix(), endTime.Unix())
cva := types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix())
// require all coins vesting in the beginning of the vesting schedule
vestingCoins := cva.GetVestingCoins(now)
@ -72,11 +72,11 @@ func TestSpendableCoinsContVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
cva := NewContinuousVestingAccount(&bacc, origCoins, now.Unix(), endTime.Unix())
cva := types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix())
// require that all original coins are locked at the end of the vesting
// schedule
@ -100,24 +100,24 @@ func TestTrackDelegationContVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
// require the ability to delegate all vesting coins
cva := NewContinuousVestingAccount(&bacc, origCoins, now.Unix(), endTime.Unix())
cva := types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix())
cva.TrackDelegation(now, origCoins, origCoins)
require.Equal(t, origCoins, cva.DelegatedVesting)
require.Nil(t, cva.DelegatedFree)
// require the ability to delegate all vested coins
cva = NewContinuousVestingAccount(&bacc, origCoins, now.Unix(), endTime.Unix())
cva = types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix())
cva.TrackDelegation(endTime, origCoins, origCoins)
require.Nil(t, cva.DelegatedVesting)
require.Equal(t, origCoins, cva.DelegatedFree)
// require the ability to delegate all vesting coins (50%) and all vested coins (50%)
cva = NewContinuousVestingAccount(&bacc, origCoins, now.Unix(), endTime.Unix())
cva = types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix())
cva.TrackDelegation(now.Add(12*time.Hour), origCoins, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 50)})
require.Equal(t, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 50)}, cva.DelegatedVesting)
require.Nil(t, cva.DelegatedFree)
@ -127,7 +127,7 @@ func TestTrackDelegationContVestingAcc(t *testing.T) {
require.Equal(t, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 50)}, cva.DelegatedFree)
// require no modifications when delegation amount is zero or not enough funds
cva = NewContinuousVestingAccount(&bacc, origCoins, now.Unix(), endTime.Unix())
cva = types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix())
require.Panics(t, func() {
cva.TrackDelegation(endTime, origCoins, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 1000000)})
})
@ -139,19 +139,19 @@ func TestTrackUndelegationContVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
// require the ability to undelegate all vesting coins
cva := NewContinuousVestingAccount(&bacc, origCoins, now.Unix(), endTime.Unix())
cva := types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix())
cva.TrackDelegation(now, origCoins, origCoins)
cva.TrackUndelegation(origCoins)
require.Nil(t, cva.DelegatedFree)
require.Nil(t, cva.DelegatedVesting)
// require the ability to undelegate all vested coins
cva = NewContinuousVestingAccount(&bacc, origCoins, now.Unix(), endTime.Unix())
cva = types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix())
cva.TrackDelegation(endTime, origCoins, origCoins)
cva.TrackUndelegation(origCoins)
@ -159,7 +159,7 @@ func TestTrackUndelegationContVestingAcc(t *testing.T) {
require.Nil(t, cva.DelegatedVesting)
// require no modifications when the undelegation amount is zero
cva = NewContinuousVestingAccount(&bacc, origCoins, now.Unix(), endTime.Unix())
cva = types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix())
require.Panics(t, func() {
cva.TrackUndelegation(sdk.Coins{sdk.NewInt64Coin(stakeDenom, 0)})
@ -168,7 +168,7 @@ func TestTrackUndelegationContVestingAcc(t *testing.T) {
require.Nil(t, cva.DelegatedVesting)
// vest 50% and delegate to two validators
cva = NewContinuousVestingAccount(&bacc, origCoins, now.Unix(), endTime.Unix())
cva = types.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix())
cva.TrackDelegation(now.Add(12*time.Hour), origCoins, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 50)})
cva.TrackDelegation(now.Add(12*time.Hour), origCoins, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 50)})
@ -187,12 +187,12 @@ func TestGetVestedCoinsDelVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
// require no coins are vested until schedule maturation
dva := NewDelayedVestingAccount(&bacc, origCoins, endTime.Unix())
dva := types.NewDelayedVestingAccount(bacc, origCoins, endTime.Unix())
vestedCoins := dva.GetVestedCoins(now)
require.Nil(t, vestedCoins)
@ -205,12 +205,12 @@ func TestGetVestingCoinsDelVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
// require all coins vesting at the beginning of the schedule
dva := NewDelayedVestingAccount(&bacc, origCoins, endTime.Unix())
dva := types.NewDelayedVestingAccount(bacc, origCoins, endTime.Unix())
vestingCoins := dva.GetVestingCoins(now)
require.Equal(t, origCoins, vestingCoins)
@ -223,13 +223,13 @@ func TestSpendableCoinsDelVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
// require that all coins are locked in the beginning of the vesting
// schedule
dva := NewDelayedVestingAccount(&bacc, origCoins, endTime.Unix())
dva := types.NewDelayedVestingAccount(bacc, origCoins, endTime.Unix())
lockedCoins := dva.LockedCoins(now)
require.True(t, lockedCoins.IsEqual(origCoins))
@ -260,31 +260,31 @@ func TestTrackDelegationDelVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
// require the ability to delegate all vesting coins
dva := NewDelayedVestingAccount(&bacc, origCoins, endTime.Unix())
dva := types.NewDelayedVestingAccount(bacc, origCoins, endTime.Unix())
dva.TrackDelegation(now, origCoins, origCoins)
require.Equal(t, origCoins, dva.DelegatedVesting)
require.Nil(t, dva.DelegatedFree)
// require the ability to delegate all vested coins
dva = NewDelayedVestingAccount(&bacc, origCoins, endTime.Unix())
dva = types.NewDelayedVestingAccount(bacc, origCoins, endTime.Unix())
dva.TrackDelegation(endTime, origCoins, origCoins)
require.Nil(t, dva.DelegatedVesting)
require.Equal(t, origCoins, dva.DelegatedFree)
// require the ability to delegate all coins half way through the vesting
// schedule
dva = NewDelayedVestingAccount(&bacc, origCoins, endTime.Unix())
dva = types.NewDelayedVestingAccount(bacc, origCoins, endTime.Unix())
dva.TrackDelegation(now.Add(12*time.Hour), origCoins, origCoins)
require.Equal(t, origCoins, dva.DelegatedVesting)
require.Nil(t, dva.DelegatedFree)
// require no modifications when delegation amount is zero or not enough funds
dva = NewDelayedVestingAccount(&bacc, origCoins, endTime.Unix())
dva = types.NewDelayedVestingAccount(bacc, origCoins, endTime.Unix())
require.Panics(t, func() {
dva.TrackDelegation(endTime, origCoins, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 1000000)})
@ -297,26 +297,26 @@ func TestTrackUndelegationDelVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
// require the ability to undelegate all vesting coins
dva := NewDelayedVestingAccount(&bacc, origCoins, endTime.Unix())
dva := types.NewDelayedVestingAccount(bacc, origCoins, endTime.Unix())
dva.TrackDelegation(now, origCoins, origCoins)
dva.TrackUndelegation(origCoins)
require.Nil(t, dva.DelegatedFree)
require.Nil(t, dva.DelegatedVesting)
// require the ability to undelegate all vested coins
dva = NewDelayedVestingAccount(&bacc, origCoins, endTime.Unix())
dva = types.NewDelayedVestingAccount(bacc, origCoins, endTime.Unix())
dva.TrackDelegation(endTime, origCoins, origCoins)
dva.TrackUndelegation(origCoins)
require.Nil(t, dva.DelegatedFree)
require.Nil(t, dva.DelegatedVesting)
// require no modifications when the undelegation amount is zero
dva = NewDelayedVestingAccount(&bacc, origCoins, endTime.Unix())
dva = types.NewDelayedVestingAccount(bacc, origCoins, endTime.Unix())
require.Panics(t, func() {
dva.TrackUndelegation(sdk.Coins{sdk.NewInt64Coin(stakeDenom, 0)})
@ -325,7 +325,7 @@ func TestTrackUndelegationDelVestingAcc(t *testing.T) {
require.Nil(t, dva.DelegatedVesting)
// vest 50% and delegate to two validators
dva = NewDelayedVestingAccount(&bacc, origCoins, endTime.Unix())
dva = types.NewDelayedVestingAccount(bacc, origCoins, endTime.Unix())
dva.TrackDelegation(now.Add(12*time.Hour), origCoins, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 50)})
dva.TrackDelegation(now.Add(12*time.Hour), origCoins, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 50)})
@ -344,16 +344,16 @@ func TestTrackUndelegationDelVestingAcc(t *testing.T) {
func TestGetVestedCoinsPeriodicVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
periods := Periods{
Period{Length: int64(12 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 500), sdk.NewInt64Coin(stakeDenom, 50)}},
Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
periods := types.Periods{
types.Period{Length: int64(12 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 500), sdk.NewInt64Coin(stakeDenom, 50)}},
types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
}
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
pva := NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva := types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
// require no coins vested at the beginning of the vesting schedule
vestedCoins := pva.GetVestedCoins(now)
@ -389,17 +389,17 @@ func TestGetVestedCoinsPeriodicVestingAcc(t *testing.T) {
func TestGetVestingCoinsPeriodicVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
periods := Periods{
Period{Length: int64(12 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 500), sdk.NewInt64Coin(stakeDenom, 50)}},
Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
periods := types.Periods{
types.Period{Length: int64(12 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 500), sdk.NewInt64Coin(stakeDenom, 50)}},
types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
}
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{
sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
pva := NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva := types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
// require all coins vesting at the beginning of the vesting schedule
vestingCoins := pva.GetVestingCoins(now)
@ -429,17 +429,17 @@ func TestGetVestingCoinsPeriodicVestingAcc(t *testing.T) {
func TestSpendableCoinsPeriodicVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
periods := Periods{
Period{Length: int64(12 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 500), sdk.NewInt64Coin(stakeDenom, 50)}},
Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
periods := types.Periods{
types.Period{Length: int64(12 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 500), sdk.NewInt64Coin(stakeDenom, 50)}},
types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
}
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{
sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
pva := NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva := types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
// require that there exist no spendable coins at the beginning of the
// vesting schedule
@ -464,44 +464,44 @@ func TestSpendableCoinsPeriodicVestingAcc(t *testing.T) {
func TestTrackDelegationPeriodicVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
periods := Periods{
Period{Length: int64(12 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 500), sdk.NewInt64Coin(stakeDenom, 50)}},
Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
periods := types.Periods{
types.Period{Length: int64(12 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 500), sdk.NewInt64Coin(stakeDenom, 50)}},
types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
}
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
// require the ability to delegate all vesting coins
pva := NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva := types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
pva.TrackDelegation(now, origCoins, origCoins)
require.Equal(t, origCoins, pva.DelegatedVesting)
require.Nil(t, pva.DelegatedFree)
// require the ability to delegate all vested coins
pva = NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva = types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
pva.TrackDelegation(endTime, origCoins, origCoins)
require.Nil(t, pva.DelegatedVesting)
require.Equal(t, origCoins, pva.DelegatedFree)
// delegate half of vesting coins
pva = NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva = types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
pva.TrackDelegation(now, origCoins, periods[0].Amount)
// require that all delegated coins are delegated vesting
require.Equal(t, pva.DelegatedVesting, periods[0].Amount)
require.Nil(t, pva.DelegatedFree)
// delegate 75% of coins, split between vested and vesting
pva = NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva = types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
pva.TrackDelegation(now.Add(12*time.Hour), origCoins, periods[0].Amount.Add(periods[1].Amount...))
// require that the maximum possible amount of vesting coins are chosen for delegation.
require.Equal(t, pva.DelegatedFree, periods[1].Amount)
require.Equal(t, pva.DelegatedVesting, periods[0].Amount)
// require the ability to delegate all vesting coins (50%) and all vested coins (50%)
pva = NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva = types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
pva.TrackDelegation(now.Add(12*time.Hour), origCoins, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 50)})
require.Equal(t, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 50)}, pva.DelegatedVesting)
require.Nil(t, pva.DelegatedFree)
@ -511,7 +511,7 @@ func TestTrackDelegationPeriodicVestingAcc(t *testing.T) {
require.Equal(t, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 50)}, pva.DelegatedFree)
// require no modifications when delegation amount is zero or not enough funds
pva = NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva = types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
require.Panics(t, func() {
pva.TrackDelegation(endTime, origCoins, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 1000000)})
})
@ -522,25 +522,25 @@ func TestTrackDelegationPeriodicVestingAcc(t *testing.T) {
func TestTrackUndelegationPeriodicVestingAcc(t *testing.T) {
now := tmtime.Now()
endTime := now.Add(24 * time.Hour)
periods := Periods{
Period{Length: int64(12 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 500), sdk.NewInt64Coin(stakeDenom, 50)}},
Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
periods := types.Periods{
types.Period{Length: int64(12 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 500), sdk.NewInt64Coin(stakeDenom, 50)}},
types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
types.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin(feeDenom, 250), sdk.NewInt64Coin(stakeDenom, 25)}},
}
_, _, addr := KeyTestPubAddr()
_, _, addr := authtypes.KeyTestPubAddr()
origCoins := sdk.Coins{sdk.NewInt64Coin(feeDenom, 1000), sdk.NewInt64Coin(stakeDenom, 100)}
bacc := authtypes.NewBaseAccountWithAddress(addr)
// require the ability to undelegate all vesting coins at the beginning of vesting
pva := NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva := types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
pva.TrackDelegation(now, origCoins, origCoins)
pva.TrackUndelegation(origCoins)
require.Nil(t, pva.DelegatedFree)
require.Nil(t, pva.DelegatedVesting)
// require the ability to undelegate all vested coins at the end of vesting
pva = NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva = types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
pva.TrackDelegation(endTime, origCoins, origCoins)
pva.TrackUndelegation(origCoins)
@ -548,14 +548,14 @@ func TestTrackUndelegationPeriodicVestingAcc(t *testing.T) {
require.Nil(t, pva.DelegatedVesting)
// require the ability to undelegate half of coins
pva = NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva = types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
pva.TrackDelegation(endTime, origCoins, periods[0].Amount)
pva.TrackUndelegation(periods[0].Amount)
require.Nil(t, pva.DelegatedFree)
require.Nil(t, pva.DelegatedVesting)
// require no modifications when the undelegation amount is zero
pva = NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva = types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
require.Panics(t, func() {
pva.TrackUndelegation(sdk.Coins{sdk.NewInt64Coin(stakeDenom, 0)})
@ -564,7 +564,7 @@ func TestTrackUndelegationPeriodicVestingAcc(t *testing.T) {
require.Nil(t, pva.DelegatedVesting)
// vest 50% and delegate to two validators
pva = NewPeriodicVestingAccount(&bacc, origCoins, now.Unix(), periods)
pva = types.NewPeriodicVestingAccount(bacc, origCoins, now.Unix(), periods)
pva.TrackDelegation(now.Add(12*time.Hour), origCoins, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 50)})
pva.TrackDelegation(now.Add(12*time.Hour), origCoins, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 50)})
@ -579,97 +579,68 @@ func TestTrackUndelegationPeriodicVestingAcc(t *testing.T) {
require.Equal(t, sdk.Coins{sdk.NewInt64Coin(stakeDenom, 25)}, pva.DelegatedVesting)
}
// TODO: Move test to bank
// func TestNewBaseVestingAccount(t *testing.T) {
// pubkey := secp256k1.GenPrivKey().PubKey()
// addr := sdk.AccAddress(pubkey.Address())
// _, err := NewBaseVestingAccount(
// authtypes.NewBaseAccount(addr, sdk.NewCoins(), pubkey, 0, 0),
// sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)}, 100,
// )
// require.Equal(t, errors.New("vesting amount cannot be greater than total amount"), err)
// _, err = NewBaseVestingAccount(
// authtypes.NewBaseAccount(addr, sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 10)), pubkey, 0, 0),
// sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)}, 100,
// )
// require.Equal(t, errors.New("vesting amount cannot be greater than total amount"), err)
// _, err = NewBaseVestingAccount(
// authtypes.NewBaseAccount(addr, sdk.NewCoins(sdk.NewInt64Coin("uatom", 50), sdk.NewInt64Coin("eth", 50)), pubkey, 0, 0),
// sdk.NewCoins(sdk.NewInt64Coin("uatom", 100), sdk.NewInt64Coin("eth", 20)), 100,
// )
// require.Equal(t, errors.New("vesting amount cannot be greater than total amount"), err)
// _, err = NewBaseVestingAccount(
// authtypes.NewBaseAccount(addr, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)}, pubkey, 0, 0),
// sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)}, 100,
// )
// require.NoError(t, err)
// }
func TestGenesisAccountValidate(t *testing.T) {
pubkey := secp256k1.GenPrivKey().PubKey()
addr := sdk.AccAddress(pubkey.Address())
baseAcc := authtypes.NewBaseAccount(addr, pubkey, 0, 0)
initialVesting := sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 50))
baseVestingWithCoins := NewBaseVestingAccount(baseAcc, initialVesting, 100)
baseVestingWithCoins := types.NewBaseVestingAccount(baseAcc, initialVesting, 100)
tests := []struct {
name string
acc authexported.GenesisAccount
expErr error
expErr bool
}{
{
"valid base account",
baseAcc,
nil,
false,
},
{
"invalid base valid account",
authtypes.NewBaseAccount(addr, secp256k1.GenPrivKey().PubKey(), 0, 0),
errors.New("pubkey and address pair is invalid"),
true,
},
{
"valid base vesting account",
baseVestingWithCoins,
nil,
false,
},
{
"valid continuous vesting account",
NewContinuousVestingAccount(baseAcc, initialVesting, 100, 200),
nil,
types.NewContinuousVestingAccount(baseAcc, initialVesting, 100, 200),
false,
},
{
"invalid vesting times",
NewContinuousVestingAccount(baseAcc, initialVesting, 1654668078, 1554668078),
errors.New("vesting start-time cannot be before end-time"),
types.NewContinuousVestingAccount(baseAcc, initialVesting, 1654668078, 1554668078),
true,
},
{
"valid periodic vesting account",
NewPeriodicVestingAccount(baseAcc, initialVesting, 0, Periods{Period{Length: int64(100), Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)}}}),
nil,
types.NewPeriodicVestingAccount(baseAcc, initialVesting, 0, types.Periods{types.Period{Length: int64(100), Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)}}}),
false,
},
{
"invalid vesting period lengths",
NewPeriodicVestingAccountRaw(
types.NewPeriodicVestingAccountRaw(
baseVestingWithCoins,
0, Periods{Period{Length: int64(50), Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)}}}),
errors.New("vesting end time does not match length of all vesting periods"),
0, types.Periods{types.Period{Length: int64(50), Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)}}}),
true,
},
{
"invalid vesting period amounts",
NewPeriodicVestingAccountRaw(
types.NewPeriodicVestingAccountRaw(
baseVestingWithCoins,
0, Periods{Period{Length: int64(100), Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 25)}}}),
errors.New("original vesting coins does not match the sum of all coins in vesting periods"),
0, types.Periods{types.Period{Length: int64(100), Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 25)}}}),
true,
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
err := tt.acc.Validate()
require.Equal(t, tt.expErr, err)
require.Equal(t, tt.expErr, tt.acc.Validate() != nil)
})
}
}
@ -680,7 +651,7 @@ func TestBaseVestingAccountJSON(t *testing.T) {
coins := sdk.NewCoins(sdk.NewInt64Coin("test", 5))
baseAcc := authtypes.NewBaseAccount(addr, pubkey, 10, 50)
acc := NewBaseVestingAccount(baseAcc, coins, time.Now().Unix())
acc := types.NewBaseVestingAccount(baseAcc, coins, time.Now().Unix())
bz, err := json.Marshal(acc)
require.NoError(t, err)
@ -689,19 +660,41 @@ func TestBaseVestingAccountJSON(t *testing.T) {
require.NoError(t, err)
require.Equal(t, string(bz1), string(bz))
var a BaseVestingAccount
var a types.BaseVestingAccount
require.NoError(t, json.Unmarshal(bz, &a))
require.Equal(t, acc.String(), a.String())
}
func TestContinuousVestingAccountMarshal(t *testing.T) {
pubkey := secp256k1.GenPrivKey().PubKey()
addr := sdk.AccAddress(pubkey.Address())
coins := sdk.NewCoins(sdk.NewInt64Coin("test", 5))
baseAcc := authtypes.NewBaseAccount(addr, pubkey, 10, 50)
baseVesting := types.NewBaseVestingAccount(baseAcc, coins, time.Now().Unix())
acc := types.NewContinuousVestingAccountRaw(baseVesting, baseVesting.EndTime)
bz, err := appCodec.MarshalAccount(acc)
require.Nil(t, err)
acc2, err := appCodec.UnmarshalAccount(bz)
require.Nil(t, err)
require.IsType(t, &types.ContinuousVestingAccount{}, acc2)
require.Equal(t, acc.String(), acc2.String())
// error on bad bytes
_, err = appCodec.UnmarshalAccount(bz[:len(bz)/2])
require.NotNil(t, err)
}
func TestContinuousVestingAccountJSON(t *testing.T) {
pubkey := secp256k1.GenPrivKey().PubKey()
addr := sdk.AccAddress(pubkey.Address())
coins := sdk.NewCoins(sdk.NewInt64Coin("test", 5))
baseAcc := authtypes.NewBaseAccount(addr, pubkey, 10, 50)
baseVesting := NewBaseVestingAccount(baseAcc, coins, time.Now().Unix())
acc := NewContinuousVestingAccountRaw(baseVesting, baseVesting.EndTime)
baseVesting := types.NewBaseVestingAccount(baseAcc, coins, time.Now().Unix())
acc := types.NewContinuousVestingAccountRaw(baseVesting, baseVesting.EndTime)
bz, err := json.Marshal(acc)
require.NoError(t, err)
@ -710,18 +703,39 @@ func TestContinuousVestingAccountJSON(t *testing.T) {
require.NoError(t, err)
require.Equal(t, string(bz1), string(bz))
var a ContinuousVestingAccount
var a types.ContinuousVestingAccount
require.NoError(t, json.Unmarshal(bz, &a))
require.Equal(t, acc.String(), a.String())
}
func TestPeriodicVestingAccountMarshal(t *testing.T) {
pubkey := secp256k1.GenPrivKey().PubKey()
addr := sdk.AccAddress(pubkey.Address())
coins := sdk.NewCoins(sdk.NewInt64Coin("test", 5))
baseAcc := authtypes.NewBaseAccount(addr, pubkey, 10, 50)
acc := types.NewPeriodicVestingAccount(baseAcc, coins, time.Now().Unix(), types.Periods{types.Period{3600, coins}})
bz, err := appCodec.MarshalAccount(acc)
require.Nil(t, err)
acc2, err := appCodec.UnmarshalAccount(bz)
require.Nil(t, err)
require.IsType(t, &types.PeriodicVestingAccount{}, acc2)
require.Equal(t, acc.String(), acc2.String())
// error on bad bytes
_, err = appCodec.UnmarshalAccount(bz[:len(bz)/2])
require.NotNil(t, err)
}
func TestPeriodicVestingAccountJSON(t *testing.T) {
pubkey := secp256k1.GenPrivKey().PubKey()
addr := sdk.AccAddress(pubkey.Address())
coins := sdk.NewCoins(sdk.NewInt64Coin("test", 5))
baseAcc := authtypes.NewBaseAccount(addr, pubkey, 10, 50)
acc := NewPeriodicVestingAccount(baseAcc, coins, time.Now().Unix(), Periods{Period{3600, coins}})
acc := types.NewPeriodicVestingAccount(baseAcc, coins, time.Now().Unix(), types.Periods{types.Period{3600, coins}})
bz, err := json.Marshal(acc)
require.NoError(t, err)
@ -730,18 +744,39 @@ func TestPeriodicVestingAccountJSON(t *testing.T) {
require.NoError(t, err)
require.Equal(t, string(bz1), string(bz))
var a PeriodicVestingAccount
var a types.PeriodicVestingAccount
require.NoError(t, json.Unmarshal(bz, &a))
require.Equal(t, acc.String(), a.String())
}
func TestDelayedVestingAccountMarshal(t *testing.T) {
pubkey := secp256k1.GenPrivKey().PubKey()
addr := sdk.AccAddress(pubkey.Address())
coins := sdk.NewCoins(sdk.NewInt64Coin("test", 5))
baseAcc := authtypes.NewBaseAccount(addr, pubkey, 10, 50)
acc := types.NewDelayedVestingAccount(baseAcc, coins, time.Now().Unix())
bz, err := appCodec.MarshalAccount(acc)
require.Nil(t, err)
acc2, err := appCodec.UnmarshalAccount(bz)
require.Nil(t, err)
require.IsType(t, &types.DelayedVestingAccount{}, acc2)
require.Equal(t, acc.String(), acc2.String())
// error on bad bytes
_, err = appCodec.UnmarshalAccount(bz[:len(bz)/2])
require.NotNil(t, err)
}
func TestDelayedVestingAccountJSON(t *testing.T) {
pubkey := secp256k1.GenPrivKey().PubKey()
addr := sdk.AccAddress(pubkey.Address())
coins := sdk.NewCoins(sdk.NewInt64Coin("test", 5))
baseAcc := authtypes.NewBaseAccount(addr, pubkey, 10, 50)
acc := NewDelayedVestingAccount(baseAcc, coins, time.Now().Unix())
acc := types.NewDelayedVestingAccount(baseAcc, coins, time.Now().Unix())
bz, err := json.Marshal(acc)
require.NoError(t, err)
@ -750,7 +785,7 @@ func TestDelayedVestingAccountJSON(t *testing.T) {
require.NoError(t, err)
require.Equal(t, string(bz1), string(bz))
var a DelayedVestingAccount
var a types.DelayedVestingAccount
require.NoError(t, json.Unmarshal(bz, &a))
require.Equal(t, acc.String(), a.String())
}

View File

@ -3,8 +3,8 @@ package bank
// nolint
import (
"github.com/cosmos/cosmos-sdk/x/bank/internal/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
const (

View File

@ -16,7 +16,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
authexported "github.com/cosmos/cosmos-sdk/x/auth/exported"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
type (
@ -356,7 +356,7 @@ func TestMsgMultiSendDependent(t *testing.T) {
err := acc2.SetAccountNumber(1)
require.NoError(t, err)
genAccs := []authexported.GenesisAccount{&acc1, &acc2}
genAccs := []authexported.GenesisAccount{acc1, acc2}
app := simapp.SetupWithGenesisAccounts(genAccs)
ctx := app.BaseApp.NewContext(false, abci.Header{})

View File

@ -11,7 +11,7 @@ import (
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
const (

View File

@ -12,7 +12,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
// GetTxCmd returns the transaction commands for this module

View File

@ -9,7 +9,7 @@ import (
"github.com/cosmos/cosmos-sdk/client/context"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
// QueryBalancesRequestHandlerFn returns a REST handler that queries for all

View File

@ -9,7 +9,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
// SendReq defines the properties of a send request's body.

View File

@ -3,8 +3,8 @@ package bank
import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/bank/internal/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
// NewHandler returns a handler for "bank" type messages.

View File

@ -1,20 +0,0 @@
package types
import (
"github.com/cosmos/cosmos-sdk/codec"
)
// Register concrete types on codec codec
func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(MsgSend{}, "cosmos-sdk/MsgSend", nil)
cdc.RegisterConcrete(MsgMultiSend{}, "cosmos-sdk/MsgMultiSend", nil)
}
// module codec
var ModuleCdc *codec.Codec
func init() {
ModuleCdc = codec.New()
RegisterCodec(ModuleCdc)
ModuleCdc.Seal()
}

View File

@ -1,13 +0,0 @@
package types
import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
// x/bank module sentinel errors
var (
ErrNoInputs = sdkerrors.Register(ModuleName, 1, "no inputs to send transaction")
ErrNoOutputs = sdkerrors.Register(ModuleName, 2, "no outputs to send transaction")
ErrInputOutputMismatch = sdkerrors.Register(ModuleName, 3, "sum inputs != sum outputs")
ErrSendDisabled = sdkerrors.Register(ModuleName, 4, "send transactions are disabled")
)

View File

@ -4,7 +4,7 @@ import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
// RegisterInvariants registers the bank module invariants

View File

@ -11,8 +11,8 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
vestexported "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/params"
"github.com/cosmos/cosmos-sdk/x/bank/types"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
)
var _ Keeper = (*BaseKeeper)(nil)
@ -31,11 +31,11 @@ type BaseKeeper struct {
BaseSendKeeper
ak types.AccountKeeper
paramSpace params.Subspace
paramSpace paramtypes.Subspace
}
func NewBaseKeeper(
cdc *codec.Codec, storeKey sdk.StoreKey, ak types.AccountKeeper, paramSpace params.Subspace, blacklistedAddrs map[string]bool,
cdc codec.Marshaler, storeKey sdk.StoreKey, ak types.AccountKeeper, paramSpace paramtypes.Subspace, blacklistedAddrs map[string]bool,
) BaseKeeper {
ps := paramSpace.WithKeyTable(types.ParamKeyTable())
@ -146,17 +146,17 @@ var _ SendKeeper = (*BaseSendKeeper)(nil)
type BaseSendKeeper struct {
BaseViewKeeper
cdc *codec.Codec
cdc codec.Marshaler
ak types.AccountKeeper
storeKey sdk.StoreKey
paramSpace params.Subspace
paramSpace paramtypes.Subspace
// list of addresses that are restricted from receiving transactions
blacklistedAddrs map[string]bool
}
func NewBaseSendKeeper(
cdc *codec.Codec, storeKey sdk.StoreKey, ak types.AccountKeeper, paramSpace params.Subspace, blacklistedAddrs map[string]bool,
cdc codec.Marshaler, storeKey sdk.StoreKey, ak types.AccountKeeper, paramSpace paramtypes.Subspace, blacklistedAddrs map[string]bool,
) BaseSendKeeper {
return BaseSendKeeper{
@ -341,7 +341,7 @@ func (k BaseSendKeeper) SetBalance(ctx sdk.Context, addr sdk.AccAddress, balance
balancesStore := prefix.NewStore(store, types.BalancesPrefix)
accountStore := prefix.NewStore(balancesStore, addr.Bytes())
bz := k.cdc.MustMarshalBinaryBare(balance)
bz := k.cdc.MustMarshalBinaryBare(&balance)
accountStore.Set([]byte(balance.Denom), bz)
return nil
@ -385,13 +385,13 @@ type ViewKeeper interface {
// BaseViewKeeper implements a read only keeper implementation of ViewKeeper.
type BaseViewKeeper struct {
cdc *codec.Codec
cdc codec.Marshaler
storeKey sdk.StoreKey
ak types.AccountKeeper
}
// NewBaseViewKeeper returns a new BaseViewKeeper.
func NewBaseViewKeeper(cdc *codec.Codec, storeKey sdk.StoreKey, ak types.AccountKeeper) BaseViewKeeper {
func NewBaseViewKeeper(cdc codec.Marshaler, storeKey sdk.StoreKey, ak types.AccountKeeper) BaseViewKeeper {
return BaseViewKeeper{
cdc: cdc,
storeKey: storeKey,

View File

@ -13,7 +13,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/auth/vesting"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
const (
@ -171,7 +171,7 @@ func (suite *IntegrationTestSuite) TestValidateBalance() {
suite.Require().NoError(app.BankKeeper.ValidateBalance(ctx, addr1))
bacc := auth.NewBaseAccountWithAddress(addr2)
vacc := vesting.NewContinuousVestingAccount(&bacc, balances.Add(balances...), now.Unix(), endTime.Unix())
vacc := vesting.NewContinuousVestingAccount(bacc, balances.Add(balances...), now.Unix(), endTime.Unix())
app.AccountKeeper.SetAccount(ctx, vacc)
suite.Require().NoError(app.BankKeeper.SetBalances(ctx, addr2, balances))
@ -392,7 +392,7 @@ func (suite *IntegrationTestSuite) TestSpendableCoins() {
macc := app.AccountKeeper.NewAccountWithAddress(ctx, addrModule)
bacc := auth.NewBaseAccountWithAddress(addr1)
vacc := vesting.NewContinuousVestingAccount(&bacc, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix())
vacc := vesting.NewContinuousVestingAccount(bacc, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix())
acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr2)
app.AccountKeeper.SetAccount(ctx, macc)
@ -421,7 +421,7 @@ func (suite *IntegrationTestSuite) TestVestingAccountSend() {
addr2 := sdk.AccAddress([]byte("addr2"))
bacc := auth.NewBaseAccountWithAddress(addr1)
vacc := vesting.NewContinuousVestingAccount(&bacc, origCoins, now.Unix(), endTime.Unix())
vacc := vesting.NewContinuousVestingAccount(bacc, origCoins, now.Unix(), endTime.Unix())
app.AccountKeeper.SetAccount(ctx, vacc)
suite.Require().NoError(app.BankKeeper.SetBalances(ctx, addr1, origCoins))
@ -454,7 +454,7 @@ func (suite *IntegrationTestSuite) TestPeriodicVestingAccountSend() {
}
bacc := auth.NewBaseAccountWithAddress(addr1)
vacc := vesting.NewPeriodicVestingAccount(&bacc, origCoins, ctx.BlockHeader().Time.Unix(), periods)
vacc := vesting.NewPeriodicVestingAccount(bacc, origCoins, ctx.BlockHeader().Time.Unix(), periods)
app.AccountKeeper.SetAccount(ctx, vacc)
suite.Require().NoError(app.BankKeeper.SetBalances(ctx, addr1, origCoins))
@ -484,7 +484,7 @@ func (suite *IntegrationTestSuite) TestVestingAccountReceive() {
addr2 := sdk.AccAddress([]byte("addr2"))
bacc := auth.NewBaseAccountWithAddress(addr1)
vacc := vesting.NewContinuousVestingAccount(&bacc, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix())
vacc := vesting.NewContinuousVestingAccount(bacc, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix())
acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr2)
app.AccountKeeper.SetAccount(ctx, vacc)
@ -523,7 +523,7 @@ func (suite *IntegrationTestSuite) TestPeriodicVestingAccountReceive() {
vesting.Period{Length: int64(6 * 60 * 60), Amount: sdk.Coins{sdk.NewInt64Coin("stake", 25)}},
}
vacc := vesting.NewPeriodicVestingAccount(&bacc, origCoins, ctx.BlockHeader().Time.Unix(), periods)
vacc := vesting.NewPeriodicVestingAccount(bacc, origCoins, ctx.BlockHeader().Time.Unix(), periods)
acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr2)
app.AccountKeeper.SetAccount(ctx, vacc)
@ -560,7 +560,7 @@ func (suite *IntegrationTestSuite) TestDelegateCoins() {
macc := app.AccountKeeper.NewAccountWithAddress(ctx, addrModule) // we don't need to define an actual module account bc we just need the address for testing
acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr2)
bacc := auth.NewBaseAccountWithAddress(addr1)
vacc := vesting.NewContinuousVestingAccount(&bacc, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix())
vacc := vesting.NewContinuousVestingAccount(bacc, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix())
app.AccountKeeper.SetAccount(ctx, vacc)
app.AccountKeeper.SetAccount(ctx, acc)
@ -620,7 +620,7 @@ func (suite *IntegrationTestSuite) TestUndelegateCoins() {
bacc := auth.NewBaseAccountWithAddress(addr1)
macc := app.AccountKeeper.NewAccountWithAddress(ctx, addrModule) // we don't need to define an actual module account bc we just need the address for testing
vacc := vesting.NewContinuousVestingAccount(&bacc, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix())
vacc := vesting.NewContinuousVestingAccount(bacc, origCoins, ctx.BlockHeader().Time.Unix(), endTime.Unix())
acc := app.AccountKeeper.NewAccountWithAddress(ctx, addr2)
app.AccountKeeper.SetAccount(ctx, vacc)

View File

@ -6,7 +6,7 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
// NewQuerier returns a new sdk.Keeper instance.

View File

@ -7,8 +7,8 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/bank/internal/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
func (suite *IntegrationTestSuite) TestQuerier_QueryBalance() {

View File

@ -16,9 +16,9 @@ import (
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/bank/client/cli"
"github.com/cosmos/cosmos-sdk/x/bank/client/rest"
"github.com/cosmos/cosmos-sdk/x/bank/internal/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/simulation"
"github.com/cosmos/cosmos-sdk/x/bank/types"
sim "github.com/cosmos/cosmos-sdk/x/simulation"
)
@ -39,14 +39,14 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { RegisterCodec(cdc) }
// DefaultGenesis returns default genesis state as raw bytes for the bank
// module.
func (AppModuleBasic) DefaultGenesis() json.RawMessage {
return ModuleCdc.MustMarshalJSON(DefaultGenesisState())
func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage {
return cdc.MustMarshalJSON(DefaultGenesisState())
}
// ValidateGenesis performs genesis state validation for the bank module.
func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error {
func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessage) error {
var data GenesisState
if err := ModuleCdc.UnmarshalJSON(bz, &data); err != nil {
if err := cdc.UnmarshalJSON(bz, &data); err != nil {
return fmt.Errorf("failed to unmarshal %s genesis state: %w", ModuleName, err)
}
@ -111,18 +111,18 @@ func (am AppModule) NewQuerierHandler() sdk.Querier {
// InitGenesis performs genesis initialization for the bank module. It returns
// no validator updates.
func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate {
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate {
var genesisState GenesisState
ModuleCdc.MustUnmarshalJSON(data, &genesisState)
cdc.MustUnmarshalJSON(data, &genesisState)
InitGenesis(ctx, am.keeper, genesisState)
return []abci.ValidatorUpdate{}
}
// ExportGenesis returns the exported genesis state as raw bytes for the bank
// module.
func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage {
func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage {
gs := ExportGenesis(ctx, am.keeper)
return ModuleCdc.MustMarshalJSON(gs)
return cdc.MustMarshalJSON(gs)
}
// BeginBlock performs a no-op.

View File

@ -7,7 +7,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
)
// Simulation parameter constants

View File

@ -10,8 +10,8 @@ import (
"github.com/cosmos/cosmos-sdk/simapp/helpers"
simappparams "github.com/cosmos/cosmos-sdk/simapp/params"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/internal/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/keeper"
"github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/simulation"
)

View File

@ -6,7 +6,7 @@ import (
"fmt"
"math/rand"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/simulation"
)

28
x/bank/types/codec.go Normal file
View File

@ -0,0 +1,28 @@
package types
import (
"github.com/cosmos/cosmos-sdk/codec"
)
// Register concrete types on codec codec
func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(MsgSend{}, "cosmos-sdk/MsgSend", nil)
cdc.RegisterConcrete(MsgMultiSend{}, "cosmos-sdk/MsgMultiSend", nil)
}
var (
amino = codec.New()
// ModuleCdc references the global x/staking module codec. Note, the codec should
// ONLY be used in certain instances of tests and for JSON encoding as Amino is
// still used for that purpose.
//
// The actual codec used for serialization should be provided to x/staking and
// defined at the application level.
ModuleCdc = codec.NewHybridCodec(amino)
)
func init() {
RegisterCodec(amino)
amino.Seal()
}

13
x/bank/types/errors.go Normal file
View File

@ -0,0 +1,13 @@
package types
import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
// x/bank module sentinel errors
var (
ErrNoInputs = sdkerrors.Register(ModuleName, 2, "no inputs to send transaction")
ErrNoOutputs = sdkerrors.Register(ModuleName, 3, "no outputs to send transaction")
ErrInputOutputMismatch = sdkerrors.Register(ModuleName, 4, "sum inputs != sum outputs")
ErrSendDisabled = sdkerrors.Register(ModuleName, 5, "send transactions are disabled")
)

View File

@ -4,7 +4,7 @@ import (
"testing"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/bank/internal/types"
"github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/stretchr/testify/require"
)

View File

@ -5,13 +5,6 @@ import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
// MsgSend - high level transaction of the coin module
type MsgSend struct {
FromAddress sdk.AccAddress `json:"from_address" yaml:"from_address"`
ToAddress sdk.AccAddress `json:"to_address" yaml:"to_address"`
Amount sdk.Coins `json:"amount" yaml:"amount"`
}
var _ sdk.Msg = MsgSend{}
// NewMsgSend - construct arbitrary multi-in, multi-out send msg.
@ -52,12 +45,6 @@ func (msg MsgSend) GetSigners() []sdk.AccAddress {
return []sdk.AccAddress{msg.FromAddress}
}
// MsgMultiSend - high level transaction of the coin module
type MsgMultiSend struct {
Inputs []Input `json:"inputs" yaml:"inputs"`
Outputs []Output `json:"outputs" yaml:"outputs"`
}
var _ sdk.Msg = MsgMultiSend{}
// NewMsgMultiSend - construct arbitrary multi-in, multi-out send msg.
@ -99,12 +86,6 @@ func (msg MsgMultiSend) GetSigners() []sdk.AccAddress {
return addrs
}
// Input models transaction input
type Input struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
Coins sdk.Coins `json:"coins" yaml:"coins"`
}
// ValidateBasic - validate transaction input
func (in Input) ValidateBasic() error {
if len(in.Address) == 0 {
@ -127,12 +108,6 @@ func NewInput(addr sdk.AccAddress, coins sdk.Coins) Input {
}
}
// Output models transaction outputs
type Output struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
Coins sdk.Coins `json:"coins" yaml:"coins"`
}
// ValidateBasic - validate transaction output
func (out Output) ValidateBasic() error {
if len(out.Address) == 0 {

View File

@ -3,7 +3,7 @@ package types
import (
"fmt"
"github.com/cosmos/cosmos-sdk/x/params"
paramtypes "github.com/cosmos/cosmos-sdk/x/params/types"
)
const (
@ -17,9 +17,9 @@ const (
var ParamStoreKeySendEnabled = []byte("sendenabled")
// ParamKeyTable type declaration for parameters
func ParamKeyTable() params.KeyTable {
return params.NewKeyTable(
params.NewParamSetPair(ParamStoreKeySendEnabled, false, validateSendEnabled),
func ParamKeyTable() paramtypes.KeyTable {
return paramtypes.NewKeyTable(
paramtypes.NewParamSetPair(ParamStoreKeySendEnabled, false, validateSendEnabled),
)
}

1314
x/bank/types/types.pb.go Normal file

File diff suppressed because it is too large Load Diff

56
x/bank/types/types.proto Normal file
View File

@ -0,0 +1,56 @@
syntax = "proto3";
package cosmos_sdk.x.bank.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/bank/types";
import "third_party/proto/gogoproto/gogo.proto";
import "types/types.proto";
// MsgSend - high level transaction of the coin module
message MsgSend {
option (gogoproto.equal) = true;
bytes from_address = 1 [
(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress",
(gogoproto.moretags) = "yaml:\"from_address\""
];
bytes to_address = 2 [
(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress",
(gogoproto.moretags) = "yaml:\"to_address\""
];
repeated cosmos_sdk.v1.Coin amount = 3 [
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
}
// Input models transaction input
message Input {
option (gogoproto.equal) = true;
bytes address = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"];
repeated cosmos_sdk.v1.Coin coins = 2 [
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
}
// Output models transaction outputs
message Output {
option (gogoproto.equal) = true;
bytes address = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"];
repeated cosmos_sdk.v1.Coin coins = 2 [
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"
];
}
// MsgMultiSend - high level transaction of the coin module
message MsgMultiSend {
option (gogoproto.equal) = true;
repeated Input inputs = 1 [(gogoproto.nullable) = false];
repeated Output outputs = 2 [(gogoproto.nullable) = false];
}

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