diff --git a/CHANGELOG.md b/CHANGELOG.md index 00a3a19b0441..dadcf175e0ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,11 @@ Ref: https://keepachangelog.com/en/1.0.0/ # Changelog +## [v0.39.1] + +* (x/auth) [\#6861](https://github.com/cosmos/cosmos-sdk/pull/6861) Remove public key Bech32 encoding for all account types for JSON serialization, instead relying on direct Amino encoding. In addition, JSON serialization utilizes Amino instead of the Go stdlib, so integers are treated as strings. +* (client) [\#6853](https://github.com/cosmos/cosmos-sdk/pull/6853) Add --unsafe-cors flag. + ## [v0.39.0] ### Improvements @@ -2949,7 +2954,9 @@ BUG FIXES: -[Unreleased]: https://github.com/cosmos/cosmos-sdk/compare/v0.38.2...HEAD +[Unreleased]: https://github.com/cosmos/cosmos-sdk/compare/v0.39.1...HEAD +[v0.39.1]: https://github.com/cosmos/cosmos-sdk/releases/tag/v0.39.1 +[v0.39.0]: https://github.com/cosmos/cosmos-sdk/releases/tag/v0.39.0 [v0.38.2]: https://github.com/cosmos/cosmos-sdk/releases/tag/v0.38.2 [v0.38.1]: https://github.com/cosmos/cosmos-sdk/releases/tag/v0.38.1 [v0.38.0]: https://github.com/cosmos/cosmos-sdk/releases/tag/v0.38.0 diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 85975749b270..efbe90d5ff2a 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,131 +1,20 @@ -# Cosmos SDK v0.39.0 Release Notes +# Cosmos SDK v0.39.1 Release Notes -This is the inaugural release of the **Cosmos SDK 0.39 «Launchpad»** release series. +This release fixes the [issue affecting the accounts migration](https://github.com/cosmos/cosmos-sdk/issues/6828) from v0.38 to v0.39. -See the [Cosmos SDK 0.39.0 milestone](https://github.com/cosmos/cosmos-sdk/milestone/27?closed=1) on our issue tracker for details. +See the [Cosmos SDK 0.39.1 milestone](https://github.com/cosmos/cosmos-sdk/milestone/29?closed=1) on our issue tracker for details. -## Changes to IAVL and store pruning +## Remove custom JSON serialization for account types -The pruning features introduced in the `0.38` release series are buggy and might lead to data loss, -even after upgrading to `v0.39.0`. When upgrading from `0.38` it is important to follow the instructions -below, to prevent data loss and database corruption. +Account types JSON serialization has now changed to Amino. Changes are significant (e.g. integers are treated +as strings) thus it is required to migrate the exported state of an application before restarting the node +with a more recent version of the Cosmos SDK. -**Note: there are are several breaking changes with regard to IAVL, stores, and pruning settings that affect command line clients, server configuration, and Golang API.** +## REST server's --unsafe-cors mode -### Migrate an application from 0.38.5 to 0.39.0 +This a UX improvement [back ported from master](https://github.com/cosmos/cosmos-sdk/pull/6853) that allows developers to disable CORS +restrictions during app development and testing by passing the `--unsafe-cors` option to the client's `rest-server` command. -The IAVL's `v0.13.0` release introduced a pruning functionality that turned out to be buggy and flawed. -IAVL's new `v0.14.0` release now commits and flushes every state to disk as it did in pre-`v0.13.0` release. -The SDK's multi-store will track and ensure the proper heights are pruned. The operator can now set the pruning -options by passing a `pruning` configuration via command line option or `app.toml`. The `pruning` flag supports the following -options: `default`, `everything`, `nothing`, `custom` - see docs for further details. If the operator chooses `custom`, they -may want to provide either of the granular pruning values: -- `pruning-keep-recent` -- `pruning-keep-every` -- `pruning-interval` +## Tendermint 0.33.7 -The former two options dictate how many recent versions are kept on disk and the offset of what versions are kept after that -respectively, and the latter defines the height interval in which versions are deleted in a batch. **Note: there are are some -client application breaking changes with regard to IAVL, stores, and pruning settings.** An example patch follows: - -```patch -From 5884171ba73c3054e98564c39adc9cbbab8d4646 Mon Sep 17 00:00:00 2001 -From: Alessio Treglia -Date: Tue, 14 Jul 2020 14:54:19 +0100 -Subject: [PATCH 2/4] use new pruning options - ---- - cmd/cnd/main.go | 8 ++++++-- - 1 file changed, 6 insertions(+), 2 deletions(-) - -diff --git a/cmd/cnd/main.go b/cmd/cnd/main.go -index b0c86f4a..4a3a8518 100644 ---- a/cmd/cnd/main.go -+++ b/cmd/cnd/main.go -@@ -23,7 +23,6 @@ import ( - comgenutilcli "github.com/commercionetwork/commercionetwork/x/genutil/client/cli" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/server" -- "github.com/cosmos/cosmos-sdk/store" - genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" - "github.com/cosmos/cosmos-sdk/x/staking" - ) -@@ -87,9 +86,14 @@ func main() { - } - - func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application { -+ pruningOpts, err := server.GetPruningOptionsFromFlags() -+ if err != nil { -+ panic(err) -+ } -+ - return app.NewCommercioNetworkApp( - logger, db, traceStore, true, invCheckPeriod, -- baseapp.SetPruning(store.NewPruningOptionsFromString(viper.GetString("pruning"))), -+ baseapp.SetPruning(pruningOpts), - baseapp.SetMinGasPrices(viper.GetString(server.FlagMinGasPrices)), - baseapp.SetHaltHeight(uint64(viper.GetInt(server.FlagHaltHeight))), - ) -``` - -### Migrate a node from 0.38.5 to 0.39.0 - -Note: **do not modify pruning settings with any release prior to `v0.39.0` as that may cause data corruption**. - -The following instructions assume that **pruning settings have not been modified since the node started using 0.38.x. Note: the default pruning setting `syncable` used `KeepEvery:100`. - -#### Chain Hard Fork (also know as The Tested Upgrade Path) - -This strategy entails performing a hard fork of your chain. -It takes time, coordination and a few technical steps that the validators of the network must follow. Note: a software upgrade guide for `gaia`, the application that powers the Cosmos Hub, is [available too](https://hub.cosmos.network/master/gaia-tutorials/upgrade-node.html). It contains detailed instructions on how to upgrade network nodes that apply to the vast majority of Cosmos SDK applications. - -In preparation of the upgrade, you need to export the current state. This operation should be be performed on one node: - - * Stop the node and export the current state, e.g.: `appd export --for-zero-height > export_genesis.json`. - * Manually replace the chain id and genesis time fields in `export_genesis.json` with the values that the network had agreed upon. - -Follow these steps to perform the upgrade: - -* Make a backup copy of the old `genesis.json` file in your server application's config directory (e.g. `$HOME/.appd/config/genesis.json`) and replace it with `export_genesis.json`. Note: do rename `export_genesis.json` to `genesis.json`. -* Replace the old binary with the new one and restart the service using the new binary. - -#### Alternative strategies - -Alternatively, you can follow *one of* the following strategies: - -* Replace the application server's binary and perform a full sync of the node from scratch. - -* If your node had started with using `KeepEvery:1` (e.g. pruning settings `nothing` or `everything`), upgrading to `v0.39.0` should be simple and safe. - -* Do halt block processing with `--halt-height` after committing a height divisible by `KeepEvery` - e.g. at block 147600 with `KeepEvery:100`. The **node must never have processed a height beyond that at any time in its past**. Upgrading to `v0.39.0` is then safe. - -* Set the `KeepEvery` setting to the same as the previous `KeepEvery` setting (both `<=v0.38.5` and `v0.39.0` default to `KeepEvery:100`). Upgrade to `v0.39.0` is then safe as long as you wait one `KeepEvery` interval plus one `KeepRecent` interval **plus** one pruning `Interval` before changing pruning settings or deleting the last `<=v0.38.5` height (so wait *210* heights with the default configuration). - -* Otherwise, make sure the last version persisted with `<=v0.38.5` is never deleted after upgrading to `v0.39.0`, as doing so may cause data loss and data corruption. - -## Regression in the signature verification when multiple transactions in the same block are sent from the same account - -When multiple transactions in the same block are sent (and correctly signed) by the same account, chances are that some of them could be rejected and the error `unauthorized: signature verification failed` would be returned due to the account's sequence (*nonce*) getting stuck and not being incremented by the ante handler. This behaviour was [a regression](https://github.com/cosmos/cosmos-sdk/issues/6287) introduced in the `v0.38` release series, it did not occur in the `v0.37` release series and is now fixed in this release. - -## Changes to ABCI Query's "app/simulate" path - -The `app/simulate` query path is used to simulate the execution transactions in order to obtain an estimate -of the gas consumption that would be required to actually execute them. The response used to return only -the amount of gas, it now returns the result of the transaction as well. - -## bank.send event comes with sender information - -The `bank.send` event used to carry only the recipient and amount. It was assumed that the sender of the funds was `message.sender`. -This is often not true when a module call the bank keeper directly. This may be due to staking distribution, or via a cosmwasm contract that released funds (where I discovered the issue). - -`bank.send` now contains the entire triple `(sender, recipient, amount)`. - -## trace option is no longer ignored - -The `--trace` option is reintroduced. It comes in very handy for debugging as it causes the full stack trace to be included in the ABCI error logs. - -## appcli keys parse command didn't honor client application's bech32 prefixes - -The `key parse` command ignored the application-specific address bech32 -prefixes and used to return `cosmos*1`-prefixed addresses regardless -of the client application's configuration. +Tendermint 0.33.7 brings an important regression fix. Please refer to [this bug report](https://github.com/tendermint/tendermint/issues/5112) for more information. diff --git a/client/flags/flags.go b/client/flags/flags.go index 64dc2f25a34f..746b512b0697 100644 --- a/client/flags/flags.go +++ b/client/flags/flags.go @@ -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 } diff --git a/client/lcd/root.go b/client/lcd/root.go index a99f99fe9faf..6b5abf87bcc2 100644 --- a/client/lcd/root.go +++ b/client/lcd/root.go @@ -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,7 +69,13 @@ func (rs *RestServer) Start(listenAddr string, maxOpen int, readTimeout, writeTi ), ) - return tmrpcserver.Serve(rs.listener, rs.Mux, rs.log, cfg) + var h http.Handler = rs.Mux + if cors { + allowAllCORS := handlers.CORS(handlers.AllowedHeaders([]string{"Content-Type"})) + h = allowAllCORS(h) + } + + return tmrpcserver.Serve(rs.listener, h, rs.log, cfg) } // ServeCommand will start the application REST service as a blocking process. It @@ -90,6 +97,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 diff --git a/docs/interfaces/rest.md b/docs/interfaces/rest.md index 75e5a78dc3d8..9ba57ffb2af9 100644 --- a/docs/interfaces/rest.md +++ b/docs/interfaces/rest.md @@ -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 --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 +``` diff --git a/go.mod b/go.mod index 43d37e1a2c95..840086d89cbb 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,8 @@ require ( github.com/cosmos/ledger-cosmos-go v0.11.1 github.com/gogo/protobuf v1.3.1 github.com/golang/mock v1.3.1-0.20190508161146-9fa652df1129 - github.com/gorilla/mux v1.7.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 @@ -27,7 +28,7 @@ require ( github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 github.com/tendermint/go-amino v0.15.1 github.com/tendermint/iavl v0.14.0 - github.com/tendermint/tendermint v0.33.6 + github.com/tendermint/tendermint v0.33.7 github.com/tendermint/tm-db v0.5.1 google.golang.org/grpc v1.30.0 // indirect gopkg.in/yaml.v2 v2.3.0 diff --git a/go.sum b/go.sum index f826ee5ea29c..f942dd234128 100644 --- a/go.sum +++ b/go.sum @@ -172,9 +172,12 @@ github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ 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/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= +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.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +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 v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= @@ -421,10 +424,9 @@ 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.14.0 h1:Jkff+IFrXxRWtH9Jn/ga/2cxNnzMTv58xEKgCJsKUBg= github.com/tendermint/iavl v0.14.0/go.mod h1:QmfViflFiXzxKLQE4tAUuWQHq+RSuQFxablW5oJZ6sE= -github.com/tendermint/tendermint v0.33.5 h1:jYgRd9ImkzA9iOyhpmgreYsqSB6tpDa6/rXYPb8HKE8= github.com/tendermint/tendermint v0.33.5/go.mod h1:0yUs9eIuuDq07nQql9BmI30FtYGcEC60Tu5JzB5IezM= -github.com/tendermint/tendermint v0.33.6 h1:W4UOsXY4ROJZ3TLLGVVv71VXD4WK2gJRb3gzeced+mg= -github.com/tendermint/tendermint v0.33.6/go.mod h1:0yUs9eIuuDq07nQql9BmI30FtYGcEC60Tu5JzB5IezM= +github.com/tendermint/tendermint v0.33.7 h1:b5CQD8ggDtl4u0EbXzabi0MaOw9NrcXker6ijEkAE74= +github.com/tendermint/tendermint v0.33.7/go.mod h1:0yUs9eIuuDq07nQql9BmI30FtYGcEC60Tu5JzB5IezM= github.com/tendermint/tm-db v0.5.1 h1:H9HDq8UEA7Eeg13kdYckkgwwkQLBnJGgX4PgLJRhieY= github.com/tendermint/tm-db v0.5.1/go.mod h1:g92zWjHpCYlEvQXvy9M168Su8V1IBEeawpXVVBaK4f4= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= diff --git a/x/auth/legacy/v0_38/migrate.go b/x/auth/legacy/v0_38/migrate.go index e76937777678..f4a32b4454c3 100644 --- a/x/auth/legacy/v0_38/migrate.go +++ b/x/auth/legacy/v0_38/migrate.go @@ -42,9 +42,9 @@ func Migrate(authGenState v036auth.GenesisState, genAccountsGenState v036genacco accounts[i] = genAccount } - accounts = sanitizeGenesisAccounts(accounts) + accounts = SanitizeGenesisAccounts(accounts) - if err := validateGenAccounts(accounts); err != nil { + if err := ValidateGenAccounts(accounts); err != nil { panic(err) } diff --git a/x/auth/legacy/v0_38/types.go b/x/auth/legacy/v0_38/types.go index 15896a39121f..67b515182fc4 100644 --- a/x/auth/legacy/v0_38/types.go +++ b/x/auth/legacy/v0_38/types.go @@ -46,7 +46,7 @@ type ( BaseAccount struct { Address sdk.AccAddress `json:"address" yaml:"address"` - Coins sdk.Coins `json:"coins" yaml:"coins"` + Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"` PubKey crypto.PubKey `json:"public_key" yaml:"public_key"` AccountNumber uint64 `json:"account_number" yaml:"account_number"` Sequence uint64 `json:"sequence" yaml:"sequence"` @@ -54,7 +54,7 @@ type ( baseAccountPretty struct { Address sdk.AccAddress `json:"address" yaml:"address"` - Coins sdk.Coins `json:"coins" yaml:"coins"` + Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"` PubKey string `json:"public_key" yaml:"public_key"` AccountNumber uint64 `json:"account_number" yaml:"account_number"` Sequence uint64 `json:"sequence" yaml:"sequence"` @@ -72,7 +72,7 @@ type ( vestingAccountPretty struct { Address sdk.AccAddress `json:"address" yaml:"address"` - Coins sdk.Coins `json:"coins" yaml:"coins"` + Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"` PubKey string `json:"public_key" yaml:"public_key"` AccountNumber uint64 `json:"account_number" yaml:"account_number"` Sequence uint64 `json:"sequence" yaml:"sequence"` @@ -104,7 +104,7 @@ type ( moduleAccountPretty struct { Address sdk.AccAddress `json:"address" yaml:"address"` - Coins sdk.Coins `json:"coins" yaml:"coins"` + Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"` PubKey string `json:"public_key" yaml:"public_key"` AccountNumber uint64 `json:"account_number" yaml:"account_number"` Sequence uint64 `json:"sequence" yaml:"sequence"` @@ -434,7 +434,7 @@ func NewModuleAccount(baseAccount *BaseAccount, name string, permissions ...stri } func (ma ModuleAccount) Validate() error { - if err := validatePermissions(ma.Permissions...); err != nil { + if err := ValidatePermissions(ma.Permissions...); err != nil { return err } @@ -476,7 +476,7 @@ func (ma *ModuleAccount) UnmarshalJSON(bz []byte) error { return nil } -func validatePermissions(permissions ...string) error { +func ValidatePermissions(permissions ...string) error { for _, perm := range permissions { if strings.TrimSpace(perm) == "" { return fmt.Errorf("module permission is empty") @@ -486,7 +486,7 @@ func validatePermissions(permissions ...string) error { return nil } -func sanitizeGenesisAccounts(genAccounts GenesisAccounts) GenesisAccounts { +func SanitizeGenesisAccounts(genAccounts GenesisAccounts) GenesisAccounts { sort.Slice(genAccounts, func(i, j int) bool { return genAccounts[i].GetAccountNumber() < genAccounts[j].GetAccountNumber() }) @@ -500,7 +500,7 @@ func sanitizeGenesisAccounts(genAccounts GenesisAccounts) GenesisAccounts { return genAccounts } -func validateGenAccounts(genAccounts GenesisAccounts) error { +func ValidateGenAccounts(genAccounts GenesisAccounts) error { addrMap := make(map[string]bool, len(genAccounts)) for _, acc := range genAccounts { diff --git a/x/auth/legacy/v0_39/migrate.go b/x/auth/legacy/v0_39/migrate.go new file mode 100644 index 000000000000..410283dc93fd --- /dev/null +++ b/x/auth/legacy/v0_39/migrate.go @@ -0,0 +1,60 @@ +package v039 + +import ( + "fmt" + + v038auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v0_38" +) + +// Migrate accepts exported genesis state from v0.38 and migrates it to v0.39 +// genesis state. +func Migrate(oldAuthGenState v038auth.GenesisState) GenesisState { + accounts := make(v038auth.GenesisAccounts, len(oldAuthGenState.Accounts)) + + for i, acc := range oldAuthGenState.Accounts { + switch t := acc.(type) { + case *v038auth.BaseAccount: + accounts[i] = NewBaseAccount(t.Address, t.Coins, t.PubKey, t.AccountNumber, t.Sequence) + + case *v038auth.BaseVestingAccount: + accounts[i] = NewBaseVestingAccount( + NewBaseAccount(t.Address, t.Coins, t.PubKey, t.AccountNumber, t.Sequence), + t.OriginalVesting, t.DelegatedFree, t.DelegatedVesting, t.EndTime, + ) + + case *v038auth.ContinuousVestingAccount: + accounts[i] = NewContinuousVestingAccountRaw( + NewBaseVestingAccount( + NewBaseAccount(t.Address, t.Coins, t.PubKey, t.AccountNumber, t.Sequence), + t.OriginalVesting, t.DelegatedFree, t.DelegatedVesting, t.EndTime, + ), + t.StartTime, + ) + + case *v038auth.DelayedVestingAccount: + accounts[i] = NewDelayedVestingAccountRaw( + NewBaseVestingAccount( + NewBaseAccount(t.Address, t.Coins, t.PubKey, t.AccountNumber, t.Sequence), + t.OriginalVesting, t.DelegatedFree, t.DelegatedVesting, t.EndTime, + ), + ) + + case *v038auth.ModuleAccount: + accounts[i] = NewModuleAccount( + NewBaseAccount(t.Address, t.Coins, t.PubKey, t.AccountNumber, t.Sequence), + t.Name, t.Permissions..., + ) + + default: + panic(fmt.Sprintf("unexpected account type: %T", acc)) + } + } + + accounts = v038auth.SanitizeGenesisAccounts(accounts) + + if err := v038auth.ValidateGenAccounts(accounts); err != nil { + panic(err) + } + + return NewGenesisState(oldAuthGenState.Params, accounts) +} diff --git a/x/auth/legacy/v0_39/types.go b/x/auth/legacy/v0_39/types.go new file mode 100644 index 000000000000..dbf9b3b8870d --- /dev/null +++ b/x/auth/legacy/v0_39/types.go @@ -0,0 +1,426 @@ +package v039 + +// DONTCOVER +// nolint + +import ( + "bytes" + "errors" + "fmt" + "strings" + + "github.com/tendermint/tendermint/crypto" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + v034auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v0_34" + v038auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v0_38" +) + +const ( + ModuleName = "auth" +) + +type ( + GenesisState struct { + Params v034auth.Params `json:"params" yaml:"params"` + Accounts v038auth.GenesisAccounts `json:"accounts" yaml:"accounts"` + } + + BaseAccount struct { + Address sdk.AccAddress `json:"address" yaml:"address"` + Coins sdk.Coins `json:"coins,omitempty" yaml:"coins,omitempty"` + PubKey crypto.PubKey `json:"public_key" yaml:"public_key"` + AccountNumber uint64 `json:"account_number" yaml:"account_number"` + Sequence uint64 `json:"sequence" yaml:"sequence"` + } + + BaseVestingAccount struct { + *BaseAccount + + OriginalVesting sdk.Coins `json:"original_vesting"` + DelegatedFree sdk.Coins `json:"delegated_free"` + DelegatedVesting sdk.Coins `json:"delegated_vesting"` + + EndTime int64 `json:"end_time"` + } + + vestingAccountJSON struct { + Address sdk.AccAddress `json:"address" yaml:"address"` + Coins sdk.Coins `json:"coins,omitempty" yaml:"coins"` + PubKey crypto.PubKey `json:"public_key" yaml:"public_key"` + AccountNumber uint64 `json:"account_number" yaml:"account_number"` + Sequence uint64 `json:"sequence" yaml:"sequence"` + 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"` + } + + ContinuousVestingAccount struct { + *BaseVestingAccount + + StartTime int64 `json:"start_time"` + } + + DelayedVestingAccount struct { + *BaseVestingAccount + } + + 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 []Period + + 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 + } + + ModuleAccount struct { + *BaseAccount + + Name string `json:"name" yaml:"name"` + Permissions []string `json:"permissions" yaml:"permissions"` + } + + moduleAccountPretty struct { + Address sdk.AccAddress `json:"address" yaml:"address"` + Coins sdk.Coins `json:"coins,omitempty" yaml:"coins"` + PubKey string `json:"public_key" yaml:"public_key"` + AccountNumber uint64 `json:"account_number" yaml:"account_number"` + Sequence uint64 `json:"sequence" yaml:"sequence"` + Name string `json:"name" yaml:"name"` + Permissions []string `json:"permissions" yaml:"permissions"` + } +) + +func NewGenesisState(params v034auth.Params, accounts v038auth.GenesisAccounts) GenesisState { + return GenesisState{ + Params: params, + Accounts: accounts, + } +} + +func NewBaseAccountWithAddress(addr sdk.AccAddress) BaseAccount { + return BaseAccount{ + Address: addr, + } +} + +func NewBaseAccount( + address sdk.AccAddress, coins sdk.Coins, pk crypto.PubKey, accountNumber, sequence uint64, +) *BaseAccount { + + return &BaseAccount{ + Address: address, + Coins: coins, + PubKey: pk, + AccountNumber: accountNumber, + Sequence: sequence, + } +} + +func (acc BaseAccount) GetAddress() sdk.AccAddress { + return acc.Address +} + +func (acc *BaseAccount) GetAccountNumber() uint64 { + return acc.AccountNumber +} + +func (acc *BaseAccount) GetCoins() sdk.Coins { + return acc.Coins +} + +func (acc *BaseAccount) SetCoins(coins sdk.Coins) error { + acc.Coins = coins + return nil +} + +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") + } + + return nil +} + +func NewBaseVestingAccount( + baseAccount *BaseAccount, originalVesting, delegatedFree, delegatedVesting sdk.Coins, endTime int64, +) *BaseVestingAccount { + + return &BaseVestingAccount{ + BaseAccount: baseAccount, + OriginalVesting: originalVesting, + DelegatedFree: delegatedFree, + DelegatedVesting: delegatedVesting, + EndTime: endTime, + } +} + +func (bva BaseVestingAccount) MarshalJSON() ([]byte, error) { + alias := vestingAccountJSON{ + Address: bva.Address, + Coins: bva.Coins, + PubKey: bva.PubKey, + AccountNumber: bva.AccountNumber, + Sequence: bva.Sequence, + OriginalVesting: bva.OriginalVesting, + DelegatedFree: bva.DelegatedFree, + DelegatedVesting: bva.DelegatedVesting, + EndTime: bva.EndTime, + } + + return codec.Cdc.MarshalJSON(alias) +} + +func (bva *BaseVestingAccount) UnmarshalJSON(bz []byte) error { + var alias vestingAccountJSON + if err := codec.Cdc.UnmarshalJSON(bz, &alias); err != nil { + return err + } + + bva.BaseAccount = NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence) + bva.OriginalVesting = alias.OriginalVesting + bva.DelegatedFree = alias.DelegatedFree + bva.DelegatedVesting = alias.DelegatedVesting + bva.EndTime = alias.EndTime + + return nil +} + +func (bva BaseVestingAccount) GetEndTime() int64 { + return bva.EndTime +} + +func (bva BaseVestingAccount) Validate() error { + + return bva.BaseAccount.Validate() +} + +func NewContinuousVestingAccountRaw(bva *BaseVestingAccount, startTime int64) *ContinuousVestingAccount { + return &ContinuousVestingAccount{ + BaseVestingAccount: bva, + StartTime: startTime, + } +} + +func (cva ContinuousVestingAccount) Validate() error { + if cva.StartTime >= cva.EndTime { + return errors.New("vesting start-time cannot be before end-time") + } + + return cva.BaseVestingAccount.Validate() +} + +func (cva ContinuousVestingAccount) MarshalJSON() ([]byte, error) { + alias := vestingAccountJSON{ + Address: cva.Address, + Coins: cva.Coins, + PubKey: cva.PubKey, + AccountNumber: cva.AccountNumber, + Sequence: cva.Sequence, + OriginalVesting: cva.OriginalVesting, + DelegatedFree: cva.DelegatedFree, + DelegatedVesting: cva.DelegatedVesting, + EndTime: cva.EndTime, + StartTime: cva.StartTime, + } + + return codec.Cdc.MarshalJSON(alias) +} + +func (cva *ContinuousVestingAccount) UnmarshalJSON(bz []byte) error { + var alias vestingAccountJSON + if err := codec.Cdc.UnmarshalJSON(bz, &alias); err != nil { + return err + } + + cva.BaseVestingAccount = &BaseVestingAccount{ + BaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence), + OriginalVesting: alias.OriginalVesting, + DelegatedFree: alias.DelegatedFree, + DelegatedVesting: alias.DelegatedVesting, + EndTime: alias.EndTime, + } + cva.StartTime = alias.StartTime + + return nil +} + +func NewDelayedVestingAccountRaw(bva *BaseVestingAccount) *DelayedVestingAccount { + return &DelayedVestingAccount{ + BaseVestingAccount: bva, + } +} + +func (dva DelayedVestingAccount) Validate() error { + return dva.BaseVestingAccount.Validate() +} + +func (dva DelayedVestingAccount) MarshalJSON() ([]byte, error) { + alias := vestingAccountJSON{ + Address: dva.Address, + Coins: dva.Coins, + PubKey: dva.PubKey, + AccountNumber: dva.AccountNumber, + Sequence: dva.Sequence, + OriginalVesting: dva.OriginalVesting, + DelegatedFree: dva.DelegatedFree, + DelegatedVesting: dva.DelegatedVesting, + EndTime: dva.EndTime, + } + + return codec.Cdc.MarshalJSON(alias) +} + +// UnmarshalJSON unmarshals raw JSON bytes into a DelayedVestingAccount. +func (dva *DelayedVestingAccount) UnmarshalJSON(bz []byte) error { + var alias vestingAccountJSON + if err := codec.Cdc.UnmarshalJSON(bz, &alias); err != nil { + return err + } + + dva.BaseVestingAccount = &BaseVestingAccount{ + BaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence), + OriginalVesting: alias.OriginalVesting, + DelegatedFree: alias.DelegatedFree, + DelegatedVesting: alias.DelegatedVesting, + EndTime: alias.EndTime, + } + + return nil +} + +func (pva PeriodicVestingAccount) GetStartTime() int64 { + return pva.StartTime +} + +func (pva PeriodicVestingAccount) Validate() error { + if pva.GetStartTime() >= pva.GetEndTime() { + return errors.New("vesting start-time cannot be before end-time") + } + endTime := pva.StartTime + originalVesting := sdk.NewCoins() + for _, p := range pva.VestingPeriods { + endTime += p.Length + originalVesting = originalVesting.Add(p.Amount...) + } + if endTime != pva.EndTime { + return errors.New("vesting end time does not match length of all vesting periods") + } + if !originalVesting.IsEqual(pva.OriginalVesting) { + return errors.New("original vesting coins does not match the sum of all coins in vesting periods") + } + + return pva.BaseVestingAccount.Validate() +} + +func (pva PeriodicVestingAccount) MarshalJSON() ([]byte, error) { + alias := vestingAccountJSON{ + Address: pva.Address, + Coins: pva.Coins, + PubKey: pva.PubKey, + AccountNumber: pva.AccountNumber, + Sequence: pva.Sequence, + OriginalVesting: pva.OriginalVesting, + DelegatedFree: pva.DelegatedFree, + DelegatedVesting: pva.DelegatedVesting, + EndTime: pva.EndTime, + StartTime: pva.StartTime, + VestingPeriods: pva.VestingPeriods, + } + + return codec.Cdc.MarshalJSON(alias) +} + +// UnmarshalJSON unmarshals raw JSON bytes into a PeriodicVestingAccount. +func (pva *PeriodicVestingAccount) UnmarshalJSON(bz []byte) error { + var alias vestingAccountJSON + if err := codec.Cdc.UnmarshalJSON(bz, &alias); err != nil { + return err + } + + pva.BaseVestingAccount = &BaseVestingAccount{ + BaseAccount: NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence), + OriginalVesting: alias.OriginalVesting, + DelegatedFree: alias.DelegatedFree, + DelegatedVesting: alias.DelegatedVesting, + EndTime: alias.EndTime, + } + pva.StartTime = alias.StartTime + pva.VestingPeriods = alias.VestingPeriods + + return nil +} + +func NewModuleAccount(baseAccount *BaseAccount, name string, permissions ...string) *ModuleAccount { + return &ModuleAccount{ + BaseAccount: baseAccount, + Name: name, + Permissions: permissions, + } +} + +func (ma ModuleAccount) Validate() error { + if err := v038auth.ValidatePermissions(ma.Permissions...); err != nil { + return err + } + + if strings.TrimSpace(ma.Name) == "" { + return errors.New("module account name cannot be blank") + } + + if x := sdk.AccAddress(crypto.AddressHash([]byte(ma.Name))); !ma.Address.Equals(x) { + return fmt.Errorf("address %s cannot be derived from the module name '%s'; expected: %s", ma.Address, ma.Name, x) + } + + return ma.BaseAccount.Validate() +} + +// MarshalJSON returns the JSON representation of a ModuleAccount. +func (ma ModuleAccount) MarshalJSON() ([]byte, error) { + return codec.Cdc.MarshalJSON(moduleAccountPretty{ + Address: ma.Address, + Coins: ma.Coins, + PubKey: "", + AccountNumber: ma.AccountNumber, + Sequence: ma.Sequence, + Name: ma.Name, + Permissions: ma.Permissions, + }) +} + +// UnmarshalJSON unmarshals raw JSON bytes into a ModuleAccount. +func (ma *ModuleAccount) UnmarshalJSON(bz []byte) error { + var alias moduleAccountPretty + if err := codec.Cdc.UnmarshalJSON(bz, &alias); err != nil { + return err + } + + ma.BaseAccount = NewBaseAccount(alias.Address, alias.Coins, nil, alias.AccountNumber, alias.Sequence) + ma.Name = alias.Name + ma.Permissions = alias.Permissions + + return nil +} + +func RegisterCodec(cdc *codec.Codec) { + cdc.RegisterInterface((*v038auth.GenesisAccount)(nil), nil) + cdc.RegisterInterface((*v038auth.Account)(nil), nil) + cdc.RegisterConcrete(&BaseAccount{}, "cosmos-sdk/Account", nil) + cdc.RegisterConcrete(&BaseVestingAccount{}, "cosmos-sdk/BaseVestingAccount", nil) + cdc.RegisterConcrete(&ContinuousVestingAccount{}, "cosmos-sdk/ContinuousVestingAccount", nil) + cdc.RegisterConcrete(&DelayedVestingAccount{}, "cosmos-sdk/DelayedVestingAccount", nil) + cdc.RegisterConcrete(&PeriodicVestingAccount{}, "cosmos-sdk/PeriodicVestingAccount", nil) + cdc.RegisterConcrete(&ModuleAccount{}, "cosmos-sdk/ModuleAccount", nil) +} diff --git a/x/auth/vesting/types/vesting_account.go b/x/auth/vesting/types/vesting_account.go index 256c9d598fec..7964ca2a4544 100644 --- a/x/auth/vesting/types/vesting_account.go +++ b/x/auth/vesting/types/vesting_account.go @@ -1,17 +1,17 @@ package types import ( - "encoding/json" "errors" "time" + "github.com/tendermint/tendermint/crypto" + "gopkg.in/yaml.v2" + + "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" vestexported "github.com/cosmos/cosmos-sdk/x/auth/vesting/exported" - - "github.com/tendermint/tendermint/crypto" - "gopkg.in/yaml.v2" ) // Compile-time type assertions @@ -185,7 +185,7 @@ func (bva BaseVestingAccount) Validate() error { return bva.BaseAccount.Validate() } -type vestingAccountPretty struct { +type vestingAccountYAML struct { Address sdk.AccAddress `json:"address" yaml:"address"` Coins sdk.Coins `json:"coins" yaml:"coins"` PubKey string `json:"public_key" yaml:"public_key"` @@ -201,6 +201,22 @@ type vestingAccountPretty struct { VestingPeriods Periods `json:"vesting_periods,omitempty" yaml:"vesting_periods,omitempty"` } +type vestingAccountJSON struct { + Address sdk.AccAddress `json:"address" yaml:"address"` + Coins sdk.Coins `json:"coins" yaml:"coins"` + PubKey crypto.PubKey `json:"public_key" yaml:"public_key"` + AccountNumber uint64 `json:"account_number" yaml:"account_number"` + Sequence uint64 `json:"sequence" yaml:"sequence"` + 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) @@ -208,7 +224,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, Coins: bva.Coins, AccountNumber: bva.AccountNumber, @@ -219,8 +235,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 } @@ -238,9 +255,10 @@ 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, Coins: bva.Coins, + PubKey: bva.GetPubKey(), AccountNumber: bva.AccountNumber, Sequence: bva.Sequence, OriginalVesting: bva.OriginalVesting, @@ -249,38 +267,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, alias.Coins, pk, alias.AccountNumber, alias.Sequence) + bva.BaseAccount = authtypes.NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence) bva.OriginalVesting = alias.OriginalVesting bva.DelegatedFree = alias.DelegatedFree bva.DelegatedVesting = alias.DelegatedVesting @@ -393,7 +390,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, Coins: cva.Coins, AccountNumber: cva.AccountNumber, @@ -405,8 +402,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 } @@ -424,9 +422,10 @@ 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, Coins: cva.Coins, + PubKey: cva.GetPubKey(), AccountNumber: cva.AccountNumber, Sequence: cva.Sequence, OriginalVesting: cva.OriginalVesting, @@ -436,39 +435,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, alias.Coins, pk, alias.AccountNumber, alias.Sequence), + BaseAccount: authtypes.NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence), OriginalVesting: alias.OriginalVesting, DelegatedFree: alias.DelegatedFree, DelegatedVesting: alias.DelegatedVesting, @@ -608,7 +586,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, Coins: pva.Coins, AccountNumber: pva.AccountNumber, @@ -621,8 +599,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 } @@ -640,9 +619,10 @@ 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, Coins: pva.Coins, + PubKey: pva.GetPubKey(), AccountNumber: pva.AccountNumber, Sequence: pva.Sequence, OriginalVesting: pva.OriginalVesting, @@ -653,39 +633,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, alias.Coins, pk, alias.AccountNumber, alias.Sequence), + BaseAccount: authtypes.NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence), OriginalVesting: alias.OriginalVesting, DelegatedFree: alias.DelegatedFree, DelegatedVesting: alias.DelegatedVesting, @@ -769,9 +728,10 @@ func (dva DelayedVestingAccount) Validate() error { // MarshalJSON returns the JSON representation of a DelayedVestingAccount. func (dva DelayedVestingAccount) MarshalJSON() ([]byte, error) { - alias := vestingAccountPretty{ + alias := vestingAccountJSON{ Address: dva.Address, Coins: dva.Coins, + PubKey: dva.GetPubKey(), AccountNumber: dva.AccountNumber, Sequence: dva.Sequence, OriginalVesting: dva.OriginalVesting, @@ -780,39 +740,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, alias.Coins, pk, alias.AccountNumber, alias.Sequence), + BaseAccount: authtypes.NewBaseAccount(alias.Address, alias.Coins, alias.PubKey, alias.AccountNumber, alias.Sequence), OriginalVesting: alias.OriginalVesting, DelegatedFree: alias.DelegatedFree, DelegatedVesting: alias.DelegatedVesting, diff --git a/x/auth/vesting/types/vesting_account_test.go b/x/auth/vesting/types/vesting_account_test.go index 651416338c06..f349f7202dd5 100644 --- a/x/auth/vesting/types/vesting_account_test.go +++ b/x/auth/vesting/types/vesting_account_test.go @@ -10,6 +10,7 @@ import ( "github.com/tendermint/tendermint/crypto/secp256k1" tmtime "github.com/tendermint/tendermint/types/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" @@ -743,7 +744,7 @@ func TestBaseVestingAccountJSON(t *testing.T) { acc, err := NewBaseVestingAccount(baseAcc, coins, time.Now().Unix()) require.NoError(t, err) - bz, err := json.Marshal(acc) + bz, err := codec.Cdc.MarshalJSON(acc) require.NoError(t, err) bz1, err := acc.MarshalJSON() diff --git a/x/genutil/client/cli/migrate.go b/x/genutil/client/cli/migrate.go index 3ae77c506d61..107d622971b9 100644 --- a/x/genutil/client/cli/migrate.go +++ b/x/genutil/client/cli/migrate.go @@ -16,6 +16,7 @@ import ( extypes "github.com/cosmos/cosmos-sdk/x/genutil" v036 "github.com/cosmos/cosmos-sdk/x/genutil/legacy/v0_36" v038 "github.com/cosmos/cosmos-sdk/x/genutil/legacy/v0_38" + v039 "github.com/cosmos/cosmos-sdk/x/genutil/legacy/v0_39" ) const ( @@ -29,6 +30,7 @@ const ( var migrationMap = extypes.MigrationMap{ "v0.36": v036.Migrate, "v0.38": v038.Migrate, // NOTE: v0.37 and v0.38 are genesis compatible + "v0.39": v039.Migrate, } // GetMigrationCallback returns a MigrationCallback for a given version. @@ -118,7 +120,7 @@ $ %s migrate v0.36 /path/to/genesis.json --chain-id=cosmoshub-3 --genesis-time=2 return errors.Wrap(err, "failed to sort JSON genesis doc") } - fmt.Println(string(sortedBz)) + cmd.Println(string(sortedBz)) return nil }, } diff --git a/x/genutil/client/cli/migrate_test.go b/x/genutil/client/cli/migrate_test.go index d0dbf94a4764..acf307d85071 100644 --- a/x/genutil/client/cli/migrate_test.go +++ b/x/genutil/client/cli/migrate_test.go @@ -1,10 +1,20 @@ -package cli +package cli_test import ( "io/ioutil" + "os" "path" + "path/filepath" "testing" + abci "github.com/tendermint/tendermint/abci/types" + dbm "github.com/tendermint/tm-db" + + "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" + genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" + "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/stretchr/testify/require" @@ -17,6 +27,14 @@ import ( "github.com/cosmos/cosmos-sdk/tests" ) +// custom tx codec +func makeCodec() *codec.Codec { + var cdc = codec.New() + sdk.RegisterCodec(cdc) + codec.RegisterCrypto(cdc) + return cdc +} + func setupCmd(genesisTime string, chainID string) *cobra.Command { c := &cobra.Command{ Use: "c", @@ -24,15 +42,15 @@ func setupCmd(genesisTime string, chainID string) *cobra.Command { Run: func(_ *cobra.Command, args []string) {}, } - c.Flags().String(flagGenesisTime, genesisTime, "") - c.Flags().String(flagChainID, chainID, "") + c.Flags().String("genesis-time", genesisTime, "") + c.Flags().String("chain-id", chainID, "") return c } func TestGetMigrationCallback(t *testing.T) { - for _, version := range GetMigrationVersions() { - require.NotNil(t, GetMigrationCallback(version)) + for _, version := range genutilcli.GetMigrationVersions() { + require.NotNil(t, genutilcli.GetMigrationCallback(version)) } } @@ -52,13 +70,52 @@ func TestMigrateGenesis(t *testing.T) { defer cleanup() // Reject if we dont' have the right parameters or genesis does not exists - require.Error(t, MigrateGenesisCmd(ctx, cdc).RunE(nil, []string{target, genesisPath})) + require.Error(t, genutilcli.MigrateGenesisCmd(ctx, cdc).RunE(nil, []string{target, genesisPath})) // Noop migration with minimal genesis emptyGenesis := []byte(`{"chain_id":"test","app_state":{}}`) err = ioutil.WriteFile(genesisPath, emptyGenesis, 0600) require.Nil(t, err) cmd := setupCmd("", "test2") - require.NoError(t, MigrateGenesisCmd(ctx, cdc).RunE(cmd, []string{target, genesisPath})) + require.NoError(t, genutilcli.MigrateGenesisCmd(ctx, cdc).RunE(cmd, []string{target, genesisPath})) // Every migration function shuold tests its own module separately } + +func TestMigrateCommercioGenesisData(t *testing.T) { + home, cleanup := tests.NewTestCaseDir(t) + t.Cleanup(cleanup) + viper.Set(cli.HomeFlag, home) + viper.Set(flags.FlagName, "moniker") + logger := log.NewNopLogger() + cfg, err := tcmd.ParseConfig() + require.Nil(t, err) + ctx := server.NewContext(cfg, logger) + cdc := makeCodec() + + genesisPath := filepath.Join("testdata", "commercio-genesis.json") + require.NoError(t, err) + target := "v0.39" + + config := sdk.GetConfig() + config.SetBech32PrefixForAccount("did:com:", "did:com:pub") + config.Seal() + + // Migration with minimal genesis + cmd := setupCmd("2020-08-10T09:52:06.576222474Z", "test2") + _, newGenesisStream, _ := tests.ApplyMockIO(cmd) + require.NoError(t, genutilcli.MigrateGenesisCmd(ctx, cdc).RunE(cmd, []string{target, genesisPath})) + + db := dbm.NewMemDB() + app := simapp.NewSimApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, 0) + newGenesisBytes := newGenesisStream.Bytes() + + // Initialize the chain + require.NotPanics(t, func() { + app.InitChain( + abci.RequestInitChain{ + Validators: []abci.ValidatorUpdate{}, + AppStateBytes: newGenesisBytes, + }, + ) + }) +} diff --git a/x/genutil/client/cli/testdata/commercio-genesis.json b/x/genutil/client/cli/testdata/commercio-genesis.json new file mode 100644 index 000000000000..7ceefe9fa22d --- /dev/null +++ b/x/genutil/client/cli/testdata/commercio-genesis.json @@ -0,0 +1,244 @@ +{ + "genesis_time": "2020-08-06T09:52:06.576222474Z", + "chain_id": "testnet", + "consensus_params": { + "block": { + "max_bytes": "22020096", + "max_gas": "-1", + "time_iota_ms": "1000" + }, + "evidence": { + "max_age_num_blocks": "100000", + "max_age_duration": "172800000000000" + }, + "validator": { + "pub_key_types": [ + "ed25519" + ] + } + }, + "app_hash": "", + "app_state": { + "distribution": { + "params": { + "community_tax": "0.020000000000000000", + "base_proposer_reward": "0.010000000000000000", + "bonus_proposer_reward": "0.040000000000000000", + "withdraw_addr_enabled": true + }, + "fee_pool": { + "community_pool": [] + }, + "delegator_withdraw_infos": [], + "previous_proposer": "", + "outstanding_rewards": [], + "validator_accumulated_commissions": [], + "validator_historical_rewards": [], + "validator_current_rewards": [], + "delegator_starting_infos": [], + "validator_slash_events": [] + }, + "pricefeed": { + "oracles": [ + "did:com:1r93fsdxfthckptsz0wush4cx08t8c2fz4jhruw" + ], + "assets": [ + "ucommercio" + ], + "raw_prices": [ + { + "oracle": "did:com:1r93fsdxfthckptsz0wush4cx08t8c2fz4jhruw", + "price": { + "asset_name": "ucommercio", + "value": "1.000000000000000000", + "expiry": "100000000" + }, + "created": "0" + } + ], + "denom_blacklist": [ + "uccc" + ] + }, + "docs": { + "documents": null, + "receipts": null, + "supported_metadata_schemes": null, + "trusted_metadata_schema_proposers": null + }, + "accreditations": { + "liquidity_pool_amount": [], + "invites": null, + "trusted_service_providers": [ + "did:com:1r93fsdxfthckptsz0wush4cx08t8c2fz4jhruw", + "did:com:1zlr8yn5plplvf39zr7laj05e8dm8mqd7ljznhf" + ], + "stable_credits_denom": "uccc", + "memberships": [ + { + "owner": "did:com:1r93fsdxfthckptsz0wush4cx08t8c2fz4jhruw", + "membership_type": "black" + } + ] + }, + "params": null, + "vbr": { + "pool_amount": [ + { + "denom": "ucommercio", + "amount": "12500000000000.000000000000000000" + } + ], + "yearly_pool_amount": null, + "year_number": "0" + }, + "commerciomint": { + "positions": [], + "pool_amount": [], + "credits_denom": "uccc", + "collateral_rate": "2.000000000000000000" + }, + "slashing": { + "params": { + "signed_blocks_window": "100", + "min_signed_per_window": "0.500000000000000000", + "downtime_jail_duration": "600000000000", + "slash_fraction_double_sign": "0.050000000000000000", + "slash_fraction_downtime": "0.010000000000000000" + }, + "signing_infos": {}, + "missed_blocks": {} + }, + "creditrisk": { + "pool": [] + }, + "bank": { + "send_enabled": true, + "blocked_accounts": [] + }, + "id": { + "did_documents": null, + "power_up_requests": null + }, + "crisis": { + "constant_fee": { + "denom": "ucommercio", + "amount": "1000" + } + }, + "staking": { + "params": { + "unbonding_time": "1814400000000000", + "max_validators": 100, + "max_entries": 7, + "historical_entries": 0, + "bond_denom": "ucommercio" + }, + "last_total_power": "0", + "last_validator_powers": null, + "validators": null, + "delegations": null, + "unbonding_delegations": null, + "redelegations": null, + "exported": false + }, + "government": { + "government_address": "did:com:1r93fsdxfthckptsz0wush4cx08t8c2fz4jhruw", + "tumbler_address": "did:com:1ej6229ezfdn443ry72l964nle6ra0sc5sstyy3" + }, + "supply": { + "supply": [] + }, + "genutil": { + "gentxs": [ + { + "type": "cosmos-sdk/StdTx", + "value": { + "msg": [ + { + "type": "cosmos-sdk/MsgCreateValidator", + "value": { + "description": { + "moniker": "testchain", + "identity": "", + "website": "", + "security_contact": "", + "details": "" + }, + "commission": { + "rate": "0.100000000000000000", + "max_rate": "0.200000000000000000", + "max_change_rate": "0.010000000000000000" + }, + "min_self_delegation": "1", + "delegator_address": "did:com:1r93fsdxfthckptsz0wush4cx08t8c2fz4jhruw", + "validator_address": "did:com:valoper1r93fsdxfthckptsz0wush4cx08t8c2fzk3w93a", + "pubkey": "did:com:valconspub1zcjduepqt3k7lh6qledmay447gnfl3ns4ejjwrzqk9n6ydcmr5clka5yvjlsdhcpag", + "value": { + "denom": "ucommercio", + "amount": "100000000" + } + } + } + ], + "fee": { + "amount": [], + "gas": "200000" + }, + "signatures": [ + { + "pub_key": { + "type": "tendermint/PubKeySecp256k1", + "value": "A0ZymN/QXBkfyxQJjfxvjReNhZjHjdaKjBqmAs945S4f" + }, + "signature": "oqLK+EycP7E5Ikaacltz5WI8eg1mJQOKUNEKQa6AQIlqBN9oYX4BKlMXSNfbu8Y3JlUNTDYNfOJKA2oSw6nssw==" + } + ], + "memo": "e5ecfe387a5210f0e6798f63d37802db26a19868@192.168.1.6:26656" + } + } + ] + }, + "auth": { + "params": { + "max_memo_characters": "256", + "tx_sig_limit": "7", + "tx_size_cost_per_byte": "10", + "sig_verify_cost_ed25519": "590", + "sig_verify_cost_secp256k1": "1000" + }, + "accounts": [ + { + "type": "cosmos-sdk/Account", + "value": { + "address": "did:com:1r93fsdxfthckptsz0wush4cx08t8c2fz4jhruw", + "coins": [ + { + "denom": "ucommercio", + "amount": "10000000000000" + } + ], + "public_key": "", + "account_number": 0, + "sequence": 0 + } + }, + { + "type": "cosmos-sdk/Account", + "value": { + "address": "did:com:1zlr8yn5plplvf39zr7laj05e8dm8mqd7ljznhf", + "coins": [ + { + "denom": "uccc", + "amount": "10000000000" + } + ], + "public_key": "", + "account_number": 0, + "sequence": 0 + } + } + ] + } + } +} \ No newline at end of file diff --git a/x/genutil/legacy/v0_38/migrate.go b/x/genutil/legacy/v0_38/migrate.go index 59ba4772705f..ae22212c3d14 100644 --- a/x/genutil/legacy/v0_38/migrate.go +++ b/x/genutil/legacy/v0_38/migrate.go @@ -7,13 +7,13 @@ import ( v036distr "github.com/cosmos/cosmos-sdk/x/distribution/legacy/v0_36" v038distr "github.com/cosmos/cosmos-sdk/x/distribution/legacy/v0_38" v036genaccounts "github.com/cosmos/cosmos-sdk/x/genaccounts/legacy/v0_36" - "github.com/cosmos/cosmos-sdk/x/genutil" + "github.com/cosmos/cosmos-sdk/x/genutil/types" v036staking "github.com/cosmos/cosmos-sdk/x/staking/legacy/v0_36" v038staking "github.com/cosmos/cosmos-sdk/x/staking/legacy/v0_38" ) // Migrate migrates exported state from v0.36/v0.37 to a v0.38 genesis state. -func Migrate(appState genutil.AppMap) genutil.AppMap { +func Migrate(appState types.AppMap) types.AppMap { v036Codec := codec.New() codec.RegisterCrypto(v036Codec) @@ -34,9 +34,7 @@ func Migrate(appState genutil.AppMap) genutil.AppMap { // Migrate relative source genesis application state and marshal it into // the respective key. - appState[v038auth.ModuleName] = v038Codec.MustMarshalJSON( - v038auth.Migrate(authGenState, genAccountsGenState), - ) + appState[v038auth.ModuleName] = v038Codec.MustMarshalJSON(v038auth.Migrate(authGenState, genAccountsGenState)) } // migrate staking state diff --git a/x/genutil/legacy/v0_38/migrate_test.go b/x/genutil/legacy/v0_38/migrate_test.go index 66ea18e2fc5d..d0c5e8293c2a 100644 --- a/x/genutil/legacy/v0_38/migrate_test.go +++ b/x/genutil/legacy/v0_38/migrate_test.go @@ -5,8 +5,8 @@ import ( v036auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v0_36" v036genaccounts "github.com/cosmos/cosmos-sdk/x/genaccounts/legacy/v0_36" - "github.com/cosmos/cosmos-sdk/x/genutil" v038 "github.com/cosmos/cosmos-sdk/x/genutil/legacy/v0_38" + "github.com/cosmos/cosmos-sdk/x/genutil/types" v036staking "github.com/cosmos/cosmos-sdk/x/staking/legacy/v0_36" "github.com/stretchr/testify/require" @@ -132,7 +132,7 @@ var genStakingState = []byte(`{ }`) func TestMigrate(t *testing.T) { - genesis := genutil.AppMap{ + genesis := types.AppMap{ v036auth.ModuleName: genAuthState, v036genaccounts.ModuleName: genAccountsState, v036staking.ModuleName: genStakingState, diff --git a/x/genutil/legacy/v0_39/migrate.go b/x/genutil/legacy/v0_39/migrate.go new file mode 100644 index 000000000000..6e614cc5a4af --- /dev/null +++ b/x/genutil/legacy/v0_39/migrate.go @@ -0,0 +1,33 @@ +package v039 + +import ( + "github.com/cosmos/cosmos-sdk/codec" + v038auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v0_38" + v039auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v0_39" + "github.com/cosmos/cosmos-sdk/x/genutil/types" +) + +// Migrate migrates exported state from v0.38 to a v0.39 genesis state. +// +// NOTE: No actual migration occurs since the types do not change, but JSON +// serialization of accounts do change. +func Migrate(appState types.AppMap) types.AppMap { + v038Codec := codec.New() + codec.RegisterCrypto(v038Codec) + v038auth.RegisterCodec(v038Codec) + + v039Codec := codec.New() + codec.RegisterCrypto(v039Codec) + v039auth.RegisterCodec(v039Codec) + + // migrate x/auth state (JSON serialization only) + if appState[v038auth.ModuleName] != nil { + var authGenState v038auth.GenesisState + v038Codec.MustUnmarshalJSON(appState[v038auth.ModuleName], &authGenState) + + delete(appState, v038auth.ModuleName) // delete old key in case the name changed + appState[v039auth.ModuleName] = v039Codec.MustMarshalJSON(v039auth.Migrate(authGenState)) + } + + return appState +} diff --git a/x/genutil/legacy/v0_39/migrate_test.go b/x/genutil/legacy/v0_39/migrate_test.go new file mode 100644 index 000000000000..c50434aeadc1 --- /dev/null +++ b/x/genutil/legacy/v0_39/migrate_test.go @@ -0,0 +1,120 @@ +package v039_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + + v038auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v0_38" + v039auth "github.com/cosmos/cosmos-sdk/x/auth/legacy/v0_39" + v039 "github.com/cosmos/cosmos-sdk/x/genutil/legacy/v0_39" + "github.com/cosmos/cosmos-sdk/x/genutil/types" +) + +var genAuthState = []byte(`{ + "params": { + "max_memo_characters": "10", + "tx_sig_limit": "10", + "tx_size_cost_per_byte": "10", + "sig_verify_cost_ed25519": "10", + "sig_verify_cost_secp256k1": "10" + }, + "accounts": [ + { + "type": "cosmos-sdk/Account", + "value": { + "address": "cosmos19hz3ee9e3lj9mne4jggj3v8hxjrpre22jukj9y", + "coins": [ + { + "denom": "stake", + "amount": "400000" + } + ], + "public_key": "cosmospub1addwnpepqtezq4ajkevh724ls45zp72x70rj8mhszqf5pxcaahazm8trv490swlf404", + "account_number": 1, + "sequence": 1 + } + }, + { + "type": "cosmos-sdk/ModuleAccount", + "value": { + "address": "cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh", + "coins": [ + { + "denom": "stake", + "amount": "400000000" + } + ], + "public_key": "", + "account_number": 2, + "sequence": 4, + "name": "bonded_tokens_pool", + "permissions": [ + "burner", + "staking" + ] + } + }, + { + "type": "cosmos-sdk/ContinuousVestingAccount", + "value": { + "address": "cosmos1vtzxzyjv506dvhl9pa527xsugf5gez4fnqxq0n", + "coins": [ + { + "denom": "stake", + "amount": "10000205" + } + ], + "public_key": "cosmospub1addwnpepqdxrk48q89xlmnzrr5nkssle05tkp73uknevzaavm53c02v26vlyzz6vcdh", + "account_number": 3, + "sequence": 5, + "original_vesting": [ + { + "denom": "stake", + "amount": "10000205" + } + ], + "delegated_free": [], + "delegated_vesting": [], + "end_time": 1596125048, + "start_time": 1595952248 + } + }, + { + "type": "cosmos-sdk/DelayedVestingAccount", + "value": { + "address": "cosmos1prxkcqclweqa0g28p7vmf6z78ghyeckm4qak30", + "coins": [ + { + "denom": "stake", + "amount": "10000205" + } + ], + "public_key": "cosmospub1addwnpepqwewcad349e2yw3weatf8lzfyv5cd6am9jkk4ajach3f568k6gg47nls3p8", + "account_number": 4, + "sequence": 15, + "original_vesting": [ + { + "denom": "stake", + "amount": "10000205" + } + ], + "delegated_free": [], + "delegated_vesting": [], + "end_time": 1596125048 + } + } + ] +}`) + +var expectedGenAuthState = []byte(`{"params":{"max_memo_characters":"10","tx_sig_limit":"10","tx_size_cost_per_byte":"10","sig_verify_cost_ed25519":"10","sig_verify_cost_secp256k1":"10"},"accounts":[{"type":"cosmos-sdk/Account","value":{"address":"cosmos19hz3ee9e3lj9mne4jggj3v8hxjrpre22jukj9y","coins":[{"denom":"stake","amount":"400000"}],"public_key":{"type":"tendermint/PubKeySecp256k1","value":"AvIgV7K2WX8qv4VoIPlG88cj7vAQE0CbHe36LZ1jZUr4"},"account_number":"1","sequence":"1"}},{"type":"cosmos-sdk/ModuleAccount","value":{"address":"cosmos1fl48vsnmsdzcv85q5d2q4z5ajdha8yu34mf0eh","coins":[{"denom":"stake","amount":"400000000"}],"public_key":"","account_number":"2","sequence":"4","name":"bonded_tokens_pool","permissions":["burner","staking"]}},{"type":"cosmos-sdk/ContinuousVestingAccount","value":{"address":"cosmos1vtzxzyjv506dvhl9pa527xsugf5gez4fnqxq0n","coins":[{"denom":"stake","amount":"10000205"}],"public_key":{"type":"tendermint/PubKeySecp256k1","value":"A0w7VOA5Tf3MQx0naEP5fRdg+jy08sF3rN0jh6mK0z5B"},"account_number":"3","sequence":"5","original_vesting":[{"denom":"stake","amount":"10000205"}],"delegated_free":[],"delegated_vesting":[],"end_time":"1596125048","start_time":"1595952248"}},{"type":"cosmos-sdk/DelayedVestingAccount","value":{"address":"cosmos1prxkcqclweqa0g28p7vmf6z78ghyeckm4qak30","coins":[{"denom":"stake","amount":"10000205"}],"public_key":{"type":"tendermint/PubKeySecp256k1","value":"A7LsdbGpcqI6Ls9Wk/xJIymG67ssrWr2XcXimmj20hFf"},"account_number":"4","sequence":"15","original_vesting":[{"denom":"stake","amount":"10000205"}],"delegated_free":[],"delegated_vesting":[],"end_time":"1596125048"}}]}`) + +func TestMigrate(t *testing.T) { + genesis := types.AppMap{ + v038auth.ModuleName: genAuthState, + } + + var migrated types.AppMap + require.NotPanics(t, func() { migrated = v039.Migrate(genesis) }) + require.Equal(t, string(expectedGenAuthState), string(migrated[v039auth.ModuleName])) +} diff --git a/x/supply/internal/types/account.go b/x/supply/internal/types/account.go index ac2136ec6910..b49b38890dfc 100644 --- a/x/supply/internal/types/account.go +++ b/x/supply/internal/types/account.go @@ -1,7 +1,6 @@ package types import ( - "encoding/json" "errors" "fmt" "strings" @@ -10,6 +9,7 @@ import ( "github.com/tendermint/tendermint/crypto" + "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" @@ -150,7 +150,7 @@ func (ma ModuleAccount) MarshalYAML() (interface{}, error) { // MarshalJSON returns the JSON representation of a ModuleAccount. func (ma ModuleAccount) MarshalJSON() ([]byte, error) { - return json.Marshal(moduleAccountPretty{ + return codec.Cdc.MarshalJSON(moduleAccountPretty{ Address: ma.Address, Coins: ma.Coins, PubKey: "", @@ -164,7 +164,7 @@ func (ma ModuleAccount) MarshalJSON() ([]byte, error) { // UnmarshalJSON unmarshals raw JSON bytes into a ModuleAccount. func (ma *ModuleAccount) UnmarshalJSON(bz []byte) error { var alias moduleAccountPretty - if err := json.Unmarshal(bz, &alias); err != nil { + if err := codec.Cdc.UnmarshalJSON(bz, &alias); err != nil { return err }