Merge PR #5533: Protobuf: x/auth & x/supply

This commit is contained in:
Alexander Bezobchuk 2020-02-18 13:50:13 +01:00 committed by GitHub
parent c0a4222e6b
commit 794a496892
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
108 changed files with 5235 additions and 1013 deletions

View File

@ -57,6 +57,8 @@ 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.
### Bug Fixes
@ -72,7 +74,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 +82,7 @@ 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/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 +91,21 @@ 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.
### Improvements

2
go.mod
View File

@ -16,7 +16,7 @@ require (
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/jwalterweatherman v1.1.0 // indirect

7
go.sum
View File

@ -91,7 +91,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=
@ -196,8 +195,8 @@ 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=
@ -253,7 +252,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 +339,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"
@ -78,7 +79,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 +124,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 +150,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,23 +163,23 @@ 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(),
)
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,
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(
@ -305,7 +305,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
}

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

@ -0,0 +1,128 @@
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/supply"
"github.com/cosmos/cosmos-sdk/x/supply/exported"
)
var (
_ auth.Codec = (*Codec)(nil)
_ supply.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 exported.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) (exported.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 exported.SupplyI) ([]byte, error) {
return c.Marshaler.MarshalJSON(supply)
}
// UnmarshalSupplyJSON returns a SupplyI from JSON encoded bytes.
func (c *Codec) UnmarshalSupplyJSON(bz []byte) (exported.SupplyI, error) {
supply := &Supply{}
if err := c.Marshaler.UnmarshalJSON(bz, supply); err != nil {
return nil, err
}
return supply.GetSupplyI(), nil
}
// ----------------------------------------------------------------------------
// 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(bm module.BasicManager) *codec.Codec {
cdc := codec.New()
bm.RegisterCodec(cdc)
vesting.RegisterCodec(cdc)
sdk.RegisterCodec(cdc)
codec.RegisterCrypto(cdc)
return cdc
}

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

File diff suppressed because it is too large Load Diff

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

@ -0,0 +1,33 @@
syntax = "proto3";
package cosmos_sdk.simapp.codec.v1;
import "third_party/proto/cosmos-proto/cosmos.proto";
import "x/auth/types/types.proto";
import "x/auth/vesting/types/types.proto";
import "x/supply/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 (cosmos_proto.interface_type) = "*github.com/cosmos/cosmos-sdk/x/supply/exported.SupplyI";
// sum defines a list of all acceptable concrete Supply implementations.
oneof sum {
cosmos_sdk.x.supply.v1.Supply supply = 1;
}
}

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

@ -137,7 +137,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")

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

@ -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,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,10 +3,10 @@ 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"
@ -17,23 +17,18 @@ import (
// 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 subspace.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 subspace.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,7 +2,6 @@ package types
import (
"bytes"
"encoding/json"
"errors"
"github.com/tendermint/tendermint/crypto"
@ -12,28 +11,19 @@ import (
"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 {
var pkStr string
if pubKey != nil {
pkStr = sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pubKey)
}
return &BaseAccount{
Address: address,
PubKey: pubKey,
PubKey: pkStr,
AccountNumber: accountNumber,
Sequence: sequence,
}
@ -45,8 +35,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 +51,33 @@ 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
if acc.PubKey == "" {
return nil
}
return sdk.MustGetPubKeyFromBech32(sdk.Bech32PubKeyTypeAccPub, acc.PubKey)
}
// SetPubKey - Implements sdk.Account.
func (acc *BaseAccount) SetPubKey(pubKey crypto.PubKey) error {
acc.PubKey = pubKey
pkStr, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pubKey)
if err != nil {
return err
}
acc.PubKey = pkStr
return nil
}
// GetAccountNumber - Implements Account
func (acc *BaseAccount) GetAccountNumber() uint64 {
func (acc BaseAccount) GetAccountNumber() uint64 {
return acc.AccountNumber
}
@ -88,7 +88,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,90 +100,15 @@ 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()) {
if acc.PubKey != "" && acc.Address != nil &&
!bytes.Equal(acc.GetPubKey().Address().Bytes(), acc.Address.Bytes()) {
return errors.New("pubkey and address pair is invalid")
}
return nil
}
type baseAccountPretty struct {
Address sdk.AccAddress `json:"address" yaml:"address"`
PubKey string `json:"public_key" yaml:"public_key"`
AccountNumber uint64 `json:"account_number" yaml:"account_number"`
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{
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
}
bz, err := yaml.Marshal(alias)
if err != nil {
return nil, err
}
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
out, _ := yaml.Marshal(acc)
return string(out)
}

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,22 +38,22 @@ 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 {
acc, err := ar.codec.UnmarshalAccountJSON(bz)
if err != nil {
return nil, height, err
}
return account, height, nil
return acc, height, nil
}
// EnsureExists returns an error if no account exists for the given address else nil.

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,21 @@
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 +39,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 +56,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,28 +66,23 @@ 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
@ -103,39 +95,17 @@ func TestGenesisAccountValidate(t *testing.T) {
},
{
"invalid base valid account",
NewBaseAccount(addr, secp256k1.GenPrivKey().PubKey(), 0, 0),
types.NewBaseAccount(addr, secp256k1.GenPrivKey().PubKey(), 0, 0),
errors.New("pubkey and address pair is invalid"),
},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
err := tt.acc.Validate()
require.Equal(t, tt.expErr, err)
})
}
}
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

@ -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"
)
// DefaultParamspace defines the default auth module parameter subspace
@ -32,18 +31,10 @@ var (
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"`
}
// 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,
@ -72,13 +63,6 @@ func (p *Params) ParamSetPairs() subspace.ParamSetPairs {
}
}
// 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)
}

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

File diff suppressed because it is too large Load Diff

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

@ -0,0 +1,49 @@
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"];
string 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 {
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

@ -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
@ -204,6 +188,7 @@ func (bva BaseVestingAccount) String() string {
func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {
alias := vestingAccountPretty{
Address: bva.Address,
PubKey: bva.PubKey,
AccountNumber: bva.AccountNumber,
Sequence: bva.Sequence,
OriginalVesting: bva.OriginalVesting,
@ -212,15 +197,6 @@ func (bva BaseVestingAccount) MarshalYAML() (interface{}, 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
}
bz, err := yaml.Marshal(alias)
if err != nil {
return nil, err
@ -233,6 +209,7 @@ func (bva BaseVestingAccount) MarshalYAML() (interface{}, error) {
func (bva BaseVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountPretty{
Address: bva.Address,
PubKey: bva.PubKey,
AccountNumber: bva.AccountNumber,
Sequence: bva.Sequence,
OriginalVesting: bva.OriginalVesting,
@ -241,15 +218,6 @@ 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)
}
@ -287,14 +255,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{
@ -386,6 +346,7 @@ func (cva ContinuousVestingAccount) String() string {
func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {
alias := vestingAccountPretty{
Address: cva.Address,
PubKey: cva.PubKey,
AccountNumber: cva.AccountNumber,
Sequence: cva.Sequence,
OriginalVesting: cva.OriginalVesting,
@ -395,15 +356,6 @@ func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, 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
}
bz, err := yaml.Marshal(alias)
if err != nil {
return nil, err
@ -416,6 +368,7 @@ func (cva ContinuousVestingAccount) MarshalYAML() (interface{}, error) {
func (cva ContinuousVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountPretty{
Address: cva.Address,
PubKey: cva.PubKey,
AccountNumber: cva.AccountNumber,
Sequence: cva.Sequence,
OriginalVesting: cva.OriginalVesting,
@ -425,15 +378,6 @@ 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)
}
@ -474,14 +418,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{
@ -602,6 +538,7 @@ func (pva PeriodicVestingAccount) String() string {
func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {
alias := vestingAccountPretty{
Address: pva.Address,
PubKey: pva.PubKey,
AccountNumber: pva.AccountNumber,
Sequence: pva.Sequence,
OriginalVesting: pva.OriginalVesting,
@ -612,15 +549,6 @@ func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, 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
}
bz, err := yaml.Marshal(alias)
if err != nil {
return nil, err
@ -633,6 +561,7 @@ func (pva PeriodicVestingAccount) MarshalYAML() (interface{}, error) {
func (pva PeriodicVestingAccount) MarshalJSON() ([]byte, error) {
alias := vestingAccountPretty{
Address: pva.Address,
PubKey: pva.PubKey,
AccountNumber: pva.AccountNumber,
Sequence: pva.Sequence,
OriginalVesting: pva.OriginalVesting,
@ -643,15 +572,6 @@ 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)
}
@ -693,13 +613,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 +669,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{
Address: dva.Address,
PubKey: dva.PubKey,
AccountNumber: dva.AccountNumber,
Sequence: dva.Sequence,
OriginalVesting: dva.OriginalVesting,
@ -768,15 +687,6 @@ 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)
}

View File

@ -1,4 +1,4 @@
package types
package types_test
import (
"encoding/json"
@ -13,6 +13,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 +25,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 +51,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 +73,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 +101,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 +128,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 +140,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 +160,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 +169,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 +188,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 +206,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 +224,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 +261,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 +298,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 +326,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 +345,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 +390,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 +430,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 +465,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 +512,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 +523,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 +549,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 +565,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,42 +580,12 @@ 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
@ -637,31 +608,31 @@ func TestGenesisAccountValidate(t *testing.T) {
},
{
"valid continuous vesting account",
NewContinuousVestingAccount(baseAcc, initialVesting, 100, 200),
types.NewContinuousVestingAccount(baseAcc, initialVesting, 100, 200),
nil,
},
{
"invalid vesting times",
NewContinuousVestingAccount(baseAcc, initialVesting, 1654668078, 1554668078),
types.NewContinuousVestingAccount(baseAcc, initialVesting, 1654668078, 1554668078),
errors.New("vesting start-time cannot be before end-time"),
},
{
"valid periodic vesting account",
NewPeriodicVestingAccount(baseAcc, initialVesting, 0, Periods{Period{Length: int64(100), Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)}}}),
types.NewPeriodicVestingAccount(baseAcc, initialVesting, 0, types.Periods{types.Period{Length: int64(100), Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)}}}),
nil,
},
{
"invalid vesting period lengths",
NewPeriodicVestingAccountRaw(
types.NewPeriodicVestingAccountRaw(
baseVestingWithCoins,
0, Periods{Period{Length: int64(50), Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 50)}}}),
0, types.Periods{types.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"),
},
{
"invalid vesting period amounts",
NewPeriodicVestingAccountRaw(
types.NewPeriodicVestingAccountRaw(
baseVestingWithCoins,
0, Periods{Period{Length: int64(100), Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 25)}}}),
0, types.Periods{types.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"),
},
}
@ -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

@ -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

@ -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

@ -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

@ -4,32 +4,26 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
)
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 NewCodec(amino *codec.Codec) *Codec {
return &Codec{Marshaler: codec.NewHybridCodec(amino), amino: amino}
}
// ----------------------------------------------------------------------------
// RegisterCodec registers all the necessary crisis module concrete types and
// interfaces with the provided codec reference.
// RegisterCodec registers the necessary x/crisis interfaces and concrete types
// on the provided Amino codec. These types are used for Amino JSON serialization.
func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(MsgVerifyInvariant{}, "cosmos-sdk/MsgVerifyInvariant", nil)
}
// ModuleCdc defines a crisis module global Amino codec.
var ModuleCdc *Codec
var (
amino = codec.New()
// ModuleCdc references the global x/crisis 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/crisis and
// defined at the application level.
ModuleCdc = codec.NewHybridCodec(amino)
)
func init() {
ModuleCdc = NewCodec(codec.New())
RegisterCodec(ModuleCdc.amino)
codec.RegisterCrypto(ModuleCdc.amino)
ModuleCdc.amino.Seal()
RegisterCodec(amino)
codec.RegisterCrypto(amino)
amino.Seal()
}

View File

@ -38,14 +38,14 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {
// DefaultGenesis returns default genesis state as raw bytes for the crisis
// module.
func (AppModuleBasic) DefaultGenesis() json.RawMessage {
return types.ModuleCdc.MustMarshalJSON(DefaultGenesisState())
func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage {
return cdc.MustMarshalJSON(DefaultGenesisState())
}
// ValidateGenesis performs genesis state validation for the crisis 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", ModuleName, err)
}
@ -109,9 +109,9 @@ func (AppModule) NewQuerierHandler() sdk.Querier { return nil }
// InitGenesis performs genesis initialization for the crisis 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.keeper, genesisState)
am.keeper.AssertInvariants(ctx)
@ -120,9 +120,9 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va
// ExportGenesis returns the exported genesis state as raw bytes for the crisis
// 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 types.ModuleCdc.MustMarshalJSON(gs)
return cdc.MustMarshalJSON(gs)
}
// BeginBlock performs a no-op.

View File

@ -111,7 +111,6 @@ var (
ParamStoreKeyBonusProposerReward = types.ParamStoreKeyBonusProposerReward
ParamStoreKeyWithdrawAddrEnabled = types.ParamStoreKeyWithdrawAddrEnabled
ModuleCdc = types.ModuleCdc
NewCodec = types.NewCodec
EventTypeSetWithdrawAddress = types.EventTypeSetWithdrawAddress
EventTypeRewards = types.EventTypeRewards
EventTypeCommission = types.EventTypeCommission
@ -156,5 +155,4 @@ type (
ValidatorSlashEvent = types.ValidatorSlashEvent
ValidatorSlashEvents = types.ValidatorSlashEvents
ValidatorOutstandingRewards = types.ValidatorOutstandingRewards
Codec = types.Codec
)

View File

@ -12,15 +12,15 @@ import (
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/codec"
simappcodec "github.com/cosmos/cosmos-sdk/simapp/codec"
"github.com/cosmos/cosmos-sdk/store"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/bank"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/cosmos/cosmos-sdk/x/params"
"github.com/cosmos/cosmos-sdk/x/staking"
"github.com/cosmos/cosmos-sdk/x/supply"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
)
//nolint:deadcode,unused
@ -126,10 +126,11 @@ func CreateTestInputAdvanced(
blacklistedAddrs[distrAcc.GetAddress().String()] = true
cdc := MakeTestCodec()
appCodec := simappcodec.NewAppCodec(cdc)
pk := params.NewKeeper(params.ModuleCdc, keyParams, tkeyParams)
ctx := sdk.NewContext(ms, abci.Header{ChainID: "foochainid"}, isCheckTx, log.NewNopLogger())
accountKeeper := auth.NewAccountKeeper(cdc, keyAcc, pk.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount)
accountKeeper := auth.NewAccountKeeper(appCodec, keyAcc, pk.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount)
bankKeeper := bank.NewBaseKeeper(cdc, keyBank, accountKeeper, pk.Subspace(bank.DefaultParamspace), blacklistedAddrs)
maccPerms := map[string][]string{
auth.FeeCollectorName: nil,
@ -137,7 +138,7 @@ func CreateTestInputAdvanced(
staking.NotBondedPoolName: {supply.Burner, supply.Staking},
staking.BondedPoolName: {supply.Burner, supply.Staking},
}
supplyKeeper := supply.NewKeeper(cdc, keySupply, accountKeeper, bankKeeper, maccPerms)
supplyKeeper := supply.NewKeeper(appCodec, keySupply, accountKeeper, bankKeeper, maccPerms)
sk := staking.NewKeeper(staking.ModuleCdc, keyStaking, bankKeeper, supplyKeeper, pk.Subspace(staking.DefaultParamspace))
sk.SetParams(ctx, staking.DefaultParams())

View File

@ -43,14 +43,14 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {
// DefaultGenesis returns default genesis state as raw bytes for the distribution
// 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 distribution 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)
}
@ -132,18 +132,18 @@ func (am AppModule) NewQuerierHandler() sdk.Querier {
// InitGenesis performs genesis initialization for the distribution 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.bankKeeper, am.supplyKeeper, am.keeper, genesisState)
return []abci.ValidatorUpdate{}
}
// ExportGenesis returns the exported genesis state as raw bytes for the distribution
// 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 returns the begin blocker for the distribution module.

View File

@ -4,22 +4,8 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
)
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 NewCodec(amino *codec.Codec) *Codec {
return &Codec{Marshaler: codec.NewHybridCodec(amino), amino: amino}
}
// ----------------------------------------------------------------------------
// RegisterCodec registers all the necessary crisis module concrete types and
// interfaces with the provided codec reference.
// RegisterCodec registers the necessary x/distribution interfaces and concrete types
// on the provided Amino codec. These types are used for Amino JSON serialization.
func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(MsgWithdrawDelegatorReward{}, "cosmos-sdk/MsgWithdrawDelegationReward", nil)
cdc.RegisterConcrete(MsgWithdrawValidatorCommission{}, "cosmos-sdk/MsgWithdrawValidatorCommission", nil)
@ -27,12 +13,20 @@ func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(CommunityPoolSpendProposal{}, "cosmos-sdk/CommunityPoolSpendProposal", nil)
}
// generic sealed codec to be used throughout module
var ModuleCdc *Codec
var (
amino = codec.New()
// ModuleCdc references the global x/distribution 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/distribution and
// defined at the application level.
ModuleCdc = codec.NewHybridCodec(amino)
)
func init() {
ModuleCdc = NewCodec(codec.New())
RegisterCodec(ModuleCdc.amino)
codec.RegisterCrypto(ModuleCdc.amino)
ModuleCdc.amino.Seal()
RegisterCodec(amino)
codec.RegisterCrypto(amino)
amino.Seal()
}

View File

@ -51,14 +51,14 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {
}
// DefaultGenesis returns the evidence module's default genesis state.
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 evidence module.
func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error {
func (AppModuleBasic) ValidateGenesis(cdc codec.JSONMarshaler, bz json.RawMessage) error {
var gs GenesisState
if err := ModuleCdc.UnmarshalJSON(bz, &gs); err != nil {
if err := cdc.UnmarshalJSON(bz, &gs); err != nil {
return fmt.Errorf("failed to unmarshal %s genesis state: %w", ModuleName, err)
}
@ -140,9 +140,9 @@ func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) {}
// InitGenesis performs the evidence module's genesis initialization It returns
// no validator updates.
func (am AppModule) InitGenesis(ctx sdk.Context, bz json.RawMessage) []abci.ValidatorUpdate {
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, bz json.RawMessage) []abci.ValidatorUpdate {
var gs GenesisState
err := ModuleCdc.UnmarshalJSON(bz, &gs)
err := cdc.UnmarshalJSON(bz, &gs)
if err != nil {
panic(fmt.Sprintf("failed to unmarshal %s genesis state: %s", ModuleName, err))
}
@ -152,8 +152,8 @@ func (am AppModule) InitGenesis(ctx sdk.Context, bz json.RawMessage) []abci.Vali
}
// ExportGenesis returns the evidence module's exported genesis state as raw JSON bytes.
func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage {
return ModuleCdc.MustMarshalJSON(ExportGenesis(ctx, am.keeper))
func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage {
return cdc.MustMarshalJSON(ExportGenesis(ctx, am.keeper))
}
// BeginBlock executes all ABCI BeginBlock logic respective to the evidence module.

View File

@ -88,7 +88,7 @@ func GenTxCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicManager, sm
return errors.Wrap(err, "failed to unmarshal genesis state")
}
if err = mbm.ValidateGenesis(genesisState); err != nil {
if err = mbm.ValidateGenesis(cdc, genesisState); err != nil {
return errors.Wrap(err, "failed to validate genesis state")
}

View File

@ -87,7 +87,7 @@ func InitCmd(ctx *server.Context, cdc codec.JSONMarshaler, mbm module.BasicManag
if !viper.GetBool(flagOverwrite) && tmos.FileExists(genFile) {
return fmt.Errorf("genesis.json file already exists: %v", genFile)
}
appState, err := codec.MarshalJSONIndent(cdc, mbm.DefaultGenesis())
appState, err := codec.MarshalJSONIndent(cdc, mbm.DefaultGenesis(cdc))
if err != nil {
return errors.Wrap(err, "Failed to marshall default genesis state")
}

View File

@ -41,7 +41,7 @@ func ValidateGenesisCmd(ctx *server.Context, cdc *codec.Codec, mbm module.BasicM
return fmt.Errorf("error unmarshalling genesis doc %s: %s", genesis, err.Error())
}
if err = mbm.ValidateGenesis(genState); err != nil {
if err = mbm.ValidateGenesis(cdc, genState); err != nil {
return fmt.Errorf("error validating genesis file %s: %s", genesis, err.Error())
}

View File

@ -34,14 +34,14 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {}
// DefaultGenesis returns default genesis state as raw bytes for the genutil
// module.
func (AppModuleBasic) DefaultGenesis() json.RawMessage {
return ModuleCdc.MustMarshalJSON(types.DefaultGenesisState())
func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage {
return cdc.MustMarshalJSON(types.DefaultGenesisState())
}
// ValidateGenesis performs genesis state validation for the genutil 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)
}
@ -82,14 +82,14 @@ func NewAppModule(accountKeeper types.AccountKeeper,
// InitGenesis performs genesis initialization for the genutil 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)
return InitGenesis(ctx, ModuleCdc, am.stakingKeeper, am.deliverTx, genesisState)
}
// ExportGenesis returns the exported genesis state as raw bytes for the genutil
// module.
func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage {
func (am AppModule) ExportGenesis(_ sdk.Context, _ codec.JSONMarshaler) json.RawMessage {
return nil
}

View File

@ -52,19 +52,19 @@ func TestImportExportQueues(t *testing.T) {
// export the state and import it into a new app
govGenState := gov.ExportGenesis(ctx, app.GovKeeper)
db := dbm.NewMemDB()
app2 := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, 0)
genesisState := simapp.NewDefaultGenesisState()
genesisState[auth.ModuleName] = app.Codec().MustMarshalJSON(authGenState)
genesisState[gov.ModuleName] = app.Codec().MustMarshalJSON(govGenState)
stateBytes, err := codec.MarshalJSONIndent(app2.Codec(), genesisState)
stateBytes, err := codec.MarshalJSONIndent(app.Codec(), genesisState)
if err != nil {
panic(err)
}
db := dbm.NewMemDB()
app2 := simapp.NewSimApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, 0)
app2.InitChain(
abci.RequestInitChain{
Validators: []abci.ValidatorUpdate{},

View File

@ -1,6 +1,7 @@
// nolint
package keeper // noalias
package keeper
// noalias
// nolint
// DONTCOVER
import (
@ -9,16 +10,15 @@ import (
"testing"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/log"
tmtypes "github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/codec"
simappcodec "github.com/cosmos/cosmos-sdk/simapp/codec"
"github.com/cosmos/cosmos-sdk/store"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
@ -125,7 +125,9 @@ func createTestInput(
},
},
)
cdc := makeTestCodec()
appCodec := simappcodec.NewAppCodec(cdc)
maccPerms := map[string][]string{
auth.FeeCollectorName: nil,
@ -147,9 +149,9 @@ func createTestInput(
blacklistedAddrs[bondPool.GetAddress().String()] = true
pk := params.NewKeeper(params.ModuleCdc, keyParams, tkeyParams)
accountKeeper := auth.NewAccountKeeper(cdc, keyAcc, pk.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount)
accountKeeper := auth.NewAccountKeeper(appCodec, keyAcc, pk.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount)
bankKeeper := bank.NewBaseKeeper(cdc, keyBank, accountKeeper, pk.Subspace(bank.DefaultParamspace), blacklistedAddrs)
supplyKeeper := supply.NewKeeper(cdc, keySupply, accountKeeper, bankKeeper, maccPerms)
supplyKeeper := supply.NewKeeper(appCodec, keySupply, accountKeeper, bankKeeper, maccPerms)
sk := staking.NewKeeper(staking.ModuleCdc, keyStaking, bankKeeper, supplyKeeper, pk.Subspace(staking.DefaultParamspace))
sk.SetParams(ctx, staking.DefaultParams())

View File

@ -54,14 +54,14 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {
// DefaultGenesis returns default genesis state as raw bytes for the gov
// 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 gov 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", types.ModuleName, err)
}
@ -149,18 +149,18 @@ func (am AppModule) NewQuerierHandler() sdk.Querier {
// InitGenesis performs genesis initialization for the gov 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.bankKeeper, am.supplyKeeper, am.keeper, genesisState)
return []abci.ValidatorUpdate{}
}
// ExportGenesis returns the exported genesis state as raw bytes for the gov
// 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

@ -41,14 +41,14 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {}
// DefaultGenesis returns default genesis state as raw bytes for the mint
// 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 mint 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 mint 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 mint
// 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 returns the begin blocker for the mint module.

View File

@ -36,10 +36,10 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {
// DefaultGenesis returns default genesis state as raw bytes for the params
// module.
func (AppModuleBasic) DefaultGenesis() json.RawMessage { return nil }
func (AppModuleBasic) DefaultGenesis(_ codec.JSONMarshaler) json.RawMessage { return nil }
// ValidateGenesis performs genesis state validation for the params module.
func (AppModuleBasic) ValidateGenesis(_ json.RawMessage) error { return nil }
func (AppModuleBasic) ValidateGenesis(_ codec.JSONMarshaler, _ json.RawMessage) error { return nil }
// RegisterRESTRoutes registers the REST routes for the params module.
func (AppModuleBasic) RegisterRESTRoutes(_ context.CLIContext, _ *mux.Router) {}

View File

@ -1,7 +1,8 @@
package keeper
// nolint:deadcode,unused
// DONTCOVER
// noalias
package keeper
import (
"encoding/hex"
@ -9,7 +10,6 @@ import (
"time"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/ed25519"
@ -17,6 +17,7 @@ import (
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/codec"
simappcodec "github.com/cosmos/cosmos-sdk/simapp/codec"
"github.com/cosmos/cosmos-sdk/store"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
@ -80,6 +81,7 @@ func CreateTestInput(t *testing.T, defaults types.Params) (sdk.Context, bank.Kee
ctx := sdk.NewContext(ms, abci.Header{Time: time.Unix(0, 0)}, false, log.NewNopLogger())
cdc := createTestCodec()
appCodec := simappcodec.NewAppCodec(cdc)
feeCollectorAcc := supply.NewEmptyModuleAccount(auth.FeeCollectorName)
notBondedPool := supply.NewEmptyModuleAccount(staking.NotBondedPoolName, supply.Burner, supply.Staking)
@ -91,7 +93,7 @@ func CreateTestInput(t *testing.T, defaults types.Params) (sdk.Context, bank.Kee
blacklistedAddrs[bondPool.GetAddress().String()] = true
paramsKeeper := params.NewKeeper(params.ModuleCdc, keyParams, tkeyParams)
accountKeeper := auth.NewAccountKeeper(cdc, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount)
accountKeeper := auth.NewAccountKeeper(appCodec, keyAcc, paramsKeeper.Subspace(auth.DefaultParamspace), auth.ProtoBaseAccount)
bk := bank.NewBaseKeeper(cdc, keyBank, accountKeeper, paramsKeeper.Subspace(bank.DefaultParamspace), blacklistedAddrs)
maccPerms := map[string][]string{
@ -99,7 +101,7 @@ func CreateTestInput(t *testing.T, defaults types.Params) (sdk.Context, bank.Kee
staking.NotBondedPoolName: {supply.Burner, supply.Staking},
staking.BondedPoolName: {supply.Burner, supply.Staking},
}
supplyKeeper := supply.NewKeeper(cdc, keySupply, accountKeeper, bk, maccPerms)
supplyKeeper := supply.NewKeeper(appCodec, keySupply, accountKeeper, bk, maccPerms)
totalSupply := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, InitTokens.MulRaw(int64(len(Addrs)))))
supplyKeeper.SetSupply(ctx, supply.NewSupply(totalSupply))

View File

@ -45,14 +45,14 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {
// DefaultGenesis returns default genesis state as raw bytes for the slashing
// 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 slashing 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", types.ModuleName, err)
}
@ -127,7 +127,7 @@ func (am AppModule) NewQuerierHandler() sdk.Querier {
// InitGenesis performs genesis initialization for the slashing 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)
InitGenesis(ctx, am.keeper, am.stakingKeeper, genesisState)
@ -136,9 +136,9 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va
// ExportGenesis returns the exported genesis state as raw bytes for the slashing
// 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 returns the begin blocker for the slashing module.

View File

@ -176,7 +176,6 @@ var (
NewDescription = types.NewDescription
// variable aliases
NewCodec = types.NewCodec
ModuleCdc = types.ModuleCdc
LastValidatorPowerKey = types.LastValidatorPowerKey
LastTotalPowerKey = types.LastTotalPowerKey
@ -201,7 +200,6 @@ var (
type (
Keeper = keeper.Keeper
Codec = types.Codec
Commission = types.Commission
CommissionRates = types.CommissionRates
DVPair = types.DVPair

View File

@ -1,4 +1,6 @@
package keeper // noalias
package keeper
// noalias
import (
"bytes"
@ -16,6 +18,7 @@ import (
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/codec"
simappcodec "github.com/cosmos/cosmos-sdk/simapp/codec"
"github.com/cosmos/cosmos-sdk/store"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
@ -105,7 +108,9 @@ func CreateTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context
},
},
)
cdc := MakeTestCodec()
appCodec := simappcodec.NewAppCodec(cdc)
feeCollectorAcc := supply.NewEmptyModuleAccount(auth.FeeCollectorName)
notBondedPool := supply.NewEmptyModuleAccount(types.NotBondedPoolName, supply.Burner, supply.Staking)
@ -119,10 +124,10 @@ func CreateTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context
pk := params.NewKeeper(params.ModuleCdc, keyParams, tkeyParams)
accountKeeper := auth.NewAccountKeeper(
cdc, // amino codec
keyAcc, // target store
appCodec,
keyAcc,
pk.Subspace(auth.DefaultParamspace),
auth.ProtoBaseAccount, // prototype
auth.ProtoBaseAccount,
)
bk := bank.NewBaseKeeper(
@ -138,7 +143,7 @@ func CreateTestInput(t *testing.T, isCheckTx bool, initPower int64) (sdk.Context
types.NotBondedPoolName: {supply.Burner, supply.Staking},
types.BondedPoolName: {supply.Burner, supply.Staking},
}
supplyKeeper := supply.NewKeeper(cdc, keySupply, accountKeeper, bk, maccPerms)
supplyKeeper := supply.NewKeeper(appCodec, keySupply, accountKeeper, bk, maccPerms)
initTokens := sdk.TokensFromConsensusPower(initPower)
initCoins := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))

View File

@ -48,14 +48,14 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {
// DefaultGenesis returns default genesis state as raw bytes for the staking
// 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 staking 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)
}
@ -154,17 +154,17 @@ func (am AppModule) NewQuerierHandler() sdk.Querier {
// InitGenesis performs genesis initialization for the staking 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)
return InitGenesis(ctx, am.keeper, am.accountKeeper, am.bankKeeper, am.supplyKeeper, genesisState)
}
// ExportGenesis returns the exported genesis state as raw bytes for the staking
// 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 returns the begin blocker for the staking module.

View File

@ -4,22 +4,8 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
)
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 NewCodec(amino *codec.Codec) *Codec {
return &Codec{Marshaler: codec.NewHybridCodec(amino), amino: amino}
}
// ----------------------------------------------------------------------------
// RegisterCodec registers all the necessary staking module concrete types and
// interfaces with the provided codec reference.
// RegisterCodec registers the necessary x/staking interfaces and concrete types
// on the provided Amino codec. These types are used for Amino JSON serialization.
func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(MsgCreateValidator{}, "cosmos-sdk/MsgCreateValidator", nil)
cdc.RegisterConcrete(MsgEditValidator{}, "cosmos-sdk/MsgEditValidator", nil)
@ -28,13 +14,20 @@ func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterConcrete(MsgBeginRedelegate{}, "cosmos-sdk/MsgBeginRedelegate", nil)
}
// ModuleCdc defines a staking module global Amino codec.
var ModuleCdc *Codec
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() {
ModuleCdc = NewCodec(codec.New())
RegisterCodec(ModuleCdc.amino)
codec.RegisterCrypto(ModuleCdc.amino)
ModuleCdc.amino.Seal()
RegisterCodec(amino)
codec.RegisterCrypto(amino)
amino.Seal()
}

View File

@ -1,13 +1,11 @@
// nolint
// autogenerated code using github.com/rigelrozanski/multitool
// aliases generated for the following subdirectories:
// ALIASGEN: github.com/cosmos/cosmos-sdk/x/supply/internal/keeper
// ALIASGEN: github.com/cosmos/cosmos-sdk/x/supply/internal/types
package supply
// DONTCOVER
// nolint
import (
"github.com/cosmos/cosmos-sdk/x/supply/internal/keeper"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/keeper"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
const (
@ -46,4 +44,5 @@ type (
ModuleAccount = types.ModuleAccount
GenesisState = types.GenesisState
Supply = types.Supply
Codec = types.Codec
)

View File

@ -12,7 +12,7 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/version"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
// GetQueryCmd returns the cli query commands for this module

View File

@ -8,7 +8,7 @@ import (
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
// RegisterRoutes registers staking-related REST handlers to a router

View File

@ -6,7 +6,8 @@ import (
"github.com/cosmos/cosmos-sdk/x/auth/exported"
)
// ModuleAccountI defines an account interface for modules that hold tokens in an escrow
// ModuleAccountI defines an account interface for modules that hold tokens in
// an escrow.
type ModuleAccountI interface {
exported.Account
@ -19,10 +20,10 @@ type ModuleAccountI interface {
// token supply.
type SupplyI interface {
GetTotal() sdk.Coins
SetTotal(total sdk.Coins) SupplyI
SetTotal(total sdk.Coins)
Inflate(amount sdk.Coins) SupplyI
Deflate(amount sdk.Coins) SupplyI
Inflate(amount sdk.Coins)
Deflate(amount sdk.Coins)
String() string
ValidateBasic() error

View File

@ -2,7 +2,7 @@ package supply
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
// InitGenesis sets supply information for genesis.

View File

@ -1,35 +0,0 @@
package keeper_test
import (
abci "github.com/tendermint/tendermint/abci/types"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
keep "github.com/cosmos/cosmos-sdk/x/supply/internal/keeper"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
)
var (
multiPerm = "multiple permissions account"
randomPerm = "random permission"
holder = "holder"
)
// nolint:deadcode,unused
func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context) {
app := simapp.Setup(isCheckTx)
// add module accounts to supply keeper
maccPerms := simapp.GetMaccPerms()
maccPerms[holder] = nil
maccPerms[types.Burner] = []string{types.Burner}
maccPerms[types.Minter] = []string{types.Minter}
maccPerms[multiPerm] = []string{types.Burner, types.Minter, types.Staking}
maccPerms[randomPerm] = []string{"random"}
ctx := app.BaseApp.NewContext(isCheckTx, abci.Header{})
app.SupplyKeeper = keep.NewKeeper(app.Codec(), app.GetKey(types.StoreKey), app.AccountKeeper, app.BankKeeper, maccPerms)
app.SupplyKeeper.SetSupply(ctx, types.NewSupply(sdk.NewCoins()))
return app, ctx
}

View File

@ -1,38 +0,0 @@
package keeper_test
import (
"testing"
"github.com/stretchr/testify/require"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
)
func TestSupply(t *testing.T) {
initialPower := int64(100)
initTokens := sdk.TokensFromConsensusPower(initialPower)
app, ctx := createTestApp(false)
totalSupply := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))
app.SupplyKeeper.SetSupply(ctx, types.NewSupply(totalSupply))
total := app.SupplyKeeper.GetSupply(ctx).GetTotal()
require.Equal(t, totalSupply, total)
}
func TestValidatePermissions(t *testing.T) {
app, _ := createTestApp(false)
err := app.SupplyKeeper.ValidatePermissions(multiPermAcc)
require.NoError(t, err)
err = app.SupplyKeeper.ValidatePermissions(randomPermAcc)
require.NoError(t, err)
// unregistered permissions
otherAcc := types.NewEmptyModuleAccount("other", "other")
err = app.SupplyKeeper.ValidatePermissions(otherAcc)
require.Error(t, err)
}

View File

@ -1,24 +0,0 @@
package types
import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/x/supply/exported"
)
// RegisterCodec registers the account types and interface
func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterInterface((*exported.ModuleAccountI)(nil), nil)
cdc.RegisterInterface((*exported.SupplyI)(nil), nil)
cdc.RegisterConcrete(&ModuleAccount{}, "cosmos-sdk/ModuleAccount", nil)
cdc.RegisterConcrete(&Supply{}, "cosmos-sdk/Supply", nil)
}
// ModuleCdc generic sealed codec to be used throughout module
var ModuleCdc *codec.Codec
func init() {
cdc := codec.New()
RegisterCodec(cdc)
codec.RegisterCrypto(cdc)
ModuleCdc = cdc.Seal()
}

View File

@ -3,7 +3,7 @@ package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/supply/exported"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
// GetModuleAddress returns an address based on the module name

View File

@ -5,7 +5,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
// SendCoinsFromModuleToAccount transfers coins from a ModuleAccount to an AccAddress.
@ -112,7 +112,7 @@ func (k Keeper) MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) err
// update total supply
supply := k.GetSupply(ctx)
supply = supply.Inflate(amt)
supply.Inflate(amt)
k.SetSupply(ctx, supply)
@ -141,7 +141,7 @@ func (k Keeper) BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) err
// update total supply
supply := k.GetSupply(ctx)
supply = supply.Deflate(amt)
supply.Deflate(amt)
k.SetSupply(ctx, supply)
logger := k.Logger(ctx)

View File

@ -4,13 +4,21 @@ import (
"testing"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/cosmos/cosmos-sdk/simapp"
simappcodec "github.com/cosmos/cosmos-sdk/simapp/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
keep "github.com/cosmos/cosmos-sdk/x/supply/internal/keeper"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
keep "github.com/cosmos/cosmos-sdk/x/supply/keeper"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
const initialPower = int64(100)
const (
initialPower = int64(100)
holder = "holder"
multiPerm = "multiple permissions account"
randomPerm = "random permission"
)
// create module accounts for testing
var (
@ -36,8 +44,20 @@ func getCoinsByName(ctx sdk.Context, sk keep.Keeper, ak types.AccountKeeper, bk
}
func TestSendCoins(t *testing.T) {
app, ctx := createTestApp(false)
keeper := app.SupplyKeeper
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, abci.Header{Height: 1})
// add module accounts to supply keeper
maccPerms := simapp.GetMaccPerms()
maccPerms[holder] = nil
maccPerms[types.Burner] = []string{types.Burner}
maccPerms[types.Minter] = []string{types.Minter}
maccPerms[multiPerm] = []string{types.Burner, types.Minter, types.Staking}
maccPerms[randomPerm] = []string{"random"}
appCodec := simappcodec.NewAppCodec(app.Codec())
keeper := keep.NewKeeper(appCodec, app.GetKey(types.StoreKey), app.AccountKeeper, app.BankKeeper, maccPerms)
ak := app.AccountKeeper
bk := app.BankKeeper
@ -85,8 +105,20 @@ func TestSendCoins(t *testing.T) {
}
func TestMintCoins(t *testing.T) {
app, ctx := createTestApp(false)
keeper := app.SupplyKeeper
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, abci.Header{Height: 1})
// add module accounts to supply keeper
maccPerms := simapp.GetMaccPerms()
maccPerms[holder] = nil
maccPerms[types.Burner] = []string{types.Burner}
maccPerms[types.Minter] = []string{types.Minter}
maccPerms[multiPerm] = []string{types.Burner, types.Minter, types.Staking}
maccPerms[randomPerm] = []string{"random"}
appCodec := simappcodec.NewAppCodec(app.Codec())
keeper := keep.NewKeeper(appCodec, app.GetKey(types.StoreKey), app.AccountKeeper, app.BankKeeper, maccPerms)
ak := app.AccountKeeper
bk := app.BankKeeper
@ -121,8 +153,20 @@ func TestMintCoins(t *testing.T) {
}
func TestBurnCoins(t *testing.T) {
app, ctx := createTestApp(false)
keeper := app.SupplyKeeper
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, abci.Header{Height: 1})
// add module accounts to supply keeper
maccPerms := simapp.GetMaccPerms()
maccPerms[holder] = nil
maccPerms[types.Burner] = []string{types.Burner}
maccPerms[types.Minter] = []string{types.Minter}
maccPerms[multiPerm] = []string{types.Burner, types.Minter, types.Staking}
maccPerms[randomPerm] = []string{"random"}
appCodec := simappcodec.NewAppCodec(app.Codec())
keeper := keep.NewKeeper(appCodec, app.GetKey(types.StoreKey), app.AccountKeeper, app.BankKeeper, maccPerms)
ak := app.AccountKeeper
bk := app.BankKeeper
@ -131,7 +175,7 @@ func TestBurnCoins(t *testing.T) {
keeper.SetModuleAccount(ctx, burnerAcc)
initialSupply := keeper.GetSupply(ctx)
initialSupply = initialSupply.Inflate(initCoins)
initialSupply.Inflate(initCoins)
keeper.SetSupply(ctx, initialSupply)
require.Panics(t, func() { keeper.BurnCoins(ctx, "", initCoins) }, "no module account")
@ -147,7 +191,7 @@ func TestBurnCoins(t *testing.T) {
// test same functionality on module account with multiple permissions
initialSupply = keeper.GetSupply(ctx)
initialSupply = initialSupply.Inflate(initCoins)
initialSupply.Inflate(initCoins)
keeper.SetSupply(ctx, initialSupply)
require.NoError(t, bk.SetBalances(ctx, multiPermAcc.GetAddress(), initCoins))

View File

@ -4,7 +4,7 @@ import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
// RegisterInvariants register all supply invariants

View File

@ -5,15 +5,14 @@ import (
"github.com/tendermint/tendermint/libs/log"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/supply/exported"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
// Keeper of the supply store
type Keeper struct {
cdc *codec.Codec
cdc types.Codec
storeKey sdk.StoreKey
ak types.AccountKeeper
bk types.BankKeeper
@ -21,8 +20,11 @@ type Keeper struct {
}
// NewKeeper creates a new Keeper instance
func NewKeeper(cdc *codec.Codec, key sdk.StoreKey, ak types.AccountKeeper, bk types.BankKeeper, maccPerms map[string][]string) Keeper {
// set the addresses
func NewKeeper(
cdc types.Codec, key sdk.StoreKey, ak types.AccountKeeper,
bk types.BankKeeper, maccPerms map[string][]string,
) Keeper {
permAddrs := make(map[string]types.PermissionsForAddress)
for name, perms := range maccPerms {
permAddrs[name] = types.NewPermissionsForAddress(name, perms)
@ -43,21 +45,30 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger {
}
// GetSupply retrieves the Supply from store
func (k Keeper) GetSupply(ctx sdk.Context) (supply exported.SupplyI) {
func (k Keeper) GetSupply(ctx sdk.Context) exported.SupplyI {
store := ctx.KVStore(k.storeKey)
b := store.Get(SupplyKey)
if b == nil {
bz := store.Get(SupplyKey)
if bz == nil {
panic("stored supply should not have been nil")
}
k.cdc.MustUnmarshalBinaryLengthPrefixed(b, &supply)
return
supply, err := k.cdc.UnmarshalSupply(bz)
if err != nil {
panic(err)
}
return supply
}
// SetSupply sets the Supply to store
func (k Keeper) SetSupply(ctx sdk.Context, supply exported.SupplyI) {
store := ctx.KVStore(k.storeKey)
b := k.cdc.MustMarshalBinaryLengthPrefixed(supply)
store.Set(SupplyKey, b)
bz, err := k.cdc.MarshalSupply(supply)
if err != nil {
panic(err)
}
store.Set(SupplyKey, bz)
}
// ValidatePermissions validates that the module account has been granted
@ -69,5 +80,6 @@ func (k Keeper) ValidatePermissions(macc exported.ModuleAccountI) error {
return fmt.Errorf("invalid module permission %s", perm)
}
}
return nil
}

View File

@ -0,0 +1,55 @@
package keeper_test
import (
"testing"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/cosmos/cosmos-sdk/simapp"
simappcodec "github.com/cosmos/cosmos-sdk/simapp/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
keep "github.com/cosmos/cosmos-sdk/x/supply/keeper"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
func TestSupply(t *testing.T) {
initialPower := int64(100)
initTokens := sdk.TokensFromConsensusPower(initialPower)
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, abci.Header{Height: 1})
totalSupply := sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, initTokens))
app.SupplyKeeper.SetSupply(ctx, types.NewSupply(totalSupply))
total := app.SupplyKeeper.GetSupply(ctx).GetTotal()
require.Equal(t, totalSupply, total)
}
func TestValidatePermissions(t *testing.T) {
app := simapp.Setup(false)
// add module accounts to supply keeper
maccPerms := simapp.GetMaccPerms()
maccPerms[holder] = nil
maccPerms[types.Burner] = []string{types.Burner}
maccPerms[types.Minter] = []string{types.Minter}
maccPerms[multiPerm] = []string{types.Burner, types.Minter, types.Staking}
maccPerms[randomPerm] = []string{"random"}
appCodec := simappcodec.NewAppCodec(app.Codec())
keeper := keep.NewKeeper(appCodec, app.GetKey(types.StoreKey), app.AccountKeeper, app.BankKeeper, maccPerms)
err := keeper.ValidatePermissions(multiPermAcc)
require.NoError(t, err)
err = keeper.ValidatePermissions(randomPermAcc)
require.NoError(t, err)
// unregistered permissions
otherAcc := types.NewEmptyModuleAccount("other", "other")
err = app.SupplyKeeper.ValidatePermissions(otherAcc)
require.Error(t, err)
}

View File

@ -6,7 +6,7 @@ import (
"github.com/cosmos/cosmos-sdk/client"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
// NewQuerier creates a querier for supply REST endpoints

View File

@ -7,13 +7,16 @@ import (
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
keep "github.com/cosmos/cosmos-sdk/x/supply/internal/keeper"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
keep "github.com/cosmos/cosmos-sdk/x/supply/keeper"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
func TestNewQuerier(t *testing.T) {
app, ctx := createTestApp(false)
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, abci.Header{Height: 1})
keeper := app.SupplyKeeper
cdc := app.Codec()
@ -59,7 +62,9 @@ func TestNewQuerier(t *testing.T) {
}
func TestQuerySupply(t *testing.T) {
app, ctx := createTestApp(false)
app := simapp.Setup(false)
ctx := app.BaseApp.NewContext(false, abci.Header{Height: 1})
keeper := app.SupplyKeeper
cdc := app.Codec()

View File

@ -17,8 +17,8 @@ import (
sim "github.com/cosmos/cosmos-sdk/x/simulation"
"github.com/cosmos/cosmos-sdk/x/supply/client/cli"
"github.com/cosmos/cosmos-sdk/x/supply/client/rest"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/simulation"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
var (
@ -42,14 +42,14 @@ func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) {
// DefaultGenesis returns default genesis state as raw bytes for the supply
// 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 supply 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)
}
@ -120,18 +120,18 @@ func (am AppModule) NewQuerierHandler() sdk.Querier {
// InitGenesis performs genesis initialization for the supply 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, am.bk, genesisState)
return []abci.ValidatorUpdate{}
}
// ExportGenesis returns the exported genesis state as raw bytes for the supply
// 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 returns the begin blocker for the supply module.

View File

@ -7,8 +7,8 @@ import (
tmkv "github.com/tendermint/tendermint/libs/kv"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/x/supply/internal/keeper"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/keeper"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
// DecodeStore unmarshals the KVPair's Value to the corresponding supply type
@ -19,6 +19,7 @@ func DecodeStore(cdc *codec.Codec, kvA, kvB tmkv.Pair) string {
cdc.MustUnmarshalBinaryLengthPrefixed(kvA.Value, &supplyA)
cdc.MustUnmarshalBinaryLengthPrefixed(kvB.Value, &supplyB)
return fmt.Sprintf("%v\n%v", supplyB, supplyB)
default:
panic(fmt.Sprintf("invalid supply key %X", kvA.Key))
}

View File

@ -10,8 +10,8 @@ import (
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/supply/internal/keeper"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/keeper"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
func makeTestCodec() (cdc *codec.Codec) {

View File

@ -9,7 +9,7 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/x/supply/internal/types"
"github.com/cosmos/cosmos-sdk/x/supply/types"
)
// RandomizedGenState generates a random GenesisState for supply

View File

@ -21,21 +21,6 @@ var (
_ exported.ModuleAccountI = (*ModuleAccount)(nil)
)
func init() {
// Register the ModuleAccount type as a GenesisAccount so that when no
// concrete GenesisAccount types exist and **default** genesis state is used,
// the genesis state will serialize correctly.
authtypes.RegisterAccountTypeCodec(&ModuleAccount{}, "cosmos-sdk/ModuleAccount")
}
// ModuleAccount defines an account for modules that holds coins on a pool
type ModuleAccount struct {
*authtypes.BaseAccount
Name string `json:"name" yaml:"name"` // name of the module
Permissions []string `json:"permissions" yaml:"permissions"` // permissions of module account
}
// NewModuleAddress creates an AccAddress from the hash of the module's name
func NewModuleAddress(name string) sdk.AccAddress {
return sdk.AccAddress(crypto.AddressHash([]byte(name)))
@ -51,16 +36,14 @@ func NewEmptyModuleAccount(name string, permissions ...string) *ModuleAccount {
}
return &ModuleAccount{
BaseAccount: &baseAcc,
BaseAccount: baseAcc,
Name: name,
Permissions: permissions,
}
}
// NewModuleAccount creates a new ModuleAccount instance
func NewModuleAccount(ba *authtypes.BaseAccount,
name string, permissions ...string) *ModuleAccount {
func NewModuleAccount(ba *authtypes.BaseAccount, name string, permissions ...string) *ModuleAccount {
if err := validatePermissions(permissions...); err != nil {
panic(err)
}

View File

@ -6,15 +6,13 @@ import (
"fmt"
"testing"
yaml "gopkg.in/yaml.v2"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto/secp256k1"
yaml "gopkg.in/yaml.v2"
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/stretchr/testify/require"
)
func TestModuleAccountMarshalYAML(t *testing.T) {

45
x/supply/types/codec.go Normal file
View File

@ -0,0 +1,45 @@
package types
import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/x/supply/exported"
)
// Codec defines the interface needed to serialize x/supply state. It must
// be aware of all concrete supply types.
type Codec interface {
codec.Marshaler
MarshalSupply(supply exported.SupplyI) ([]byte, error)
UnmarshalSupply(bz []byte) (exported.SupplyI, error)
MarshalSupplyJSON(supply exported.SupplyI) ([]byte, error)
UnmarshalSupplyJSON(bz []byte) (exported.SupplyI, error)
}
// RegisterCodec registers the necessary x/supply interfaces and concrete types
// on the provided Amino codec. These types are used for Amino JSON serialization.
func RegisterCodec(cdc *codec.Codec) {
cdc.RegisterInterface((*exported.ModuleAccountI)(nil), nil)
cdc.RegisterInterface((*exported.SupplyI)(nil), nil)
cdc.RegisterConcrete(&ModuleAccount{}, "cosmos-sdk/ModuleAccount", nil)
cdc.RegisterConcrete(&Supply{}, "cosmos-sdk/Supply", nil)
}
var (
amino = codec.New()
// ModuleCdc references the global x/supply 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/supply and
// defined at the application level.
ModuleCdc = codec.NewHybridCodec(amino)
)
func init() {
RegisterCodec(amino)
codec.RegisterCrypto(amino)
amino.Seal()
}

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